-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathTcpSocketClient.m
1031 lines (888 loc) · 33.8 KB
/
TcpSocketClient.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
#import "TcpSocketClient.h"
#import <arpa/inet.h>
#import <netinet/in.h>
#import <netinet/tcp.h>
#import <React/RCTLog.h>
#import <CommonCrypto/CommonDigest.h>
#import <Security/SecCertificate.h>
#import <Security/SecImportExport.h>
#import <Security/SecItem.h>
#import <Security/SecKey.h>
#import <Security/SecPolicy.h>
#import <Security/Security.h>
NSString *const RCTTCPErrorDomain = @"RCTTCPErrorDomain";
@implementation ResolvableOption
- (instancetype)initWithValue:(NSString *)value
needsResolution:(BOOL)needsResolution {
if (self = [super init]) {
_value = value;
_needsResolution = needsResolution;
}
return self;
}
+ (instancetype)optionWithValue:(NSString *)value
needsResolution:(BOOL)needsResolution {
return [[self alloc] initWithValue:value needsResolution:needsResolution];
}
- (NSString *)resolve {
if (!self.needsResolution) {
return self.value;
}
NSURL *url = [[NSURL alloc] initWithString:self.value];
NSError *error = nil;
NSString *contents =
[[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
if (error) {
return nil;
}
return contents;
}
@end
@interface TcpSocketClient () {
@private
BOOL _tls;
BOOL _checkValidity;
BOOL _paused;
BOOL _connecting;
ResolvableOption *_resolvableCaCert;
NSString *_host;
GCDAsyncSocket *_tcpSocket;
NSMutableDictionary<NSNumber *, NSNumber *> *_pendingSends;
NSDictionary *_tlsSettings;
NSLock *_lock;
NSNumber *_serverId;
long _sendTag;
SecTrustRef _peerTrust;
SecIdentityRef _clientIdentity;
}
- (id)initWithClientId:(NSNumber *)clientID
andConfig:(id<SocketClientDelegate>)aDelegate;
- (id)initWithClientId:(NSNumber *)clientID
andConfig:(id<SocketClientDelegate>)aDelegate
andSocket:(GCDAsyncSocket *)tcpSocket
andServer:(NSNumber *)serverID;
@end
@implementation TcpSocketClient
- (GCDAsyncSocket *)getSocket {
return _tcpSocket;
}
+ (id)socketClientWithId:(nonnull NSNumber *)clientID
andConfig:(id<SocketClientDelegate>)delegate {
return [[[self class] alloc] initWithClientId:clientID
andConfig:delegate
andSocket:nil
andServer:nil];
}
- (id)initWithClientId:(NSNumber *)clientID
andConfig:(id<SocketClientDelegate>)aDelegate {
return [self initWithClientId:clientID
andConfig:aDelegate
andSocket:nil
andServer:nil];
}
- (id)initWithClientId:(NSNumber *)clientID
andConfig:(id<SocketClientDelegate>)aDelegate
andSocket:(GCDAsyncSocket *)tcpSocket
andServer:(NSNumber *)serverID;
{
self = [super init];
if (self) {
_id = clientID;
_clientDelegate = aDelegate;
_paused = false;
_connecting = false;
_pendingSends = [NSMutableDictionary dictionary];
_lock = [[NSLock alloc] init];
_tcpSocket = tcpSocket;
_serverId = serverID;
[_tcpSocket setUserData:clientID];
[_tcpSocket setDelegate:self];
[_tcpSocket setDelegateQueue:[self methodQueue]];
}
return self;
}
- (BOOL)connect:(NSString *)host
port:(int)port
withOptions:(NSDictionary *)options
tlsOptions:(NSDictionary *)tlsOptions
error:(NSError **)error {
if (_tcpSocket) {
if (error) {
*error = [self badInvocationError:
@"this client's socket is already connected"];
}
return false;
}
_tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self
delegateQueue:[self methodQueue]];
[_tcpSocket setUserData:_id];
BOOL result = false;
NSString *localAddress = options[@"localAddress"];
NSNumber *localPort = options[@"localPort"];
_host = host;
_connecting = true;
if (!localAddress && !localPort) {
result = [_tcpSocket connectToHost:host onPort:port error:error];
} else {
NSMutableArray *interface = [NSMutableArray arrayWithCapacity:2];
[interface addObject:localAddress ? localAddress : @""];
if (localPort) {
[interface addObject:[localPort stringValue]];
}
result =
[_tcpSocket connectToHost:host
onPort:port
viaInterface:[interface componentsJoinedByString:@":"]
withTimeout:-1
error:error];
}
if (result && tlsOptions) {
[self startTLS:tlsOptions];
}
return result;
}
- (ResolvableOption *)getResolvableOption:(NSDictionary *)tlsOptions
forKey:(NSString *)key {
id value = [tlsOptions objectForKey:key];
if (!value || ![value isKindOfClass:[NSString class]] || [(NSString *)value length] == 0) {
return nil;
}
NSArray *resolvedKeys = tlsOptions[@"resolvedKeys"];
BOOL needsResolution = resolvedKeys != nil && [resolvedKeys containsObject:key];
return [ResolvableOption optionWithValue:(NSString *)value
needsResolution:needsResolution];
}
- (void)startTLS:(NSDictionary *)tlsOptions {
if (_tls)
return;
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
_resolvableCaCert = [self getResolvableOption:tlsOptions forKey:@"ca"];
BOOL checkValidity = (tlsOptions[@"rejectUnauthorized"]
? [tlsOptions[@"rejectUnauthorized"] boolValue]
: true);
if (!checkValidity) {
// Do not validate
_checkValidity = false;
[settings setObject:[NSNumber numberWithBool:YES]
forKey:GCDAsyncSocketManuallyEvaluateTrust];
} else if (_resolvableCaCert != nil) {
// Self-signed certificate
[settings setObject:[NSNumber numberWithBool:YES]
forKey:GCDAsyncSocketManuallyEvaluateTrust];
} else {
// Default certificates
[settings setObject:_host forKey:(NSString *)kCFStreamSSLPeerName];
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////:
// Handle client certificate authentication
/////////////////////////////////////////////////////////////////////////////////////////////////////////////:
SecIdentityRef myIdent = NULL;
ResolvableOption *resolvableKey = [self getResolvableOption:tlsOptions forKey:@"key"];
ResolvableOption *resolvableCert = [self getResolvableOption:tlsOptions forKey:@"cert"];
NSString *keyAlias = tlsOptions[@"keyAlias"];
if (keyAlias) { [settings setObject:keyAlias forKey:@"keyAlias"]; }
NSString *certAlias = tlsOptions[@"certAlias"];
if (certAlias) { [settings setObject:certAlias forKey:@"certAlias"]; }
// if user provides certAlias without cert it means an identity(cert+key) has already been
// inserted in keychain.
if ((certAlias && certAlias.length > 0) && (!resolvableCert)) {
//RCTLogWarn(@"startTLS: Trying to find existing identity with certAlias %@", certAlias);
NSDictionary *identityQuery = @{
(__bridge id)kSecClass : (__bridge id)kSecClassIdentity,
(__bridge id)kSecReturnRef : @YES,
(__bridge id)kSecAttrLabel : certAlias
};
SecItemCopyMatching((__bridge CFDictionaryRef)identityQuery, (CFTypeRef *)&myIdent);
} else if (resolvableCert != nil && resolvableKey != nil) {
//RCTLogWarn(@"startTLS: Attempting client certificate authentication");
NSString *pemCert = [resolvableCert resolve];
NSString *pemKey = [resolvableKey resolve];
if (pemCert && pemKey) {
myIdent = [self createIdentityWithCert:pemCert
privateKey:pemKey
settings:settings];
//RCTLogWarn(@"startTLS: Identity creation %@", myIdent ? @"successful" : @"failed");
}
}
if (myIdent) {
if (_clientIdentity) { CFRelease(_clientIdentity); }
_clientIdentity = (SecIdentityRef)CFRetain(myIdent);
NSArray *myCerts = @[ (__bridge id)myIdent ];
[settings setObject:myCerts
forKey:(NSString *)kCFStreamSSLCertificates];
//RCTLogWarn(@"startTLS: Client certificates configured successfully");
}
//RCTLogWarn(@"startTLS: Final settings: %@", settings);
_tls = true;
[_tcpSocket startTLS:settings];
}
- (NSDictionary<NSString *, id> *)getAddress {
if (_tcpSocket) {
if (_tcpSocket.isConnected) {
return @{
@"port" : @(_tcpSocket.connectedPort),
@"address" : _tcpSocket.connectedHost ?: @"unknown",
@"family" : _tcpSocket.isIPv6 ? @"IPv6" : @"IPv4"
};
} else {
return @{
@"port" : @(_tcpSocket.localPort),
@"address" : _tcpSocket.localHost ?: @"unknown",
@"family" : _tcpSocket.isIPv6 ? @"IPv6" : @"IPv4"
};
}
}
return @{@"port" : @(0), @"address" : @"unknown", @"family" : @"unkown"};
}
- (void)setNoDelay:(BOOL)noDelay {
[_tcpSocket performBlock:^{
int fd = [self->_tcpSocket socketFD];
int on = noDelay ? 1 : 0;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&on, sizeof(on)) ==
-1) {
/* TODO: handle error */
RCTLogWarn(@"react-native-tcp-socket: setNoDelay() caused an "
@"unexpected error");
}
}];
}
- (void)setKeepAlive:(BOOL)enable initialDelay:(int)initialDelay {
[_tcpSocket performBlock:^{
int fd = [self->_tcpSocket socketFD];
int on = enable ? 1 : 0;
int enableKA = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
// `initialDelay` is ignored
if (enableKA == -1) {
/* TODO: handle error */
RCTLogWarn(@"react-native-tcp-socket: setKeepAlive() caused an "
@"unexpected error");
}
}];
}
- (BOOL)listen:(NSDictionary *)options error:(NSError **)error {
if (_tcpSocket) {
if (error) {
*error = [self badInvocationError:
@"this client's socket is already connected"];
}
return false;
}
_tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self
delegateQueue:[self methodQueue]];
[_tcpSocket setUserData:_id];
// Get TLS data if present
NSDictionary *tlsOptions = options[@"tls"];
if (tlsOptions) {
BOOL success = [self setSecureContext:tlsOptions];
if (!success) {
if (error) {
*error = [self badInvocationError:@"failed to set TLS context"];
}
return false;
}
}
// Get the host and port
NSString *host = options[@"host"];
int port = [options[@"port"] intValue];
// GCDAsyncSocket doesn't recognize 0.0.0.0
if ([@"0.0.0.0" isEqualToString:host]) {
host = nil;
}
BOOL isListening = [_tcpSocket acceptOnInterface:host
port:port
error:error];
if (isListening == YES) {
[_clientDelegate onListen:self];
}
return isListening;
}
- (BOOL)setSecureContext:(NSDictionary *)tlsOptions {
NSString *keystoreResourcePath = tlsOptions[@"keystore"];
NSURL *keystoreUrl = [[NSURL alloc] initWithString:keystoreResourcePath];
NSData *pkcs12data = [[NSData alloc] initWithContentsOfURL:keystoreUrl];
CFDataRef inPCKS12Data = (CFDataRef)CFBridgingRetain(pkcs12data);
CFStringRef password = CFSTR("");
const void *keys[] = {kSecImportExportPassphrase};
const void *values[] = {password};
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import(inPCKS12Data, options, &items);
CFRelease(options);
CFRelease(password);
if (securityError != errSecSuccess) {
return false;
}
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef myIdent = (SecIdentityRef)CFDictionaryGetValue(
identityDict, kSecImportItemIdentity);
SecIdentityRef certArray[1] = {myIdent};
CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL);
_tlsSettings = [NSMutableDictionary dictionary];
[(NSMutableDictionary *)_tlsSettings
setObject:[NSNumber numberWithBool:YES]
forKey:(NSString *)kCFStreamSSLIsServer];
[(NSMutableDictionary *)_tlsSettings
setObject:[NSNumber numberWithInteger:2]
forKey:GCDAsyncSocketSSLProtocolVersionMin];
[(NSMutableDictionary *)_tlsSettings
setObject:[NSNumber numberWithInteger:8]
forKey:GCDAsyncSocketSSLProtocolVersionMax];
[(NSMutableDictionary *)_tlsSettings
setObject:(id)CFBridgingRelease(myCerts)
forKey:(NSString *)kCFStreamSSLCertificates];
_tls = true;
return true;
}
- (void)setPendingSend:(NSNumber *)msgId forKey:(NSNumber *)key {
[_lock lock];
@try {
[_pendingSends setObject:msgId forKey:key];
} @finally {
[_lock unlock];
}
}
- (NSNumber *)getPendingSend:(NSNumber *)key {
[_lock lock];
@try {
return [_pendingSends objectForKey:key];
} @finally {
[_lock unlock];
}
}
- (void)dropPendingSend:(NSNumber *)key {
[_lock lock];
@try {
[_pendingSends removeObjectForKey:key];
} @finally {
[_lock unlock];
}
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)msgTag {
NSNumber *tagNum = [NSNumber numberWithLong:msgTag];
NSNumber *msgId = [self getPendingSend:tagNum];
if (msgId) {
[_clientDelegate onWrittenData:self msgId:msgId];
[self dropPendingSend:tagNum];
}
}
- (void)writeData:(NSData *)data msgId:(NSNumber *)msgId {
[self setPendingSend:msgId forKey:@(_sendTag)];
[_tcpSocket writeData:data withTimeout:-1 tag:_sendTag];
_sendTag++;
}
- (void)end {
[_tcpSocket disconnectAfterWriting];
}
- (void)destroy {
[_tcpSocket disconnect];
}
- (void)pause {
_paused = true;
}
- (void)resume {
if (_paused) {
[_tcpSocket readDataWithTimeout:-1 tag:_id.longValue];
}
_paused = false;
}
- (void)socket:(GCDAsyncSocket *)sock
didReadData:(NSData *)data
withTag:(long)tag {
if (!_clientDelegate) {
RCTLogWarn(@"didReadData with nil clientDelegate for %@",
[sock userData]);
return;
}
[_clientDelegate onData:@(tag) data:data];
if (!_paused) {
[sock readDataWithTimeout:-1 tag:tag];
}
}
- (void)socket:(GCDAsyncSocket *)sock
didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
TcpSocketClient *inComing =
[[TcpSocketClient alloc] initWithClientId:[_clientDelegate getNextId]
andConfig:_clientDelegate
andSocket:newSocket
andServer:_id];
// Store the socket or the connection will be closed
[_clientDelegate addClient:inComing];
if (_tls) {
[newSocket startTLS:_tlsSettings];
} else {
[_clientDelegate onConnection:inComing toClient:_id];
}
[newSocket readDataWithTimeout:-1 tag:inComing.id.longValue];
}
- (void)socketDidSecure:(GCDAsyncSocket *)sock {
// Only for TLS
if (!_clientDelegate) {
RCTLogWarn(@"socketDidSecure with nil clientDelegate for %@",
[sock userData]);
return;
}
if (_serverId != nil) {
[_clientDelegate onSecureConnection:self toClient:_serverId];
} else if (_connecting) {
[_clientDelegate onConnect:self];
_connecting = false;
}
_tls = true;
}
- (void)socket:(GCDAsyncSocket *)sock
didReceiveTrust:(SecTrustRef)trust
completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler {
// Store the trust reference
if (_peerTrust) {
CFRelease(_peerTrust);
}
_peerTrust = (SecTrustRef)CFRetain(trust);
// Check if we should check the validity
if (!_checkValidity) {
completionHandler(YES);
return;
}
// Server certificate
SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(trust, 0);
CFDataRef serverCertificateData = SecCertificateCopyData(serverCertificate);
const UInt8 *const serverData = CFDataGetBytePtr(serverCertificateData);
const CFIndex serverDataSize = CFDataGetLength(serverCertificateData);
NSData *cert1 = [NSData dataWithBytes:serverData
length:(NSUInteger)serverDataSize];
// Local certificate
NSString *pemCaCert = [_resolvableCaCert resolve];
if (!pemCaCert) {
RCTLogWarn(@"Failed to resolve CA certificate");
completionHandler(NO);
return;
}
// Strip PEM header and footer
NSString *cleanedCaCert = [self stripPEMHeader:pemCaCert
prefix:@"CERTIFICATE"];
NSData *pemCaCertData = [[NSData alloc]
initWithBase64EncodedString:cleanedCaCert
options:
NSDataBase64DecodingIgnoreUnknownCharacters];
SecCertificateRef localCertificate =
SecCertificateCreateWithData(NULL, (CFDataRef)pemCaCertData);
if (!localCertificate) {
[NSException raise:@"Configuration invalid"
format:@"Failed to parse PEM certificate"];
}
CFDataRef myCertData = SecCertificateCopyData(localCertificate);
const UInt8 *const localData = CFDataGetBytePtr(myCertData);
const CFIndex localDataSize = CFDataGetLength(myCertData);
NSData *cert2 = [NSData dataWithBytes:localData
length:(NSUInteger)localDataSize];
if (cert1 == nil || cert2 == nil) {
RCTLogWarn(@"BAD SSL CERTIFICATE");
completionHandler(NO);
return;
}
if ([cert1 isEqualToData:cert2]) {
completionHandler(YES);
} else {
completionHandler(NO);
}
}
- (void)socket:(GCDAsyncSocket *)sock
didConnectToHost:(NSString *)host
port:(uint16_t)port {
if (!_clientDelegate) {
RCTLogWarn(@"didConnectToHost with nil clientDelegate for %@",
[sock userData]);
return;
}
// Show up if SSL handsake is done
if (!_tls) {
[_clientDelegate onConnect:self];
}
[sock readDataWithTimeout:-1 tag:_id.longValue];
}
- (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock {
// TODO : investigate for half-closed sockets
// for now close the stream completely
[sock disconnect];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
if (!_clientDelegate) {
RCTLogWarn(@"socketDidDisconnect with nil clientDelegate for %@",
[sock userData]);
return;
}
[_clientDelegate
onClose:[sock userData]
withError:(!err || err.code == GCDAsyncSocketClosedError ? nil : err)];
}
typedef NS_ENUM(NSInteger, PEMType) {
PEMTypeUnknown,
PEMTypeCertificate,
PEMTypePKCS1,
PEMTypePKCS8
};
- (PEMType)detectPEMType:(NSString *)pemData {
if ([pemData containsString:@"BEGIN CERTIFICATE"]) {
return PEMTypeCertificate;
}
if ([pemData containsString:@"BEGIN PRIVATE KEY"]) {
return PEMTypePKCS8;
}
if ([pemData containsString:@"BEGIN RSA PRIVATE KEY"]) {
return PEMTypePKCS1;
}
return PEMTypeUnknown;
}
- (NSData *)getDataFromPEM:(NSString *)pemData error:(NSError **)error {
PEMType type = [self detectPEMType:pemData];
if (type == PEMTypeUnknown) {
if (error) {
*error = [NSError
errorWithDomain:RCTTCPErrorDomain
code:-1
userInfo:@{
NSLocalizedDescriptionKey : @"Invalid PEM format"
}];
}
return nil;
}
// Extract the base64 data between headers
NSString *prefix;
switch (type) {
case PEMTypeCertificate:
prefix = @"CERTIFICATE";
break;
case PEMTypePKCS8:
prefix = @"PRIVATE KEY";
break;
case PEMTypePKCS1:
prefix = @"RSA PRIVATE KEY";
break;
default:
return nil;
}
NSString *cleanedPEM = [self stripPEMHeader:pemData prefix:prefix];
NSData *decodedData = [[NSData alloc]
initWithBase64EncodedString:cleanedPEM
options:
NSDataBase64DecodingIgnoreUnknownCharacters];
// For PKCS#8, extract the RSA key
if (type == PEMTypePKCS8) {
return [self extractRSAKeyFromPKCS8:decodedData error:error];
}
return decodedData;
}
- (NSData *)extractRSAKeyFromPKCS8:(NSData *)pkcs8Data error:(NSError **)error {
// RSA 2048-bit PKCS#8 header (26 bytes)
const uint8_t rsa2048Prefix[] = {
0x30, 0x82, 0x04, 0xBE, 0x02, 0x01, 0x00, 0x30,
0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
0x04, 0xA8
};
// Check for minimum data length
if (pkcs8Data.length <= sizeof(rsa2048Prefix)) {
if (error) {
*error = [NSError errorWithDomain:RCTTCPErrorDomain
code:-1
userInfo:@{
NSLocalizedDescriptionKey: @"Invalid PKCS#8 data: too short"
}];
}
return nil;
}
// Verify RSA 2048-bit key prefix - We need a ASN1 decoder to support more !!!
if (memcmp(pkcs8Data.bytes, rsa2048Prefix, sizeof(rsa2048Prefix)) != 0) {
if (error) {
*error = [NSError errorWithDomain:RCTTCPErrorDomain
code:-1
userInfo:@{
NSLocalizedDescriptionKey: @"Unsupported key format: only RSA 2048-bit keys are supported"
}];
}
return nil;
}
// Extract the RSA private key data
return [pkcs8Data subdataWithRange:NSMakeRange(sizeof(rsa2048Prefix),
pkcs8Data.length - sizeof(rsa2048Prefix))];
}
- (SecIdentityRef)createIdentityWithCert:(NSString *)pemCert
privateKey:(NSString *)pemKey
settings:(NSDictionary *)settings {
OSStatus status = -1;
SecIdentityRef identity = NULL;
// Get aliases from settings
NSString *certAlias = settings[@"certAlias"] ?: @"clientTlsCert";
NSString *keyAlias = settings[@"keyAlias"] ?: @"clientTlsKey";
NSError *pemError = nil;
NSData *certData = [self getDataFromPEM:pemCert error:&pemError];
NSData *keyData = [self getDataFromPEM:pemKey error:&pemError];
if (pemError || !certData || !keyData) {
RCTLogWarn(@"createIdentity: Failed to process PEM data: %@", pemError);
return NULL;
}
// Creates a certificate object from its DER representation
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
if (!cert) {
RCTLogWarn(@"createIdentity: Failed to create certificate from data");
return NULL;
}
// Import certificate in keychain
NSDictionary *deleteCertQuery = @{
(__bridge id)kSecClass : (__bridge id)kSecClassCertificate,
(__bridge id)kSecAttrLabel: certAlias,
(__bridge id)kSecReturnRef : @YES
};
status = SecItemDelete((__bridge CFDictionaryRef)deleteCertQuery);
NSDictionary *certAttributes = @{
//(__bridge id)kSecClass : (__bridge id)kSecClassCertificate,
(__bridge id)kSecValueRef : (__bridge id)cert,
(__bridge id)kSecAttrLabel : certAlias,
};
status = SecItemAdd((__bridge CFDictionaryRef)certAttributes, NULL);
if (status != errSecSuccess && status != errSecDuplicateItem) {
RCTLogWarn(@"createIdentity: Failed to store certificate, status: %d",
(int)status);
CFRelease(cert);
return NULL;
}
NSDictionary *privateKeyAttributes = @{
(__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeRSA,
(__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate
};
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateWithData(
(__bridge CFDataRef)keyData,
(__bridge CFDictionaryRef)privateKeyAttributes, &error);
if (!privateKey) {
RCTLogWarn(@"createIdentity: Failed to create private key: %@", error);
CFRelease(cert);
if (error)
CFRelease(error);
return NULL;
}
NSDictionary *deleteKeyQuery = @{
(__bridge id)kSecClass : (__bridge id)kSecClassKey,
(__bridge id)kSecAttrLabel: keyAlias,
(__bridge id)kSecReturnRef : @YES
};
status = SecItemDelete((__bridge CFDictionaryRef)deleteKeyQuery);
// Add the private key to keychain
NSDictionary *keyAttributes = @{
(__bridge id)kSecValueRef: (__bridge id)privateKey,
(__bridge id)kSecAttrLabel : keyAlias
};
status = SecItemAdd((__bridge CFDictionaryRef)keyAttributes, NULL);
if (status != errSecSuccess && status != errSecDuplicateItem) {
RCTLogWarn(@"createIdentity: Failed to store private key, status: %d",
(int)status);
CFRelease(cert);
CFRelease(privateKey);
return NULL;
}
NSDictionary *identityQuery = @{
(__bridge id)kSecClass : (__bridge id)kSecClassIdentity,
(__bridge id)kSecReturnRef : @YES,
(__bridge id)kSecAttrLabel : certAlias
};
status = SecItemCopyMatching((__bridge CFDictionaryRef)identityQuery,
(CFTypeRef *)&identity);
if (status != errSecSuccess || !identity) {
RCTLogWarn(@"createIdentity: Failed to find identity, status: %d",
(int)status);
}
// Clean up
CFRelease(cert);
CFRelease(privateKey);
return identity;
}
- (NSString *)stripPEMHeader:(NSString *)pemData prefix:(NSString *)prefix {
NSMutableString *cleaned = [pemData mutableCopy];
// Remove header
NSString *header =
[NSString stringWithFormat:@"-----BEGIN %@-----", prefix];
[cleaned replaceOccurrencesOfString:header
withString:@""
options:NSLiteralSearch
range:NSMakeRange(0, cleaned.length)];
// Remove footer
NSString *footer = [NSString stringWithFormat:@"-----END %@-----", prefix];
[cleaned replaceOccurrencesOfString:footer
withString:@""
options:NSLiteralSearch
range:NSMakeRange(0, cleaned.length)];
// Remove whitespace and newlines
NSArray *components =
[cleaned componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *result = [components componentsJoinedByString:@""];
return result;
}
+ (BOOL)hasIdentity:(NSDictionary *)aliases {
NSString *certAlias = aliases[@"certAlias"];
if (!certAlias) {
return NO;
}
NSDictionary *identityQuery = @{
(__bridge id)kSecClass : (__bridge id)kSecClassIdentity,
(__bridge id)kSecAttrLabel : certAlias
};
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)identityQuery, (CFTypeRef *)NULL);
return status == errSecSuccess;
}
- (NSDictionary *)getPeerCertificate {
NSDictionary *result = nil;
if (!_tcpSocket || !_tls || !_peerTrust) {
return nil;
}
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(_peerTrust, 0);
if (!certificate) {
return nil;
}
result = [self certificateToDict:certificate detailed:YES];
return result;
}
- (NSDictionary *)getCertificate {
NSDictionary *result = nil;
if (!_tcpSocket || !_tls) {
return nil;
}
SecCertificateRef certificate = NULL;
if (_clientIdentity) {
// If we have a client identity, get the certificate from it
OSStatus status = SecIdentityCopyCertificate(_clientIdentity, &certificate);
if (status != errSecSuccess) {
RCTLogWarn(@"getCertificate: Failed to get certificate from identity, status: %d", (int)status);
return nil;
}
}
result = [self certificateToDict:certificate detailed:YES];
CFRelease(certificate);
return result;
}
// We need an ASN1 decoder to parse properly but for my case I only need modulus
// and exponent In addition SecCertificateCopyNormalizedIssuerSequence has some
// issues since it normalizes issuer and we don't want that
- (NSDictionary *)certificateToDict:(SecCertificateRef)certificate
detailed:(BOOL)detailed {
NSMutableDictionary *certInfo = [NSMutableDictionary dictionary];
// Get public key info
SecKeyRef publicKey = SecCertificateCopyKey(certificate);
if (publicKey) {
CFDictionaryRef attributes = SecKeyCopyAttributes(publicKey);
if (attributes) {
// Get key size (bits)
NSNumber *keySize =
CFDictionaryGetValue(attributes, kSecAttrKeySizeInBits);
certInfo[@"bits"] = keySize;
// Get modulus and exponent for RSA keys
CFDataRef keyData =
SecKeyCopyExternalRepresentation(publicKey, NULL);
if (keyData) {
NSData *keyDataNS = (__bridge NSData *)keyData;
// For RSA, the external representation is a DER-encoded
// RSAPublicKey
if ([self isRSAKey:publicKey]) {
NSArray *components = [self parseRSAPublicKey:keyDataNS];
if (components.count == 2) {
certInfo[@"modulus"] = components[0];
certInfo[@"exponent"] = [NSString stringWithFormat:@"0x%@", components[1]];
}
}
// Add base64 encoded public key
certInfo[@"pubkey"] = [keyDataNS base64EncodedStringWithOptions:0];
CFRelease(keyData);
}
CFRelease(attributes);
}
CFRelease(publicKey);
}
// Get subject
CFStringRef subjectName = NULL;
OSStatus status = SecCertificateCopyCommonName(certificate, &subjectName);
if (status == errSecSuccess && subjectName) {
certInfo[@"subject"] =
@{@"CN" : (__bridge_transfer NSString *)subjectName};
}
// Get issuer using the normalized sequence
CFDataRef issuerSequence =
SecCertificateCopyNormalizedIssuerSequence(certificate);
if (issuerSequence) {
CFStringRef issuerName = NULL;
status = SecCertificateCopyCommonName(certificate, &issuerName);
if (status == errSecSuccess && issuerName) {
certInfo[@"issuer"] =
@{@"CN" : (__bridge_transfer NSString *)issuerName};
}
CFRelease(issuerSequence);
}
return certInfo;
}
- (BOOL)isRSAKey:(SecKeyRef)key {
CFDictionaryRef attributes = SecKeyCopyAttributes(key);
if (!attributes)
return NO;
CFStringRef keyType = CFDictionaryGetValue(attributes, kSecAttrKeyType);
BOOL isRSA = keyType && CFEqual(keyType, kSecAttrKeyTypeRSA);
CFRelease(attributes);
return isRSA;
}
- (NSArray *)parseRSAPublicKey:(NSData *)keyData {
// Parse DER-encoded RSAPublicKey structure
const uint8_t *bytes = keyData.bytes;
NSInteger length = keyData.length;
// Skip header and length bytes
if (length < 2 || bytes[0] != 0x30) return nil;
NSInteger idx = 2;
if (bytes[1] & 0x80) {
idx += (bytes[1] & 0x7F);
}
// Read modulus
if (idx >= length || bytes[idx] != 0x02) return nil;
idx++;
NSInteger modulusLength = bytes[idx++];
if (modulusLength & 0x80) {
int lenBytes = modulusLength & 0x7F;
modulusLength = 0;
for (int i = 0; i < lenBytes; i++) {
modulusLength = (modulusLength << 8) | bytes[idx++];
}
}
// Skip leading zero if present for modulus
NSInteger startOffset = 0;
if (bytes[idx] == 0x00) {
startOffset = 1;
modulusLength--;
}
NSMutableString *modulus = [NSMutableString string];
for (NSInteger i = 0; i < modulusLength; i++) {
[modulus appendFormat:@"%02X", bytes[idx + startOffset + i]];
}
idx += modulusLength + startOffset;
// Read exponent
if (idx >= length || bytes[idx] != 0x02) return nil;