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
| // // JITGMSocket.m // GMTest // // Created by JITPlatform001 on 2021/10/29. //
#import "JITGMSocket.h"
#include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h>
#include <openssl/ossl_typ.h> #include <openssl/ssl.h> #include <openssl/err.h>
#define SSL_ERROR_WANT_HSM_RESULT 10
/** 是否单向认证 */ BOOL G_beOneWay = YES;
@interface JITGMSocket() { __weak id<JITSocketDelegate> _delegate; int _socketFD; NSString *_host; int _port; SSL *m_ssl; SSL_CTX *m_ctx; BOOL _isSecure; }
@property (retain, readonly) NSMutableData *sslWriteData; @property (retain, readonly) NSMutableData *sslReadData;
@end
@implementation JITGMSocket
#pragma mark -- Life Cycle - (instancetype)initWithDelegate:(id<JITSocketDelegate>)aDelegate { if (!aDelegate) return nil; self = [super init]; if(self) { _delegate = aDelegate; _sslWriteData = [[NSMutableData alloc] init]; _sslReadData = [[NSMutableData alloc] init]; } return self; }
- (void)dealloc { NSLog(@"%s",__func__); [self disconnect]; }
#pragma mark -- Socket连接服务端 - (void)connectToHost:(NSString *)host onPort:(int)port { _host = host; _port = port; if (!host || !port) { [self closeWithError:[self otherError:@"host/port error"]]; return; } /* 1.初始化socket a.参数domain指明通信域,如PF_UNIX(unix域),PF_INET(IPv4),PF_INET6(IPv6)等 b.type 指明通信类型,最常用的如SOCK_STREAM(面向连接可靠方式, 比如TCP)、 SOCK_DGRAM(非面向连接的非可靠方式,比如UDP)等。 SOCK_STREAM 是数据流,一般是tcp/ip协议的编程,SOCK_DGRAM分是数据抱,是udp协议网络编程。 c.参数protocol指定需要使用的协议。虽然可以对同一个协议 家族(protocol family) (或者说通信域(domain))指定不同的协议 参数, 但是通常只有一个。对于TCP参数可指定为IPPROTO_TCP,对于 UDP可以用IPPROTO_UDP。你不必显式制定这个参数,使用0则根据前两个参数使用默认的协议 */ _socketFD = socket(PF_INET, SOCK_STREAM, 0); if (_socketFD == -1) { [self closeWithError:[self otherError:@"socket error"]]; return; } /* 2.向服务器发送socket连接请求 */ struct sockaddr_in connectAddr; unsigned long ulIPV4 = [self DnsToIP:[host UTF8String]]; connectAddr.sin_family = PF_INET; connectAddr.sin_port = htons(port); connectAddr.sin_addr.s_addr = (in_addr_t)(ulIPV4); memset(&(connectAddr.sin_zero),'\0',8); // 连接(0 连接成功,-1 连接失败) int result = connect(_socketFD, (struct sockaddr*)&connectAddr, sizeof(connectAddr)); if (result == 0) { // 连接成功 [self didConnect]; } else { // 连接失败 [self closeWithError:[self otherError:@"connect error"]]; } } // 域名转ip地址 - (unsigned long)DnsToIP:(const char *)pszDomainName{ unsigned long dwIP = 0; int nAdapter = 0; struct sockaddr_in sAddr; unsigned long dwError = -1;
dwIP = inet_addr(pszDomainName); if( dwIP!=INADDR_NONE && dwIP!=INADDR_ANY ) { return dwIP; }
struct hostent *pHostEnt = gethostbyname(pszDomainName); if( pHostEnt!=NULL ) { while (pHostEnt->h_addr_list[nAdapter] ) { memcpy(&sAddr.sin_addr.s_addr, pHostEnt->h_addr_list[nAdapter], pHostEnt->h_length); dwIP = sAddr.sin_addr.s_addr; nAdapter++; return dwIP; } }
struct addrinfo* pstAddrInfo = NULL; struct addrinfo* ptr = NULL; struct addrinfo stHints ; memset(&stHints, 0, sizeof(stHints));
stHints.ai_family = AF_INET; stHints.ai_socktype = SOCK_STREAM; stHints.ai_protocol = IPPROTO_TCP; getaddrinfo(pszDomainName, NULL, &stHints, &pstAddrInfo); dwError = 0; if (0 == dwError) { for (ptr = pstAddrInfo; ptr != NULL ;ptr = ptr->ai_next) { if (AF_INET == ptr->ai_family && SOCK_STREAM == ptr->ai_socktype && IPPROTO_TCP == ptr->ai_protocol) { struct sockaddr_in *pstAddr_in = (struct sockaddr_in *)ptr->ai_addr; dwIP = pstAddr_in->sin_addr.s_addr; dwError = 0; break; } } } freeaddrinfo(pstAddrInfo);
if (dwError == 0) { return dwIP; } return -1; } // 已经连接 - (void)didConnect { if (_delegate && [_delegate respondsToSelector:@selector(didConnectSocket:host:port:)]) { NSLog(@"didSecure"); [_delegate didConnectSocket:self host:_host port:_port]; } }
#pragma mark - 显示证书 - (void)showCert{ X509 * cert; char * line; cert = SSL_get_peer_certificate(m_ssl); // 如果验证不通过,那么程序抛出异常终止连接 if (SSL_get_verify_result(m_ssl) == X509_V_OK) { NSLog(@"证书验证通过\n"); if (cert != NULL) { NSLog(@"数字证书信息:\n"); line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); NSLog(@"证书:%s\n",line); free(line); // 颁发者 line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); NSLog(@"颁发者:%s\n",line); free(line); // 释放 X509_free(cert); }else { NSLog(@"无证书信息!\n"); } }else { NSLog(@"证书验证不通过\n"); } }
#pragma mark -- STL/SSL 加密通信 - (void)startSSL:(BOOL)beOneWay andSSLInfo:(JITSSLInfo *)sslInfo{ if (!_delegate) { return; } // 1.SSL初始化 // SSL 库初始化 SSL_library_init(); // 载入所有 SSL 算法 OpenSSL_add_ssl_algorithms(); // 载入所有 SSL 错误消息 SSL_load_error_strings(); /* 2.初始化SSL上下文环境(调用成功返回SSL_CTX结构体指针, 否则返回NULL) a.SSL_METHOD:代表使用的协议 SSLv2_server_method():V2标准 SSLv3_server_method():V3标准 SSLv23_server_method(): V2和V3标准 CNTLS_client_method(): 国密标准 */ if (!m_ctx) { m_ctx = SSL_CTX_new((const SSL_METHOD *)CNTLS_client_method()); } /* 3.设置SSL通信方式 */ G_beOneWay = beOneWay; // 如果是 单向认证(只需要验证SSL服务器身份,不需要验证SSL客户端身份。) if (G_beOneWay) { // 配置启不启用双向认证(SSL_VERIFY_NONE 不启用,SSL_VERIFY_PEER 启用) SSL_CTX_set_verify(m_ctx, SSL_VERIFY_NONE, NULL); } // 如果是 双向认证(要求服务器和客户端双方都有证书,客户端需要校验服务端,服务端也需要校验客户端。) else { if (!sslInfo || !sslInfo.privCertInfo || !sslInfo.caInfo) { if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"sslInfo is null"]]; } return; } /* 如果传输被阻塞,永远不要用重试来打扰应用程序: SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); */
/* 4.设置信任根证书,加载CA证书 */ NSArray *caArray = sslInfo.caInfo; for (NSString *path in caArray) { if (!path) { continue; } NSLog(@"SSL_CTX_load_verify_locations start!");
// SSL_CTX_load_verify_locations:加载信任的根证书 if (!SSL_CTX_load_verify_locations(m_ctx, (const char *)[path UTF8String], NULL)){ NSLog(@"SSL_CTX_load_verify_locations error!"); ERR_print_errors_fp(stderr); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_load_verify_locations Error"]]; } return; } NSLog(@"SSL_CTX_load_verify_locations ok!"); }
JITPrivCertInfo *privCertInfo = sslInfo.privCertInfo;
/* 5.加载自己的 证书 */ if (privCertInfo.signCertPath) { NSString *strUserCertPath = privCertInfo.signCertPath; NSLog(@"SSL_CTX_use_Key_sign_cert start!"); if (SSL_CTX_use_certificate_file(m_ctx, (const char *)[strUserCertPath UTF8String], SSL_FILETYPE_PEM) <= 0){ NSLog(@"SSL_CTX_use_Key_sign_cert error!"); ERR_print_errors_fp(stderr); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_use_Key_sign_cert Error"]]; } return; } NSLog(@"SSL_CTX_use_Key_sign_cert ok!"); }
/* 6.加载自己的 私钥 */ if (privCertInfo.signPrivPath) { NSString *strUserKeyPath = privCertInfo.signPrivPath; NSLog(@"SSL_CTX_use_Key_sign_key start!"); if (SSL_CTX_use_PrivateKey_file(m_ctx, (const char *)[strUserKeyPath UTF8String], SSL_FILETYPE_PEM) <= 0){ NSLog(@"SSL_CTX_use_Key_sign_key error!"); ERR_print_errors_fp(stderr); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_use_Key_sign_key Error"]]; } return; } NSLog(@"SSL_CTX_use_Key_sign_key ok!"); }
/* 7.加载自己 加密证书 */ if (privCertInfo.encCertPath) { NSString *strUserCertPath = privCertInfo.encCertPath; NSLog(@"SSL_CTX_use_Key_enc_cert start!"); if (SSL_CTX_use_enc_certificate_file(m_ctx, (const char *)[strUserCertPath UTF8String], SSL_FILETYPE_PEM) <= 0){ NSLog(@"SSL_CTX_use_Key_enc_cert error!"); ERR_print_errors_fp(stderr); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_use_Key_enc_cert Error"]]; } return; } NSLog(@"SSL_CTX_use_Key_enc_cert ok!"); }
/* 8.加载自己的 加密证书私钥 */ if (privCertInfo.encPrivPath) { NSString *strUserKeyPath = privCertInfo.encPrivPath; NSLog(@"SSL_CTX_use_Key_enc_key start!"); if (SSL_CTX_use_enc_PrivateKey_file(m_ctx, (const char *)[strUserKeyPath UTF8String], SSL_FILETYPE_PEM) <= 0){ NSLog(@"SSL_CTX_use_Key_enc_key error!"); ERR_print_errors_fp(stderr); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_use_Key_enc_key Error"]]; } return; } NSLog(@"SSL_CTX_use_Key_enc_key ok!"); } /* 9.客户端验证 证书和私钥 是否一致(成功返回1) 验证导致握手失败? */ NSLog(@"SSL_CTX_check_private_key start!"); if (SSL_CTX_check_private_key(m_ctx) != 1) { ERR_print_errors_fp(stderr); NSLog(@"SSL_CTX_use_Key_sign_key error!"); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_check_private_key Error"]]; } } NSLog(@"SSL_CTX_check_private_key ok!"); /* 10.检查用户私钥是否正确 真正进行验证,一定要调用这个函数不然前面四个光配置而已并不会进行双向验证) */ NSLog(@"SSL_CTX_check_private_key start!"); if (!SSL_CTX_check_private_key(m_ctx)) { NSLog(@"SSL_CTX_check_private_key error!"); ERR_print_errors_fp(stderr); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_CTX_check_private_key Error"]]; } return; } NSLog(@"SSL_CTX_check_private_key ok!");
// 11.初始化SSL安全通信的对象(为一个新SSL链接建立SSL*结构体变量。) if (!m_ssl) { m_ssl = SSL_new(m_ctx); } // 12.将SSL对象和文件描述符关联起来 int result = SSL_set_fd(m_ssl, _socketFD); if (result == -1) { if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"SSL_set_fd Error"]]; return; } } /* 13.SSL_CTX_set_verify:配置启用双向认证 1、SSL_VERIFY_PEER:要求对证书进行认证,表示需要验证服务器端,没有证书也会放行,若不需要验证则使用 SSL_VERIFY_NONE 2、SSL_VERIFY_FAIL_IF_NO_PEER_CERT:要求客户端需要提供证书,但验证发现单独使用没有证书也会放行 */ SSL_CTX_set_verify(m_ctx, SSL_VERIFY_PEER, NULL); SSL_set_verify(m_ssl, SSL_VERIFY_PEER, NULL); /* 14.设置加密套件 */ if (sslInfo.ciperSuite == 0) { SSL_set_cipher_list(m_ssl,"ECC-SM4-SM3"); } else { SSL_set_cipher_list(m_ssl,"ECDHE-SM4-SM3"); } } /* 15.SSL握手 */ [self sslHandshake]; } // SSL握手 - (void)sslHandshake { int ret = 0; // 初始化SSL协商处理 SSL_set_connect_state(m_ssl); while (1){ // 实现握手 ret = SSL_do_handshake(m_ssl); if (ret > 0) { break; } else { ERR_print_errors_fp(stderr); // SSL_get_error:获取错误码 if (SSL_get_error(m_ssl, ret) == SSL_ERROR_WANT_HSM_RESULT) { continue; } else { NSLog(@"error of ssl do handshake"); break; } } } // 握手失败 if(ret <= 0) { NSLog(@"handshake failed"); if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:[self sslError:@"handshake failed"]]; } } // 握手成功 else { NSLog(@"ssl connect ok"); // 握手成功的回调 [self didSSLHandshake]; // 显示证书 [self showCert]; } } // 关闭连接 - (void)disconnect{ if(_socketFD > 0){ close(_socketFD); _socketFD = 0; }
if(m_ssl != NULL){ SSL_shutdown(m_ssl); SSL_free(m_ssl); m_ssl = NULL; }
if (m_ctx != NULL) { SSL_CTX_free(m_ctx); m_ctx = NULL; } } // 已经SSL握手 - (void)didSSLHandshake { _isSecure = YES; NSError * error = nil; if (_delegate && [_delegate respondsToSelector:@selector(didSecure:error:)]) { [_delegate didSecure:self error:error]; } }
#pragma mark -- 向网关写数据 - (int)writeData:(char *)buff andLen:(int)len andTimeOut:(int)timeout{ int ret = -100; if (!buff || !len) { [self didWriteOrReadError:[self wOrRError:@"parameter error"]]; return ret; } struct timeval sendtimeout = {0,0}; if (timeout > 0) { sendtimeout.tv_sec = timeout/1000; sendtimeout.tv_usec=(timeout%1000)*1000; setsockopt(_socketFD, SOL_SOCKET, SO_SNDTIMEO, (const void *)(&sendtimeout), sizeof(struct timeval)); } if (m_ssl) { ret = SSL_write(m_ssl, (const void *)buff, len); } else { ret = (int)send(_socketFD, buff, (size_t)len, 0); } if (ret > 0) { [self _didWrite]; } else { [self didWriteOrReadError:[self wOrRError:@"write failed"]]; } return ret; } // 写成功的代理回调 - (void)_didWrite { if (_delegate && [_delegate respondsToSelector:@selector(didWriteData:)]) { [_delegate didWriteData:self]; } }
#pragma mark - 从网关读数据 - (int)readData:(char *)buff andLen:(int)len andTimeOut:(int)timeout{ int ret = -100; if (!buff || !len) { [self didWriteOrReadError:[self wOrRError:@"parameter error"]]; return ret; } // 设置超时时间 struct timeval receiveTimeout = {0,0}; if (timeout > 0) { receiveTimeout.tv_sec = timeout/1000; receiveTimeout.tv_usec=(timeout%1000)*1000; setsockopt(_socketFD, SOL_SOCKET, SO_RCVTIMEO, (const void *)(&receiveTimeout), sizeof(struct timeval)); }
if (m_ssl) { ret = SSL_read(m_ssl, buff, len); } else { ret = (int)recv(_socketFD, buff, len, 0); }
if (ret == -1) { NSString *strErr = [NSString stringWithFormat:@"read failed, ssl code = [%d]", SSL_get_error(m_ssl, ret)]; [self didWriteOrReadError:[self wOrRError:strErr]]; } else { int err = SSL_get_error(m_ssl, ret); NSLog(@"err:%d",err); /* ret:0 表示被关闭了 ret:大于0 表示接收到数据 */ NSData *data = [NSData dataWithBytes:buff length:ret]; [self _didRead:data]; } return ret; } // 从网关读数据成功的代理回调 - (void)_didRead:(NSData *)data { if (_delegate && [_delegate respondsToSelector:@selector(didReadSocket:data:)]) { [_delegate didReadSocket:self data:data]; } }
#pragma mark - 读/写错误的代理回调 - (void)didWriteOrReadError:(NSError *)error { if (_delegate && [_delegate respondsToSelector:@selector(didWriteOrRead:error:)]) { [_delegate didWriteOrRead:self error:error]; } }
#pragma mark -- 关闭socket连接 - (void)closeWithError:(NSError *)error { close(_socketFD); _socketFD = -1; if (_delegate && [_delegate respondsToSelector:@selector(didDisconnectSocket:error:)]) { [_delegate didDisconnectSocket:self error:error]; } }
#pragma mark -- Error - (NSError *)otherError:(NSString *)errMsg { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; return [NSError errorWithDomain:@"SocketErrorDomain" code:5 userInfo:userInfo]; }
- (NSError *)wOrRError:(NSString *)errMsg { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; return [NSError errorWithDomain:@"SSLWriteOrReadErrorDomain" code:6 userInfo:userInfo]; }
- (NSError *)sslError:(NSString *)errMsg { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; return [NSError errorWithDomain:@"SSLErrorDomain" code:7 userInfo:userInfo]; }
@end
@implementation JITSSLInfo
- (instancetype)init { self = [super init]; if (self) { _ciperSuite = 0; _caInfo = @[]; _privCertInfo = [[JITPrivCertInfo alloc] init]; } return self; }
@end
@implementation JITPrivCertInfo
- (instancetype)init { self = [super init]; if (self) { _signCertPath = nil; _signPrivPath = nil; _encCertPath = nil; _encPrivPath = nil; } return self; }
@end
|