]> arthur.barton.de Git - ngircd.git/blob - src/ngircd/conn-ssl.c
5011628874a4ee5cad3ba393b002e3fa285232d1
[ngircd.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  * Copyright (c)2008-2014 Alexander Barton (alex@barton.de) and Contributors.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * Please read the file COPYING, README and AUTHORS for more information.
11  */
12
13 #include "portab.h"
14
15 /**
16  * @file
17  * SSL wrapper functions
18  */
19
20 #include "conf-ssl.h"
21
22 #ifdef SSL_SUPPORT
23
24 #include "io.h"
25 #include <assert.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <errno.h>
30
31 #define CONN_MODULE
32 #include "conn.h"
33 #include "conf.h"
34 #include "conn-func.h"
35 #include "conn-ssl.h"
36 #include "log.h"
37
38 #include "defines.h"
39
40 extern struct SSLOptions Conf_SSLOptions;
41
42 #ifdef HAVE_LIBSSL
43 #include <openssl/err.h>
44 #include <openssl/rand.h>
45 #include <openssl/dh.h>
46 #include <openssl/x509v3.h>
47
48 #define MAX_CERT_CHAIN_LENGTH   10      /* XXX: do not hardcode */
49
50 static SSL_CTX * ssl_ctx;
51 static DH *dh_params;
52
53 static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
54 static bool ConnSSL_SetVerifyProperties_openssl PARAMS((SSL_CTX * c));
55 #endif
56
57 #ifdef HAVE_LIBGNUTLS
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <fcntl.h>
61 #include <unistd.h>
62 #include <gnutls/x509.h>
63
64 #define DH_BITS 2048
65 #define DH_BITS_MIN 1024
66
67 #define MAX_HASH_SIZE   64      /* from gnutls-int.h */
68
69 typedef struct {
70         int refcnt;
71         gnutls_certificate_credentials_t x509_cred;
72         gnutls_dh_params_t dh_params;
73 } x509_cred_slot;
74
75 static array x509_creds = INIT_ARRAY;
76 static size_t x509_cred_idx;
77
78 static gnutls_dh_params_t dh_params;
79 static gnutls_priority_t priorities_cache = NULL;
80 static bool ConnSSL_LoadServerKey_gnutls PARAMS(( void ));
81 static bool ConnSSL_SetVerifyProperties_gnutls PARAMS((void));
82 #endif
83
84 #define SHA256_STRING_LEN       (32 * 2 + 1)
85
86 static bool ConnSSL_Init_SSL PARAMS(( CONNECTION *c ));
87 static int ConnectAccept PARAMS(( CONNECTION *c, bool connect ));
88 static int ConnSSL_HandleError PARAMS(( CONNECTION *c, const int code, const char *fname ));
89
90 #ifdef HAVE_LIBGNUTLS
91 static char * openreadclose(const char *name, size_t *len)
92 {
93         char *buf = NULL;
94         struct stat s;
95         ssize_t br;
96         int fd = open(name, O_RDONLY);
97         if (fd < 0) {
98                 Log(LOG_ERR, "Could not open %s: %s", name, strerror(errno));
99                 return NULL;
100         }
101         if (fstat(fd, &s)) {
102                 Log(LOG_ERR, "Could not fstat %s: %s", name, strerror(errno));
103                 goto out;
104         }
105         if (!S_ISREG(s.st_mode)) {
106                 Log(LOG_ERR, "%s: Not a regular file", name);
107                 goto out;
108         }
109         if (s.st_size <= 0) {
110                 Log(LOG_ERR, "%s: invalid file length (size %ld <= 0)", name, (long) s.st_size);
111                 goto out;
112         }
113         buf = malloc(s.st_size);
114         if (!buf) {
115                 Log(LOG_ERR, "Could not malloc %lu bytes for file %s: %s", s.st_size, name, strerror(errno));
116                 goto out;
117         }
118         br = read(fd, buf, s.st_size);
119         if (br != (ssize_t)s.st_size) {
120                 Log(LOG_ERR, "Could not read file %s: read returned %ld, expected %ld: %s",
121                         name, (long) br, (long) s.st_size, br == -1 ? strerror(errno):"short read?!");
122                 memset(buf, 0, s.st_size);
123                 free(buf);
124                 buf = NULL;
125         } else {
126                 *len = br;
127         }
128 out:
129         close(fd);
130         return buf;
131 }
132 #endif
133
134
135 #ifdef HAVE_LIBSSL
136 /**
137  * Log OpenSSL error message.
138  *
139  * @param level The log level
140  * @param msg The error message.
141  * @param info Additional information text or NULL.
142  */
143 static void
144 LogOpenSSL_CertInfo(int level, X509 * cert, const char *msg)
145 {
146         BIO *mem;
147         char *memptr;
148         long len;
149
150         assert(cert);
151         assert(msg);
152
153         if (!cert)
154                 return;
155         mem = BIO_new(BIO_s_mem());
156         if (!mem)
157                 return;
158         X509_NAME_print_ex(mem, X509_get_subject_name(cert), 0,
159                            XN_FLAG_ONELINE);
160         X509_NAME_print_ex(mem, X509_get_issuer_name(cert), 2, XN_FLAG_ONELINE);
161         if (BIO_write(mem, "", 1) == 1) {
162                 len = BIO_get_mem_data(mem, &memptr);
163                 if (memptr && len > 0)
164                         Log(level, "%s: \"%s\".", msg, memptr);
165         }
166         (void)BIO_set_close(mem, BIO_CLOSE);
167         BIO_free(mem);
168 }
169
170 static void
171 LogOpenSSLError(const char *error, const char *info)
172 {
173         unsigned long err = ERR_get_error();
174         char * errmsg = err
175                 ? ERR_error_string(err, NULL)
176                 : "Unable to determine error";
177
178         assert(error != NULL);
179
180         if (info)
181                 Log(LOG_ERR, "%s: %s (%s)", error, info, errmsg);
182         else
183                 Log(LOG_ERR, "%s: %s", error, errmsg);
184 }
185
186
187 static int
188 pem_passwd_cb(char *buf, int size, int rwflag, void *password)
189 {
190         array *pass = password;
191         int passlen;
192
193         (void)rwflag;           /* rwflag is unused if DEBUG is not set. */
194         assert(rwflag == 0);    /* 0 -> callback used for decryption.
195                                  * See SSL_CTX_set_default_passwd_cb(3) */
196
197         passlen = (int) array_bytes(pass);
198
199         LogDebug("pem_passwd_cb buf size %d, array size %d", size, passlen);
200         assert(passlen >= 0);
201         if (passlen <= 0) {
202                 Log(LOG_ERR, "PEM password required but not set [in pem_passwd_cb()]!");
203                 return 0;
204         }
205         size = passlen > size ? size : passlen;
206         memcpy(buf, (char *)(array_start(pass)), size);
207         return size;
208 }
209
210
211 static int
212 Verify_openssl(int preverify_ok, X509_STORE_CTX * ctx)
213 {
214 #ifdef DEBUG
215         if (!preverify_ok) {
216                 int err = X509_STORE_CTX_get_error(ctx);
217                 LogDebug("Certificate validation failed: %s",
218                          X509_verify_cert_error_string(err));
219         }
220 #else
221         (void)preverify_ok;
222         (void)ctx;
223 #endif
224
225         /* Always(!) return success as we have to deal with invalid
226          * (self-signed, expired, ...) client certificates and with invalid
227          * server certificates when "SSLVerify" is disabled, which we don't
228          * know at this stage. Therefore we postpone this check, it will be
229          * (and has to be!) handled in cb_connserver_login_ssl(). */
230         return 1;
231 }
232 #endif
233
234
235 static bool
236 Load_DH_params(void)
237 {
238 #ifdef HAVE_LIBSSL
239         FILE *fp;
240         bool ret = true;
241
242         if (!Conf_SSLOptions.DHFile) {
243                 Log(LOG_NOTICE, "Configuration option \"DHFile\" not set!");
244                 return false;
245         }
246         fp = fopen(Conf_SSLOptions.DHFile, "r");
247         if (!fp) {
248                 Log(LOG_ERR, "%s: %s", Conf_SSLOptions.DHFile, strerror(errno));
249                 return false;
250         }
251         dh_params = PEM_read_DHparams(fp, NULL, NULL, NULL);
252         if (!dh_params) {
253                 Log(LOG_ERR, "%s: Failed to read SSL DH parameters!",
254                     Conf_SSLOptions.DHFile);
255                 ret = false;
256         }
257         fclose(fp);
258         return ret;
259 #endif
260 #ifdef HAVE_LIBGNUTLS
261         bool need_dhgenerate = true;
262         int err;
263         gnutls_dh_params_t tmp_dh_params;
264
265         err = gnutls_dh_params_init(&tmp_dh_params);
266         if (err < 0) {
267                 Log(LOG_ERR, "Failed to initialize SSL DH parameters: %s",
268                     gnutls_strerror(err));
269                 return false;
270         }
271         if (Conf_SSLOptions.DHFile) {
272                 gnutls_datum_t dhparms;
273                 size_t size;
274                 dhparms.data = (unsigned char *) openreadclose(Conf_SSLOptions.DHFile, &size);
275                 if (dhparms.data) {
276                         dhparms.size = size;
277                         err = gnutls_dh_params_import_pkcs3(tmp_dh_params, &dhparms, GNUTLS_X509_FMT_PEM);
278                         if (err == 0)
279                                 need_dhgenerate = false;
280                         else
281                                 Log(LOG_ERR,
282                                     "Failed to initialize SSL DH parameters: %s",
283                                     gnutls_strerror(err));
284
285                         memset(dhparms.data, 0, size);
286                         free(dhparms.data);
287                 }
288         }
289         if (need_dhgenerate) {
290                 Log(LOG_WARNING,
291                     "DHFile not set, generating %u bit DH parameters. This may take a while ...",
292                     DH_BITS);
293                 err = gnutls_dh_params_generate2(tmp_dh_params, DH_BITS);
294                 if (err < 0) {
295                         Log(LOG_ERR, "Failed to generate SSL DH parameters: %s",
296                             gnutls_strerror(err));
297                         return false;
298                 }
299         }
300         dh_params = tmp_dh_params;
301         return true;
302 #endif
303 }
304
305
306 void ConnSSL_Free(CONNECTION *c)
307 {
308 #ifdef HAVE_LIBSSL
309         SSL *ssl = c->ssl_state.ssl;
310         if (ssl) {
311                 SSL_shutdown(ssl);
312                 SSL_free(ssl);
313                 c->ssl_state.ssl = NULL;
314                 if (c->ssl_state.fingerprint) {
315                         free(c->ssl_state.fingerprint);
316                         c->ssl_state.fingerprint = NULL;
317                 }
318         }
319 #endif
320 #ifdef HAVE_LIBGNUTLS
321         gnutls_session_t sess = c->ssl_state.gnutls_session;
322         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
323                 gnutls_bye(sess, GNUTLS_SHUT_RDWR);
324                 gnutls_deinit(sess);
325         }
326         x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), c->ssl_state.x509_cred_idx);
327         assert(slot != NULL);
328         assert(slot->refcnt > 0);
329         assert(slot->x509_cred != NULL);
330         slot->refcnt--;
331         if ((c->ssl_state.x509_cred_idx != x509_cred_idx) && (slot->refcnt <= 0)) {
332                 LogDebug("Discarding X509 certificate credentials from slot %zd.",
333                          c->ssl_state.x509_cred_idx);
334                 gnutls_certificate_free_keys(slot->x509_cred);
335                 gnutls_certificate_free_credentials(slot->x509_cred);
336                 slot->x509_cred = NULL;
337                 gnutls_dh_params_deinit(slot->dh_params);
338                 slot->dh_params = NULL;
339                 slot->refcnt = 0;
340         }
341 #endif
342         assert(Conn_OPTION_ISSET(c, CONN_SSL));
343         /* can't just set bitmask to 0 -- there are other, non-ssl related flags, e.g. CONN_ZIP. */
344         Conn_OPTION_DEL(c, CONN_SSL_FLAGS_ALL);
345 }
346
347
348 bool
349 ConnSSL_InitLibrary( void )
350 {
351         if (!Conf_SSLInUse()) {
352                 LogDebug("SSL not in use, skipping initialization.");
353                 return true;
354         }
355
356 #ifdef HAVE_LIBSSL
357         SSL_CTX *newctx;
358
359 #if OPENSSL_API_COMPAT < 0x10100000L
360         if (!ssl_ctx) {
361                 SSL_library_init();
362                 SSL_load_error_strings();
363         }
364 #endif
365
366         if (!RAND_status()) {
367                 Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
368                 /*
369                  * it is probably best to fail and let the user install EGD or
370                  * a similar program if no kernel random device is available.
371                  * According to OpenSSL RAND_egd(3): "The automatic query of
372                  * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
373                  * so it makes little sense to deal with PRNGD seeding ourselves.
374                  */
375                 array_free(&Conf_SSLOptions.ListenPorts);
376                 return false;
377         }
378
379         newctx = SSL_CTX_new(SSLv23_method());
380         if (!newctx) {
381                 LogOpenSSLError("Failed to create SSL context", NULL);
382                 array_free(&Conf_SSLOptions.ListenPorts);
383                 return false;
384         }
385
386         if (!ConnSSL_LoadServerKey_openssl(newctx)) {
387                 /* Failed to read new key but an old ssl context
388                  * already exists -> reuse old context */
389                 if (ssl_ctx) {
390                         SSL_CTX_free(newctx);
391                         Log(LOG_WARNING,
392                         "Re-Initializing of SSL failed, using old keys!");
393                         return true;
394                 }
395                 /* No preexisting old context -> error. */
396                 goto out;
397         }
398
399         if (SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0) {
400                 Log(LOG_ERR, "Failed to apply OpenSSL cipher list \"%s\"!",
401                     Conf_SSLOptions.CipherList);
402                 goto out;
403         }
404
405         SSL_CTX_set_session_id_context(newctx, (unsigned char *)"ngircd", 6);
406         if (!ConnSSL_SetVerifyProperties_openssl(newctx))
407                 goto out;
408         SSL_CTX_set_options(newctx,
409                             SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2 |
410                             SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
411                             SSL_OP_NO_COMPRESSION);
412         SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
413         SSL_CTX_free(ssl_ctx);
414         ssl_ctx = newctx;
415         Log(LOG_INFO, "%s initialized.", OpenSSL_version(OPENSSL_VERSION));
416         return true;
417 out:
418         SSL_CTX_free(newctx);
419         array_free(&Conf_SSLOptions.ListenPorts);
420         return false;
421 #endif
422 #ifdef HAVE_LIBGNUTLS
423         int err;
424         static bool initialized;
425
426         if (!initialized) {
427                 err = gnutls_global_init();
428                 if (err) {
429                         Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
430                             gnutls_strerror(err));
431                         goto out;
432                 }
433         }
434
435         if (!ConnSSL_LoadServerKey_gnutls())
436                 goto out;
437
438         if (priorities_cache != NULL) {
439                 gnutls_priority_deinit(priorities_cache);
440         }
441         if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
442                                  NULL) != GNUTLS_E_SUCCESS) {
443                 Log(LOG_ERR,
444                     "Failed to apply GnuTLS cipher list \"%s\"!",
445                     Conf_SSLOptions.CipherList);
446                 goto out;
447         }
448
449         if (!ConnSSL_SetVerifyProperties_gnutls())
450                 goto out;
451
452         Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
453         initialized = true;
454         return true;
455 out:
456         array_free(&Conf_SSLOptions.ListenPorts);
457         return false;
458 #endif
459 }
460
461
462 #ifdef HAVE_LIBGNUTLS
463 static bool
464 ConnSSL_SetVerifyProperties_gnutls(void)
465 {
466         int err;
467
468         if (!Conf_SSLOptions.CAFile)
469                 return true;
470
471         err = gnutls_certificate_set_x509_trust_file(x509_cred,
472                                                      Conf_SSLOptions.CAFile,
473                                                      GNUTLS_X509_FMT_PEM);
474         if (err < 0) {
475                 Log(LOG_ERR, "Failed to load x509 trust file %s: %s",
476                     Conf_SSLOptions.CAFile, gnutls_strerror(err));
477                 return false;
478         }
479         if (Conf_SSLOptions.CRLFile) {
480                 err =
481                     gnutls_certificate_set_x509_crl_file(x509_cred,
482                                                          Conf_SSLOptions.CRLFile,
483                                                          GNUTLS_X509_FMT_PEM);
484                 if (err < 0) {
485                         Log(LOG_ERR, "Failed to load x509 crl file %s: %s",
486                             Conf_SSLOptions.CRLFile, gnutls_strerror(err));
487                         return false;
488                 }
489         }
490         return true;
491 }
492
493
494 static bool
495 ConnSSL_LoadServerKey_gnutls(void)
496 {
497         int err;
498         const char *cert_file;
499
500         x509_cred_slot *slot = NULL;
501         gnutls_certificate_credentials_t x509_cred;
502
503         err = gnutls_certificate_allocate_credentials(&x509_cred);
504         if (err < 0) {
505                 Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
506                     gnutls_strerror(err));
507                 return false;
508         }
509
510         if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
511                 Log(LOG_WARNING,
512                     "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
513
514         if (!Load_DH_params())
515                 return false;
516
517         gnutls_certificate_set_dh_params(x509_cred, dh_params);
518
519         cert_file = Conf_SSLOptions.CertFile ?
520                         Conf_SSLOptions.CertFile : Conf_SSLOptions.KeyFile;
521         if (Conf_SSLOptions.KeyFile) {
522                 err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file,
523                                                            Conf_SSLOptions.KeyFile,
524                                                            GNUTLS_X509_FMT_PEM);
525                 if (err < 0) {
526                         Log(LOG_ERR,
527                             "Failed to set certificate key file (cert %s, key %s): %s",
528                             cert_file,
529                             Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
530                             gnutls_strerror(err));
531                         return false;
532                 }
533         }
534
535         /* Free currently active x509 context (if any) unless it is still in use */
536         slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
537         if ((slot != NULL) && (slot->refcnt <= 0) && (slot->x509_cred != NULL)) {
538                 LogDebug("Discarding X509 certificate credentials from slot %zd.",
539                          x509_cred_idx);
540                 gnutls_certificate_free_keys(slot->x509_cred);
541                 gnutls_certificate_free_credentials(slot->x509_cred);
542                 slot->x509_cred = NULL;
543                 gnutls_dh_params_deinit(slot->dh_params);
544                 slot->dh_params = NULL;
545                 slot->refcnt = 0;
546         }
547
548         /* Find free slot */
549         x509_cred_idx = (size_t) -1;
550         size_t i;
551         for (slot = array_start(&x509_creds), i = 0;
552              i < array_length(&x509_creds, sizeof(x509_cred_slot));
553              slot++, i++) {
554                 if (slot->refcnt <= 0) {
555                         x509_cred_idx = i;
556                         break;
557                 }
558         }
559         /* ... allocate new slot otherwise. */
560         if (x509_cred_idx == (size_t) -1) {
561                 x509_cred_idx = array_length(&x509_creds, sizeof(x509_cred_slot));
562                 slot = array_alloc(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
563                 if (slot == NULL) {
564                         Log(LOG_ERR, "Failed to allocate new slot for certificate credentials");
565                         return false;
566                 }
567         }
568         Log(LOG_INFO, "Storing new X509 certificate credentials in slot %zd.", x509_cred_idx);
569         slot->x509_cred = x509_cred;
570         slot->refcnt = 0;
571
572         return true;
573 }
574 #endif
575
576
577 #ifdef HAVE_LIBSSL
578 static bool
579 ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
580 {
581         char *cert_key;
582
583         assert(ctx);
584         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
585         SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
586
587         if (!Conf_SSLOptions.KeyFile)
588                 return true;
589
590         if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
591                 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
592                 LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
593                 return false;
594         }
595
596         cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
597         if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
598                 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
599                 LogOpenSSLError("Failed to load certificate chain", cert_key);
600                 return false;
601         }
602
603         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
604
605         if (!SSL_CTX_check_private_key(ctx)) {
606                 LogOpenSSLError("Server private key does not match certificate", NULL);
607                 return false;
608         }
609         if (Load_DH_params()) {
610                 if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
611                         LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
612                 /* don't return false here: the non-DH modes will still work */
613                 DH_free(dh_params);
614                 dh_params = NULL;
615         }
616         return true;
617 }
618
619
620 static bool
621 ConnSSL_SetVerifyProperties_openssl(SSL_CTX * ctx)
622 {
623         X509_STORE *store = NULL;
624         X509_LOOKUP *lookup;
625         bool ret = false;
626
627         if (!Conf_SSLOptions.CAFile)
628                 return true;
629
630         if (SSL_CTX_load_verify_locations(ctx, Conf_SSLOptions.CAFile, NULL) !=
631             1) {
632                 LogOpenSSLError("SSL_CTX_load_verify_locations", NULL);
633                 goto out;
634         }
635
636         if (Conf_SSLOptions.CRLFile) {
637                 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
638                 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
639                 SSL_CTX_set1_param(ctx, param);
640
641                 store = SSL_CTX_get_cert_store(ctx);
642                 assert(store);
643                 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
644                 if (!lookup) {
645                         LogOpenSSLError("X509_STORE_add_lookup",
646                                         Conf_SSLOptions.CRLFile);
647                         goto out;
648                 }
649
650                 if (X509_load_crl_file
651                     (lookup, Conf_SSLOptions.CRLFile, X509_FILETYPE_PEM) != 1) {
652                         LogOpenSSLError("X509_load_crl_file",
653                                         Conf_SSLOptions.CRLFile);
654                         goto out;
655                 }
656         }
657
658         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
659                            Verify_openssl);
660         SSL_CTX_set_verify_depth(ctx, MAX_CERT_CHAIN_LENGTH);
661         ret = true;
662 out:
663         if (Conf_SSLOptions.CRLFile)
664                 free(Conf_SSLOptions.CRLFile);
665         Conf_SSLOptions.CRLFile = NULL;
666         return ret;
667 }
668
669
670 #endif
671 static bool
672 ConnSSL_Init_SSL(CONNECTION *c)
673 {
674         int ret;
675
676         LogDebug("Initializing SSL ...");
677         assert(c != NULL);
678
679 #ifdef HAVE_LIBSSL
680         if (!ssl_ctx) {
681                 Log(LOG_ERR,
682                     "Can't initialize SSL context, OpenSSL initialization failed at startup!");
683                 return false;
684         }
685         assert(c->ssl_state.ssl == NULL);
686         assert(c->ssl_state.fingerprint == NULL);
687
688         c->ssl_state.ssl = SSL_new(ssl_ctx);
689         if (!c->ssl_state.ssl) {
690                 LogOpenSSLError("Failed to create SSL structure", NULL);
691                 return false;
692         }
693         Conn_OPTION_ADD(c, CONN_SSL);
694
695         ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
696         if (ret != 1) {
697                 LogOpenSSLError("Failed to set SSL file descriptor", NULL);
698                 ConnSSL_Free(c);
699                 return false;
700         }
701 #endif
702 #ifdef HAVE_LIBGNUTLS
703         Conn_OPTION_ADD(c, CONN_SSL);
704         ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
705         if (ret != GNUTLS_E_SUCCESS) {
706                 Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
707                     gnutls_strerror(ret));
708                 ConnSSL_Free(c);
709                 return false;
710         }
711         /*
712          * The intermediate (long) cast is here to avoid a warning like:
713          * "cast to pointer from integer of different size" on 64-bit platforms.
714          * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
715          * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
716          */
717         gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
718                                  (gnutls_transport_ptr_t) (long) c->sock);
719         gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
720                                               GNUTLS_CERT_REQUEST);
721
722         LogDebug("Using X509 credentials from slot %zd.", x509_cred_idx);
723         c->ssl_state.x509_cred_idx = x509_cred_idx;
724         x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
725         slot->refcnt++;
726         ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
727                                      GNUTLS_CRD_CERTIFICATE, slot->x509_cred);
728         if (ret != 0) {
729                 Log(LOG_ERR, "Failed to set SSL credentials: %s",
730                     gnutls_strerror(ret));
731                 ConnSSL_Free(c);
732                 return false;
733         }
734         gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
735 #endif
736         return true;
737 }
738
739
740 bool
741 ConnSSL_PrepareConnect(CONNECTION * c, CONF_SERVER * s)
742 {
743         bool ret;
744 #ifdef HAVE_LIBGNUTLS
745         int err;
746
747         err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
748         if (err) {
749                 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
750                     gnutls_strerror(err));
751                 return false;
752         }
753 #endif
754         ret = ConnSSL_Init_SSL(c);
755         if (!ret)
756                 return false;
757         Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
758
759 #ifdef HAVE_LIBSSL
760         assert(c->ssl_state.ssl);
761
762         X509_VERIFY_PARAM *param = SSL_get0_param(c->ssl_state.ssl);
763         X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
764         int err = X509_VERIFY_PARAM_set1_host(param, s->host, 0);
765         if (err != 1) {
766                 Log(LOG_ERR,
767                     "Cannot set up hostname verification for '%s': %u",
768                     s->host, err);
769                 return false;
770         }
771
772         if (s->SSLVerify)
773                 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_PEER,
774                                Verify_openssl);
775         else
776                 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
777 #endif
778
779         return true;
780 }
781
782
783 /**
784  * Check and handle error return codes after failed calls to SSL functions.
785  *
786  * OpenSSL:
787  * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
788  * SSL_write() on ssl.
789  *
790  * GnuTLS:
791  * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
792  *
793  * @param c The connection handle.
794  * @prarm code The return code.
795  * @param fname The name of the function in which the error occurred.
796  * @return -1 on fatal errors, 0 if we can try again later.
797  */
798 static int
799 ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
800 {
801 #ifdef HAVE_LIBSSL
802         int ret = SSL_ERROR_SYSCALL;
803         unsigned long sslerr;
804         int real_errno = errno;
805
806         ret = SSL_get_error(c->ssl_state.ssl, code);
807
808         switch (ret) {
809         case SSL_ERROR_WANT_READ:
810                 io_event_del(c->sock, IO_WANTWRITE);
811                 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
812                 return 0;       /* try again later */
813         case SSL_ERROR_WANT_WRITE:
814                 io_event_del(c->sock, IO_WANTREAD);
815                 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
816         case SSL_ERROR_NONE:
817                 return 0;       /* try again later */
818         case SSL_ERROR_ZERO_RETURN:
819                 LogDebug("SSL connection shut down normally.");
820                 break;
821         case SSL_ERROR_SYSCALL:
822                 /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
823                  * and SSL_ERROR_WANT_X509_LOOKUP */
824                 sslerr = ERR_get_error();
825                 if (sslerr) {
826                         Log(LOG_ERR, "SSL error: %s [in %s()]!",
827                             ERR_error_string(sslerr, NULL), fname);
828                 } else {
829                         switch (code) { /* EOF that violated protocol */
830                         case 0:
831                                 Log(LOG_ERR,
832                                     "SSL error, client disconnected [in %s()]!",
833                                     fname);
834                                 break;
835                         case -1:
836                                 /* Low level socket I/O error, check errno. But
837                                  * we don't need to log this here, the generic
838                                  * connection layer will take care of it. */
839                                 LogDebug("SSL error: %s [in %s()]!",
840                                          strerror(real_errno), fname);
841                         }
842                 }
843                 break;
844         case SSL_ERROR_SSL:
845                 LogOpenSSLError("SSL protocol error", fname);
846                 break;
847         default:
848                 Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
849         }
850         ConnSSL_Free(c);
851         return -1;
852 #endif
853 #ifdef HAVE_LIBGNUTLS
854         switch (code) {
855         case GNUTLS_E_AGAIN:
856         case GNUTLS_E_INTERRUPTED:
857                 if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
858                         Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
859                         io_event_del(c->sock, IO_WANTREAD);
860                 } else {
861                         Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
862                         io_event_del(c->sock, IO_WANTWRITE);
863                 }
864                 break;
865         default:
866                 assert(code < 0);
867                 if (gnutls_error_is_fatal(code)) {
868                         Log(LOG_ERR, "SSL error: %s [%s].",
869                             gnutls_strerror(code), fname);
870                         ConnSSL_Free(c);
871                         return -1;
872                 }
873         }
874         return 0;
875 #endif
876 }
877
878
879 #ifdef HAVE_LIBGNUTLS
880 static void *
881 LogMalloc(size_t s)
882 {
883         void *mem = malloc(s);
884         if (!mem)
885                 Log(LOG_ERR, "Out of memory: Could not allocate %lu byte",
886                     (unsigned long)s);
887         return mem;
888 }
889
890
891 static void
892 LogGnuTLS_CertInfo(int level, gnutls_x509_crt_t cert, const char *msg)
893 {
894         char *dn, *issuer_dn;
895         size_t size = 0;
896         int err = gnutls_x509_crt_get_dn(cert, NULL, &size);
897         if (size == 0) {
898                 Log(LOG_ERR, "gnutls_x509_crt_get_dn: size == 0");
899                 return;
900         }
901         if (err && err != GNUTLS_E_SHORT_MEMORY_BUFFER)
902                 goto err_crt_get;
903         dn = LogMalloc(size);
904         if (!dn)
905                 return;
906         err = gnutls_x509_crt_get_dn(cert, dn, &size);
907         if (err)
908                 goto err_crt_get;
909         gnutls_x509_crt_get_issuer_dn(cert, NULL, &size);
910         assert(size);
911         issuer_dn = LogMalloc(size);
912         if (!issuer_dn) {
913                 Log(level, "%s: Distinguished Name: %s", msg, dn);
914                 free(dn);
915                 return;
916         }
917         gnutls_x509_crt_get_issuer_dn(cert, issuer_dn, &size);
918         Log(level, "%s: Distinguished Name: \"%s\", Issuer \"%s\"", msg, dn,
919             issuer_dn);
920         free(dn);
921         free(issuer_dn);
922         return;
923
924       err_crt_get:
925         Log(LOG_ERR, "gnutls_x509_crt_get_dn: %s", gnutls_strerror(err));
926         return;
927 }
928 #endif
929
930
931 static void
932 ConnSSL_LogCertInfo( CONNECTION * c, bool connect)
933 {
934         bool cert_seen = false, cert_ok = false;
935         char msg[128];
936 #ifdef HAVE_LIBSSL
937         const char *comp_alg = "no compression";
938         const void *comp;
939         X509 *peer_cert = NULL;
940         SSL *ssl = c->ssl_state.ssl;
941
942         assert(ssl);
943
944         comp = SSL_get_current_compression(ssl);
945         if (comp)
946                 comp_alg = SSL_COMP_get_name(comp);
947         Log(LOG_INFO, "Connection %d: initialized %s using cipher %s, %s.",
948             c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl), comp_alg);
949         peer_cert = SSL_get_peer_certificate(ssl);
950         if (peer_cert) {
951                 cert_seen = true;
952
953                 if (connect) {
954                         /* Outgoing connection. Verify the remote server! */
955                         int err = SSL_get_verify_result(ssl);
956                         if (err == X509_V_OK) {
957                                 const char *peername = SSL_get0_peername(ssl);
958                                 if (peername != NULL)
959                                         cert_ok = true;
960                                 LogDebug("X509_V_OK, peername = '%s'", peername);
961                         } else
962                                 Log(LOG_WARNING, "Certificate validation failed: %s!",
963                                     X509_verify_cert_error_string(err));
964
965                         snprintf(msg, sizeof(msg), "Got %svalid server certificate",
966                                  cert_ok ? "" : "in");
967                         LogOpenSSL_CertInfo(LOG_INFO, peer_cert, msg);
968                 } else {
969                         /* Incoming connection.
970                          * Accept all certificates, don't depend on their
971                          * validity: for example, we don't know the hostname
972                          * to check, because we not yet even know if this is a
973                          * server connection at all and if so, which one, so we
974                          * don't know a host name to look for. On the other
975                          * hand we want client certificates, for example for
976                          * "CertFP" authentication with services ... */
977                         LogOpenSSL_CertInfo(LOG_INFO, peer_cert,
978                                             "Got unchecked client certificate");
979                 }
980
981                 X509_free(peer_cert);
982         }
983 #endif
984 #ifdef HAVE_LIBGNUTLS
985         unsigned int status;
986         gnutls_credentials_type_t cred;
987         gnutls_session_t sess = c->ssl_state.gnutls_session;
988         gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
989
990         Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
991             c->sock,
992             gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
993             gnutls_cipher_get_name(cipher),
994             gnutls_mac_get_name(gnutls_mac_get(sess)));
995         cred = gnutls_auth_get_type(c->ssl_state.gnutls_session);
996         if (cred == GNUTLS_CRD_CERTIFICATE && connect) {
997                 cert_seen = true;
998                 int verify =
999                     gnutls_certificate_verify_peers2(c->
1000                                                      ssl_state.gnutls_session,
1001                                                      &status);
1002                 if (verify < 0) {
1003                         Log(LOG_ERR,
1004                             "gnutls_certificate_verify_peers2 failed: %s",
1005                             gnutls_strerror(verify));
1006                         goto done_cn_validation;
1007                 } else if (status) {
1008                         gnutls_datum_t out;
1009
1010                         if (gnutls_certificate_verification_status_print
1011                             (status, gnutls_certificate_type_get(sess), &out,
1012                              0) == GNUTLS_E_SUCCESS) {
1013                                 Log(LOG_ERR,
1014                                     "Certificate validation failed: %s",
1015                                     out.data);
1016                                 gnutls_free(out.data);
1017                         }
1018                 }
1019
1020                 gnutls_x509_crt_t cert;
1021                 unsigned cert_list_size;
1022                 const gnutls_datum_t *cert_list =
1023                     gnutls_certificate_get_peers(sess, &cert_list_size);
1024                 if (!cert_list || cert_list_size == 0) {
1025                         Log(LOG_ERR, "No certificates found");
1026                         goto done_cn_validation;
1027                 }
1028                 int err = gnutls_x509_crt_init(&cert);
1029                 if (err < 0) {
1030                         Log(LOG_ERR,
1031                             "Failed to initialize x509 certificate: %s",
1032                             gnutls_strerror(err));
1033                         goto done_cn_validation;
1034                 }
1035                 err = gnutls_x509_crt_import(cert, cert_list,
1036                                            GNUTLS_X509_FMT_DER);
1037                 if (err < 0) {
1038                         Log(LOG_ERR, "Failed to parse the certificate: %s",
1039                             gnutls_strerror(err));
1040                         goto done_cn_validation;
1041                 }
1042                 err = gnutls_x509_crt_check_hostname(cert, c->host);
1043                 if (err == 0)
1044                         Log(LOG_ERR,
1045                             "Failed to verify the hostname, expected \"%s\"",
1046                             c->host);
1047                 else
1048                         cert_ok = verify == 0 && status == 0;
1049
1050                 snprintf(msg, sizeof(msg), "%svalid peer certificate",
1051                         cert_ok ? "" : "in");
1052                 LogGnuTLS_CertInfo(cert_ok ? LOG_DEBUG : LOG_ERR, cert, msg);
1053
1054                 gnutls_x509_crt_deinit(cert);
1055 done_cn_validation:
1056                 ;
1057         }
1058 #endif
1059         /*
1060          * can be used later to check if connection was authenticated, e.g.
1061          * if inbound connection tries to register itself as server.
1062          * Could also restrict /OPER to authenticated connections, etc.
1063          */
1064         if (cert_ok)
1065                 Conn_OPTION_ADD(c, CONN_SSL_PEERCERT_OK);
1066         if (!cert_seen)
1067                 Log(LOG_INFO, "Peer did not present a certificate.");
1068 }
1069
1070
1071 /*
1072  Accept incoming SSL connection.
1073  Return Values:
1074          1: SSL Connection established
1075          0: try again
1076         -1: SSL Connection not established due to fatal error.
1077 */
1078 int
1079 ConnSSL_Accept( CONNECTION *c )
1080 {
1081         assert(c != NULL);
1082         if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
1083 #ifdef HAVE_LIBGNUTLS
1084                 int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
1085                 if (err) {
1086                         Log(LOG_ERR, "Failed to initialize new SSL session: %s",
1087                             gnutls_strerror(err));
1088                         return false;
1089                 }
1090 #endif
1091                 if (!ConnSSL_Init_SSL(c))
1092                         return -1;
1093         }
1094         return ConnectAccept(c, false );
1095 }
1096
1097
1098 int
1099 ConnSSL_Connect( CONNECTION *c )
1100 {
1101         assert(c != NULL);
1102 #ifdef HAVE_LIBSSL
1103         assert(c->ssl_state.ssl);
1104 #endif
1105         assert(Conn_OPTION_ISSET(c, CONN_SSL));
1106         return ConnectAccept(c, true);
1107 }
1108
1109 static int
1110 ConnSSL_InitCertFp( CONNECTION *c )
1111 {
1112         const char hex[] = "0123456789abcdef";
1113         int i;
1114
1115 #ifdef HAVE_LIBSSL
1116         unsigned char digest[EVP_MAX_MD_SIZE];
1117         unsigned int digest_size;
1118         X509 *cert;
1119
1120         cert = SSL_get_peer_certificate(c->ssl_state.ssl);
1121         if (!cert)
1122                 return 0;
1123
1124         if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
1125                 X509_free(cert);
1126                 return 0;
1127         }
1128
1129         X509_free(cert);
1130 #endif /* HAVE_LIBSSL */
1131 #ifdef HAVE_LIBGNUTLS
1132         gnutls_x509_crt_t cert;
1133         unsigned int cert_list_size;
1134         const gnutls_datum_t *cert_list;
1135         unsigned char digest[MAX_HASH_SIZE];
1136         size_t digest_size;
1137
1138         if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
1139                                         GNUTLS_CRT_X509)
1140                 return 0;
1141
1142         if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
1143                 return 0;
1144
1145         cert_list_size = 0;
1146         cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
1147                                                  &cert_list_size);
1148         if (!cert_list) {
1149                 gnutls_x509_crt_deinit(cert);
1150                 return 0;
1151         }
1152
1153         if (gnutls_x509_crt_import(cert, &cert_list[0],
1154                                    GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
1155                 gnutls_x509_crt_deinit(cert);
1156                 return 0;
1157         }
1158
1159         digest_size = sizeof(digest);
1160         if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
1161                                             &digest_size)) {
1162                 gnutls_x509_crt_deinit(cert);
1163                 return 0;
1164         }
1165
1166         gnutls_x509_crt_deinit(cert);
1167 #endif /* HAVE_LIBGNUTLS */
1168
1169         assert(c->ssl_state.fingerprint == NULL);
1170
1171         c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
1172         if (!c->ssl_state.fingerprint)
1173                 return 0;
1174
1175         for (i = 0; i < (int)digest_size; i++) {
1176                 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
1177                 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
1178         }
1179         c->ssl_state.fingerprint[i * 2] = '\0';
1180
1181         return 1;
1182 }
1183
1184 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
1185 static int
1186 ConnectAccept( CONNECTION *c, bool connect)
1187 {
1188         int ret;
1189 #ifdef HAVE_LIBSSL
1190         SSL *ssl = c->ssl_state.ssl;
1191         assert(ssl != NULL);
1192
1193         ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
1194         if (1 != ret)
1195                 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
1196 #endif
1197 #ifdef HAVE_LIBGNUTLS
1198         (void) connect;
1199         ret = gnutls_handshake(c->ssl_state.gnutls_session);
1200         if (ret)
1201                 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
1202 #endif /* _GNUTLS */
1203         (void)ConnSSL_InitCertFp(c);
1204
1205         Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
1206         ConnSSL_LogCertInfo(c, connect);
1207
1208         Conn_StartLogin(CONNECTION2ID(c));
1209         return 1;
1210 }
1211
1212
1213 ssize_t
1214 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
1215 {
1216         ssize_t bw;
1217
1218         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1219
1220         assert(count > 0);
1221 #ifdef HAVE_LIBSSL
1222         bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
1223 #endif
1224 #ifdef HAVE_LIBGNUTLS
1225         bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
1226 #endif
1227         if (bw > 0)
1228                 return bw;
1229         if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
1230                 errno = EAGAIN; /* try again */
1231         return -1;
1232 }
1233
1234
1235 ssize_t
1236 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
1237 {
1238         ssize_t br;
1239
1240         Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1241 #ifdef HAVE_LIBSSL
1242         br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
1243         if (br > 0)     /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
1244                 return br;
1245 #endif
1246 #ifdef HAVE_LIBGNUTLS
1247         br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
1248         if (br >= 0)    /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
1249                 return br;
1250 #endif
1251         /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
1252         if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
1253                 errno = EAGAIN;
1254                 return -1;
1255         }
1256         return 0;
1257 }
1258
1259
1260 bool
1261 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
1262 {
1263 #ifdef HAVE_LIBSSL
1264         char *nl;
1265         SSL *ssl = c->ssl_state.ssl;
1266
1267         if (!ssl)
1268                 return false;
1269         *buf = 0;
1270         SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
1271         nl = strchr(buf, '\n');
1272         if (nl)
1273                 *nl = 0;
1274         return true;
1275 #endif
1276 #ifdef HAVE_LIBGNUTLS
1277         if (Conn_OPTION_ISSET(c, CONN_SSL)) {
1278                 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
1279                 unsigned keysize;
1280
1281                 gnutls_session_t sess = c->ssl_state.gnutls_session;
1282                 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
1283                 name_cipher = gnutls_cipher_get_name(cipher);
1284                 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
1285                 keysize = gnutls_cipher_get_key_size(cipher) * 8;
1286                 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
1287                 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
1288
1289                 return snprintf(buf, len, "%s-%s%15s Kx=%s      Enc=%s(%u) Mac=%s",
1290                         name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
1291         }
1292         return false;
1293 #endif
1294 }
1295
1296 char *
1297 ConnSSL_GetCertFp(CONNECTION *c)
1298 {
1299         return c->ssl_state.fingerprint;
1300 }
1301
1302 bool
1303 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
1304 {
1305         assert (c != NULL);
1306         c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
1307         return c->ssl_state.fingerprint != NULL;
1308 }
1309 #else
1310
1311 bool
1312 ConnSSL_InitLibrary(void)
1313 {
1314         return true;
1315 }
1316
1317 #endif /* SSL_SUPPORT */
1318 /* -eof- */