SSL Client certificate verification on linphone - android

I was implementing secure calling from asterisk official site tutorial
And after a lot of effort and understanding of ssl and certificates, I have managed to secure it only 1 way.
Following was the best clue and direction:
SSL using self signed certs on linphone
How can I make use of client certificates (which the above tutorial generated) to validate clients also on server; called full ssl authentication
I read about this setting in linphonerc file: "verify_client_certs=1" but I don't know where to put client certs?

Hi you can check on our wiki to more information about client certificats.
https://wiki.linphone.org/wiki/index.php/Security:ClientCertAuth
Security:ClientCertAuth
1. Creating Client certificate
Generate a Certificate Signing Request
Creates a new private key and a certificate request with CN=username#domain
example test#test.linphone.org
openssl req -new -keyout key.pem -out newreq.pem
Sign the client certificate
Creates newcert.pem certificate signed by root certificate. You will need to enter the passphrase of the cacert.pem
openssl ca -policy policy_anything -out newcert.pem -infiles newreq.pem
Then extract the private key in a new file
openssl rsa -in key.pem -out clientkey.pem
Parameters for linphone
In linphonerc add path to client/key certificate
[sip]
client_cert_chain=/pathTo/newcert.pem
client_cert_key=/pathTo/clientkey.pem

Please, confirm where in following command we use cacert.pem
openssl ca -policy policy_anything -out newcert.pem -infiles newreq.pem
also i have trying to use self signed ca certficate to setup asterisk with linphone. But i could'nt figure where in linphone app i have to put the client cert or even would it work if i just add my rootca.pem to the rootca.pem in the provided source for linphone-android

Related

One self-signed cert to rule them all? Chrome, Android, and iOS

Yet another self-signed cert question, but I've tried for several days to find the best/correct way to create a self-signed cert that will work in my development environment for the latest versions of Chrome, Android, and iOS.
The instructions I've found here and elsewhere are outdated for at least one of these platforms.
Here is the best I've found, but it only works with Chrome and Android.
openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 -subj "/C=US/ST=Oklahoma/L=Stillwater/O=My Company/OU=Engineering" -keyout ca.key -out ca.crt
openssl genrsa -out "test.key" 2048
openssl req -new -key test.key -out test.csr -config openssl.cnf
openssl x509 -req -days 3650 -in test.csr -CA ca.crt -CAkey ca.key -CAcreateserial -extensions v3_req -extfile openssl.cnf -out test.crt
openssl x509 -inform PEM -outform DER -in test.crt -out test.der.crt
Contents of openssl.cnf:
[req]
default_bits = 2048
encrypt_key = no # Change to encrypt the private key using des3 or similar
default_md = sha256
prompt = no
utf8 = yes
# Specify the DN here so we aren't prompted (along with prompt = no above).
distinguished_name = req_distinguished_name
# Extensions for SAN IP and SAN DNS
req_extensions = v3_req
# Be sure to update the subject to match your organization.
[req_distinguished_name]
C = US
ST = Oklahoma
L = Stillwater
O = My Company
OU = Engineering
CN = test.com
# Allow client and server auth. You may want to only allow server auth.
# Link to SAN names.
[v3_req]
basicConstraints = CA:TRUE
subjectKeyIdentifier = hash
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, serverAuth
subjectAltName = #alt_names
# Alternative names are specified as IP.# and DNS.# for IP addresses and
# DNS accordingly.
[alt_names]
DNS.1 = test.com
After installing test.crt and test.key on my development server, this method works great for Chrome: just added test.crt to my Mac's keychain and turned on "Always Trust" for it.
It also works great for Android: emailed test.der.crt to the device and tapped it to install. Most important: it showed up in the "USER" tab under Settings / Encryption & credentials / Trusted credentials. This is essential for using networkSecurityConfig in my Android app.
Unfortunately it didn't work for iOS:
I installed it in an Xcode simulator by dragging the certificates to it.
I had to install both test.crt and ca.crt. If I just installed test.crt, it remained in "unverified" status, which makes sense since the ca.crt is the root certificate.
It did not show up under Settings / About / Certificate Trust Settings which is required for me to turn it on.
When my app tries to access my server with NSMutableURLRequest, it gets a "TIC SSL Trust Error" with 10 key-value pairs, including:
NSURLErrorFailingURLPeerTrustErrorKey=
_kCFStreamErrorDomainKey=3
_kCFStreamErrorCodeKey=-9813
NSErrorPeerCertificateChainKey=1 element, and NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “test.com” which could put your confidential information at risk.
Any idea how to change what I did so I can turn it on for iOS under "Certificate Trust Settings"?
Note 1: Since other answers to other questions about the -9813 error code suggested there may be a missing intermediate certificate, I added ca.crt to my Apache configuration for the SSLCaCertificateFile setting. It still worked fine for Chrome and Android, but had exactly the same error in iOS.
Thanks!
This answer has been updated (and simplified) to be compatible with iOS 13 and Android 8. Credit now goes to https://discussions.apple.com/thread/250666160 answer by user:fixitnowyes on October 6, 2019.
Just one openssl command works to create a self-signed certificate that works in Chrome, Android, and iOS:
openssl req -config openssl.cnf -new -x509 -days 825 -out ca.crt
This outputs both ca.crt and ca.key. Note that 825 days is the maximum duration allowed by iOS 13+, and it must be specified in the openssl command. The days setting in openssl.cnf does not do anything that I can tell.
Check information about the certificate with:
openssl x509 -in ca.crt -text -noout
Contents of openssl.cnf:
[ req ]
default_bits = 2048
default_keyfile = ca.key
default_md = sha256
default_days = 825
encrypt_key = no
distinguished_name = subject
req_extensions = req_ext
x509_extensions = x509_ext
string_mask = utf8only
prompt = no
# The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
# Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
[ subject ]
countryName = US
stateOrProvinceName = Oklahoma
localityName = Stillwater
organizationName = My Company
OU = Engineering
# Use a friendly name here because it's presented to the user. The server's DNS
# names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
# by both IETF and CA/Browser Forums. If you place a DNS name here, then you
# must include the DNS name in the SAN too (otherwise, Chrome and others that
# strictly follow the CA/Browser Baseline Requirements will fail).
commonName = test.com
emailAddress = me#home.com
# Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
[ x509_ext ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
# You only need digitalSignature below. *If* you don't allow
# RSA Key transport (i.e., you use ephemeral cipher suites), then
# omit keyEncipherment because that's key transport.
basicConstraints = critical, CA:TRUE
keyUsage = critical, digitalSignature, keyEncipherment, cRLSign, keyCertSign
subjectAltName = DNS:test.com
extendedKeyUsage = serverAuth
# RFC 5280, Section 4.2.1.12 makes EKU optional
# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
# In either case, you probably only need serverAuth.
extendedKeyUsage = TLS Web Server Authentication
# Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
[ req_ext ]
subjectKeyIdentifier = hash
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = DNS:test.com
nsComment = "OpenSSL Generated Certificate"
# RFC 5280, Section 4.2.1.12 makes EKU optional
# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
# In either case, you probably only need serverAuth.
# extendedKeyUsage = serverAuth, clientAuth
# [ alternate_names ]
# DNS.1 = example.com
# DNS.2 = www.example.com
# DNS.3 = mail.example.com
# DNS.4 = ftp.example.com
# Add these if you need them. But usually you don't want them or
# need them in production. You may need them for development.
# DNS.5 = localhost
# DNS.6 = localhost.localdomain
# DNS.7 = 127.0.0.1
# IPv6 localhost
# DNS.8 = ::1
After creating the certificates...
Server installation:
Install ca.crt and ca.key in your server.
Restart server.
Chrome / Safari installation:
Add ca.crt to your Mac's KeyChain Access in the System keychain (or PC equivalent).
Set it to "Always Trust" (in Mac) so that it works in Chrome and Safari.
iOS device installation:
Send ca.crt to your device and download it to Files
Go to Files and open ca.crt
Go to General / VPN & Device Management, find your cert (listed by domain), and install it
Go to General / About / Certificate Trust Settings and turn on the certificate
iOS Xcode simulator installation:
Drag ca.crt to the simulator. Note that there is no confirmation that anything happened.
There should be no need to go to Settings / General / About / Certificate Trust Settings and enable it. It should be already enabled.
Android installation:
Email ca.crt to your Gmail account, then log into Gmail in your
Android simulator and tap to install it.
It should appear in the "USER" tab under Settings / Lock screen & security / Encryption & credentials / Trusted credentials.
I'll share my batch file for creating self signed certificates that work on Windows, iOS, Android, Chrome, FireFox and Safari. I've tested on the latest versions of Chrome, Firefox and the native browsers on mobile (Android 8.1, Latest iOS).
I found the accepted answer wasn't quite covering some scenarios - I still had to accept an exception on some mobile versions of Firefox. Although accepting the exception shows the lock icon this would cause the url to show in PWAs when installed as fullscreen or standalone modes. My goal was to support an intranet with no exceptions in order to have proper PWA installations on a private local network.
What I found covered all scenarios (real devices) tested was;
creating a CA
creating a signing request
creating a CERT with the signing request
binding the CERT to the website
installing the CA on all devices.
Note: The batch file creates a lot of files but many of them are just different formats to support different scenarios. The batch file will ask for a password several times. Don't get confused by entering multiple passwords - as the batch file progresses through steps it's always verifying the initial password created on step one. If you run into an error through a pause at the end of the batch file.
SelfCert.bat
:: Please install openssl in c:\openssl
:: The path to config should be C:\openssl\openssl.cnf
:: Otherwise you will need to add -config "path to openssl.cnf" when making requests
:: Change to current directory of batch file
cd %~dp0
:: GENERATING CA
:: 1.Generate RSA
openssl genrsa -aes256 -out ca-key.pem 4096
:: 2.Generate a public CA Cert
openssl req -new -x509 -sha256 -days 365 -key ca-key.pem -out ca.pem
:: GENERATING CERTIFICATE
:: 1. Create a RSA key
openssl genrsa -out cert-key.pem 4096
:: 2. Create a Certificate Signing Request (CSR)
openssl req -new -sha256 -subj "/CN=yourcngoeshere" -key cert-key.pem -out cert.csr
:: 3. Create a extfile with all the alternative names
:: OBSOLETE HANDLED IN C#
:: echo "subjectAltName=DNS:your-dns.record,IP:XXX.XXX.XXX.XXX" >> extfile.cnf
:: 4. Create the Certificate
openssl x509 -req -sha256 -days 365 -in cert.csr -CA ca.pem -CAkey ca-key.pem -out cert.pem -extfile extfile.cnf -CAcreateserial
:: At this point the chian is completed.Now we will create different formats for uses cases and add to trusted root.
:: 5. Create a crt for Android
openssl x509 -outform der -in ca.pem -out ca.crt
:: 6. Create a pfx for IIS, Kestrel
openssl pkcs12 -export -out cert.pfx -inkey cert-key.pem -in cert.pem -certfile ca.pem
:: 7. Add the certification to our trusted root (iOS can add crt or pem)
certutil.exe -addstore root ca.pem
:: Remember in iOS to enable the certificate after installing it
:: Settings > General > About > Certificate Trust Settings
extfile.cnf
I create this file before running the batch file but you could uncomment step 3 under GENERATING CERTIFICATE.
subjectAltName=DNS:your-dns.record,IP:XXX.XXX.XXX.XXX
Server / Client - Windows
On Windows the CA is added to the Trusted Root on the last line of the batch file certutil.exe -addstore root ca.pem.
On IIS and Kestrel I assign the cert.pfx to the website.
builder.WebHost.ConfigureKestrel(opt => { opt.ListenAnyIP(6001, listOpt => { listOpt.UseHttps(#"path to cert.pfx", "pfxpassword");});});
Client - Android
On Android I email the ca.crt. Some versions of Android seem to be picky about the type. Clicking the attachment from the email is enough to install it.
Verify it's installed by nagivating to Settings > Security & Location > Encryption & credentials > Trusted Credentials > User.
If not you may need to go to Settings > Security & Location > Encryption & credentials > Install from SD Card > Downloads
Client - iOS
On iOS I email the ca.crt or the ca.pem. Be sure to follow the prompted instructions for enabling the CA after installation.
Usually after downloading you need to go to Settings > General > Profiles > Install
After installing it you need to go to Settings > General > About > Certificate Trust Settings > Enable Certificate
Two days ago I dove into certification chains and having no experience in cryptography really hurt my brain. Major credits go to Christian Lempa. I just put his commands into a batch file and converted them to different formats at the end. Hopefully this helps someone out.

Trying to import the private key into a PKCS12 format key store, but instead I get usage note

I am following this tutorial
http://ankitagarwal.com/wordpress/2014/05/08/https-communication-between-an-android-app-and-tomcat7-using-self-signed-certificates/
and I am currently on "Create the Server’s Key Store containing its Self-Signed Digital Certificate" section.
When I do
openssl pkcs12 –export –inkey web_server_private_key.pem –in web_server_ssl_certificate.pem –out web_server_key_store.p12
I get usage information...why?
No keys are imported/generated.
Your copy/pasted example uses "fancy hyphens". Here's what happens when I run that locally:
openssl pkcs12 –export –inkey web_server_private_key.pem –in web_server_ssl_certificate.pem –out web_server_key_store.p12
(prints usage information, as in your screenshot)
And with ascii hyphens:
openssl pkcs12 -export -inkey web_server_private_key.pem -in web_server_ssl_certificate.pem -out web_server_key_store.p12
Error opening input file web_server_ssl_certificate.pem
web_server_ssl_certificate.pem: No such file or directory
So, that explains the usage information.

Android No peer certificate DefaultHttpClient

2 days I'm reading blog/answer/docs but no solution. I have a SimpleHosting on Gandi's servers with a SSL certificate https://auth.ruchers.net
As you can see, the certificate is valid.
But when I try to connect to this page with my DefaultHttpClient class I receive a [No peer certificate] error. My code is the same as you can find here : http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/
I read here Android SSL No peer certificate and here Android SSL - No Peer Certificate that the problem could be the order of the certificate chain... Ok, let's go, I'll control the chain :
openssl s_client -connect auth.ruchers.net:443
return
... no peer certificate available ...
To have a correct answer I need to specifie the servername
openssl s_client -connect auth.ruchers.net:443 -servername auth.ruchers.net
How can I say to my SSLSocketFactory to use "auth.ruchers.net" as servername for this certificate ?
Thank you for the help.
Best Regards,
Greg

PKCS#12 Keystore creation on Android device

I'm currently developing an Android app that generates an RSA key pair, builds and sends an PKCS#10 certification request to one CA, waits for the CA's response (which contains the certificate-chain including the issued for the end-entity), and then builds the PKCS#12 KeyStore to be installed within the Android KeyStore.
I just show you below some piece of code:
// It removes Android-BC
Security.removeProvider("BC");
// I've tried with SpongyCastle but it also fails.
// I've previously imported BC jars.
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance("PKCS12","BC");
ks.load(null);
// KeyPair generated by RSA with BC, and certificates obtained from CA.
PrivateKey prvK;
Certificate eeCert, caCert;
PKCS12BagAttributeCarrier caCertBagAttr =
(PKCS12BagAttributeCarrier) caCert;
caCertBagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("CA"));
PKCS12BagAttributeCarrier certBagAttr =
(PKCS12BagAttributeCarrier) eeCert;
certBagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("EE Certificate"));
certBagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
new SubjectKeyIdentifierStructure(eeCert.getPublicKey()));
Certificate[] chain = new Certificate[2];
chain[1] = caCert;
chain[0] = eeCert;
PKCS12BagAttributeCarrier privBagAttr =
(PKCS12BagAttributeCarrier) prvK;
privBagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
new DERBMPString("EE Certificate Key"));
privBagAttr.setBagAttribute(
PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
new SubjectKeyIdentifierStructure(eeCert.getPublicKey()));
// Finally, keystore is saved to file.
ks.setKeyEntry("P12", prvK, null, chain);
saveP12File(ks);
The thing is that everything is working OK when I run it on my Windows PC (BouncyCastle 1.49), but that PKCS#12 file created when I run it on Android cannot be used on SSL handshake or signing because Logcat says that it doesn't have any associated PrivateKey.
If I print the full content of the KeyStore on Java after loading the file, it seems that everything is right, but when I use on Android Browser or when I take it and install on Windows, its private key can't be used.
Same code on Android and PC, same version of BC, PKCS#12 doesn't seem to be malformed.
Can anybody help me?
Thanks in advance.
EDIT
I have built a servlet that generates an RSA Key Pair and sends back to my app in PEM format.
All seems work OK:
I can generate a valid (encrypting with public and decrypting test works good) RSA keypair either on Android device or through the external servlet.
I receive both CA and EE certificates from the CA.
I'm able to build a "valid" PKCS12 (I called it valid because it can be read by Android, Windows)
But:
I'm not able to open an SSL channel using the EE certificate as client-certificate for handshake. Either on Windows or Android.
I have uploaded to my Dropbox:
CA certificate
EE certificate issued by the CA
Private Key for the EE certificate
Public Key for the EE certificate
PKCS12 created on Android
Java Android Code
Tested against Tomcat with empty trustStore (doesnt' matter which CA issued client-certificate) unsuccessfully.
Does anybody see something that could explain it?

How to use .key and .pem file to create a socket SSL in Android?

My .key file like:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA1j6eGXbHpqigZ1K//wnuyr5v/L2jFm7dzTtHJx8ZoMQ4CbsG
My .pem file like:
-----BEGIN CERTIFICATE-----
MIIE4zCCA8ugAwIBAgIDBOziMA0GCSqGSIb3DQEBBQUAMDwxCzAJBgNVBAYTAlVT
I don't know how many steps of authenticate at here. I only want to create a ssl socket to an IP and port, and send/receive data in that socket.
I tried to use keystock, but perhaps I don't understand deep about it, I always get wrong.
Please give me a guide, or sample code.
Thanks so much.
I assume that the .key and .pem file represents your client certificate you have to use for performing an HTTPS client authentication. Unfortunately Java/Android prefers a different format, therefore I recommend you to import both file into a BKS file.
Creating a BKS file and importing existing .key+.pem file is very simple using KeyStore Explorer. After starting KeyStore Explorer select File -> New Keystore -> BKSv1. Afterwards you can execute Tools -> Import Key Pair and select the .pem file. Afterwards KeyStore Explorer will ask you for selecting the .key file.
Finally save the key store protected with a password of your choice.
The created BKSv1 file can now be used in your Android app. See for example the code posted in this question: Using client/server certificates for two way authentication SSL socket on Android
When creating a SSL connection, you just need the socket to allow the connection with your server, enabling it as a trusted source. To do so, you need to have your SSL certificate in X509 format and then create your connection as stated in this article.
Here's a guide on generating X.509 certificates.

Categories

Resources