]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn-ssl.c
059e871ddaa38af341e995f577225fad84940091
[ngircd-alex.git] / src / ngircd / conn-ssl.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c) 2005-2008 Florian Westphal <fw@strlen.de>
4  */
5
6 #include "portab.h"
7
8 /**
9  * @file
10  * SSL wrapper functions
11  */
12
13 #include "imp.h"
14 #include "conf-ssl.h"
15
16 #ifdef SSL_SUPPORT
17
18 #include "io.h"
19 #include <assert.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <errno.h>
24
25 #define CONN_MODULE
26 #include "conn.h"
27 #include "conf.h"
28 #include "conn-func.h"
29 #include "conn-ssl.h"
30 #include "log.h"
31
32 #include "exp.h"
33 #include "defines.h"
34
35 extern struct SSLOptions Conf_SSLOptions;
36
37 #ifdef HAVE_LIBSSL
38 #include <openssl/err.h>
39 #include <openssl/rand.h>
40
41 static SSL_CTX * ssl_ctx;
42 static DH *dh_params;
43
44 static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
45 #endif
46
47 #ifdef HAVE_LIBGNUTLS
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <fcntl.h>
51 #include <unistd.h>
52 #include <gnutls/x509.h>
53
54 #define DH_BITS 2048
55 #define DH_BITS_MIN 1024
56
57 #define MAX_HASH_SIZE   64      /* from gnutls-int.h */
58
59 static gnutls_certificate_credentials_t x509_cred;
60 static gnutls_dh_params_t dh_params;
61 static bool ConnSSL_LoadServerKey_gnutls PARAMS(( void ));
62 #endif
63
64 #define SHA1_STRING_LEN (20 * 2 + 1)
65
66 static bool ConnSSL_Init_SSL PARAMS(( CONNECTION *c ));
67 static int ConnectAccept PARAMS(( CONNECTION *c, bool connect ));
68 static int ConnSSL_HandleError PARAMS(( CONNECTION *c, const int code, const char *fname ));
69
70 #ifdef HAVE_LIBGNUTLS
71 static char * openreadclose(const char *name, size_t *len)
72 {
73         char *buf = NULL;
74         struct stat s;
75         ssize_t br;
76         int fd = open(name, O_RDONLY);
77         if (fd < 0) {
78                 Log(LOG_ERR, "Could not open %s: %s", name, strerror(errno));
79                 return NULL;
80         }
81         if (fstat(fd, &s)) {
82                 Log(LOG_ERR, "Could not fstat %s: %s", name, strerror(errno));
83                 goto out;
84         }
85         if (!S_ISREG(s.st_mode)) {
86                 Log(LOG_ERR, "%s: Not a regular file", name);
87                 goto out;
88         }
89         if (s.st_size <= 0) {
90                 Log(LOG_ERR, "%s: invalid file length (size %ld <= 0)", name, (long) s.st_size);
91                 goto out;
92         }
93         buf = malloc(s.st_size);
94         if (!buf) {
95                 Log(LOG_ERR, "Could not malloc %lu bytes for file %s: %s", s.st_size, name, strerror(errno));
96                 goto out;
97         }
98         br = read(fd, buf, s.st_size);
99         if (br != (ssize_t)s.st_size) {
100                 Log(LOG_ERR, "Could not read file %s: read returned %ld, expected %ld: %s",
101                         name, (long) br, (long) s.st_size, br == -1 ? strerror(errno):"short read?!");
102                 memset(buf, 0, s.st_size);
103                 free(buf);
104                 buf = NULL;
105         } else {
106                 *len = br;
107         }
108 out:
109         close(fd);
110         return buf;
111 }
112 #endif
113
114
115 #ifdef HAVE_LIBSSL
116 /**
117  * Log OpenSSL error message.
118  *
119  * @param msg The error message.
120  * @param info Additional information text or NULL.
121  */
122 static void
123 LogOpenSSLError(const char *error, const char *info)
124 {
125         unsigned long err = ERR_get_error();
126         char * errmsg = err
127                 ? ERR_error_string(err, NULL)
128                 : "Unable to determine error";
129
130         assert(error != NULL);
131
132         if (info)
133                 Log(LOG_ERR, "%s: %s (%s)", error, info, errmsg);
134         else
135                 Log(LOG_ERR, "%s: %s", error, errmsg);
136 }
137
138
139 static int
140 pem_passwd_cb(char *buf, int size, int rwflag, void *password)
141 {
142         array *pass = password;
143         int passlen;
144
145         (void)rwflag;           /* rwflag is unused if DEBUG is not set. */
146         assert(rwflag == 0);    /* 0 -> callback used for decryption.
147                                  * See SSL_CTX_set_default_passwd_cb(3) */
148
149         passlen = (int) array_bytes(pass);
150
151         LogDebug("pem_passwd_cb buf size %d, array size %d", size, passlen);
152         assert(passlen >= 0);
153         if (passlen <= 0) {
154                 Log(LOG_ERR, "PEM password required but not set [in pem_passwd_cb()]!");
155                 return 0;
156         }
157         size = passlen > size ? size : passlen;
158         memcpy(buf, (char *)(array_start(pass)), size);
159         return size;
160 }
161
162
163 static int
164 Verify_openssl(UNUSED int preverify_ok, UNUSED X509_STORE_CTX *x509_ctx)
165 {
166         return 1;
167 }
168 #endif
169
170
171 static bool
172 Load_DH_params(void)
173 {
174 #ifdef HAVE_LIBSSL
175         FILE *fp;
176         bool ret = true;
177
178         if (!Conf_SSLOptions.DHFile) {
179                 Log(LOG_NOTICE, "Configuration option \"DHFile\" not set!");
180                 return false;
181         }
182         fp = fopen(Conf_SSLOptions.DHFile, "r");
183         if (!fp) {
184                 Log(LOG_ERR, "%s: %s", Conf_SSLOptions.DHFile, strerror(errno));
185                 return false;
186         }
187         dh_params = PEM_read_DHparams(fp, NULL, NULL, NULL);
188         if (!dh_params) {
189                 Log(LOG_ERR, "%s: Failed to read SSL DH parameters!",
190                     Conf_SSLOptions.DHFile);
191                 ret = false;
192         }
193         fclose(fp);
194         return ret;
195 #endif
196 #ifdef HAVE_LIBGNUTLS
197         bool need_dhgenerate = true;
198         int err;
199         gnutls_dh_params_t tmp_dh_params;
200
201         err = gnutls_dh_params_init(&tmp_dh_params);
202         if (err < 0) {
203                 Log(LOG_ERR, "Failed to initialize SSL DH parameters: %s",
204                     gnutls_strerror(err));
205                 return false;
206         }
207         if (Conf_SSLOptions.DHFile) {
208                 gnutls_datum_t dhparms;
209                 size_t size;
210                 dhparms.data = (unsigned char *) openreadclose(Conf_SSLOptions.DHFile, &size);
211                 if (dhparms.data) {
212                         dhparms.size = size;
213                         err = gnutls_dh_params_import_pkcs3(tmp_dh_params, &dhparms, GNUTLS_X509_FMT_PEM);
214                         if (err == 0)
215                                 need_dhgenerate = false;
216                         else
217                                 Log(LOG_ERR,
218                                     "Failed to initialize SSL DH parameters: %s",
219                                     gnutls_strerror(err));
220
221                         memset(dhparms.data, 0, size);
222                         free(dhparms.data);
223                 }
224         }
225         if (need_dhgenerate) {
226                 Log(LOG_WARNING,
227                     "DHFile not set, generating %u bit DH parameters. This may take a while ...",
228                     DH_BITS);
229                 err = gnutls_dh_params_generate2(tmp_dh_params, DH_BITS);
230                 if (err < 0) {
231                         Log(LOG_ERR, "Failed to generate SSL DH parameters: %s",
232                             gnutls_strerror(err));
233                         return false;
234                 }
235         }
236         dh_params = tmp_dh_params;
237         return true;
238 #endif
239 }
240
241
242 void ConnSSL_Free(CONNECTION *c)
243 {
244 #ifdef HAVE_LIBSSL
245         SSL *ssl = c->ssl_state.ssl;
246         if (ssl) {
247                 SSL_shutdown(ssl);
248                 SSL_free(ssl);
249                 c->ssl_state.ssl = NULL;
250                 if (c->ssl_state.fingerprint) {
251                         free(c->ssl_state.fingerprint);
252                         c->ssl_state.fingerprint = NULL;
253                 }
254         }
255 #endif
256 #ifdef HAVE_LIBGNUTLS
257         gnutls_session_t sess = c->ssl_state.gnutls_session;
258         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
259                 gnutls_bye(sess, GNUTLS_SHUT_RDWR);
260                 gnutls_deinit(sess);
261         }
262 #endif
263         assert(Conn_OPTION_ISSET(c, CONN_SSL));
264         /* can't just set bitmask to 0 -- there are other, non-ssl related flags, e.g. CONN_ZIP. */
265         Conn_OPTION_DEL(c, CONN_SSL_FLAGS_ALL);
266 }
267
268
269 bool
270 ConnSSL_InitLibrary( void )
271 {
272         if (!Conf_SSLInUse()) {
273                 LogDebug("SSL not in use, skipping initialization.");
274                 return true;
275         }
276
277 #ifdef HAVE_LIBSSL
278         SSL_CTX *newctx;
279
280         if (!ssl_ctx) {
281                 SSL_library_init();
282                 SSL_load_error_strings();
283         }
284
285         if (!RAND_status()) {
286                 Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
287                 /*
288                  * it is probably best to fail and let the user install EGD or
289                  * a similar program if no kernel random device is available.
290                  * According to OpenSSL RAND_egd(3): "The automatic query of
291                  * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
292                  * so it makes little sense to deal with PRNGD seeding ourselves.
293                  */
294                 array_free(&Conf_SSLOptions.ListenPorts);
295                 return false;
296         }
297
298         newctx = SSL_CTX_new(SSLv23_method());
299         if (!newctx) {
300                 LogOpenSSLError("Failed to create SSL context", NULL);
301                 array_free(&Conf_SSLOptions.ListenPorts);
302                 return false;
303         }
304
305         if (!ConnSSL_LoadServerKey_openssl(newctx))
306                 goto out;
307
308         if(Conf_SSLOptions.CipherList && *Conf_SSLOptions.CipherList) {
309                 if(SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0 ) {
310                         Log(LOG_ERR,
311                             "Failed to apply SSL cipher list \"%s\"!",
312                             Conf_SSLOptions.CipherList);
313                         goto out;
314                 } else {
315                         Log(LOG_INFO,
316                             "Successfully applied SSL cipher list: \"%s\".",
317                             Conf_SSLOptions.CipherList);
318                 }
319         }
320
321         SSL_CTX_set_options(newctx, SSL_OP_SINGLE_DH_USE|SSL_OP_NO_SSLv2);
322         SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
323         SSL_CTX_set_verify(newctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
324                            Verify_openssl);
325         SSL_CTX_free(ssl_ctx);
326         ssl_ctx = newctx;
327         Log(LOG_INFO, "%s initialized.", SSLeay_version(SSLEAY_VERSION));
328         return true;
329 out:
330         SSL_CTX_free(newctx);
331         array_free(&Conf_SSLOptions.ListenPorts);
332         return false;
333 #endif
334 #ifdef HAVE_LIBGNUTLS
335         int err;
336         static bool initialized;
337
338         if (initialized) {
339                 /* TODO: cannot reload gnutls keys: can't simply free x509
340                  * context -- it may still be in use */
341                 return false;
342         }
343
344         if(Conf_SSLOptions.CipherList != NULL) {
345                 Log(LOG_ERR,
346                     "Failed to apply SSL cipher list \"%s\": Not implemented for GnuTLS!",
347                     Conf_SSLOptions.CipherList);
348                 array_free(&Conf_SSLOptions.ListenPorts);
349                 return false;
350         }
351
352         err = gnutls_global_init();
353         if (err) {
354                 Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
355                     gnutls_strerror(err));
356                 array_free(&Conf_SSLOptions.ListenPorts);
357                 return false;
358         }
359         if (!ConnSSL_LoadServerKey_gnutls()) {
360                 array_free(&Conf_SSLOptions.ListenPorts);
361                 return false;
362         }
363
364         Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
365         initialized = true;
366         return true;
367 #endif
368 }
369
370
371 #ifdef HAVE_LIBGNUTLS
372 static bool
373 ConnSSL_LoadServerKey_gnutls(void)
374 {
375         int err;
376         const char *cert_file;
377
378         err = gnutls_certificate_allocate_credentials(&x509_cred);
379         if (err < 0) {
380                 Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
381                     gnutls_strerror(err));
382                 return false;
383         }
384
385         cert_file = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
386         if (!cert_file) {
387                 Log(LOG_ERR, "No SSL server key configured!");
388                 return false;
389         }
390
391         if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
392                 Log(LOG_WARNING,
393                     "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
394
395         if (!Load_DH_params())
396                 return false;
397
398         gnutls_certificate_set_dh_params(x509_cred, dh_params);
399         err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file, Conf_SSLOptions.KeyFile, GNUTLS_X509_FMT_PEM);
400         if (err < 0) {
401                 Log(LOG_ERR,
402                     "Failed to set certificate key file (cert %s, key %s): %s",
403                     cert_file,
404                     Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
405                     gnutls_strerror(err));
406                 return false;
407         }
408         return true;
409 }
410 #endif
411
412
413 #ifdef HAVE_LIBSSL
414 static bool
415 ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
416 {
417         char *cert_key;
418
419         assert(ctx);
420         if (!Conf_SSLOptions.KeyFile) {
421                 Log(LOG_ERR, "No SSL server key configured!");
422                 return false;
423         }
424
425         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
426         SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
427
428         if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
429                 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
430                 LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
431                 return false;
432         }
433
434         cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
435         if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
436                 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
437                 LogOpenSSLError("Failed to load certificate chain", cert_key);
438                 return false;
439         }
440
441         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
442
443         if (!SSL_CTX_check_private_key(ctx)) {
444                 LogOpenSSLError("Server private key does not match certificate", NULL);
445                 return false;
446         }
447         if (Load_DH_params()) {
448                 if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
449                         LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
450                 /* don't return false here: the non-DH modes will still work */
451                 DH_free(dh_params);
452                 dh_params = NULL;
453         }
454         return true;
455 }
456
457
458 #endif
459 static bool
460 ConnSSL_Init_SSL(CONNECTION *c)
461 {
462         int ret;
463         assert(c != NULL);
464 #ifdef HAVE_LIBSSL
465         if (!ssl_ctx) {
466                 Log(LOG_ERR,
467                     "Can't initialize SSL context, OpenSSL initialization failed at startup!");
468                 return false;
469         }
470         assert(c->ssl_state.ssl == NULL);
471         assert(c->ssl_state.fingerprint == NULL);
472
473         c->ssl_state.ssl = SSL_new(ssl_ctx);
474         if (!c->ssl_state.ssl) {
475                 LogOpenSSLError("Failed to create SSL structure", NULL);
476                 return false;
477         }
478
479         ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
480         if (ret != 1) {
481                 LogOpenSSLError("Failed to set SSL file descriptor", NULL);
482                 ConnSSL_Free(c);
483                 return false;
484         }
485 #endif
486 #ifdef HAVE_LIBGNUTLS
487         ret = gnutls_set_default_priority(c->ssl_state.gnutls_session);
488         if (ret < 0) {
489                 Log(LOG_ERR, "Failed to set GnuTLS default priority: %s",
490                     gnutls_strerror(ret));
491                 ConnSSL_Free(c);
492                 return false;
493         }
494         /*
495          * The intermediate (long) cast is here to avoid a warning like:
496          * "cast to pointer from integer of different size" on 64-bit platforms.
497          * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
498          * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
499          */
500         gnutls_transport_set_ptr(c->ssl_state.gnutls_session, (gnutls_transport_ptr_t) (long) c->sock);
501         gnutls_certificate_server_set_request(c->ssl_state.gnutls_session, GNUTLS_CERT_REQUEST);
502         ret = gnutls_credentials_set(c->ssl_state.gnutls_session, GNUTLS_CRD_CERTIFICATE, x509_cred);
503         if (ret < 0) {
504                 Log(LOG_ERR, "Failed to set SSL credentials: %s", gnutls_strerror(ret));
505                 ConnSSL_Free(c);
506                 return false;
507         }
508         gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
509 #endif
510         Conn_OPTION_ADD(c, CONN_SSL);
511         return true;
512 }
513
514
515 bool
516 ConnSSL_PrepareConnect(CONNECTION *c, UNUSED CONF_SERVER *s)
517 {
518         bool ret;
519 #ifdef HAVE_LIBGNUTLS
520         int err;
521
522         err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
523         if (err) {
524                 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
525                     gnutls_strerror(err));
526                 return false;
527         }
528 #endif
529         ret = ConnSSL_Init_SSL(c);
530         if (!ret)
531                 return false;
532         Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
533 #ifdef HAVE_LIBSSL
534         assert(c->ssl_state.ssl);
535         SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
536 #endif
537         return true;
538 }
539
540
541 /**
542  * Check and handle error return codes after failed calls to SSL functions.
543  *
544  * OpenSSL:
545  * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
546  * SSL_write() on ssl.
547  *
548  * GnuTLS:
549  * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
550  *
551  * @param c The connection handle.
552  * @prarm code The return code.
553  * @param fname The name of the function in which the error occurred.
554  * @return -1 on fatal errors, 0 if we can try again later.
555  */
556 static int
557 ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
558 {
559 #ifdef HAVE_LIBSSL
560         int ret = SSL_ERROR_SYSCALL;
561         unsigned long sslerr;
562         int real_errno = errno;
563
564         ret = SSL_get_error(c->ssl_state.ssl, code);
565
566         switch (ret) {
567         case SSL_ERROR_WANT_READ:
568                 io_event_del(c->sock, IO_WANTWRITE);
569                 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
570                 return 0;       /* try again later */
571         case SSL_ERROR_WANT_WRITE:
572                 io_event_del(c->sock, IO_WANTREAD);
573                 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
574         case SSL_ERROR_NONE:
575                 return 0;       /* try again later */
576         case SSL_ERROR_ZERO_RETURN:
577                 LogDebug("SSL connection shut down normally.");
578                 break;
579         case SSL_ERROR_SYSCALL:
580                 /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
581                  * and SSL_ERROR_WANT_X509_LOOKUP */
582                 sslerr = ERR_get_error();
583                 if (sslerr) {
584                         Log(LOG_ERR, "SSL error: %s [in %s()]!",
585                             ERR_error_string(sslerr, NULL), fname);
586                 } else {
587                         switch (code) { /* EOF that violated protocol */
588                         case 0:
589                                 Log(LOG_ERR,
590                                     "SSL error, client disconnected [in %s()]!",
591                                     fname);
592                                 break;
593                         case -1:        /* low level socket I/O error, check errno */
594                                 Log(LOG_ERR, "SSL error: %s [in %s()]!",
595                                     strerror(real_errno), fname);
596                         }
597                 }
598                 break;
599         case SSL_ERROR_SSL:
600                 LogOpenSSLError("SSL protocol error", fname);
601                 break;
602         default:
603                 Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
604         }
605         ConnSSL_Free(c);
606         return -1;
607 #endif
608 #ifdef HAVE_LIBGNUTLS
609         switch (code) {
610         case GNUTLS_E_AGAIN:
611         case GNUTLS_E_INTERRUPTED:
612                 if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
613                         Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
614                         io_event_del(c->sock, IO_WANTREAD);
615                 } else {
616                         Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
617                         io_event_del(c->sock, IO_WANTWRITE);
618                 }
619                 break;
620         default:
621                 assert(code < 0);
622                 if (gnutls_error_is_fatal(code)) {
623                         Log(LOG_ERR, "SSL error: %s [%s].",
624                             gnutls_strerror(code), fname);
625                         ConnSSL_Free(c);
626                         return -1;
627                 }
628         }
629         return 0;
630 #endif
631 }
632
633
634 static void
635 ConnSSL_LogCertInfo( CONNECTION *c )
636 {
637 #ifdef HAVE_LIBSSL
638         SSL *ssl = c->ssl_state.ssl;
639
640         assert(ssl);
641
642         Log(LOG_INFO, "Connection %d: initialized %s using cipher %s.",
643                 c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl));
644 #endif
645 #ifdef HAVE_LIBGNUTLS
646         gnutls_session_t sess = c->ssl_state.gnutls_session;
647         gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
648
649         Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
650             c->sock,
651             gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
652             gnutls_cipher_get_name(cipher),
653             gnutls_mac_get_name(gnutls_mac_get(sess)));
654 #endif
655 }
656
657
658 /*
659  Accept incoming SSL connection.
660  Return Values:
661          1: SSL Connection established
662          0: try again
663         -1: SSL Connection not established due to fatal error.
664 */
665 int
666 ConnSSL_Accept( CONNECTION *c )
667 {
668         assert(c != NULL);
669         if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
670 #ifdef HAVE_LIBGNUTLS
671                 int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
672                 if (err) {
673                         Log(LOG_ERR, "Failed to initialize new SSL session: %s",
674                             gnutls_strerror(err));
675                         return false;
676                 }
677 #endif
678                 LogDebug("Initializing SSL data ...");
679                 if (!ConnSSL_Init_SSL(c))
680                         return -1;
681         }
682         return ConnectAccept(c, false );
683 }
684
685
686 int
687 ConnSSL_Connect( CONNECTION *c )
688 {
689         assert(c != NULL);
690 #ifdef HAVE_LIBSSL
691         assert(c->ssl_state.ssl);
692 #endif
693         assert(Conn_OPTION_ISSET(c, CONN_SSL));
694         return ConnectAccept(c, true);
695 }
696
697 static int
698 ConnSSL_InitCertFp( CONNECTION *c )
699 {
700         const char hex[] = "0123456789abcdef";
701         int i;
702
703 #ifdef HAVE_LIBSSL
704         unsigned char digest[EVP_MAX_MD_SIZE];
705         unsigned int digest_size;
706         X509 *cert;
707
708         cert = SSL_get_peer_certificate(c->ssl_state.ssl);
709         if (!cert)
710                 return 0;
711
712         if (!X509_digest(cert, EVP_sha1(), digest, &digest_size)) {
713                 X509_free(cert);
714                 return 0;
715         }
716
717         X509_free(cert);
718 #endif /* HAVE_LIBSSL */
719 #ifdef HAVE_LIBGNUTLS
720         gnutls_x509_crt_t cert;
721         unsigned int cert_list_size;
722         const gnutls_datum_t *cert_list;
723         unsigned char digest[MAX_HASH_SIZE];
724         size_t digest_size;
725
726         if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) != GNUTLS_CRT_X509)
727                 return 0;
728
729         if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
730                 return 0;
731
732         cert_list_size = 0;
733         cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
734                                                  &cert_list_size);
735         if (!cert_list) {
736                 gnutls_x509_crt_deinit(cert);
737                 return 0;
738         }
739         
740         if (gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
741                 gnutls_x509_crt_deinit(cert);
742                 return 0;
743         }
744
745         digest_size = sizeof(digest);
746         if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, digest, &digest_size)) {
747                 gnutls_x509_crt_deinit(cert);
748                 return 0;
749         }
750
751         gnutls_x509_crt_deinit(cert);
752 #endif /* HAVE_LIBGNUTLS */
753
754         assert(c->ssl_state.fingerprint == NULL);
755
756         c->ssl_state.fingerprint = malloc(SHA1_STRING_LEN);
757         if (!c->ssl_state.fingerprint)
758                 return 0;
759
760         for (i = 0; i < (int)digest_size; i++) {
761                 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
762                 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
763         }
764         c->ssl_state.fingerprint[i * 2] = '\0';
765
766         return 1;
767 }
768
769 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
770 static int
771 ConnectAccept( CONNECTION *c, bool connect)
772 {
773         int ret;
774 #ifdef HAVE_LIBSSL
775         SSL *ssl = c->ssl_state.ssl;
776         assert(ssl != NULL);
777
778         ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
779         if (1 != ret)
780                 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
781 #endif
782 #ifdef HAVE_LIBGNUTLS
783         (void) connect;
784         ret = gnutls_handshake(c->ssl_state.gnutls_session);
785         if (ret)
786                 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
787 #endif /* _GNUTLS */
788         (void)ConnSSL_InitCertFp(c);
789
790         Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
791         ConnSSL_LogCertInfo(c);
792
793         Conn_StartLogin(CONNECTION2ID(c));
794         return 1;
795 }
796
797
798 ssize_t
799 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
800 {
801         ssize_t bw;
802
803         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
804
805         assert(count > 0);
806 #ifdef HAVE_LIBSSL
807         bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
808 #endif
809 #ifdef HAVE_LIBGNUTLS
810         bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
811 #endif
812         if (bw > 0)
813                 return bw;
814         if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
815                 errno = EAGAIN; /* try again */
816         return -1;
817 }
818
819
820 ssize_t
821 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
822 {
823         ssize_t br;
824
825         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
826 #ifdef HAVE_LIBSSL
827         br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
828         if (br > 0)     /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
829                 return br;
830 #endif
831 #ifdef HAVE_LIBGNUTLS
832         br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
833         if (br >= 0)    /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
834                 return br;
835 #endif
836         /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
837         if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
838                 errno = EAGAIN;
839                 return -1;
840         }
841         return 0;
842 }
843
844
845 bool
846 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
847 {
848 #ifdef HAVE_LIBSSL
849         char *nl;
850         SSL *ssl = c->ssl_state.ssl;
851
852         if (!ssl)
853                 return false;
854         *buf = 0;
855         SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
856         nl = strchr(buf, '\n');
857         if (nl)
858                 *nl = 0;
859         return true;
860 #endif
861 #ifdef HAVE_LIBGNUTLS
862         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
863                 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
864                 unsigned keysize;
865
866                 gnutls_session_t sess = c->ssl_state.gnutls_session;
867                 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
868                 name_cipher = gnutls_cipher_get_name(cipher);
869                 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
870                 keysize = gnutls_cipher_get_key_size(cipher) * 8;
871                 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
872                 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
873
874                 return snprintf(buf, len, "%s-%s%15s Kx=%s      Enc=%s(%u) Mac=%s",
875                         name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
876         }
877         return false;
878 #endif
879 }
880
881 char *
882 ConnSSL_GetCertFp(CONNECTION *c)
883 {
884         return c->ssl_state.fingerprint;
885 }
886
887 bool
888 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
889 {
890         assert (c != NULL);
891         c->ssl_state.fingerprint = strndup(fingerprint, SHA1_STRING_LEN - 1);
892         return c->ssl_state.fingerprint != NULL;
893 }
894 #else
895
896 bool
897 ConnSSL_InitLibrary(void)
898 {
899         return true;
900 }
901
902 #endif /* SSL_SUPPORT */
903 /* -eof- */
904
905