2015-09-21 6 views
5

У меня есть приложение, которое подключается непосредственно к аппаратным маршрутизаторам. Начиная с iOS 9 Я обновил AFNetworking и теперь получаю ssl ошибки при попытке подключения через https.AFNetworking необходимо обходить проверку ssl

Это не iOS 9App Transport Security вопрос, как я добавил соответствующую .plist запись, чтобы обойти его и соединения работают отлично над http.

Мне нужно обойти проверку сертификатов, поскольку каждый маршрутизатор имеет свой собственный сертификат, поэтому я, очевидно, не могу добавить сертификаты в свое приложение, так как каждый пользователь отличается.

Я использую AFHTTPRequestOperation подкласс соединений и установить self.securityPolicy.allowInvalidCertificates = YES;, но я получаю следующее сообщение об ошибке:

Error during connection: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9806, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fa9f3611b40 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey= https://myserver.com:4780/Info.htm , NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFNetworkCFStreamSSLErrorOriginalValue=-9806, _kCFStreamPropertySSLClientCertificateState=0, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., _kCFStreamErrorDomainKey=3, NSErrorFailingURLKey= https://myserver.com:4780/Info.htm , _kCFStreamErrorCodeKey=-9806}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey= https://myserver.com:4780/Info.htm , NSErrorFailingURLStringKey= https://myserver.com:4780/Info.htm , _kCFStreamErrorDomainKey=3}

Я также попытался добавить setWillSendRequestForAuthenticationChallengeBlock: однако блок никогда не вызывается.

Может кто-нибудь помочь?

Благодаря

EDIT ----- Установка self.securityPolicy.validatesDomainName = NO; также не работает. Интересно, не проблема с типом сертификата на оборудовании.

EDIT 2 ----- Вот свидетельство

New, TLSv1/SSLv3, Cipher is DES-CBC3-SHA Server public key is 2048 bit Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE SSL-Session: Protocol : SSLv3 Cipher : DES-CBC3-SHA Session-ID: 010000000C6B8632215649C0665E9DCC9EC59E22F8F021672B6B50B84222A342 Session-ID-ctx: Master-Key: D71EC7D8F7A4A3581E25CDAD9C532B2C7B4DA8B513AF337095496B575F525CFBA02A40797B2D2A4F0B5911EFEFC3623F Key-Arg : None Start Time: 1443102149 Timeout : 300 (sec) Verify return code: 18 (self signed certificate)

EDIT 3 -------- Добавления этого кода в мой AFHTTPRequestOperation подкласс делает его работу на прошивке 8, однако блок даже не вызывается на прошивке 9.

[self setWillSendRequestForAuthenticationChallengeBlock:^(NSURLConnection * _Nonnull connection, NSURLAuthenticationChallenge * _Nonnull challenge) 
    { 
     NSLog(@"**** HERE ****"); 
     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) 
     { 
      [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; 
     } 
     [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; 
    }]; 
+0

Что ATS Plist записей, которые вы добавили? – Paulw11

+0

'NSAllowsArbitraryLoads = True' перед добавлением этого, даже с http-соединениями не удалось. Я считаю, что ATS просто заставляет http-соединения использовать https. – Darren

+0

Хм. Этот дубликат - http://stackoverflow.com/questions/32634986/ios9-what-is-the-proper-way-to-update-afnetworking-calls-to-work-with-https-err предлагает такое же исправление, но ответ не принимается – Paulw11

ответ

1

я столкнулся с подобными проблемами и в моем случае я решил, что установка политики безопасности AFSSLPinningModeNone и, очевидно, позволяя и алидные сертификаты.

Пример в Obj-C:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 

AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; 
securityPolicy.allowInvalidCertificates = YES; 
manager.securityPolicy = securityPolicy; 

[manager POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 
    NSLog(@"Response: %@",responseObject); 
} 
failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{ 
    NSLog(@"Error: %@", error); 
}]; 
+0

Все еще не работает. Я думаю, что сертификат слишком устарел. – Darren

0

В вашем подклассе AFHTTPRequestOperation, осуществлять следующее:

- (BOOL)connection:(NSURLConnection *)connection 
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{ 

    if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 
     return YES; 
    } 

    return [super connection:connection canAuthenticateAgainstProtectionSpace:protectionSpace]; 
} 


- (void)connection:(NSURLConnection *)connection 
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 

    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 
     [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; 
     return; 
    } 

    return [super connection:connection didReceiveAuthenticationChallenge:challenge]; 
} 
+0

Я добавил их и добавил журнал, и их даже не вызывают. – Darren

+0

https://github.com/AFNetworking/AFNetworking/issues/388 –

+0

Кажется, что методы были устаревшими. Я попытался добавить протокол, но они все еще не вызывались. – Darren

1

От Apple's documentation:

Default Behavior

All connections using the NSURLConnection, CFURL, or NSURLSession APIs use App Transport Security default behavior in apps built for iOS 9.0 or later, and OS X v10.11 or later. Connections that do not follow the requirements will fail. For more information on various the connection methods, see NSURLConnection Class Reference, CFURL Reference, or NSURLSession Class Reference.

These are the App Transport Security requirements:

The server must support at least Transport Layer Security (TLS) protocol version 1.2. Connection ciphers are limited to those that provide forward secrecy (see the list of ciphers below.) Certificates must be signed using a SHA256 or greater signature hash algorithm, with either a 2048-bit or greater RSA key or a 256-bit or greater Elliptic-Curve (ECC) key. Invalid certificates result in a hard failure and no connection. These are the accepted ciphers:

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

Вы можете обновить параметры безопасности на вашем оборудовании должны быть совместимы с выше и/или r установить NSExceptionMinimumTLSVersion на TLSv1.0

+0

К сожалению, аппаратное обеспечение не может быть обновлено. Приложение подключается к домашним маршрутизаторам пользователей. – Darren

+0

Несомненно, отключение ATS с использованием записи plist должно переопределить все элементы ATS? – Darren

+0

не отключить, установите вместо него минимальную принятую версию. –

0

Чтобы разрешить недействительный сертификат SSL с AFNetworking. Добавьте следующую строку в AFURLConnectionOperation.h ниже #import Availability.h

определяют _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 1

+0

Начиная с версии 1.2.1 вам больше не нужно устанавливать это определение. Вместо этого вы можете установить свойство allowIDvalidSSLCertificate для YES на AFHTTPRequestOperation, что гораздо удобнее –

+1

[Менеджер AFHTTPRequestOperationManager] .securityPolicy.allowInvalidCertificates = YES; В AFNetworking 2.0 вы можете использовать следующее: –

1
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; 
securityPolicy.allowInvalidCertificates = YES; 
manager.securityPolicy = securityPolicy; 
+2

вы можете отредактировать свой ответ, вместо добавления дополнительного ... – Miknash

+0

я удалил еще один ответ. –

+0

Я пробовал это, и он все еще терпит неудачу. – Darren

Смежные вопросы