OpenSSL: server cannot verify client certificate - c++

I am working with a legacy OpenSSL wrapper, which I intend to extend with client certificates. This wrapper contains both server and client parts, but the issue is related only to server handshake part. The problem I am facing is that the server cannot get the certificate from client.
Here are the commands which I used to generate a pair of certificates for client and server:
1) Generate Certificate Authority:
openssl req -out ca.pem -new -x509
2) Generate server certificate:
openssl genrsa -out server.key 1024
openssl req -key server.key -new -out server.req
echo "00" > file.srl
openssl x509 -req -in server.req -CA ca.pem -CAkey privkey.pem -CAserial file.srl -out server.pem
3) Generate client certificate:
openssl genrsa -out client.key 1024
openssl req -key client.key -new -out client.req
openssl x509 -req -in client.req -CA ca.pem -CAkey privkey.pem -CAserial file.srl -out client.pem
All of the certificates are placed in one folder
When I am trying to connect to server implemented by Wrapper using s_client, I got the following output:
$ openssl s_client -connect localhost:40912 -CAfile ca.pem -cert client.pem -key client.key -state
CONNECTED(00000003)
SSL_connect:before/connect initialization
SSL_connect:unknown state
SSL_connect:SSLv3 read server hello A
depth=1 C = RO, ST = Rootville, L = Rootbirgem, O = CA Limited, OU = Issuer, CN = Autorida, emailAddress = ca#ca.mil
verify return:1
depth=0 C = SR, ST = Serverstan, L = Serversaintsburg, O = Servers advanced productions, OU = Acceptors factory, CN = Servstian, emailAddress = server#internet.org
verify return:1
SSL_connect:SSLv3 read server certificate A
SSL_connect:SSLv3 read server certificate request A
SSL_connect:SSLv3 read server done A
SSL_connect:SSLv3 write client certificate A
SSL_connect:SSLv3 write client key exchange A
SSL_connect:SSLv3 write certificate verify A
SSL_connect:SSLv3 write change cipher spec A
SSL_connect:SSLv3 write finished A
SSL_connect:SSLv3 flush data
SSL3 alert read:fatal:unknown CA
SSL_connect:failed in SSLv3 read server session ticket A
3073885884:error:14094418:SSL routines:SSL3_READ_BYTES:tlsv1 alert unknown ca:s3_pkt.c:1262:SSL alert number 48
3073885884:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:177:
---
Certificate chain
0 s:/C=SR/ST=Serverstan/L=Serversaintsburg/O=Servers advanced productions/OU=Acceptors factory/CN=Servstian/emailAddress=server#internet.org
i:/C=RO/ST=Rootville/L=Rootbirgem/O=CA Limited/OU=Issuer/CN=Autorida/emailAddress=ca#ca.mil
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDMzCCAhsCAQIwDQYJKoZIhvcNAQELBQAwgYkxCzAJBgNVBAYTAlJPMRIwEAYD
VQQIDAlSb290dmlsbGUxEzARBgNVBAcMClJvb3RiaXJnZW0xEzARBgNVBAoMCkNB
IExpbWl0ZWQxDzANBgNVBAsMBklzc3VlcjERMA8GA1UEAwwIQXV0b3JpZGExGDAW
BgkqhkiG9w0BCQEWCWNhQGNhLm1pbDAeFw0xNTEwMjcxNTA3MjlaFw0xNTExMjYx
NTA3MjlaMIG4MQswCQYDVQQGEwJTUjETMBEGA1UECAwKU2VydmVyc3RhbjEZMBcG
A1UEBwwQU2VydmVyc2FpbnRzYnVyZzElMCMGA1UECgwcU2VydmVycyBhZHZhbmNl
ZCBwcm9kdWN0aW9uczEaMBgGA1UECwwRQWNjZXB0b3JzIGZhY3RvcnkxEjAQBgNV
BAMMCVNlcnZzdGlhbjEiMCAGCSqGSIb3DQEJARYTc2VydmVyQGludGVybmV0Lm9y
ZzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAy6j9ZHv/xCOqrRUXbWTE2Xht
PRPf/70Rytri4McCyjT6AO/GrDlAfD815yZPqTssRWy13sJGczoM4CPOffR7ufQR
4oMfugbX0W6kqlN7K1VpPlqtm8fb2jei5K0+tXOb7UHox13b69y0kVvArfhcUqmE
SGllcB++/Se2IIdcCOECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEA5Eot8mv6QXvG
jd8oeX/JmJzzPSOn6kGMRsyR06OnF4tALHo5EdHaTF4EBgylVuAIp7dBRrdHzU4y
XnsY+X8lPlFEUFsSEuheJmISJgKZ8GtlbjHkV2cgXFSsFeiiI6Gjzlj2aOzYQQHD
DtpOL4InjHgeDTv7JxtMZXRaQqSvIejVXki0d+FOP42H3GyqleYABDtPl7o3gOmh
b8I7aZaOj/qxR8J//nGjXmodGHmL+RKK3vJ3thgD5UWREdE87qygJ2sZEUvXsnhG
CTulJEdWShGw27xuYw26wCt2yo0VXLcYsMgJLOjUAEdW3k+TowTi4XmZN4MaudAp
KFMlb2y7jg==
-----END CERTIFICATE-----
subject=/C=SR/ST=Serverstan/L=Serversaintsburg/O=Servers advanced productions/OU=Acceptors factory/CN=Servstian/emailAddress=server#internet.org
issuer=/C=RO/ST=Rootville/L=Rootbirgem/O=CA Limited/OU=Issuer/CN=Autorida/emailAddress=ca#ca.mil
---
Acceptable client certificate CA names
/C=RO/ST=Rootville/L=Rootbirgem/O=CA Limited/OU=Issuer/CN=Autorida/emailAddress=ca#ca.mil
---
SSL handshake has read 1101 bytes and written 2149 bytes
---
New, TLSv1/SSLv3, Cipher is AES256-GCM-SHA384
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1.2
Cipher : AES256-GCM-SHA384
Session-ID:
Session-ID-ctx:
Master-Key: 4CA603347F386EB0A723BCF1F07040E0C47FAD52AE9CBCC5DCB3D329D69C8E3FB31E994DC24FBA9E8312A476A8F08905
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1445977139
Timeout : 300 (sec)
Verify return code: 0 (ok)
---
At the same time on server part SSL_accept returns -1, SSL_get_error then returns SSL_ERROR_SSL and ERR_print_errors_fp gives me a message
3080665920:error:140890B2:SSL routines:SSL3_GET_CLIENT_CERTIFICATE:no certificate returned:s3_srvr.c:3279:
I don't have any experience with cryptography or OpenSSL, so all of these errors seems really confusing for me. OpenSSL's documentation doesn't make things clear at all.
As far as I can see from s_client log, the problems is with certificates themselves, although I don't understand what exactly goes wrong. At the same time, I can successfully use these certificates with s_server application, so this is reproducible only with my implementation of server. It seems that my implementation is incomplete in some way, but I don't see a way how I can resolve the situation from here, most of the documents I found on the web avoid client certificates topic at all, and all of the error messages are cryptic.
Here's a a simplified code of the server (with omitted error checking, logging, timeouts, etc):
ctx_ = SSL_CTX_new(SSLv23_server_method());
SSL_CTX_use_certificate_file(ctx_, config.cert_file.c_str(), SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(ctx_, config.private_key.c_str(), SSL_FILETYPE_PEM);
if( !SSL_CTX_check_private_key(ctx_) )
{ /* never happens */ }
ssl_ = SSL_new(ctx_);
STACK_OF(X509_NAME)* list;
list = SSL_load_client_CA_file(config.client_ca_file.c_str());
SSL_set_client_CA_list(ssl_, list);
SSL_set_verify(ssl_, SSL_VERIFY_PEER, 0);
int flags = fcntl(fd_, F_GETFL, 0);
flags |= O_NONBLOCK;
if( fcntl(fd_, F_SETFL, flags) < 0 )
SSL_set_fd(ssl_, fd_);
while( /* not timeout */ )
{
int res = SSL_accept(ssl_);
if( res > 0) {break;}
ec = WaitAfterError(res, /* timeout */);
if( !ec.isSucceeded() )
{
return; // Returns here
}
}
Wait after error have the following implementation:
ErrorCode OpenSslWrapper::WaitAfterError( int res, long* ptimeout )
{
ErrorCode ec;
int ret = SSL_get_error(ssl_, res);
switch( ret )
{
case SSL_ERROR_WANT_READ:
WaitForFd(fd_, Consts::k_WaitRead, ptimeout);
return ec;
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
WaitForFd(fd_, Consts::k_WaitWrite, ptimeout);
return ec;
case SSL_ERROR_SYSCALL:
if( !errno ) {return ec;}
case SSL_ERROR_SSL:
// Got message here:
ERR_print_errors_fp(stderr);
ec = ErrorCode::Fail;
return ec;
default:
ec = ERR_reason_error_string(ret);
return ec;
}
}
WaitForFd is just a simple wrapper over select.

The documentation for SSL_CTX_set_client_CA_list() says:
The CAs listed do not become trusted (list only contains the names, not the complete certificates); use SSL_CTX_load_verify_locations to additionally load them for verification.

Related

Signing certificate by self signed CA

I have created selfsigned CA certificate on Ubuntu that runs on AWS . I have also created client and server certificates signed by current CA.
SSL connection is used by Mosquitto MQTT service. Unfortunatly I have Received fatal alert: unknown_ca error from client side when it tries to connect to server.
I was tested the same certificate generation procedure on my Raspberry Pi and SSL+MQTT works well.
Creating certificates:
# CA
openssl req -new -newkey rsa:2048 -keyout private/cakey.pem -out careq.pem -config ./openssl.cnf
openssl ca -create_serial -out cacert.pem -days 365 -keyfile private/cakey.pem -selfsign -config ./openssl.cnf -infiles careq.pem
# Server
openssl req -new -out server.csr -config openssl.cnf -newkey rsa:2048 -nodes -keyout server.key
openssl ca -config openssl.cnf -in server.csr -out server.crt
# Client
openssl req -new -out client.csr -config openssl.cnf -newkey rsa:2048 -nodes -keyout client.key
openssl ca -config openssl.cnf -in client.csr -out client.crt
openssl.cnf content:
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = . # Where everything is kept
certs = $dir/certsdb # Where the issued certs are kept
new_certs_dir = $certs # default place for new certs.
database = $dir/index.txt # database index file.
certificate = $dir/cacert.pem # The CA certificate
private_key = $dir/private/cakey.pem# The private key
serial = $dir/serial # The current serial number
RANDFILE = $dir/private/.rand # private random number file
crldir = $dir/crl
crlnumber = $dir/crlnumber # the current crl number
crl = $crldir/crl.pem # The current CRL
x509_extensions = usr_cert # The extentions to add to the cert
copy_extensions = copy
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = sha1 # which md to use.
preserve = no # keep passed DN ordering
policy = policy_match
[ policy_match ]
countryName = match # Must be the same as the CA
stateOrProvinceName = match # Must be the same as the CA
organizationName = match # Must be the same as the CA
organizationalUnitName = optional # not required
commonName = supplied # must be there, whatever it is
emailAddress = optional # not required
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
prompt = yes
default_bits = 2048
#default_keyfile = privkey.pem
distinguished_name = req_distinguished_name # where to get DN for reqs
attributes = req_attributes # req attributes
x509_extensions = v3_ca # The extentions to add to self signed certs
req_extensions = v3_req # The extensions to add to req's
string_mask = nombstr
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = US
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = California
localityName = Locality Name (eg, city)
localityName_default = Hawthorne
0.organizationName = Organization Name (eg, company)
0.organizationName_default = PhilNet
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = UN
commonName = Common Name (eg, YOUR name)
commonName_default = CN
commonName_max = 64
emailAddress_default = aaa#bbb.cc
emailAddress = Email Address
emailAddress_max = 64
[ req_attributes ]
[ usr_cert ]
basicConstraints=CA:false
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
#subjectAltName=email:move
subjectAltName = #alt_names
[alt_names]
IP.1 = 34.245.0.160
DNS.1 = ec2-34-245-0-160.eu-west-1.compute.amazonaws.com
[ usr_cert_has_san ]
basicConstraints = CA:false
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
[ v3_req ]
subjectAltName=email:move
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = CA:true
[ v3_ca_has_san ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = CA:true
My Java web client uses paho library for MQTT communication:
public class TestMQTT4 {
public static void main(String[] args) {
System.out.println("Starting");
String serverUrl ="ssl://ec2-34-245-0-160.eu-west-1.compute.amazonaws.com:8887";
String path= "C:\\projects\\certs\\U\\CA6\\";
String caFilePath =path+"cacert.pem";
String clientCrtFilePath = path+ "client.crt";
String clientKeyFilePath = path+ "client.key";
String mqttUserName = "b";
String mqttPassword = "b";
MqttClient client;
try {
client = new MqttClient(serverUrl, "2");
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(mqttUserName);
options.setPassword(mqttPassword.toCharArray());
options.setConnectionTimeout(60);
options.setKeepAliveInterval(60);
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
SSLSocketFactory socketFactory = getSocketFactory(caFilePath,clientCrtFilePath, clientKeyFilePath, "aaabbb");
//SSLSocketFactory socketFactory = getSocketFactory3(caFilePath);
options.setSocketFactory(socketFactory);
System.out.println("starting connect the server...");
client.connect(options);
System.out.println("connected!");
Thread.sleep(1000);
client.subscribe("aaa",0);
client.disconnect();
System.out.println("disconnected!");
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static SSLSocketFactory getSocketFactory(final String caCrtFile,
final String crtFile, final String keyFile, final String password)
throws Exception {
Security.addProvider(new BouncyCastleProvider());
// load CA certificate
X509Certificate caCert = null;
FileInputStream fis = new FileInputStream(caCrtFile);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
caCert = (X509Certificate) cf.generateCertificate(bis);
}
//System.out.println("load CA certificate certificate done :"+caCert);
// load client certificate
bis = new BufferedInputStream(new FileInputStream(crtFile));
X509Certificate cert = null;
while (bis.available() > 0) {
cert = (X509Certificate) cf.generateCertificate(bis);
}
//System.out.println("load client certificate done :"+cert);
// load client private key
PEMParser pemParser = new PEMParser(new FileReader(keyFile));
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
PrivateKey pk=null;
if (object instanceof PEMEncryptedKeyPair) {
KeyPair key;
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
System.out.println("Encrypted key - we will use provided password");
key = converter.getKeyPair(((PEMEncryptedKeyPair) object)
.decryptKeyPair(decProv));
pk = key.getPrivate();
} else
if (object instanceof PrivateKeyInfo)
{
System.out.println("got PrivateKeyInfo ");
pk = converter.getPrivateKey((PrivateKeyInfo) object);
System.out.println("algorithm "+pk.getAlgorithm() +" format " + pk.getFormat());
}else
if (object instanceof PEMKeyPair)
{
KeyPair key;
System.out.println("Unencrypted key - no password needed "+object.getClass().getName());
key = converter.getKeyPair((PEMKeyPair) object);
pk = key.getPrivate();
}
pemParser.close();
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", caCert);
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
} };
// client key and certificates are sent to server so it can authenticate
// us
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry("certificate", cert);
ks.setKeyEntry("private-key", pk, password.toCharArray(),
new java.security.cert.Certificate[] { cert });
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password.toCharArray());
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(kmf.getKeyManagers(), trustAllCerts, null);
return context.getSocketFactory();
}
}
Log:
...
....
*** CertificateVerify
Signature Algorithm SHA256withRSA
update handshake state: certificate_verify[15]
upcoming handshake states: client change_cipher_spec[-1]
upcoming handshake states: client finished[20]
upcoming handshake states: server change_cipher_spec[-1]
upcoming handshake states: server finished[20]
MQTT Con: 2, WRITE: TLSv1.2 Handshake, length = 264
update handshake state: change_cipher_spec
upcoming handshake states: client finished[20]
upcoming handshake states: server change_cipher_spec[-1]
upcoming handshake states: server finished[20]
MQTT Con: 2, WRITE: TLSv1.2 Change Cipher Spec, length = 1
*** Finished
verify_data: { 74, 211, 43, 244, 29, 37, 34, 169, 164, 170, 51, 82 }
***
update handshake state: finished[20]
upcoming handshake states: server change_cipher_spec[-1]
upcoming handshake states: server finished[20]
MQTT Con: 2, WRITE: TLSv1.2 Handshake, length = 40
MQTT Con: 2, READ: TLSv1.2 Alert, length = 2
MQTT Con: 2, RECV TLSv1.2 ALERT: fatal, unknown_ca
%% Invalidated: [Session-1, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384]
MQTT Con: 2, called closeSocket()
MQTT Con: 2, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca
MQTT Con: 2, called close()
MQTT Con: 2, called closeInternal(true)
MqttException (0) - javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca
UPD
I found difference in Signature Algorithm in log file in good connection (Raspberry Pi) and bad one (Ubuntu on AWS)
Failed (Ubuntu on AWS)
*** CertificateVerify
Signature Algorithm SHA256withRSA
Good (Raspberry Pi)
*** CertificateVerify
Signature Algorithm SHA512withRSA
Why I have different signature algorithm? In moth cases identical commands was used to create and sign certificates.
Might it be problem while communicating with Java?
UPD
I did some changes accoding to comments and now my certificates works fine.
Certificates generation proedure:
openssl req -new -newkey rsa:2048 -keyout private/cakey.pem -out careq.pem -config ./openssl.cnf -extensions v3_ca_509 -reqexts v3_ca_req -subj "/C=US/ST=California/L=Hawthorne/O=PhilNet/CN=CA/"
openssl ca -create_serial -out cacert.pem -days 365 -keyfile private/cakey.pem -selfsign -config ./openssl.cnf -extensions v3_ca_509 -infiles careq.pem
openssl req -new -newkey rsa:2048 -keyout server.key -out server.csr -config openssl.cnf -reqexts v3_server_req -nodes -subj "/C=US/ST=California/L=Hawthorne/O=PhilNet/CN=Server/"
openssl ca -config openssl.cnf -in server.csr -out server.crt
openssl req -new -newkey rsa:2048 -keyout client.key -out client.csr -config openssl.cnf -reqexts v3_server_req -nodes -subj "/C=US/ST=California/L=Hawthorne/O=PhilNet/CN=Client/"
openssl ca -config openssl.cnf -in client.csr -out client.crt
openssl.cnf file:
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = . # Where everything is kept
certs = $dir/certsdb # Where the issued certs are kept
new_certs_dir = $certs # default place for new certs.
database = $dir/index.txt # database index file.
certificate = $dir/cacert.pem # The CA certificate
private_key = $dir/private/cakey.pem# The private key
serial = $dir/serial # The current serial number
RANDFILE = $dir/private/.rand # private random number file
crldir = $dir/crl
crlnumber = $dir/crlnumber # the current crl number
crl = $crldir/crl.pem # The current CRL
#x509_extensions = usr_cert # The extentions to add to the cert
copy_extensions = copy
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = sha1 # which md to use.
preserve = no # keep passed DN ordering
policy = policy_anything
[ policy_anything ]
countryName = match
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
prompt = yes
default_bits = 2048
attributes = req_attributes
#x509_extensions = v3_ca # The extentions to add to self signed certs
#req_extensions = v3_req # The extensions to add to req's
string_mask = nombstr
[ req_attributes ]
[ v3_ca_509 ]
basicConstraints = CA:true
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
[ v3_ca_req ]
basicConstraints = CA:true
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, keyCertSign
[ v3_server_req ]
basicConstraints=CA:false
subjectKeyIdentifier=hash
subjectAltName = #alt_names_server
[alt_names_server]
IP.1 = 34.245.0.159
DNS.1 = ec2-34-245-0-159.eu-west-1.compute.amazonaws.com
[ v3_client_req ]
basicConstraints=CA:false
subjectKeyIdentifier=hash
subjectAltName = #alt_names_client
[alt_names_client]
IP.1 = 192.168.1.103
DNS.1 = GM

Poco + OpenSSL + CA PEM : "Unacceptable certificate" error for 1 out of 2 identical sites

I am trying to do a SSL handshake with www1.filemail.com. I am using cURL's cacert.pem, but I am getting this error:
Unacceptable certificate from 188.138.81.30: application verification failure
Making the handshake against any other HTTPS website works - including www2.filemail.com. www1 and www2 should be identically configured - and they both work fine in all browsers. They also test fine here (identical certificates and intermediary certificates are sent out for both sites):
SSL Labs www1.filemail.com
SSL Labs www2.filemail.com
Why am I getting this problem with www1 using OpenSSL and the cacert.pem file?
There has to be a difference in the certificate setup of www1 and www2. I have tested with a myriad of tools (openssl, ssllabs etc.) to try to pinpoint the difference - but I always get the exact same results for both sites (except when running my code)
What am I missing here? What's the difference between the sites?
(It should be noted that we are using a relatively cheap wildcard certificate provided by RapidSSL - so I'm guessing it has something to do with intermediate or cross-root certificates - but everything seems to be in order when testing with the tools mentioned above.)
Code:
Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> pCert = new Poco::Net::ConsoleCertificateHandler(false);
Poco::Net::Context::Ptr pContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "C:\\cacert.pem", Poco::Net::Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
Poco::Net::SSLManager::instance().initializeClient(0, pCert, pContext);
URI uri("https://www1.filemail.com");
Poco::Net::SecureStreamSocket ss(Poco::Net::SocketAddress(uri.getHost().c_str(), uri.getPort()));
ss.completeHandshake();
www1 and www2 should be identically configured - and they both work fine in all browsers...
Here are the certificates. A diff shows they are the same end-entity (server) certificate:
$ diff www1.txt www2.txt
$
Each server is could be a sending a different chain. Use openssl s_client with openssl x509 and -showcerts to get the chain.
www1
$ openssl s_client -connect www1.filemail.com:443 -tls1 -servername www1.filemail.com | openssl x509 -text -noout > www1.txt
depth=1 C = US, O = GeoTrust Inc., CN = RapidSSL SHA256 CA - G3
verify error:num=20:unable to get local issuer certificate
^C
riemann:~$ cat www1.txt
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 15955 (0x3e53)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = US, O = GeoTrust Inc., CN = RapidSSL SHA256 CA - G3
Validity
Not Before: Oct 14 20:14:57 2014 GMT
Not After : Aug 4 13:09:28 2018 GMT
Subject: OU = GT83551982, OU = See www.rapidssl.com/resources/cps (c)14, OU = Domain Control Validated - RapidSSL(R), CN = *.filemail.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:c5:38:89:72:40:74:77:e2:76:f0:20:ae:d9:91:
26:ac:42:85:03:86:ff:2f:a1:94:b7:f3:86:4c:f7:
ce:63:46:47:e6:03:73:95:01:07:0b:e0:60:9a:93:
c3:b4:14:bc:4e:16:f2:50:12:89:11:42:f5:58:51:
74:15:81:d0:ce:6e:e2:85:e8:d2:3a:38:48:a3:02:
80:e0:a1:fa:ea:8f:ca:ee:bc:00:b3:b2:64:7f:9c:
da:ca:e8:3f:a7:48:af:5c:ed:8e:2f:27:95:19:52:
85:d1:15:9b:f5:4d:b7:21:44:89:05:6f:06:92:7b:
ab:9e:10:63:be:7e:ce:3b:58:10:68:ae:7a:52:6e:
e5:62:bf:ff:56:33:06:51:e5:61:a0:bd:6b:3c:c9:
f3:55:54:02:16:f2:56:27:81:be:83:82:53:25:1e:
c4:1c:1d:65:da:9f:2c:f7:97:49:3c:e1:03:35:1c:
da:c3:02:6d:93:1a:4a:89:53:4c:f5:3e:e7:f9:b9:
c0:10:e0:80:77:3a:d9:5d:ed:b1:46:9e:92:7e:86:
46:d7:be:fe:af:5a:af:02:b4:1b:d2:2b:08:1d:bc:
b5:93:8c:48:45:27:ba:26:69:a9:a8:9f:98:d3:de:
2d:f5:70:f5:39:6a:30:3b:8c:01:6c:85:19:a2:a6:
9a:65
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Authority Key Identifier:
keyid:C3:9C:F3:FC:D3:46:08:34:BB:CE:46:7F:A0:7C:5B:F3:E2:08:CB:59
Authority Information Access:
OCSP - URI:http://gv.symcd.com
CA Issuers - URI:http://gv.symcb.com/gv.crt
X509v3 Key Usage: critical
Digital Signature, Key Encipherment
X509v3 Extended Key Usage:
TLS Web Server Authentication, TLS Web Client Authentication
X509v3 Subject Alternative Name:
DNS:*.filemail.com, DNS:filemail.com
X509v3 CRL Distribution Points:
Full Name:
URI:http://gv.symcb.com/gv.crl
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Certificate Policies:
Policy: 2.16.840.1.113733.1.7.54
CPS: https://www.rapidssl.com/legal
Signature Algorithm: sha256WithRSAEncryption
77:7e:54:47:93:6c:b0:4e:9c:dc:01:47:1f:76:54:9d:f2:42:
94:c1:94:f8:7b:b4:68:82:fe:6d:66:45:68:e1:bd:df:ba:6d:
15:a1:6c:b0:79:9e:d7:99:d9:11:7e:84:e9:f1:63:7c:92:25:
c3:fe:cc:02:1a:61:b9:a3:29:59:18:c2:f1:d2:d7:84:dc:8d:
28:2e:b5:6e:91:d9:68:65:37:5a:b9:b3:d5:f4:d1:1f:b2:ec:
2b:0f:e1:50:30:72:f7:04:70:68:26:b0:61:47:44:49:d0:62:
31:81:53:fa:cc:3a:7b:a1:3b:74:da:c2:3b:7b:5d:9c:23:de:
69:92:51:fc:ff:8d:7a:ea:fd:b2:68:5f:38:3d:22:f6:a6:4a:
d7:a0:88:97:06:54:fd:ba:dc:b9:3a:69:25:89:99:0e:81:82:
c8:63:5c:87:98:bf:70:08:0a:89:20:a1:17:63:31:26:7b:af:
b3:83:f3:9c:b6:7e:64:52:08:bf:a3:74:d5:0c:26:f6:25:7c:
b9:cb:27:57:88:7f:af:1c:b5:99:08:4a:fd:c2:b4:ec:7a:40:
ea:80:ac:e8:88:84:33:53:ab:90:af:bc:bc:ea:6f:88:fe:a8:
f9:c7:63:a3:74:2c:0b:37:5c:90:39:ad:85:82:6a:e9:ea:a7:
e1:55:c2:dd
www2
$ openssl s_client -connect www2.filemail.com:443 -tls1 -servername www2.filemail.com | openssl x509 -text -noout > www2.txt
depth=1 C = US, O = GeoTrust Inc., CN = RapidSSL SHA256 CA - G3
verify error:num=20:unable to get local issuer certificate
^C
riemann:~$ cat www2.txt
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 15955 (0x3e53)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = US, O = GeoTrust Inc., CN = RapidSSL SHA256 CA - G3
Validity
Not Before: Oct 14 20:14:57 2014 GMT
Not After : Aug 4 13:09:28 2018 GMT
Subject: OU = GT83551982, OU = See www.rapidssl.com/resources/cps (c)14, OU = Domain Control Validated - RapidSSL(R), CN = *.filemail.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:c5:38:89:72:40:74:77:e2:76:f0:20:ae:d9:91:
26:ac:42:85:03:86:ff:2f:a1:94:b7:f3:86:4c:f7:
ce:63:46:47:e6:03:73:95:01:07:0b:e0:60:9a:93:
c3:b4:14:bc:4e:16:f2:50:12:89:11:42:f5:58:51:
74:15:81:d0:ce:6e:e2:85:e8:d2:3a:38:48:a3:02:
80:e0:a1:fa:ea:8f:ca:ee:bc:00:b3:b2:64:7f:9c:
da:ca:e8:3f:a7:48:af:5c:ed:8e:2f:27:95:19:52:
85:d1:15:9b:f5:4d:b7:21:44:89:05:6f:06:92:7b:
ab:9e:10:63:be:7e:ce:3b:58:10:68:ae:7a:52:6e:
e5:62:bf:ff:56:33:06:51:e5:61:a0:bd:6b:3c:c9:
f3:55:54:02:16:f2:56:27:81:be:83:82:53:25:1e:
c4:1c:1d:65:da:9f:2c:f7:97:49:3c:e1:03:35:1c:
da:c3:02:6d:93:1a:4a:89:53:4c:f5:3e:e7:f9:b9:
c0:10:e0:80:77:3a:d9:5d:ed:b1:46:9e:92:7e:86:
46:d7:be:fe:af:5a:af:02:b4:1b:d2:2b:08:1d:bc:
b5:93:8c:48:45:27:ba:26:69:a9:a8:9f:98:d3:de:
2d:f5:70:f5:39:6a:30:3b:8c:01:6c:85:19:a2:a6:
9a:65
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Authority Key Identifier:
keyid:C3:9C:F3:FC:D3:46:08:34:BB:CE:46:7F:A0:7C:5B:F3:E2:08:CB:59
Authority Information Access:
OCSP - URI:http://gv.symcd.com
CA Issuers - URI:http://gv.symcb.com/gv.crt
X509v3 Key Usage: critical
Digital Signature, Key Encipherment
X509v3 Extended Key Usage:
TLS Web Server Authentication, TLS Web Client Authentication
X509v3 Subject Alternative Name:
DNS:*.filemail.com, DNS:filemail.com
X509v3 CRL Distribution Points:
Full Name:
URI:http://gv.symcb.com/gv.crl
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Certificate Policies:
Policy: 2.16.840.1.113733.1.7.54
CPS: https://www.rapidssl.com/legal
Signature Algorithm: sha256WithRSAEncryption
77:7e:54:47:93:6c:b0:4e:9c:dc:01:47:1f:76:54:9d:f2:42:
94:c1:94:f8:7b:b4:68:82:fe:6d:66:45:68:e1:bd:df:ba:6d:
15:a1:6c:b0:79:9e:d7:99:d9:11:7e:84:e9:f1:63:7c:92:25:
c3:fe:cc:02:1a:61:b9:a3:29:59:18:c2:f1:d2:d7:84:dc:8d:
28:2e:b5:6e:91:d9:68:65:37:5a:b9:b3:d5:f4:d1:1f:b2:ec:
2b:0f:e1:50:30:72:f7:04:70:68:26:b0:61:47:44:49:d0:62:
31:81:53:fa:cc:3a:7b:a1:3b:74:da:c2:3b:7b:5d:9c:23:de:
69:92:51:fc:ff:8d:7a:ea:fd:b2:68:5f:38:3d:22:f6:a6:4a:
d7:a0:88:97:06:54:fd:ba:dc:b9:3a:69:25:89:99:0e:81:82:
c8:63:5c:87:98:bf:70:08:0a:89:20:a1:17:63:31:26:7b:af:
b3:83:f3:9c:b6:7e:64:52:08:bf:a3:74:d5:0c:26:f6:25:7c:
b9:cb:27:57:88:7f:af:1c:b5:99:08:4a:fd:c2:b4:ec:7a:40:
ea:80:ac:e8:88:84:33:53:ab:90:af:bc:bc:ea:6f:88:fe:a8:
f9:c7:63:a3:74:2c:0b:37:5c:90:39:ad:85:82:6a:e9:ea:a7:
e1:55:c2:dd
I am trying to do a SSL handshake towards www1.filemail.com - but I am
getting this error:
Unacceptable certificate from 188.138.81.30: application verification failure
RapidSSL SHA256 CA - G3 is a CA; it issued the server's certificate. The server is called the subject. As you work up a chain, the former issuer becomes the current subject. At the top of the chain is the self signed root. At the root, the issuer==subject.
The RapidSSL G3 CA is either (1) self-signed, so its a root CA; or (2) signed by another CA higher in the chain, so its a subordinate CA (i.e., it has an issuer). In this case, the G3 CA is a subordinate and it has an issuer.
It sounds like one server is sending the complete chain needed to validate the server's certificate; and the other server is not. Servers are supposed to send the complete chain to avoid the "which directory" problem in PKI. The "complete chain" is every certificate except the self-signed root (but many send the root, too).
The client must trust the self-signed root a priori, and its why it should not be sent (otherwise, a bad guy can swap-in his own chain). Or, instead of using cacert.pem:
Poco::Net::Context::CLIENT_USE, "", "", "C:\\cacert.pem", ...
You can load RapidSSL SHA256 CA - G3 and use that as the root of the trust. You will avoid the other 300 or so CA's in cacert.pem that are not needed to validate the server chain. Its good security engineering.
You can fetch RapidSSL SHA256 CA - G3 from rapidSSL's site at Intermediate CA Certificate: RapidSSL with SHA-2 (under SHA-1 Root).
UPDATE using RapidSSL SHA256 CA - G3:
Here's the signer's certificate:
$ cat rapidssl.pem
-----BEGIN CERTIFICATE-----
MIIEJTCCAw2gAwIBAgIDAjp3MA0GCSqGSIb3DQEBCwUAMEIxCzAJBgNVBAYTAlVT
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
YWwgQ0EwHhcNMTQwODI5MjEzOTMyWhcNMjIwNTIwMjEzOTMyWjBHMQswCQYDVQQG
EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXUmFwaWRTU0wg
U0hBMjU2IENBIC0gRzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCv
VJvZWF0eLFbG1eh/9H0WA//Qi1rkjqfdVC7UBMBdmJyNkA+8EGVf2prWRHzAn7Xp
SowLBkMEu/SW4ib2YQGRZjEiwzQ0Xz8/kS9EX9zHFLYDn4ZLDqP/oIACg8PTH2lS
1p1kD8mD5xvEcKyU58Okaiy9uJ5p2L4KjxZjWmhxgHsw3hUEv8zTvz5IBVV6s9cQ
DAP8m/0Ip4yM26eO8R5j3LMBL3+vV8M8SKeDaCGnL+enP/C1DPz1hNFTvA5yT2AM
QriYrRmIV9cE7Ie/fodOoyH5U/02mEiN1vi7SPIpyGTRzFRIU4uvt2UevykzKdkp
YEj4/5G8V1jlNS67abZZAgMBAAGjggEdMIIBGTAfBgNVHSMEGDAWgBTAephojYn7
qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUw5zz/NNGCDS7zkZ/oHxb8+IIy1kwEgYD
VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwNQYDVR0fBC4wLDAqoCig
JoYkaHR0cDovL2cuc3ltY2IuY29tL2NybHMvZ3RnbG9iYWwuY3JsMC4GCCsGAQUF
BwEBBCIwIDAeBggrBgEFBQcwAYYSaHR0cDovL2cuc3ltY2QuY29tMEwGA1UdIARF
MEMwQQYKYIZIAYb4RQEHNjAzMDEGCCsGAQUFBwIBFiVodHRwOi8vd3d3Lmdlb3Ry
dXN0LmNvbS9yZXNvdXJjZXMvY3BzMA0GCSqGSIb3DQEBCwUAA4IBAQCjWB7GQzKs
rC+TeLfqrlRARy1+eI1Q9vhmrNZPc9ZE768LzFvB9E+aj0l+YK/CJ8cW8fuTgZCp
fO9vfm5FlBaEvexJ8cQO9K8EWYOHDyw7l8NaEpt7BDV7o5UzCHuTcSJCs6nZb0+B
kvwHtnm8hEqddwnxxYny8LScVKoSew26T++TGezvfU5ho452nFnPjJSxhJf3GrkH
uLLGTxN5279PURt/aQ1RKsHWFf83UTRlUfQevjhq7A6rvz17OQV79PP7GqHQyH5O
ZI3NjGFVkP46yl0lD/gdo0p0Vk8aVUBwdSWmMy66S6VdU5oNMOGNX2Esr8zvsJmh
gP8L8mJMcCaY
-----END CERTIFICATE-----
Notice OpenSSL finished with Verify return code: 2 (unable to get issuer certificate). That's fine because you don't care about the issuer. You've rooted your trust at GeoTrust Inc., CN = RapidSSL SHA256 CA - G3, and RapidSSL SHA256 CA - G3 certified/signed the server's certificate.
$ openssl s_client -connect www1.filemail.com:443 -tls1 -servername www1.filemail.com -CAfile rapidssl.pem
CONNECTED(00000003)
depth=1 C = US, O = GeoTrust Inc., CN = RapidSSL SHA256 CA - G3
verify error:num=2:unable to get issuer certificate
issuer= C = US, O = GeoTrust Inc., CN = GeoTrust Global CA
Server did acknowledge servername extension.
---
Certificate chain
0 s:/OU=GT83551982/OU=See www.rapidssl.com/resources/cps (c)14/OU=Domain Control Validated - RapidSSL(R)/CN=*.filemail.com
i:/C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
1 s:/C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
i:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIEsDCCA5igAwIBAgICPlMwDQYJKoZIhvcNAQELBQAwRzELMAkGA1UEBhMCVVMx
FjAUBgNVBAoTDUdlb1RydXN0IEluYy4xIDAeBgNVBAMTF1JhcGlkU1NMIFNIQTI1
NiBDQSAtIEczMB4XDTE0MTAxNDIwMTQ1N1oXDTE4MDgwNDEzMDkyOFowgZIxEzAR
BgNVBAsTCkdUODM1NTE5ODIxMTAvBgNVBAsTKFNlZSB3d3cucmFwaWRzc2wuY29t
L3Jlc291cmNlcy9jcHMgKGMpMTQxLzAtBgNVBAsTJkRvbWFpbiBDb250cm9sIFZh
bGlkYXRlZCAtIFJhcGlkU1NMKFIpMRcwFQYDVQQDDA4qLmZpbGVtYWlsLmNvbTCC
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMU4iXJAdHfidvAgrtmRJqxC
hQOG/y+hlLfzhkz3zmNGR+YDc5UBBwvgYJqTw7QUvE4W8lASiRFC9VhRdBWB0M5u
4oXo0jo4SKMCgOCh+uqPyu68ALOyZH+c2sroP6dIr1ztji8nlRlShdEVm/VNtyFE
iQVvBpJ7q54QY75+zjtYEGiuelJu5WK//1YzBlHlYaC9azzJ81VUAhbyVieBvoOC
UyUexBwdZdqfLPeXSTzhAzUc2sMCbZMaSolTTPU+5/m5wBDggHc62V3tsUaekn6G
Rte+/q9arwK0G9IrCB28tZOMSEUnuiZpqaifmNPeLfVw9TlqMDuMAWyFGaKmmmUC
AwEAAaOCAVgwggFUMB8GA1UdIwQYMBaAFMOc8/zTRgg0u85Gf6B8W/PiCMtZMFcG
CCsGAQUFBwEBBEswSTAfBggrBgEFBQcwAYYTaHR0cDovL2d2LnN5bWNkLmNvbTAm
BggrBgEFBQcwAoYaaHR0cDovL2d2LnN5bWNiLmNvbS9ndi5jcnQwDgYDVR0PAQH/
BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAnBgNVHREEIDAe
gg4qLmZpbGVtYWlsLmNvbYIMZmlsZW1haWwuY29tMCsGA1UdHwQkMCIwIKAeoByG
Gmh0dHA6Ly9ndi5zeW1jYi5jb20vZ3YuY3JsMAwGA1UdEwEB/wQCMAAwRQYDVR0g
BD4wPDA6BgpghkgBhvhFAQc2MCwwKgYIKwYBBQUHAgEWHmh0dHBzOi8vd3d3LnJh
cGlkc3NsLmNvbS9sZWdhbDANBgkqhkiG9w0BAQsFAAOCAQEAd35UR5NssE6c3AFH
H3ZUnfJClMGU+Hu0aIL+bWZFaOG937ptFaFssHme15nZEX6E6fFjfJIlw/7MAhph
uaMpWRjC8dLXhNyNKC61bpHZaGU3Wrmz1fTRH7LsKw/hUDBy9wRwaCawYUdESdBi
MYFT+sw6e6E7dNrCO3tdnCPeaZJR/P+Neur9smhfOD0i9qZK16CIlwZU/brcuTpp
JYmZDoGCyGNch5i/cAgKiSChF2MxJnuvs4PznLZ+ZFIIv6N01Qwm9iV8ucsnV4h/
rxy1mQhK/cK07HpA6oCs6IiEM1OrkK+8vOpviP6o+cdjo3QsCzdckDmthYJq6eqn
4VXC3Q==
-----END CERTIFICATE-----
subject=/OU=GT83551982/OU=See www.rapidssl.com/resources/cps (c)14/OU=Domain Control Validated - RapidSSL(R)/CN=*.filemail.com
issuer=/C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
---
No client certificate CA names sent
Server Temp Key: ECDH, P-521, 521 bits
---
SSL handshake has read 2834 bytes and written 338 bytes
Verification error: unable to get issuer certificate
---
New, SSLv3, Cipher is ECDHE-RSA-AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1
Cipher : ECDHE-RSA-AES256-SHA
Session-ID: 27390000AF3638FDEA75DDF52B9D937F290593304123134062F049306BBDE87F
Session-ID-ctx:
Master-Key: E8E2613F6267C705CA82EEE4C8A992880A2ABDA9E8D477A10C952764B1F4DD3D39244D3F0AD915B8FEB7E5FA1E8D55FD
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1473889933
Timeout : 7200 (sec)
Verify return code: 2 (unable to get issuer certificate)
Extended master secret: yes
----
Günter Obiltschnig helped me out via POCO#Github and got it working by replacing
Poco::Net::SecureStreamSocket ss(Poco::Net::SocketAddress(uri.getHost().c_str(), uri.getPort()));
with
Poco::Net::SecureStreamSocket ss(Poco::Net::SocketAddress(uri.getHost().c_str(), uri.getPort()), uri.getHost());
(including the host name in the constructor of SecureStreamSocket - it is used for certificate verification)
From the POCO documentation:
SecureStreamSocket(
const SocketAddress & address,
const std::string & hostName
);
//Creates a secure stream socket using the default client SSL context and connects it to the socket specified by address.
//The given host name is used for certificate verification <=======
I still do not know the exact difference in config between www1 and www2 are, would love if someone could enlighten me on this.

Qt QSslSocket "The certificate is self-signed, and untrusted"

i want to connect server with QSslSocket and on server i get soketSslError "The certificate is self-signed, and untrusted" , but i dont understand why i have this error.
On first step was generated file for server and client with openssl
$openssl req -new -newkey rsa:1024 -keyout ca.key -x509 -days 500 -out ca.crt
$openssl req -new -newkey rsa:1024 -keyout client01.key -out client01.csr
$openssl ca -config ca.config -in client01.csr -out client01.crt -batch
in c++ server / client
On server:
start server
if (listen(QHostAddress::Any,this->connectingPort)) {
std::cout<<"Server start on port: "<<this->connectingPort<<std::endl;
return true;
} else {
std::cout<<"Cant start server. "<<errorString().toStdString().c_str()<<std::endl;
return false;
}
incomingConnection
QFile keyFile("ca.key");
if (!keyFile.open(QIODevice::ReadOnly)) {
delete this->sslSocket;
qDebug()<<"Cant open file: "<<keyFile.fileName();
return false;
}
QByteArray pasp ="qwerty";
QSslKey key(keyFile.readAll(),QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,pasp);
if (key.isNull()) {
delete this->sslSocket;
qDebug()<<"key in file "<<keyFile.fileName()<<" is empty";
return false;
}
keyFile.close();
this->sslSocket->setPrivateKey(key);
this->sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer);
this->sslSocket->setLocalCertificate("ca.crt");
this->sslSocket->startServerEncryption();
on client side:
this->sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer);
QFile keyFile("client01.key");
if (!keyFile.open(QIODevice::ReadOnly)) {
delete this->sslSocket;
qDebug()<<"Cant open file: "<<keyFile.fileName();
return ;
}
QByteArray pasp ="qwerty";
QSslKey key(keyFile.readAll(),QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,pasp);
if (key.isNull()) {
delete this->sslSocket;
qDebug()<<"key in file "<<keyFile.fileName()<<" is empty";
return ;
}
keyFile.close();
this->sslSocket->setPrivateKey(key);
this->sslSocket->setLocalCertificate("client01.crt");
this->sslSocket->connectToHostEncrypted("192.168.0.10",1258);
if (!this->sslSocket->waitForEncrypted()) {
qDebug()<<"error: "<<sslSocket->errorString();
}
and when i connecting from client i get on server error
soket ssl error
"The certificate is self-signed, and untrusted"
"The certificate is self-signed, and untrusted"
socketError: QAbstractSocket::SocketError( 13 )
any idea what i do wrong?
UPDATE:
Qt Creator 3.0.1
Based on Qt 5.2.1 (GCC 4.8.2, 64 bit)
I suggest you try this on the server:
QList<QSslCertificate> cert = QSslCertificate::fromPath(QLatin1String("your-certificate.pem"));
QSslError error(QSslError::SelfSignedCertificate, cert.at(0));
QList<QSslError> expectedSslErrors;
expectedSslErrors.append(error);
this->sslSocket.ignoreSslErrors(expectedSslErrors);
probleb has been resolved
what i doen:
update version Qt for 5.5
and generated new ssl certificate:
openssl req -x509 -newkey rsa:1024 -keyout key.key -out key.pem -days 365 -nodes
in server:
sslServer.setSslLocalCertificate("key.pem");
sslServer.setSslPrivateKey("key.key");
sslServer.setSslProtocol(QSsl::TlsV1_2);
in client:
sslSocket.addCaCertificates("key.pem");

SSL_CTX_use_PrivateKey_file() failed

I'm writing a client application on Windows that establishes an SSL connection to a server, and the server requests client certificate for authentication. The server provides me a .pfx file, then I use openssl command line tool to get the certificate and the private key like this:
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
after that, I try to load the certificate and the private key with functions from openssl as below, but SSL_CTX_use_PrivateKey_file() always failed, the error message is "error:0906D06C:PEM routines:PEM_read_bio:no start line", I can't figure it out why, can anyone give me some enlightenment?
Here is the code.
#include "openssl/ssl.h"
#include "openssl/err.h"
#include <stdio.h>
#include <string>
int InitClientCtx()
{
OpenSSL_add_ssl_algorithms();
SSL_CTX* m_pClientCtx;
m_pClientCtx = SSL_CTX_new(SSLv23_method());
if(!m_pClientCtx)
{
return -1;
}
::SSL_CTX_set_options(m_pClientCtx, SSL_OP_ALL); //for well-known bugs
int nRet = 0;
std::string sCertFilePath = "C:\\cert.pem";
nRet = SSL_CTX_use_certificate_chain_file(m_pClientCtx, sCertFilePath.c_str());
std::string sKeyPassWord = "123456";
SSL_CTX_set_default_passwd_cb_userdata(m_pClientCtx, (void*)(sKeyPassWord.c_str()));
std::string sKeyFilePath = "C:\\key.pem";
// this method returned 0, which means it failed.
nRet = SSL_CTX_use_PrivateKey_file(m_pClientCtx, sKeyFilePath.c_str(), SSL_FILETYPE_PEM);
SSL_load_error_strings();
unsigned long n = ERR_get_error();
char buf[1024];
printf("%s\n", ERR_error_string(n, buf));
nRet = SSL_CTX_check_private_key(m_pClientCtx);
if (nRet <= 0)
{
return -1;
}
/*std::string sCACertFilePath;
nRet = SSL_CTX_load_verify_locations(m_pClientCtx, sCACertFilePath.c_str(), NULL);*/
return 0;
}
int main()
{
InitClientCtx();
return 0;
};
In my case the error was because the PEM file did not contain both a key and a certificate.
Make sure your file contains both sections:
-----BEGIN PRIVATE KEY----- jhajk838383jks.....
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE----- yoe55wjcxnshre.....
-----END CERTIFICATE KEY-----
I catenated .key and .crt files I already had in my Apache configuration to make a .pem file.
The 'no start line' error is certainly misleading as you can have a perfectly good "BEGIN" line in your PEM file and still get the error.
The error error:0906D06C:PEM routines:PEM_read_bio:no start line is because in both the cert.pem as well as key.pem, don't start off with -----BEGIN CERTIFICATE----- and -----BEGIN ENCRYPTED PRIVATE KEY-----.
If you open up your cert.pem and key.pem in a text editor and yank off whatever is there before the BEGIN markers, you should be good.
When you create a certificate and a key pair using Certificate Signing Request, you won't get this additional information.
I've solved this problem myself. I generated the key.pem using OpenSSL for Windows, when the CMD prompts me to type in the pass phrase, I just typed a Enter since I needn't a pass phrase, but the key.pem was invalid(neither BEGIN nor END markers). When I generate the private key in Linux, the terminal prompts I must type a pass phrase and I do. Then I remove the key pass phrase using this command:
openssl rsa -in key.pem -out newkey.pem
After that, I open the key.pem in a text editor, it starts off with -----BEGIN RSA PRIVATE KEY----- and end up with -----END RSA PRIVATE KEY-----. And SSL_CTX_use_PrivateKey_file() just works fine!
Under openssl directory demo/openssl there is a client example.
Change:
meth = SSLv2_client_method();
in your case to:
meth = SSLv23_client_method();
Try this example and see where it fails.
Are you sure that the key password is 123456 ?
I had the same problem in NGINX while installing the SSL certificate and I resolved using the following step:
Go to the folder where you have your certificate and pem files
Open your ca-bundle.crt file and copy everything, sudo nano your fileName select all and copy. the file looks like
-----BEGIN CERTIFICATE----- MIIE0DCCA7igAwIBAgIBBzANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx
EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT
..........
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE----- MIIEfTCCA2WgAwIBAgIDG+cVMA0GCSqGSIb3DQEBCwUAMGMxCzAJBgNVBAYTAlVT
MSEwHwYDVQQKExhUaGUgR28gRGFkZHkgR3JvdXAsIEluYy4xMTAvBgNVBAsTKEdv
..........
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE----- MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh
MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE
..........
-----END CERTIFICATE-----
Open your pem file using sudo nano your fileName.pem
You will see some code like
-----BEGIN CERTIFICATE----- MIIGLzCCBRegAwIBAgIIWI4ndTQi3MwwDQYJKoZIhvcNAQELBQAwgbQxCzAJBgNV
MAAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA4GA1UdDwEB/wQEAwIF
oDA4BgNVHR8EMTAvMC2gK6AphidodHRwOi8vY3JsLmdvZGFkZHkuY29tL2dkaWcy
-----END CERTIFICATE-----
After -----END CERTIFICATE----- paste all the code copied from ca-bundle.crt file and save it
Restart your Nginx server using following command sudo service nginx restart
The above steps worked for me in my Nginx and SSL configuration

How I can create a DomainKey-Signature and DKIM-Signature by C++(or VC++) help of OpenSSL, Is it possible?

I have a public/private key pair, I submitted my public key into the server DNS TXT record(in SPF record), and I have a private key file.. I want to create DKIM-Signature and DomainKey-Signature for email, so I want to encrypt text message by private key to send it to email servers.. I want to use SHA-256 as the cryptographic hash and RSA as the public key encryption scheme.. I want to use OpenSSL and C++ to make DKIM-Signature and DomainKey-Signature for email..
This is my Public key in server TXT record :
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnHVS+q65lvG2xocltTYgPGt9F
aysGZTrcOwHedo8tX1dyPrcx2I8x/cvB9nmfdAkt65aGFAlBZrofbPCr2Mq4wDdv
IZ31KSuyMQI4T68ylWNT89GewQF6AOkpY1E2bW+oDXc+MpbtpYXY1rUJAS/Abt5v
Xi7gwKN9FSJ3mm9bjQIDAQAB
-----END PUBLIC KEY-----
This is my Privet key :
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCnHVS+q65lvG2xocltTYgPGt9FaysGZTrcOwHedo8tX1dyPrcx
2I8x/cvB9nmfdAkt65aGFAlBZrofbPCr2Mq4wDdvIZ31KSuyMQI4T68ylWNT89Ge
wQF6AOkpY1E2bW+oDXc+MpbtpYXY1rUJAS/Abt5vXi7gwKN9FSJ3mm9bjQIDAQAB
AoGACXuxnmxRpjZOJ0FeE9TNfsXwm5jcRS2jbHHwxjYGI/YAGVyTusFmRtj3Iheh
iTnld3SiAxPJ/qscrsHY2nef8Up60V7RF8bs+sbICnHbdz8ZoKxN9dEFCwJkIl55
dv0GHjox6UgWUUkUAiHCM2EgG5eOOQ8PsuXY8LpPWLvfuyUCQQDbkFG9y/Q/3lmb
CdYfBpsP3qvma+fdgCw9lRXTowhu0rKen/CC3rFkHMeHfSW9GHuR8QbPYdVA6d9H
Y7KxYa7LAkEAwtjTEo/zAVexH/+YgiqL6w89BHlTAmwIEkXpqtAnE86kDDCekYdE
fRIdGK1zHDOUddMAhwoJQjJzy/NJreQ8BwJBAMoJ6U3vKZjD8Ex8Jq5yE6nsyt3D
mZ73XL5mO6l9sjrYY0kX/+dNKIro+KoyfNGef8bxtcSLUALlsnIsybf0HTUCQQCR
DD4cvGJHJpOp4WkTxT6Bjsd6lCKyU9+yUq8/RFNC0HqYxHzWkx7uCFT2sPBXFyK2
j4v9+v+ncs13DzZTJ+tzAkBI6UWHtsn839nrAT32M8PEPF/TuDmqebMhFOaTl4an
W0Jr8w8iGk2gvQS2cXEPNh4XT9AgcTKDQkhui4RgxK4F
-----END RSA PRIVATE KEY-----
I tried some code help of OpenSSL, but I am unable to create DKIM-Signature and DomainKey-Signature for email..
This is code :
#include <stdio.h>
#include <stdlib.h>
#include <openssl/bio.h>
#include <openssl/pkcs7.h>
#include <openssl/pkcs12.h>
#include <openssl/x509.h>
/ * Arguments: to be signed email, PKCS#12 certificate with private key
*/
int main(int argc, char** argv) {
if (argc < 3) exit(1);
OpenSSL_add_all_algorithms();
BIO *data = BIO_new_file(argv[1], "rb");
if (!data) exit(1);
BIO *p12file = BIO_new_file(argv[2], "rb");
if (!p12file) exit(1);
PKCS12 *p12 = d2i_PKCS12_bio(p12file, NULL);
if (!p12) exit(1);
X509 *signcert;
EVP_PKEY *pkey;
STACK_OF(X509) *ca;
int ret = PKCS12_parse(p12, "", &pkey, &signcert, &ca);
if (!ret) exit(1);
PKCS7 *p7 = PKCS7_sign(signcert, pkey, ca, data, 0);
if (!p7) exit(1);
BIO *out = BIO_new_file("email.eml", "wb");
if (!out) exit(1);
ret = SMIME_write_PKCS7(out, p7, data, 0);
if (!ret) exit(1);
BIO_free(data);
BIO_free(p12file);
PKCS12_free(p12);
PKCS7_free(p7);
return (EXIT_SUCCESS);
}
Any one can help me how I will use my Privet key with text to create this "DKIM-Signature and DomainKey-Signature"????
This is not working : BIO *p12file = BIO_new_file(argv[2], "rb");
I dont have "PKCS#12 certificate", so how I will use only my Privet key with email's text message to create "DKIM-Signature and DomainKey-Signature" ????
Your private and public key are in PEM format. You can use OpenSSL to convert it to PKCS#12.
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
Having said this, this will not help you. The source code that you presented is for signing e-mails using S/MIME. This uses personal certificates that are signed by an official Certification Authority, not using self-signed certificates. This also provides for the ability to encrypt e-mails, provided the recipient has your public key in their key chain.
What you are looking for is DKIM and DomainKeys. This is signed and then hashed using SHA256 and SHA1, respectively. It is computationally less expensive than S/MIME, but requires canonicalization (Google it) of the header and body before hashes can be calculated.
I recommend you have a look at PHPMailer projet on Github. Although this is PHP source code, it should be readily adaptable to work in C. It only covers the DKIM implementation, but DKIM supersedes DomainKeys, so I wouldn't bother implementing DomainKeys.