-
Notifications
You must be signed in to change notification settings - Fork 284
/
Copy pathGSHTTPAuthentication.m
645 lines (590 loc) · 16.5 KB
/
GSHTTPAuthentication.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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/* Implementation for GSHTTPAuthentication for GNUstep
Copyright (C) 2006 Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
Date: 2006
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
*/
#import "common.h"
#import "GSURLPrivate.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSEnumerator.h"
#import "Foundation/NSScanner.h"
#import "Foundation/NSSet.h"
#import "Foundation/NSValue.h"
#import "GNUstepBase/GSMime.h"
#import "GNUstepBase/NSData+GNUstepBase.h"
static NSMutableDictionary *domainMap = nil;
static NSMutableSet *spaces = nil;
static NSMutableDictionary *store = nil;
static NSLock *storeLock = nil;
static GSMimeParser *mimeParser = nil;
@interface NSData(GSHTTPDigest)
- (NSString*) digestHex;
@end
@implementation NSData(GSHTTPDigest)
- (NSString*) digestHex
{
static const char *hexChars = "0123456789abcdef";
unsigned slen = [self length];
unsigned dlen = slen * 2;
const unsigned char *src = (const unsigned char *)[self bytes];
char *dst;
unsigned spos = 0;
unsigned dpos = 0;
NSData *data;
NSString *string;
dst = (char*)NSZoneMalloc(NSDefaultMallocZone(), dlen);
while (spos < slen)
{
unsigned char c = src[spos++];
dst[dpos++] = hexChars[(c >> 4) & 0x0f];
dst[dpos++] = hexChars[c & 0x0f];
}
data = [NSData allocWithZone: NSDefaultMallocZone()];
data = [data initWithBytesNoCopy: dst length: dlen];
string = [[NSString alloc] initWithData: data
encoding: NSASCIIStringEncoding];
RELEASE(data);
return AUTORELEASE(string);
}
@end
@implementation GSHTTPAuthentication
+ (void) initialize
{
if (store == nil)
{
mimeParser = [GSMimeParser new];
[[NSObject leakAt: &mimeParser] release];
spaces = [NSMutableSet new];
[[NSObject leakAt: &spaces] release];
domainMap = [NSMutableDictionary new];
[[NSObject leakAt: &domainMap] release];
store = [NSMutableDictionary new];
[[NSObject leakAt: &store] release];
storeLock = [NSLock new];
[[NSObject leakAt: &storeLock] release];
}
}
+ (GSHTTPAuthentication *) authenticationWithCredential:
(NSURLCredential*)credential
inProtectionSpace: (NSURLProtectionSpace*)space
{
NSMutableDictionary *cDict = nil;
NSURLProtectionSpace *known = nil;
GSHTTPAuthentication *authentication = nil;
NSAssert([credential isKindOfClass: [NSURLCredential class]] == YES,
NSInvalidArgumentException);
NSAssert([space isKindOfClass: [NSURLProtectionSpace class]] == YES,
NSInvalidArgumentException);
[storeLock lock];
NS_DURING
{
/*
* Keep track of known protection spaces so we don't make lots of
* duplicate copies, but share one copy between authentication objects.
*/
known = [spaces member: space];
if (known == nil)
{
[spaces addObject: space];
known = [spaces member: space];
}
space = known;
cDict = [store objectForKey: space];
if (cDict == nil)
{
cDict = [NSMutableDictionary new];
[store setObject: cDict forKey: space];
RELEASE(cDict);
}
authentication = [cDict objectForKey: credential];
if (authentication == nil)
{
authentication = [[GSHTTPAuthentication alloc]
initWithCredential: credential
inProtectionSpace: space];
if (authentication != nil)
{
[cDict setObject: authentication
forKey: [authentication credential]];
RELEASE(authentication);
}
}
IF_NO_ARC([[authentication retain] autorelease];)
}
NS_HANDLER
{
[storeLock unlock];
[localException raise];
}
NS_ENDHANDLER
[storeLock unlock];
return authentication;
}
+ (NSURLProtectionSpace*) protectionSpaceForAuthentication: (NSString*)auth
requestURL: (NSURL*)URL;
{
if ([auth isKindOfClass: [NSString class]] == YES)
{
NSString *method = nil;
NSURLProtectionSpace *space;
NSScanner *sc;
NSString *domain = nil;
NSString *realm = nil;
NSString *key;
NSString *val;
space = [self protectionSpaceForURL: URL];
sc = [NSScanner scannerWithString: auth];
key = [mimeParser scanName: sc];
if ([key caseInsensitiveCompare: @"Basic"] == NSOrderedSame)
{
method = NSURLAuthenticationMethodHTTPBasic;
domain = [URL path];
}
else if ([key caseInsensitiveCompare: @"Digest"] == NSOrderedSame)
{
method = NSURLAuthenticationMethodHTTPDigest;
}
else if ([key caseInsensitiveCompare: @"NTLM"] == NSOrderedSame)
{
method = NSURLAuthenticationMethodNTLM;
}
else if ([key caseInsensitiveCompare: @"Negotiate"] == NSOrderedSame)
{
method = NSURLAuthenticationMethodNegotiate;
}
else
{
return nil; // Unknown authentication
}
while ((key = [mimeParser scanName: sc]) != nil)
{
if ([sc scanString: @"=" intoString: 0] == NO)
{
return nil; // Bad name=value specification
}
if ((val = [mimeParser scanToken: sc]) == nil)
{
return nil; // Bad name=value specification
}
if ([key caseInsensitiveCompare: @"domain"] == NSOrderedSame)
{
domain = val;
}
else if ([key caseInsensitiveCompare: @"realm"] == NSOrderedSame)
{
realm = val;
}
if ([sc scanString: @"," intoString: 0] == NO)
{
break; // No more in list.
}
}
if (realm == nil)
{
return nil; // No realm to authenticate in
}
/*
* If the realm and authentication method match the space we
* found for the URL, assume that it is unchanged.
*/
if ([[space realm] isEqualToString: realm]
&& [space authenticationMethod] == method)
{
return space;
}
space = [[NSURLProtectionSpace alloc] initWithHost: [URL host]
port: [[URL port] intValue]
protocol: [URL scheme]
realm: realm
authenticationMethod: method];
[self setProtectionSpace: space
forDomains: [domain componentsSeparatedByString: @" "]
baseURL: URL];
return AUTORELEASE(space);
}
return nil;
}
+ (NSURLProtectionSpace *) protectionSpaceForURL: (NSURL*)URL
{
NSURLProtectionSpace *space = nil;
NSString *scheme;
NSNumber *port;
NSString *server;
scheme = [URL scheme];
port = [URL port];
if ([port intValue] == 80 && [scheme isEqualToString: @"http"])
{
port = nil;
}
else if ([port intValue] == 443 && [scheme isEqualToString: @"https"])
{
port = nil;
}
if ([port intValue] == 0)
{
server = [NSString stringWithFormat: @"%@://%@",
scheme, [URL host]];
}
else
{
server = [NSString stringWithFormat: @"%@://%@:%@",
scheme, [URL host], port];
}
[storeLock lock];
NS_DURING
{
NSString *found = nil;
NSDictionary *sDict;
NSArray *keys;
unsigned count;
NSString *path;
sDict = [domainMap objectForKey: server];
keys = [sDict allKeys];
count = [keys count];
path = [URL path];
while (count-- > 0)
{
NSString *key = [keys objectAtIndex: count];
unsigned kl = [key length];
if (found == nil || kl > [found length])
{
if (kl == 0 || [path hasPrefix: key] == YES)
{
found = key;
}
}
}
if (found != nil)
{
space = AUTORELEASE(RETAIN([sDict objectForKey: found]));
}
}
NS_HANDLER
{
[storeLock unlock];
[localException raise];
}
NS_ENDHANDLER
[storeLock unlock];
return space;
}
+ (void) setProtectionSpace: (NSURLProtectionSpace *)space
forDomains: (NSArray*)domains
baseURL: (NSURL*)base
{
/*
* If there are no URIs specified, everything on the
* host of the base URL is in the protection space
*/
if ([domains count] == 0)
{
domains = [NSArray arrayWithObject: @"/"];
}
[storeLock lock];
NS_DURING
{
NSEnumerator *e = [domains objectEnumerator];
NSString *domain;
while ((domain = [e nextObject]) != nil)
{
NSURL *u;
NSString *path;
NSNumber *port;
NSString *scheme;
NSString *server;
NSMutableDictionary *sDict;
u = [NSURL URLWithString: domain];
scheme = [u scheme];
if (scheme == nil)
{
u = [NSURL URLWithString: domain relativeToURL: base];
scheme = [u scheme];
}
port = [u port];
if ([port intValue] == 80 && [scheme isEqualToString: @"http"])
{
port = nil;
}
else if ([port intValue] == 443 && [scheme isEqualToString: @"https"])
{
port = nil;
}
path = [u path];
if (path == nil)
{
path = @"";
}
if ([port intValue] == 0)
{
server = [NSString stringWithFormat: @"%@://%@",
scheme, [u host]];
}
else
{
server = [NSString stringWithFormat: @"%@://%@:%@",
scheme, [u host], port];
}
sDict = [domainMap objectForKey: server];
if (sDict == nil)
{
sDict = [NSMutableDictionary new];
[domainMap setObject: sDict forKey: server];
RELEASE(sDict);
}
[sDict setObject: space forKey: path];
}
}
NS_HANDLER
{
[storeLock unlock];
[localException raise];
}
NS_ENDHANDLER
[storeLock unlock];
}
- (NSString*) authorizationForAuthentication: (NSString*)authentication
method: (NSString*)method
path: (NSString*)path
{
NSMutableString *authorisation;
if ([self->_space authenticationMethod]
== NSURLAuthenticationMethodHTTPDigest)
{
NSString *realm = nil;
NSString *qop = nil;
NSString *nonce = nil;
NSString *opaque = nil;
NSString *stale = @"FALSE";
NSString *algorithm = @"MD5";
NSString *cnonce;
NSString *HA1;
NSString *HA2;
NSString *response;
int nc;
if (authentication != nil)
{
NSScanner *sc;
NSString *key;
NSString *val;
sc = [NSScanner scannerWithString: authentication];
if ([sc scanString: @"Digest" intoString: 0] == NO)
{
NSDebugMLog(@"Bad format HTTP digest in '%@'", authentication);
return nil; // Not a digest authentication
}
while ((key = [mimeParser scanName: sc]) != nil)
{
if ([sc scanString: @"=" intoString: 0] == NO)
{
NSDebugMLog(@"Missing '=' in HTTP digest '%@'",
authentication);
return nil; // Bad name=value specification
}
if ((val = [mimeParser scanToken: sc]) == nil)
{
NSDebugMLog(@"Missing value in HTTP digest '%@'",
authentication);
return nil; // Bad name=value specification
}
if ([key caseInsensitiveCompare: @"realm"] == NSOrderedSame)
{
realm = val;
}
if ([key caseInsensitiveCompare: @"qop"] == NSOrderedSame)
{
qop = val;
}
if ([key caseInsensitiveCompare: @"nonce"] == NSOrderedSame)
{
nonce = val;
}
if ([key caseInsensitiveCompare: @"opaque"] == NSOrderedSame)
{
opaque = val;
}
if ([key caseInsensitiveCompare: @"stale"] == NSOrderedSame)
{
stale = val;
}
if ([key caseInsensitiveCompare: @"algorithm"] == NSOrderedSame)
{
algorithm = val;
}
if ([sc scanString: @"," intoString: 0] == NO)
{
break; // No more in list.
}
}
if (realm == nil)
{
NSDebugMLog(@"Missing HTTP digest realm in '%@'", authentication);
return nil;
}
if ([realm isEqualToString: [self->_space realm]] == NO)
{
NSDebugMLog(@"Bad HTTP digest realm in '%@'", authentication);
return nil;
}
if (nonce == nil)
{
NSDebugMLog(@"Missing HTTP digest nonce in '%@'", authentication);
return nil;
}
if ([algorithm isEqualToString: @"MD5"] == NO)
{
NSDebugMLog(@"Unsupported HTTP digest algorithm in '%@'",
authentication);
return nil;
}
if (![[qop componentsSeparatedByString: @","]
containsObject: @"auth"])
{
NSDebugMLog(@"Unsupported/missing HTTP digest qop in '%@'",
authentication);
return nil;
}
[self->_lock lock];
if ([stale boolValue] == YES
|| [nonce isEqualToString: _nonce] == NO)
{
_nc = 1;
}
ASSIGN(_nonce, nonce);
ASSIGN(_qop, qop);
ASSIGN(_opaque, opaque);
}
else
{
[self->_lock lock];
nonce = _nonce;
opaque = _opaque;
realm = [self->_space realm];
}
nc = _nc++;
qop = @"auth";
cnonce = [[[[[NSProcessInfo processInfo] globallyUniqueString]
dataUsingEncoding: NSUTF8StringEncoding] md5Digest] digestHex];
HA1 = [[[[NSString stringWithFormat: @"%@:%@:%@",
[self->_credential user], realm, [self->_credential password]]
dataUsingEncoding: NSUTF8StringEncoding] md5Digest] digestHex];
HA2 = [[[[NSString stringWithFormat: @"%@:%@", method, path]
dataUsingEncoding: NSUTF8StringEncoding] md5Digest] digestHex];
response = [[[[NSString stringWithFormat: @"%@:%@:%08x:%@:%@:%@",
HA1, nonce, nc, cnonce, qop, HA2]
dataUsingEncoding: NSUTF8StringEncoding] md5Digest] digestHex];
authorisation = [NSMutableString stringWithCapacity: 512];
[authorisation appendFormat: @"Digest realm=\"%@\"", realm];
[authorisation appendFormat: @",username=\"%@\"",
[self->_credential user]];
[authorisation appendFormat: @",nonce=\"%@\"", nonce];
[authorisation appendFormat: @",uri=\"%@\"", path];
[authorisation appendFormat: @",response=\"%@\"", response];
[authorisation appendFormat: @",qop=\"%@\"", qop];
[authorisation appendFormat: @",nc=%08x", nc];
[authorisation appendFormat: @",cnonce=\"%@\"", cnonce];
if (opaque != nil)
{
[authorisation appendFormat: @",opaque=\"%@\"", opaque];
}
[self->_lock unlock];
}
else if ([self->_space authenticationMethod]
== NSURLAuthenticationMethodHTMLForm)
{
// This should not generate any authentication header.
return nil;
}
else if ([self->_space authenticationMethod]
== NSURLAuthenticationMethodNTLM)
{
// FIXME: this needs to be implemented
return nil;
}
else if ([self->_space authenticationMethod]
== NSURLAuthenticationMethodNegotiate)
{
// FIXME: this needs to be implemented
return nil;
}
else if ([self->_space authenticationMethod]
== NSURLAuthenticationMethodDefault
|| [self->_space authenticationMethod]
== NSURLAuthenticationMethodHTTPBasic)
{
NSString *toEncode;
if (authentication != nil)
{
NSScanner *sc;
sc = [NSScanner scannerWithString: authentication];
if ([sc scanString: @"Basic" intoString: 0] == NO)
{
NSDebugMLog(@"Bad format HTTP basic in '%@'", authentication);
return nil; // Not a basic authentication
}
}
authorisation = [NSMutableString stringWithCapacity: 64];
if ([[self->_credential password] length] > 0)
{
toEncode = [NSString stringWithFormat: @"%@:%@",
[self->_credential user], [self->_credential password]];
}
else
{
toEncode = [NSString stringWithFormat: @"%@",
[self->_credential user]];
}
[authorisation appendFormat: @"Basic %@",
[GSMimeDocument encodeBase64String: toEncode]];
}
else
{
// FIXME: Currently, ClientCertificate and ServerTrust authentication
// methods are NOT implemented and will end up here. They should, in fact,
// be handled in the SSL connection layer (in GSHTTPURLHandle) rather than
// in this method.
return nil;
}
return authorisation;
}
- (NSURLCredential *) credential
{
return self->_credential;
}
- (void) dealloc
{
RELEASE(_credential);
RELEASE(_space);
RELEASE(_nonce);
RELEASE(_opaque);
RELEASE(_qop);
RELEASE(_lock);
[super dealloc];
}
- (id) initWithCredential: (NSURLCredential*)credential
inProtectionSpace: (NSURLProtectionSpace*)space
{
if ((self = [super init]) != nil)
{
self->_lock = [NSLock new];
ASSIGN(self->_space, space);
ASSIGN(self->_credential, credential);
}
return self;
}
- (NSURLProtectionSpace *) space
{
return self->_space;
}
@end