1 /*
2  * tls.c -- handles:
3  *   TLS support functions
4  *   Certificate handling
5  *   OpenSSL initialization and shutdown
6  */
7 /*
8  * Written by Rumen Stoyanov <pseudo@egg6.net>
9  *
10  * Copyright (C) 2010 - 2021 Eggheads Development Team
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26 
27 #include "main.h"
28 
29 #ifdef TLS
30 
31 #include <openssl/err.h>
32 #include <openssl/rand.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/ssl.h>
35 
36 extern int tls_vfydcc;
37 extern struct dcc_t *dcc;
38 
39 int tls_maxdepth = 9;         /* Max certificate chain verification depth     */
40 int ssl_files_loaded = 0;     /* Check for loaded SSL key/cert files          */
41 SSL_CTX *ssl_ctx = NULL;      /* SSL context object                           */
42 char *tls_randfile = NULL;    /* Random seed file for SSL                     */
43 char tls_capath[121] = "";    /* Path to trusted CA certificates              */
44 char tls_cafile[121] = "";    /* File containing trusted CA certificates      */
45 char tls_certfile[121] = "";  /* Our own digital certificate ;)               */
46 char tls_keyfile[121] = "";   /* Private key for use with eggdrop             */
47 char tls_protocols[61] = "TLSv1 TLSv1.1 TLSv1.2 TLSv1.3" ; /* A list of protocols for SSL to use */
48 char tls_dhparam[121] = "";   /* dhparam for SSL to use                       */
49 char tls_ciphers[2049] = "";  /* A list of ciphers for SSL to use             */
50 
51 
52 /* Count allocated memory for SSL. This excludes memory allocated by OpenSSL's
53  * family of malloc functions.
54  */
expmem_tls()55 int expmem_tls()
56 {
57   int i, tot;
58   struct threaddata *td = threaddata();
59 
60   /* currently it's only the appdata structs allocated by ssl_handshake() */
61   for (i = 0, tot = 0; i < td->MAXSOCKS; i++)
62     if (!(td->socklist[i].flags & (SOCK_UNUSED | SOCK_TCL)))
63       if (td->socklist[i].ssl && SSL_get_app_data(td->socklist[i].ssl))
64         tot += sizeof(ssl_appdata);
65   return tot;
66 }
67 
68 /* Seeds the PRNG
69  *
70  * Only does something if the system doesn't have enough entropy.
71  * If there is no random file, one will be created either at
72  * $RANDFILE if set or at $HOME/.rnd
73  *
74  * Return value: 0 on success, !=0 on failure.
75  */
ssl_seed(void)76 static int ssl_seed(void)
77 {
78   char stackdata[1024];
79   static char rand_file[120];
80   FILE *fh;
81 
82   if (RAND_status())
83     return 0;     /* Status OK */
84   /* If '/dev/urandom' is present, OpenSSL will use it by default.
85    * Otherwise we'll have to generate pseudorandom data ourselves,
86    * using system time, our process ID and some uninitialized static
87    * storage.
88    */
89   putlog(LOG_MISC, "*", "WARNING: TLS: PRNG has not been sufficiently seeded. Seeding now.");
90   if ((fh = fopen("/dev/urandom", "r"))) {
91     fclose(fh);
92     return 0;
93   }
94   if (RAND_file_name(rand_file, sizeof(rand_file)))
95     tls_randfile = rand_file;
96   else
97     return 1;
98   if (!RAND_load_file(rand_file, -1)) {
99     /* generate some pseudo random data */
100     unsigned int c;
101     c = time(NULL);
102     RAND_seed(&c, sizeof(c));
103     c = getpid();
104     RAND_seed(&c, sizeof(c));
105     RAND_seed(stackdata, sizeof(stackdata));
106   }
107   if (!RAND_status())
108     return 2; /* pseudo random data still not enough */
109   return 0;
110 }
111 
112 /* Prepares and initializes SSL stuff
113  *
114  * Creates a context object, supporting SSLv2/v3 & TLSv1 protocols;
115  * Seeds the Pseudo Random Number Generator;
116  * Optionally loads a SSL certifate and a private key.
117  * Tell OpenSSL the location of certificate authority certs
118  *
119  * Return value: 0 on successful initialization, !=0 on failure
120  */
ssl_init()121 int ssl_init()
122 {
123   /* OpenSSL library initialization
124    * If you are using 1.1.0 or above then you don't need to take any further steps. */
125 #if OPENSSL_VERSION_NUMBER < 0x10100000L /* 1.1.0 */
126   SSL_library_init();
127   SSL_load_error_strings();
128   OpenSSL_add_all_algorithms();
129 #endif
130   if (ssl_seed()) {
131     putlog(LOG_MISC, "*", "ERROR: TLS: unable to seed PRNG. Disabling SSL");
132     ERR_free_strings();
133     return -2;
134   }
135   /* A TLS/SSL connection established with this method will understand all
136      supported protocols (SSLv2, SSLv3, and TLSv1) */
137   if (!(ssl_ctx = SSL_CTX_new(SSLv23_method()))) {
138     putlog(LOG_MISC, "*", ERR_error_string(ERR_get_error(), NULL));
139     putlog(LOG_MISC, "*", "ERROR: TLS: unable to create context. Disabling SSL.");
140     ERR_free_strings();
141     return -1;
142   }
143   ssl_files_loaded = 0;
144   if ((tls_certfile[0] == '\0') != (tls_keyfile[0] == '\0')) {
145     /* Both need to be set or unset */
146     putlog(LOG_MISC, "*", "ERROR: TLS: %s set but %s unset. Both must be set "
147         "to use a certificate, or unset both to disable.",
148         tls_certfile[0] ? "ssl-certificate" : "ssl-privatekey",
149         tls_certfile[0] ? "ssl-privatekey" : "ssl-certificate");
150     fatal("ssl-privatekey and ssl-certificate must both be set or unset.", 0);
151   }
152   if (tls_certfile[0] && tls_keyfile[0]) {
153     /* Load our own certificate and private key. Mandatory for acting as
154     server, because we don't support anonymous ciphers by default. */
155     if (SSL_CTX_use_certificate_chain_file(ssl_ctx, tls_certfile) != 1) {
156       putlog(LOG_MISC, "*", "ERROR: TLS: unable to load own certificate from %s: %s",
157           tls_certfile, ERR_error_string(ERR_get_error(), NULL));
158       fatal("Unable to load TLS certificate (ssl-certificate config setting)!", 0);
159     }
160     if (SSL_CTX_use_PrivateKey_file(ssl_ctx, tls_keyfile, SSL_FILETYPE_PEM) != 1) {
161       putlog(LOG_MISC, "*", "ERROR: TLS: unable to load private key from %s: %s",
162           tls_keyfile, ERR_error_string(ERR_get_error(), NULL));
163       fatal("Unable to load TLS private key (ssl-privatekey config setting)!", 0);
164     }
165     ssl_files_loaded = 1;
166   }
167   if ((tls_capath[0] || tls_cafile[0]) &&
168       !SSL_CTX_load_verify_locations(ssl_ctx, tls_cafile[0] ? tls_cafile : NULL,
169       tls_capath[0] ? tls_capath : NULL)) {
170     putlog(LOG_MISC, "*", "ERROR: TLS: unable to set CA certificates location: %s",
171            ERR_error_string(ERR_get_error(), NULL));
172     ERR_free_strings();
173   }
174   /* Let advanced users specify the list of allowed ssl protocols */
175   #define EGG_SSLv2   (1 << 0)
176   #define EGG_SSLv3   (1 << 1)
177   #define EGG_TLSv1   (1 << 2)
178   #define EGG_TLSv1_1 (1 << 3)
179   #define EGG_TLSv1_2 (1 << 4)
180   #define EGG_TLSv1_3 (1 << 5)
181   if (tls_protocols[0]) {
182     char s[sizeof tls_protocols];
183     char *sep = " ";
184     char *word;
185     unsigned int protocols = 0;
186     strcpy(s, tls_protocols);
187     for (word = strtok(s, sep); word; word = strtok(NULL, sep)) {
188       if (!strcmp(word, "SSLv2"))
189         protocols |= EGG_SSLv2;
190       if (!strcmp(word, "SSLv3"))
191         protocols |= EGG_SSLv3;
192       if (!strcmp(word, "TLSv1"))
193         protocols |= EGG_TLSv1;
194       if (!strcmp(word, "TLSv1.1"))
195         protocols |= EGG_TLSv1_1;
196       if (!strcmp(word, "TLSv1.2"))
197         protocols |= EGG_TLSv1_2;
198       if (!strcmp(word, "TLSv1.3"))
199         protocols |= EGG_TLSv1_3;
200     }
201     if (!(protocols & EGG_SSLv2)) {
202       SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
203     }
204     if (!(protocols & EGG_SSLv3)) {
205       SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
206     }
207     if (!(protocols & EGG_TLSv1)) {
208       SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
209     }
210 #ifdef SSL_OP_NO_TLSv1_1
211     if (!(protocols & EGG_TLSv1_1)) {
212       SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
213     }
214 #endif
215 #ifdef SSL_OP_NO_TLSv1_2
216     if (!(protocols & EGG_TLSv1_2)) {
217       SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
218     }
219 #endif
220 #ifdef SSL_OP_NO_TLSv1_3
221     if (!(protocols & EGG_TLSv1_3)) {
222       SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
223     }
224 #endif
225   }
226 #ifdef SSL_OP_NO_COMPRESSION
227   SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_COMPRESSION);
228 #endif
229   /* Let advanced users specify dhparam */
230   if (tls_dhparam[0]) {
231     DH *dh;
232     FILE *paramfile = fopen(tls_dhparam, "r");
233     if (paramfile) {
234       dh = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
235       fclose(paramfile);
236       if (dh) {
237         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
238           putlog(LOG_MISC, "*", "ERROR: TLS: unable to set tmp dh %s: %s",
239                  tls_dhparam, ERR_error_string(ERR_get_error(), NULL));
240         }
241         DH_free(dh);
242       }
243       else {
244         putlog(LOG_MISC, "*", "ERROR: TLS: unable to read DHparams %s: %s",
245                tls_dhparam, ERR_error_string(ERR_get_error(), NULL));
246       }
247     }
248     else {
249       putlog(LOG_MISC, "*", "ERROR: TLS: unable to open %s: %s",
250              tls_dhparam, strerror(errno));
251     }
252   }
253   /* Let advanced users specify the list of allowed ssl ciphers */
254   if (tls_ciphers[0] && !SSL_CTX_set_cipher_list(ssl_ctx, tls_ciphers)) {
255     /* this replaces any preset ciphers so an invalid list is fatal */
256     putlog(LOG_MISC, "*", "ERROR: TLS: no valid ciphers found. Disabling SSL.");
257     ERR_free_strings();
258     SSL_CTX_free(ssl_ctx);
259     ssl_ctx = NULL;
260     return -3;
261   }
262   return 0;
263 }
264 
265 /* Free the SSL CTX, clean up the mess */
ssl_cleanup()266 void ssl_cleanup()
267 {
268   if (ssl_ctx) {
269     SSL_CTX_free(ssl_ctx);
270     ssl_ctx = NULL;
271   }
272   if (tls_randfile)
273     RAND_write_file(tls_randfile);
274   ERR_free_strings();
275 }
276 
ssl_fpconv(char * in,char * out)277 char *ssl_fpconv(char *in, char *out)
278 {
279   long len;
280   char *fp;
281   unsigned char *sha1;
282 
283   if (!in)
284     return NULL;
285 
286   if ((sha1 = OPENSSL_hexstr2buf(in, &len))) {
287     fp = OPENSSL_buf2hexstr(sha1, len);
288     if (fp) {
289       out = user_realloc(out, strlen(fp) + 1);
290       strcpy(out, fp);
291       OPENSSL_free(sha1);
292       OPENSSL_free(fp);
293       return out;
294     }
295     OPENSSL_free(sha1);
296   }
297   return NULL;
298 }
299 
300 /* Get the certificate, corresponding to the connection
301  * identified by sock.
302  *
303  * Return value: pointer to a X509 certificate or NULL if we couldn't
304  * look up the certificate.
305  */
ssl_getcert(int sock)306 static X509 *ssl_getcert(int sock)
307 {
308   int i;
309   struct threaddata *td = threaddata();
310 
311   i = findsock(sock);
312   if (i == -1 || !td->socklist[i].ssl)
313     return NULL;
314   return SSL_get_peer_certificate(td->socklist[i].ssl);
315 }
316 
317 /* Get the certificate fingerprint of the connection corresponding
318  * to the socket.
319  *
320  * Return value: ptr to the hexadecimal representation of the fingerprint
321  * or NULL if there's no certificate associated with the connection.
322  */
ssl_getfp(int sock)323 char *ssl_getfp(int sock)
324 {
325   char *p;
326   unsigned int i;
327   X509 *cert;
328   static char fp[64];
329   unsigned char md[EVP_MAX_MD_SIZE];
330 
331   if (!(cert = ssl_getcert(sock)))
332     return NULL;
333   if (!X509_digest(cert, EVP_sha1(), md, &i))
334     return NULL;
335   if (!(p = OPENSSL_buf2hexstr(md, i)))
336     return NULL;
337   strlcpy(fp, p, sizeof fp);
338   OPENSSL_free(p);
339   return fp;
340 }
341 
342 /* Get the UID field from the certificate subject name.
343  * The certificate is looked up using the socket of the connection.
344  *
345  * Return value: Pointer to the uid string or NULL if not found
346  */
ssl_getuid(int sock)347 const char *ssl_getuid(int sock)
348 {
349   int idx;
350   X509 *cert;
351   X509_NAME *subj;
352   ASN1_STRING *name;
353 
354   if (!(cert = ssl_getcert(sock)))
355     return NULL;
356   /* Get the subject name */
357   if (!(subj = X509_get_subject_name(cert)))
358     return NULL;
359 
360   /* Get the first UID */
361   idx = X509_NAME_get_index_by_NID(subj, NID_userId, -1);
362   if (idx == -1)
363     return NULL;
364   name = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subj, idx));
365   /* Extract the contents, assuming null-terminated ASCII string */
366   return (const char *) egg_ASN1_string_data(name);
367 }
368 
369 /* Compare the peer's host with their Common Name or dnsName found in
370  * it's certificate. Only the first domain component of cn is allowed to
371  * be a wildcard '*'. The non-wildcard characters are compared ignoring
372  * case.
373  *
374  * Return value: 1 if cn matches host, 0 otherwise.
375  */
ssl_hostmatch(const char * cn,const char * host)376 static int ssl_hostmatch(const char *cn, const char *host)
377 {
378   const char *p, *q, *r;
379 
380   if ((r = strchr(cn + 1, '.')) && r[-1] == '*' && strchr(r, '.')) {
381     for (p = cn, q = host; *p != '*'; p++, q++)
382       if (toupper((const unsigned char)*p) != toupper((const unsigned char)*q))
383         return 0;
384 
385     if (!(p = strchr(host, '.')) || strcasecmp(p, r))
386       return 0;
387     return 1;
388   }
389 
390   /* First domain component is not a wildcard and they aren't allowed
391      elsewhere, so just compare the strings. */
392   return strcasecmp(cn, host) ? 0 : 1;
393 }
394 
395 /* Confirm the peer identity, by checking if the certificate subject
396  * matches the peer's DNS name or IP address. Matching is performed in
397  * accordance with RFC 2818:
398  *
399  * If the certificate has a subjectAltName extension, all names of type
400  * IPAddress or dnsName present there, will be compared to data->host,
401  * depending on it's contents.
402  * In case there's no subjectAltName extension, commonName (CN) parts
403  * of the certificate subject field will be used instead of IPAddress
404  * and dnsName entries. For IP addresses, common names must contain IPs
405  * in presentation format (1.2.3.4 or 2001:DB8:15:dead::)
406  * Finally, if no subjectAltName or common names are present, the
407  * certificate is considered to not match the peer.
408  *
409  * The structure of X509 certificates and all fields referenced above
410  * are described in RFC 5280.
411  *
412  * The certificate must be pointed by cert and the peer's host must be
413  * placed in data->host. The format is a regular DNS name or an IP in
414  * presentation format (see above).
415  *
416  * Return value: 1 if the certificate matches the peer, 0 otherwise.
417  */
ssl_verifycn(X509 * cert,ssl_appdata * data)418 static int ssl_verifycn(X509 *cert, ssl_appdata *data)
419 {
420   const char *cn;
421   int crit = 0, match = 0;
422   ASN1_OCTET_STRING *ip;
423   GENERAL_NAMES *altname; /* SubjectAltName ::= GeneralNames */
424 
425   ip = a2i_IPADDRESS(data->host); /* check if it's an IP or a hostname */
426   if ((altname = X509_get_ext_d2i(cert, NID_subject_alt_name, &crit, NULL))) {
427     GENERAL_NAME *gn;
428 
429     /* Loop through the general names in altname and pick these
430        of type ip address or dns name */
431     while (!match && (gn = sk_GENERAL_NAME_pop(altname))) {
432       /* if the peer's host is an IP, we're only interested in
433          matching against iPAddress general names, otherwise
434          we'll only look for dnsName's */
435       if (ip) {
436         if (gn->type == GEN_IPADD)
437           match = !ASN1_STRING_cmp(gn->d.ip, ip);
438       } else if (gn->type == GEN_DNS) {
439         /* IA5string holds ASCII data */
440         cn = (const char *) egg_ASN1_string_data(gn->d.ia5);
441         match = ssl_hostmatch(cn, data->host);
442       }
443     }
444     sk_GENERAL_NAME_free(altname);
445   } else { /* no subjectAltName, try to match against the subject CNs */
446     X509_NAME *subj; /* certificate subject */
447 
448     /* the following is just for information */
449     switch (crit) {
450       case 0:
451         debug0("TLS: X509 subjectAltName cannot be decoded");
452         break;
453       case -1:
454         debug0("TLS: X509 has no subjectAltName extension");
455         break;
456       case -2:
457         debug0("TLS: X509 has multiple subjectAltName extensions");
458     }
459     /* no subject name either? A completely broken certificate :) */
460     if (!(subj = X509_get_subject_name(cert))) {
461       putlog(data->loglevel, "*", "TLS: peer certificate has no subject: %s",
462              data->host);
463       match = 0;
464     } else { /* we have a subject name, look at it */
465       int pos = -1;
466       ASN1_STRING *name;
467 
468       /* Look for commonName attributes in the subject name */
469       pos = X509_NAME_get_index_by_NID(subj, NID_commonName, pos);
470       if (pos == -1) /* sorry */
471         putlog(data->loglevel, "*", "TLS: Peer has no common names and "
472               "no subjectAltName extension. Verification failed.");
473       /* Loop through all common names which may be present in the subject
474          name until we find a match. */
475       while (!match && pos != -1) {
476         name = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subj, pos));
477         cn = (const char *) egg_ASN1_string_data(name);
478         if (ip)
479           match = a2i_IPADDRESS(cn) ? (ASN1_STRING_cmp(ip, a2i_IPADDRESS(cn)) ? 0 : 1) : 0;
480         else
481           match = ssl_hostmatch(cn, data->host);
482         pos = X509_NAME_get_index_by_NID(subj, NID_commonName, pos);
483       }
484     }
485   }
486 
487   if (ip)
488     ASN1_OCTET_STRING_free(ip);
489   return match;
490 }
491 
492 /* Extract a human readable version of a X509_NAME and put the result
493  * into a nmalloc'd buffer.
494  * The X509_NAME structure is used for example in certificate subject
495  * and issuer names.
496  *
497  * You need to nfree() the returned pointer.
498  */
ssl_printname(X509_NAME * name)499 static char *ssl_printname(X509_NAME *name)
500 {
501   long len;
502   char *data, *buf;
503   BIO *bio = BIO_new(BIO_s_mem());
504 
505   /* X509_NAME_oneline() is easier and shorter, but is deprecated and
506      the manual discourages it's usage, so let's not be lazy ;) */
507   if (X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE & ~XN_FLAG_SPC_EQ)) {
508     len = BIO_get_mem_data(bio, &data);
509     if (len > 0) {
510       buf = nmalloc(len + 1);
511       memcpy(buf, data, len); /* don't strlcpy() for it would read data[len] */
512       buf[len] = 0;
513     } else {
514       debug0("TLS: ssl_printname(): BIO_get_mem_data(): error");
515       buf = nmalloc(1);
516       *buf = 0;
517     }
518   } else {
519     debug0("TLS: ssl_printname(): X509_NAME_print_ex(): error");
520     buf = nmalloc(1);
521     *buf = 0;
522   }
523   BIO_free(bio);
524   return buf;
525 }
526 
527 /* Print the time from a ASN1_UTCTIME object in standard format i.e.
528  * Nov 21 23:59:00 1996 GMT and store it in a nmalloc'd buffer.
529  * The ASN1_UTCTIME structure is what's used for example with
530  * certificate validity dates.
531  *
532  * You need to nfree() the returned pointer.
533  */
ssl_printtime(ASN1_UTCTIME * t)534 static char *ssl_printtime(ASN1_UTCTIME *t)
535 {
536   long len;
537   char *data, *buf;
538   BIO *bio = BIO_new(BIO_s_mem());
539 
540   ASN1_UTCTIME_print(bio, t);
541   len = BIO_get_mem_data(bio, &data);
542   if (len > 0) {
543     buf = nmalloc(len + 1);
544     memcpy(buf, data, len); /* don't strlcpy() for it would read data[len] */
545     buf[len] = 0;
546   } else {
547     debug0("TLS: ssl_printtime(): BIO_get_mem_data(): error");
548     buf = nmalloc(1);
549     *buf = 0;
550   }
551   BIO_free(bio);
552   return buf;
553 }
554 
555 /* Print the value of an ASN1_INTEGER in hexadecimal format.
556  * A typical use for this is to display certificate serial numbers.
557  * As usual, we use a memory BIO.
558  *
559  * You need to nfree() the returned pointer.
560  */
ssl_printnum(ASN1_INTEGER * i)561 static char *ssl_printnum(ASN1_INTEGER *i)
562 {
563   long len;
564   char *data, *buf;
565   BIO *bio = BIO_new(BIO_s_mem());
566 
567   i2a_ASN1_INTEGER(bio, i);
568   len = BIO_get_mem_data(bio, &data);
569   if (len > 0) {
570     buf = nmalloc(len + 1);
571     memcpy(buf, data, len); /* don't strlcpy() for it would read data[len] */
572     buf[len] = 0;
573   } else {
574     debug0("TLS: ssl_printnum(): BIO_get_mem_data(): error");
575     buf = nmalloc(1);
576     *buf = 0;
577   }
578   BIO_free(bio);
579   return buf;
580 }
581 
582 /* Show the user all relevant information about a certificate: subject,
583  * issuer, validity dates and fingerprints.
584  */
ssl_showcert(X509 * cert,const int loglev)585 static void ssl_showcert(X509 *cert, const int loglev)
586 {
587   char *buf, *from, *to;
588   X509_NAME *name;
589   unsigned int len;
590   unsigned char md[EVP_MAX_MD_SIZE];
591 
592   /* Subject and issuer names */
593   if ((name = X509_get_subject_name(cert))) {
594     buf = ssl_printname(name);
595     putlog(loglev, "*", "TLS: certificate subject: %s", buf);
596     nfree(buf);
597   } else
598     putlog(loglev, "*", "TLS: cannot get subject name from certificate!");
599   if ((name = X509_get_issuer_name(cert))) {
600     buf = ssl_printname(name);
601     putlog(loglev, "*", "TLS: certificate issuer: %s", buf);
602     nfree(buf);
603   } else
604     putlog(loglev, "*", "TLS: cannot get issuer name from certificate!");
605 
606   /* Fingerprints */
607   if (X509_digest(cert, EVP_sha1(), md, &len)) {
608     buf = OPENSSL_buf2hexstr(md, len);
609     putlog(loglev, "*", "TLS: certificate SHA1 Fingerprint: %s", buf);
610     OPENSSL_free(buf);
611   }
612   if (X509_digest(cert, EVP_sha256(), md, &len)) {
613     buf = OPENSSL_buf2hexstr(md, len);
614     putlog(loglev, "*", "TLS: certificate SHA-256 Fingerprint: %s", buf);
615     OPENSSL_free(buf);
616   }
617 
618 
619   /* Validity time */
620   from = ssl_printtime(X509_get_notBefore(cert));
621   to = ssl_printtime(X509_get_notAfter(cert));
622   putlog(loglev, "*", "TLS: certificate valid from %s to %s", from, to);
623   nfree(from);
624   nfree(to);
625 }
626 
627 /* Certificate validation callback
628  *
629  * Check if the certificate given is valid with respect to the
630  * ssl-verify config variable. This makes it possible to allow
631  * self-signed certificates and is also a convenient place to
632  * extract a certificate summary.
633  *
634  * Return value: 1 - validation passed, 0 - invalid cert
635  */
ssl_verify(int ok,X509_STORE_CTX * ctx)636 int ssl_verify(int ok, X509_STORE_CTX *ctx)
637 {
638   SSL *ssl;
639   X509 *cert;
640   ssl_appdata *data;
641   int err, depth;
642 
643   /* get cert, callbacks, error codes, etc. */
644   depth = X509_STORE_CTX_get_error_depth(ctx);
645   cert = X509_STORE_CTX_get_current_cert(ctx);
646   ssl = X509_STORE_CTX_get_ex_data(ctx,
647                           SSL_get_ex_data_X509_STORE_CTX_idx());
648   data = (ssl_appdata *) SSL_get_app_data(ssl);
649   err = X509_STORE_CTX_get_error(ctx);
650 
651   /* OpenSSL won't explicitly generate this error; instead it will
652    * report missing certificates. Refer to SSL_CTX_set_verify(3)
653    * manual for details
654    */
655   if (depth > tls_maxdepth) {
656     ok = 0;
657     err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
658 
659   /* depth 0 is actually the peer certificate. We do all custom
660    * verification here and leave the rest of the certificate chain
661    * to OpenSSL's built in procedures.
662    */
663   } else if (!depth) {
664     /* OpenSSL doesn't perform subject name verification. We need to do
665      * it ourselves. We check here for validity even if it's not requested
666      * in order to be able to warn the user.
667      */
668     if (!(data->flags & TLS_DEPTH0) && (data->verify & TLS_VERIFYCN) &&
669         !ssl_verifycn(cert, data)) {
670         putlog(data->loglevel, "*", "TLS: certificate validation failed. "
671                "Certificate subject does not match peer.");
672         return 0;
673     }
674     data->flags |= TLS_DEPTH0;
675     /* Allow exceptions for certain common verification errors, if the
676      * caller requested so. A lot of servers provide completely invalid
677      * certificates useless for any authentication.
678      */
679     if (!ok || data->verify)
680       if (((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) &&
681           !(data->verify & TLS_VERIFYISSUER)) ||
682           ((err == X509_V_ERR_CERT_REVOKED) &&
683           !(data->verify & TLS_VERIFYREV)) ||
684           ((err == X509_V_ERR_CERT_NOT_YET_VALID) &&
685           !(data->verify & TLS_VERIFYFROM)) ||
686           ((err == X509_V_ERR_CERT_HAS_EXPIRED) &&
687           !(data->verify & TLS_VERIFYTO))) {
688         debug1("TLS: peer certificate warning: %s",
689                X509_verify_cert_error_string(err));
690         ok = 1;
691       }
692   }
693   if (ok || !data->verify)
694     return 1;
695   putlog(data->loglevel, "*",
696          "TLS: certificate validation failed at depth %d: %s",
697          depth, X509_verify_cert_error_string(err));
698   return 0;
699 }
700 
701 /* SSL info callback, this is used to trace engine state changes
702  * and to check when the handshake is finished, so we can display
703  * some cipher and session information and process callbacks.
704  */
ssl_info(const SSL * ssl,int where,int ret)705 static void ssl_info(const SSL *ssl, int where, int ret)
706 {
707   int sock;
708   X509 *cert;
709   char buf[256];
710   ssl_appdata *data;
711 #if OPENSSL_VERSION_NUMBER >= 0x009080d1L /* 0.9.8m-beta1 */
712   const
713 #endif
714   SSL_CIPHER *cipher;
715   int secret, processed;
716 
717   if (!(data = (ssl_appdata *) SSL_get_app_data(ssl)))
718     return;
719 
720   /* We're doing non-blocking IO, so we check here if the handshake has
721      finished */
722   if (where & SSL_CB_HANDSHAKE_DONE) {
723     /* Callback for completed handshake. Cheaper and more convenient than
724        using H_tls */
725     sock = SSL_get_fd(ssl);
726     if (data->cb)
727       data->cb(sock);
728     /* Call TLS binds. We allow scripts to take over or disable displaying of
729        certificate information. */
730     if (check_tcl_tls(sock))
731       return;
732 
733     putlog(data->loglevel, "*", "TLS: handshake successful. Secure connection "
734            "established.");
735 
736     if ((cert = SSL_get_peer_certificate(ssl))) {
737       ssl_showcert(cert, data->loglevel);
738       X509_free(cert);
739     }
740     else
741       putlog(data->loglevel, "*", "TLS: peer did not present a certificate");
742 
743     /* Display cipher information */
744     cipher = SSL_get_current_cipher(ssl);
745     processed = SSL_CIPHER_get_bits(cipher, &secret);
746     putlog(data->loglevel, "*", "TLS: cipher used: %s %s; %d bits (%d secret)",
747            SSL_CIPHER_get_name(cipher), SSL_get_version(ssl),
748            processed, secret);
749     /* secret are the actually secret bits. If processed and secret differ,
750        the rest of the bits are fixed, i.e. for limited export ciphers */
751 
752     /* More verbose information, for debugging only */
753     SSL_CIPHER_description(cipher, buf, sizeof buf);
754     debug1("TLS: cipher details: %s", buf);
755   } else if (where & SSL_CB_ALERT) {
756     if (strcmp(SSL_alert_type_string(ret), "W") ||
757         strcmp(SSL_alert_desc_string(ret), "CN")) {
758       putlog(data->loglevel, "*", "TLS: alert during %s: %s (%s).",
759              (where & SSL_CB_READ) ? "read" : "write",
760              SSL_alert_type_string_long(ret),
761              SSL_alert_desc_string_long(ret));
762     } else {
763       /* Ignore close notify warnings */
764       debug1("Received close notify warning during %s",
765              (where & SSL_CB_READ) ? "read" : "write");
766     }
767   } else if (where & SSL_CB_EXIT) {
768     /* SSL_CB_EXIT may point to soft error for non-blocking! */
769     if (ret == 0) {
770       /* According to manpage, only 0 indicates a real error */
771       putlog(data->loglevel, "*", "TLS: failed in: %s.",
772              SSL_state_string_long(ssl));
773     } else if (ret < 0) {
774       int err = SSL_get_error(ssl, ret);
775       /* However we still check <0 as man example does so too */
776       if (err & (SSL_ERROR_WANT_READ | SSL_ERROR_WANT_WRITE)) {
777         /* Errors to be ignored for non-blocking */
778         debug1("TLS: awaiting more %s", (err & SSL_ERROR_WANT_READ) ? "reads" : "writes");
779       } else {
780         putlog(data->loglevel, "*", "TLS: error in: %s.",
781                SSL_state_string_long(ssl));
782       }
783     }
784   } else {
785     /* Display the state of the engine for debugging purposes */
786     debug1("TLS: state change: %s", SSL_state_string_long(ssl));
787   }
788 }
789 
790 /* Switch a socket to SSL communication
791  *
792  * Creates a SSL data structure for the connection;
793  * Sets up callbacks and initiates a SSL handshake with the peer;
794  * Reports error conditions and performs cleanup upon failure.
795  *
796  * flags: ssl flags, i.e connect or listen
797  * verify: peer certificate verification flags
798  * loglevel: is the level to output information about the connection
799  * and certificates.
800  * host: contains the dns name or ip address of the peer. Used for
801  * verification.
802  * cb: optional callback, this function will be called after the
803  * handshake completes.
804  *
805  * Return value: 0 on success, !=0 on failure.
806  */
ssl_handshake(int sock,int flags,int verify,int loglevel,char * host,IntFunc cb)807 int ssl_handshake(int sock, int flags, int verify, int loglevel, char *host,
808                   IntFunc cb)
809 {
810   int i, err, ret;
811   ssl_appdata *data;
812   struct threaddata *td = threaddata();
813 
814   debug0("TLS: attempting SSL negotiation...");
815   if (!ssl_ctx && ssl_init()) {
816     debug0("TLS: Failed. OpenSSL not initialized properly.");
817     return -1;
818   }
819   if ((flags & TLS_LISTEN) && !ssl_files_loaded) {
820     putlog(LOG_MISC, "*", "TLS: Failed. Certificate/Key not loaded, cannot support SSL/TLS for client (see doc/TLS).");
821     return -4;
822   }
823   /* find the socket in the list */
824   i = findsock(sock);
825   if (i == -1) {
826     debug0("TLS: socket not in socklist");
827     return -2;
828   }
829   if (td->socklist[i].ssl) {
830     debug0("TLS: handshake not required - SSL session already established");
831     return 0;
832   }
833   td->socklist[i].ssl = SSL_new(ssl_ctx);
834   if (!td->socklist[i].ssl ||
835       !SSL_set_fd(td->socklist[i].ssl, td->socklist[i].sock)) {
836     debug1("TLS: cannot initiate SSL session - %s",
837            ERR_error_string(ERR_get_error(), 0));
838     return -3;
839   }
840 
841   /* Prepare a ssl appdata struct for the verify callback */
842   data = nmalloc(sizeof(ssl_appdata));
843   egg_bzero(data, sizeof(ssl_appdata));
844   data->flags = flags & (TLS_LISTEN | TLS_CONNECT);
845   data->verify = verify;
846   /* Invert these flags as their corresponding configuration values express
847    * exceptions
848    */
849   if (data->verify)
850       data->verify ^= (TLS_VERIFYISSUER | TLS_VERIFYCN | TLS_VERIFYFROM |
851                        TLS_VERIFYTO | TLS_VERIFYREV);
852   data->loglevel = loglevel;
853   data->cb = cb;
854   strlcpy(data->host, host ? host : "", sizeof(data->host));
855   SSL_set_app_data(td->socklist[i].ssl, data);
856   SSL_set_info_callback(td->socklist[i].ssl, ssl_info);
857   /* We set this +1 to be able to report extra long chains properly.
858    * Otherwise, OpenSSL will break the verification reporting about
859    * missing certificates instead. The rest of the fix is in
860    * ssl_verify()
861    */
862   SSL_set_verify_depth(td->socklist[i].ssl, tls_maxdepth + 1);
863 
864   SSL_set_mode(td->socklist[i].ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
865                SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
866   if (data->flags & TLS_CONNECT) {
867     struct timespec req = { 0, 1000000L };
868     SSL_set_verify(td->socklist[i].ssl, SSL_VERIFY_PEER, ssl_verify);
869     /* Introduce 1ms lag so an unpatched hub has time to setup the ssl handshake */
870     nanosleep(&req, NULL);
871 #ifdef SSL_set_tlsext_host_name
872     if (*data->host)
873       if (!SSL_set_tlsext_host_name(td->socklist[i].ssl, data->host))
874         debug1("TLS: setting the server name indication (SNI) to %s failed", data->host);
875       else
876         debug1("TLS: setting the server name indication (SNI) to %s successful", data->host);
877     else
878       debug0("TLS: not setting the server name indication (SNI) because host is an empty string");
879 #else
880     debug0("TLS: setting the server name indication (SNI) not supported by ssl "
881            "lib, probably < openssl 0.9.8f");
882 #endif
883     ret = SSL_connect(td->socklist[i].ssl);
884     if (!ret)
885       debug0("TLS: connect handshake failed.");
886   } else {
887     if (data->verify & TLS_VERIFYPEER)
888       SSL_set_verify(td->socklist[i].ssl, SSL_VERIFY_PEER |
889                      SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify);
890     else
891       SSL_set_verify(td->socklist[i].ssl, SSL_VERIFY_PEER, ssl_verify);
892     ret = SSL_accept(td->socklist[i].ssl);
893     if (!ret)
894       debug0("TLS: accept handshake failed");
895   }
896 
897   err = SSL_get_error(td->socklist[i].ssl, ret);
898   /* Normal condition for async I/O, similar to EAGAIN */
899   if (ret > 0 || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
900     debug0("TLS: handshake in progress");
901     return 0;
902   }
903   if ((err = ERR_peek_error())) {
904     putlog(data->loglevel, "*",
905            "TLS: handshake failed due to the following error: %s",
906            ERR_reason_error_string(err));
907     debug0("TLS: handshake failed due to the following errors: ");
908     while ((err = ERR_get_error()))
909       debug1("TLS: %s", ERR_error_string(err, NULL));
910   }
911 
912   /* Attempt failed, cleanup and abort */
913   SSL_shutdown(td->socklist[i].ssl);
914   SSL_free(td->socklist[i].ssl);
915   td->socklist[i].ssl = NULL;
916   nfree(data);
917   return -4;
918 }
919 
920 /* Tcl functions */
921 
922 /* Is the connection secure? */
923 static int tcl_istls STDVAR
924 {
925   int j;
926 
927   BADARGS(2, 2, " idx");
928 
929   j = findidx(atoi(argv[1]));
930   if (j < 0) {
931     Tcl_AppendResult(irp, "invalid idx", NULL);
932     return TCL_ERROR;
933   }
934   if (dcc[j].ssl)
935     Tcl_AppendResult(irp, "1", NULL);
936   else
937     Tcl_AppendResult(irp, "0", NULL);
938   return TCL_OK;
939 }
940 
941 /* Perform a SSL handshake over an existing plain text
942  * connection.
943  */
944 static int tcl_starttls STDVAR
945 {
946   int j;
947   struct threaddata *td = threaddata();
948 
949   BADARGS(2, 2, " idx");
950 
951   j = findidx(atoi(argv[1]));
952   if (j < 0 || (dcc[j].type != &DCC_SCRIPT)) {
953     Tcl_AppendResult(irp, "invalid idx", NULL);
954     return TCL_ERROR;
955   }
956   if (dcc[j].ssl) {
957     Tcl_AppendResult(irp, "already started", NULL);
958     return TCL_ERROR;
959   }
960   /* Determine if we're playing a client or a server */
961   j = findsock(dcc[j].sock);
962   if (ssl_handshake(dcc[j].sock, (td->socklist[j].flags & SOCK_CONNECT) ?
963       TLS_CONNECT : TLS_LISTEN, tls_vfydcc, LOG_MISC, NULL, NULL))
964     Tcl_AppendResult(irp, "0", NULL);
965   else
966     Tcl_AppendResult(irp, "1", NULL);
967   return TCL_OK;
968 }
969 
970 /* Get all relevant information about an established ssl connection.
971  * This includes certificate subject and issuer, serial number,
972  * expiry date, protocol version and cipher information.
973  * All data is presented as a flat list consisting of name-value pairs.
974  */
975 static int tcl_tlsstatus STDVAR
976 {
977   char *p;
978   int i, j;
979   X509 *cert;
980   const SSL_CIPHER *cipher;
981   struct threaddata *td = threaddata();
982   Tcl_DString ds;
983 
984   BADARGS(2, 2, " idx");
985 
986   /* Allow it to be used for any connection, not just scripted
987    * ones. This makes it possible for a script to display the
988    * server certificate.
989    */
990   i = findanyidx(atoi(argv[1]));
991   if (i < 0) {
992     Tcl_AppendResult(irp, "invalid idx", NULL);
993     return TCL_ERROR;
994   }
995   j = findsock(dcc[i].sock);
996   if (!j || !dcc[i].ssl || !td->socklist[j].ssl) {
997     Tcl_AppendResult(irp, "not a TLS connection", NULL);
998     return TCL_ERROR;
999   }
1000 
1001   Tcl_DStringInit(&ds);
1002   /* Try to get a cert, clients aren't required to send a
1003    * certificate, so this is optional
1004    */
1005   cert = SSL_get_peer_certificate(td->socklist[j].ssl);
1006   /* The following information is certificate dependent */
1007   if (cert) {
1008     p = ssl_printname(X509_get_subject_name(cert));
1009     Tcl_DStringAppendElement(&ds, "subject");
1010     Tcl_DStringAppendElement(&ds, p);
1011     nfree(p);
1012     p = ssl_printname(X509_get_issuer_name(cert));
1013     Tcl_DStringAppendElement(&ds, "issuer");
1014     Tcl_DStringAppendElement(&ds, p);
1015     nfree(p);
1016     p = ssl_printtime(X509_get_notBefore(cert));
1017     Tcl_DStringAppendElement(&ds, "notBefore");
1018     Tcl_DStringAppendElement(&ds, p);
1019     nfree(p);
1020     p = ssl_printtime(X509_get_notAfter(cert));
1021     Tcl_DStringAppendElement(&ds, "notAfter");
1022     Tcl_DStringAppendElement(&ds, p);
1023     nfree(p);
1024     p = ssl_printnum(X509_get_serialNumber(cert));
1025     Tcl_DStringAppendElement(&ds, "serial");
1026     Tcl_DStringAppendElement(&ds, p);
1027     nfree(p);
1028   }
1029   /* We should always have a cipher, but who knows? */
1030   cipher = SSL_get_current_cipher(td->socklist[j].ssl);
1031   if (cipher) { /* don't bother if there's none */
1032     Tcl_DStringAppendElement(&ds, "protocol");
1033     Tcl_DStringAppendElement(&ds, SSL_CIPHER_get_version(cipher));
1034     Tcl_DStringAppendElement(&ds, "cipher");
1035     Tcl_DStringAppendElement(&ds, SSL_CIPHER_get_name(cipher));
1036   }
1037 
1038   /* Done, get a Tcl list from this and return it to the caller */
1039   Tcl_AppendResult(irp, Tcl_DStringValue(&ds), NULL);
1040   Tcl_DStringFree(&ds);
1041   return TCL_OK;
1042 }
1043 
1044 /* These will be added by tcl.c which is the established practice */
1045 tcl_cmds tcltls_cmds[] = {
1046   {"istls",         tcl_istls},
1047   {"starttls",   tcl_starttls},
1048   {"tlsstatus", tcl_tlsstatus},
1049   {NULL,                 NULL}
1050 };
1051 
1052 #endif /* TLS */
1053