|
| 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 | + |
| 5 | +using System.Diagnostics; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using System.Text; |
| 8 | + |
| 9 | +namespace System.Security |
| 10 | +{ |
| 11 | + // SecureString attempts to provide a defense-in-depth solution. |
| 12 | + // |
| 13 | + // On Windows, this is done with several mechanisms: |
| 14 | + // 1. keeping the data in unmanaged memory so that copies of it aren't implicitly made by the GC moving it around |
| 15 | + // 2. zero'ing out that unmanaged memory so that the string is reliably removed from memory when done with it |
| 16 | + // 3. encrypting the data while it's not being used (it's unencrypted to manipulate and use it) |
| 17 | + // |
| 18 | + // On Unix, we do 1 and 2, but we don't do 3 as there's no CryptProtectData equivalent. |
| 19 | + |
| 20 | + public sealed partial class SecureString |
| 21 | + { |
| 22 | + private UnmanagedBuffer _buffer; |
| 23 | + |
| 24 | + internal SecureString(SecureString str) |
| 25 | + { |
| 26 | + // Allocate enough space to store the provided string |
| 27 | + EnsureCapacity(str._decryptedLength); |
| 28 | + _decryptedLength = str._decryptedLength; |
| 29 | + |
| 30 | + // Copy the string into the newly allocated space |
| 31 | + if (_decryptedLength > 0) |
| 32 | + { |
| 33 | + UnmanagedBuffer.Copy(str._buffer, _buffer, (ulong)(str._decryptedLength * sizeof(char))); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private unsafe void InitializeSecureString(char* value, int length) |
| 38 | + { |
| 39 | + // Allocate enough space to store the provided string |
| 40 | + EnsureCapacity(length); |
| 41 | + _decryptedLength = length; |
| 42 | + if (length == 0) |
| 43 | + { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + // Copy the string into the newly allocated space |
| 48 | + byte* ptr = null; |
| 49 | + try |
| 50 | + { |
| 51 | + _buffer.AcquirePointer(ref ptr); |
| 52 | + Buffer.MemoryCopy(value, ptr, _buffer.ByteLength, (ulong)(length * sizeof(char))); |
| 53 | + } |
| 54 | + finally |
| 55 | + { |
| 56 | + if (ptr != null) |
| 57 | + { |
| 58 | + _buffer.ReleasePointer(); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private void DisposeCore() |
| 64 | + { |
| 65 | + if (_buffer != null && !_buffer.IsInvalid) |
| 66 | + { |
| 67 | + _buffer.Dispose(); |
| 68 | + _buffer = null; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private void EnsureNotDisposed() |
| 73 | + { |
| 74 | + if (_buffer == null) |
| 75 | + { |
| 76 | + throw new ObjectDisposedException(GetType().Name); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + private void ClearCore() |
| 81 | + { |
| 82 | + _decryptedLength = 0; |
| 83 | + _buffer.Clear(); |
| 84 | + } |
| 85 | + |
| 86 | + private unsafe void AppendCharCore(char c) |
| 87 | + { |
| 88 | + // Make sure we have enough space for the new character, then write it at the end. |
| 89 | + EnsureCapacity(_decryptedLength + 1); |
| 90 | + _buffer.Write((ulong)(_decryptedLength * sizeof(char)), c); |
| 91 | + _decryptedLength++; |
| 92 | + } |
| 93 | + |
| 94 | + private unsafe void InsertAtCore(int index, char c) |
| 95 | + { |
| 96 | + // Make sure we have enough space for the new character, then shift all of the characters above it and insert it. |
| 97 | + EnsureCapacity(_decryptedLength + 1); |
| 98 | + byte* ptr = null; |
| 99 | + try |
| 100 | + { |
| 101 | + _buffer.AcquirePointer(ref ptr); |
| 102 | + ptr += index * sizeof(char); |
| 103 | + long bytesToShift = (_decryptedLength - index) * sizeof(char); |
| 104 | + Buffer.MemoryCopy(ptr, ptr + sizeof(char), bytesToShift, bytesToShift); |
| 105 | + *((char*)ptr) = c; |
| 106 | + ++_decryptedLength; |
| 107 | + } |
| 108 | + finally |
| 109 | + { |
| 110 | + if (ptr != null) |
| 111 | + { |
| 112 | + _buffer.ReleasePointer(); |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + private unsafe void RemoveAtCore(int index) |
| 118 | + { |
| 119 | + // Shift down all values above the specified index, then null out the empty space at the end. |
| 120 | + byte* ptr = null; |
| 121 | + try |
| 122 | + { |
| 123 | + _buffer.AcquirePointer(ref ptr); |
| 124 | + ptr += index * sizeof(char); |
| 125 | + long bytesToShift = (_decryptedLength - index - 1) * sizeof(char); |
| 126 | + Buffer.MemoryCopy(ptr + sizeof(char), ptr, bytesToShift, bytesToShift); |
| 127 | + *((char*)(ptr + bytesToShift)) = (char)0; |
| 128 | + --_decryptedLength; |
| 129 | + } |
| 130 | + finally |
| 131 | + { |
| 132 | + if (ptr != null) |
| 133 | + { |
| 134 | + _buffer.ReleasePointer(); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private void SetAtCore(int index, char c) |
| 140 | + { |
| 141 | + // Overwrite the character at the specified index |
| 142 | + _buffer.Write((ulong)(index * sizeof(char)), c); |
| 143 | + } |
| 144 | + |
| 145 | + internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode) |
| 146 | + { |
| 147 | + int length = _decryptedLength; |
| 148 | + |
| 149 | + byte* bufferPtr = null; |
| 150 | + IntPtr stringPtr = IntPtr.Zero, result = IntPtr.Zero; |
| 151 | + try |
| 152 | + { |
| 153 | + _buffer.AcquirePointer(ref bufferPtr); |
| 154 | + if (unicode) |
| 155 | + { |
| 156 | + int resultLength = (length + 1) * sizeof(char); |
| 157 | + stringPtr = globalAlloc ? Marshal.AllocHGlobal(resultLength) : Marshal.AllocCoTaskMem(resultLength); |
| 158 | + Buffer.MemoryCopy( |
| 159 | + source: bufferPtr, |
| 160 | + destination: (byte*)stringPtr.ToPointer(), |
| 161 | + destinationSizeInBytes: resultLength, |
| 162 | + sourceBytesToCopy: length * sizeof(char)); |
| 163 | + *(length + (char*)stringPtr) = '\0'; |
| 164 | + } |
| 165 | + else |
| 166 | + { |
| 167 | + int resultLength = Encoding.UTF8.GetByteCount((char*)bufferPtr, length) + 1; |
| 168 | + stringPtr = globalAlloc ? Marshal.AllocHGlobal(resultLength) : Marshal.AllocCoTaskMem(resultLength); |
| 169 | + int encodedLength = Encoding.UTF8.GetBytes((char*)bufferPtr, length, (byte*)stringPtr, resultLength); |
| 170 | + Debug.Assert(encodedLength + 1 == resultLength, $"Expected encoded length to match result, got {encodedLength} != {resultLength}"); |
| 171 | + *(resultLength - 1 + (byte*)stringPtr) = 0; |
| 172 | + } |
| 173 | + |
| 174 | + result = stringPtr; |
| 175 | + } |
| 176 | + finally |
| 177 | + { |
| 178 | + // If there was a failure, such that result isn't initialized, |
| 179 | + // release the string if we had one. |
| 180 | + if (stringPtr != IntPtr.Zero && result == IntPtr.Zero) |
| 181 | + { |
| 182 | + UnmanagedBuffer.ZeroMemory((byte*)stringPtr, (ulong)(length * sizeof(char))); |
| 183 | + MarshalFree(stringPtr, globalAlloc); |
| 184 | + } |
| 185 | + |
| 186 | + if (bufferPtr != null) |
| 187 | + { |
| 188 | + _buffer.ReleasePointer(); |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + return result; |
| 193 | + } |
| 194 | + |
| 195 | + // ----------------------------- |
| 196 | + // ---- PAL layer ends here ---- |
| 197 | + // ----------------------------- |
| 198 | + |
| 199 | + private void EnsureCapacity(int capacity) |
| 200 | + { |
| 201 | + // Make sure the requested capacity doesn't exceed SecureString's defined limit |
| 202 | + if (capacity > MaxLength) |
| 203 | + { |
| 204 | + throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); |
| 205 | + } |
| 206 | + |
| 207 | + // If we already have enough space allocated, we're done |
| 208 | + if (_buffer != null && (capacity * sizeof(char)) <= (int)_buffer.ByteLength) |
| 209 | + { |
| 210 | + return; |
| 211 | + } |
| 212 | + |
| 213 | + // We need more space, so allocate a new buffer, copy all our data into it, |
| 214 | + // and then swap the new for the old. |
| 215 | + UnmanagedBuffer newBuffer = UnmanagedBuffer.Allocate(capacity * sizeof(char)); |
| 216 | + if (_buffer != null) |
| 217 | + { |
| 218 | + UnmanagedBuffer.Copy(_buffer, newBuffer, _buffer.ByteLength); |
| 219 | + _buffer.Dispose(); |
| 220 | + } |
| 221 | + _buffer = newBuffer; |
| 222 | + } |
| 223 | + |
| 224 | + /// <summary>SafeBuffer for managing memory meant to be kept confidential.</summary> |
| 225 | + private sealed class UnmanagedBuffer : SafeBuffer |
| 226 | + { |
| 227 | + internal UnmanagedBuffer() : base(true) { } |
| 228 | + |
| 229 | + internal static UnmanagedBuffer Allocate(int bytes) |
| 230 | + { |
| 231 | + Debug.Assert(bytes >= 0); |
| 232 | + UnmanagedBuffer buffer = new UnmanagedBuffer(); |
| 233 | + buffer.SetHandle(Marshal.AllocHGlobal(bytes)); |
| 234 | + buffer.Initialize((ulong)bytes); |
| 235 | + return buffer; |
| 236 | + } |
| 237 | + |
| 238 | + internal unsafe void Clear() |
| 239 | + { |
| 240 | + byte* ptr = null; |
| 241 | + try |
| 242 | + { |
| 243 | + AcquirePointer(ref ptr); |
| 244 | + ZeroMemory(ptr, ByteLength); |
| 245 | + } |
| 246 | + finally |
| 247 | + { |
| 248 | + if (ptr != null) |
| 249 | + { |
| 250 | + ReleasePointer(); |
| 251 | + } |
| 252 | + } |
| 253 | + } |
| 254 | + |
| 255 | + internal static unsafe void Copy(UnmanagedBuffer source, UnmanagedBuffer destination, ulong bytesLength) |
| 256 | + { |
| 257 | + if (bytesLength == 0) |
| 258 | + { |
| 259 | + return; |
| 260 | + } |
| 261 | + |
| 262 | + byte* srcPtr = null, dstPtr = null; |
| 263 | + try |
| 264 | + { |
| 265 | + source.AcquirePointer(ref srcPtr); |
| 266 | + destination.AcquirePointer(ref dstPtr); |
| 267 | + Buffer.MemoryCopy(srcPtr, dstPtr, destination.ByteLength, bytesLength); |
| 268 | + } |
| 269 | + finally |
| 270 | + { |
| 271 | + if (dstPtr != null) |
| 272 | + { |
| 273 | + destination.ReleasePointer(); |
| 274 | + } |
| 275 | + if (srcPtr != null) |
| 276 | + { |
| 277 | + source.ReleasePointer(); |
| 278 | + } |
| 279 | + } |
| 280 | + } |
| 281 | + |
| 282 | + protected override unsafe bool ReleaseHandle() |
| 283 | + { |
| 284 | + Marshal.FreeHGlobal(handle); |
| 285 | + return true; |
| 286 | + } |
| 287 | + |
| 288 | + internal static unsafe void ZeroMemory(byte* ptr, ulong len) |
| 289 | + { |
| 290 | + for (ulong i = 0; i < len; i++) *ptr++ = 0; |
| 291 | + } |
| 292 | + } |
| 293 | + |
| 294 | + } |
| 295 | +} |
0 commit comments