-
Notifications
You must be signed in to change notification settings - Fork 284
/
Copy pathGSTLS.m
2588 lines (2301 loc) · 69 KB
/
GSTLS.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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Implementation for GSTLS classes for GNUStep
Copyright (C) 2012 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
Date: 2101
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 "Foundation/NSArray.h"
#import "Foundation/NSBundle.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSEnumerator.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSHost.h"
#import "Foundation/NSException.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSProcessInfo.h"
#import "Foundation/NSStream.h"
#import "Foundation/NSTask.h"
#import "Foundation/NSThread.h"
#import "Foundation/NSUserDefaults.h"
#import "Foundation/NSUUID.h"
#import "GNUstepBase/GSTLS.h"
#import "GSPrivate.h"
@interface NSString(gnutlsFileSystemRepresentation)
- (const char*) gnutlsFileSystemRepresentation;
@end
@implementation NSString(gnutlsFileSystemRepresentation)
- (const char*) gnutlsFileSystemRepresentation
{
#if defined(_WIN32)
const unichar *buf = (const unichar*)[self fileSystemRepresentation];
int len = 0;
NSString *str;
const char *result;
while (buf[len] > 0)
{
len++;
}
str = [[NSString alloc] initWithBytes: buf
length: len * 2
encoding: NSUnicodeStringEncoding];
result = [str UTF8String];
RELEASE(str);
return result;
#else
return [self fileSystemRepresentation];
#endif
}
@end
#if defined(HAVE_GNUTLS)
static NSString *
standardizedPath(NSString *path)
{
if (0 == [path length])
{
return nil; // Not a path
}
if (NO == [path isAbsolutePath])
{
path = [[[NSFileManager defaultManager] currentDirectoryPath]
stringByAppendingPathComponent: path];
}
return [path stringByStandardizingPath];
}
#if GNUTLS_VERSION_NUMBER <= 0x020b00
/* Set up locking callbacks for gcrypt so that it will be thread-safe.
*/
static int gcry_mutex_init(void **priv)
{
NSLock *lock = [NSLock new];
*priv = (void*)lock;
return 0;
}
static int gcry_mutex_destroy(void **lock)
{
[((NSLock*)*lock) release];
return 0;
}
static int gcry_mutex_lock(void **lock)
{
[((NSLock*)*lock) lock];
return 0;
}
static int gcry_mutex_unlock(void **lock)
{
[((NSLock*)*lock) unlock];
return 0;
}
static struct gcry_thread_cbs gcry_threads_other = {
GCRY_THREAD_OPTION_DEFAULT,
NULL,
gcry_mutex_init,
gcry_mutex_destroy,
gcry_mutex_lock,
gcry_mutex_unlock
};
#endif
static void
GSTLSLog(int level, const char *msg)
{
NSLog(@"%s", msg);
}
/* The caFile variable holds the location of the file containing the default
* certificate authorities to be used by our system.
* The hard-coded value is a file in the GSTLS folder of the base library
* resource bundle, but this can be overridden by the GS_TLS_CA_FILE
* environment variable, which in turn will be overridden by the GSTLSCAFile
* user default string.
*/
static NSString *caFile = nil; // GSTLS/ca-certificates.crt
/* The caRevoke variable holds the location of the file containing the default
* certificate revocation list to be used by our system.
* The hard-coded value is a file in the GSTLS folder of the base library
* resource bundle, but this can be overridden by the GS_TLS_REVOKE
* environment variable, which in turn will be overridden by the GSTLSRevokeFile
* user default string.
*/
static NSString *revokeFile = nil; // GSTLS/revoke.crl
/* The verifyClient variable tells us if connections from a remote server
* should (by default) provide a client certificate which we verify against
* our trusted authorities.
* The hard-coded value can be overridden by the GS_TLS_VERIFY_C environment
* variable, which in turn will be overridden by the GSTLSVerifyClient user
* default string.
* A GSTLSVerify option set for a specific session overrides this default
*/
static BOOL verifyClient = NO;
/* The verifyServer variable tells us if outgoing connections (as a client)
* to a remote server should (by default) verify that server's certificate
* against our trusted authorities.
* The hard-coded value can be overridden by the GS_TLS_VERIFY_S environment
* variable, which in turn will be overridden by the GSTLSVerifyServer user
* default string.
* A GSTLSVerify option set for a specific session overrides this default
*/
static BOOL verifyServer = NO;
/* The globalDebug variable turns on gnutls debug. The hard-code value is
* overridden by GS_TLS_DEBUG, which in turn can be overridden by the
* GSTLSDebug user default. This is an integer debug level with higher
* values producing more debug output. Usually levels above 1 are too
* verbose and not useful unless you have the gnutls source code to hand.
* NB. The GSTLSDebug session option is a boolean to turn on extra debug for
* a particular session to be produced on verification failure.
*/
static int globalDebug = 0;
/* Defines the default priority list.
*/
static NSString *priority = nil;
static gnutls_anon_client_credentials_t anoncred;
/* This class is used to ensure that the GNUTLS system is initialised
* and thread-safe.
*/
@implementation GSTLSObject
static NSLock *certificateListLock = nil;
static NSMutableDictionary *certificateListCache = nil;
static NSLock *credentialsLock = nil;
static NSMutableDictionary *credentialsCache = nil;
static NSLock *fileLock = nil;
static NSMutableDictionary *fileMap = nil;
static NSLock *paramsLock = nil;
static NSMutableDictionary *paramsCache = nil;
static NSLock *privateKeyLock = nil;
static NSMutableDictionary *privateKeyCache0 = nil;
static NSMutableDictionary *privateKeyCache1 = nil;
+ (void) _defaultsChanged: (NSNotification*)n
{
NSBundle *bundle;
NSUserDefaults *defs;
NSDictionary *env;
NSString *str;
bundle = [NSBundle bundleForClass: [NSObject class]];
defs = [NSUserDefaults standardUserDefaults];
env = [[NSProcessInfo processInfo] environment];
str = [defs stringForKey: @"GSCipherList"];
if (nil != str)
{
GSOnceMLog(@"GSCipherList is no longer used, please try GSTLSPriority");
}
str = [defs stringForKey: GSTLSPriority];
if (0 == [str length])
{
str = nil; // nil or empty string resets to default
}
ASSIGN(priority, str);
/* The GSTLSCAFile user default overrides the builtin value or the
* GS_TLS_CA_FILE environment variable.
*/
str = [defs stringForKey: GSTLSCAFile];
if (nil == str)
{
/* Let the GS_TLS_CA_FILE environment variable override the
* default certificate authority location.
* Failing that, use the same environment variable as OpenSSL
*/
str = [env objectForKey: @"GS_TLS_CA_FILE"];
if (nil == str)
{
str = [env objectForKey: @"SSL_CERT_FILE"];
}
if (nil == str)
{
str = [bundle pathForResource: @"ca-certificates"
ofType: @"crt"
inDirectory: @"GSTLS"];
}
}
str = standardizedPath(str);
ASSIGN(caFile, str);
/* The GSTLSRevokeFile user default overrides the builtin value or the
* GS_TLS_REVOKE environment variable.
*/
str = [defs stringForKey: GSTLSRevokeFile];
if (nil == str)
{
/* Let the GS_TLS_REVOKE environment variable override the
* default revocation list location.
*/
str = [env objectForKey: @"GS_TLS_REVOKE"];
if (nil == str)
{
str = [bundle pathForResource: @"revoke"
ofType: @"crl"
inDirectory: @"GSTLS"];
}
}
str = standardizedPath(str);
ASSIGN(revokeFile, str);
str = [defs stringForKey: @"GSTLSVerifyClient"];
if (nil == str)
{
str = [env objectForKey: @"GS_TLS_VERIFY_C"];
}
verifyClient = [str boolValue];
str = [defs stringForKey: @"GSTLSVerifyServer"];
if (nil == str)
{
str = [env objectForKey: @"GS_TLS_VERIFY_S"];
}
verifyServer = [str boolValue];
str = [defs stringForKey: GSTLSDebug];
if (nil == str)
{
str = [env objectForKey: @"GS_TLS_DEBUG"];
}
globalDebug = [str intValue];
if (globalDebug < 0)
{
globalDebug = 0;
}
gnutls_global_set_log_level(globalDebug);
}
+ (void) atExit
{
if ([NSObject shouldCleanUp])
{
DESTROY(certificateListLock);
DESTROY(certificateListCache);
DESTROY(credentialsLock);
DESTROY(credentialsCache);
DESTROY(fileLock);
DESTROY(fileMap);
DESTROY(paramsLock);
DESTROY(paramsCache);
DESTROY(privateKeyLock);
DESTROY(privateKeyCache0);
DESTROY(privateKeyCache1);
}
}
+ (NSData*) dataForTLSFile: (NSString*)fileName
{
NSData *result;
if (NO == [fileName isKindOfClass: [NSString class]])
{
[NSException raise: NSInvalidArgumentException
format: @"[GSTLS+dataForTLSFile:] called with bad file name"];
}
[fileLock lock];
NS_DURING
{
result = [[fileMap objectForKey: fileName] retain];
}
NS_HANDLER
{
[fileLock unlock];
result = nil;
[localException raise];
}
NS_ENDHANDLER
[fileLock unlock];
if (nil == result)
{
return [NSData dataWithContentsOfFile: fileName];
}
return [result autorelease];
}
+ (void) initialize
{
if ([GSTLSObject class] == self)
{
static BOOL beenHere = NO;
if (beenHere == NO)
{
beenHere = YES;
[self registerAtExit];
fileLock = [NSLock new];
fileMap = [NSMutableDictionary new];
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: @selector(_defaultsChanged:)
name: NSUserDefaultsDidChangeNotification
object: nil];
#if GNUTLS_VERSION_NUMBER <= 0x020b00
/* Make gcrypt thread-safe
*/
gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_other);
#endif
/* Initialise gnutls
*/
gnutls_global_init();
/* Allocate global credential information for anonymous tls
*/
gnutls_anon_allocate_client_credentials(&anoncred);
/* Enable gnutls logging via NSLog
*/
gnutls_global_set_log_function(GSTLSLog);
[self _defaultsChanged: nil];
}
}
}
+ (void) setData: (NSData*)data forTLSFile: (NSString*)fileName
{
fileName = standardizedPath(fileName);
if (nil != data && NO == [data isKindOfClass: [NSData class]])
{
[NSException raise: NSInvalidArgumentException
format: @"[GSTLS+setData:forTLSFile:] called with bad data"];
}
if (NO == [fileName isKindOfClass: [NSString class]])
{
[NSException raise: NSInvalidArgumentException
format: @"[GSTLS+setData:forTLSFile:] called with bad file"];
}
[fileLock lock];
NS_DURING
{
if (data == nil)
{
[fileMap removeObjectForKey: fileName];
}
else
{
[fileMap setObject: data forKey: fileName];
}
}
NS_HANDLER
{
[fileLock unlock];
[localException raise];
}
NS_ENDHANDLER
[fileLock unlock];
}
@end
@implementation GSTLSDHParams
static NSTimeInterval paramsWhen = 0.0;
static BOOL paramsGenerating = NO;
static GSTLSDHParams *paramsCurrent = nil;
+ (GSTLSDHParams*) current
{
GSTLSDHParams *p;
[paramsLock lock];
if (nil == paramsCurrent)
{
if (NO == paramsGenerating)
{
[paramsLock unlock];
[self generate];
[paramsLock lock];
}
while (nil == paramsCurrent)
{
[paramsLock unlock];
[NSThread sleepForTimeInterval: 0.2];
[paramsLock lock];
}
}
p = [paramsCurrent retain];
[paramsLock unlock];
return [p autorelease];
}
+ (void) generate
{
GSTLSDHParams *p;
[paramsLock lock];
if (YES == paramsGenerating)
{
[paramsLock unlock];
return;
}
paramsGenerating = YES;
[paramsLock unlock];
p = [GSTLSDHParams new];
/* Generate Diffie-Hellman parameters - for use with DHE
* kx algorithms. When short bit length is used, it might
* be wise to regenerate parameters often.
*/
gnutls_dh_params_init(&p->params);
gnutls_dh_params_generate2 (p->params, 2048);
[paramsLock lock];
[paramsCurrent release];
paramsCurrent = p;
paramsWhen = [NSDate timeIntervalSinceReferenceDate];
paramsGenerating = NO;
[paramsLock unlock];
}
+ (void) housekeeping: (NSNotification*)n
{
NSEnumerator *enumerator;
NSString *key;
NSTimeInterval now;
now = [NSDate timeIntervalSinceReferenceDate];
[paramsLock lock];
enumerator = [[paramsCache allKeys] objectEnumerator];
while (nil != (key = [enumerator nextObject]))
{
GSTLSDHParams *p;
p = [paramsCache objectForKey: key];
if (now - p->when > 300.0)
{
[paramsCache removeObjectForKey: key];
}
}
/* Regenerate DH params once per day, perfoming generation in another
* thread since it's likely to be rather slow.
*/
if (nil != paramsCurrent && NO == paramsGenerating
&& paramsWhen > 24.0 * 60.0 * 60.0)
{
[NSThread detachNewThreadSelector: @selector(generate)
toTarget: self
withObject: nil];
}
[paramsLock unlock];
}
+ (void) initialize
{
if (nil == paramsLock)
{
paramsLock = [NSLock new];
paramsWhen = [NSDate timeIntervalSinceReferenceDate];
paramsCache = [NSMutableDictionary new];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)
name: @"GSHousekeeping" object: nil];
}
}
+ (GSTLSDHParams*) paramsFromFile: (NSString*)f
{
GSTLSDHParams *p;
if (nil == f)
{
return nil;
}
f = standardizedPath(f);
[paramsLock lock];
p = [[paramsCache objectForKey: f] retain];
[paramsLock unlock];
if (nil == p)
{
NSData *data;
int ret;
gnutls_datum_t datum;
data = [[self class] dataForTLSFile: f];
if (nil == data)
{
NSLog(@"Unable to read DF params file '%@'", f);
return nil;
}
datum.data = (unsigned char*)[data bytes];
datum.size = (unsigned int)[data length];
p = [self alloc];
p->when = [NSDate timeIntervalSinceReferenceDate];
p->path = [f copy];
gnutls_dh_params_init(&p->params);
ret = gnutls_dh_params_import_pkcs3(p->params, &datum,
GNUTLS_X509_FMT_PEM);
if (ret < 0)
{
NSLog(@"Unable to parse DH params file '%@': %s",
p->path, gnutls_strerror(ret));
[p release];
return nil;
}
[paramsLock lock];
[paramsCache setObject: p forKey: p->path];
[paramsLock unlock];
}
return [p autorelease];
}
- (void) dealloc
{
gnutls_dh_params_deinit(params);
[super dealloc];
}
- (gnutls_dh_params_t) params
{
return params;
}
@end
@implementation GSTLSCertificateList
+ (void) certInfo: (gnutls_x509_crt_t)cert to: (NSMutableString*)str
{
#if GNUTLS_VERSION_NUMBER >= 0x030507
gnutls_datum_t dn;
#else
char dn[1024];
size_t dn_size = sizeof(dn);
#endif
char serial[40];
size_t serial_size = sizeof(serial);
time_t expiret;
time_t activet;
int algo;
unsigned int bits;
int i;
[str appendFormat: _(@"- Certificate version: #%d\n"),
gnutls_x509_crt_get_version(cert)];
#if GNUTLS_VERSION_NUMBER >= 0x030507
if (GNUTLS_E_SUCCESS == gnutls_x509_crt_get_dn3(cert, &dn, 0))
{
[str appendFormat: @"- Certificate DN: %@\n",
[NSString stringWithUTF8String: (const char*)dn.data]];
gnutls_free(dn.data);
}
if (GNUTLS_E_SUCCESS == gnutls_x509_crt_get_issuer_dn3(cert, &dn, 0))
{
[str appendFormat: _(@"- Certificate Issuer's DN: %@\n"),
[NSString stringWithUTF8String: (const char*)dn.data]];
gnutls_free(dn.data);
}
#else
dn_size = sizeof(dn) - 1;
gnutls_x509_crt_get_dn(cert, dn, &dn_size);
dn[dn_size] = '\0';
[str appendFormat: @"- Certificate DN: %@\n",
[NSString stringWithUTF8String: dn]];
dn_size = sizeof(dn) - 1;
gnutls_x509_crt_get_issuer_dn(cert, dn, &dn_size);
dn[dn_size] = '\0';
[str appendFormat: _(@"- Certificate Issuer's DN: %@\n"),
[NSString stringWithUTF8String: dn]];
#endif
activet = gnutls_x509_crt_get_activation_time(cert);
[str appendFormat: _(@"- Certificate is valid since: %s"),
ctime(&activet)];
expiret = gnutls_x509_crt_get_expiration_time(cert);
[str appendFormat: _(@"- Certificate expires: %s"),
ctime (&expiret)];
#if 0
{
char digest[20];
size_t digest_size = sizeof(digest);
if (gnutls_x509_fingerprint(GNUTLS_DIG_MD5,
&cert_list[0], digest, &digest_size) >= 0)
{
[str appendString: _(@"- Certificate fingerprint: ")];
for (i = 0; i < digest_size; i++)
{
[str appendFormat: @"%.2x ", (unsigned char)digest[i]];
}
[str appendString: @"\n"];
}
}
#endif
if (gnutls_x509_crt_get_serial(cert, serial, &serial_size) >= 0)
{
[str appendString: _(@"- Certificate serial number: ")];
for (i = 0; i < serial_size; i++)
{
[str appendFormat: @"%.2x ", (unsigned char)serial[i]];
}
[str appendString: @"\n"];
}
[str appendString: _(@"- Certificate public key: ")];
algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
if (GNUTLS_PK_RSA == algo)
{
[str appendFormat: _(@"RSA - Modulus: %d bits\n"), bits];
}
else if (GNUTLS_PK_DSA == algo)
{
[str appendFormat: _(@"DSA - Exponent: %d bits\n"), bits];
}
else
{
[str appendString: _(@"UNKNOWN\n")];
}
}
/* Method to purge older lists from cache.
*/
+ (void) housekeeping: (NSNotification*)n
{
NSEnumerator *enumerator;
NSString *key;
NSTimeInterval now;
now = [NSDate timeIntervalSinceReferenceDate];
[certificateListLock lock];
enumerator = [[certificateListCache allKeys] objectEnumerator];
while (nil != (key = [enumerator nextObject]))
{
GSTLSCertificateList *list;
list = [certificateListCache objectForKey: key];
if (now - list->when > 300.0)
{
[certificateListCache removeObjectForKey: key];
}
}
[certificateListLock unlock];
}
+ (void) initialize
{
if (nil == certificateListLock)
{
certificateListLock = [NSLock new];
certificateListCache = [NSMutableDictionary new];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)
name: @"GSHousekeeping" object: nil];
}
}
+ (GSTLSCertificateList*) listFromFile: (NSString*)f
{
GSTLSCertificateList *l;
if (nil == f)
{
return nil;
}
f = standardizedPath(f);
[certificateListLock lock];
l = [[certificateListCache objectForKey: f] retain];
[certificateListLock unlock];
if (nil == l)
{
NSData *data;
int ret;
gnutls_datum_t datum;
unsigned int count = 100;
gnutls_x509_crt_t crts[count];
data = [[self class] dataForTLSFile: f];
if (nil == data)
{
NSLog(@"Unable to read certificate file '%@'", f);
return nil;
}
datum.data = (unsigned char*)[data bytes];
datum.size = (unsigned int)[data length];
l = [self alloc];
l->when = [NSDate timeIntervalSinceReferenceDate];
l->path = [f copy];
ret = gnutls_x509_crt_list_import(crts, &count, &datum,
GNUTLS_X509_FMT_PEM,
// GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED |
GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
if (ret < 0)
{
NSLog(@"Unable to parse certificate file '%@': %s",
l->path, gnutls_strerror(ret));
[l release];
return nil;
}
if (count > 0)
{
time_t now = (time_t)[[NSDate date] timeIntervalSince1970];
unsigned int i;
l->crts = malloc(sizeof(gnutls_x509_crt_t) * count);
memcpy(l->crts, crts, sizeof(gnutls_x509_crt_t) * count);
l->count = count;
for (i = 0; i < count; i++)
{
time_t expiret = gnutls_x509_crt_get_expiration_time(crts[i]);
time_t activet = gnutls_x509_crt_get_activation_time(crts[i]);
if (expiret <= now)
{
NSLog(@"WARNING: at index %u in %@ ... expired at %s",
i, l->path, ctime(&activet));
}
if (activet > now)
{
NSLog(@"WARNING: at index %u in %@ ... not valid until %s",
i, l->path, ctime(&activet));
}
if (expiret <= now || activet > now)
{
NSMutableString *m;
m = [NSMutableString stringWithCapacity: 2000];
[self certInfo: crts[i] to: m];
NSLog(@"%@", m);
}
}
}
[certificateListLock lock];
[certificateListCache setObject: l forKey: l->path];
[certificateListLock unlock];
}
return [l autorelease];
}
- (gnutls_x509_crt_t*) certificateList
{
return crts;
}
- (unsigned int) count
{
return count;
}
- (NSDate*) expiresAt
{
unsigned index = count;
time_t expiret;
if (index-- == 0)
{
return nil;
}
expiret = gnutls_x509_crt_get_expiration_time(crts[index]);
if (expiret < 0)
{
return nil;
}
while (index > 0)
{
time_t t = gnutls_x509_crt_get_expiration_time(crts[--index]);
if (t < 0)
{
return nil;
}
if (t < expiret)
{
expiret = t;
}
}
return [NSDate dateWithTimeIntervalSince1970: expiret];
}
- (NSDate*) expiresAt: (unsigned int)index
{
time_t expiret;
if (count == 0 || index > count - 1)
{
return nil;
}
expiret = gnutls_x509_crt_get_expiration_time(crts[index]);
if (expiret < 0)
{
return nil;
}
else
{
return [NSDate dateWithTimeIntervalSince1970: expiret];
}
}
- (void) dealloc
{
if (nil != path)
{
DESTROY(path);
if (count > 0)
{
while (count-- > 0)
{
if (crts) gnutls_x509_crt_deinit(crts[count]);
}
if (crts) free(crts);
}
}
[super dealloc];
}
@end
@implementation GSTLSPrivateKey
/* Method to purge older keys from cache.
*/
+ (void) housekeeping: (NSNotification*)n
{
NSEnumerator *outer;
NSString *oKey;
NSTimeInterval now;
now = [NSDate timeIntervalSinceReferenceDate];
[privateKeyLock lock];
outer = [[privateKeyCache0 allKeys] objectEnumerator];
while (nil != (oKey = [outer nextObject]))
{
GSTLSPrivateKey *key;
key = [privateKeyCache0 objectForKey: oKey];
if (now - key->when > 300.0)
{
[privateKeyCache0 removeObjectForKey: oKey];
}
}
outer = [[privateKeyCache1 allKeys] objectEnumerator];
while (nil != (oKey = [outer nextObject]))
{
NSMutableDictionary *m;
NSEnumerator *inner;
NSString *iKey;
m = [privateKeyCache1 objectForKey: oKey];
inner = [[m allKeys] objectEnumerator];
while (nil != (iKey = [inner nextObject]))
{
GSTLSPrivateKey *key = [m objectForKey: iKey];
if (now - key->when > 300.0)
{
[m removeObjectForKey: iKey];
if (0 == [m count])
{
[privateKeyCache1 removeObjectForKey: oKey];
}
}
}
}
[privateKeyLock unlock];
}
+ (void) initialize
{
if (nil == privateKeyLock)
{
privateKeyLock = [NSLock new];
privateKeyCache0 = [NSMutableDictionary new];
privateKeyCache1 = [NSMutableDictionary new];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)
name: @"GSHousekeeping" object: nil];
}
}
+ (GSTLSPrivateKey*) keyFromFile: (NSString*)f withPassword: (NSString*)p
{
GSTLSPrivateKey *k;
if (nil == f)
{
return nil;
}
f = standardizedPath(f);
[privateKeyLock lock];
if (nil == p)
{
k = [privateKeyCache0 objectForKey: f];
}
else
{
NSMutableDictionary *m;
m = [privateKeyCache1 objectForKey: f];
if (nil == m)
{
k = nil;
}
else
{
k = [m objectForKey: p];
}