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