AFNetworking 2.2 SSL pinning with self-signed certificate - ios

I want to prevent my app/server communication from a MITM attack so I am trying to setup SSL pinning, but I am having problems getting it working with AFNetworking 2.2, using a self-signed certificate. I think it's mostly a problem with how I am generating the certificate.
I first tried generating a self-signed certificate according to these instructions:
Generating the private key:
sudo openssl genrsa -des3 -out server.key 2048
Generating the Signing Request, and using the domain name when asked for the Common Name:
sudo openssl req -new -key server.key -out server.csr
Generating the certificate:
sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Finally, converting it to der format (since AFNetworking requires it)
sudo openssl x509 -outform der -in server.crt -out server.der
The server is Ubuntu 12.04, running ngninx+passenger to serve up a Rails 4 app. Here is the bit of my nginx server config to turn on SSL:
server {
listen 80;
listen 443;
server_name myapp.com;
passenger_enabled on;
root /var/www/myapp/current/public;
rails_env production;
ssl on;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
}
After restarting nginx, downloading the der file, adding it to my project, and renaming it "server.cer" (since AFNetworking requires the certificate to use the .cer extension), I use this code to turn on SSL pinning for my AFHTTPSessionManager subclass:
client.securityPolicy = [AFSecurityPolicy
policyWithPinningMode:AFSSLPinningModeCertificate];
Then, with the first request to the server AFNetworking attempts to verify that the "trust is valid in the AFServerTrustIsValid function:
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
SecTrustResultType result = 0;
OSStatus status = SecTrustEvaluate(serverTrust, &result);
NSCAssert(status == errSecSuccess, #"SecTrustEvaluate error: %ld", (long int)status);
return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
}
If I put a breakpoint at the return, I can see that the result is always kSecTrustResultRecoverableTrustFailure.
If I skip the AFServerTrustIsValid function by setting allowInvalidCertificates to YES on the security policy, then the request succeeds. But I don't really want to allow invalid certificates if I don't have to.
Back to the drawing board, this SO question lead me to this tutorial on creating a self-signed cert with also creating a CA. I setup my openssl.cnf file like so:
[ req ]
default_md = sha1
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = United Kingdon
countryName_default = UK
countryName_min = 2
countryName_max = 2
localityName = Locality
localityName_default = London
organizationName = Organization
organizationName_default = Eric Organization
commonName = Common Name
commonName_max = 64
[ certauth ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = CA:true
crlDistributionPoints = #crl
[ server ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
nsCertType = server
subjectAltName = DNS:myapp.com
crlDistributionPoints = #crl
[ crl ]
URI=http://testca.local/ca.crl
And then used these commands to generate everything. First the CA stuff:
sudo openssl req -config ./openssl.cnf -newkey rsa:2048 -nodes -keyform PEM -keyout ca.key -x509 -days 3650 -extensions certauth -outform PEM -out ca.cer
Then again the server's private key:
sudo openssl genrsa -out server.key 2048
The signing request:
sudo openssl req -config ./openssl.cnf -new -key server.key -out server.req
The certificate:
sudo openssl x509 -req -in server.req -CA ca.cer -CAkey ca.key -set_serial 100 -extfile openssl.cnf -extensions server -days 365 -outform PEM -out server.cer
And finally the der file:
sudo openssl x509 -outform der -in server.cer -out stopcastapp.com.der
When I update and restart nginx,, download and add the server.der to my project (making sure to rename it to server.cer and to reset the Simulator), I get the same exact result.
The dreaded kSecTrustResultRecoverableTrustFailure rears its ugly head again.
What am I doing wrong? Am I like WAY off on how this all works, or do I need to tweak just one little thing to get it all working? If you could help in any way I would really, really appreciate it (I've been on this problem for two days now). Thanks!

Somewhere in your code you need to specify this, or something similar. You need to tell the code to accept invalid certificates (AKA self signed).
self.allowsInvalidSSLCertificate = YES;

Related

Error: "No credentials are available in the security package" with DPS SDK

I am attempting to use the IoT SDK to communicate to DPS and then IoT Hub.
When I load a valid certificate PEM file, it looks correct in debug window shown below:
After loading the cert, I am unable to use it in the IoT SDK, getting the error below:
[note I have already configured DPS to trust the ca.cert.pem and have created an enrollment group.
My certificate is a v1, as shown below:
I am using a very simple CA from OpenSSL:
openssl genrsa -aes256 -out ca.key.pem 4096
openssl req -key ca.key.pem -new -x509 -days 3650 -sha256 -out ca.cert.pem
openssl req -nodes -new -subj /CN=device4 -sha256 -out verify.csr -keyout private.pem
openssl x509 -req -in verify.csr -CA ca.cert.pem -CAkey ca.key.pem -CAcreateserial -out public.pem -days 180 -sha256
Here is the code I am using:
certificate = X509Certificate2.CreateFromPemFile(publicKeyFileName, privateKeyFileName);
SecurityProviderX509Certificate securityProvider = new SecurityProviderX509Certificate(certificate);
ProvisioningDeviceClient = ProvisioningDeviceClient.Create(DPSURL, DPSScopeId, securityProvider, provisioningTransportHandler);
DeviceRegistrationResult registrationResult = ProvisioningDeviceClient.RegisterAsync().Result;
There appears to be an issue in the SDK. There is a workaround if you export to PFX and then import the PFX. Submitted the Bug here: https://github.com/Azure/azure-iot-sdk-csharp/issues/2150

"Add to home screen" icon not working on iOS 13 with HTTPS

With iOS 13, the "Add to Home Screen" icon is no longer populating, and remains a screenshot of the page:
Image for iOS 13 on iPad: https://i.ibb.co/StxckYP/20191017-125540.jpg
With iOS prior to 13, the icon is created normally:
Image for iOS 12 on iPod: https://i.ibb.co/JqVFZgd/20191017-125423.jpg
It appears to be a certificate issue, as it populates normally over HTTP. Also it works with a global CA signed certificates (GoDaddy). With a private CA signed certificate it does not.
Server is IIS in both cases. Page otherwise works normally over HTTPS.
Meta tag for the icon:
<link id="apple-touch-icon" rel="apple-touch-icon" href="resources/images/app-test114.png">
Batch script for creating CA:
openssl req -x509 -newkey rsa:1024 -sha256 -days 3650 -nodes -keyout ca.key -out ca.crt -config ca.conf
openssl pkcs12 -export -out ca.pfx -inkey ca.key -in ca.crt
pause
Config file for CA:
[req]
distinguished_name=information
prompt=no
x509_extensions=v3_ca
[information]
C=...
ST=...
L=...
O=...
OU=...
CN=...
[v3_ca]
subjectKeyIdentifier=hash
extendedKeyUsage=critical,serverAuth,clientAuth
basicConstraints=CA:true
keyUsage=cRLSign,keyCertSign,digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment,keyAgreement,keyCertSign,cRLSign
Batch script for creating web hosting certificate:
openssl req -newkey rsa:1024 -sha256 -nodes -keyout cert.key -out cert.csr -config cert.conf
openssl x509 -sha256 -req -in cert.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out cert.crt -days 365 -extfile cert.conf -extensions extensions
openssl pkcs12 -export -out cert.pfx -inkey cert.key -in cert.crt
pause
Config file for certificate:
[req]
distinguished_name=information
prompt=no
[information]
C=...
ST=...
L=...
O=...
OU=...
CN=...
[extensions]
subjectAltName=#alt_names
[alt_names]
DNS.1=localhost
IP.1=192.168.77.132
Prior to getting the correct certificates, when I had to allow for a certain URL to open with an unsecure https connection, the behaviour was the same. Once certificates were fixed, the icon populated normally. With update to iOS 13, icon stopped working normally.
Is there any way to find out why the icon is not loaded?
The link from Hudgi resolved the issue.
https://support.apple.com/en-us/HT210176
It was the required key size of 2048 bit, and my key was 1024 bit.
The reason the page was otherwise working is that it was cached.

2 way Secured Mosquitto MQTT error

I'm new to MQTT. I create a mosquitto broker with ssl and connect successfully. My commands to create certificates as:
openssl req -new -x509 -days durations -keyout mqtt_ca.key -out mqtt_ca.crt
openssl genrsa -des3 -out mqtt_server.key size_bits
openssl req -out mqtt_server.csr -key mqtt_server.key -new
openssl x509 -req -in mqtt_server.csr -CA mqtt_ca.crt -CAkey mqtt_ca.key -CAcreateserial -out mqtt_server.crt -days durations*
In mosquitto.conf:
port 8883
cafile your_path/mqtt_ca.crt
certfile your_path/mqtt_server.crt
keyfile your_path/mqtt_server.key
require_certificate false
tls_version tlsv1.1
But it is just one way connection. I want to set `require_certificate true but I don't know how to create client certificates and modify mosquitto.conf. Please show me how to do that. Thank you so much!
Creating a Certificate Authority is too detailed to go into here, but there are plenty of examples online e.g There are many examples of how to create your own Certificate Authority (CA) online e.g.
https://jamielinux.com/docs/openssl-certificate-authority/
For the broker certificate the CN should match the host name of the machine running the broker.
For client certificates the CN can be anything you want.
The only changes to the mosquitto.conf file will be to make sure the cafile entry points to the CA certificate you generate at the start of the instructions for setting up the CA.
If you want to enforce require_certificate true then you should probably also look at use_identity_as_username true as well to user the CN from the client certificate as the username when matching against ACLs

Error while creating iOS Developer CSR for iOS

I am trying to generate a certificate request for an iOS Developer certificate. I get the error below (Unknown option CN=...). I am able to generate the private key just fine, it is the next step - generating the cert request that is failing.
openssl req -new -key privatekey.key -out CertificateSigningRequest.certSigningRequest \
-subj “/emailAddress=myaddress#yahoo.com, CN=MyAccountName, C=US”
Results in:
Unknown Option CN=MyAccountName
The way you have formated your request is incorrect.
Use / to separate subject information. Use ' instead of "
openssl req -new -key serverkey.pem -out CertificateSigningRequest.certSigningRequest -subj '/emailAddress=myaddress#yahoo.com/CN=MyAccountName/C=US'

RSA Encryption using public key

I am writing iOS Application. Server sends RSA public key to application. Now application has to encrypt some information using RSA algorithm
Kindly provide me some reference.
Thanks
iOS has no special API for RSA, but there are some APIs about Certificate. You can use these APIs to encrypt your data by RSA.
First, you must use openssl to generate your RSA private key and public key. The most important thing is that the public key must be signed. Here is a instruction to generate the keys.
openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650
However, if you already has a private key(.pem file), you can follow the instructions:
openssl req -new -out cert.csr -key private_key.pem
openssl x509 -req -in cert.csr -out public_key.der -outform der -signkey private_key.pem -days 3650
You can check the public_key.der by opening it in xcode.
When you get the correct public_key.der file, you can view the RSA.h and RSA.m here. I'm sorry that I have no time to rewrite this post by English again.
This Pod encapsulates the encryption: https://github.com/xjunior/XRSA
I don't know much about iOS but the Certificate, Key, and Trust Services Reference seems to be what you need. It appears the SecKeyEncrypt will be used by you at some point.

Resources