NativeDapiProtection.cs 7.2 KB

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