NativeDapiProtection.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. //
  2. // NativeDapiProtection.cs -
  3. // Protect (encrypt) data without (user involved) key management
  4. //
  5. // Author:
  6. // Sebastien Pouliot <[email protected]>
  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. #if NET_2_0
  30. using System;
  31. using System.IO;
  32. using System.Runtime.InteropServices;
  33. using System.Security;
  34. using System.Security.Cryptography;
  35. using System.Security.Permissions;
  36. namespace Mono.Security.Cryptography {
  37. // DAPI is only available in Windows 2000 and later operating systems
  38. // see ManagedProtection for other platforms
  39. // notes:
  40. // * no need to assert KeyContainerPermission here as unmanaged code can
  41. // do what it wants;
  42. // * which is why we also need the [SuppressUnmanagedCodeSecurity]
  43. // attribute on each native function (so we don't require UnmanagedCode)
  44. internal class NativeDapiProtection {
  45. private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1;
  46. private const uint CRYPTPROTECT_LOCAL_MACHINE = 0x4;
  47. [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
  48. private struct DATA_BLOB {
  49. private int cbData;
  50. private IntPtr pbData;
  51. public void Alloc (int size)
  52. {
  53. if (size > 0) {
  54. pbData = Marshal.AllocHGlobal (size);
  55. cbData = size;
  56. }
  57. }
  58. public void Alloc (byte[] managedMemory)
  59. {
  60. if (managedMemory != null) {
  61. int size = managedMemory.Length;
  62. pbData = Marshal.AllocHGlobal (size);
  63. cbData = size;
  64. Marshal.Copy (managedMemory, 0, pbData, cbData);
  65. }
  66. }
  67. public void Free ()
  68. {
  69. if (pbData != IntPtr.Zero) {
  70. // clear copied memory!
  71. ZeroMemory (pbData, cbData);
  72. Marshal.FreeHGlobal (pbData);
  73. pbData = IntPtr.Zero;
  74. cbData = 0;
  75. }
  76. }
  77. public byte[] ToBytes ()
  78. {
  79. if (cbData <= 0)
  80. return new byte [0];
  81. byte[] managedMemory = new byte[cbData];
  82. Marshal.Copy (pbData, managedMemory, 0, cbData);
  83. return managedMemory;
  84. }
  85. }
  86. [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
  87. private struct CRYPTPROTECT_PROMPTSTRUCT {
  88. private int cbSize;
  89. private uint dwPromptFlags;
  90. private IntPtr hwndApp;
  91. private string szPrompt;
  92. public CRYPTPROTECT_PROMPTSTRUCT (uint flags)
  93. {
  94. cbSize = Marshal.SizeOf (typeof (CRYPTPROTECT_PROMPTSTRUCT));
  95. dwPromptFlags = flags;
  96. hwndApp = IntPtr.Zero;
  97. szPrompt = null;
  98. }
  99. }
  100. // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptprotectdata.asp
  101. [SuppressUnmanagedCodeSecurity]
  102. [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  103. private static extern bool CryptProtectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy,
  104. IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);
  105. // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptunprotectdata.asp
  106. [SuppressUnmanagedCodeSecurity]
  107. [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  108. private static extern bool CryptUnprotectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy,
  109. IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);
  110. // http://msdn.microsoft.com/library/en-us/memory/base/zeromemory.asp
  111. // note: SecureZeroMemory is an inline function (and can't be used here)
  112. // anyway I don't think the CLR will optimize this call away (like a C/C++ compiler could do)
  113. [SuppressUnmanagedCodeSecurity]
  114. [DllImport ("kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  115. private static extern void ZeroMemory (IntPtr dest, int size);
  116. // managed helpers
  117. public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
  118. {
  119. byte[] encdata = null;
  120. int hr = 0;
  121. DATA_BLOB data = new DATA_BLOB ();
  122. DATA_BLOB entropy = new DATA_BLOB ();
  123. DATA_BLOB cipher = new DATA_BLOB ();
  124. try {
  125. CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0);
  126. data.Alloc (userData);
  127. entropy.Alloc (optionalEntropy);
  128. // note: the scope/flags has already been check by the public caller
  129. uint flags = CRYPTPROTECT_UI_FORBIDDEN;
  130. if (scope == DataProtectionScope.LocalMachine)
  131. flags |= CRYPTPROTECT_LOCAL_MACHINE;
  132. // note: on Windows 2000 the string parameter *cannot* be null
  133. if (CryptProtectData (ref data, String.Empty, ref entropy, IntPtr.Zero,
  134. ref prompt, flags, ref cipher)) {
  135. // copy encrypted data back to managed codde
  136. encdata = cipher.ToBytes ();
  137. } else {
  138. hr = Marshal.GetLastWin32Error ();
  139. }
  140. }
  141. catch (Exception ex) {
  142. string msg = Locale.GetText ("Error protecting data.");
  143. throw new CryptographicException (msg, ex);
  144. }
  145. finally {
  146. cipher.Free ();
  147. data.Free ();
  148. entropy.Free ();
  149. }
  150. if ((encdata == null) || (hr != 0)) {
  151. throw new CryptographicException (Marshal.GetLastWin32Error ());
  152. }
  153. return encdata;
  154. }
  155. public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
  156. {
  157. byte[] decdata = null;
  158. int hr = 0;
  159. DATA_BLOB cipher = new DATA_BLOB ();
  160. DATA_BLOB entropy = new DATA_BLOB ();
  161. DATA_BLOB data = new DATA_BLOB ();
  162. try {
  163. CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0);
  164. cipher.Alloc (encryptedData);
  165. entropy.Alloc (optionalEntropy);
  166. // note: the scope/flags has already been check by the public caller
  167. uint flags = CRYPTPROTECT_UI_FORBIDDEN;
  168. if (scope == DataProtectionScope.LocalMachine)
  169. flags |= CRYPTPROTECT_LOCAL_MACHINE;
  170. if (CryptUnprotectData (ref cipher, null, ref entropy, IntPtr.Zero,
  171. ref prompt, flags, ref data)) {
  172. // copy decrypted data back to managed codde
  173. decdata = data.ToBytes ();
  174. } else {
  175. hr = Marshal.GetLastWin32Error ();
  176. }
  177. }
  178. catch (Exception ex) {
  179. string msg = Locale.GetText ("Error protecting data.");
  180. throw new CryptographicException (msg, ex);
  181. }
  182. finally {
  183. cipher.Free ();
  184. data.Free ();
  185. entropy.Free ();
  186. }
  187. if ((decdata == null) || (hr != 0)) {
  188. throw new CryptographicException (hr);
  189. }
  190. return decdata;
  191. }
  192. }
  193. }
  194. #endif