SecureString.Windows.cs 9.5 KB

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