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