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