Skip to content

Commit ab6acd1

Browse files
committed
refactor: rewrite macOS keychain integration since SecKeychain* methods are marked as Deprecated
Signed-off-by: leo <longshuang@msn.cn>
1 parent 7ae0193 commit ab6acd1

1 file changed

Lines changed: 169 additions & 102 deletions

File tree

‎src/Native/MacOS.cs‎

Lines changed: 169 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -349,140 +349,207 @@ public static void ShowAllApplications()
349349
[SupportedOSPlatform("macOS")]
350350
public class MacOSKeychain : OS.IKeychain
351351
{
352-
[DllImport("/System/Library/Frameworks/Security.framework/Security")]
353-
private static extern int SecKeychainAddGenericPassword(
354-
IntPtr keychain,
355-
uint serviceNameLength,
356-
byte[] serviceName,
357-
uint accountNameLength,
358-
byte[] accountName,
359-
uint passwordLength,
360-
byte[] passwordData,
361-
out IntPtr itemRef);
352+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
353+
private static extern IntPtr CFStringCreateWithCString(IntPtr alloc, byte[] cStr, uint encoding);
354+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
355+
private static extern IntPtr CFDataCreate(IntPtr allocator, byte[] bytes, nint length);
356+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
357+
private static extern nint CFDataGetLength(IntPtr theData);
358+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
359+
private static extern IntPtr CFDataGetBytePtr(IntPtr theData);
360+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
361+
private static extern IntPtr CFDictionaryCreateMutable(IntPtr allocator, IntPtr capacity, IntPtr keyCallBacks, IntPtr valueCallBacks);
362+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
363+
private static extern void CFDictionarySetValue(IntPtr theDict, IntPtr key, IntPtr value);
364+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
365+
private static extern void CFRelease(IntPtr cf);
362366

363-
[DllImport("/System/Library/Frameworks/Security.framework/Security")]
364-
private static extern int SecKeychainFindGenericPassword(
365-
IntPtr keychainOrArray,
366-
uint serviceNameLength,
367-
byte[] serviceName,
368-
uint accountNameLength,
369-
byte[] accountName,
370-
out uint passwordLength,
371-
out IntPtr passwordData,
372-
out IntPtr itemRef);
367+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecClass")]
368+
private static extern IntPtr _kSecClass();
369+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecClassGenericPassword")]
370+
private static extern IntPtr _kSecClassGenericPassword();
371+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecAttrService")]
372+
private static extern IntPtr _kSecAttrService();
373+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecAttrAccount")]
374+
private static extern IntPtr _kSecAttrAccount();
375+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecValueData")]
376+
private static extern IntPtr _kSecValueData();
377+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecReturnData")]
378+
private static extern IntPtr _kSecReturnData();
379+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecMatchLimit")]
380+
private static extern IntPtr _kSecMatchLimit();
381+
[DllImport("/System/Library/Frameworks/Security.framework/Security", EntryPoint = "kSecMatchLimitOne")]
382+
private static extern IntPtr _kSecMatchLimitOne();
383+
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", EntryPoint = "kCFBooleanTrue")]
384+
private static extern IntPtr _kCFBooleanTrue();
373385

374386
[DllImport("/System/Library/Frameworks/Security.framework/Security")]
375-
private static extern int SecKeychainItemModifyAttributesAndData(
376-
IntPtr itemRef,
377-
IntPtr attrList,
378-
uint length,
379-
byte[] data);
380-
387+
private static extern int SecItemAdd(IntPtr attributes, IntPtr result);
381388
[DllImport("/System/Library/Frameworks/Security.framework/Security")]
382-
private static extern int SecKeychainItemDelete(IntPtr itemRef);
383-
389+
private static extern int SecItemCopyMatching(IntPtr query, out IntPtr result);
384390
[DllImport("/System/Library/Frameworks/Security.framework/Security")]
385-
private static extern int SecKeychainItemFreeContent(IntPtr attrList, IntPtr data);
391+
private static extern int SecItemUpdate(IntPtr query, IntPtr attributesToUpdate);
392+
[DllImport("/System/Library/Frameworks/Security.framework/Security")]
393+
private static extern int SecItemDelete(IntPtr query);
394+
395+
private static readonly Lazy<IntPtr> kSecClass = new(() => _kSecClass());
396+
private static readonly Lazy<IntPtr> kSecClassGenericPassword = new(() => _kSecClassGenericPassword());
397+
private static readonly Lazy<IntPtr> kSecAttrService = new(() => _kSecAttrService());
398+
private static readonly Lazy<IntPtr> kSecAttrAccount = new(() => _kSecAttrAccount());
399+
private static readonly Lazy<IntPtr> kSecValueData = new(() => _kSecValueData());
400+
private static readonly Lazy<IntPtr> kSecReturnData = new(() => _kSecReturnData());
401+
private static readonly Lazy<IntPtr> kSecMatchLimit = new(() => _kSecMatchLimit());
402+
private static readonly Lazy<IntPtr> kSecMatchLimitOne = new(() => _kSecMatchLimitOne());
403+
private static readonly Lazy<IntPtr> kCFBooleanTrue = new(() => _kCFBooleanTrue());
386404

387-
[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
388-
private static extern void CFRelease(IntPtr cf);
405+
private const int errSecSuccess = 0;
406+
private const int errSecItemNotFound = -25300;
407+
private const int errSecDuplicateItem = -25299;
389408

390409
public void Store(string host, string username, string password)
391410
{
392-
var serviceBytes = Encoding.UTF8.GetBytes(host);
393-
var accountBytes = Encoding.UTF8.GetBytes(username);
394-
var secretBytes = Encoding.UTF8.GetBytes(password);
395-
396-
var status = SecKeychainAddGenericPassword(
397-
IntPtr.Zero,
398-
(uint)serviceBytes.Length, serviceBytes,
399-
(uint)accountBytes.Length, accountBytes,
400-
(uint)secretBytes.Length, secretBytes,
401-
out _);
402-
403-
if (status == errSecDuplicateItem)
411+
IntPtr query = IntPtr.Zero;
412+
IntPtr serviceCf = IntPtr.Zero;
413+
IntPtr accountCf = IntPtr.Zero;
414+
IntPtr dataCf = IntPtr.Zero;
415+
IntPtr attrsToUpdate = IntPtr.Zero;
416+
417+
try
404418
{
405-
// If the item already exists, update it instead
406-
status = SecKeychainFindGenericPassword(
407-
IntPtr.Zero,
408-
(uint)serviceBytes.Length, serviceBytes,
409-
(uint)accountBytes.Length, accountBytes,
410-
out _, out _, out var itemRef);
419+
serviceCf = CreateCFString(host);
420+
accountCf = CreateCFString(username);
421+
dataCf = CreateCFData(Encoding.UTF8.GetBytes(password));
422+
423+
query = CFDictionaryCreateMutable(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
424+
CFDictionarySetValue(query, kSecClass.Value, kSecClassGenericPassword.Value);
425+
CFDictionarySetValue(query, kSecAttrService.Value, serviceCf);
426+
CFDictionarySetValue(query, kSecAttrAccount.Value, accountCf);
427+
CFDictionarySetValue(query, kSecValueData.Value, dataCf);
428+
429+
int status = SecItemAdd(query, IntPtr.Zero);
430+
if (status == errSecSuccess)
431+
return;
411432

412-
if (status != errSecSuccess)
413-
throw new Exception($"Failed to find original keychain item to modify: {status}");
433+
if (status != errSecDuplicateItem)
434+
throw new Exception($"Failed to store credential to keychain: {status}");
414435

415-
status = SecKeychainItemModifyAttributesAndData(
416-
itemRef,
417-
IntPtr.Zero,
418-
(uint)secretBytes.Length, secretBytes);
436+
attrsToUpdate = CFDictionaryCreateMutable(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
437+
CFDictionarySetValue(attrsToUpdate, kSecValueData.Value, dataCf);
438+
status = SecItemUpdate(query, attrsToUpdate);
419439

420-
CFRelease(itemRef);
440+
if (status != errSecSuccess)
441+
throw new Exception($"Failed to update credential in keychain: {status}");
442+
}
443+
finally
444+
{
445+
if (query != IntPtr.Zero)
446+
CFRelease(query);
447+
if (serviceCf != IntPtr.Zero)
448+
CFRelease(serviceCf);
449+
if (accountCf != IntPtr.Zero)
450+
CFRelease(accountCf);
451+
if (dataCf != IntPtr.Zero)
452+
CFRelease(dataCf);
453+
if (attrsToUpdate != IntPtr.Zero)
454+
CFRelease(attrsToUpdate);
421455
}
422-
423-
if (status != errSecSuccess)
424-
throw new Exception($"Failed to store credential to keychain: {status}");
425456
}
426457

427458
public string Read(string host, string username)
428459
{
429-
var serviceBytes = Encoding.UTF8.GetBytes(host);
430-
var accountBytes = Encoding.UTF8.GetBytes(username);
431-
432-
var status = SecKeychainFindGenericPassword(
433-
IntPtr.Zero,
434-
(uint)serviceBytes.Length, serviceBytes,
435-
(uint)accountBytes.Length, accountBytes,
436-
out var passwordLength,
437-
out var passwordData,
438-
out var itemRef);
460+
IntPtr query = IntPtr.Zero;
461+
IntPtr serviceCf = IntPtr.Zero;
462+
IntPtr accountCf = IntPtr.Zero;
463+
IntPtr dataCf = IntPtr.Zero;
439464

440-
if (status == errSecItemNotFound)
441-
throw new Exception("Credential not found in keychain");
465+
try
466+
{
467+
serviceCf = CreateCFString(host);
468+
accountCf = CreateCFString(username);
469+
470+
query = CFDictionaryCreateMutable(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
471+
CFDictionarySetValue(query, kSecClass.Value, kSecClassGenericPassword.Value);
472+
CFDictionarySetValue(query, kSecAttrService.Value, serviceCf);
473+
CFDictionarySetValue(query, kSecAttrAccount.Value, accountCf);
474+
CFDictionarySetValue(query, kSecReturnData.Value, kCFBooleanTrue.Value);
475+
CFDictionarySetValue(query, kSecMatchLimit.Value, kSecMatchLimitOne.Value);
476+
477+
int status = SecItemCopyMatching(query, out dataCf);
478+
if (status == errSecItemNotFound)
479+
throw new Exception("Credential not found in keychain");
480+
if (status != errSecSuccess)
481+
throw new Exception($"Failed to read credential from keychain: {status}");
442482

443-
if (status != errSecSuccess)
444-
throw new Exception($"Failed to read credential from keychain: {status}");
483+
var len = CFDataGetLength(dataCf);
484+
if (len <= 0)
485+
return string.Empty;
445486

446-
if (passwordLength == 0 || passwordData == IntPtr.Zero)
487+
var ptr = CFDataGetBytePtr(dataCf);
488+
var bytes = new byte[len];
489+
Marshal.Copy(ptr, bytes, 0, (int)len);
490+
return Encoding.UTF8.GetString(bytes);
491+
}
492+
finally
447493
{
448-
CFRelease(itemRef);
449-
return string.Empty;
494+
if (query != IntPtr.Zero)
495+
CFRelease(query);
496+
if (serviceCf != IntPtr.Zero)
497+
CFRelease(serviceCf);
498+
if (accountCf != IntPtr.Zero)
499+
CFRelease(accountCf);
500+
if (dataCf != IntPtr.Zero)
501+
CFRelease(dataCf);
450502
}
451-
452-
var passwordBytes = new byte[passwordLength];
453-
Marshal.Copy(passwordData, passwordBytes, 0, (int)passwordLength);
454-
CFRelease(itemRef);
455-
return Encoding.UTF8.GetString(passwordBytes);
456503
}
457504

458505
public void Erase(string host, string username)
459506
{
460-
var serviceBytes = Encoding.UTF8.GetBytes(host);
461-
var accountBytes = Encoding.UTF8.GetBytes(username);
462-
463-
var status = SecKeychainFindGenericPassword(
464-
IntPtr.Zero,
465-
(uint)serviceBytes.Length, serviceBytes,
466-
(uint)accountBytes.Length, accountBytes,
467-
out var passwordLength,
468-
out var passwordData,
469-
out var itemRef);
470-
471-
if (status == errSecItemNotFound)
472-
return;
507+
IntPtr query = IntPtr.Zero;
508+
IntPtr serviceCf = IntPtr.Zero;
509+
IntPtr accountCf = IntPtr.Zero;
473510

474-
if (status != errSecSuccess)
475-
throw new Exception($"Failed to find credential in keychain: {status}");
511+
try
512+
{
513+
serviceCf = CreateCFString(host);
514+
accountCf = CreateCFString(username);
476515

477-
status = SecKeychainItemDelete(itemRef);
478-
CFRelease(itemRef);
516+
query = CFDictionaryCreateMutable(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
517+
CFDictionarySetValue(query, kSecClass.Value, kSecClassGenericPassword.Value);
518+
CFDictionarySetValue(query, kSecAttrService.Value, serviceCf);
519+
CFDictionarySetValue(query, kSecAttrAccount.Value, accountCf);
520+
521+
int status = SecItemDelete(query);
522+
if (status == errSecSuccess || status == errSecItemNotFound)
523+
return;
479524

480-
if (status != errSecSuccess && status != errSecItemNotFound)
481525
throw new Exception($"Failed to delete credential from keychain: {status}");
526+
}
527+
finally
528+
{
529+
if (query != IntPtr.Zero)
530+
CFRelease(query);
531+
if (serviceCf != IntPtr.Zero)
532+
CFRelease(serviceCf);
533+
if (accountCf != IntPtr.Zero)
534+
CFRelease(accountCf);
535+
}
482536
}
483537

484-
private const int errSecSuccess = 0;
485-
private const int errSecItemNotFound = -25300;
486-
private const int errSecDuplicateItem = -25299;
538+
private IntPtr CreateCFString(string str)
539+
{
540+
var bytes = Encoding.UTF8.GetBytes(str + "\0");
541+
var ptr = CFStringCreateWithCString(IntPtr.Zero, bytes, 0x08000100 /* kCFStringEncodingUTF8 */);
542+
if (ptr == IntPtr.Zero)
543+
throw new InvalidOperationException("CFStringCreateWithCString failed.");
544+
return ptr;
545+
}
546+
547+
private IntPtr CreateCFData(byte[] bytes)
548+
{
549+
var ptr = CFDataCreate(IntPtr.Zero, bytes, bytes.Length);
550+
if (ptr == IntPtr.Zero)
551+
throw new InvalidOperationException("CFDataCreate failed.");
552+
return ptr;
553+
}
487554
}
488555
}

0 commit comments

Comments
 (0)