]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn-ssl.c
Clarify that "CAFile" is not set by default
[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  * 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                 /* Failed to read new key but an old ssl context
316                  * already exists -> reuse old context */
317                 if (ssl_ctx) {
318                         SSL_CTX_free(newctx);
319                         Log(LOG_WARNING,
320                         "Re-Initializing of SSL failed, using old keys!");
321                         return true;
322                 }
323                 /* No preexisting old context -> error. */
324                 goto out;
325         }
326
327         if (SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0) {
328                 Log(LOG_ERR, "Failed to apply OpenSSL cipher list \"%s\"!",
329                     Conf_SSLOptions.CipherList);
330                 goto out;
331         }
332
333         SSL_CTX_set_session_id_context(newctx, (unsigned char *)"ngircd", 6);
334         SSL_CTX_set_options(newctx, SSL_OP_SINGLE_DH_USE|SSL_OP_NO_SSLv2);
335         SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
336         SSL_CTX_set_verify(newctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
337                            Verify_openssl);
338         SSL_CTX_free(ssl_ctx);
339         ssl_ctx = newctx;
340         Log(LOG_INFO, "%s initialized.", OpenSSL_version(OPENSSL_VERSION));
341         return true;
342 out:
343         SSL_CTX_free(newctx);
344         array_free(&Conf_SSLOptions.ListenPorts);
345         return false;
346 #endif
347 #ifdef HAVE_LIBGNUTLS
348         int err;
349         static bool initialized;
350
351         if (initialized) {
352                 /* TODO: cannot reload gnutls keys: can't simply free x509
353                  * context -- it may still be in use */
354                 return false;
355         }
356
357         err = gnutls_global_init();
358         if (err) {
359                 Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
360                     gnutls_strerror(err));
361                 goto out;
362         }
363
364         if (!ConnSSL_LoadServerKey_gnutls())
365                 goto out;
366
367         if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
368                                  NULL) != GNUTLS_E_SUCCESS) {
369                 Log(LOG_ERR,
370                     "Failed to apply GnuTLS cipher list \"%s\"!",
371                     Conf_SSLOptions.CipherList);
372                 goto out;
373         }
374
375         Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
376         initialized = true;
377         return true;
378 out:
379         array_free(&Conf_SSLOptions.ListenPorts);
380         return false;
381 #endif
382 }
383
384
385 #ifdef HAVE_LIBGNUTLS
386 static bool
387 ConnSSL_LoadServerKey_gnutls(void)
388 {
389         int err;
390         const char *cert_file;
391
392         err = gnutls_certificate_allocate_credentials(&x509_cred);
393         if (err < 0) {
394                 Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
395                     gnutls_strerror(err));
396                 return false;
397         }
398
399         cert_file = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
400         if (!cert_file) {
401                 Log(LOG_ERR, "No SSL server key configured!");
402                 return false;
403         }
404
405         if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
406                 Log(LOG_WARNING,
407                     "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
408
409         if (!Load_DH_params())
410                 return false;
411
412         gnutls_certificate_set_dh_params(x509_cred, dh_params);
413         err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file, Conf_SSLOptions.KeyFile, GNUTLS_X509_FMT_PEM);
414         if (err < 0) {
415                 Log(LOG_ERR,
416                     "Failed to set certificate key file (cert %s, key %s): %s",
417                     cert_file,
418                     Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
419                     gnutls_strerror(err));
420                 return false;
421         }
422         return true;
423 }
424 #endif
425
426
427 #ifdef HAVE_LIBSSL
428 static bool
429 ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
430 {
431         char *cert_key;
432
433         assert(ctx);
434         if (!Conf_SSLOptions.KeyFile) {
435                 Log(LOG_ERR, "No SSL server key configured!");
436                 return false;
437         }
438
439         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
440         SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
441
442         if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
443                 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
444                 LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
445                 return false;
446         }
447
448         cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
449         if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
450                 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
451                 LogOpenSSLError("Failed to load certificate chain", cert_key);
452                 return false;
453         }
454
455         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
456
457         if (!SSL_CTX_check_private_key(ctx)) {
458                 LogOpenSSLError("Server private key does not match certificate", NULL);
459                 return false;
460         }
461         if (Load_DH_params()) {
462                 if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
463                         LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
464                 /* don't return false here: the non-DH modes will still work */
465                 DH_free(dh_params);
466                 dh_params = NULL;
467         }
468         return true;
469 }
470
471
472 #endif
473 static bool
474 ConnSSL_Init_SSL(CONNECTION *c)
475 {
476         int ret;
477
478         LogDebug("Initializing SSL ...");
479         assert(c != NULL);
480
481 #ifdef HAVE_LIBSSL
482         if (!ssl_ctx) {
483                 Log(LOG_ERR,
484                     "Can't initialize SSL context, OpenSSL initialization failed at startup!");
485                 return false;
486         }
487         assert(c->ssl_state.ssl == NULL);
488         assert(c->ssl_state.fingerprint == NULL);
489
490         c->ssl_state.ssl = SSL_new(ssl_ctx);
491         if (!c->ssl_state.ssl) {
492                 LogOpenSSLError("Failed to create SSL structure", NULL);
493                 return false;
494         }
495         Conn_OPTION_ADD(c, CONN_SSL);
496
497         ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
498         if (ret != 1) {
499                 LogOpenSSLError("Failed to set SSL file descriptor", NULL);
500                 ConnSSL_Free(c);
501                 return false;
502         }
503 #endif
504 #ifdef HAVE_LIBGNUTLS
505         Conn_OPTION_ADD(c, CONN_SSL);
506         ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
507         if (ret != GNUTLS_E_SUCCESS) {
508                 Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
509                     gnutls_strerror(ret));
510                 ConnSSL_Free(c);
511                 return false;
512         }
513         /*
514          * The intermediate (long) cast is here to avoid a warning like:
515          * "cast to pointer from integer of different size" on 64-bit platforms.
516          * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
517          * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
518          */
519         gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
520                                  (gnutls_transport_ptr_t) (long) c->sock);
521         gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
522                                               GNUTLS_CERT_REQUEST);
523         ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
524                                      GNUTLS_CRD_CERTIFICATE, x509_cred);
525         if (ret != 0) {
526                 Log(LOG_ERR, "Failed to set SSL credentials: %s",
527                     gnutls_strerror(ret));
528                 ConnSSL_Free(c);
529                 return false;
530         }
531         gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
532 #endif
533         return true;
534 }
535
536
537 bool
538 ConnSSL_PrepareConnect(CONNECTION *c, UNUSED CONF_SERVER *s)
539 {
540         bool ret;
541 #ifdef HAVE_LIBGNUTLS
542         int err;
543
544         err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
545         if (err) {
546                 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
547                     gnutls_strerror(err));
548                 return false;
549         }
550 #endif
551         ret = ConnSSL_Init_SSL(c);
552         if (!ret)
553                 return false;
554         Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
555 #ifdef HAVE_LIBSSL
556         assert(c->ssl_state.ssl);
557         SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
558 #endif
559         return true;
560 }
561
562
563 /**
564  * Check and handle error return codes after failed calls to SSL functions.
565  *
566  * OpenSSL:
567  * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
568  * SSL_write() on ssl.
569  *
570  * GnuTLS:
571  * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
572  *
573  * @param c The connection handle.
574  * @prarm code The return code.
575  * @param fname The name of the function in which the error occurred.
576  * @return -1 on fatal errors, 0 if we can try again later.
577  */
578 static int
579 ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
580 {
581 #ifdef HAVE_LIBSSL
582         int ret = SSL_ERROR_SYSCALL;
583         unsigned long sslerr;
584         int real_errno = errno;
585
586         ret = SSL_get_error(c->ssl_state.ssl, code);
587
588         switch (ret) {
589         case SSL_ERROR_WANT_READ:
590                 io_event_del(c->sock, IO_WANTWRITE);
591                 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
592                 return 0;       /* try again later */
593         case SSL_ERROR_WANT_WRITE:
594                 io_event_del(c->sock, IO_WANTREAD);
595                 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
596         case SSL_ERROR_NONE:
597                 return 0;       /* try again later */
598         case SSL_ERROR_ZERO_RETURN:
599                 LogDebug("SSL connection shut down normally.");
600                 break;
601         case SSL_ERROR_SYSCALL:
602                 /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
603                  * and SSL_ERROR_WANT_X509_LOOKUP */
604                 sslerr = ERR_get_error();
605                 if (sslerr) {
606                         Log(LOG_ERR, "SSL error: %s [in %s()]!",
607                             ERR_error_string(sslerr, NULL), fname);
608                 } else {
609                         switch (code) { /* EOF that violated protocol */
610                         case 0:
611                                 Log(LOG_ERR,
612                                     "SSL error, client disconnected [in %s()]!",
613                                     fname);
614                                 break;
615                         case -1:        /* low level socket I/O error, check errno */
616                                 Log(LOG_ERR, "SSL error: %s [in %s()]!",
617                                     strerror(real_errno), fname);
618                         }
619                 }
620                 break;
621         case SSL_ERROR_SSL:
622                 LogOpenSSLError("SSL protocol error", fname);
623                 break;
624         default:
625                 Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
626         }
627         ConnSSL_Free(c);
628         return -1;
629 #endif
630 #ifdef HAVE_LIBGNUTLS
631         switch (code) {
632         case GNUTLS_E_AGAIN:
633         case GNUTLS_E_INTERRUPTED:
634                 if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
635                         Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
636                         io_event_del(c->sock, IO_WANTREAD);
637                 } else {
638                         Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
639                         io_event_del(c->sock, IO_WANTWRITE);
640                 }
641                 break;
642         default:
643                 assert(code < 0);
644                 if (gnutls_error_is_fatal(code)) {
645                         Log(LOG_ERR, "SSL error: %s [%s].",
646                             gnutls_strerror(code), fname);
647                         ConnSSL_Free(c);
648                         return -1;
649                 }
650         }
651         return 0;
652 #endif
653 }
654
655
656 static void
657 ConnSSL_LogCertInfo( CONNECTION *c )
658 {
659 #ifdef HAVE_LIBSSL
660         SSL *ssl = c->ssl_state.ssl;
661
662         assert(ssl);
663
664         Log(LOG_INFO, "Connection %d: initialized %s using cipher %s.",
665                 c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl));
666 #endif
667 #ifdef HAVE_LIBGNUTLS
668         gnutls_session_t sess = c->ssl_state.gnutls_session;
669         gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
670
671         Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
672             c->sock,
673             gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
674             gnutls_cipher_get_name(cipher),
675             gnutls_mac_get_name(gnutls_mac_get(sess)));
676 #endif
677 }
678
679
680 /*
681  Accept incoming SSL connection.
682  Return Values:
683          1: SSL Connection established
684          0: try again
685         -1: SSL Connection not established due to fatal error.
686 */
687 int
688 ConnSSL_Accept( CONNECTION *c )
689 {
690         assert(c != NULL);
691         if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
692 #ifdef HAVE_LIBGNUTLS
693                 int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
694                 if (err) {
695                         Log(LOG_ERR, "Failed to initialize new SSL session: %s",
696                             gnutls_strerror(err));
697                         return false;
698                 }
699 #endif
700                 if (!ConnSSL_Init_SSL(c))
701                         return -1;
702         }
703         return ConnectAccept(c, false );
704 }
705
706
707 int
708 ConnSSL_Connect( CONNECTION *c )
709 {
710         assert(c != NULL);
711 #ifdef HAVE_LIBSSL
712         assert(c->ssl_state.ssl);
713 #endif
714         assert(Conn_OPTION_ISSET(c, CONN_SSL));
715         return ConnectAccept(c, true);
716 }
717
718 static int
719 ConnSSL_InitCertFp( CONNECTION *c )
720 {
721         const char hex[] = "0123456789abcdef";
722         int i;
723
724 #ifdef HAVE_LIBSSL
725         unsigned char digest[EVP_MAX_MD_SIZE];
726         unsigned int digest_size;
727         X509 *cert;
728
729         cert = SSL_get_peer_certificate(c->ssl_state.ssl);
730         if (!cert)
731                 return 0;
732
733         if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
734                 X509_free(cert);
735                 return 0;
736         }
737
738         X509_free(cert);
739 #endif /* HAVE_LIBSSL */
740 #ifdef HAVE_LIBGNUTLS
741         gnutls_x509_crt_t cert;
742         unsigned int cert_list_size;
743         const gnutls_datum_t *cert_list;
744         unsigned char digest[MAX_HASH_SIZE];
745         size_t digest_size;
746
747         if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
748                                         GNUTLS_CRT_X509)
749                 return 0;
750
751         if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
752                 return 0;
753
754         cert_list_size = 0;
755         cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
756                                                  &cert_list_size);
757         if (!cert_list) {
758                 gnutls_x509_crt_deinit(cert);
759                 return 0;
760         }
761
762         if (gnutls_x509_crt_import(cert, &cert_list[0],
763                                    GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
764                 gnutls_x509_crt_deinit(cert);
765                 return 0;
766         }
767
768         digest_size = sizeof(digest);
769         if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
770                                             &digest_size)) {
771                 gnutls_x509_crt_deinit(cert);
772                 return 0;
773         }
774
775         gnutls_x509_crt_deinit(cert);
776 #endif /* HAVE_LIBGNUTLS */
777
778         assert(c->ssl_state.fingerprint == NULL);
779
780         c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
781         if (!c->ssl_state.fingerprint)
782                 return 0;
783
784         for (i = 0; i < (int)digest_size; i++) {
785                 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
786                 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
787         }
788         c->ssl_state.fingerprint[i * 2] = '\0';
789
790         return 1;
791 }
792
793 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
794 static int
795 ConnectAccept( CONNECTION *c, bool connect)
796 {
797         int ret;
798 #ifdef HAVE_LIBSSL
799         SSL *ssl = c->ssl_state.ssl;
800         assert(ssl != NULL);
801
802         ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
803         if (1 != ret)
804                 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
805 #endif
806 #ifdef HAVE_LIBGNUTLS
807         (void) connect;
808         ret = gnutls_handshake(c->ssl_state.gnutls_session);
809         if (ret)
810                 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
811 #endif /* _GNUTLS */
812         (void)ConnSSL_InitCertFp(c);
813
814         Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
815         ConnSSL_LogCertInfo(c);
816
817         Conn_StartLogin(CONNECTION2ID(c));
818         return 1;
819 }
820
821
822 ssize_t
823 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
824 {
825         ssize_t bw;
826
827         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
828
829         assert(count > 0);
830 #ifdef HAVE_LIBSSL
831         bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
832 #endif
833 #ifdef HAVE_LIBGNUTLS
834         bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
835 #endif
836         if (bw > 0)
837                 return bw;
838         if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
839                 errno = EAGAIN; /* try again */
840         return -1;
841 }
842
843
844 ssize_t
845 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
846 {
847         ssize_t br;
848
849         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
850 #ifdef HAVE_LIBSSL
851         br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
852         if (br > 0)     /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
853                 return br;
854 #endif
855 #ifdef HAVE_LIBGNUTLS
856         br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
857         if (br >= 0)    /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
858                 return br;
859 #endif
860         /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
861         if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
862                 errno = EAGAIN;
863                 return -1;
864         }
865         return 0;
866 }
867
868
869 bool
870 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
871 {
872 #ifdef HAVE_LIBSSL
873         char *nl;
874         SSL *ssl = c->ssl_state.ssl;
875
876         if (!ssl)
877                 return false;
878         *buf = 0;
879         SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
880         nl = strchr(buf, '\n');
881         if (nl)
882                 *nl = 0;
883         return true;
884 #endif
885 #ifdef HAVE_LIBGNUTLS
886         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
887                 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
888                 unsigned keysize;
889
890                 gnutls_session_t sess = c->ssl_state.gnutls_session;
891                 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
892                 name_cipher = gnutls_cipher_get_name(cipher);
893                 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
894                 keysize = gnutls_cipher_get_key_size(cipher) * 8;
895                 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
896                 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
897
898                 return snprintf(buf, len, "%s-%s%15s Kx=%s      Enc=%s(%u) Mac=%s",
899                         name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
900         }
901         return false;
902 #endif
903 }
904
905 char *
906 ConnSSL_GetCertFp(CONNECTION *c)
907 {
908         return c->ssl_state.fingerprint;
909 }
910
911 bool
912 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
913 {
914         assert (c != NULL);
915         c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
916         return c->ssl_state.fingerprint != NULL;
917 }
918 #else
919
920 bool
921 ConnSSL_InitLibrary(void)
922 {
923         return true;
924 }
925
926 #endif /* SSL_SUPPORT */
927 /* -eof- */