ProtectedMemory.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. //
  2. // ProtectedMemory.cs: Protect (encrypt) memory without (user involved) key management
  3. //
  4. // Author:
  5. // Sebastien Pouliot <[email protected]>
  6. //
  7. // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
  8. // Copyright (C) 2004-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.Runtime.InteropServices;
  31. using System.Security;
  32. using System.Security.Permissions;
  33. namespace System.Security.Cryptography {
  34. // References:
  35. // a. Windows Data Protection
  36. // http://msdn.microsoft.com/library/en-us/dnsecure/html/windataprotection-dpapi.asp?frame=true
  37. public sealed class ProtectedMemory {
  38. private ProtectedMemory ()
  39. {
  40. }
  41. [MonoTODO ("only supported on Windows 2000 SP3 and later")]
  42. // FIXME [DataProtectionPermission (SecurityAction.Demand, ProtectMemory = true)]
  43. public static void Protect (byte[] userData, MemoryProtectionScope scope)
  44. {
  45. if (userData == null)
  46. throw new ArgumentNullException ("userData");
  47. Check (userData.Length, scope);
  48. try {
  49. uint flags = (uint) scope;
  50. uint length = (uint) userData.Length;
  51. switch (impl) {
  52. case MemoryProtectionImplementation.Win32RtlEncryptMemory:
  53. int err = RtlEncryptMemory (userData, length, flags);
  54. if (err < 0) {
  55. string msg = Locale.GetText ("Error. NTSTATUS = {0}.", err);
  56. throw new CryptographicException (msg);
  57. }
  58. break;
  59. case MemoryProtectionImplementation.Win32CryptoProtect:
  60. bool result = CryptProtectMemory (userData, length, flags);
  61. if (!result)
  62. throw new CryptographicException (Marshal.GetLastWin32Error ());
  63. break;
  64. default:
  65. throw new PlatformNotSupportedException ();
  66. }
  67. }
  68. catch {
  69. // Windows 2000 before SP3 will throw
  70. impl = MemoryProtectionImplementation.Unsupported;
  71. throw new PlatformNotSupportedException ();
  72. }
  73. }
  74. [MonoTODO ("only supported on Windows 2000 SP3 and later")]
  75. // FIXME [DataProtectionPermission (SecurityAction.Demand, UnprotectMemory = true)]
  76. public static void Unprotect (byte[] encryptedData, MemoryProtectionScope scope)
  77. {
  78. if (encryptedData == null)
  79. throw new ArgumentNullException ("encryptedData");
  80. Check (encryptedData.Length, scope);
  81. try {
  82. uint flags = (uint) scope;
  83. uint length = (uint) encryptedData.Length;
  84. switch (impl) {
  85. case MemoryProtectionImplementation.Win32RtlEncryptMemory:
  86. int err = RtlDecryptMemory (encryptedData, length, flags);
  87. if (err < 0) {
  88. string msg = Locale.GetText ("Error. NTSTATUS = {0}.", err);
  89. throw new CryptographicException (msg);
  90. }
  91. break;
  92. case MemoryProtectionImplementation.Win32CryptoProtect:
  93. bool result = CryptUnprotectMemory (encryptedData, length, flags);
  94. if (!result)
  95. throw new CryptographicException (Marshal.GetLastWin32Error ());
  96. break;
  97. default:
  98. throw new PlatformNotSupportedException ();
  99. }
  100. }
  101. catch {
  102. // Windows 2000 before SP3 will throw
  103. impl = MemoryProtectionImplementation.Unsupported;
  104. throw new PlatformNotSupportedException ();
  105. }
  106. }
  107. // private stuff
  108. private const int BlockSize = 16;
  109. enum MemoryProtectionImplementation {
  110. Unknown,
  111. Win32RtlEncryptMemory,
  112. Win32CryptoProtect,
  113. Unsupported = Int32.MinValue
  114. }
  115. private static MemoryProtectionImplementation impl;
  116. private static void Detect ()
  117. {
  118. OperatingSystem os = Environment.OSVersion;
  119. switch (os.Platform) {
  120. case PlatformID.Win32NT:
  121. Version v = os.Version;
  122. if (v.Major < 5) {
  123. impl = MemoryProtectionImplementation.Unsupported;
  124. } else if (v.Major == 5) {
  125. if (v.Minor < 2) {
  126. // 2000 (5.0) Service Pack 3 and XP (5.1)
  127. impl = MemoryProtectionImplementation.Win32RtlEncryptMemory;
  128. } else {
  129. impl = MemoryProtectionImplementation.Win32CryptoProtect;
  130. }
  131. } else {
  132. // vista (6.0) and later
  133. impl = MemoryProtectionImplementation.Win32CryptoProtect;
  134. }
  135. break;
  136. default:
  137. impl = MemoryProtectionImplementation.Unsupported;
  138. break;
  139. }
  140. }
  141. private static void Check (int size, MemoryProtectionScope scope)
  142. {
  143. if (size % BlockSize != 0) {
  144. string msg = Locale.GetText ("Not a multiple of {0} bytes.", BlockSize);
  145. throw new CryptographicException (msg);
  146. }
  147. if ((scope < MemoryProtectionScope.SameProcess) || (scope > MemoryProtectionScope.SameLogon)) {
  148. string msg = Locale.GetText ("Invalid enum value for '{0}'.", "MemoryProtectionScope");
  149. throw new ArgumentException (msg, "scope");
  150. }
  151. switch (impl) {
  152. case MemoryProtectionImplementation.Unknown:
  153. Detect ();
  154. break;
  155. case MemoryProtectionImplementation.Unsupported:
  156. throw new PlatformNotSupportedException ();
  157. }
  158. }
  159. // http://msdn.microsoft.com/library/en-us/dncode/html/secure06122003.asp
  160. // Summary: CryptProtectMemory and CryptUnprotectMemory exists only in Windows 2003 +
  161. // but they are available in advapi32.dll as RtlEncryptMemory (SystemFunction040) and
  162. // RtlDecryptMemory (SystemFunction041) since Windows 2000 SP 3. Sadly both can disappear
  163. // anytime with newer OS so we include support for Crypt[Unp|P]rotectMemory too.
  164. [SuppressUnmanagedCodeSecurity]
  165. [DllImport ("advapi32.dll", EntryPoint="SystemFunction040", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  166. private static extern int RtlEncryptMemory (byte[] pData, uint cbData, uint dwFlags);
  167. [SuppressUnmanagedCodeSecurity]
  168. [DllImport ("advapi32.dll", EntryPoint = "SystemFunction041", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  169. private static extern int RtlDecryptMemory (byte[] pData, uint cbData, uint dwFlags);
  170. [SuppressUnmanagedCodeSecurity]
  171. [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  172. private static extern bool CryptProtectMemory (byte[] pData, uint cbData, uint dwFlags);
  173. [SuppressUnmanagedCodeSecurity]
  174. [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  175. private static extern bool CryptUnprotectMemory (byte[] pData, uint cbData, uint dwFlags);
  176. }
  177. }
  178. #endif