Add support for PolarSSL 1.3.x
[umurmur.git] / src / ssl.c
1 /* Copyright (C) 2009-2013, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2013, Thorvald Natvig <thorvald@natvig.com>
3
4    All rights reserved.
5
6    Redistribution and use in source and binary forms, with or without
7    modification, are permitted provided that the following conditions
8    are met:
9
10    - Redistributions of source code must retain the above copyright notice,
11      this list of conditions and the following disclaimer.
12    - Redistributions in binary form must reproduce the above copyright notice,
13      this list of conditions and the following disclaimer in the documentation
14      and/or other materials provided with the distribution.
15    - Neither the name of the Developers nor the names of its contributors may
16      be used to endorse or promote products derived from this software without
17      specific prior written permission.
18
19    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22    A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 #include <string.h>
32 #include <stdlib.h>
33 #include <fcntl.h>
34
35 #include "conf.h"
36 #include "log.h"
37 #include "ssl.h"
38
39 #ifdef USE_POLARSSL
40 /*
41  * PolarSSL interface
42  */
43
44 #include <polarssl/config.h>
45 #include <polarssl/havege.h>
46 #include <polarssl/certs.h>
47 #include <polarssl/x509.h>
48 #include <polarssl/ssl.h>
49 #include <polarssl/net.h>
50
51 #ifdef POLARSSL_API_V1_2_ABOVE
52 int ciphers[] =
53 {
54     TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
55     TLS_RSA_WITH_AES_256_CBC_SHA,
56     TLS_RSA_WITH_AES_128_CBC_SHA,
57     0
58 };
59 #else
60 int ciphers[] =
61 {
62     SSL_EDH_RSA_AES_256_SHA,
63     SSL_RSA_AES_256_SHA,
64     SSL_RSA_AES_128_SHA,
65     0
66 };
67 #endif
68
69 #ifdef POLARSSL_API_V1_3_ABOVE
70 static x509_crt certificate;
71 static inline int x509parse_keyfile(rsa_context *rsa, const char *path,
72                                     const char *pwd)
73 {
74     int ret;
75     pk_context pk;
76     
77     pk_init(&pk);
78     ret = pk_parse_keyfile(&pk, path, pwd);
79     if (ret == 0 && !pk_can_do( &pk, POLARSSL_PK_RSA))
80         ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
81     if (ret == 0)
82         rsa_copy(rsa, pk_rsa(pk));
83     else
84         rsa_free(rsa);
85     pk_free(&pk);
86     return ret;
87 }
88 #else
89 static x509_cert certificate;
90 #endif
91
92 static rsa_context key;
93 bool_t builtInTestCertificate;
94
95 #ifdef USE_POLARSSL_HAVEGE
96 havege_state hs;
97 #else
98 int urandom_fd;
99 #endif
100
101 /* DH prime */
102 char *my_dhm_P =
103         "9CE85640903BF123906947FEDE767261" \
104         "D9B4A973EB8F7D984A8C656E2BCC161C" \
105         "183D4CA471BA78225F940F16D1D99CA3" \
106         "E66152CC68EDCE1311A390F307741835" \
107         "44FF6AB553EC7073AD0CB608F2A3B480" \
108         "19E6C02BCED40BD30E91BB2469089670" \
109         "DEF409C08E8AC24D1732A6128D2220DC53";
110 char *my_dhm_G = "4";
111
112 #ifdef USE_POLARSSL_TESTCERT
113 static void initTestCert()
114 {
115         int rc;
116         builtInTestCertificate = true;
117 #ifdef POLARSSL_API_V1_3_ABOVE
118         rc = x509_crt_parse_rsa(&certificate, (unsigned char *)test_srv_crt,
119                 strlen(test_srv_crt));
120 #else
121         rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
122                 strlen(test_srv_crt));
123 #endif
124         if (rc != 0)
125                 Log_fatal("Could not parse built-in test certificate");
126 }
127
128 static void initTestKey()
129 {
130         int rc;
131         
132         rc = x509parse_key_rsa(&key, (unsigned char *)test_srv_key,
133                                strlen(test_srv_key), NULL, 0);
134         if (rc != 0)
135                 Log_fatal("Could not parse built-in test RSA key");
136 }
137 #endif
138
139 /*
140  * How to generate a self-signed cert with openssl:
141  * openssl genrsa 1024 > host.key
142  * openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert
143  */
144 static void initCert()
145 {
146         int rc;
147         char *crtfile = (char *)getStrConf(CERTIFICATE);
148         
149         if (crtfile == NULL) {
150 #ifdef USE_POLARSSL_TESTCERT
151                 Log_warn("No certificate file specified. Falling back to test certificate.");
152                 initTestCert();
153 #else
154                 Log_fatal("No certificate file specified");
155 #endif
156                 return;
157         }
158 #ifdef POLARSSL_API_V1_3_ABOVE
159         rc = x509_crt_parse_file(&certificate, crtfile);
160 #else
161         rc = x509parse_crtfile(&certificate, crtfile);
162 #endif
163         if (rc != 0) {
164 #ifdef USE_POLARSSL_TESTCERT
165                 Log_warn("Could not read certificate file '%s'. Falling back to test certificate.", crtfile);
166                 initTestCert();
167 #else
168                 Log_fatal("Could not read certificate file '%s'", crtfile);
169 #endif
170                 return;
171         }
172 }
173
174 static void initKey()
175 {
176         int rc;
177         char *keyfile = (char *)getStrConf(KEY);
178
179         if (keyfile == NULL)
180                 Log_fatal("No key file specified"); 
181         rc = x509parse_keyfile(&key, keyfile, NULL);
182         if (rc != 0)
183                 Log_fatal("Could not read RSA key file %s", keyfile);
184 }
185
186 #ifndef USE_POLARSSL_HAVEGE
187 int urandom_bytes(void *ctx, unsigned char *dest, size_t len)
188 {
189         int cur;
190         
191         while (len) {
192                 cur = read(urandom_fd, dest, len);
193                 if (cur < 0)
194                         continue;
195                 len -= cur;
196         }
197         return 0;
198 }
199 #endif
200
201 #define DEBUG_LEVEL 0
202 static void pssl_debug(void *ctx, int level, const char *str)
203 {
204     if (level <= DEBUG_LEVEL)
205                 Log_info("PolarSSL [level %d]: %s", level, str);
206 }
207
208 void SSLi_init(void)
209 {
210         char verstring[12];
211         
212         initCert();
213 #ifdef USE_POLARSSL_TESTCERT
214         if (builtInTestCertificate) {
215                 Log_warn("*** Using built-in test certificate and RSA key ***");
216                 Log_warn("*** This is not secure! Please use a CA-signed certificate or create a key and self-signed certificate ***");
217                 initTestKey();
218         }
219         else
220                 initKey();
221 #else
222         initKey();
223 #endif
224
225         /* Initialize random number generator */
226 #ifdef USE_POLARSSL_HAVEGE
227     havege_init(&hs);
228 #else
229     urandom_fd = open("/dev/urandom", O_RDONLY);
230     if (urandom_fd < 0)
231             Log_fatal("Cannot open /dev/urandom");
232 #endif
233     
234     version_get_string(verstring);
235     Log_info("PolarSSL library version %s initialized", verstring);
236 }
237
238 void SSLi_deinit(void)
239 {
240 #ifdef POLARSSL_API_V1_3_ABOVE
241         x509_crt_free(&certificate);
242 #else   
243         x509_free(&certificate);
244 #endif
245         rsa_free(&key);
246 }
247
248 /* Create SHA1 of last certificate in the peer's chain. */
249 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
250 {
251 #ifdef POLARSSL_API_V1_3_ABOVE
252         x509_crt const *cert;
253 #else
254         x509_cert const *cert;
255 #endif
256 #ifdef POLARSSL_API_V1_2_ABOVE
257         cert = ssl_get_peer_cert(ssl);
258 #else
259         cert = ssl->peer_cert;
260 #endif
261         if (!cert) {
262                 return false;
263         }       
264         sha1(cert->raw.p, cert->raw.len, hash);
265         return true;
266 }
267         
268 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
269 {
270         ssl_context *ssl;
271         ssl_session *ssn;
272         int rc;
273         
274         ssl = malloc(sizeof(ssl_context));
275         ssn = malloc(sizeof(ssl_session));
276         if (!ssl || !ssn)
277                 Log_fatal("Out of memory");
278         memset(ssl, 0, sizeof(ssl_context));
279         memset(ssn, 0, sizeof(ssl_session));
280         
281         rc = ssl_init(ssl);
282         if (rc != 0 )
283                 Log_fatal("Failed to initialize: %d", rc);
284         
285         ssl_set_endpoint(ssl, SSL_IS_SERVER);   
286         ssl_set_authmode(ssl, SSL_VERIFY_OPTIONAL);
287         
288 #ifdef USE_POLARSSL_HAVEGE
289         ssl_set_rng(ssl, HAVEGE_RAND, &hs);
290 #else
291         ssl_set_rng(ssl, urandom_bytes, NULL);
292 #endif
293         
294         ssl_set_dbg(ssl, pssl_debug, NULL);
295         ssl_set_bio(ssl, net_recv, fd, net_send, fd);
296
297         ssl_set_ciphersuites(ssl, ciphers);
298
299 #ifdef POLARSSL_API_V1_2_ABOVE
300     ssl_set_session(ssl, ssn);
301 #else
302     ssl_set_session(ssl, 0, 0, ssn);
303 #endif
304     
305     ssl_set_ca_chain(ssl, &certificate, NULL, NULL);
306 #ifdef POLARSSL_API_V1_3_ABOVE
307         ssl_set_own_cert_rsa(ssl, &certificate, &key);
308 #else
309         ssl_set_own_cert(ssl, &certificate, &key);
310 #endif
311         ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
312
313         return ssl;
314 }
315
316 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
317 {
318         int rc;
319         
320         rc = ssl_handshake(ssl);
321         if (rc != 0) {
322                 if (rc == POLARSSL_ERR_NET_WANT_READ || rc == POLARSSL_ERR_NET_WANT_WRITE) {
323                         return 0;
324                 } else if (rc == POLARSSL_ERR_X509_CERT_VERIFY_FAILED) { /* Allow this (selfsigned etc) */
325                         return 0;                       
326                 } else {
327                         Log_warn("SSL handshake failed: %d", rc);
328                         return -1;
329                 }
330         }
331         *SSLready = true;
332         return 0;
333 }
334
335 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
336 {
337         int rc;
338
339         rc = ssl_read(ssl, buf, len);
340         if (rc == POLARSSL_ERR_NET_WANT_READ)
341                 return SSLI_ERROR_WANT_READ;
342         return rc;
343 }
344
345 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
346 {
347         int rc;
348         
349         rc = ssl_write(ssl, buf, len);
350         if (rc == POLARSSL_ERR_NET_WANT_WRITE)
351                 return SSLI_ERROR_WANT_WRITE;
352         return rc;
353 }
354
355 int SSLi_get_error(SSL_handle_t *ssl, int code)
356 {
357         return code;
358 }
359
360 bool_t SSLi_data_pending(SSL_handle_t *ssl)
361 {
362         return ssl_get_bytes_avail(ssl) > 0;
363 }
364
365 void SSLi_shutdown(SSL_handle_t *ssl)
366 {
367         ssl_close_notify(ssl);
368 }
369
370 void SSLi_free(SSL_handle_t *ssl)
371 {
372         Log_debug("SSLi_free");
373 #if (POLARSSL_VERSION_MINOR <= 2 && POLARSSL_VERSION_PATCH < 6)
374         free(ssl->session); /* Workaround for memory leak in PolarSSL < 1.2.6 */
375         ssl->session = NULL;
376 #endif
377         ssl_free(ssl);
378         free(ssl);
379 }
380
381 #else
382 /*
383  * OpenSSL interface
384  */
385
386 #include <openssl/x509v3.h>
387 #include <openssl/ssl.h>
388 #include <openssl/err.h>
389 #include <openssl/safestack.h>
390 static X509 *x509;
391 static RSA *rsa;
392 static SSL_CTX *context;
393 static EVP_PKEY *pkey;
394  
395 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx);
396
397 static int SSL_add_ext(X509 * crt, int nid, char *value) {
398         X509_EXTENSION *ex;
399         X509V3_CTX ctx;
400         X509V3_set_ctx_nodb(&ctx);
401         X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
402         ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
403         if (!ex)
404                 return 0;
405
406         X509_add_ext(crt, ex, -1);
407         X509_EXTENSION_free(ex);
408         return 1;
409 }
410
411 static X509 *SSL_readcert(char *certfile)
412 {
413         FILE *fp;
414         X509 *x509;
415                         
416         /* open the private key file */
417         fp = fopen(certfile, "r");
418         if (fp == NULL) {
419                 Log_warn("Unable to open the X509 file %s for reading.", certfile);
420                 return NULL;
421         }
422         
423         /* allocate memory for the cert structure */    
424         x509 = X509_new();
425         
426         if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
427                 /* error reading the x509 information - check the error stack */
428                 Log_warn("Error trying to read X509 info.");
429                 fclose(fp);
430                 X509_free(x509);
431                 return NULL;
432         }
433         fclose(fp);
434         return x509;
435 }
436
437 static RSA *SSL_readprivatekey(char *keyfile)
438 {
439         FILE *fp;
440         RSA *rsa;
441
442 /* open the private key file for reading */
443         fp = fopen(keyfile, "r");
444         if (fp == NULL) {
445                 Log_warn("Unable to open the private key file %s for reading.", keyfile);
446                 return NULL;
447         }
448         
449 /* allocate memory for the RSA structure */
450         rsa = RSA_new();
451         
452         /* assign a callback function for the password */
453         
454         /* read a private key from file */      
455         if (PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL) <= 0) {
456                 /* error reading the key - check the error stack */
457                 Log_warn("Error trying to read private key.");
458                 RSA_free(rsa);
459                 fclose(fp);
460                 return NULL;
461         }
462         fclose(fp);
463         return rsa;
464 }
465
466 static void SSL_writecert(char *certfile, X509 *x509)
467 {
468         FILE *fp;
469                 
470         /* open the private key file */
471         fp = fopen(certfile, "w");
472         if (fp == NULL) {
473                 Log_warn("Unable to open the X509 file %s for writing", certfile);
474                 return;
475         }               
476         if (PEM_write_X509(fp, x509) == 0) {
477                 Log_warn("Error trying to write X509 info.");
478         }
479         fclose(fp);
480 }
481
482 static void SSL_writekey(char *keyfile, RSA *rsa)
483 {
484         FILE *fp;
485         
486         /* open the private key file for reading */
487         fp = fopen(keyfile, "w");
488         if (fp == NULL) {
489                 Log_warn("Unable to open the private key file %s for writing.", keyfile);
490                 return;
491         }
492         
493         if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
494                 Log_warn("Error trying to write private key");
495         }
496         fclose(fp);
497 }
498
499 static void SSL_initializeCert() {
500         char *crt, *key, *pass;
501         
502         crt = (char *)getStrConf(CERTIFICATE);
503         key = (char *)getStrConf(KEY);
504         pass = (char *)getStrConf(PASSPHRASE);
505
506         x509 = SSL_readcert(crt);
507         rsa = SSL_readprivatekey(key);
508         if (rsa != NULL) {
509                 pkey = EVP_PKEY_new();
510                 EVP_PKEY_assign_RSA(pkey, rsa);
511         }               
512         
513 #if 0
514         /* Later ... */
515         if (key && !x509) {             
516                 qscCert = QSslCertificate(key);
517                 if (! qscCert.isNull()) {
518                         logthis("Using certificate from key.");
519                 }
520         }
521
522         if (! qscCert.isNull()) {
523                 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
524                 /* Fetch algorith from cert */
525                 if (! key.isEmpty()) {
526                         /* get key */
527                         qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
528                         if (qskKey.isNull()) {
529                                 logthis("Failed to parse key.");
530                         }
531                 }
532
533                 if (! crt.isEmpty() && qskKey.isNull()) {
534                         /* get key from certificate */
535                         qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
536                         if (! qskKey.isNull()) {
537                                 logthis("Using key from certificate.");
538                         }
539                 }
540
541         }
542 #endif
543         
544         if (!rsa || !x509) {
545                 Log_info("Generating new server certificate.");
546
547                 
548                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
549                                 
550                 x509 = X509_new();
551                 pkey = EVP_PKEY_new();
552                 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
553                 EVP_PKEY_assign_RSA(pkey, rsa);
554                 
555                 X509_set_version(x509, 2);
556                 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
557                 X509_gmtime_adj(X509_get_notBefore(x509),0);
558                 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
559                 X509_set_pubkey(x509, pkey);
560                 
561                 X509_NAME *name=X509_get_subject_name(x509);
562                 
563                 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
564                 X509_set_issuer_name(x509, name);
565                 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
566                 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
567                 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
568                 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
569                 
570                 X509_sign(x509, pkey, EVP_md5());
571                 
572                 SSL_writecert(crt, x509);
573                 SSL_writekey(key, rsa);
574         }
575
576 }
577
578 void SSLi_init(void)
579 {
580         const SSL_METHOD *method;
581         SSL *ssl;
582         int i, offset = 0, cipherstringlen = 0;
583         STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
584         SSL_CIPHER *cipher;
585         char *cipherstring, tempstring[128];
586                 
587         SSL_library_init();
588     OpenSSL_add_all_algorithms();               /* load & register all cryptos, etc. */
589     SSL_load_error_strings();                   /* load all error messages */
590     ERR_load_crypto_strings();                  /* load all error messages */
591     method = SSLv23_server_method();            /* create new server-method instance */
592     context = SSL_CTX_new(method);                      /* create new context from method */
593     if (context == NULL)
594     {
595         ERR_print_errors_fp(stderr);
596         abort();
597     }
598         SSL_initializeCert();
599         if (SSL_CTX_use_certificate(context, x509) <= 0)
600                 Log_fatal("Failed to initialize cert");
601         if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
602                 ERR_print_errors_fp(stderr);
603                 Log_fatal("Failed to initialize private key");
604         }
605
606         /* Set cipher list */
607         ssl = SSL_new(context); 
608         cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
609         cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
610         
611         for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
612                 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
613                         sk_SSL_CIPHER_push(cipherlist_new, cipher);
614                 }
615         }
616         Log_debug("List of ciphers:");
617         if (cipherlist_new) {
618                 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
619                         Log_debug("%s", SSL_CIPHER_get_name(cipher));
620                         cipherstringlen += strlen(SSL_CIPHER_get_name(cipher)) + 1;
621                 }
622                 cipherstring = malloc(cipherstringlen + 1);
623                 if (cipherstring == NULL)
624                         Log_fatal("Out of memory");
625                 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
626                         offset += sprintf(cipherstring + offset, "%s:", SSL_CIPHER_get_name(cipher));
627                 }
628         }
629         
630         if (cipherlist_new)
631                 sk_SSL_CIPHER_free(cipherlist_new);
632         
633         if (strlen(cipherstring) == 0)
634                 Log_fatal("No suitable ciphers found!");
635         
636         if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
637                 Log_fatal("Failed to set cipher list!");
638
639         free(cipherstring);
640         
641         SSL_CTX_set_verify(context, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
642                            verify_callback);            
643         
644         SSL_free(ssl);
645         Log_info("OpenSSL library initialized");
646
647 }
648
649 void SSLi_deinit(void)
650 {
651         SSL_CTX_free(context);
652         EVP_cleanup();
653 }
654
655 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
656 {
657         int rc;
658         rc = SSL_accept(ssl);
659         if (rc < 0) {
660                 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
661                         SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
662                         Log_debug("SSL not ready");
663                         return 0;
664                 } else {
665                         Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
666                         return -1;
667                 }
668         }
669         *SSLready = true;
670         return 0;
671 }
672
673 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
674 {
675         SSL *ssl;
676         
677         *SSLready = false;
678         ssl = SSL_new(context);
679         SSL_set_fd(ssl, *fd);
680         if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
681                 SSL_free(ssl);
682                 return NULL;
683         }
684         return ssl;
685 }
686
687 /* Create SHA1 of last certificate in the peer's chain. */
688 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
689 {
690         X509 *x509;
691         uint8_t *buf, *p;
692         int len;
693         
694         x509 = SSL_get_peer_certificate(ssl);
695         if (!x509) {
696                 return false;
697         }       
698         
699         len = i2d_X509(x509, NULL);
700         buf = malloc(len);
701         if (buf == NULL) {
702                 Log_fatal("malloc");
703         }
704
705         p = buf;
706         i2d_X509(x509, &p);     
707         
708         SHA1(buf, len, hash);
709         free(buf);
710         return true;
711 }
712  
713 void SSLi_closeconnection(SSL_handle_t *ssl)
714 {
715         SSL_free(ssl);
716 }
717
718 void SSLi_shutdown(SSL_handle_t *ssl)
719 {
720         SSL_shutdown(ssl);
721 }
722
723 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
724 {
725         return SSL_read(ssl, buf, len);
726 }
727
728 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
729 {
730         return SSL_write(ssl, buf, len);
731 }
732
733 int SSLi_get_error(SSL_handle_t *ssl, int code)
734 {
735         return SSL_get_error(ssl, code);
736 }
737
738 bool_t SSLi_data_pending(SSL_handle_t *ssl)
739 {
740         return SSL_pending(ssl);
741 }
742
743 void SSLi_free(SSL_handle_t *ssl)
744 {
745         SSL_free(ssl);
746 }
747
748 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
749 {
750         char    buf[256];
751         X509   *err_cert;
752         int     err, depth;
753         SSL    *ssl;
754     
755     err_cert = X509_STORE_CTX_get_current_cert(ctx);
756     err = X509_STORE_CTX_get_error(ctx);
757     depth = X509_STORE_CTX_get_error_depth(ctx);
758     
759     ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
760     X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
761         
762     if (depth > 5) {
763         preverify_ok = 0;
764         err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
765         X509_STORE_CTX_set_error(ctx, err);
766     }
767     if (!preverify_ok) {
768             Log_warn("SSL: verify error:num=%d:%s:depth=%d:%s\n", err,
769                      X509_verify_cert_error_string(err), depth, buf);
770     }
771     /*
772      * At this point, err contains the last verification error. We can use
773      * it for something special
774      */
775     if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
776             X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
777             Log_warn("issuer= %s", buf);
778     }
779     return 1;
780 }
781  
782 #endif