Merge pull request #3213 from henricm/fix-for-win-securestring-to-bstr
[mono.git] / mcs / class / System.Security / Mono.Security.Cryptography / NativeDapiProtection.cs
1 //
2 // NativeDapiProtection.cs - 
3 //      Protect (encrypt) data without (user involved) key management
4 //
5 // Author:
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30
31 using System;
32 using System.IO;
33 using System.Runtime.InteropServices;
34 using System.Security;
35 using System.Security.Cryptography;
36 using System.Security.Permissions;
37
38 namespace Mono.Security.Cryptography {
39
40         // DAPI is only available in Windows 2000 and later operating systems
41         // see ManagedProtection for other platforms
42
43         // notes:
44         // * no need to assert KeyContainerPermission here as unmanaged code can
45         //   do what it wants;
46         // * which is why we also need the [SuppressUnmanagedCodeSecurity] 
47         //   attribute on each native function (so we don't require UnmanagedCode)
48
49         internal class NativeDapiProtection {
50
51                 private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1;
52                 private const uint CRYPTPROTECT_LOCAL_MACHINE = 0x4;
53
54                 [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
55                 private struct DATA_BLOB {
56
57                         private int cbData;
58                         private IntPtr pbData;
59
60                         public void Alloc (int size)
61                         {
62                                 if (size > 0) {
63                                         pbData = Marshal.AllocHGlobal (size);
64                                         cbData = size;
65                                 }
66                         }
67
68                         public void Alloc (byte[] managedMemory)
69                         {
70                                 if (managedMemory != null) {
71                                         int size = managedMemory.Length;
72                                         pbData = Marshal.AllocHGlobal (size);
73                                         cbData = size;
74                                         Marshal.Copy (managedMemory, 0, pbData, cbData);
75                                 }
76                         }
77
78                         public void Free ()
79                         {
80                                 if (pbData != IntPtr.Zero) {
81                                         // clear copied memory!
82                                         ZeroMemory (pbData, cbData);
83                                         Marshal.FreeHGlobal (pbData);
84                                         pbData = IntPtr.Zero;
85                                         cbData = 0;
86                                 }
87                         }
88
89                         public byte[] ToBytes ()
90                         {
91                                 if (cbData <= 0)
92                                         return new byte [0];
93
94                                 byte[] managedMemory = new byte[cbData];
95                                 Marshal.Copy (pbData, managedMemory, 0, cbData);
96                                 return managedMemory;
97                         }
98                 }
99
100                 [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
101                 private struct CRYPTPROTECT_PROMPTSTRUCT {
102
103                         private int cbSize;
104                         private uint dwPromptFlags;
105                         private IntPtr hwndApp;
106                         private string szPrompt;
107
108                         public CRYPTPROTECT_PROMPTSTRUCT (uint flags)
109                         {
110                                 cbSize = Marshal.SizeOf (typeof (CRYPTPROTECT_PROMPTSTRUCT));
111                                 dwPromptFlags = flags;
112                                 hwndApp = IntPtr.Zero;
113                                 szPrompt = null;
114                         }
115                 }
116
117                 // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptprotectdata.asp
118                 [SuppressUnmanagedCodeSecurity]
119                 [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
120                 private static extern bool CryptProtectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy,
121                         IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);
122
123                 // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptunprotectdata.asp
124                 [SuppressUnmanagedCodeSecurity]
125                 [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
126                 private static extern bool CryptUnprotectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy,
127                         IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);
128
129                 // http://msdn.microsoft.com/library/en-us/memory/base/zeromemory.asp
130                 // note: SecureZeroMemory is an inline function (and can't be used here)
131                 // anyway I don't think the CLR will optimize this call away (like a C/C++ compiler could do)
132                 [SuppressUnmanagedCodeSecurity]
133                 [DllImport ("kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
134                 private static extern void ZeroMemory (IntPtr dest, int size);
135
136
137                 // managed helpers
138
139                 public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
140                 {
141                         byte[] encdata = null;
142                         int hr = 0;
143
144                         DATA_BLOB data = new DATA_BLOB ();
145                         DATA_BLOB entropy = new DATA_BLOB ();
146                         DATA_BLOB cipher = new DATA_BLOB ();
147                         try {
148                                 CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0);
149                                 data.Alloc (userData);
150                                 entropy.Alloc (optionalEntropy);
151
152                                 // note: the scope/flags has already been check by the public caller
153                                 uint flags = CRYPTPROTECT_UI_FORBIDDEN;
154                                 if (scope == DataProtectionScope.LocalMachine)
155                                         flags |= CRYPTPROTECT_LOCAL_MACHINE;
156
157                                 // note: on Windows 2000 the string parameter *cannot* be null
158                                 if (CryptProtectData (ref data, String.Empty, ref entropy, IntPtr.Zero,
159                                         ref prompt, flags, ref cipher)) {
160                                         // copy encrypted data back to managed codde
161                                         encdata = cipher.ToBytes ();
162                                 } else {
163                                         hr = Marshal.GetLastWin32Error ();
164                                 }
165                         }
166                         catch (Exception ex) {
167                                 string msg = Locale.GetText ("Error protecting data.");
168                                 throw new CryptographicException (msg, ex);
169                         }
170                         finally {
171                                 cipher.Free ();
172                                 data.Free ();
173                                 entropy.Free ();
174                         }
175
176                         if ((encdata == null) || (hr != 0)) {
177                                 throw new CryptographicException (hr);
178                         }
179                         return encdata;
180                 }
181
182                 public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
183                 {
184                         byte[] decdata = null;
185                         int hr = 0;
186
187                         DATA_BLOB cipher = new DATA_BLOB ();
188                         DATA_BLOB entropy = new DATA_BLOB ();
189                         DATA_BLOB data = new DATA_BLOB ();
190                         try {
191                                 CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0);
192                                 cipher.Alloc (encryptedData);
193                                 entropy.Alloc (optionalEntropy);
194
195                                 // note: the scope/flags has already been check by the public caller
196                                 uint flags = CRYPTPROTECT_UI_FORBIDDEN;
197                                 if (scope == DataProtectionScope.LocalMachine)
198                                         flags |= CRYPTPROTECT_LOCAL_MACHINE;
199
200                                 if (CryptUnprotectData (ref cipher, null, ref entropy, IntPtr.Zero,
201                                         ref prompt, flags, ref data)) {
202                                         // copy decrypted data back to managed codde
203                                         decdata = data.ToBytes ();
204                                 } else {
205                                         hr = Marshal.GetLastWin32Error ();
206                                 }
207                         }
208                         catch (Exception ex) {
209                                 string msg = Locale.GetText ("Error protecting data.");
210                                 throw new CryptographicException (msg, ex);
211                         }
212                         finally {
213                                 cipher.Free ();
214                                 data.Free ();
215                                 entropy.Free ();
216                         }
217
218                         if ((decdata == null) || (hr != 0)) {
219                                 throw new CryptographicException (hr);
220                         }
221                         return decdata;
222                 }
223         }
224 }
225