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