[C] Client/Serveur SSL/TLS multiplateformes avec OpenSSL

03
Jul
2012
  • Google Plus
  • LinkedIn
  • Viadeo
Posted by: Yann C.  /   Category: Network and system administration / Cryptography / Cryptology / OS / Programming & Development / Projects & tools / Windows   /   No Comments

Au cours de la plupart des développements actuels de logiciels exploitant les réseaux, la sécurité de ces échanges est primordiale. Une des solutions les plus employée de part sa facilité d’intégration, sa standardisation et qui a fait ses preuves est une encapsulation via le protocole SSL/TLS.

SSL (Secure Socket Layer) / TLS (Transport Layer Security) est un protocole permettant de relier des systèmes informatiques entre eux d’une manière sécurisée. Garantissant l’intégrité des échanges, la confidentialité et l’authentification des données, ce protocole est un standard en termes de protocole sécurisé. Datant de de 1994, SSL se découpe en 3 versions (1.0 non-utilisée, 2.0 jugée à présent obsolète et insécurisée et 3.0 extrêmement déployée). Après une standardisation du protocole par l’IETF en 2001, SSL à changé de nom pour TLS qui lui aussi se découpe en 3 version (1.0 très déployée, 1.1 et 1.2 qui étendent ses fonctionnalités).

SSL/TLS se découpe en 4 sous-protocoles:

  • Handshake : la négociation des paramètres de sécurité en tant que tel.
  • Change Cipher Spec : la validation de la négociation préalable, pour vérifier que les deux partis se sont bien accordés quant à la clé maîtresse générée, aux algorithmes à employer etc.
  • Alert : protocole informatif de l’état de la liaison.
  • Record : protocole d’acheminement des données de la communication. Ce protocole peut encapsuler tout autre protocole et le rend ainsi sécurisé.

SSL/TLS évolue à l’inter-couche transport/application de la pile OSI. Il est utilisé avec d’autres protocoles standardisés tels que HTTP, FTP ou encore SMPT en leur ajoutant un “S” final. Pour les puristes, “HTTPS”, “FTPS” ou “STMPS” ne sont pas des protocoles en tant que tel. Ce sont des encapsulations de protocoles insécurisés (HTTP) dans une couche SSL/TLS ; d’où leur mise en italique dans la figure suivante.

Pile OSI et placement du protocole SSL/TLS

Pile OSI et placement du protocole SSL/TLS

Ce protocole se fonde initialement sur un mode de transport TCP (pouvant être UDP pour le DTLS, WTLS…) et s’implémente dans des développements logiciels par le biais d’API dont certaines des plus connues sont:

  • OpenSSL : l’API de référence.
  • GnuTLS : alternative à OpenSSL
  • yaSSL : version destinée au monde de l’embarqué
  • MatrixSSL : cible également le monde de l’embarqué

Au sein de cet article, il vous est présenté une implémentation simple d’un client et d’un serveur exploitant le protocole SSL/TLS pour communiquer via l’API OpenSSL. Ce client/serveur est multi-plateformes Windows/Linux.

Fonctionnalité du serveur :

  • Se met en écoute sur un port défini
  • Permet d’utiliser les versions SSL2.0, SSL3.0n SSL2.0 & 3.0, TLS1.0
  • Permet de charger un certificat contenant une clé publique à partir d’un fichier, idem concernant la clé privée.
  • Permet d’utiliser un certificat contenant une clé publique et une clé privée codés en dur dans l’application, au format PEM (encodage base64 du format DER).
  • Permet de générer un nouveau certificat et une nouvelle clé publique dynamiquement à chaque lancement du serveur.
  • Le serveur vérifie la correspondance entre le certificat et la clé privée avant de se mettre en écoute.
  • Le serveur patiente jusqu’à la connexion d’un client. Il affiche les détails du potentiel certificat envoyé par le client (facultatif) et attend la réception d’un message via le protocole “record“.
  • Lorsqu’un message arrive, celui-ci est directement retourné au client (ping-pong) puis le serveur attend une nouvelle connexion.
Code source du serveur :
[c]/** SSL/TLS Server<br /><br /><br />
* SSL/TLS server demonstration. This source code is cross-plateforme Windows and Linux.<br /><br /><br />
* Compile under Linux with : g++ main.cpp -Wall -lssl -lcrypto -o main<br /><br /><br />
* Certificat and private key to protect transaction can be used from :<br /><br /><br />
* – External(s) file(s), created with command : openssl req -x509 -nodes -newkey rsa:2048 -keyout server.pem -out server.pem<br /><br /><br />
* – Internal uniq hardcoded certificat and private key, equal into each server instance<br /><br /><br />
* – Randomly generated certificat and private key, best solution to used dynamic keying material at each server lauching.<br /><br /><br />
* Usage :<br /><br /><br />
* # run the server on port 1337 for SSLv2&3 protocol with internals key and certificat<br /><br /><br />
* $ [./]server[.exe] 1337<br /><br /><br />
* # run the server on port 1337 for TLSv1 protocol with key and certificat in server.pem file<br /><br /><br />
* $ [./]server[.exe] 1337 1 server.pem server.pem<br /><br /><br />
* @author x@s<br /><br /><br />
*/</p><br /><br />
<p>#define DEFAULT_PORT 443</p><br /><br />
<p>#ifdef __unix__ // __unix__ is usually defined by compilers targeting Unix systems<br /><br /><br />
# include <unistd.h><br /><br /><br />
# include <sys/socket.h><br /><br /><br />
# include <arpa/inet.h><br /><br /><br />
# include <resolv.h><br /><br /><br />
# define SOCKLEN_T socklen_t<br /><br /><br />
# define CLOSESOCKET close<br /><br /><br />
#elif defined _WIN32 // _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems<br /><br /><br />
# include <windows.h><br /><br /><br />
# include <winsock2.h><br /><br /><br />
# define SOCKLEN_T int<br /><br /><br />
# define CLOSESOCKET closesocket<br /><br /><br />
#endif</p><br /><br />
<p>#include <stdio.h><br /><br /><br />
#include <errno.h><br /><br /><br />
#include <unistd.h><br /><br /><br />
#include <malloc.h><br /><br /><br />
#include <string.h></p><br /><br />
<p>#include <openssl/crypto.h><br /><br /><br />
#include <openssl/x509v3.h><br /><br /><br />
#include <openssl/pem.h><br /><br /><br />
#include <openssl/ssl.h><br /><br /><br />
#include <openssl/err.h><br /><br /><br />
#include <openssl/bio.h></p><br /><br />
<p>#ifdef _WIN32<br /><br /><br />
WSADATA wsa; // Winsock data<br /><br /><br />
#endif</p><br /><br />
<p>/**<br /><br /><br />
* printUsage function who describe the utilisation of this script.<br /><br /><br />
* @param char* bin : the name of the current binary.<br /><br /><br />
*/<br /><br /><br />
void printHeader(char* bin){<br /><br /><br />
printf("[?] Usage : %s <port> [<method> <server_cert> <server_private_key>]\n", bin);<br /><br /><br />
printf("[?] With <method> :\n");<br /><br /><br />
printf("\t1 :\tTLS v1\n");<br /><br /><br />
printf("\t2 :\tSSL v2 (deprecated so disabled)\n");<br /><br /><br />
printf("\t3 :\tSSL v3\n");<br /><br /><br />
printf("\t4 :\tSSL v2 & v3 (default)\n");<br /><br /><br />
return;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* makeServerSocket function who create a traditionnal server socket, bind it and listen to it.<br /><br /><br />
* @param int port : the port to listen<br /><br /><br />
* @return int socket : the socket number created<br /><br /><br />
*/<br /><br /><br />
int makeServerSocket(int port){<br /><br /><br />
int sock;<br /><br /><br />
struct sockaddr_in addr;<br /><br /><br />
#ifdef _WIN32<br /><br /><br />
WSAStartup(MAKEWORD(2,0),&wsa);<br /><br /><br />
#endif<br /><br /><br />
sock = socket(PF_INET, SOCK_STREAM, 0);<br /><br /><br />
memset(&addr, 0, sizeof(addr));<br /><br /><br />
addr.sin_family = AF_INET;<br /><br /><br />
addr.sin_port = htons(port);<br /><br /><br />
addr.sin_addr.s_addr = INADDR_ANY;<br /><br /><br />
if(bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0){<br /><br /><br />
perror("[-] Can’t bind port on indicated port…");<br /><br /><br />
abort();<br /><br /><br />
}<br /><br /><br />
if(listen(sock, 10) != 0){<br /><br /><br />
perror("[-] Can’t listening on indicated port…");<br /><br /><br />
abort();<br /><br /><br />
}<br /><br /><br />
printf("[+] Server listening on the %d port…\n", port);<br /><br /><br />
return sock;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* callbackGeneratingKey called during internal dynamic key generation.<br /><br /><br />
* A callback function may be used to provide feedback about the<br /><br /><br />
* progress of the key generation. If callback is not NULL, it will<br /><br /><br />
* be called as follows:<br /><br /><br />
* – While a random prime number is generated, it is called as<br /><br /><br />
* described in BN_generate_prime(3).<br /><br /><br />
* – When the n-th randomly generated prime is rejected as not<br /><br /><br />
* suitable for the key, callback(2, n, cb_arg) is called.<br /><br /><br />
* – When a random p has been found with p-1 relatively prime to e,<br /><br /><br />
* it is called as callback(3, 0, cb_arg).<br /><br /><br />
* The process is then repeated for prime q with callback(3, 1, cb_arg).<br /><br /><br />
* @param int p : callback random prime flag<br /><br /><br />
* @param int n : n-th randomly generation<br /><br /><br />
* @param void *arg : argument for the callback passed from initial call<br /><br /><br />
*/<br /><br /><br />
static void callbackGeneratingKey(int p, int n, void *arg){<br /><br /><br />
char c=’B’;<br /><br /><br />
if (p == 0) c = ‘.’; // generating key…<br /><br /><br />
if (p == 1) c = ‘+’; // near the end of generation…<br /><br /><br />
if (p == 2) c = ‘*’; // rejecting current random generation…<br /><br /><br />
if (p == 3) c = ‘\n’; // key generated<br /><br /><br />
fputc(c, stderr); // print generation state<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* makekCert function who create the server certificat containing public key and<br /><br /><br />
* the server private key signed (dynamic method).<br /><br /><br />
* @param X509 **x509p : potential previous instance of X509 certificat<br /><br /><br />
* @param EVP_PKEY **pkeyp : potential previous instance of private key<br /><br /><br />
* @param int bits : length of the RSA key to generate (precaunized greater than or equal 2048b)<br /><br /><br />
* @param int serial : long integer representing a serial number<br /><br /><br />
* @param int days : number of valid days of the certificat<br /><br /><br />
* @see Inpired from /demos/x509/mkcert.c file of OpenSSL library.<br /><br /><br />
*/<br /><br /><br />
void makekCert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days){<br /><br /><br />
X509 *x;<br /><br /><br />
EVP_PKEY *pk;<br /><br /><br />
RSA *rsa;<br /><br /><br />
X509_NAME *name = NULL;</p><br /><br />
<p>if((pkeyp == NULL) || (*pkeyp == NULL)){<br /><br /><br />
if((pk = EVP_PKEY_new()) == NULL)<br /><br /><br />
abort();<br /><br /><br />
} else<br /><br /><br />
pk= *pkeyp;<br /><br /><br />
if((x509p == NULL) || (*x509p == NULL)){<br /><br /><br />
if ((x = X509_new()) == NULL)<br /><br /><br />
abort();<br /><br /><br />
} else<br /><br /><br />
x= *x509p;</p><br /><br />
<p>// create RSA key<br /><br /><br />
rsa = RSA_generate_key(bits, RSA_F4, callbackGeneratingKey, NULL);<br /><br /><br />
if(!EVP_PKEY_assign_RSA(pk, rsa))<br /><br /><br />
abort();<br /><br /><br />
rsa = NULL;</p><br /><br />
<p>X509_set_version(x, 2); // why not 3 ?<br /><br /><br />
ASN1_INTEGER_set(X509_get_serialNumber(x), serial);<br /><br /><br />
X509_gmtime_adj(X509_get_notBefore(x), 0); // define validation begin cert<br /><br /><br />
X509_gmtime_adj(X509_get_notAfter(x), (long)60*60*24*days); // define validation end cert<br /><br /><br />
X509_set_pubkey(x, pk); // define public key in cert<br /><br /><br />
name = X509_get_subject_name(x);</p><br /><br />
<p>// This function creates and adds the entry, working out the<br /><br /><br />
// correct string type and performing checks on its length.<br /><br /><br />
// Normally we’d check the return value for errors…<br /><br /><br />
X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (const unsigned char*)"XX", -1, -1, 0); // useless if more anonymity needed<br /><br /><br />
X509_NAME_add_entry_by_txt(name,"CN", MBSTRING_ASC, (const unsigned char*)"ASRAT", -1, -1, 0); // useless if more anonymity needed</p><br /><br />
<p>// Its self signed so set the issuer name to be the same as the subject.<br /><br /><br />
X509_set_issuer_name(x, name);</p><br /><br />
<p>if(!X509_sign(x, pk, EVP_md5())) // secured more with sha1? md5/sha1? sha256?<br /><br /><br />
abort();</p><br /><br />
<p>*x509p = x;<br /><br /><br />
*pkeyp = pk;<br /><br /><br />
return;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* initSSLContext function who initialize the SSL/TLS engine with right method/protocol<br /><br /><br />
* @param int ctxMethod : the number coresponding to the method/protocol to use<br /><br /><br />
* @return SSL_CTX *ctx : a pointer to the SSL context created<br /><br /><br />
*/<br /><br /><br />
SSL_CTX* initSSLContext(int ctxMethod){<br /><br /><br />
const SSL_METHOD *method;<br /><br /><br />
SSL_CTX *ctx;</p><br /><br />
<p>SSL_library_init(); // initialize the SSL library<br /><br /><br />
SSL_load_error_strings(); // bring in and register error messages<br /><br /><br />
OpenSSL_add_all_algorithms(); // load usable algorithms</p><br /><br />
<p>switch(ctxMethod){ // create new client-method instance<br /><br /><br />
case 1 :<br /><br /><br />
method = TLSv1_server_method();<br /><br /><br />
printf("[+] Use TLSv1 method.\n");<br /><br /><br />
break;<br /><br /><br />
// SSLv2 isn’t sure and is deprecated, so the latest OpenSSL version on Linux delete his implementation.<br /><br /><br />
/*case 2 :<br /><br /><br />
method = SSLv2_server_method();<br /><br /><br />
printf("[+] Use SSLv2 method.\n");<br /><br /><br />
break;*/<br /><br /><br />
case 3 :<br /><br /><br />
method = SSLv3_server_method();<br /><br /><br />
printf("[+] Use SSLv3 method.\n");<br /><br /><br />
break;<br /><br /><br />
case 4 :<br /><br /><br />
method = SSLv23_server_method();<br /><br /><br />
printf("[+] Use SSLv2&3 method.\n");<br /><br /><br />
break;<br /><br /><br />
default :<br /><br /><br />
method = SSLv23_server_method();<br /><br /><br />
printf("[+] Use SSLv2&3 method.\n");<br /><br /><br />
}</p><br /><br />
<p>ctx = SSL_CTX_new(method); // create new context from selected method<br /><br /><br />
if(ctx == NULL){<br /><br /><br />
ERR_print_errors_fp(stderr);<br /><br /><br />
abort();<br /><br /><br />
}<br /><br /><br />
return ctx;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* loadCertificates function who load private key and certificat from files.<br /><br /><br />
* 3 mecanisms available :<br /><br /><br />
* – loading certificate and private key from file(s)<br /><br /><br />
* – use embed hardcoded certificate and private key in the PEM format<br /><br /><br />
* – generate random and dynamic certificate and private key at each server’s launch instance.<br /><br /><br />
* @param SSL_CTX* ctx : the SSL/TLS context<br /><br /><br />
* @param char *certFile : filename of the PEM certificat<br /><br /><br />
* @param char *keyFile : filename of the PEM private key<br /><br /><br />
*/<br /><br /><br />
void loadCertificates(SSL_CTX* ctx, const char* certFile, const char* keyFile){<br /><br /><br />
// The server private key in PEM format, if internals required<br /><br /><br />
/*const char *keyBuffer = "—–BEGIN PRIVATE KEY—–\n"<br /><br /><br />
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDP1SC2T/+NW59H\n"<br /><br /><br />
"CYF0mzkoFcObGUAkoK7mvemFk2P99FLcKbqYKZZDMLVBg+tLU12kuIefYrC4G8F7\n"<br /><br /><br />
"K8WReTZ+ZBWI1h+gEBhilZ0O4+XXoww2tjVyuHNe5twSxOhRYvoPNSKMLPR70Oij\n"<br /><br /><br />
"b4nHSyu0a7JHAWvEdpk7HIeWugKYbY8ss58iCmkWGcrop/od6SPW12W+ugAyDGD9\n"<br /><br /><br />
"F1Otrmb+T3KQPadlPgGdNprvVXHjk+eS1RcwOsT630usogl1JqhoAT4ViQvxDP0J\n"<br /><br /><br />
"LEffPvG2Iow2WoRtjLGfKqGinhtrLyuht5s3XBzm05kHYNVDc1vkWPvk4PuoIfTp\n"<br /><br /><br />
"ezrxuMR5AgMBAAECggEADV6wlAnhbr6OKIu8ADxcGPANfVTKg5Cyr7VX6Hfq3tNw\n"<br /><br /><br />
"4SjuEAvc1sWzY1uRL29VfttAHkjDBZUDhWDzfMBHeSoHGJ5tumZOq0jkqaiPiKe8\n"<br /><br /><br />
"iWh/V7n18gz3610vdMzhOUk5x7q8n5p43Mq4GlIDpb+n4Fl/DUxz3xGex1t//z4v\n"<br /><br /><br />
"W7U1j+dKxiZGaNz2dyVVM7eHaynvEE4QL8i4msjhmrFSItqjF/0M/CJ0oEPPb2VL\n"<br /><br /><br />
"6GLSfqCcjBzt0Sy93gVNhxO+KjMpumB1a9omDxBkTO4HF4xoDojrtkgYXaUx3uKk\n"<br /><br /><br />
"Gc35xLoOdkn/pNDDzGzQT+xWYOO6IBxJGj/INvnIAQKBgQDwdVsC02z0Pb4JrlcM\n"<br /><br /><br />
"KRBGyJetxxQguiZ3TYMIGMMP/fQZn3uofmWxNGPbk20VmDXXtZFsCJG7zrFVOUe3\n"<br /><br /><br />
"eXIPjE2ho80aPAMWeiPAMkivhj0OnPHTg5sof75uH5F9zPerw7kgcwZMFPZk/Za0\n"<br /><br /><br />
"53gxjakIZo2mlrtaomZLD/U+2QKBgQDdQ/EQlMG5+sjGn6MQrqpzlIT+PYQ4OmFE\n"<br /><br /><br />
"p8B6AKtwC1oVKkY/1dWVUQ33DqTbXv8i8zN2mplMaFM/6rJNcY4BhKwBm+pW5XuV\n"<br /><br /><br />
"LHLMGGkubues3bCb2OHax8DOm/i6hDJ14cEORsZSA2Jt6qzxaQ9HrtCZy29S5FIg\n"<br /><br /><br />
"cFGCLHNuoQKBgAIe5tiViMZ2rPBk6zueORiGuF+9+712JtSyiE9P+Jhxgu+e6nZH\n"<br /><br /><br />
"9xmi/qZ3HGUuXHs0jL3JLY/ceM/pm2pQ1eKxOBYO3cY3dUeDeEE/sEhsBKnWVIOr\n"<br /><br /><br />
"C3lF9yX9fUkAv8ZyCXXxzcJqBOpLGkMqL3Mwbqc2UFWBytE30XMkBuOxAoGBAI8l\n"<br /><br /><br />
"qGzAwIBwpboShy2AwteZq1zMMaEq68i9+oEzs7X+Mh5lRiOAVPiQAsfmGnOuBsP2\n"<br /><br /><br />
"sUG3DRxolgtQ7F+76lJDIgC8fSQQvR4qLm6qEEoxCANHPT3mV1/yQWOpdoY8hmTL\n"<br /><br /><br />
"U9nHogBnHiPcYlygSnlmuJ/3BCONgTBpWeIsndVhAoGAOFpnITiCmUFc5AUaxglZ\n"<br /><br /><br />
"fz4fC+Mt4SF4XGFUtL8feGN4XGXHU6lQVQqu1yaRpYjSTabq6V6LLvVOh1sb+qZw\n"<br /><br /><br />
"sSB4hC5C+VjjIBScsaN0pytFdL0+FeRaGPVBUs/yBWzfhi6Lm9vE8ebE0fMxr7b5\n"<br /><br /><br />
"gw4qJCTvXYDZ8ZOIwG4YRRs=\n"<br /><br /><br />
"—–END PRIVATE KEY—–\n";<br /><br /><br />
// The server certificat containing public key in PEM format<br /><br /><br />
const char *certBuffer = "—–BEGIN CERTIFICATE—–\n"<br /><br /><br />
"MIIDiTCCAnGgAwIBAgIJAK0drhMsLqg2MA0GCSqGSIb3DQEBBQUAMFsxCzAJBgNV\n"<br /><br /><br />
"BAYTAlhYMQowCAYDVQQIDAFYMQowCAYDVQQHDAFYMQowCAYDVQQKDAFYMQowCAYD\n"<br /><br /><br />
"VQQLDAFYMQowCAYDVQQDDAFYMRAwDgYJKoZIhvcNAQkBFgFYMB4XDTEyMDMwMTEz\n"<br /><br /><br />
"NDcwM1oXDTEyMDMzMTEzNDcwM1owWzELMAkGA1UEBhMCWFgxCjAIBgNVBAgMAVgx\n"<br /><br /><br />
"CjAIBgNVBAcMAVgxCjAIBgNVBAoMAVgxCjAIBgNVBAsMAVgxCjAIBgNVBAMMAVgx\n"<br /><br /><br />
"EDAOBgkqhkiG9w0BCQEWAVgwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n"<br /><br /><br />
"AQDP1SC2T/+NW59HCYF0mzkoFcObGUAkoK7mvemFk2P99FLcKbqYKZZDMLVBg+tL\n"<br /><br /><br />
"U12kuIefYrC4G8F7K8WReTZ+ZBWI1h+gEBhilZ0O4+XXoww2tjVyuHNe5twSxOhR\n"<br /><br /><br />
"YvoPNSKMLPR70Oijb4nHSyu0a7JHAWvEdpk7HIeWugKYbY8ss58iCmkWGcrop/od\n"<br /><br /><br />
"6SPW12W+ugAyDGD9F1Otrmb+T3KQPadlPgGdNprvVXHjk+eS1RcwOsT630usogl1\n"<br /><br /><br />
"JqhoAT4ViQvxDP0JLEffPvG2Iow2WoRtjLGfKqGinhtrLyuht5s3XBzm05kHYNVD\n"<br /><br /><br />
"c1vkWPvk4PuoIfTpezrxuMR5AgMBAAGjUDBOMB0GA1UdDgQWBBRG76BYshU93k3q\n"<br /><br /><br />
"hy6gIpMl/VUDhTAfBgNVHSMEGDAWgBRG76BYshU93k3qhy6gIpMl/VUDhTAMBgNV\n"<br /><br /><br />
"HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBCGmmyVt9gRJ0fuWh9o5MnT70m\n"<br /><br /><br />
"nwbt0fM3Z6AO/Gkc0fkc6H4pZ3tnEtubtXBBm24wMFfXutcXFAjZMk0OTCPj5U8I\n"<br /><br /><br />
"0/yjk5zuBdgktIFUTjs4Os/Ct2wvIfIiOm/WeL3FZOWli/HOX1PqjbeF/HXN+069\n"<br /><br /><br />
"31U++ajDzM0uDFGc7dEPTXTEuE7w81696n9PTF0PSLt3/xIOwkMx28Wykc9XKgAp\n"<br /><br /><br />
"MztGxeEtyb32ib+zL7UhEyuDHnW4haC8QsjG1QLpESTMMASbRe6QxrYxuMFjkf+g\n"<br /><br /><br />
"FMw9jUYsThZropV2gFipcltT63ncyk0/W8gj1zmF6QsC46r1MFPUfnc/I6dx\n"<br /><br /><br />
"—–END CERTIFICATE—–\n";*/<br /><br /><br />
X509 *cert = NULL;<br /><br /><br />
EVP_PKEY *pkey = NULL;<br /><br /><br />
// RSA *rsa = NULL; // if internal private key and certificat required<br /><br /><br />
//BIO *cbio, *kbio; // if internal private key and certificat required</p><br /><br />
<p>if(certFile == NULL || keyFile == NULL){</p><br /><br />
<p>/*<br /><br /><br />
// if internal certificat and private key required<br /><br /><br />
printf("[*] Loading internal server’s certificat and private key.\n");<br /><br /><br />
cbio = BIO_new_mem_buf((void*)certBuffer, -1);<br /><br /><br />
PEM_read_bio_X509(cbio, &cert, 0, NULL);<br /><br /><br />
SSL_CTX_use_certificate(ctx, cert);<br /><br /><br />
kbio = BIO_new_mem_buf((void*)keyBuffer, -1);<br /><br /><br />
PEM_read_bio_RSAPrivateKey(kbio, &rsa, 0, NULL);<br /><br /><br />
SSL_CTX_use_RSAPrivateKey(ctx, rsa);<br /><br /><br />
*/</p><br /><br />
<p>printf("[*] Generate random server’s certificat and private key.\n");<br /><br /><br />
makekCert(&cert, &pkey, 2048, 0, 0);<br /><br /><br />
SSL_CTX_use_certificate(ctx, cert);<br /><br /><br />
SSL_CTX_use_PrivateKey(ctx, pkey);</p><br /><br />
<p>// set the local certificate from certFile if certFile specified<br /><br /><br />
// set the private key from keyFile (may be the same as certFile) if specified<br /><br /><br />
} else if(SSL_CTX_use_certificate_file(ctx, certFile, SSL_FILETYPE_PEM) <= 0 ||<br /><br /><br />
SSL_CTX_use_RSAPrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) <= 0){<br /><br /><br />
ERR_print_errors_fp(stderr);<br /><br /><br />
abort();<br /><br /><br />
} else<br /><br /><br />
printf("[*] Server’s certificat and private key loaded from file.\n");</p><br /><br />
<p>// verify private key match the public key into the certificate<br /><br /><br />
if(!SSL_CTX_check_private_key(ctx)){<br /><br /><br />
fprintf(stderr, "[-] Private key does not match the public certificate…\n");<br /><br /><br />
abort();<br /><br /><br />
} else<br /><br /><br />
printf("[+] Server’s private key match public certificat !\n");<br /><br /><br />
return;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* showCerts function who catch and print out certificate’s data from the client.<br /><br /><br />
* @param SSL* ssl : the SSL/TLS connection<br /><br /><br />
*/<br /><br /><br />
void showCerts(SSL* ssl){<br /><br /><br />
X509 *cert;<br /><br /><br />
char *subject, *issuer;</p><br /><br />
<p>cert = SSL_get_peer_certificate(ssl); // get the client’s certificate<br /><br /><br />
if(cert != NULL){<br /><br /><br />
subject = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); // get certificate’s subject<br /><br /><br />
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); // get certificate’s issuer</p><br /><br />
<p>printf("[+] Client certificates :\n");<br /><br /><br />
printf("\tSubject: %s\n", subject);<br /><br /><br />
printf("\tIssuer: %s\n", issuer);</p><br /><br />
<p>free(subject); // free the malloc’ed string<br /><br /><br />
free(issuer); // free the malloc’ed string<br /><br /><br />
X509_free(cert); // free the malloc’ed certificate copy<br /><br /><br />
}<br /><br /><br />
else<br /><br /><br />
printf("[-] No client’s certificates\n");<br /><br /><br />
return;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* routine function who treat the content of data received and reply to the client.<br /><br /><br />
* this function is threadable and his context sharedable.<br /><br /><br />
* @param SSL* ssl : the SSL/TLS connection<br /><br /><br />
*/<br /><br /><br />
void routine(SSL* ssl){<br /><br /><br />
char buf[1024], reply[1024];<br /><br /><br />
int sock, bytes;<br /><br /><br />
const char* echo = "Enchante %s, je suis ServerName.\n";</p><br /><br />
<p>if(SSL_accept(ssl) == -1) // accept SSL/TLS connection<br /><br /><br />
ERR_print_errors_fp(stderr);<br /><br /><br />
else{<br /><br /><br />
printf("[+] Cipher used : %s\n", SSL_get_cipher(ssl));<br /><br /><br />
showCerts(ssl); // get any client certificates<br /><br /><br />
bytes = SSL_read(ssl, buf, sizeof(buf)); // read data from client request<br /><br /><br />
if(bytes > 0){<br /><br /><br />
buf[bytes] = 0;<br /><br /><br />
printf("[+] Client data received : %s\n", buf);<br /><br /><br />
sprintf(reply, echo, buf); // construct response<br /><br /><br />
SSL_write(ssl, reply, strlen(reply)); // send response<br /><br /><br />
} else {<br /><br /><br />
switch(SSL_get_error(ssl, bytes)){<br /><br /><br />
case SSL_ERROR_ZERO_RETURN :<br /><br /><br />
printf("SSL_ERROR_ZERO_RETURN : ");<br /><br /><br />
break;<br /><br /><br />
case SSL_ERROR_NONE :<br /><br /><br />
printf("SSL_ERROR_NONE : ");<br /><br /><br />
break;<br /><br /><br />
case SSL_ERROR_SSL:<br /><br /><br />
printf("SSL_ERROR_SSL : ");<br /><br /><br />
break;<br /><br /><br />
}<br /><br /><br />
ERR_print_errors_fp(stderr);<br /><br /><br />
}</p><br /><br />
<p>}<br /><br /><br />
sock = SSL_get_fd(ssl); // get traditionnal socket connection from SSL connection<br /><br /><br />
SSL_shutdown(ssl);<br /><br /><br />
SSL_free(ssl); // release SSL connection state<br /><br /><br />
CLOSESOCKET(sock); // close socket<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* main function who coordinate the socket and SSL connection creation, then receive and emit data to and from the client.<br /><br /><br />
*/<br /><br /><br />
int main(int argc, char **argv){<br /><br /><br />
int sock, ctxMethod, port;<br /><br /><br />
SSL_CTX *ctx;<br /><br /><br />
const char *certFile, *keyFile;</p><br /><br />
<p>if(argc != 2 && argc != 5){<br /><br /><br />
printHeader(argv[0]);<br /><br /><br />
exit(0);<br /><br /><br />
}</p><br /><br />
<p>port = (atoi(argv[1]) > 0 && atoi(argv[1]) < 65535) ? atoi(argv[1]) : DEFAULT_PORT;<br /><br /><br />
ctxMethod = (argc >= 3) ? atoi(argv[2]) : 4; // SSLv2, SSLv3, SSLv2&3 or TLSv1<br /><br /><br />
ctx = initSSLContext(ctxMethod); // load SSL library and dependances<br /><br /><br />
certFile = (argc >= 4) ? argv[3] : NULL;<br /><br /><br />
keyFile = (argc >= 5) ? argv[4] : NULL;</p><br /><br />
<p>loadCertificates(ctx, certFile, keyFile); // load certificats and keys</p><br /><br />
<p>sock = makeServerSocket(port); // make a classic server socket</p><br /><br />
<p>while(42){<br /><br /><br />
struct sockaddr_in addr;<br /><br /><br />
SSL *ssl;<br /><br /><br />
SOCKLEN_T len = sizeof(addr);<br /><br /><br />
int client = accept(sock, (struct sockaddr*)&addr, &len); // accept connection of client<br /><br /><br />
printf("[+] Connection [%s:%d]\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));<br /><br /><br />
ssl = SSL_new(ctx); // get new SSL state with context<br /><br /><br />
SSL_set_fd(ssl, client); // set traditionnal socket to SSL<br /><br /><br />
routine(ssl); // apply routine to the socket’s content<br /><br /><br />
}</p><br /><br />
<p>CLOSESOCKET(sock); // close socket<br /><br /><br />
#ifdef _WIN32<br /><br /><br />
WSACleanup(); // Windows’s Winsock clean<br /><br /><br />
#endif<br /><br /><br />
SSL_CTX_free(ctx); // release SSL’s context<br /><br /><br />
return 0;<br /><br /><br />
}</p><br /><br />
<p>[/c]

Fonctionnalités du client :

  • Se connecte à un serveur sur un port défini
  • Utilise la version du protocole au choix entre SSL2.0, SSL3.0n SSL2.0 & 3.0, TLS1.0
  • Envoi un message au serveur et attend le retour de celui-ci.
Code source du client :
[c]/** SSL/TLS Client<br /><br /><br />
* SSL/TLS client demonstration. This source code is cross-plateforme Windows and Linux.<br /><br /><br />
* Compile under Linux with : g++ main.cpp -Wall -lssl -lcrypto -o main<br /><br /><br />
* Usage :<br /><br /><br />
* # run the client to 127.0.0.1 on port 1337 for SSLv2&3 protocol<br /><br /><br />
* $ [./]client[.exe] 127.0.0.1 1337<br /><br /><br />
* # run the client to 127.0.0.1 on port 1337 for TLSv1 protocol<br /><br /><br />
* $ [./]client[.exe] 127.0.0.1 1337 1<br /><br /><br />
* @author x@s<br /><br /><br />
*/</p><br /><br />
<p>#define DEFAULT_PORT 443</p><br /><br />
<p>#ifdef __unix__ // __unix__ is usually defined by compilers targeting Unix systems<br /><br /><br />
# include <unistd.h><br /><br /><br />
# include <sys/socket.h><br /><br /><br />
# include <resolv.h><br /><br /><br />
# include <netdb.h><br /><br /><br />
# define SOCKLEN_T socklen_t<br /><br /><br />
# define CLOSESOCKET close<br /><br /><br />
#elif defined _WIN32 // _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems<br /><br /><br />
# include <windows.h><br /><br /><br />
# include <winsock2.h><br /><br /><br />
# define SOCKLEN_T int<br /><br /><br />
# define CLOSESOCKET closesocket<br /><br /><br />
#endif</p><br /><br />
<p>#include <stdio.h><br /><br /><br />
#include <errno.h><br /><br /><br />
#include <malloc.h><br /><br /><br />
#include <string.h></p><br /><br />
<p>#include <openssl/crypto.h><br /><br /><br />
#include <openssl/x509.h><br /><br /><br />
#include <openssl/pem.h><br /><br /><br />
#include <openssl/ssl.h><br /><br /><br />
#include <openssl/err.h></p><br /><br />
<p>#ifdef _WIN32<br /><br /><br />
WSADATA wsa; // Winsock data<br /><br /><br />
#endif</p><br /><br />
<p>/**<br /><br /><br />
* printUsage function who describe the utilisation of this script.<br /><br /><br />
* @param char* bin : the name of the current binary.<br /><br /><br />
*/<br /><br /><br />
void printHeader(char* bin){<br /><br /><br />
printf("[?] Usage : %s <hostname> <port> [<method>]\n", bin);<br /><br /><br />
printf("[?] With optional <method> :\n");<br /><br /><br />
printf("\t1 :\tTLS v1\n");<br /><br /><br />
printf("\t2 :\tSSL v2 (deprecated so disabled)\n");<br /><br /><br />
printf("\t3 :\tSSL v3\n");<br /><br /><br />
printf("\t4 :\tSSL v2 & v3 (default)\n");<br /><br /><br />
return;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* makeClientSocket function who create a traditionnal client socket to the hostname throught the port.<br /><br /><br />
* @param char* hostname : the target to connect to<br /><br /><br />
* @param int port : the port to connect throught<br /><br /><br />
* @return int socket ; the socket number created<br /><br /><br />
*/<br /><br /><br />
int makeClientSocket(const char *hostname, int port){<br /><br /><br />
int sock;<br /><br /><br />
struct hostent *host;<br /><br /><br />
struct sockaddr_in addr;<br /><br /><br />
#ifdef _WIN32<br /><br /><br />
WSAStartup(MAKEWORD(2,0),&wsa);<br /><br /><br />
#endif<br /><br /><br />
if((host = gethostbyname(hostname)) == NULL ){<br /><br /><br />
perror(hostname);<br /><br /><br />
abort();<br /><br /><br />
}<br /><br /><br />
sock = socket(PF_INET, SOCK_STREAM, 0);<br /><br /><br />
memset(&addr, 0, sizeof(addr));<br /><br /><br />
addr.sin_family = AF_INET;<br /><br /><br />
addr.sin_port = htons(port);<br /><br /><br />
addr.sin_addr.s_addr = *(long*)(host->h_addr);<br /><br /><br />
if(connect(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0){<br /><br /><br />
CLOSESOCKET(sock);<br /><br /><br />
perror(hostname);<br /><br /><br />
abort();<br /><br /><br />
}<br /><br /><br />
return sock;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* initSSLContext function who initialize the SSL/TLS engine with right method/protocol<br /><br /><br />
* @param int ctxMethod : the number coresponding to the method/protocol to use<br /><br /><br />
* @return SSL_CTX *ctx ; a pointer to the SSL context created<br /><br /><br />
*/<br /><br /><br />
SSL_CTX* initSSLContext(int ctxMethod){<br /><br /><br />
const SSL_METHOD *method;<br /><br /><br />
SSL_CTX *ctx;</p><br /><br />
<p>SSL_library_init(); // initialize the SSL library<br /><br /><br />
SSL_load_error_strings(); // bring in and register error messages<br /><br /><br />
OpenSSL_add_all_algorithms(); // load usable algorithms</p><br /><br />
<p>switch(ctxMethod){ // create new client-method instance<br /><br /><br />
case 1 :<br /><br /><br />
method = TLSv1_client_method();<br /><br /><br />
printf("[+] Use TLSv1 method.\n");<br /><br /><br />
break;<br /><br /><br />
// SSLv2 isn’t sure and is deprecated, so the latest OpenSSL version delete his implementation.<br /><br /><br />
/*case 2 :<br /><br /><br />
method = SSLv2_client_method();<br /><br /><br />
printf("[+] Use SSLv2 method.\n");<br /><br /><br />
break;*/<br /><br /><br />
case 3 :<br /><br /><br />
method = SSLv3_client_method();<br /><br /><br />
printf("[+] Use SSLv3 method.\n");<br /><br /><br />
break;<br /><br /><br />
case 4 :<br /><br /><br />
method = SSLv23_client_method();<br /><br /><br />
printf("[+] Use SSLv2&3 method.\n");<br /><br /><br />
break;<br /><br /><br />
default :<br /><br /><br />
method = SSLv23_client_method();<br /><br /><br />
printf("[+] Use SSLv2&3 method.\n");<br /><br /><br />
}</p><br /><br />
<p>ctx = SSL_CTX_new(method); // create new context from selected method<br /><br /><br />
if(ctx == NULL){<br /><br /><br />
ERR_print_errors_fp(stderr);<br /><br /><br />
abort();<br /><br /><br />
}<br /><br /><br />
return ctx;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* showCerts function who catch and print out certificat’s data from the server<br /><br /><br />
* @param SSL* ssl : the SSL/TLS connection<br /><br /><br />
*/<br /><br /><br />
void showCerts(SSL* ssl){<br /><br /><br />
X509 *cert;<br /><br /><br />
char *subject, *issuer;</p><br /><br />
<p>cert = SSL_get_peer_certificate(ssl); // get the server’s certificate<br /><br /><br />
if(cert != NULL){<br /><br /><br />
subject = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); // get certificat’s subject<br /><br /><br />
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); // get certificat’s issuer</p><br /><br />
<p>printf("[+] Server certificates :\n");<br /><br /><br />
printf("\tSubject: %s\n", subject);<br /><br /><br />
printf("\tIssuer: %s\n", issuer);</p><br /><br />
<p>free(subject); // free the malloc’ed string<br /><br /><br />
free(issuer); // free the malloc’ed string<br /><br /><br />
X509_free(cert); // free the malloc’ed certificate copy<br /><br /><br />
if(SSL_get_verify_result(ssl) == X509_V_OK) // check certificat’s trust<br /><br /><br />
printf("[+] Server certificates X509 is trust!\n");<br /><br /><br />
else<br /><br /><br />
printf("[-] Server certificates X509 is not trust…\n");<br /><br /><br />
}<br /><br /><br />
else<br /><br /><br />
printf("[-] No server’s certificates\n");<br /><br /><br />
return;<br /><br /><br />
}</p><br /><br />
<p>/**<br /><br /><br />
* main function who coordinate the socket and SSL connection creation, then receive and emit data to and from the server.<br /><br /><br />
*/<br /><br /><br />
int main(int argc, char **argv){<br /><br /><br />
int sock, bytes, ctxMethod, port;<br /><br /><br />
SSL_CTX *ctx;<br /><br /><br />
SSL *ssl;<br /><br /><br />
char buf[1024];<br /><br /><br />
char *hostname;</p><br /><br />
<p>if(argc != 3 && argc != 4){<br /><br /><br />
printHeader(argv[0]);<br /><br /><br />
exit(0);<br /><br /><br />
}</p><br /><br />
<p>hostname = argv[1];<br /><br /><br />
port = (atoi(argv[2]) > 0 && atoi(argv[2]) < 65535) ? atoi(argv[2]) : DEFAULT_PORT;<br /><br /><br />
ctxMethod = (argc == 4) ? atoi(argv[3]) : 4; // SSLv2, SSLv3, SSLv2&3 or TLSv1<br /><br /><br />
ctx = initSSLContext(ctxMethod); // load SSL library and dependances<br /><br /><br />
sock = makeClientSocket(hostname, port); // make a classic socket to the hostname throught the port<br /><br /><br />
ssl = SSL_new(ctx); // create new SSL connection state</p><br /><br />
<p>SSL_set_fd(ssl, sock); // attach the socket descriptor</p><br /><br />
<p>if(SSL_connect(ssl) == -1) // make the SSL connection<br /><br /><br />
ERR_print_errors_fp(stderr);<br /><br /><br />
else{<br /><br /><br />
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); // if the server suddenly wants a new handshake,<br /><br /><br />
// OpenSSL handles it in the background. Without this<br /><br /><br />
// option, any read or write operation will return an<br /><br /><br />
// error if the server wants a new handshake.</p><br /><br />
<p>char msg[] = "ClientName";<br /><br /><br />
printf("[+] Cipher used : %s\n", SSL_get_cipher(ssl));<br /><br /><br />
showCerts(ssl); // get any certificats<br /><br /><br />
SSL_write(ssl, msg, strlen(msg)); // encrypt and send message<br /><br /><br />
bytes = SSL_read(ssl, buf, sizeof(buf)); // get response and decrypt content<br /><br /><br />
buf[bytes] = 0;<br /><br /><br />
printf("[+] Server data received : %s\n", buf);<br /><br /><br />
SSL_shutdown(ssl);<br /><br /><br />
SSL_free(ssl); // release SSL connection state</p><br /><br />
<p>}<br /><br /><br />
CLOSESOCKET(sock); // close socket<br /><br /><br />
#ifdef _WIN32<br /><br /><br />
WSACleanup(); // Windows’s Winsock clean<br /><br /><br />
#endif<br /><br /><br />
SSL_CTX_free(ctx); // release SSL’s context<br /><br /><br />
return 0;<br /><br /><br />
}</p><br /><br />
<p>[/c]

L’objectif de ce client/serveur est de disposer d’un code source d’exemple fonctionnel, cross-plateformes, épuré, documenté et clair quand à la mise en place d’une connexion SSL/TLS en C pour un quelconque développement futur.

La création du certificat et de la clé privée du serveur peut se faire avec la ligne de commande suivante (résultat dans un unique fichier) :

[bash]openssl req -x509 -nodes -newkey rsa:2048 -keyout server.pem -out server.pem[/bash]

Compilation sous environnements Linux:

[bash]g++ main.cpp -Wall -lssl -lcrypto -o main[/bash]

Sous Windows, OpenSSL doit être installé avec les fichiers d’en-têtes disponibles dans les includes de l’IDE. Le linkerde l’IDE utilisé doit utiliser les bibliothèques statiques d’OpenSSL (libcrypto.a et libssl.a) ou bien les DLL d’OpenSSL (libeay32.dll et libssl32.dll) doivent être présentes au côté du binaire.
Utilisation du serveur:

[bash]<br /><br /><br />
# Usage :<br /><br /><br />
# run the server on port 1337 for SSLv2&3 protocol with internal randomly generated key and certificate<br /><br /><br />
$ [./]server[.exe] 1337<br /><br /><br />
# run the server on port 1337 for TLSv1 protocol with key and certificate in server.pem file<br /><br /><br />
$ [./]server[.exe] 1337 1 server.pem server.pem<br /><br /><br />
[/bash]

Utilisation du client:

[bash]<br /><br /><br />
# Usage :<br /><br /><br />
# run the client to 127.0.0.1 on port 1337 for SSLv2&3 protocol<br /><br /><br />
$ [./]client[.exe] 127.0.0.1 1337<br /><br /><br />
# run the client to 127.0.0.1 on port 1337 for TLSv1 protocol<br /><br /><br />
$ [./]client[.exe] 127.0.0.1 1337 1<br /><br /><br />
[/bash]

L’ensemble des sources et binaires (Gcc et Code::Blocks) sont disponibles dans l’archive suivante [Client/Server OpenSSL]. La version utilisée d’OpenSSL au temps de développement était la 1.0.0e.

  • Google Plus
  • LinkedIn
  • Viadeo
Author Avatar

About the Author : Yann C.

Consultant en sécurité informatique et s’exerçant dans ce domaine depuis le début des années 2000 en autodidacte par passion, plaisir et perspectives, il maintient le portail ASafety pour présenter des articles, des projets personnels, des recherches et développements, ainsi que des « advisory » de vulnérabilités décelées notamment au cours de pentest.