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