1368fa6f873ecb30d4adc0fe95884670502b2a1a
[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 certificate 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
501         char *crt, *key, *pass;
502         
503         crt = (char *)getStrConf(CERTIFICATE);
504         key = (char *)getStrConf(KEY);
505         pass = (char *)getStrConf(PASSPHRASE);
506
507         x509 = SSL_readcert(crt);
508         rsa = SSL_readprivatekey(key);
509         if (rsa != NULL) {
510                 pkey = EVP_PKEY_new();
511                 EVP_PKEY_assign_RSA(pkey, rsa);
512         }               
513
514         
515 #if 0
516         /* Later ... */
517         if (key && !x509) {             
518                 qscCert = QSslCertificate(key);
519                 if (! qscCert.isNull()) {
520                         logthis("Using certificate from key.");
521                 }
522         }
523
524         if (! qscCert.isNull()) {
525                 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
526                 /* Fetch algorith from cert */
527                 if (! key.isEmpty()) {
528                         /* get key */
529                         qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
530                         if (qskKey.isNull()) {
531                                 logthis("Failed to parse key.");
532                         }
533                 }
534
535                 if (! crt.isEmpty() && qskKey.isNull()) {
536                         /* get key from certificate */
537                         qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
538                         if (! qskKey.isNull()) {
539                                 logthis("Using key from certificate.");
540                         }
541                 }
542
543         }
544 #endif
545         
546         if (!rsa || !x509) {
547                 Log_info("Generating new server certificate.");
548
549                 
550                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
551                                 
552                 x509 = X509_new();
553                 pkey = EVP_PKEY_new();
554                 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
555                 EVP_PKEY_assign_RSA(pkey, rsa);
556                 
557                 X509_set_version(x509, 2);
558                 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
559                 X509_gmtime_adj(X509_get_notBefore(x509),0);
560                 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
561                 X509_set_pubkey(x509, pkey);
562                 
563                 X509_NAME *name=X509_get_subject_name(x509);
564                 
565                 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
566                 X509_set_issuer_name(x509, name);
567                 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
568                 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
569                 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
570                 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
571                 
572                 X509_sign(x509, pkey, EVP_md5());
573                 
574                 SSL_writecert(crt, x509);
575                 SSL_writekey(key, rsa);
576         }
577
578 }
579
580 void SSLi_init(void)
581 {
582         const SSL_METHOD *method;
583         SSL *ssl;
584         int i, offset = 0, cipherstringlen = 0;
585         STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
586         SSL_CIPHER *cipher;
587         char *cipherstring, tempstring[128];
588                 
589         SSL_library_init();
590         OpenSSL_add_all_algorithms();           /* load & register all cryptos, etc. */
591         SSL_load_error_strings();                       /* load all error messages */
592         ERR_load_crypto_strings();                      /* load all error messages */
593         method = SSLv23_server_method();                /* create new server-method instance */
594         context = SSL_CTX_new(method);                  /* create new context from method */
595         if (context == NULL)
596         {
597                 ERR_print_errors_fp(stderr);
598                 abort();
599         }
600         
601         char* sslCAPath = getStrConf(CAPATH);
602         if(sslCAPath != NULL)
603         {
604                 SSL_CTX_load_verify_locations(context, NULL, sslCAPath);
605         }
606         
607         SSL_initializeCert();
608         if (SSL_CTX_use_certificate(context, x509) <= 0)
609                 Log_fatal("Failed to initialize cert");
610         if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
611                 ERR_print_errors_fp(stderr);
612                 Log_fatal("Failed to initialize private key");
613         }
614         
615         /* Set cipher list */
616         ssl = SSL_new(context); 
617         cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
618         cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
619         
620         for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
621                 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
622                         sk_SSL_CIPHER_push(cipherlist_new, cipher);
623                 }
624         }
625         Log_debug("List of ciphers:");
626         if (cipherlist_new) {
627                 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
628                         Log_debug("%s", SSL_CIPHER_get_name(cipher));
629                         cipherstringlen += strlen(SSL_CIPHER_get_name(cipher)) + 1;
630                 }
631                 cipherstring = malloc(cipherstringlen + 1);
632                 if (cipherstring == NULL)
633                         Log_fatal("Out of memory");
634                 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
635                         offset += sprintf(cipherstring + offset, "%s:", SSL_CIPHER_get_name(cipher));
636                 }
637         }
638         
639         if (cipherlist_new)
640                 sk_SSL_CIPHER_free(cipherlist_new);
641         
642         if (strlen(cipherstring) == 0)
643                 Log_fatal("No suitable ciphers found!");
644         
645         if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
646                 Log_fatal("Failed to set cipher list!");
647
648         free(cipherstring);
649         
650         SSL_CTX_set_verify(context, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
651                            verify_callback);            
652         
653         SSL_free(ssl);
654         Log_info("OpenSSL library initialized");
655
656 }
657
658 void SSLi_deinit(void)
659 {
660         SSL_CTX_free(context);
661         EVP_cleanup();
662 }
663
664 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
665 {
666         int rc;
667         rc = SSL_accept(ssl);
668         if (rc < 0) {
669                 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
670                         SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
671                         Log_debug("SSL not ready");
672                         return 0;
673                 } else {
674                         Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
675                         return -1;
676                 }
677         }
678         *SSLready = true;
679         return 0;
680 }
681
682 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
683 {
684         SSL *ssl;
685         
686         *SSLready = false;
687         ssl = SSL_new(context);
688         SSL_set_fd(ssl, *fd);
689         if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
690                 SSL_free(ssl);
691                 return NULL;
692         }
693         return ssl;
694 }
695
696 /* Create SHA1 of last certificate in the peer's chain. */
697 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
698 {
699         X509 *x509;
700         uint8_t *buf, *p;
701         int len;
702         
703         x509 = SSL_get_peer_certificate(ssl);
704         if (!x509) {
705                 return false;
706         }       
707         
708         len = i2d_X509(x509, NULL);
709         buf = malloc(len);
710         if (buf == NULL) {
711                 Log_fatal("malloc");
712         }
713
714         p = buf;
715         i2d_X509(x509, &p);     
716         
717         SHA1(buf, len, hash);
718         free(buf);
719         return true;
720 }
721  
722 void SSLi_closeconnection(SSL_handle_t *ssl)
723 {
724         SSL_free(ssl);
725 }
726
727 void SSLi_shutdown(SSL_handle_t *ssl)
728 {
729         SSL_shutdown(ssl);
730 }
731
732 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
733 {
734         return SSL_read(ssl, buf, len);
735 }
736
737 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
738 {
739         return SSL_write(ssl, buf, len);
740 }
741
742 int SSLi_get_error(SSL_handle_t *ssl, int code)
743 {
744         return SSL_get_error(ssl, code);
745 }
746
747 bool_t SSLi_data_pending(SSL_handle_t *ssl)
748 {
749         return SSL_pending(ssl);
750 }
751
752 void SSLi_free(SSL_handle_t *ssl)
753 {
754         SSL_free(ssl);
755 }
756
757 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
758 {
759         char    buf[256];
760         X509   *err_cert;
761         int     err, depth;
762         SSL    *ssl;
763     
764     err_cert = X509_STORE_CTX_get_current_cert(ctx);
765     err = X509_STORE_CTX_get_error(ctx);
766     depth = X509_STORE_CTX_get_error_depth(ctx);
767     
768     ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
769     X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
770         
771     if (depth > 5) {
772         preverify_ok = 0;
773         err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
774         X509_STORE_CTX_set_error(ctx, err);
775     }
776     if (!preverify_ok) {
777             Log_warn("SSL: verify error:num=%d:%s:depth=%d:%s\n", err,
778                      X509_verify_cert_error_string(err), depth, buf);
779     }
780     /*
781      * At this point, err contains the last verification error. We can use
782      * it for something special
783      */
784     if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
785             X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
786             Log_warn("issuer= %s", buf);
787     }
788     return 1;
789 }
790  
791 #endif