/
CK2SSHCredential.m
437 lines (330 loc) · 16.5 KB
/
CK2SSHCredential.m
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
//
// CK2SSHCredential.m
// Sandvox
//
// Created by Mike Abdullah on 02/09/2011.
// Copyright © 2011 Karelia Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import "CK2SSHCredential.h"
@interface CK2SSHCredential : NSURLCredential
{
@private
SecKeychainItemRef _keychainItem;
CFStringRef _password;
BOOL _isPublicKey;
NSURL *_publicKey;
NSURL *_privateKey;
}
@end
@implementation CK2SSHCredential
- (id)initWithUser:(NSString *)user keychainItem:(SecKeychainItemRef)item;
{
NSParameterAssert(item);
if (self = [self initWithUser:user password:nil persistence:NSURLCredentialPersistencePermanent])
{
_keychainItem = item;
CFRetain(_keychainItem);
}
return self;
}
- (id)initWithUser:(NSString *)user;
{
if (self = [self initWithUser:user password:nil persistence:NSURLCredentialPersistenceNone])
{
_isPublicKey = YES;
}
return self;
}
- (void)dealloc
{
if (_keychainItem) CFRelease(_keychainItem);
if (_password) CFRelease(_password);
[_publicKey release];
[_privateKey release];
[super dealloc];
}
void freeKeychainContent(void *ptr, void *info)
{
SecKeychainItemFreeContent(NULL, ptr);
}
- (NSString *)password
{
if (!_keychainItem) return [super password];
@synchronized((id)_keychainItem)
{
if (!_password)
{
void *passwordData;
UInt32 passwordLength;
OSStatus status = SecKeychainItemCopyContent(_keychainItem, NULL, NULL, &passwordLength, &passwordData);
if (status != errSecSuccess)
{
// HACK: let it be known there was a problem
// make sure runs on main thread
NSString *opFormat = NSLocalizedStringFromTableInBundle(@"The password for user %@ couldn't be retrieved.",
nil,
[NSBundle bundleForClass:[CK2SSHCredential class]],
"error description");
NSError *error = [NSURLCredentialStorage ck2_keychainErrorWithCode:status
localizedOperationDescription:[NSString stringWithFormat:opFormat, [self user]]];
[[NSClassFromString(@"NSApplication") sharedApplication] performSelectorOnMainThread:@selector(presentError:) withObject:error waitUntilDone:NO];
return nil;
}
// Password data must be freed using special keychain APIs. Do so with a specially crafted CFString
CFAllocatorContext context = { 0, NULL, NULL, NULL, NULL, NULL, NULL, freeKeychainContent, NULL };
CFAllocatorRef allocator = CFAllocatorCreate(NULL, &context);
_password = CFStringCreateWithBytesNoCopy(NULL, passwordData, passwordLength, kCFStringEncodingUTF8, false, allocator);
CFRelease(allocator);
}
}
return (NSString *)_password;
}
- (BOOL)hasPassword;
{
// Super's implementation says there's no password if initted with nil, so we have correct it
return (_keychainItem != nil || [super hasPassword]);
}
- (BOOL)ck2_isPublicKeyCredential; { return _isPublicKey; }
- (NSURL *)ck2_publicKeyURL; { return _publicKey; }
- (NSURL *)ck2_privateKeyURL; { return _privateKey; }
- (void)setPublicKeyURL:(NSURL *)publicKey privateKeyURL:(NSURL *)privateKey;
{
NSParameterAssert(privateKey);
_publicKey = [publicKey copy];
_privateKey = [privateKey copy];
_isPublicKey = YES;
}
- (NSURLCredential *)ck2_credentialWithPassword:(NSString *)password persistence:(NSURLCredentialPersistence)persistence;
{
id result = [super ck2_credentialWithPassword:password persistence:persistence];
if ([self ck2_isPublicKeyCredential]) [result setPublicKeyURL:[self ck2_publicKeyURL] privateKeyURL:[self ck2_privateKeyURL]];
return result;
}
@end
#pragma mark -
@interface CK2GenericPasswordCredential : NSURLCredential
{
@private
NSString *_service;
}
- (id)initWithUser:(NSString *)user service:(NSString *)service;
@end
@implementation CK2GenericPasswordCredential
- (id)initWithUser:(NSString *)user service:(NSString *)service;
{
if (self = [self initWithUser:user password:nil persistence:NSURLCredentialPersistencePermanent])
{
_service = [service copy];
}
return self;
}
- (void)dealloc
{
[_service release];
[super dealloc];
}
- (NSString *)password
{
const char *serviceName = [_service UTF8String];
const char *username = [[self user] UTF8String];
UInt32 passwordLength = 0;
void *password = nil;
OSStatus status = SecKeychainFindGenericPassword(NULL, (UInt32) strlen(serviceName), serviceName, (UInt32) strlen(username), username, &passwordLength, &password, NULL);
if (status != noErr) return nil;
NSString *result = [[NSString alloc] initWithBytes:password length:passwordLength encoding:NSUTF8StringEncoding];
SecKeychainItemFreeContent(NULL, password);
return [result autorelease];
}
- (BOOL)hasPassword { return YES; }
@end
#pragma mark -
@implementation NSURLCredential (CK2SSHCredential)
+ (NSURLCredential *)ck2_SSHAgentCredentialWithUser:(NSString *)user;
{
return [[[CK2SSHCredential alloc] initWithUser:user] autorelease];
}
+ (NSURLCredential *)ck2_credentialWithUser:(NSString *)user
publicKeyURL:(NSURL *)publicKey
privateKeyURL:(NSURL *)privateKey;
{
NSParameterAssert(privateKey);
CK2SSHCredential *result = [[CK2SSHCredential alloc] initWithUser:user
password:nil
persistence:NSURLCredentialPersistenceNone];
[result setPublicKeyURL:publicKey privateKeyURL:privateKey];
return [result autorelease];
}
+ (NSURLCredential *)ck2_credentialWithUser:(NSString *)user service:(NSString *)service;
{
const char *serviceName = [service UTF8String];
const char *username = [user UTF8String];
OSStatus status = SecKeychainFindGenericPassword(NULL, (UInt32) strlen(serviceName), serviceName, (UInt32) strlen(username), username, NULL, NULL, NULL);
if (status != noErr) return nil;
return [[[CK2GenericPasswordCredential alloc] initWithUser:user service:service] autorelease];
}
+ (NSURLCredential *)ck2_credentialWithUser:(NSString *)user keychainItem:(SecKeychainItemRef)item;
{
return [[[CK2SSHCredential alloc] initWithUser:user keychainItem:item] autorelease];
}
- (BOOL)ck2_isPublicKeyCredential; { return NO; }
- (NSURL *)ck2_publicKeyURL; { return nil; }
- (NSURL *)ck2_privateKeyURL; { return nil; }
- (NSURLCredential *)ck2_credentialWithPassword:(NSString *)password persistence:(NSURLCredentialPersistence)persistence;
{
return [[[[self class] alloc] initWithUser:[self user]
password:password
persistence:persistence]
autorelease];
}
@end
#pragma mark -
@implementation NSURLCredentialStorage (CK2SSHCredential)
+ (NSError *)ck2_keychainErrorWithCode:(OSStatus)code localizedOperationDescription:(NSString *)opDescription;
{
CFStringRef message = SecCopyErrorMessageString(code, NULL);
NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithCapacity:2];
if (message) [userInfo setObject:(NSString *)message forKey:NSLocalizedFailureReasonErrorKey];
if (opDescription) [userInfo setObject:[opDescription stringByAppendingFormat:@" %@", message] forKey:NSLocalizedDescriptionKey];
// com.apple.Keychain was my logical guess at domain, and searching the internet reveals Apple are using it in a few places
NSError *result = [NSError errorWithDomain:@"com.apple.Keychain" code:code userInfo:userInfo];
[userInfo release];
if (message) CFRelease(message);
return result;
}
- (BOOL)ck2_setCredential:(NSURLCredential *)credential forSSHHost:(NSString *)host port:(NSInteger)port error:(NSError **)error;
{
// Can't do anything with non-persistent credentials
if ([credential persistence] != NSURLCredentialPersistencePermanent) return YES;
// Retrieve the keychain item
NSString *user = [credential user];
SecKeychainItemRef keychainItem;
OSStatus status = SecKeychainFindInternetPassword(NULL,
(UInt32) [host lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [host UTF8String],
0, NULL,
(UInt32) [user lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [user UTF8String],
0, NULL,
port,
kSecProtocolTypeSSH,
kSecAuthenticationTypeDefault,
NULL, NULL,
&keychainItem);
// Store the password
NSString *password = [credential password];
NSAssert(password, @"%@ was handed password-less credential", NSStringFromSelector(_cmd));
NSString *opDescription;
if (status == errSecSuccess)
{
status = SecKeychainItemModifyAttributesAndData(keychainItem,
NULL, // no change to attributes
(UInt32) [password lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [password UTF8String]);
opDescription = NSLocalizedStringFromTableInBundle(@"The password stored in your keychain couldn't be updated.", nil, [NSBundle bundleForClass:[CK2SSHCredential class]], "error description");
CFRelease(keychainItem); // know for sure keychainItem isn't nil as this line hasn't been reported to crash so far!
}
else
{
status = SecKeychainAddInternetPassword(NULL,
(UInt32) [host lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [host UTF8String],
0, NULL,
(UInt32) [user lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [user UTF8String],
0, NULL,
port,
kSecProtocolTypeSSH,
kSecAuthenticationTypeDefault,
(UInt32) [password lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [password UTF8String],
NULL);
opDescription = NSLocalizedStringFromTableInBundle(@"The password couldn't be added to your keychain.", nil, [NSBundle bundleForClass:[CK2SSHCredential class]], "error description");
}
if (status == errSecSuccess) return YES;
// Note the host etc. involved
opDescription = [opDescription stringByAppendingFormat:
NSLocalizedStringFromTableInBundle(@" (%@@%@:%i).",
nil,
[NSBundle bundleForClass:[CK2SSHCredential class]],
"error description"),
[credential user],
host,
port];
// Note a crazily empty password
if (![password length]) opDescription = [opDescription stringByAppendingFormat:
NSLocalizedStringFromTableInBundle(@" (%@ password.)",
nil,
[NSBundle bundleForClass:[CK2SSHCredential class]],
"error description"),
password /* don't worry, it's either nil or empty! */];
if (error) *error = [[self class] ck2_keychainErrorWithCode:status localizedOperationDescription:opDescription];
return NO;
}
- (SecKeychainItemRef)copyKeychainItemForPrivateKeyPath:(NSString *)privateKey;
{
NSString *service = @"SSH";
SecKeychainItemRef result;
OSStatus status = SecKeychainFindGenericPassword(NULL,
(UInt32) [service lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [service UTF8String],
(UInt32) [privateKey lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [privateKey UTF8String],
NULL, NULL,
&result);
return (status == errSecSuccess ? result : NULL);
}
- (NSURLCredential *)ck2_credentialForPrivateKeyAtURL:(NSURL *)privateKey user:(NSString *)user;
{
// Try fetching passphrase from the keychain
// The service & account name is entirely empirical based on what's in my keychain from SSH Agent
NSString *privateKeyPath = [privateKey path];
SecKeychainItemRef item = [self copyKeychainItemForPrivateKeyPath:privateKeyPath];
if (!item) return nil;
CK2SSHCredential *result = [[CK2SSHCredential alloc] initWithUser:user keychainItem:item];
[result setPublicKeyURL:nil privateKeyURL:privateKey];
CFRelease(item);
return [result autorelease];
}
- (BOOL)ck2_setPrivateKeyCredential:(NSURLCredential *)credential;
{
NSURLCredentialPersistence persistence = [credential persistence];
if (persistence == NSURLCredentialPersistenceNone) return YES;
if ([credential persistence] != NSURLCredentialPersistencePermanent) return YES;
NSString *privateKey = [[credential ck2_privateKeyURL] path];
NSString *password = [credential password];
if (privateKey && password)
{
// Time to store the passphrase
NSString *service = @"SSH";
SecKeychainItemRef item = [self copyKeychainItemForPrivateKeyPath:privateKey];
OSStatus status;
if (item)
{
status = SecKeychainItemModifyAttributesAndData(item,
NULL, // no change to attributes
(UInt32) [password lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [password UTF8String]);
CFRelease(item);
}
else
{
status = SecKeychainAddGenericPassword(NULL,
(UInt32) [service lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [service UTF8String],
(UInt32) [privateKey lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [privateKey UTF8String],
(UInt32) [password lengthOfBytesUsingEncoding:NSUTF8StringEncoding], [password UTF8String],
NULL);
}
return status == errSecSuccess;
}
return NO;
}
@end