SecureString.Windows.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime;
  6. using System.Runtime.InteropServices;
  7. using System.Security.Cryptography;
  8. namespace System.Security
  9. {
  10. public sealed partial class SecureString
  11. {
  12. internal SecureString(SecureString str)
  13. {
  14. Debug.Assert(str != null, "Expected non-null SecureString");
  15. Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null");
  16. Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings");
  17. AllocateBuffer(str._buffer.Length);
  18. Debug.Assert(_buffer != null);
  19. SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char));
  20. _decryptedLength = str._decryptedLength;
  21. _encrypted = str._encrypted;
  22. }
  23. private unsafe void InitializeSecureString(char* value, int length)
  24. {
  25. Debug.Assert(length >= 0, $"Expected non-negative length, got {length}");
  26. AllocateBuffer((uint)length);
  27. _decryptedLength = length;
  28. byte* bufferPtr = null;
  29. Debug.Assert(_buffer != null);
  30. try
  31. {
  32. _buffer.AcquirePointer(ref bufferPtr);
  33. Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char));
  34. }
  35. finally
  36. {
  37. if (bufferPtr != null)
  38. {
  39. _buffer.ReleasePointer();
  40. }
  41. }
  42. ProtectMemory();
  43. }
  44. private void AppendCharCore(char c)
  45. {
  46. UnprotectMemory();
  47. try
  48. {
  49. EnsureCapacity(_decryptedLength + 1);
  50. Debug.Assert(_buffer != null);
  51. _buffer.Write<char>((uint)_decryptedLength * sizeof(char), c);
  52. _decryptedLength++;
  53. }
  54. finally
  55. {
  56. ProtectMemory();
  57. }
  58. }
  59. private void ClearCore()
  60. {
  61. _decryptedLength = 0;
  62. Debug.Assert(_buffer != null);
  63. _buffer.ClearBuffer();
  64. }
  65. private void DisposeCore()
  66. {
  67. if (_buffer != null)
  68. {
  69. _buffer.Dispose();
  70. _buffer = null;
  71. }
  72. }
  73. private unsafe void InsertAtCore(int index, char c)
  74. {
  75. byte* bufferPtr = null;
  76. UnprotectMemory();
  77. Debug.Assert(_buffer != null);
  78. try
  79. {
  80. EnsureCapacity(_decryptedLength + 1);
  81. _buffer.AcquirePointer(ref bufferPtr);
  82. char* pBuffer = (char*)bufferPtr;
  83. for (int i = _decryptedLength; i > index; i--)
  84. {
  85. pBuffer[i] = pBuffer[i - 1];
  86. }
  87. pBuffer[index] = c;
  88. ++_decryptedLength;
  89. }
  90. finally
  91. {
  92. ProtectMemory();
  93. if (bufferPtr != null)
  94. {
  95. _buffer.ReleasePointer();
  96. }
  97. }
  98. }
  99. private unsafe void RemoveAtCore(int index)
  100. {
  101. byte* bufferPtr = null;
  102. UnprotectMemory();
  103. Debug.Assert(_buffer != null);
  104. try
  105. {
  106. _buffer.AcquirePointer(ref bufferPtr);
  107. char* pBuffer = (char*)bufferPtr;
  108. for (int i = index; i < _decryptedLength - 1; i++)
  109. {
  110. pBuffer[i] = pBuffer[i + 1];
  111. }
  112. pBuffer[--_decryptedLength] = (char)0;
  113. }
  114. finally
  115. {
  116. ProtectMemory();
  117. if (bufferPtr != null)
  118. {
  119. _buffer.ReleasePointer();
  120. }
  121. }
  122. }
  123. private void SetAtCore(int index, char c)
  124. {
  125. UnprotectMemory();
  126. try
  127. {
  128. Debug.Assert(_buffer != null);
  129. _buffer.Write<char>((uint)index * sizeof(char), c);
  130. }
  131. finally
  132. {
  133. ProtectMemory();
  134. }
  135. }
  136. internal unsafe IntPtr MarshalToBSTRCore()
  137. {
  138. int length = _decryptedLength;
  139. IntPtr ptr = IntPtr.Zero;
  140. IntPtr result = IntPtr.Zero;
  141. byte* bufferPtr = null;
  142. UnprotectMemory();
  143. Debug.Assert(_buffer != null);
  144. try
  145. {
  146. _buffer.AcquirePointer(ref bufferPtr);
  147. int resultByteLength = (length + 1) * sizeof(char);
  148. ptr = Marshal.AllocBSTR(length);
  149. Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
  150. result = ptr;
  151. }
  152. finally
  153. {
  154. ProtectMemory();
  155. // If we failed for any reason, free the new buffer
  156. if (result == IntPtr.Zero && ptr != IntPtr.Zero)
  157. {
  158. RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
  159. Marshal.FreeBSTR(ptr);
  160. }
  161. if (bufferPtr != null)
  162. {
  163. _buffer.ReleasePointer();
  164. }
  165. }
  166. return result;
  167. }
  168. internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode)
  169. {
  170. int length = _decryptedLength;
  171. IntPtr ptr = IntPtr.Zero;
  172. IntPtr result = IntPtr.Zero;
  173. byte* bufferPtr = null;
  174. UnprotectMemory();
  175. Debug.Assert(_buffer != null);
  176. try
  177. {
  178. _buffer.AcquirePointer(ref bufferPtr);
  179. if (unicode)
  180. {
  181. int resultByteLength = (length + 1) * sizeof(char);
  182. ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
  183. Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
  184. *(length + (char*)ptr) = '\0';
  185. }
  186. else
  187. {
  188. uint defaultChar = '?';
  189. int resultByteLength = 1 + Interop.Kernel32.WideCharToMultiByte(
  190. Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero);
  191. ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
  192. Interop.Kernel32.WideCharToMultiByte(
  193. Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero);
  194. *(resultByteLength - 1 + (byte*)ptr) = 0;
  195. }
  196. result = ptr;
  197. }
  198. finally
  199. {
  200. ProtectMemory();
  201. // If we failed for any reason, free the new buffer
  202. if (result == IntPtr.Zero && ptr != IntPtr.Zero)
  203. {
  204. RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
  205. MarshalFree(ptr, globalAlloc);
  206. }
  207. if (bufferPtr != null)
  208. {
  209. _buffer.ReleasePointer();
  210. }
  211. }
  212. return result;
  213. }
  214. // -----------------------------
  215. // ---- PAL layer ends here ----
  216. // -----------------------------
  217. private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char);
  218. private SafeBSTRHandle? _buffer;
  219. private bool _encrypted;
  220. private void AllocateBuffer(uint size)
  221. {
  222. _buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size));
  223. }
  224. private static uint GetAlignedSize(uint size) =>
  225. size == 0 || size % BlockSize != 0 ?
  226. BlockSize + ((size / BlockSize) * BlockSize) :
  227. size;
  228. private void EnsureCapacity(int capacity)
  229. {
  230. if (capacity > MaxLength)
  231. {
  232. throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
  233. }
  234. Debug.Assert(_buffer != null);
  235. if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength)
  236. {
  237. return;
  238. }
  239. var oldBuffer = _buffer;
  240. SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity));
  241. SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char));
  242. _buffer = newBuffer;
  243. oldBuffer.Dispose();
  244. }
  245. private void ProtectMemory()
  246. {
  247. Debug.Assert(_buffer != null);
  248. Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
  249. if (_decryptedLength != 0 &&
  250. !_encrypted &&
  251. !Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
  252. {
  253. throw new CryptographicException(Marshal.GetLastWin32Error());
  254. }
  255. _encrypted = true;
  256. }
  257. private void UnprotectMemory()
  258. {
  259. Debug.Assert(_buffer != null);
  260. Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
  261. if (_decryptedLength != 0 &&
  262. _encrypted &&
  263. !Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
  264. {
  265. throw new CryptographicException(Marshal.GetLastWin32Error());
  266. }
  267. _encrypted = false;
  268. }
  269. }
  270. }