Rolling my own SSL with OpenSSL, not working - ssl

I've read all the caveats about not doing this, but ... I need to. I need to be able to POST messages to an SSL/TLS secured server from a C program, and it's just not working.
I cat GET data via SSL using this same code, but I cannot POST. Every attempt returns a 400 BAD REQUEST. I can use the exact same data via another ReST client (oddly enough called "Rest Client") and it works. I can run the same command via curl and it works. But via C/openssl, same response.
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
SSL_load_error_strings();
/* https://www.openssl.org/docs/ssl/SSL_CTX_new.html */
const SSL_METHOD* method = SSLv23_method();
/* http://www.openssl.org/docs/ssl/ctx_new.html */
ctx = SSL_CTX_new(method);
/* https://www.openssl.org/docs/ssl/ctx_set_verify.html */
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
/* https://www.openssl.org/docs/ssl/ctx_set_verify.html */
SSL_CTX_set_verify_depth(ctx, 5);
const long flags = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long old_opts = SSL_CTX_set_options(ctx, flags);
UNUSED(old_opts);
/* http://www.openssl.org/docs/ssl/SSL_CTX_set_default_verify_paths.html */
res = SSL_CTX_set_default_verify_paths(ctx);
/* https://www.openssl.org/docs/crypto/BIO_f_ssl.html */
web = BIO_new_ssl_connect(ctx);
/* https://www.openssl.org/docs/crypto/BIO_s_connect.html */
res = BIO_set_conn_hostname(web, HOST_NAME ":" HOST_PORT);
/* https://www.openssl.org/docs/crypto/BIO_f_ssl.html */
/* This copies an internal pointer. No need to free. */
BIO_get_ssl(web, &ssl);
/* https://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_CONTEXTS */
/* https://www.openssl.org/docs/ssl/SSL_CTX_set_cipher_list.html */
res = SSL_set_cipher_list(ssl, PREFERRED_CIPHERS);
/* No documentation. See the source code for tls.h and s_client.c */
res = SSL_set_tlsext_host_name(ssl, HOST_NAME);
/* https://www.openssl.org/docs/crypto/BIO_s_file.html */
out = BIO_new_fp(stdout, BIO_NOCLOSE);
/* https://www.openssl.org/docs/crypto/BIO_s_connect.html */
res = BIO_do_connect(web);
/* https://www.openssl.org/docs/crypto/BIO_f_ssl.html */
res = BIO_do_handshake(web);
/* Step 1: verify a server certifcate was presented during negotiation */
/* https://www.openssl.org/docs/ssl/SSL_get_peer_certificate.html */
X509* cert = SSL_get_peer_certificate(ssl);
/* Step 2: verify the result of chain verifcation */
/* http://www.openssl.org/docs/ssl/SSL_get_verify_result.html */
/* Error codes: http://www.openssl.org/docs/apps/verify.html */
res = SSL_get_verify_result(ssl);
certname = X509_NAME_new();
certname = X509_get_subject_name(cert);
BIO_printf(out, "Displaying the certificate subject data:\n");
X509_NAME_print_ex(out, certname, 0, 0);
BIO_printf(out, "\n");
sprintf(message, "POST /api/buckets\r\nHTTP/1.1\r\nX-IS-AccessKey: accessKey\r\nContent-Type: application/json\r\nContent-Length: 66\r\n\r\n{\"bucketKey\": \"MyBucket\", \"bucketName\": \"My Bucket\"}\r\n\r\n");
BIO_puts(web, message);
BIO_puts(out, message);
int len = 0;
do {
char buff[1536] = {};
/* https://www.openssl.org/docs/crypto/BIO_read.html */
len = BIO_read(web, buff, sizeof(buff));
if(len > 0)
BIO_write(out, buff, len);
/* BIO_should_retry returns TRUE unless there's an */
/* error. We expect an error when the server */
/* provides the response and closes the connection. */
} while (len > 0 || BIO_should_retry(web));
ret = 0;
} while (0);
And indeed this does successfully open a connection, and retrieve a certificate, and validate it, etc.
verify_callback (depth=1)(preverify=0)
Issuer (cn): DigiCert Global Root CA
Subject (cn): DigiCert SHA2 Secure Server CA
Error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
verify_callback (depth=0)(preverify=1)
Issuer (cn): DigiCert SHA2 Secure Server CA
Subject (cn): *.initialstate.com
Subject (san): *.initialstate.com
Subject (san): initialstate.com
Displaying the certificate subject data:
C=US, ST=TN, L=Brentwood, O=Initial State Technologies, Inc, CN=*.initialstate.com
So that seems to work. And if I do a simple "GET /" from www.google.com I get the same certificate responses (well, with the appropriate certificate from google) and I get all the data back just fine.
So it seems to be something to do with actually POSTing data.
If anyone can point out the error of my ways -- not just my folly for doing this! -- I'de be very thankful!

..."POST /api/buckets\r\nHTTP/1.1\r\n
The newline between the path and the HTTP version is wrong and must be a space. This means that you send here
POST /api/buckets
HTTP/1.1
instead of
POST /api/buckets HTTP/1.1

Related

How get session key from ssl session

I created client and server program to exchange the data.
Client and server uses tls to pass the message securely.
Used openssl to make the connection between server and client.
Now i have the ssl handle.
Is there any way to extract server write key, server random, client random,client write key, master key.
in the below code sample Servlet method will connect to the client do the handshake get the session keys.
i am trying to read the tls packet from the port after tls handshake completed and pass the packet to another module.
To check the for malformed or invalid packets i need to decrypt the packet to inspect the payload where i required the session keys.
Is there any way to extract server write key, server random, client random,client write key, master key.
code snippet:
main(){
// Initialize the SSL library
SSL_library_init();
portnum = Argc[1];
ctx = InitServerCTX(); /* initialize SSL */
LoadCertificates(ctx, "mycert.pem", "mycert.pem"); /* load certs */
server = OpenListener(atoi(portnum)); /* create server socket */
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
Servlet()
{
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
unsigned char key[100];
//SSL_SESSION_get_master_key(ssl,key,100);
//printf("masterkey:%s", key);
ShowCerts(ssl); /* get any certificates */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
buf[bytes] = '\0';
printf("Client msg: \"%s\"\n", buf);
if ( bytes > 0 )
{
if(strcmp(cpValidMessage,buf) == 0)
{
SSL_write(ssl, ServerResponse, strlen(ServerResponse)); /*
send reply */
}

TLS certificate verification failure

I need to have a code which performs 2-way authentication (client and server authenticates each other). My server is a TCP server. I intend to have TLS security added.
https://github.com/ospaarmann/exdgraph/wiki/TLS-client-authentication
I generated client and server, CA certificates and key files using the link above.
Server side code:
{
SSL_CTX_set_options(
ret,
SSL_OP_NO_SSLv2 |
SSL_OP_NO_SSLv3 |
SSL_OP_NO_COMPRESSION
);
SSL_CTX_set_verify(
ret,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
NULL
);
if (SSL_CTX_load_verify_locations(ret, NULL, "/home/ml5/tls_bio/MyRootCA.pem") == 0) {
fprintf(stderr, "Failed to load root certificates\n");
SSL_CTX_free(ret);
return NULL;
}
/*
* We won't set any verification settings this time. Instead
* we need to give OpenSSL our certificate and private key.
*/
if (SSL_CTX_use_certificate_chain_file(ret, "MyServer.pem") != 1) {
ssl_perror("SSL_CTX_use_certificate_file");
SSL_CTX_free(ret);
return NULL;
}
if (SSL_CTX_use_PrivateKey_file(ret, "MyServer.key", SSL_FILETYPE_PEM) != 1) {
ssl_perror("SSL_CTX_use_PrivateKey_file");
SSL_CTX_free(ret);
return NULL;
}
printf("Loaded root certificates\n");
/*
* Check that the certificate (public key) and private key match.
*/
if (SSL_CTX_check_private_key(ret) != 1) {
fprintf(stderr, "certificate and private key do not match!\n");
SSL_CTX_free(ret);
return NULL;
}
}
client side code:
=======================================================================
SSL_CTX *ret;
/* create a new SSL context */
ret = SSL_CTX_new(SSLv23_client_method( ));
if (ret == NULL) {
fprintf(stderr, "SSL_CTX_new failed!\n");
return NULL;
}
/*
* set our desired options
*
* We don't want to talk to old SSLv2 or SSLv3 servers because
* these protocols have security issues that could lead to the
* connection being compromised.
*
* Return value is the new set of options after adding these
* (we don't care).
*/
SSL_CTX_set_options(
ret,
SSL_OP_NO_SSLv2 |
SSL_OP_NO_SSLv3 |
SSL_OP_NO_COMPRESSION
);
/*
* set up certificate verification
*
* We want the verification to fail if the peer doesn't
* offer any certificate. Otherwise it's easy to impersonate
* a legitimate server just by offering no certificate.
*
* No error checking, not because I'm being sloppy, but because
* these functions don't return error information.
*/
SSL_CTX_set_verify(
ret,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
NULL
);
SSL_CTX_set_verify_depth(ret, 4);
/*
* Point our context at the root certificates.
* This may vary depending on your system.
*/
if (SSL_CTX_load_verify_locations(ret, NULL, "/home/ml5/tls_bio_l1/MyRootCA.pem") == 0) {
fprintf(stderr, "Failed to load root certificates\n");
SSL_CTX_free(ret);
return NULL;
}
/*
* We won't set any verification settings this time. Instead
* we need to give OpenSSL our certificate and private key.
*/
if (SSL_CTX_use_certificate_chain_file(ret, "MyClient.pem") != 1) {
SSL_CTX_free(ret);
return NULL;
}
if (SSL_CTX_use_PrivateKey_file(ret, "MyClient.key", SSL_FILETYPE_PEM) != 1) {
SSL_CTX_free(ret);
return NULL;
}
printf("Loaded root certificates\n");
/*
* Check that the certificate (public key) and private key match.
*/
if (SSL_CTX_check_private_key(ret) != 1) {
fprintf(stderr, "certificate and private key do not match!\n");
SSL_CTX_free(ret);
return NULL;
}
I am unsure what is wrong because of which when I start the server and the client,
I get the error as shown below on the client side:
BIO_do_connect failed: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
If I have my own verify callback on client and server ofcourse the 2-way authentication succeeds
SSL_CTX_set_cert_verify_callback(ctx, always_true_callback, NULL);
But I think thats not how it is to be done. Any help in this regard to solve the error shown above, will be greatly appreciated.
Just to those who come-in here. The issue was relating to how I generated CA certificate, client/server certificates. Once I corrected those, it started working.

How to use http websocket on Mongoose embedded web server with SSL?

I'm trying to use Http WebSocket on Mongoose embedded web server with SSL.
And I tried this mongoose example called "simplest_web_server_ssl".
But when I executed the program, it printed out this message below.
"Failed to create listener: Invalid SSL cert"
I think it's because the program doesn't know where the "server.pem" file is.
I put these "server.pem" and "server.key" files from the example folder into a "release" folder where the .exe file is created and runs.
Actually I'm quite new to Mongoose and SSL.
Please anybody could help me?
Thanks, regards.
/*
* Copyright (c) 2016 Cesanta Software Limited
* All rights reserved
*/
/*
* This example starts an SSL web server on https://localhost:8443/
*
* Please note that the certificate used is a self-signed one and will not be
* recognised as valid. You should expect an SSL error and will need to
* explicitly allow the browser to proceed.
*/
#include "mongoose.h"
static const char *s_http_port = "8443";
static const char *s_ssl_cert = "server.pem";
static const char *s_ssl_key = "server.key";
static struct mg_serve_http_opts s_http_server_opts;
static void ev_handler(struct mg_connection *nc, int ev, void *p) {
if (ev == MG_EV_HTTP_REQUEST) {
mg_serve_http(nc, (struct http_message *) p, s_http_server_opts);
}
}
int main(void) {
struct mg_mgr mgr;
struct mg_connection *nc;
struct mg_bind_opts bind_opts;
const char *err;
mg_mgr_init(&mgr, NULL);
memset(&bind_opts, 0, sizeof(bind_opts));
bind_opts.ssl_cert = s_ssl_cert;
bind_opts.ssl_key = s_ssl_key;
bind_opts.error_string = &err;
printf("Starting SSL server on port %s, cert from %s, key from %s\n",
s_http_port, bind_opts.ssl_cert, bind_opts.ssl_key);
nc = mg_bind_opt(&mgr, s_http_port, ev_handler, bind_opts);
if (nc == NULL) {
printf("Failed to create listener: %s\n", err);
return 1;
}
// Set up HTTP server parameters
mg_set_protocol_http_websocket(nc);
s_http_server_opts.document_root = "."; // Serve current directory
s_http_server_opts.enable_directory_listing = "yes";
for (;;) {
mg_mgr_poll(&mgr, 1000);
}
mg_mgr_free(&mgr);
return 0;
}
I've had the same issue. You can step into mongoose using gdb or similar tool to find the actual reason for that error message. If you think mongoose isn't finding your files, try using absolute paths. If it finds the file, you might need to regenerate (and/or register) the cert files on your computer.

Verifying my self-signed certificate with openSSL

I own the server and I own the customer's executable. I'd like to establish a secure TLS connection between them.
I can embed whatever I want into the client executable but I'm not sure how to validate a self-assigned certificate that my client received from a connection to the server, i.e. from a SSL_get_peer_certificate call.
I read around that certificates are just public keys with metadata parts signed with the private key. Can I somehow verify that the certificate the server sent me has indeed all the metadata correctly signed by embedding the public key into my client application? Is this possible (and if it is, how?)
I'm not sure how to validate a self-assigned certificate that my client received from a connection to the server ...
Depending on the OpenSSL library you are using, you have to perform two or three steps for verification. The two versions bisect at OpenSSL 1.1.0. OpenSSL 1.1.0 and above performs hostname validation so it only takes two steps. OpenSSL 1.0.2 and below does not perform hostname validation so it requires three steps.
The steps detailed below are from SSL/TLS Client on the OpenSSL wiki.
Server Certificate
Both OpenSSL 1.0.2 and 1.1.0 require you to check for the presence of a certificate. If you use ADH (Anonymous Diffie-Hellman), TLS-PSK (Preshared Key), TLS_SRP (Secure Remote Password), then there may not be a server certificate to verify.
You get the server's certificate with SSL_get_peer_certificate. If it returns non-NULL, then a certificate is present. Lack of a certificate may or may not be a reason to fail.
Certificate Chain
Both OpenSSL 1.0.2 and 1.1.0 require you to check the result of chain validation. Chain validation is part of path building, and its detailed in RFC 4158, Certification Path Building.
You get the result of path validation with SSL_get_verify_result.
Certificate Names
OpenSSL 1.0.2 an below requires you to verify the hostname matches a name listed in the certificate. Its a big topic, but the short of it is: any hostname or dns name needs to be present in the certifcate's Subject Alternative Name (SAN), and not the Common Name (CN). Also see How do you sign Certificate Signing Request with your Certification Authority and How to create a self-signed certificate with openssl? It provides a lot of background information on X.509 server certificates, how to present names, and where the various rules come from.
Effectively, you fetch the SANs with X509_get_ext_d2i(cert, NID_subject_alt_name, ...). Then you loop over the list and extract each name with sk_GENERAL_NAME_num. Then, you extract a GENERAL_NAME entry and ASN1_STRING_to_UTF8, and see if it matches the name you tried to connect to.
Below are the routines for printing the Subject Alternative Name (SAN) and the Common Name (CN). It came from the example on the OpenSSL wiki page.
void print_san_name(const char* label, X509* const cert)
{
int success = 0;
GENERAL_NAMES* names = NULL;
unsigned char* utf8 = NULL;
do
{
if(!cert) break; /* failed */
names = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0 );
if(!names) break;
int i = 0, count = sk_GENERAL_NAME_num(names);
if(!count) break; /* failed */
for( i = 0; i < count; ++i )
{
GENERAL_NAME* entry = sk_GENERAL_NAME_value(names, i);
if(!entry) continue;
if(GEN_DNS == entry->type)
{
int len1 = 0, len2 = -1;
len1 = ASN1_STRING_to_UTF8(&utf8, entry->d.dNSName);
if(utf8) {
len2 = (int)strlen((const char*)utf8);
}
if(len1 != len2) {
fprintf(stderr, " Strlen and ASN1_STRING size do not match (embedded null?): %d vs %d\n", len2, len1);
}
/* If there's a problem with string lengths, then */
/* we skip the candidate and move on to the next. */
/* Another policy would be to fails since it probably */
/* indicates the client is under attack. */
if(utf8 && len1 && len2 && (len1 == len2)) {
fprintf(stdout, " %s: %s\n", label, utf8);
success = 1;
}
if(utf8) {
OPENSSL_free(utf8), utf8 = NULL;
}
}
else
{
fprintf(stderr, " Unknown GENERAL_NAME type: %d\n", entry->type);
}
}
} while (0);
if(names)
GENERAL_NAMES_free(names);
if(utf8)
OPENSSL_free(utf8);
if(!success)
fprintf(stdout, " %s: <not available>\n", label);
}
void print_cn_name(const char* label, X509_NAME* const name)
{
int idx = -1, success = 0;
unsigned char *utf8 = NULL;
do
{
if(!name) break; /* failed */
idx = X509_NAME_get_index_by_NID(name, NID_commonName, -1);
if(!(idx > -1)) break; /* failed */
X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, idx);
if(!entry) break; /* failed */
ASN1_STRING* data = X509_NAME_ENTRY_get_data(entry);
if(!data) break; /* failed */
int length = ASN1_STRING_to_UTF8(&utf8, data);
if(!utf8 || !(length > 0)) break; /* failed */
fprintf(stdout, " %s: %s\n", label, utf8);
success = 1;
} while (0);
if(utf8)
OPENSSL_free(utf8);
if(!success)
fprintf(stdout, " %s: <not available>\n", label);
}
Verifying my self-signed certificate with openSSL
Because its your self-signed certificate, you can do even better than above. You have a priori knowledge of the host's public key. You can pin the public key, and just use the certificate to deliever the public key or as a presentation detail.
To pin the public key, see Public Key Pinning over at OWASP.
You should also avoid the IETF's RFC 7469, Public Key Pinning Extension for HTTP with Overrides. The IETF's rendition allows the attacker to break a known good pinset so the attacker can MitM the connection. They also suppress reporting the problem, so the user agent becomes complicit in the coverup.

Not able to send client certificate over openssl

I am trying to implement MSRP over TLS, which requires me to do TLS handshaking for msrp port, i.e 2855. At the time of handshaking server is requesting for client certificate as expected. At the client end I have generated the certificate and the private key,however i am unable to send the certificate. I am using Doubango stack to communicate with openssl.
"SSL_CTX_use_certificate_file(contexts[i], transport->tls.ca, SSL_FILETYPE_PEM)" is what I am using to try to set the certificate. I think it gets set properly, since it doesn't throw any error. However, no matter what i do , the certificate is never sent to the server.
The Certificates Length is always 0.
Can anyone help me regarding this problem ? These are the steps I am following to generate the client certificate.
https://gist.github.com/mtigas/952344
My code to set the certificates is something like this :
#if HAVE_OPENSSL
{
int32_t i, ret;
SSL_CTX* contexts[3] = { tsk_null };
if(transport->tls.enabled){
contexts[0] = transport->tls.ctx_client;
contexts[1] = transport->tls.ctx_server;
}
TSK_DEBUG_INFO("ca = %s, pbk = %s, pvk = %s", ca, pbk, pvk);
for(i = 0; i < sizeof(contexts)/sizeof(contexts[0]); ++i){
if(!contexts[i]){
continue;
}
SSL_CTX_set_verify(contexts[i], transport->tls.verify ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT) : SSL_VERIFY_NONE, tsk_null);
TSK_DEBUG_INFO("tls.verify :%d", transport->tls.verify);
if(!tsk_strnullORempty(transport->tls.pbk) || !tsk_strnullORempty(transport->tls.pvk) || !tsk_strnullORempty(transport->tls.ca)){
/* Sets Public key (cert) */
if((ret = SSL_CTX_use_certificate_file(contexts[i], transport->tls.ca, SSL_FILETYPE_PEM)) != 1) {
TSK_DEBUG_ERROR("SSL_CTX_use_certificate_file failed [%d,%s]", ret, ERR_error_string(ERR_get_error(), tsk_null));
return -3;
}
/*Sets the password of the private key*/
if(!tsk_strnullORempty(ssl_password)){
SSL_CTX_set_default_passwd_cb_userdata(contexts[i], (void*)ssl_password);
}
/* Sets Private key (cert) */
if (!tsk_strnullORempty(transport->tls.pvk) && (ret = SSL_CTX_use_PrivateKey_file(contexts[i], transport->tls.pvk, SSL_FILETYPE_PEM)) != 1) {
TSK_DEBUG_ERROR("SSL_CTX_use_PrivateKey_file failed [%d,%s]", ret, ERR_error_string(ERR_get_error(), tsk_null));
return -4;
}
/* Checks private key */
if(!tsk_strnullORempty(transport->tls.pvk) && SSL_CTX_check_private_key(contexts[i]) == 0) {
TSK_DEBUG_ERROR("SSL_CTX_check_private_key failed [%d,%s]", ret, ERR_error_string(ERR_get_error(), tsk_null));
return -5;
}
/* Sets trusted CAs and CA file */
if(!tsk_strnullORempty(transport->tls.ca) && (ret = SSL_CTX_load_verify_locations(contexts[i], transport->tls.ca, /*tlsdir_cas*/tsk_null)) != 1) {
TSK_DEBUG_ERROR("SSL_CTX_load_verify_locations failed [%d, %s]", ret, ERR_error_string(ERR_get_error(), tsk_null));
return -5;
}
}
}
}
#endif /* HAVE_OPENSSL */
Since I am not getting any of these errors, I am assuming that the certificates has been properly set. But still when server request for the certificates, the client fails to send it. i.e Certificates Length = 0.
Is there a way to peek into openssl if it is throwing any errors? Where can i get the openssl logs. ?
Please help or my leaves wouldnt get approved :(
I think you should check the Certificate types in Crtificate Request message. If your client certificate encryption doesn't match, then the client may not send certificate.