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