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