Ignore ssl certification MKNetworkKit - ios

So it seems that ASIHTTPRequest allows you to ignore the certificates on https:// endpoints. I'm currently using MKNetworkKit and have implemented all my calls. Unfortunately, our testing server is on https but does not have a SSL certificate.
I'm able to connect fine using a curl with the -k command. I've tried various things in MKNetworkKit to ignore the NSURLAuthenticationChallenge, but to no avail. The latest thing I tried was the following:
op.authHandler = ^(NSURLAuthenticationChallenge *challenge)
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:_userName password:password persistence:NSURLCredentialPersistenceNone];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
};
This allowed me to actually get a 401 error returned (instead of being blank). Looking at the curl string, MKNetworkKit strips my username/password when the above block hits. I'm not sure if that's progress or not.
Anyone know how to simply ignore the SSL certificate?
Edit:
I had to update MKNetwork kit to get the new method ShouldContinueWithInvalidCertificate on MKNetworkOperation and my testing server got the certError fixed.
However, now I'm having a weird error happening. I'm still unable to get any return from two specific endpoints on the server. I look at the request, copy it into the command as a curl, and it immediately returns results. I'm not getting an error either from the operation.
What's happening here?

The MKNetworkOperation class has a property called shouldContinueWithInvalidCertificate which is defaulted to NO. All you have to do is set it to YES, and it will ignore the certs.
The comments:
/*!
* #abstract Boolean variable that states whether the operation should continue if the certificate is invalid.
* #property shouldContinueWithInvalidCertificate
*
* #discussion
* If you set this property to YES, the operation will continue as if the certificate was valid (if you use Server Trust Auth)
* The default value is NO. MKNetworkKit will not run an operation with a server that is not trusted.
*/

Related

didReceiveAuthenticationChallenge called multiple times

I'm doing a SSL pinning check for a website and I need to tap into the didReceiveAuthenticationChallenge in order to do so. However when I am debugging the application I noticed that the challenge is being called 3 times before finishing and afterwards I end up with NSURLErrorDomainCode=-999.
Small snippet of how my code looks:
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
{
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
What I found odd is that on the third attempt the certificate on the bottom line of the snippet, is returning nil. But for the first 2 runs it is returning the same server certificate again.
Is this a normal behaviour from this method? The server only has one certificate installed that I am comparing against. I don't know if it might be relevant to add that I am using the React-Native-Webview solution for my application.

The certificate for this server is invalid

I know that if I use following nsurlconnectiondelegate it will be fixed
– connection:willSendRequestForAuthenticationChallenge: –
connection:canAuthenticateAgainstProtectionSpace
But I am trying to use
sendAsynchronousRequest:queue:completionHandler:
So you don't get the callback. I looked into apple docs it say following
If authentication is required in order to download the request, the required credentials must be specified as part of the URL. If authentication fails, or credentials are missing, the connection will attempt to continue without credentials.
I could not figure out how to do that. When I looked up all I got is this private call
+(void)setAllowsAnyHTTPSCertificate:(BOOL)inAllow forHost:(NSString *)inHost;
Any idea how to do this?
Following is the error I get
The certificate for this server is invalid. You might be connecting to
a server that is pretending to be “example.com=0x8b34da0
{NSErrorFailingURLStringKey=https://example.com/test/,
NSLocalizedRecoverySuggestion=Would you like to connect to the server
anyway?, NSErrorFailingURLKey=https://example.com/test/,
NSLocalizedDescription=The certificate for this server is invalid. You
might be connecting to a server that is pretending to be “example.com”
which could put your confidential information at risk.,
NSUnderlyingError=0xa26c1c0 "The certificate for this server is
invalid. You might be connecting to a server that is pretending to be
“example.com” which could put your confidential information at risk.",
NSURLErrorFailingURLPeerTrustErrorKey=
The webserver which you are using is asking for Server Trust Authentication, you need to properly respond with the appropriate action. You need to implement connection:willSendRequestForAuthenticationChallenge: delegate method and use SecTrustRef to authenticate it.
More information can be found here:-
https://developer.apple.com/library/ios/technotes/tn2232/_index.html
This was my code to fix error:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLProtectionSpace *protectionSpace = [challenge protectionSpace];
id<NSURLAuthenticationChallengeSender> sender = [challenge sender];
if ([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
SecTrustRef trust = [[challenge protectionSpace] serverTrust];
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
[sender useCredential:credential forAuthenticationChallenge:challenge];
}
else
{
[sender performDefaultHandlingForAuthenticationChallenge:challenge];
}
}
Try this.
Initiate your session using custom session config as shown below:
let session = URLSession(configuration: URLSessionConfiguration.ephemeral,
delegate: self,
delegateQueue: nil)
Implement the following delegate callback method:
public func urlSession(_: URLSession, task _: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let serverTrust = challenge.protectionSpace.serverTrust else {
return completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
return completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
}
If you are using AFNetworking, you can use this code:
(Just as a temp client-side solution!)
AFHTTPSessionManager * apiManager = [AFHTTPSessionManager initWithBaseURL:[NSURL URLWithString:baseURL];
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
policy.allowInvalidCertificates = YES;
apiManager.securityPolicy = policy;
you can't fix it with the way you are trying
either drop to CFNetworking to allow bad certs
use NSConnection with a delegate and an undoc'd method
use the private API you found
all not good. CFNetwork would have to be OK for apple for now but the other 2 methods aren't even appstore-safe
Better get the server fixed. Thats the easiest and CLEANEST
This issue cannot be fixed with the way you are trying with blocks. you need to set delegates and implement the authentication challenge delegates to bypass the certificate validation.
Best solution is to either create a right certificate (make sure it is not self-signed) or change the protocol to HTTP if you are fine with it.
In my case, this error occurred due to my firewall blocked the required url. it's worked fine after removing firewall restrictions
That is a certificate error. you need to change your settings so that your program/os ignores the certificate, or add the url/certificate to a trusted list.
Sorry that is authentication, certificate is authentication. I took a look, and I found this article.
Not sure if it will resolve your issue, but it basically states, that they don't cover the case of connecting to a site with how a certificate in the documentation.
http://www.cocoanetics.com/2009/11/ignoring-certificate-errors-on-nsurlrequest/
In my case, this error occurred due to my system date. It was set as an old date, and the certificate is not effective from that old date. After correct the date, it works.

initWithContentsOfURL returns nil only in iOS 5.x [duplicate]

I have been stuck with this for a while and don't seem to get around this.
I am trying to read the contents of an URL as a string from an URL, But i get a weird
Error -> Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
My code :
fetchedString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"www.example.com/iphone"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#",fetchedString);
// if there is something wrong with the URL
if (error) {
NSLog(#"Error -> %#", error);
return ;
}
What am I doing wrong? I tried using getting as NSData as well, but I get null back.
Yes, the URL is missing the scheme: "http://".
"Error -> Error Domain=NSCocoaErrorDomain Code=256"
For the error code check the Apple documentation:
NSError codes in the Cocoa error domain.
NSFileReadUnknownError = 256,
NSFileReadUnknownError
"Read error, reason unknown"
Not that the error definition is very helpful. :-)
Also do not check if error is nil to determine if there is an error, check the return value for nil. error is not guaranteed to be nil on successful execution.
I had a similar problem accessing files located on my device. I followed NSURL isFileURL always returns NO
and used [NSURL fileURLWithPath] instead of [NSURL URLWithString] - this worked!
I got this error (Error Domain=NSCocoaErrorDomain Code=256) as soon as our ssl certificate expired. that may not help you but could help someone else.
Sandboxing
If you're using sandboxing in your app, you might want to check that com.apple.security.network.client is set to YES. It's in the the General tab of your Target in Xcode 5 under
Network: Outgoing Connections (Client)
Also be aware that if you see a code 257 when trying to reach a file:/// url, that's also probably because of sandboxing, but this time rather the File Access part. Because I didn't want to open it to anything else than `com.apple.security.files.user-selected.read-write'
User selected files
I preferred to use A Dead Simple Fileserver and use http://localhost:3000 when in Debug mode.
More reasons that might be causing this specific error:
SSL is misconfigured on the server
The server redirects (301) the http URL to https (see #1)
App transport security also uses this code for blocked requests.
I got the same error. The above marked answer is perfect. But in my case, I had the "http://" in the url but had to add the port number in the url request since there is a service running on a specific port that is actually responding to your request.
#"http://example.com:8084/yyy.zzz"
I got the same error, the above solution didn't work for me, in my case i was calling dataWithContentsOfURL from within a UNNotificationServiceExtension so i had to update the info.plist file of the UNNotificationServiceExtension with the app transport security entries.

NSData dataWithContentsOfURL:options:error: invalid server response

We've generally had success loading JSON-encoded data from our server using:
NSError* error;
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]
options:NSDataReadingUncached
error:&error];
(On a background thread to avoid blocking the main thread.) But, with increasing server load, we've recently seen an invalid but non-error (error == nil) server response of:
<html><body><script>document.cookie='ggggggg=00268082ggggggg_00268082;
path=/';window.location.href=window.location.href;</script></body></html>
A retry will often result in successful download of expected JSON-encoded data; the problem appears to be server-side. Three questions:
1) Does anyone recognize this server response?
2) Is our server attempting to create a cookie instead of returning our file/data!?
3) If so, where should we be looking to understand how to avoid this random cookie response from our server?
Based on message board traffic, we were able to confirm that the problem could be reproduced by a variety of means (app, browser, or command line) -- the issue had nothing to do with iOS or our application code. We were able to sporadically reproduce the problem from the command line with curl using the form:
curl -D - your-test-url-here -s
After further investigation by our ISP, they determined that the most likely cause of the invalid HTTP response was from their DDoS attack protection. After they reset the affected server(s), the problem was resolved.

ios - Restkit and SSL certificate error

I have a tomcat server that uses a self signed SSL certificate and is running a web service. I am trying to connect to the web service with Restkit. However, I am getting an error related to certificate validity. Here is my code:
NSURL *url=[NSURL URLWithString:baseURL];
RKClient *client = [RKClient clientWithBaseURL:url];
client.disableCertificateValidation=YES;
RKRequest *request = [client requestWithResourcePath:[NSString stringWithFormat:#"/addEvent?deviceID=%#&eventID=%#",deviceID,eventID]];
request.disableCertificateValidation=YES;
request.delegate=self;
RKResponse *response = [request sendSynchronously];
This request fails with the following error:
2013-01-09 15:11:53.931 Mobile_ACPL[5761:907] The certificate for this server is invalid. You might be connecting to a server that is pretending to be “notify.acpl.lib.in.us” which could put your confidential information at risk.
I get this error even though I have set disableCertificateValidation to YES. How can I get this working?
EDIT: I attempted adding the certificate as shown here: https://github.com/RestKit/RestKit/pull/131
I still get the same result.
EDIT 2: It looks like the error message is being set at this line in RKRequest.m:
payload = [NSURLConnection sendSynchronousRequest:_URLRequest returningResponse:&URLResponse error:&error];
NSURLConnection does not cater for authentication challenges in synchronous calls. You need to make asynchronous calls for this to work.
In my case, I was setting disableCertificateValidation on RKClient but I was using a RKObjectManager which used a different RKClient. The following line, placed after the RKObjectManager initialization, did the trick:
[RKObjectManager sharedManager].client.disableCertificateValidation = YES;
if you are using RestKit using
client.allowsInvalidSSLCertificate = YES;
won't work, instead do this:
if you added rest kit manually to your project, click on RestKit.xcodeproj go to project > Build Settings > Preprocessor Macros
and add _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_=1
thats finished.

Resources