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