ProtectedMemory.cs 7.2 KB

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