尝试通过TLS和网络套接字连接到网站。连接已关闭

时间:2019-04-03 14:12:41

标签: ios objective-c websocket tls1.2

我正在尝试打开一个需要iOS证书的网站。我拥有的证书是自签名的。我能够通过证书并检索HTML内容。但是连接已关闭。我需要重新打开该连接,因为必须连接到WebSocket

也无法找到通过WebSocket传递SSL的解决方案。保持400。我正在为WebSocket使用Jetfire

下面是WebSocket调用的代码

-(void)connectToSocket{

    self.socket = [[JFRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://socket.xxx.com/websocket"] protocols:@[@"chat",@"superchat"]];
    self.socket.security = [[JFRSecurity alloc] initUsingPublicKeys:YES]; //uses the .cer files in your app's bundle
    self.socket.delegate = self;
    [self.socket connect];
}

下面是TLS的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    [self HelperSSLCertificate];     
}

-(void)HelperSSLCertificate{
   tmckUrl = @"https://socket.xx.com";
   tmckReq = [NSURLRequest requestWithURL:[NSURL URLWithString:tmckUrl]];
   NSLog(@"HelperSSLCertificate connectionWithRequest start %@", tmckReq);
   [NSURLConnection connectionWithRequest:tmckReq delegate:self];
}

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:
(NSURLProtectionSpace*)space
{
    NSLog(@"connection NSURLConnection  canAuthenticateAgainstProtectionSpace ");
    return [[space authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:
(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"connection NSURLConnection  connection  didReceiveAuthenticationChallenge");

    NSLog(@"challenge.protectionSpace.host  == socket.xx.com");
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

    return [[challenge sender] cancelAuthenticationChallenge: challenge];
}

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] > 0) {
        NSLog(@"Incorrect auth challenge %@", challenge);
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        return;
    }


    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CertFolder_new"];
    //  ADD TLS certificate
    NSString *path = [NSString stringWithFormat:@"%@/%@",sourcePath,@"11731-SOR-DTM-UFI-LAY.p12"];
    NSData* p12data =[[NSData alloc]init];
    p12data = [NSData dataWithContentsOfFile:path];
    CFDataRef inP12data = (__bridge CFDataRef)p12data;

    SecIdentityRef myIdentity=[self getClientCertificate:path];
    SecTrustRef myTrust;
    extractIdentityAndTrust(inP12data, &myIdentity, &myTrust);

    SecPolicyRef policy = SecPolicyCreateBasicX509();

    SecCertificateRef certificate = nil;

    SecCertificateRef certRef;
    SecIdentityCopyCertificate(myIdentity, &certRef);

    SecCertificateRef certArray[1] = { certRef };
    CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL);
    CFRelease(certRef);

    if (policy) { CFRelease(policy); }   // Done with the policy object

    SecIdentityCopyCertificate(myIdentity, &certRef);

    CFRelease(certRef);

    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray *)myCerts persistence:NSURLCredentialPersistencePermanent];
    CFRelease(myCerts);

    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];

    SecTrustRef trust = challenge.protectionSpace.serverTrust;
    NSURLCredential *cred;

    if([challenge.protectionSpace.host isEqualToString:@"socket.xx.com"] /*check if this is host you trust: */ )



    NSLog(@"challenge.protectionSpace.host  == socket.xx.com");
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

    [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"connection didFailWithError %@", error);
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    NSLog(@" connection  from line 304[%@] didReceiveData %@", connection.originalRequest.URL.absoluteString, [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

    NSString *htmlString=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"<button style=\"width: 25%\">Send</button>" withString:@"<button type=\"button\" style=\"width: 25%\" onclick=\"alert(myFunction())\">Send!</button><script>function myFunction() {                              var x = \" Value is : \" + document.getElementById(\"message\").value;return x;}</script>"];

    if([htmlString containsString:@"myFunction"])
        [webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];



    NSString *currentQuestionAnswer=[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('message').value"];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connection DidFinishLoading %@", connection.originalRequest.URL.absoluteString);
    NSLog(@"connectToSocket line 239 ");

}

和下面是控制台日志

 2019-04-03 19:46:10.339401+0530 SimpleTest[14048:1325896]   myCerts   LINE 326  connection(
    "<cert(0x7f806dd2a4e0) s: egaytan-0828 i: xx CA L3>" ) 2019-04-03 19:46:10.339519+0530 SimpleTest[14048:1325896] cred NSURLConnection  LINE 331  didReceiveAuthenticationChallenge(null) 2019-04-03 19:46:10.339628+0530 SimpleTest[14048:1325896]  LINE 288 challenge.protectionSpace.host  socket.xx.com 2019-04-03 19:46:10.339734+0530 SimpleTest[14048:1325896]  LINE 288 challenge.protectionSpace.host  socket.xx.com 2019-04-03 19:46:10.339833+0530 SimpleTest[14048:1325896] challenge.protectionSpace.host  == socket.xx.com 2019-04-03 19:46:10.974899+0530 SimpleTest[14048:1325896]  connection  from line 304[https://socket.xx.com] didReceiveData <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>TLS Testing</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="apple-touch-icon" href="/static/img/bsg-favicon.png?v=3c710eb3ed8835a5ee8b97ffd15acb9e">
--> <link rel="apple-touch-icon" href="/static/img/bsg-favicon.png?v=3c710eb3ed8835a5ee8b97ffd15acb9e" /> <link rel="shortcut icon" href="/static/img/bsg-favicon.ico?v=a53010e8b3f1d634ae855d0da0bc9dfe" type="image/x-icon" /> <!-- Latest compiled and minified JavaScript
--> </head> <body> <div style="width:100%; padding: 20px; overflow-y: scroll;"> <div id="messages"></div> <div style="padding-top: 20px;"> <form onsubmit="return sendMessage()"> <input id="message" type="text" style="width: 70%;"><button style="width: 25%">Send</button> </form> </div> <script> var ws = new WebSocket("wss://socket.xx.com/websocket"); // var ws = new WebSocket("wss://socket.xx.com/websocket"); // var ws = new WebSocket("ws://127.0.0.1:8888/websocket"); // var username = prompt("What's your name?"); var username = "NoOne" function sendMessage() { var messageInput = document.getElementById("message"); var message = messageInput.value; var payload = { "message": message, "user": username } // Make the request to the WebSocket. ws.send(JSON.stringify(payload)); // Clear the message from the input. messageInput.value = ""; return false; } ws.onmessage = function(evt) { var messageDict = JSON.parse(evt.data); // Create a div with the format `user: message`. var messageBox = document.createElement("div"); messageBox.innerHTML = messageDict.user
+ ": " + messageDict.message; document.getElementById("messages").appendChild(messageBox); }; </script> <br> <p>Server-Date/Time: <span>2019-04-03 14:16:10.812488</span> This is when the server rendered the page</p> <p>Client-Date/Time: <span id="datetime"></span> When this page was refreshed</p> <script> var dt = new Date(); document.getElementById("datetime").innerHTML = dt.toLocaleString(); </script> </body> </html> 2019-04-03 19:46:17.194727+0530 SimpleTest[14048:1325896] connection DidFinishLoading https://socket.xx.com 2019-04-03 19:46:17.194987+0530 SimpleTest[14048:1325896] connectToSocket line 239 2019-04-03 19:46:17.259929+0530 SimpleTest[14048:1325896] webViewDidStartLoad called 2019-04-03 19:46:20.581259+0530 SimpleTest[14048:1325896] webViewDidFinishLoad called 2019-04-03 19:46:21.222046+0530 SimpleTest[14048:1326404] CFNetwork SSLHandshake failed (-9807) 2019-04-03 19:46:21.223096+0530 SimpleTest[14048:1326404] TCP Conn 0x6000034ed2c0 SSLHandshake failed (-9807)
  

2019-04-03 20:31:33.394826 + 0530 SimpleTest [14849:1405924]响应   (400)=“ HTTP / 1.1 400错误的请求服务器:openresty / 1.13.6.2日期:   2019年4月3日星期三15:01:33 GMT内容类型:text / html;字符集= UTF-8   内容长度:259连接:关闭

     

400之前没有所需的SSL证书   发送

400错误   请求

没有所需的SSL证书   发送
openresty / 1.13.6.2   “ 2019-04-03 20:31:33.395768 + 0530 SimpleTest [14849:1405412] websocket   已断开连接:第103行操作无法完成。   (JFRWebSocket错误1。)

0 个答案:

没有答案
相关问题