/
MacOSKeychain.cs
352 lines (300 loc) · 13 KB
/
MacOSKeychain.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using GitCredentialManager.Interop.MacOS.Native;
using static GitCredentialManager.Interop.MacOS.Native.CoreFoundation;
using static GitCredentialManager.Interop.MacOS.Native.SecurityFramework;
namespace GitCredentialManager.Interop.MacOS
{
public class MacOSKeychain : ICredentialStore
{
private readonly string _namespace;
#region Constructors
/// <summary>
/// Open the default keychain (current user's login keychain).
/// </summary>
/// <param name="namespace">Optional namespace to scope credential operations.</param>
/// <returns>Default keychain.</returns>
public MacOSKeychain(string @namespace = null)
{
PlatformUtils.EnsureMacOS();
_namespace = @namespace;
}
#endregion
#region ICredentialStore
public IList<string> GetAccounts(string service)
{
IntPtr query = IntPtr.Zero;
IntPtr resultPtr = IntPtr.Zero;
IntPtr servicePtr = IntPtr.Zero;
IntPtr accountPtr = IntPtr.Zero;
try
{
query = CFDictionaryCreateMutable(
IntPtr.Zero,
0,
IntPtr.Zero, IntPtr.Zero);
CFDictionaryAddValue(query, kSecClass, kSecClassGenericPassword);
CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitAll);
CFDictionaryAddValue(query, kSecReturnAttributes, kCFBooleanTrue);
if (!string.IsNullOrWhiteSpace(service))
{
string fullService = CreateServiceName(service);
servicePtr = CreateCFStringUtf8(fullService);
CFDictionaryAddValue(query, kSecAttrService, servicePtr);
}
int searchResult = SecItemCopyMatching(query, out resultPtr);
switch (searchResult)
{
case OK:
int typeId = CFGetTypeID(resultPtr);
Debug.Assert(typeId == CFArrayGetTypeID(), "Returned unknown item from account query");
if (typeId == CFArrayGetTypeID())
{
int len = (int)CFArrayGetCount(resultPtr);
var accounts = new HashSet<string>(len);
for (int i = 0; i < len; i++)
{
IntPtr dict = CFArrayGetValueAtIndex(resultPtr, i);
string account = GetStringAttribute(dict, kSecAttrAccount);
accounts.Add(account);
}
return accounts.ToList();
}
throw new InteropException($"Unknown keychain search result type CFTypeID: {typeId}.", -1);
case ErrorSecItemNotFound:
return Array.Empty<string>();
default:
ThrowIfError(searchResult);
return null;
}
}
finally
{
if (query != IntPtr.Zero) CFRelease(query);
if (servicePtr != IntPtr.Zero) CFRelease(servicePtr);
if (accountPtr != IntPtr.Zero) CFRelease(accountPtr);
if (resultPtr != IntPtr.Zero) CFRelease(resultPtr);
}
}
public ICredential Get(string service, string account)
{
IntPtr query = IntPtr.Zero;
IntPtr resultPtr = IntPtr.Zero;
IntPtr servicePtr = IntPtr.Zero;
IntPtr accountPtr = IntPtr.Zero;
try
{
query = CFDictionaryCreateMutable(
IntPtr.Zero,
0,
IntPtr.Zero, IntPtr.Zero);
CFDictionaryAddValue(query, kSecClass, kSecClassGenericPassword);
CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
CFDictionaryAddValue(query, kSecReturnData, kCFBooleanTrue);
CFDictionaryAddValue(query, kSecReturnAttributes, kCFBooleanTrue);
if (!string.IsNullOrWhiteSpace(service))
{
string fullService = CreateServiceName(service);
servicePtr = CreateCFStringUtf8(fullService);
CFDictionaryAddValue(query, kSecAttrService, servicePtr);
}
if (!string.IsNullOrWhiteSpace(account))
{
accountPtr = CreateCFStringUtf8(account);
CFDictionaryAddValue(query, kSecAttrAccount, accountPtr);
}
int searchResult = SecItemCopyMatching(query, out resultPtr);
switch (searchResult)
{
case OK:
int typeId = CFGetTypeID(resultPtr);
Debug.Assert(typeId != CFArrayGetTypeID(), "Returned more than one keychain item in search");
if (typeId == CFDictionaryGetTypeID())
{
return CreateCredentialFromAttributes(resultPtr);
}
throw new InteropException($"Unknown keychain search result type CFTypeID: {typeId}.", -1);
case ErrorSecItemNotFound:
return null;
default:
ThrowIfError(searchResult);
return null;
}
}
finally
{
if (query != IntPtr.Zero) CFRelease(query);
if (servicePtr != IntPtr.Zero) CFRelease(servicePtr);
if (accountPtr != IntPtr.Zero) CFRelease(accountPtr);
if (resultPtr != IntPtr.Zero) CFRelease(resultPtr);
}
}
public void AddOrUpdate(string service, string account, string secret)
{
EnsureArgument.NotNullOrWhiteSpace(service, nameof(service));
byte[] secretBytes = Encoding.UTF8.GetBytes(secret);
IntPtr passwordData = IntPtr.Zero;
IntPtr itemRef = IntPtr.Zero;
string serviceName = CreateServiceName(service);
uint serviceNameLength = (uint) serviceName.Length;
uint accountLength = (uint) (account?.Length ?? 0);
try
{
// Check if an entry already exists in the keychain
int findResult = SecKeychainFindGenericPassword(
IntPtr.Zero, serviceNameLength, serviceName, accountLength, account,
out uint passwordDataLength, out passwordData, out itemRef);
switch (findResult)
{
// Update existing entry only if the password/secret is different
case OK when !InteropUtils.AreEqual(secretBytes, passwordData, passwordDataLength):
ThrowIfError(
SecKeychainItemModifyAttributesAndData(itemRef, IntPtr.Zero, (uint) secretBytes.Length, secretBytes),
"Could not update existing item"
);
break;
// Create new entry
case ErrorSecItemNotFound:
ThrowIfError(
SecKeychainAddGenericPassword(IntPtr.Zero, serviceNameLength, serviceName, accountLength,
account, (uint) secretBytes.Length, secretBytes, out itemRef),
"Could not create new item"
);
break;
default:
ThrowIfError(findResult);
break;
}
}
finally
{
if (passwordData != IntPtr.Zero)
{
SecKeychainItemFreeContent(IntPtr.Zero, passwordData);
}
if (itemRef != IntPtr.Zero)
{
CFRelease(itemRef);
}
}
}
public bool Remove(string service, string account)
{
IntPtr query = IntPtr.Zero;
IntPtr itemRefPtr = IntPtr.Zero;
IntPtr servicePtr = IntPtr.Zero;
IntPtr accountPtr = IntPtr.Zero;
try
{
query = CFDictionaryCreateMutable(
IntPtr.Zero,
0,
IntPtr.Zero, IntPtr.Zero);
CFDictionaryAddValue(query, kSecClass, kSecClassGenericPassword);
CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitOne);
CFDictionaryAddValue(query, kSecReturnRef, kCFBooleanTrue);
if (!string.IsNullOrWhiteSpace(service))
{
string fullService = CreateServiceName(service);
servicePtr = CreateCFStringUtf8(fullService);
CFDictionaryAddValue(query, kSecAttrService, servicePtr);
}
if (!string.IsNullOrWhiteSpace(account))
{
accountPtr = CreateCFStringUtf8(account);
CFDictionaryAddValue(query, kSecAttrAccount, accountPtr);
}
// Search for the credential to delete and get the SecKeychainItem ref.
int searchResult = SecItemCopyMatching(query, out itemRefPtr);
switch (searchResult)
{
case OK:
// Delete the item
ThrowIfError(
SecKeychainItemDelete(itemRefPtr)
);
return true;
case ErrorSecItemNotFound:
return false;
default:
ThrowIfError(searchResult);
return false;
}
}
finally
{
if (query != IntPtr.Zero) CFRelease(query);
if (itemRefPtr != IntPtr.Zero) CFRelease(itemRefPtr);
if (servicePtr != IntPtr.Zero) CFRelease(servicePtr);
if (accountPtr != IntPtr.Zero) CFRelease(accountPtr);
}
}
#endregion
private static IntPtr CreateCFStringUtf8(string str)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
return CFStringCreateWithBytes(IntPtr.Zero,
bytes, bytes.Length, CFStringEncoding.kCFStringEncodingUTF8, false);
}
private static ICredential CreateCredentialFromAttributes(IntPtr attributes)
{
string service = GetStringAttribute(attributes, kSecAttrService);
string account = GetStringAttribute(attributes, kSecAttrAccount);
string password = GetStringAttribute(attributes, kSecValueData);
string label = GetStringAttribute(attributes, kSecAttrLabel);
return new MacOSKeychainCredential(service, account, password, label);
}
private static string GetStringAttribute(IntPtr dict, IntPtr key)
{
if (dict == IntPtr.Zero)
{
return null;
}
IntPtr buffer = IntPtr.Zero;
try
{
if (CFDictionaryGetValueIfPresent(dict, key, out IntPtr value) && value != IntPtr.Zero)
{
if (CFGetTypeID(value) == CFStringGetTypeID())
{
int stringLength = (int)CFStringGetLength(value);
int bufferSize = stringLength + 1;
buffer = Marshal.AllocHGlobal(bufferSize);
if (CFStringGetCString(value, buffer, bufferSize, CFStringEncoding.kCFStringEncodingUTF8))
{
return Marshal.PtrToStringAuto(buffer, stringLength);
}
}
if (CFGetTypeID(value) == CFDataGetTypeID())
{
int length = CFDataGetLength(value);
IntPtr ptr = CFDataGetBytePtr(value);
return Marshal.PtrToStringAuto(ptr, length);
}
}
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(buffer);
}
}
return null;
}
private string CreateServiceName(string service)
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(_namespace))
{
sb.AppendFormat("{0}:", _namespace);
}
sb.Append(service);
return sb.ToString();
}
}
}