forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterop.Keychain.macOS.cs
493 lines (404 loc) · 16.6 KB
/
Interop.Keychain.macOS.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class AppleCrypto
{
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SecKeychainItemCopyKeychain(
IntPtr item,
out SafeKeychainHandle keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SecKeychainCreate", CharSet = CharSet.Ansi)]
private static unsafe partial int AppleCryptoNative_SecKeychainCreateTemporary(
string path,
int utf8PassphraseLength,
byte* utf8Passphrase,
out SafeTemporaryKeychainHandle keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative, CharSet = CharSet.Ansi)]
private static partial int AppleCryptoNative_SecKeychainCreate(
string path,
int utf8PassphraseLength,
byte[] utf8Passphrase,
out SafeKeychainHandle keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SecKeychainDelete(IntPtr keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SecKeychainCopyDefault(out SafeKeychainHandle keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative, CharSet = CharSet.Ansi)]
private static partial int AppleCryptoNative_SecKeychainOpen(
string keychainPath,
out SafeKeychainHandle keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SecKeychainUnlock(
SafeKeychainHandle keychain,
int utf8PassphraseLength,
byte[] utf8Passphrase);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SetKeychainNeverLock(SafeKeychainHandle keychain);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SecKeychainEnumerateCerts(
SafeKeychainHandle keychain,
out SafeCFArrayHandle matches,
out int pOSStatus);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_SecKeychainEnumerateIdentities(
SafeKeychainHandle keychain,
out SafeCFArrayHandle matches,
out int pOSStatus);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_X509StoreAddCertificate(
SafeKeychainItemHandle cert,
SafeKeychainHandle keychain,
out int pOSStatus);
[GeneratedDllImport(Libraries.AppleCryptoNative)]
private static partial int AppleCryptoNative_X509StoreRemoveCertificate(
SafeKeychainItemHandle cert,
SafeKeychainHandle keychain,
bool isReadOnlyMode,
out int pOSStatus);
private static SafeKeychainHandle SecKeychainItemCopyKeychain(SafeHandle item)
{
bool addedRef = false;
try
{
item.DangerousAddRef(ref addedRef);
var handle = SecKeychainItemCopyKeychain(item.DangerousGetHandle());
return handle;
}
finally
{
if (addedRef)
{
item.DangerousRelease();
}
}
}
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(SafeKeychainItemHandle item)
=> SecKeychainItemCopyKeychain((SafeHandle)item);
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(SafeSecKeyRefHandle item)
=> SecKeychainItemCopyKeychain((SafeHandle)item);
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(IntPtr item)
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainItemCopyKeychain(item, out keychain);
// A whole lot of NULL is expected from this.
// Any key or cert which isn't keychain-backed, and this is the primary way we'd find that out.
if (keychain.IsInvalid)
{
GC.SuppressFinalize(keychain);
}
if (osStatus == 0)
{
return keychain;
}
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeKeychainHandle SecKeychainCopyDefault()
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainCopyDefault(out keychain);
if (osStatus == 0)
{
return keychain;
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeKeychainHandle SecKeychainOpen(string keychainPath)
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainOpen(keychainPath, out keychain);
if (osStatus == 0)
{
return keychain;
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeCFArrayHandle KeychainEnumerateCerts(SafeKeychainHandle keychainHandle)
{
SafeCFArrayHandle matches;
int osStatus;
int result = AppleCryptoNative_SecKeychainEnumerateCerts(keychainHandle, out matches, out osStatus);
if (result == 1)
{
return matches;
}
matches.Dispose();
if (result == 0)
throw CreateExceptionForOSStatus(osStatus);
Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}");
throw new CryptographicException();
}
internal static SafeCFArrayHandle KeychainEnumerateIdentities(SafeKeychainHandle keychainHandle)
{
SafeCFArrayHandle matches;
int osStatus;
int result = AppleCryptoNative_SecKeychainEnumerateIdentities(keychainHandle, out matches, out osStatus);
if (result == 1)
{
return matches;
}
matches.Dispose();
if (result == 0)
throw CreateExceptionForOSStatus(osStatus);
Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}");
throw new CryptographicException();
}
internal static SafeKeychainHandle CreateOrOpenKeychain(string keychainPath, bool createAllowed)
{
const int errSecAuthFailed = -25293;
const int errSecDuplicateKeychain = -25296;
SafeKeychainHandle keychain;
int osStatus;
if (createAllowed)
{
// Attempt to create first
osStatus = AppleCryptoNative_SecKeychainCreate(
keychainPath,
0,
Array.Empty<byte>(),
out keychain);
if (osStatus == 0)
{
return keychain;
}
if (osStatus != errSecDuplicateKeychain)
{
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
}
osStatus = AppleCryptoNative_SecKeychainOpen(keychainPath, out keychain);
if (osStatus == 0)
{
// Try to unlock with empty password to match our behaviour in CreateKeychain.
// If the password doesn't match then ignore it silently and fallback to the
// default behavior of user interaction.
osStatus = AppleCryptoNative_SecKeychainUnlock(keychain, 0, Array.Empty<byte>());
if (osStatus == 0 || osStatus == errSecAuthFailed)
{
return keychain;
}
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static unsafe SafeTemporaryKeychainHandle CreateTemporaryKeychain()
{
const int randomSize = 256;
string tmpKeychainPath = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString("N") + ".keychain");
// Use a random password so that if a keychain is abandoned it isn't recoverable.
// We use stack to minimize lingering
Span<byte> random = stackalloc byte[randomSize];
RandomNumberGenerator.Fill(random);
// Create hex-like UTF8 string.
Span<byte> utf8Passphrase = stackalloc byte[randomSize * 2 +1];
utf8Passphrase[randomSize * 2] = 0; // null termination for C string.
for (int i = 0; i < random.Length; i++)
{
// Instead of true hexadecimal, we simply take lower and upper 4 bits and we offset them from ASCII 'A'
// to get printable form. We dont use managed string to avoid lingering copies.
utf8Passphrase[i*2] = (byte)((random[i] & 0x0F) + 65);
utf8Passphrase[i*2 + 1] = (byte)((random[i] >> 4) & 0x0F + 65);
}
// clear the binary bits.
CryptographicOperations.ZeroMemory(random);
SafeTemporaryKeychainHandle keychain;
int osStatus;
fixed (byte* ptr = utf8Passphrase)
{
osStatus = AppleCryptoNative_SecKeychainCreateTemporary(
tmpKeychainPath,
utf8Passphrase.Length,
ptr,
out keychain);
}
CryptographicOperations.ZeroMemory(utf8Passphrase);
SafeTemporaryKeychainHandle.TrackKeychain(keychain);
if (osStatus == 0)
{
osStatus = AppleCryptoNative_SetKeychainNeverLock(keychain);
}
if (osStatus != 0)
{
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
return keychain;
}
internal static void SecKeychainDelete(IntPtr handle, bool throwOnError=true)
{
int osStatus = AppleCryptoNative_SecKeychainDelete(handle);
if (throwOnError && osStatus != 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
}
internal static void X509StoreAddCertificate(SafeKeychainItemHandle certOrIdentity, SafeKeychainHandle keychain)
{
int osStatus;
int ret = AppleCryptoNative_X509StoreAddCertificate(certOrIdentity, keychain, out osStatus);
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
if (ret != 1)
{
Debug.Fail($"Unexpected result from AppleCryptoNative_X509StoreAddCertificate: {ret}");
throw new CryptographicException();
}
}
internal static void X509StoreRemoveCertificate(SafeKeychainItemHandle certHandle, SafeKeychainHandle keychain, bool isReadOnlyMode)
{
int osStatus;
int ret = AppleCryptoNative_X509StoreRemoveCertificate(certHandle, keychain, isReadOnlyMode, out osStatus);
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
const int SuccessOrNoMatch = 1;
const int UserTrustExists = 2;
const int AdminTrustExists = 3;
const int ReadOnlyDelete = 4;
switch (ret)
{
case SuccessOrNoMatch:
break;
case UserTrustExists:
throw new CryptographicException(SR.Cryptography_X509Store_WouldModifyUserTrust);
case AdminTrustExists:
throw new CryptographicException(SR.Cryptography_X509Store_WouldModifyAdminTrust);
case ReadOnlyDelete:
throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly);
default:
Debug.Fail($"Unexpected result from AppleCryptoNative_X509StoreRemoveCertificate: {ret}");
throw new CryptographicException();
}
}
}
}
namespace System.Security.Cryptography.Apple
{
internal class SafeKeychainItemHandle : SafeHandle
{
public SafeKeychainItemHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
SafeTemporaryKeychainHandle.UntrackItem(handle);
Interop.CoreFoundation.CFRelease(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid => handle == IntPtr.Zero;
}
internal class SafeKeychainHandle : SafeHandle
{
public SafeKeychainHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
internal SafeKeychainHandle(IntPtr handle)
: base(handle, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.CoreFoundation.CFRelease(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid => handle == IntPtr.Zero;
}
internal sealed class SafeTemporaryKeychainHandle : SafeKeychainHandle
{
private static readonly Dictionary<IntPtr, SafeTemporaryKeychainHandle> s_lookup =
new Dictionary<IntPtr, SafeTemporaryKeychainHandle>();
public SafeTemporaryKeychainHandle()
{
}
protected override bool ReleaseHandle()
{
lock (s_lookup)
{
s_lookup.Remove(handle);
}
Interop.AppleCrypto.SecKeychainDelete(handle, throwOnError: false);
return base.ReleaseHandle();
}
protected override void Dispose(bool disposing)
{
if (disposing && SafeHandleCache<SafeTemporaryKeychainHandle>.IsCachedInvalidHandle(this))
{
return;
}
base.Dispose(disposing);
}
public static SafeTemporaryKeychainHandle InvalidHandle =>
SafeHandleCache<SafeTemporaryKeychainHandle>.GetInvalidHandle(() => new SafeTemporaryKeychainHandle());
internal static void TrackKeychain(SafeTemporaryKeychainHandle toTrack)
{
if (toTrack.IsInvalid)
{
return;
}
lock (s_lookup)
{
Debug.Assert(!s_lookup.ContainsKey(toTrack.handle));
s_lookup[toTrack.handle] = toTrack;
}
}
internal static void TrackItem(SafeKeychainItemHandle keychainItem)
{
if (keychainItem.IsInvalid)
return;
using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem))
{
if (keychain.IsInvalid)
{
return;
}
lock (s_lookup)
{
SafeTemporaryKeychainHandle? temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
bool ignored = false;
temporaryHandle.DangerousAddRef(ref ignored);
}
}
}
}
internal static void UntrackItem(IntPtr keychainItem)
{
using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem))
{
if (keychain.IsInvalid)
{
return;
}
lock (s_lookup)
{
SafeTemporaryKeychainHandle? temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
temporaryHandle.DangerousRelease();
}
}
}
}
}
}