a97896758cc30c2f63724ab5396e797e064763da
[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 "imp.h"
14 #include "conf-ssl.h"
15
16 #ifdef SSL_SUPPORT
17
18 #include "io.h"
19 #include <assert.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <errno.h>
24
25 #define CONN_MODULE
26 #include "conn.h"
27 #include "conf.h"
28 #include "conn-func.h"
29 #include "conn-ssl.h"
30 #include "log.h"
31
32 #include "exp.h"
33 #include "defines.h"
34
35 extern struct SSLOptions Conf_SSLOptions;
36
37 #ifdef HAVE_LIBSSL
38 #include <openssl/err.h>
39 #include <openssl/rand.h>
40
41 static SSL_CTX * ssl_ctx;
42 static DH *dh_params;
43
44 static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
45 #endif
46
47 #ifdef HAVE_LIBGNUTLS
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <fcntl.h>
51 #include <unistd.h>
52 #include <gnutls/x509.h>
53
54 #define DH_BITS 2048
55 #define DH_BITS_MIN 1024
56
57 #define MAX_HASH_SIZE   64      /* from gnutls-int.h */
58
59 static gnutls_certificate_credentials_t x509_cred;
60 static gnutls_dh_params_t dh_params;
61 static bool ConnSSL_LoadServerKey_gnutls PARAMS(( void ));
62 #endif
63
64 #define SHA1_STRING_LEN (20 * 2 + 1)
65
66 static bool ConnSSL_Init_SSL PARAMS(( CONNECTION *c ));
67 static int ConnectAccept PARAMS(( CONNECTION *c, bool connect ));
68 static int ConnSSL_HandleError PARAMS(( CONNECTION *c, const int code, const char *fname ));
69
70 #ifdef HAVE_LIBGNUTLS
71 static char * openreadclose(const char *name, size_t *len)
72 {
73         char *buf = NULL;
74         struct stat s;
75         ssize_t br;
76         int fd = open(name, O_RDONLY);
77         if (fd < 0) {
78                 Log(LOG_ERR, "Could not open %s: %s", name, strerror(errno));
79                 return NULL;
80         }
81         if (fstat(fd, &s)) {
82                 Log(LOG_ERR, "Could not fstat %s: %s", name, strerror(errno));
83                 goto out;
84         }
85         if (!S_ISREG(s.st_mode)) {
86                 Log(LOG_ERR, "%s: Not a regular file", name);
87                 goto out;
88         }
89         if (s.st_size <= 0) {
90                 Log(LOG_ERR, "%s: invalid file length (size %ld <= 0)", name, (long) s.st_size);
91                 goto out;
92         }
93         buf = malloc(s.st_size);
94         if (!buf) {
95                 Log(LOG_ERR, "Could not malloc %lu bytes for file %s: %s", s.st_size, name, strerror(errno));
96                 goto out;
97         }
98         br = read(fd, buf, s.st_size);
99         if (br != (ssize_t)s.st_size) {
100                 Log(LOG_ERR, "Could not read file %s: read returned %ld, expected %ld: %s",
101                         name, (long) br, (long) s.st_size, br == -1 ? strerror(errno):"short read?!");
102                 memset(buf, 0, s.st_size);
103                 free(buf);
104                 buf = NULL;
105         } else {
106                 *len = br;
107         }
108 out:
109         close(fd);
110         return buf;
111 }
112 #endif
113
114
115 #ifdef HAVE_LIBSSL
116 /**
117  * Log OpenSSL error message.
118  *
119  * @param msg The error message.
120  * @param info Additional information text or NULL.
121  */
122 static void
123 LogOpenSSLError(const char *error, const char *info)
124 {
125         unsigned long err = ERR_get_error();
126         char * errmsg = err
127                 ? ERR_error_string(err, NULL)
128                 : "Unable to determine error";
129
130         assert(error != NULL);
131
132         if (info)
133                 Log(LOG_ERR, "%s: %s (%s)", error, info, errmsg);
134         else
135                 Log(LOG_ERR, "%s: %s", error, errmsg);
136 }
137
138
139 static int
140 pem_passwd_cb(char *buf, int size, int rwflag, void *password)
141 {
142         array *pass = password;
143         int passlen;
144
145         (void)rwflag;           /* rwflag is unused if DEBUG is not set. */
146         assert(rwflag == 0);    /* 0 -> callback used for decryption.
147                                  * See SSL_CTX_set_default_passwd_cb(3) */
148
149         passlen = (int) array_bytes(pass);
150
151         LogDebug("pem_passwd_cb buf size %d, array size %d", size, passlen);
152         assert(passlen >= 0);
153         if (passlen <= 0) {
154                 Log(LOG_ERR, "PEM password required but not set [in pem_passwd_cb()]!");
155                 return 0;
156         }
157         size = passlen > size ? size : passlen;
158         memcpy(buf, (char *)(array_start(pass)), size);
159         return size;
160 }
161
162
163 static int
164 Verify_openssl(UNUSED int preverify_ok, UNUSED X509_STORE_CTX *x509_ctx)
165 {
166         return 1;
167 }
168 #endif
169
170
171 static bool
172 Load_DH_params(void)
173 {
174 #ifdef HAVE_LIBSSL
175         FILE *fp;
176         bool ret = true;
177
178         if (!Conf_SSLOptions.DHFile) {
179                 Log(LOG_NOTICE, "Configuration option \"DHFile\" not set!");
180                 return false;
181         }
182         fp = fopen(Conf_SSLOptions.DHFile, "r");
183         if (!fp) {
184                 Log(LOG_ERR, "%s: %s", Conf_SSLOptions.DHFile, strerror(errno));
185                 return false;
186         }
187         dh_params = PEM_read_DHparams(fp, NULL, NULL, NULL);
188         if (!dh_params) {
189                 Log(LOG_ERR, "%s: Failed to read SSL DH parameters!",
190                     Conf_SSLOptions.DHFile);
191                 ret = false;
192         }
193         fclose(fp);
194         return ret;
195 #endif
196 #ifdef HAVE_LIBGNUTLS
197         bool need_dhgenerate = true;
198         int err;
199         gnutls_dh_params_t tmp_dh_params;
200
201         err = gnutls_dh_params_init(&tmp_dh_params);
202         if (err < 0) {
203                 Log(LOG_ERR, "Failed to initialize SSL DH parameters: %s",
204                     gnutls_strerror(err));
205                 return false;
206         }
207         if (Conf_SSLOptions.DHFile) {
208                 gnutls_datum_t dhparms;
209                 size_t size;
210                 dhparms.data = (unsigned char *) openreadclose(Conf_SSLOptions.DHFile, &size);
211                 if (dhparms.data) {
212                         dhparms.size = size;
213                         err = gnutls_dh_params_import_pkcs3(tmp_dh_params, &dhparms, GNUTLS_X509_FMT_PEM);
214                         if (err == 0)
215                                 need_dhgenerate = false;
216                         else
217                                 Log(LOG_ERR,
218                                     "Failed to initialize SSL DH parameters: %s",
219                                     gnutls_strerror(err));
220
221                         memset(dhparms.data, 0, size);
222                         free(dhparms.data);
223                 }
224         }
225         if (need_dhgenerate) {
226                 Log(LOG_WARNING,
227                     "DHFile not set, generating %u bit DH parameters. This may take a while ...",
228                     DH_BITS);
229                 err = gnutls_dh_params_generate2(tmp_dh_params, DH_BITS);
230                 if (err < 0) {
231                         Log(LOG_ERR, "Failed to generate SSL DH parameters: %s",
232                             gnutls_strerror(err));
233                         return false;
234                 }
235         }
236         dh_params = tmp_dh_params;
237         return true;
238 #endif
239 }
240
241
242 void ConnSSL_Free(CONNECTION *c)
243 {
244 #ifdef HAVE_LIBSSL
245         SSL *ssl = c->ssl_state.ssl;
246         if (ssl) {
247                 SSL_shutdown(ssl);
248                 SSL_free(ssl);
249                 c->ssl_state.ssl = NULL;
250                 if (c->ssl_state.fingerprint) {
251                         free(c->ssl_state.fingerprint);
252                         c->ssl_state.fingerprint = NULL;
253                 }
254         }
255 #endif
256 #ifdef HAVE_LIBGNUTLS
257         gnutls_session_t sess = c->ssl_state.gnutls_session;
258         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
259                 gnutls_bye(sess, GNUTLS_SHUT_RDWR);
260                 gnutls_deinit(sess);
261         }
262 #endif
263         assert(Conn_OPTION_ISSET(c, CONN_SSL));
264         /* can't just set bitmask to 0 -- there are other, non-ssl related flags, e.g. CONN_ZIP. */
265         Conn_OPTION_DEL(c, CONN_SSL_FLAGS_ALL);
266 }
267
268
269 bool
270 ConnSSL_InitLibrary( void )
271 {
272         if (!Conf_SSLInUse()) {
273                 LogDebug("SSL not in use, skipping initialization.");
274                 return true;
275         }
276
277 #ifdef HAVE_LIBSSL
278         SSL_CTX *newctx;
279
280         if (!ssl_ctx) {
281                 SSL_library_init();
282                 SSL_load_error_strings();
283         }
284
285         if (!RAND_status()) {
286                 Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
287                 /*
288                  * it is probably best to fail and let the user install EGD or
289                  * a similar program if no kernel random device is available.
290                  * According to OpenSSL RAND_egd(3): "The automatic query of
291                  * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
292                  * so it makes little sense to deal with PRNGD seeding ourselves.
293                  */
294                 array_free(&Conf_SSLOptions.ListenPorts);
295                 return false;
296         }
297
298         newctx = SSL_CTX_new(SSLv23_method());
299         if (!newctx) {
300                 LogOpenSSLError("Failed to create SSL context", NULL);
301                 array_free(&Conf_SSLOptions.ListenPorts);
302                 return false;
303         }
304
305         if (!ConnSSL_LoadServerKey_openssl(newctx))
306                 goto out;
307
308         if(Conf_SSLOptions.CipherList && *Conf_SSLOptions.CipherList) {
309                 if(SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0 ) {
310                         Log(LOG_ERR,
311                             "Failed to apply SSL cipher list \"%s\"!",
312                             Conf_SSLOptions.CipherList);
313                         goto out;
314                 } else {
315                         Log(LOG_INFO,
316                             "Successfully applied SSL cipher list: \"%s\".",
317                             Conf_SSLOptions.CipherList);
318                 }
319         }
320
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         if(Conf_SSLOptions.CipherList != NULL) {
345                 Log(LOG_ERR,
346                     "Failed to apply SSL cipher list \"%s\": Not implemented for GnuTLS!",
347                     Conf_SSLOptions.CipherList);
348                 array_free(&Conf_SSLOptions.ListenPorts);
349                 return false;
350         }
351
352         err = gnutls_global_init();
353         if (err) {
354                 Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
355                     gnutls_strerror(err));
356                 array_free(&Conf_SSLOptions.ListenPorts);
357                 return false;
358         }
359         if (!ConnSSL_LoadServerKey_gnutls()) {
360                 array_free(&Conf_SSLOptions.ListenPorts);
361                 return false;
362         }
363
364         Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
365         initialized = true;
366         return true;
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_set_default_priority(c->ssl_state.gnutls_session);
493         if (ret != 0) {
494                 Log(LOG_ERR, "Failed to set GnuTLS default priority: %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_sha1(), 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) != GNUTLS_CRT_X509)
734                 return 0;
735
736         if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
737                 return 0;
738
739         cert_list_size = 0;
740         cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
741                                                  &cert_list_size);
742         if (!cert_list) {
743                 gnutls_x509_crt_deinit(cert);
744                 return 0;
745         }
746         
747         if (gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
748                 gnutls_x509_crt_deinit(cert);
749                 return 0;
750         }
751
752         digest_size = sizeof(digest);
753         if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, digest, &digest_size)) {
754                 gnutls_x509_crt_deinit(cert);
755                 return 0;
756         }
757
758         gnutls_x509_crt_deinit(cert);
759 #endif /* HAVE_LIBGNUTLS */
760
761         assert(c->ssl_state.fingerprint == NULL);
762
763         c->ssl_state.fingerprint = malloc(SHA1_STRING_LEN);
764         if (!c->ssl_state.fingerprint)
765                 return 0;
766
767         for (i = 0; i < (int)digest_size; i++) {
768                 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
769                 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
770         }
771         c->ssl_state.fingerprint[i * 2] = '\0';
772
773         return 1;
774 }
775
776 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
777 static int
778 ConnectAccept( CONNECTION *c, bool connect)
779 {
780         int ret;
781 #ifdef HAVE_LIBSSL
782         SSL *ssl = c->ssl_state.ssl;
783         assert(ssl != NULL);
784
785         ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
786         if (1 != ret)
787                 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
788 #endif
789 #ifdef HAVE_LIBGNUTLS
790         (void) connect;
791         ret = gnutls_handshake(c->ssl_state.gnutls_session);
792         if (ret)
793                 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
794 #endif /* _GNUTLS */
795         (void)ConnSSL_InitCertFp(c);
796
797         Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
798         ConnSSL_LogCertInfo(c);
799
800         Conn_StartLogin(CONNECTION2ID(c));
801         return 1;
802 }
803
804
805 ssize_t
806 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
807 {
808         ssize_t bw;
809
810         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
811
812         assert(count > 0);
813 #ifdef HAVE_LIBSSL
814         bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
815 #endif
816 #ifdef HAVE_LIBGNUTLS
817         bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
818 #endif
819         if (bw > 0)
820                 return bw;
821         if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
822                 errno = EAGAIN; /* try again */
823         return -1;
824 }
825
826
827 ssize_t
828 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
829 {
830         ssize_t br;
831
832         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
833 #ifdef HAVE_LIBSSL
834         br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
835         if (br > 0)     /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
836                 return br;
837 #endif
838 #ifdef HAVE_LIBGNUTLS
839         br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
840         if (br >= 0)    /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
841                 return br;
842 #endif
843         /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
844         if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
845                 errno = EAGAIN;
846                 return -1;
847         }
848         return 0;
849 }
850
851
852 bool
853 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
854 {
855 #ifdef HAVE_LIBSSL
856         char *nl;
857         SSL *ssl = c->ssl_state.ssl;
858
859         if (!ssl)
860                 return false;
861         *buf = 0;
862         SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
863         nl = strchr(buf, '\n');
864         if (nl)
865                 *nl = 0;
866         return true;
867 #endif
868 #ifdef HAVE_LIBGNUTLS
869         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
870                 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
871                 unsigned keysize;
872
873                 gnutls_session_t sess = c->ssl_state.gnutls_session;
874                 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
875                 name_cipher = gnutls_cipher_get_name(cipher);
876                 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
877                 keysize = gnutls_cipher_get_key_size(cipher) * 8;
878                 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
879                 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
880
881                 return snprintf(buf, len, "%s-%s%15s Kx=%s      Enc=%s(%u) Mac=%s",
882                         name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
883         }
884         return false;
885 #endif
886 }
887
888 char *
889 ConnSSL_GetCertFp(CONNECTION *c)
890 {
891         return c->ssl_state.fingerprint;
892 }
893
894 bool
895 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
896 {
897         assert (c != NULL);
898         c->ssl_state.fingerprint = strndup(fingerprint, SHA1_STRING_LEN - 1);
899         return c->ssl_state.fingerprint != NULL;
900 }
901 #else
902
903 bool
904 ConnSSL_InitLibrary(void)
905 {
906         return true;
907 }
908
909 #endif /* SSL_SUPPORT */
910 /* -eof- */
911
912