"Fossies" - the Fresh Open Source Software Archive

Member "msmtp-1.8.5/src/tls.c" (25 Jun 2019, 55444 Bytes) of package /linux/privat/msmtp-1.8.5.tar.xz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "tls.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.8.4_vs_1.8.5.

    1 /*
    2  * tls.c
    3  *
    4  * This file is part of msmtp, an SMTP client.
    5  *
    6  * Copyright (C) 2000, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
    7  * 2012, 2014, 2016, 2018, 2019
    8  * Martin Lambers <marlam@marlam.de>
    9  *
   10  *   This program is free software; you can redistribute it and/or modify
   11  *   it under the terms of the GNU General Public License as published by
   12  *   the Free Software Foundation; either version 3 of the License, or
   13  *   (at your option) any later version.
   14  *
   15  *   This program is distributed in the hope that it will be useful,
   16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
   17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18  *   GNU General Public License for more details.
   19  *
   20  *   You should have received a copy of the GNU General Public License
   21  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
   22  */
   23 
   24 #ifdef HAVE_CONFIG_H
   25 # include "config.h"
   26 #endif
   27 
   28 #include <stdio.h>
   29 #include <string.h>
   30 #include <strings.h>
   31 #include <ctype.h>
   32 #include <stdlib.h>
   33 #include <limits.h>
   34 #include <time.h>
   35 #include <errno.h>
   36 
   37 #ifdef HAVE_LIBGNUTLS
   38 # include <gnutls/gnutls.h>
   39 # include <gnutls/x509.h>
   40 # include <gnutls/pkcs11.h>
   41 #endif /* HAVE_LIBGNUTLS */
   42 #ifdef HAVE_LIBSSL
   43 # include <openssl/ssl.h>
   44 # include <openssl/x509.h>
   45 # include <openssl/x509v3.h>
   46 # include <openssl/err.h>
   47 # include <openssl/rand.h>
   48 # include <openssl/evp.h>
   49 #if OPENSSL_VERSION_NUMBER < 0x10100000L
   50 #define X509_get0_notBefore X509_get_notBefore
   51 #define X509_get0_notAfter X509_get_notAfter
   52 #endif
   53 #endif /* HAVE_LIBSSL */
   54 
   55 #ifdef HAVE_LIBIDN
   56 # include <idn2.h>
   57 #endif
   58 
   59 #include "gettext.h"
   60 #define _(string) gettext(string)
   61 #define N_(string) gettext_noop(string)
   62 
   63 #include "xalloc.h"
   64 #include "readbuf.h"
   65 #include "tools.h"
   66 #include "tls.h"
   67 
   68 
   69 /*
   70  * tls_clear()
   71  *
   72  * see tls.h
   73  */
   74 
   75 void tls_clear(tls_t *tls)
   76 {
   77     tls->is_active = 0;
   78     tls->have_trust_file = 0;
   79     tls->have_sha256_fingerprint = 0;
   80     tls->have_sha1_fingerprint = 0;
   81     tls->have_md5_fingerprint = 0;
   82     tls->no_certcheck = 0;
   83     tls->hostname = NULL;
   84 }
   85 
   86 
   87 /*
   88  * seed_prng()
   89  *
   90  * Seeds the OpenSSL random number generator.
   91  * Used error codes: TLS_ESEED
   92  */
   93 
   94 #ifdef HAVE_LIBSSL
   95 int seed_prng(char **errstr)
   96 {
   97     char randfile[512];
   98     time_t t;
   99     int prn;
  100     int system_prn_max = 1024;
  101 
  102     /* Most systems have /dev/random or other sources of random numbers that
  103      * OpenSSL can use to seed itself.
  104      * The only system I know of where we must seed the PRNG is DOS.
  105      */
  106     if (!RAND_status())
  107     {
  108         if (!RAND_file_name(randfile, 512))
  109         {
  110             *errstr = xasprintf(_("no environment variables RANDFILE or HOME, "
  111                         "or filename of rand file too long"));
  112             return TLS_ESEED;
  113         }
  114         if (RAND_load_file(randfile, -1) < 1)
  115         {
  116             *errstr = xasprintf(_("%s: input error"), randfile);
  117             return TLS_ESEED;
  118         }
  119         /* Seed in time. I can't think of other "random" things on DOS
  120          * systems. */
  121         t = time(NULL);
  122         RAND_seed((unsigned char *)&t, sizeof(time_t));
  123         /* If the RANDFILE + time is not enough, we fall back to the insecure
  124          * and stupid method of seeding OpenSSLs PRNG with the systems PRNG. */
  125         if (!RAND_status())
  126         {
  127             srand((unsigned int)(t % UINT_MAX));
  128             while (!RAND_status() && system_prn_max > 0)
  129             {
  130                 prn = rand();
  131                 RAND_seed(&prn, sizeof(int));
  132                 system_prn_max--;
  133             }
  134         }
  135         /* Are we happy now? */
  136         if (!RAND_status())
  137         {
  138             *errstr = xasprintf(_("random file + time + pseudo randomness is "
  139                         "not enough, giving up"));
  140             return TLS_ESEED;
  141         }
  142         /* Save a rand file for later usage. We ignore errors here as we can't
  143          * do anything about them. */
  144         (void)RAND_write_file(randfile);
  145     }
  146     return TLS_EOK;
  147 }
  148 #endif /* HAVE_LIBSSL */
  149 
  150 
  151 /*
  152  * tls_lib_init()
  153  *
  154  * see tls.h
  155  */
  156 
  157 int tls_lib_init(char **errstr)
  158 {
  159 #ifdef HAVE_LIBGNUTLS
  160     int error_code;
  161 
  162     if ((error_code = gnutls_global_init()) != 0)
  163     {
  164         *errstr = xasprintf("%s", gnutls_strerror(error_code));
  165         return TLS_ELIBFAILED;
  166     }
  167 
  168     return TLS_EOK;
  169 #endif /* HAVE_LIBGNUTLS */
  170 
  171 #ifdef HAVE_LIBSSL
  172     int e;
  173 
  174 #if OPENSSL_VERSION_NUMBER < 0x10100000L
  175     SSL_load_error_strings();
  176     SSL_library_init();
  177 #endif
  178     if ((e = seed_prng(errstr)) != TLS_EOK)
  179     {
  180         return e;
  181     }
  182 
  183     return TLS_EOK;
  184 #endif /* HAVE_LIBSSL */
  185 }
  186 
  187 
  188 /*
  189  * tls_is_active()
  190  *
  191  * see tls.h
  192  */
  193 
  194 int tls_is_active(tls_t *tls)
  195 {
  196     return tls->is_active;
  197 }
  198 
  199 
  200 /*
  201  * tls_cert_info_new()
  202  */
  203 
  204 tls_cert_info_t *tls_cert_info_new(void)
  205 {
  206     tls_cert_info_t *tci;
  207     int i;
  208 
  209     tci = xmalloc(sizeof(tls_cert_info_t));
  210     for (i = 0; i < 6; i++)
  211     {
  212         tci->owner_info[i] = NULL;
  213         tci->issuer_info[i] = NULL;
  214     }
  215 
  216     return tci;
  217 }
  218 
  219 
  220 /*
  221  * tls_cert_info_free()
  222  */
  223 
  224 void tls_cert_info_free(tls_cert_info_t *tci)
  225 {
  226     int i;
  227 
  228     if (tci)
  229     {
  230         for (i = 0; i < 6; i++)
  231         {
  232             free(tci->owner_info[i]);
  233             free(tci->issuer_info[i]);
  234         }
  235         free(tci);
  236     }
  237 }
  238 
  239 
  240 /*
  241  * asn1time_to_time_t() [OpenSSL only]
  242  *
  243  * Convert a ASN1 time string ([YY]YYMMDDhhmm[ss](Z)) into a time_t.
  244  * The flag 'is_utc' indicates whether the string is in UTC or GENERALIZED
  245  * format. GENERALIZED means a 4 digit year.
  246  * In case of invalid strings or over-/underflows, 1 is returned, and the value
  247  * of 't' is undefined. On success, 0 is returned.
  248  *
  249  * This code uses many ideas from GnuTLS code (lib/x509/common.c).
  250  * The transformation of struct tm to time_t is based on code from Russ Allbery
  251  * (rra@stanford.edu), who wrote a mktime_utc function and placed it under
  252  * public domain.
  253  */
  254 
  255 #ifdef HAVE_LIBSSL
  256 int is_leap(int year)
  257 {
  258     return (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0));
  259 }
  260 
  261 int asn1time_to_time_t(const char *asn1time, int is_utc, time_t *t)
  262 {
  263     size_t len;
  264     int i;
  265     size_t j;
  266     const char *p;
  267     char xx[3];
  268     char xxxx[5];
  269     const int monthdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  270     struct tm tm;
  271 
  272     len = strlen(asn1time);
  273     if ((is_utc && len < 10) || (!is_utc && len < 12))
  274     {
  275         goto error_exit;
  276     }
  277     for (j = 0; j < len - 1; j++)
  278     {
  279         if (!isdigit((unsigned char)asn1time[j]))
  280         {
  281             goto error_exit;
  282         }
  283     }
  284 
  285     xx[2] = '\0';
  286     xxxx[4] = '\0';
  287     p = asn1time;
  288     if (is_utc)
  289     {
  290         strncpy(xx, p, 2);
  291         tm.tm_year = atoi(xx);
  292         tm.tm_year += (tm.tm_year > 49) ? 1900 : 2000;
  293         p += 2;
  294     }
  295     else
  296     {
  297         strncpy(xxxx, p, 4);
  298         tm.tm_year = atoi(xxxx);
  299         p += 4;
  300     }
  301     strncpy(xx, p, 2);
  302     tm.tm_mon = atoi(xx) - 1;
  303     p += 2;
  304     strncpy(xx, p, 2);
  305     tm.tm_mday = atoi(xx);
  306     p += 2;
  307     strncpy(xx, p, 2);
  308     tm.tm_hour = atoi(xx);
  309     p += 2;
  310     strncpy(xx, p, 2);
  311     tm.tm_min = atoi(xx);
  312     p += 2;
  313     if (isdigit((unsigned char)(*p)))
  314     {
  315         strncpy(xx, p, 2);
  316         tm.tm_sec = atoi(xx);
  317     }
  318     else
  319     {
  320         tm.tm_sec = 0;
  321     }
  322 
  323     /* basic check for 32 bit time_t overflows. */
  324     if (sizeof(time_t) <= 4 && tm.tm_year >= 2038)
  325     {
  326         goto error_exit;
  327     }
  328     if (tm.tm_year < 1970 || tm.tm_mon < 0 || tm.tm_mon > 11)
  329     {
  330         goto error_exit;
  331     }
  332     *t = 0;
  333     for (i = 1970; i < tm.tm_year; i++)
  334     {
  335         *t += 365 + (is_leap(i) ? 1 : 0);
  336     }
  337     for (i = 0; i < tm.tm_mon; i++)
  338     {
  339         *t += monthdays[i];
  340     }
  341     if (tm.tm_mon > 1 && is_leap(tm.tm_year))
  342     {
  343         *t += 1;
  344     }
  345     *t = 24 * (*t + tm.tm_mday - 1) + tm.tm_hour;
  346     *t = 60 * (*t) + tm.tm_min;
  347     *t = 60 * (*t) + tm.tm_sec;
  348 
  349     return 0;
  350 
  351 error_exit:
  352     return 1;
  353 }
  354 #endif /* HAVE_LIBSSL */
  355 
  356 
  357 /*
  358  * tls_cert_info_get()
  359  *
  360  * see tls.h
  361  */
  362 
  363 int tls_cert_info_get(tls_t *tls, tls_cert_info_t *tci, char **errstr)
  364 {
  365 #ifdef HAVE_LIBGNUTLS
  366     const gnutls_datum_t *cert_list;
  367     unsigned int cert_list_size;
  368     gnutls_x509_crt_t cert;
  369     size_t size;
  370     const char *oid[6] = { GNUTLS_OID_X520_COMMON_NAME,
  371         GNUTLS_OID_X520_ORGANIZATION_NAME,
  372         GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
  373         GNUTLS_OID_X520_LOCALITY_NAME,
  374         GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME,
  375         GNUTLS_OID_X520_COUNTRY_NAME };
  376     int i;
  377     int e;
  378     char *p;
  379     const char *errmsg;
  380 
  381     errmsg = _("cannot get TLS certificate info");
  382     if (!(cert_list =
  383                 gnutls_certificate_get_peers(tls->session, &cert_list_size))
  384             || cert_list_size == 0)
  385     {
  386         *errstr = xasprintf(_("%s: no certificate was found"), errmsg);
  387         return TLS_ECERT;
  388     }
  389     if (gnutls_x509_crt_init(&cert) != 0)
  390     {
  391         *errstr = xasprintf(_("%s: cannot initialize certificate structure"),
  392                 errmsg);
  393         return TLS_ECERT;
  394     }
  395     if (gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER) != 0)
  396     {
  397         *errstr = xasprintf(_("%s: error parsing certificate"), errmsg);
  398         gnutls_x509_crt_deinit(cert);
  399         return TLS_ECERT;
  400     }
  401 
  402     /* certificate information */
  403     size = 32;
  404     if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256,
  405                 tci->sha256_fingerprint, &size) != 0)
  406     {
  407         *errstr = xasprintf(_("%s: error getting SHA256 fingerprint"), errmsg);
  408         gnutls_x509_crt_deinit(cert);
  409         return TLS_ECERT;
  410     }
  411     size = 20;
  412     if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA,
  413                 tci->sha1_fingerprint, &size) != 0)
  414     {
  415         *errstr = xasprintf(_("%s: error getting SHA1 fingerprint"), errmsg);
  416         gnutls_x509_crt_deinit(cert);
  417         return TLS_ECERT;
  418     }
  419     if ((tci->activation_time = gnutls_x509_crt_get_activation_time(cert)) < 0)
  420     {
  421         *errstr = xasprintf(_("%s: cannot get activation time"), errmsg);
  422         gnutls_x509_crt_deinit(cert);
  423         return TLS_ECERT;
  424     }
  425     if ((tci->expiration_time = gnutls_x509_crt_get_expiration_time(cert)) < 0)
  426     {
  427         *errstr = xasprintf(_("%s: cannot get expiration time"), errmsg);
  428         gnutls_x509_crt_deinit(cert);
  429         return TLS_ECERT;
  430     }
  431 
  432     /* owner information */
  433     for (i = 0; i < 6; i++)
  434     {
  435         size = 0;
  436         e = gnutls_x509_crt_get_dn_by_oid(cert, oid[i], 0, 0, NULL, &size);
  437         if (e == GNUTLS_E_SHORT_MEMORY_BUFFER)
  438         {
  439             p = xmalloc(size);
  440             e = gnutls_x509_crt_get_dn_by_oid(cert, oid[i], 0, 0, p, &size);
  441             if (e == 0)
  442             {
  443                 tci->owner_info[i] = p;
  444             }
  445             else
  446             {
  447                 free(p);
  448             }
  449         }
  450     }
  451 
  452     /* issuer information */
  453     for (i = 0; i < 6; i++)
  454     {
  455         size = 0;
  456         e = gnutls_x509_crt_get_issuer_dn_by_oid(
  457                 cert, oid[i], 0, 0, NULL, &size);
  458         if (e == GNUTLS_E_SHORT_MEMORY_BUFFER)
  459         {
  460             p = xmalloc(size);
  461             e = gnutls_x509_crt_get_issuer_dn_by_oid(
  462                     cert, oid[i], 0, 0, p, &size);
  463             if (e == 0)
  464             {
  465                 tci->issuer_info[i] = p;
  466             }
  467             else
  468             {
  469                 free(p);
  470             }
  471         }
  472     }
  473 
  474     gnutls_x509_crt_deinit(cert);
  475     return TLS_EOK;
  476 #endif /* HAVE_LIBGNUTLS */
  477 
  478 #ifdef HAVE_LIBSSL
  479     X509 *x509cert;
  480     X509_NAME *x509_subject;
  481     X509_NAME *x509_issuer;
  482     const ASN1_TIME *asn1time;
  483     int nid[6] = { NID_commonName,
  484         NID_organizationName,
  485         NID_organizationalUnitName,
  486         NID_localityName,
  487         NID_stateOrProvinceName,
  488         NID_countryName };
  489     int size;
  490     unsigned int usize;
  491     char *p;
  492     int i;
  493     const char *errmsg;
  494 
  495     errmsg = _("cannot get TLS certificate info");
  496     if (!(x509cert = SSL_get_peer_certificate(tls->ssl)))
  497     {
  498         *errstr = xasprintf(_("%s: no certificate was found"), errmsg);
  499         return TLS_ECERT;
  500     }
  501     if (!(x509_subject = X509_get_subject_name(x509cert)))
  502     {
  503         *errstr = xasprintf(_("%s: cannot get certificate subject"), errmsg);
  504         X509_free(x509cert);
  505         return TLS_ECERT;
  506     }
  507     if (!(x509_issuer = X509_get_issuer_name(x509cert)))
  508     {
  509         *errstr = xasprintf(_("%s: cannot get certificate issuer"), errmsg);
  510         X509_free(x509cert);
  511         return TLS_ECERT;
  512     }
  513 
  514     /* certificate information */
  515     usize = 32;
  516     if (!X509_digest(x509cert, EVP_sha256(), tci->sha256_fingerprint, &usize))
  517     {
  518         *errstr = xasprintf(_("%s: error getting SHA256 fingerprint"), errmsg);
  519         return TLS_ECERT;
  520     }
  521     usize = 20;
  522     if (!X509_digest(x509cert, EVP_sha1(), tci->sha1_fingerprint, &usize))
  523     {
  524         *errstr = xasprintf(_("%s: error getting SHA1 fingerprint"), errmsg);
  525         return TLS_ECERT;
  526     }
  527     asn1time = X509_get0_notBefore(x509cert);
  528     if (asn1time_to_time_t((const char *)asn1time->data,
  529                 (asn1time->type != V_ASN1_GENERALIZEDTIME),
  530                 &(tci->activation_time)) != 0)
  531     {
  532         *errstr = xasprintf(_("%s: cannot get activation time"), errmsg);
  533         X509_free(x509cert);
  534         tls_cert_info_free(tci);
  535         return TLS_ECERT;
  536     }
  537     asn1time = X509_get0_notAfter(x509cert);
  538     if (asn1time_to_time_t((const char *)asn1time->data,
  539                 (asn1time->type != V_ASN1_GENERALIZEDTIME),
  540                 &(tci->expiration_time)) != 0)
  541     {
  542         *errstr = xasprintf(_("%s: cannot get expiration time"), errmsg);
  543         X509_free(x509cert);
  544         tls_cert_info_free(tci);
  545         return TLS_ECERT;
  546     }
  547 
  548     /* owner information */
  549     for (i = 0; i < 6; i++)
  550     {
  551         size = X509_NAME_get_text_by_NID(x509_subject, nid[i], NULL, 0);
  552         size++;
  553         p = xmalloc((size_t)size);
  554         if (X509_NAME_get_text_by_NID(x509_subject, nid[i], p, size) != -1)
  555         {
  556             tci->owner_info[i] = p;
  557         }
  558         else
  559         {
  560             free(p);
  561         }
  562     }
  563 
  564     /* issuer information */
  565     for (i = 0; i < 6; i++)
  566     {
  567         size = X509_NAME_get_text_by_NID(x509_issuer, nid[i], NULL, 0);
  568         size++;
  569         p = xmalloc((size_t)size);
  570         if (X509_NAME_get_text_by_NID(x509_issuer, nid[i], p, size) != -1)
  571         {
  572             tci->issuer_info[i] = p;
  573         }
  574         else
  575         {
  576             free(p);
  577         }
  578     }
  579 
  580     X509_free(x509cert);
  581     return TLS_EOK;
  582 #endif /* HAVE_LIBSSL */
  583 }
  584 
  585 
  586 /*
  587  * tls_print_info()
  588  *
  589  * see tls.h
  590  */
  591 
  592 /* Convert the given time into a string. */
  593 static void tls_time_to_string(const time_t *t, char *buf, size_t bufsize)
  594 {
  595 #ifdef ENABLE_NLS
  596     (void)strftime(buf, bufsize, "%c", localtime(t));
  597 #else
  598     char *p;
  599 
  600     (void)snprintf(buf, bufsize, "%s", ctime(t));
  601     if ((p = strchr(buf, '\n')))
  602     {
  603         *p = '\0';
  604     }
  605 #endif
  606 }
  607 
  608 void tls_print_info(const char *tls_parameter_description,
  609         const tls_cert_info_t *tci)
  610 {
  611     const char *info_fieldname[6] = { N_("Common Name"), N_("Organization"),
  612         N_("Organizational unit"), N_("Locality"), N_("State or Province"),
  613         N_("Country") };
  614     char sha256_fingerprint_string[96];
  615     char sha1_fingerprint_string[60];
  616     char timebuf[128];          /* should be long enough for every locale */
  617     char *tmp;
  618     int i;
  619 
  620     printf(_("TLS session parameters:\n"));
  621     printf("    %s\n", tls_parameter_description
  622             ? tls_parameter_description : _("not available"));
  623 
  624     print_fingerprint(sha256_fingerprint_string, tci->sha256_fingerprint, 32);
  625     print_fingerprint(sha1_fingerprint_string, tci->sha1_fingerprint, 20);
  626 
  627     printf(_("TLS certificate information:\n"));
  628     printf("    %s:\n", _("Owner"));
  629     for (i = 0; i < 6; i++)
  630     {
  631         if (tci->owner_info[i])
  632         {
  633             tmp = xstrdup(tci->owner_info[i]);
  634             printf("        %s: %s\n", gettext(info_fieldname[i]),
  635                     sanitize_string(tmp));
  636             free(tmp);
  637         }
  638     }
  639     printf("    %s:\n", _("Issuer"));
  640     for (i = 0; i < 6; i++)
  641     {
  642         if (tci->issuer_info[i])
  643         {
  644             tmp = xstrdup(tci->issuer_info[i]);
  645             printf("        %s: %s\n", gettext(info_fieldname[i]),
  646                     sanitize_string(tmp));
  647             free(tmp);
  648         }
  649     }
  650     printf("    %s:\n", _("Validity"));
  651     tls_time_to_string(&tci->activation_time, timebuf, sizeof(timebuf));
  652     printf("        %s: %s\n", _("Activation time"), timebuf);
  653     tls_time_to_string(&tci->expiration_time, timebuf, sizeof(timebuf));
  654     printf("        %s: %s\n", _("Expiration time"), timebuf);
  655     printf("    %s:\n", _("Fingerprints"));
  656     printf("        SHA256: %s\n", sha256_fingerprint_string);
  657     printf("        SHA1 (deprecated): %s\n", sha1_fingerprint_string);
  658 }
  659 
  660 
  661 /*
  662  * [OpenSSL only] hostname_match()
  663  *
  664  * Compares the hostname with the name in the certificate. The certificate name
  665  * may include a wildcard as the leftmost domain component (its first two
  666  * characters are "*." in this case).
  667  *
  668  * Returns 1 if the names match, 0 otherwise.
  669  *
  670  * This is the same form of matching that gnutls_x509_crt_check_hostname() from
  671  * GnuTLS 1.2.0 uses.
  672  * It conforms to RFC2595 (Using TLS with IMAP, POP3 and ACAP), section 2.4.
  673  * RFC2818 (HTTP over TLS), section 3.1 says that `f*.com matches foo.com'. This
  674  * function does not allow that.
  675  * RFC3207 (SMTP Service Extension for Secure SMTP over Transport Layer
  676  * Security), section 4.1 says nothing more than `A SMTP client would probably
  677  * only want to authenticate an SMTP server whose server certificate has a
  678  * domain name that is the domain name that the client thought it was connecting
  679  * to'.
  680  */
  681 
  682 #ifdef HAVE_LIBSSL
  683 int hostname_match(const char *hostname, const char *certname)
  684 {
  685     const char *cmp1, *cmp2;
  686 
  687     if (strncmp(certname, "*.", 2) == 0)
  688     {
  689         cmp1 = certname + 2;
  690         cmp2 = strchr(hostname, '.');
  691         if (!cmp2)
  692         {
  693             return 0;
  694         }
  695         else
  696         {
  697             cmp2++;
  698         }
  699     }
  700     else
  701     {
  702         cmp1 = certname;
  703         cmp2 = hostname;
  704     }
  705 
  706     if (*cmp1 == '\0' || *cmp2 == '\0')
  707     {
  708         return 0;
  709     }
  710 
  711     if (strcasecmp(cmp1, cmp2) != 0)
  712     {
  713         return 0;
  714     }
  715 
  716     return 1;
  717 }
  718 #endif /* HAVE_LIBSSL */
  719 
  720 
  721 /*
  722  * tls_check_cert()
  723  *
  724  * If the 'tls->have_trust_file' flag is set, perform a real verification of
  725  * the peer's certificate. If this succeeds, the connection can be considered
  726  * secure.
  727  * If one of the 'tls->have_*_fingerprint' flags is
  728  * set, compare the 'tls->fingerprint' data with the peer certificate's
  729  * fingerprint. If this succeeds, the connection can be considered secure.
  730  * If none of these flags is set, perform only a few sanity checks of the
  731  * peer's certificate. You cannot trust the connection when this succeeds.
  732  * Used error codes: TLS_ECERT
  733  */
  734 
  735 int tls_check_cert(tls_t *tls, char **errstr)
  736 {
  737 #ifdef HAVE_LIBGNUTLS
  738     int error_code;
  739     const char *error_msg;
  740     unsigned int status;
  741     const gnutls_datum_t *cert_list;
  742     unsigned int cert_list_size;
  743     unsigned int i;
  744     gnutls_x509_crt_t cert;
  745     time_t t1, t2;
  746     size_t size;
  747     unsigned char fingerprint[32];
  748     char *idn_hostname = NULL;
  749 
  750     if (tls->have_trust_file
  751             || tls->have_sha256_fingerprint
  752             || tls->have_sha1_fingerprint
  753             || tls->have_md5_fingerprint)
  754     {
  755         error_msg = _("TLS certificate verification failed");
  756     }
  757     else
  758     {
  759         error_msg = _("TLS certificate check failed");
  760     }
  761 
  762     if (tls->have_sha256_fingerprint
  763             || tls->have_sha1_fingerprint || tls->have_md5_fingerprint)
  764     {
  765         /* If one of these matches, we trust the peer and do not perform any
  766          * other checks. */
  767         if (!(cert_list = gnutls_certificate_get_peers(
  768                         tls->session, &cert_list_size)))
  769         {
  770             *errstr = xasprintf(_("%s: no certificate was found"), error_msg);
  771             return TLS_ECERT;
  772         }
  773         if (gnutls_x509_crt_init(&cert) < 0)
  774         {
  775             *errstr = xasprintf(
  776                     _("%s: cannot initialize certificate structure"),
  777                     error_msg);
  778             return TLS_ECERT;
  779         }
  780         if (gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER)
  781                 < 0)
  782         {
  783             *errstr = xasprintf(_("%s: error parsing certificate %u of %u"),
  784                     error_msg, 0 + 1, cert_list_size);
  785             return TLS_ECERT;
  786         }
  787         if (tls->have_sha256_fingerprint)
  788         {
  789             size = 32;
  790             if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256,
  791                         fingerprint, &size) != 0)
  792             {
  793                 *errstr = xasprintf(_("%s: error getting SHA256 fingerprint"),
  794                         error_msg);
  795                 gnutls_x509_crt_deinit(cert);
  796                 return TLS_ECERT;
  797             }
  798             if (memcmp(fingerprint, tls->fingerprint, 32) != 0)
  799             {
  800                 *errstr = xasprintf(_("%s: the certificate fingerprint "
  801                             "does not match"), error_msg);
  802                 gnutls_x509_crt_deinit(cert);
  803                 return TLS_ECERT;
  804             }
  805         }
  806         else if (tls->have_sha1_fingerprint)
  807         {
  808             size = 20;
  809             if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA,
  810                         fingerprint, &size) != 0)
  811             {
  812                 *errstr = xasprintf(_("%s: error getting SHA1 fingerprint"),
  813                         error_msg);
  814                 gnutls_x509_crt_deinit(cert);
  815                 return TLS_ECERT;
  816             }
  817             if (memcmp(fingerprint, tls->fingerprint, 20) != 0)
  818             {
  819                 *errstr = xasprintf(_("%s: the certificate fingerprint "
  820                             "does not match"), error_msg);
  821                 gnutls_x509_crt_deinit(cert);
  822                 return TLS_ECERT;
  823             }
  824         }
  825         else
  826         {
  827             size = 16;
  828             if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5,
  829                         fingerprint, &size) != 0)
  830             {
  831                 *errstr = xasprintf(_("%s: error getting MD5 fingerprint"),
  832                         error_msg);
  833                 gnutls_x509_crt_deinit(cert);
  834                 return TLS_ECERT;
  835             }
  836             if (memcmp(fingerprint, tls->fingerprint, 16) != 0)
  837             {
  838                 *errstr = xasprintf(_("%s: the certificate fingerprint "
  839                             "does not match"), error_msg);
  840                 gnutls_x509_crt_deinit(cert);
  841                 return TLS_ECERT;
  842             }
  843         }
  844         gnutls_x509_crt_deinit(cert);
  845         return TLS_EOK;
  846     }
  847 
  848     /* If 'tls->have_trust_file' is true, this function uses the trusted CAs
  849      * in the credentials structure. So you must have installed one or more CA
  850      * certificates. */
  851     if ((error_code = gnutls_certificate_verify_peers2(tls->session,
  852                     &status)) != 0)
  853     {
  854         *errstr = xasprintf("%s: %s", error_msg, gnutls_strerror(error_code));
  855         return TLS_ECERT;
  856     }
  857     if (gnutls_certificate_type_get(tls->session) != GNUTLS_CRT_X509)
  858     {
  859         *errstr = xasprintf(_("%s: the certificate type is not X509"),
  860                 error_msg);
  861         return TLS_ECERT;
  862     }
  863     if (tls->have_trust_file)
  864     {
  865 #if GNUTLS_VERSION_NUMBER < 0x030200
  866         if (status & GNUTLS_CERT_REVOKED)
  867         {
  868             *errstr = xasprintf(_("%s: the certificate has been revoked"),
  869                     error_msg);
  870             return TLS_ECERT;
  871         }
  872         if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  873         {
  874             *errstr = xasprintf(
  875                     _("%s: the certificate hasn't got a known issuer"),
  876                     error_msg);
  877             return TLS_ECERT;
  878         }
  879         if (status & GNUTLS_CERT_INVALID)
  880         {
  881             *errstr = xasprintf(_("%s: the certificate is not trusted"),
  882                     error_msg);
  883             return TLS_ECERT;
  884         }
  885 #else
  886         if (status)
  887         {
  888             gnutls_datum_t txt;
  889             gnutls_certificate_verification_status_print(status,
  890                     GNUTLS_CRT_X509, &txt, 0);
  891             *errstr = xasprintf(_("%s: %s"), error_msg, txt.data);
  892             gnutls_free(txt.data);
  893             return TLS_ECERT;
  894         }
  895 #endif
  896     }
  897     if (!(cert_list = gnutls_certificate_get_peers(
  898                     tls->session, &cert_list_size)))
  899     {
  900         *errstr = xasprintf(_("%s: no certificate was found"), error_msg);
  901         return TLS_ECERT;
  902     }
  903     /* Needed to check times: */
  904     t1 = time(NULL);
  905     /* Check the certificate chain. All certificates in the chain must have
  906      * valid activation/expiration times. The first certificate in the chain is
  907      * the host's certificate; it must match the hostname. */
  908     for (i = 0; i < cert_list_size; i++)
  909     {
  910         if (gnutls_x509_crt_init(&cert) < 0)
  911         {
  912             *errstr = xasprintf(
  913                     _("%s: cannot initialize certificate structure"),
  914                     error_msg);
  915             return TLS_ECERT;
  916         }
  917         if (gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER)
  918                 < 0)
  919         {
  920             *errstr = xasprintf(_("%s: error parsing certificate %u of %u"),
  921                     error_msg, i + 1, cert_list_size);
  922             return TLS_ECERT;
  923         }
  924         /* Check hostname */
  925         if (i == 0)
  926         {
  927 #if GNUTLS_VERSION_NUMBER < 0x030400 && defined(HAVE_LIBIDN)
  928             idn2_to_ascii_lz(tls->hostname, &idn_hostname, IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL);
  929 #endif
  930             error_code = gnutls_x509_crt_check_hostname(cert,
  931                     idn_hostname ? idn_hostname : tls->hostname);
  932             free(idn_hostname);
  933             if (error_code == 0)
  934             {
  935                 *errstr = xasprintf(_("%s: the certificate owner does not "
  936                             "match hostname %s"), error_msg, tls->hostname);
  937                 return TLS_ECERT;
  938             }
  939         }
  940         /* Check certificate times */
  941         if ((t2 = gnutls_x509_crt_get_activation_time(cert)) < 0)
  942         {
  943             *errstr = xasprintf(_("%s: cannot get activation time for "
  944                         "certificate %u of %u"),
  945                     error_msg, i + 1, cert_list_size);
  946             return TLS_ECERT;
  947         }
  948         if (t2 > t1)
  949         {
  950             *errstr = xasprintf(
  951                     _("%s: certificate %u of %u is not yet activated"),
  952                     error_msg, i + 1, cert_list_size);
  953             return TLS_ECERT;
  954         }
  955         if ((t2 = gnutls_x509_crt_get_expiration_time(cert)) < 0)
  956         {
  957             *errstr = xasprintf(_("%s: cannot get expiration time for "
  958                         "certificate %u of %u"),
  959                     error_msg, i + 1, cert_list_size);
  960             return TLS_ECERT;
  961         }
  962         if (t2 < t1)
  963         {
  964             *errstr = xasprintf(_("%s: certificate %u of %u has expired"),
  965                     error_msg, i + 1, cert_list_size);
  966             return TLS_ECERT;
  967         }
  968         gnutls_x509_crt_deinit(cert);
  969     }
  970 
  971     return TLS_EOK;
  972 #endif /* HAVE_LIBGNUTLS */
  973 
  974 #ifdef HAVE_LIBSSL
  975     X509 *x509cert;
  976     long status;
  977     const char *error_msg;
  978     int i;
  979     /* hostname in ASCII format: */
  980     char *idn_hostname = NULL;
  981     /* needed to get the common name: */
  982     X509_NAME *x509_subject;
  983     char *buf;
  984     int length;
  985     /* needed to get the DNS subjectAltNames: */
  986     void *subj_alt_names;
  987     int subj_alt_names_count;
  988     GENERAL_NAME *subj_alt_name;
  989     /* did we find a name matching hostname? */
  990     int match_found;
  991     /* needed for fingerprint checking */
  992     unsigned int usize;
  993     unsigned char fingerprint[32];
  994 
  995 
  996     if (tls->have_trust_file)
  997     {
  998         error_msg = _("TLS certificate verification failed");
  999     }
 1000     else
 1001     {
 1002         error_msg = _("TLS certificate check failed");
 1003     }
 1004 
 1005     /* Get certificate */
 1006     if (!(x509cert = SSL_get_peer_certificate(tls->ssl)))
 1007     {
 1008         *errstr = xasprintf(_("%s: no certificate was sent"), error_msg);
 1009         return TLS_ECERT;
 1010     }
 1011 
 1012     if (tls->have_sha256_fingerprint
 1013             || tls->have_sha1_fingerprint || tls->have_md5_fingerprint)
 1014     {
 1015         /* If one of these matches, we trust the peer and do not perform any
 1016          * other checks. */
 1017         if (tls->have_sha256_fingerprint)
 1018         {
 1019             usize = 32;
 1020             if (!X509_digest(x509cert, EVP_sha256(), fingerprint, &usize))
 1021             {
 1022                 *errstr = xasprintf(_("%s: error getting SHA256 fingerprint"),
 1023                         error_msg);
 1024                 X509_free(x509cert);
 1025                 return TLS_ECERT;
 1026             }
 1027             if (memcmp(fingerprint, tls->fingerprint, 32) != 0)
 1028             {
 1029                 *errstr = xasprintf(_("%s: the certificate fingerprint "
 1030                             "does not match"), error_msg);
 1031                 X509_free(x509cert);
 1032                 return TLS_ECERT;
 1033             }
 1034         }
 1035         else if (tls->have_sha1_fingerprint)
 1036         {
 1037             usize = 20;
 1038             if (!X509_digest(x509cert, EVP_sha1(), fingerprint, &usize))
 1039             {
 1040                 *errstr = xasprintf(_("%s: error getting SHA1 fingerprint"),
 1041                         error_msg);
 1042                 X509_free(x509cert);
 1043                 return TLS_ECERT;
 1044             }
 1045             if (memcmp(fingerprint, tls->fingerprint, 20) != 0)
 1046             {
 1047                 *errstr = xasprintf(_("%s: the certificate fingerprint "
 1048                             "does not match"), error_msg);
 1049                 X509_free(x509cert);
 1050                 return TLS_ECERT;
 1051             }
 1052         }
 1053         else
 1054         {
 1055             usize = 16;
 1056             if (!X509_digest(x509cert, EVP_md5(), fingerprint, &usize))
 1057             {
 1058                 *errstr = xasprintf(_("%s: error getting MD5 fingerprint"),
 1059                         error_msg);
 1060                 X509_free(x509cert);
 1061                 return TLS_ECERT;
 1062             }
 1063             if (memcmp(fingerprint, tls->fingerprint, 16) != 0)
 1064             {
 1065                 *errstr = xasprintf(_("%s: the certificate fingerprint "
 1066                             "does not match"), error_msg);
 1067                 X509_free(x509cert);
 1068                 return TLS_ECERT;
 1069             }
 1070         }
 1071         X509_free(x509cert);
 1072         return TLS_EOK;
 1073     }
 1074 
 1075     /* Get result of OpenSSL's default verify function */
 1076     if ((status = SSL_get_verify_result(tls->ssl)) != X509_V_OK)
 1077     {
 1078         if (tls->have_trust_file
 1079                 || (status != X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
 1080                     && status != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
 1081                     && status != X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN))
 1082         {
 1083             *errstr = xasprintf("%s: %s", error_msg,
 1084                     X509_verify_cert_error_string(status));
 1085             X509_free(x509cert);
 1086             return TLS_ECERT;
 1087         }
 1088     }
 1089 
 1090     /* Check if 'hostname' matches the one of the subjectAltName extensions of
 1091      * type DNS or the Common Name (CN). */
 1092 
 1093 #ifdef HAVE_LIBIDN
 1094     idn2_to_ascii_lz(tls->hostname, &idn_hostname, IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL);
 1095 #endif
 1096 
 1097     /* Try the DNS subjectAltNames. */
 1098     match_found = 0;
 1099     if ((subj_alt_names =
 1100                 X509_get_ext_d2i(x509cert, NID_subject_alt_name, NULL, NULL)))
 1101     {
 1102         subj_alt_names_count = sk_GENERAL_NAME_num(subj_alt_names);
 1103         for (i = 0; i < subj_alt_names_count; i++)
 1104         {
 1105             subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
 1106             if (subj_alt_name->type == GEN_DNS)
 1107             {
 1108                 if ((size_t)(subj_alt_name->d.ia5->length)
 1109                         != strlen((char *)(subj_alt_name->d.ia5->data)))
 1110                 {
 1111                     *errstr = xasprintf(_("%s: certificate subject "
 1112                                 "alternative name contains NUL"), error_msg);
 1113                     X509_free(x509cert);
 1114                     free(idn_hostname);
 1115                     return TLS_ECERT;
 1116                 }
 1117                 if ((match_found = hostname_match(
 1118                                 idn_hostname ? idn_hostname : tls->hostname,
 1119                                 (char *)(subj_alt_name->d.ia5->data))))
 1120                 {
 1121                     break;
 1122                 }
 1123             }
 1124         }
 1125     }
 1126     if (!match_found)
 1127     {
 1128         /* Try the common name */
 1129         if (!(x509_subject = X509_get_subject_name(x509cert)))
 1130         {
 1131             *errstr = xasprintf(_("%s: cannot get certificate subject"),
 1132                     error_msg);
 1133             X509_free(x509cert);
 1134             free(idn_hostname);
 1135             return TLS_ECERT;
 1136         }
 1137         length = X509_NAME_get_text_by_NID(x509_subject, NID_commonName,
 1138                 NULL, 0);
 1139         buf = xmalloc((size_t)length + 1);
 1140         if (X509_NAME_get_text_by_NID(x509_subject, NID_commonName,
 1141                     buf, length + 1) == -1)
 1142         {
 1143             *errstr = xasprintf(_("%s: cannot get certificate common name"),
 1144                     error_msg);
 1145             X509_free(x509cert);
 1146             free(idn_hostname);
 1147             free(buf);
 1148             return TLS_ECERT;
 1149         }
 1150         if ((size_t)length != strlen(buf))
 1151         {
 1152             *errstr = xasprintf(_("%s: certificate common name contains NUL"),
 1153                     error_msg);
 1154             X509_free(x509cert);
 1155             free(idn_hostname);
 1156             free(buf);
 1157             return TLS_ECERT;
 1158         }
 1159         match_found = hostname_match(idn_hostname ? idn_hostname : tls->hostname,
 1160                 buf);
 1161         free(buf);
 1162     }
 1163     X509_free(x509cert);
 1164     free(idn_hostname);
 1165 
 1166     if (!match_found)
 1167     {
 1168         *errstr = xasprintf(
 1169                 _("%s: the certificate owner does not match hostname %s"),
 1170                 error_msg, tls->hostname);
 1171         return TLS_ECERT;
 1172     }
 1173 
 1174     return TLS_EOK;
 1175 #endif /* HAVE_LIBSSL */
 1176 }
 1177 
 1178 
 1179 /*
 1180  * tls_pin_callback()
 1181  *
 1182  * Passes a PIN to GnuTLS for PKCS11 smart cards or similar
 1183  */
 1184 #ifdef HAVE_LIBGNUTLS
 1185 static int tls_pin_callback(void *userdata, int attempt,
 1186         const char *token_url, const char *token_label,
 1187         unsigned int flags, char *pin, size_t pin_max)
 1188 {
 1189     (void)attempt;
 1190     (void)token_url;
 1191     (void)token_label;
 1192     (void)flags;
 1193 
 1194     size_t len;
 1195     if (userdata && (len = strlen(userdata)) < pin_max)
 1196     {
 1197         strcpy(pin, userdata);
 1198         return 0;
 1199     }
 1200     else
 1201     {
 1202         return 1;
 1203     }
 1204 }
 1205 #endif
 1206 
 1207 /*
 1208  * tls_init()
 1209  *
 1210  * see tls.h
 1211  */
 1212 
 1213 int tls_init(tls_t *tls,
 1214         const char *key_file, const char *cert_file, const char *pin,
 1215         const char *trust_file, const char *crl_file,
 1216         const unsigned char *sha256_fingerprint,
 1217         const unsigned char *sha1_fingerprint,
 1218         const unsigned char *md5_fingerprint,
 1219         int min_dh_prime_bits, const char *priorities,
 1220         const char *hostname,
 1221         int no_certcheck,
 1222         char **errstr)
 1223 {
 1224 #ifdef HAVE_LIBGNUTLS
 1225     int error_code;
 1226 
 1227     if ((error_code = gnutls_init(&tls->session, GNUTLS_CLIENT)) != 0)
 1228     {
 1229         *errstr = xasprintf(_("cannot initialize TLS session: %s"),
 1230                 gnutls_strerror(error_code));
 1231         return TLS_ELIBFAILED;
 1232     }
 1233     if (priorities)
 1234     {
 1235         const char *error_pos = NULL;
 1236         if ((error_code = gnutls_priority_set_direct(tls->session,
 1237                         priorities, &error_pos)) != 0)
 1238         {
 1239             if (error_pos)
 1240             {
 1241                 char *error_pos_str = xasprintf(
 1242                         _("error in priority string at position %d"),
 1243                         (int)(error_pos - priorities + 1));
 1244                 *errstr = xasprintf(
 1245                         _("cannot set priorities for TLS session: %s"),
 1246                         error_pos_str);
 1247                 free(error_pos_str);
 1248             }
 1249             else
 1250             {
 1251                 *errstr = xasprintf(
 1252                         _("cannot set priorities for TLS session: %s"),
 1253                         gnutls_strerror(error_code));
 1254             }
 1255             gnutls_deinit(tls->session);
 1256             return TLS_ELIBFAILED;
 1257         }
 1258     }
 1259     else
 1260     {
 1261         if ((error_code = gnutls_set_default_priority(tls->session)) != 0)
 1262         {
 1263             *errstr = xasprintf(_("cannot set default priority for TLS session: "
 1264                         "%s"), gnutls_strerror(error_code));
 1265             gnutls_deinit(tls->session);
 1266             return TLS_ELIBFAILED;
 1267         }
 1268     }
 1269     if (min_dh_prime_bits >= 0)
 1270     {
 1271         gnutls_dh_set_prime_bits(tls->session, min_dh_prime_bits);
 1272     }
 1273     if ((error_code = gnutls_certificate_allocate_credentials(&tls->cred)) < 0)
 1274     {
 1275         *errstr = xasprintf(
 1276                 _("cannot allocate certificate for TLS session: %s"),
 1277                 gnutls_strerror(error_code));
 1278         gnutls_deinit(tls->session);
 1279         return TLS_ELIBFAILED;
 1280     }
 1281     if (key_file && cert_file)
 1282     {
 1283         gnutls_pkcs11_set_pin_function(tls_pin_callback, (void*)pin);
 1284         if ((error_code = gnutls_certificate_set_x509_key_file(tls->cred,
 1285                         cert_file, key_file, GNUTLS_X509_FMT_PEM)) < 0)
 1286         {
 1287             *errstr = xasprintf(_("cannot set X509 key file %s and/or "
 1288                         "X509 cert file %s for TLS session: %s"),
 1289                     key_file, cert_file, gnutls_strerror(error_code));
 1290             gnutls_deinit(tls->session);
 1291             gnutls_certificate_free_credentials(tls->cred);
 1292             return TLS_EFILE;
 1293         }
 1294     }
 1295     if (trust_file
 1296             && !no_certcheck
 1297             && !sha256_fingerprint
 1298             && !sha1_fingerprint
 1299             && !md5_fingerprint)
 1300     {
 1301         if (strcmp(trust_file, "system") == 0)
 1302         {
 1303             if ((error_code = gnutls_certificate_set_x509_system_trust(
 1304                             tls->cred)) < 0)
 1305             {
 1306                 *errstr = xasprintf(
 1307                         _("cannot set X509 system trust for TLS session: %s"),
 1308                         gnutls_strerror(error_code));
 1309                 gnutls_deinit(tls->session);
 1310                 gnutls_certificate_free_credentials(tls->cred);
 1311                 return TLS_ELIBFAILED;
 1312             }
 1313         }
 1314         else
 1315         {
 1316             if ((error_code = gnutls_certificate_set_x509_trust_file(
 1317                             tls->cred, trust_file, GNUTLS_X509_FMT_PEM)) <= 0)
 1318             {
 1319                 *errstr = xasprintf(
 1320                         _("cannot set X509 trust file %s for TLS session: %s"),
 1321                         trust_file, gnutls_strerror(error_code));
 1322                 gnutls_deinit(tls->session);
 1323                 gnutls_certificate_free_credentials(tls->cred);
 1324                 return TLS_EFILE;
 1325             }
 1326         }
 1327         if (crl_file)
 1328         {
 1329             if ((error_code = gnutls_certificate_set_x509_crl_file(
 1330                             tls->cred, crl_file, GNUTLS_X509_FMT_PEM)) < 0)
 1331             {
 1332                 *errstr = xasprintf(
 1333                         _("cannot set X509 CRL file %s for TLS session: %s"),
 1334                         crl_file, gnutls_strerror(error_code));
 1335                 gnutls_deinit(tls->session);
 1336                 gnutls_certificate_free_credentials(tls->cred);
 1337                 return TLS_EFILE;
 1338             }
 1339         }
 1340         tls->have_trust_file = 1;
 1341     }
 1342     if (sha256_fingerprint && !no_certcheck)
 1343     {
 1344         memcpy(tls->fingerprint, sha256_fingerprint, 32);
 1345         tls->have_sha256_fingerprint = 1;
 1346     }
 1347     else if (sha1_fingerprint && !no_certcheck)
 1348     {
 1349         memcpy(tls->fingerprint, sha1_fingerprint, 20);
 1350         tls->have_sha1_fingerprint = 1;
 1351     }
 1352     else if (md5_fingerprint && !no_certcheck)
 1353     {
 1354         memcpy(tls->fingerprint, md5_fingerprint, 16);
 1355         tls->have_md5_fingerprint = 1;
 1356     }
 1357     if ((error_code = gnutls_credentials_set(tls->session,
 1358                     GNUTLS_CRD_CERTIFICATE, tls->cred)) < 0)
 1359     {
 1360         *errstr = xasprintf(_("cannot set credentials for TLS session: %s"),
 1361                 gnutls_strerror(error_code));
 1362         gnutls_deinit(tls->session);
 1363         gnutls_certificate_free_credentials(tls->cred);
 1364         return TLS_ELIBFAILED;
 1365     }
 1366     tls->no_certcheck = no_certcheck;
 1367     tls->hostname = xstrdup(hostname);
 1368     return TLS_EOK;
 1369 
 1370 #endif /* HAVE_LIBGNUTLS */
 1371 
 1372 #ifdef HAVE_LIBSSL
 1373 
 1374     const SSL_METHOD *ssl_method = SSLv23_client_method();
 1375 
 1376     /* FIXME: Implement support for 'min_dh_prime_bits' */
 1377     if (min_dh_prime_bits >= 0)
 1378     {
 1379         *errstr = xasprintf(
 1380                 _("cannot set minimum number of DH prime bits for TLS: %s"),
 1381                 _("feature not yet implemented for OpenSSL"));
 1382         return TLS_ELIBFAILED;
 1383     }
 1384     /* FIXME: Implement support for 'priorities' */
 1385     if (priorities)
 1386     {
 1387         *errstr = xasprintf(
 1388                 _("cannot set priorities for TLS session: %s"),
 1389                 _("feature not yet implemented for OpenSSL"));
 1390         return TLS_ELIBFAILED;
 1391     }
 1392     /* FIXME: Implement support for 'crl_file' */
 1393     if (trust_file && crl_file)
 1394     {
 1395         *errstr = xasprintf(
 1396                 _("cannot load CRL file: %s"),
 1397                 _("feature not yet implemented for OpenSSL"));
 1398         return TLS_ELIBFAILED;
 1399     }
 1400 
 1401     if (!ssl_method)
 1402     {
 1403         *errstr = xasprintf(_("cannot set TLS method"));
 1404         return TLS_ELIBFAILED;
 1405     }
 1406     if (!(tls->ssl_ctx = SSL_CTX_new(ssl_method)))
 1407     {
 1408         *errstr = xasprintf(_("cannot create TLS context: %s"),
 1409                 ERR_error_string(ERR_get_error(), NULL));
 1410         return TLS_ELIBFAILED;
 1411     }
 1412     /* SSLv2 and SSLv3 have known flaws. Disable them. */
 1413     (void)SSL_CTX_set_options(tls->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
 1414     if (key_file && cert_file)
 1415     {
 1416         if (SSL_CTX_use_PrivateKey_file(
 1417                     tls->ssl_ctx, key_file, SSL_FILETYPE_PEM) != 1)
 1418         {
 1419             *errstr = xasprintf(_("cannot load key file %s: %s"),
 1420                     key_file, ERR_error_string(ERR_get_error(), NULL));
 1421             SSL_CTX_free(tls->ssl_ctx);
 1422             tls->ssl_ctx = NULL;
 1423             return TLS_EFILE;
 1424         }
 1425         if (SSL_CTX_use_certificate_chain_file(tls->ssl_ctx, cert_file) != 1)
 1426         {
 1427             *errstr = xasprintf(_("cannot load certificate file %s: %s"),
 1428                     cert_file, ERR_error_string(ERR_get_error(), NULL));
 1429             SSL_CTX_free(tls->ssl_ctx);
 1430             tls->ssl_ctx = NULL;
 1431             return TLS_EFILE;
 1432         }
 1433     }
 1434     if (trust_file
 1435             && !no_certcheck
 1436             && !sha256_fingerprint
 1437             && !sha1_fingerprint
 1438             && !md5_fingerprint)
 1439     {
 1440         if (strcmp(trust_file, "system") == 0)
 1441         {
 1442             if (SSL_CTX_set_default_verify_paths(tls->ssl_ctx) != 1)
 1443             {
 1444                 *errstr = xasprintf(_("cannot set X509 system trust for TLS session: %s"),
 1445                         ERR_error_string(ERR_get_error(), NULL));
 1446                 SSL_CTX_free(tls->ssl_ctx);
 1447                 tls->ssl_ctx = NULL;
 1448                 return TLS_EFILE;
 1449             }
 1450         }
 1451         else
 1452         {
 1453             if (SSL_CTX_load_verify_locations(tls->ssl_ctx, trust_file, NULL) != 1)
 1454             {
 1455                 *errstr = xasprintf(_("cannot load trust file %s: %s"),
 1456                         trust_file, ERR_error_string(ERR_get_error(), NULL));
 1457                 SSL_CTX_free(tls->ssl_ctx);
 1458                 tls->ssl_ctx = NULL;
 1459                 return TLS_EFILE;
 1460             }
 1461         }
 1462         tls->have_trust_file = 1;
 1463     }
 1464     if (sha256_fingerprint && !no_certcheck)
 1465     {
 1466         memcpy(tls->fingerprint, sha256_fingerprint, 32);
 1467         tls->have_sha256_fingerprint = 1;
 1468     }
 1469     else if (sha1_fingerprint && !no_certcheck)
 1470     {
 1471         memcpy(tls->fingerprint, sha1_fingerprint, 20);
 1472         tls->have_sha1_fingerprint = 1;
 1473     }
 1474     else if (md5_fingerprint && !no_certcheck)
 1475     {
 1476         memcpy(tls->fingerprint, md5_fingerprint, 16);
 1477         tls->have_md5_fingerprint = 1;
 1478     }
 1479     if (!(tls->ssl = SSL_new(tls->ssl_ctx)))
 1480     {
 1481         *errstr = xasprintf(_("cannot create a TLS structure: %s"),
 1482                 ERR_error_string(ERR_get_error(), NULL));
 1483         SSL_CTX_free(tls->ssl_ctx);
 1484         tls->ssl_ctx = NULL;
 1485         return TLS_ELIBFAILED;
 1486     }
 1487     tls->no_certcheck = no_certcheck;
 1488     tls->hostname = xstrdup(hostname);
 1489     return TLS_EOK;
 1490 
 1491 #endif /* HAVE_LIBSSL */
 1492 }
 1493 
 1494 
 1495 /*
 1496  * openssl_io_error()
 1497  *
 1498  * Used only internally by the OpenSSL code.
 1499  *
 1500  * Construct an error line according to 'error_code' (which originates from an
 1501  * SSL_read(), SSL_write() or SSL_connect() operation) and 'error_code2' (which
 1502  * originates from an SSL_get_error() call with 'error_code' as its argument).
 1503  * The line will read: "error_string: error_reason". 'error_string' is given by
 1504  * the calling function, this function finds out 'error_reason'.
 1505  * The resulting string will be returned in an allocated string.
 1506  * OpenSSL error strings are max 120 characters long according to
 1507  * ERR_error_string(3).
 1508  */
 1509 
 1510 #ifdef HAVE_LIBSSL
 1511 char *openssl_io_error(int error_code, int error_code2,
 1512         const char *error_string)
 1513 {
 1514     unsigned long error_code3;
 1515     const char *error_reason;
 1516 
 1517     switch (error_code2)
 1518     {
 1519         case SSL_ERROR_SYSCALL:
 1520             error_code3 = ERR_get_error();
 1521             if (error_code3 == 0)
 1522             {
 1523                 if (error_code == 0)
 1524                 {
 1525                     error_reason = _("a protocol violating EOF occurred");
 1526                 }
 1527                 else if (error_code == -1)
 1528                 {
 1529                     error_reason = strerror(errno);
 1530                 }
 1531                 else
 1532                 {
 1533                     error_reason = _("unknown error");
 1534                 }
 1535             }
 1536             else
 1537             {
 1538                 error_reason = ERR_error_string(error_code3, NULL);
 1539             }
 1540             break;
 1541 
 1542         case SSL_ERROR_ZERO_RETURN:
 1543             error_reason = _("the connection was closed unexpectedly");
 1544             break;
 1545 
 1546         case SSL_ERROR_SSL:
 1547             error_reason = ERR_error_string(ERR_get_error(), NULL);
 1548             break;
 1549 
 1550         case SSL_ERROR_WANT_READ:
 1551         case SSL_ERROR_WANT_WRITE:
 1552             error_reason = _("the operation timed out");
 1553             break;
 1554 
 1555         default:
 1556             /* probably SSL_ERROR_NONE */
 1557             error_reason = _("unknown error");
 1558             break;
 1559     }
 1560     return xasprintf("%s: %s", error_string, error_reason);
 1561 }
 1562 #endif /* HAVE_LIBSSL */
 1563 
 1564 
 1565 /*
 1566  * tls_start()
 1567  *
 1568  * see tls.h
 1569  */
 1570 
 1571 int tls_start(tls_t *tls, int fd,
 1572         tls_cert_info_t *tci, char **tls_parameter_description, char **errstr)
 1573 {
 1574 #ifdef HAVE_LIBGNUTLS
 1575     int error_code;
 1576 
 1577     gnutls_server_name_set(tls->session, GNUTLS_NAME_DNS, tls->hostname, strlen(tls->hostname));
 1578 #if GNUTLS_VERSION_NUMBER < 0x030200
 1579     gnutls_transport_set_ptr(tls->session, (gnutls_transport_ptr_t)fd);
 1580 #else
 1581     gnutls_transport_set_int(tls->session, fd);
 1582 #endif
 1583     do
 1584     {
 1585         error_code = gnutls_handshake(tls->session);
 1586     }
 1587     while (error_code < 0 && gnutls_error_is_fatal(error_code) == 0);
 1588 
 1589     if (error_code != 0)
 1590     {
 1591         *errstr = xasprintf(_("TLS handshake failed: %s"),
 1592                 gnutls_strerror(error_code));
 1593         gnutls_deinit(tls->session);
 1594         gnutls_certificate_free_credentials(tls->cred);
 1595         return TLS_EHANDSHAKE;
 1596     }
 1597     if (tci)
 1598     {
 1599         if ((error_code = tls_cert_info_get(tls, tci, errstr)) != TLS_EOK)
 1600         {
 1601             gnutls_deinit(tls->session);
 1602             gnutls_certificate_free_credentials(tls->cred);
 1603             return error_code;
 1604         }
 1605     }
 1606     if (tls_parameter_description)
 1607     {
 1608         *tls_parameter_description = gnutls_session_get_desc(tls->session);
 1609     }
 1610     if (!tls->no_certcheck)
 1611     {
 1612         if ((error_code = tls_check_cert(tls, errstr)) != TLS_EOK)
 1613         {
 1614             gnutls_deinit(tls->session);
 1615             gnutls_certificate_free_credentials(tls->cred);
 1616             return error_code;
 1617         }
 1618     }
 1619     tls->is_active = 1;
 1620     return TLS_EOK;
 1621 #endif /* HAVE_LIBGNUTLS */
 1622 
 1623 #ifdef HAVE_LIBSSL
 1624     int error_code;
 1625 
 1626     if (!SSL_set_fd(tls->ssl, fd))
 1627     {
 1628         *errstr = xasprintf(_("cannot set the file descriptor for TLS: %s"),
 1629                 ERR_error_string(ERR_get_error(), NULL));
 1630         SSL_free(tls->ssl);
 1631         SSL_CTX_free(tls->ssl_ctx);
 1632         return TLS_ELIBFAILED;
 1633     }
 1634     if ((error_code = SSL_connect(tls->ssl)) < 1)
 1635     {
 1636         if (errno == EINTR
 1637                 && (SSL_get_error(tls->ssl, error_code) == SSL_ERROR_WANT_READ
 1638                     || SSL_get_error(tls->ssl, error_code)
 1639                     == SSL_ERROR_WANT_WRITE))
 1640         {
 1641             *errstr = xasprintf(_("operation aborted"));
 1642         }
 1643         else
 1644         {
 1645             *errstr = openssl_io_error(error_code,
 1646                     SSL_get_error(tls->ssl, error_code),
 1647                     _("TLS handshake failed"));
 1648         }
 1649         SSL_free(tls->ssl);
 1650         SSL_CTX_free(tls->ssl_ctx);
 1651         return TLS_EIO;
 1652     }
 1653     if (tci)
 1654     {
 1655         if ((error_code = tls_cert_info_get(tls, tci, errstr)) != TLS_EOK)
 1656         {
 1657             SSL_free(tls->ssl);
 1658             SSL_CTX_free(tls->ssl_ctx);
 1659             return error_code;
 1660         }
 1661     }
 1662     if (tls_parameter_description)
 1663     {
 1664         *tls_parameter_description = NULL; /* TODO */
 1665     }
 1666     if (!tls->no_certcheck)
 1667     {
 1668         if ((error_code = tls_check_cert(tls, errstr)) != TLS_EOK)
 1669         {
 1670             SSL_free(tls->ssl);
 1671             SSL_CTX_free(tls->ssl_ctx);
 1672             return error_code;
 1673         }
 1674     }
 1675     tls->is_active = 1;
 1676     return TLS_EOK;
 1677 #endif /* HAVE_LIBSSL */
 1678 }
 1679 
 1680 
 1681 /*
 1682  * tls_readbuf_read()
 1683  *
 1684  * Wraps TLS read function to provide buffering for tls_gets().
 1685  */
 1686 
 1687 int tls_readbuf_read(tls_t *tls, readbuf_t *readbuf, char *ptr,
 1688         char **errstr)
 1689 {
 1690 #ifdef HAVE_LIBGNUTLS
 1691 
 1692     ssize_t ret;
 1693 
 1694     if (readbuf->count <= 0)
 1695     {
 1696         do
 1697         {
 1698             ret = gnutls_record_recv(tls->session,
 1699                     readbuf->buf, sizeof(readbuf->buf));
 1700         }
 1701         while (ret == GNUTLS_E_AGAIN);
 1702         if (ret < 0)
 1703         {
 1704             if (ret == GNUTLS_E_INTERRUPTED)
 1705             {
 1706                 *errstr = xasprintf(_("operation aborted"));
 1707             }
 1708             else
 1709             {
 1710                 *errstr = xasprintf(_("cannot read from TLS connection: %s"),
 1711                         gnutls_strerror(ret));
 1712             }
 1713             return TLS_EIO;
 1714         }
 1715         else if (ret == 0)
 1716         {
 1717             return 0;
 1718         }
 1719         readbuf->count = (int)ret;
 1720         readbuf->ptr = readbuf->buf;
 1721     }
 1722     readbuf->count--;
 1723     *ptr = *((readbuf->ptr)++);
 1724     return 1;
 1725 
 1726 #endif /* HAVE_LIBGNUTLS */
 1727 
 1728 #ifdef HAVE_LIBSSL
 1729 
 1730     int ret;
 1731     int error_code;
 1732 
 1733     if (readbuf->count <= 0)
 1734     {
 1735         ret = SSL_read(tls->ssl, readbuf->buf, sizeof(readbuf->buf));
 1736         if (ret < 1)
 1737         {
 1738             if ((error_code = SSL_get_error(tls->ssl, ret)) == SSL_ERROR_NONE)
 1739             {
 1740                 return 0;
 1741             }
 1742             else
 1743             {
 1744                 if (errno == EINTR
 1745                         && (SSL_get_error(tls->ssl, ret) == SSL_ERROR_WANT_READ
 1746                             || SSL_get_error(tls->ssl, ret)
 1747                             == SSL_ERROR_WANT_WRITE))
 1748                 {
 1749                     *errstr = xasprintf(_("operation aborted"));
 1750                 }
 1751                 else
 1752                 {
 1753                     *errstr = openssl_io_error(ret, error_code,
 1754                             _("cannot read from TLS connection"));
 1755                 }
 1756                 return TLS_EIO;
 1757             }
 1758         }
 1759         readbuf->count = ret;
 1760         readbuf->ptr = readbuf->buf;
 1761     }
 1762     readbuf->count--;
 1763     *ptr = *((readbuf->ptr)++);
 1764     return 1;
 1765 
 1766 #endif /* HAVE_LIBSSL */
 1767 }
 1768 
 1769 
 1770 /*
 1771  * tls_gets()
 1772  *
 1773  * see tls.h
 1774  */
 1775 
 1776 int tls_gets(tls_t *tls, readbuf_t *readbuf,
 1777         char *str, size_t size, size_t *len, char **errstr)
 1778 {
 1779     char c;
 1780     size_t i;
 1781     int ret;
 1782 
 1783     i = 0;
 1784     while (i + 1 < size)
 1785     {
 1786         if ((ret = tls_readbuf_read(tls, readbuf, &c, errstr)) == 1)
 1787         {
 1788             str[i++] = c;
 1789             if (c == '\n')
 1790             {
 1791                 break;
 1792             }
 1793         }
 1794         else if (ret == 0)
 1795         {
 1796             break;
 1797         }
 1798         else
 1799         {
 1800             return TLS_EIO;
 1801         }
 1802     }
 1803     str[i] = '\0';
 1804     *len = i;
 1805     return TLS_EOK;
 1806 }
 1807 
 1808 
 1809 /*
 1810  * tls_puts()
 1811  *
 1812  * see tls.h
 1813  */
 1814 
 1815 int tls_puts(tls_t *tls, const char *s, size_t len, char **errstr)
 1816 {
 1817 #ifdef HAVE_LIBGNUTLS
 1818 
 1819     ssize_t ret;
 1820 
 1821     if (len < 1)
 1822     {
 1823         /* nothing to be done */
 1824         return TLS_EOK;
 1825     }
 1826 
 1827     do
 1828     {
 1829         ret = gnutls_record_send(tls->session, s, len);
 1830     }
 1831     while (ret == GNUTLS_E_AGAIN);
 1832     if (ret < 0)
 1833     {
 1834         if (ret == GNUTLS_E_INTERRUPTED)
 1835         {
 1836             *errstr = xasprintf(_("operation aborted"));
 1837         }
 1838         else
 1839         {
 1840             *errstr = xasprintf(_("cannot write to TLS connection: %s"),
 1841                     gnutls_strerror(ret));
 1842         }
 1843         return TLS_EIO;
 1844     }
 1845     else if ((size_t)ret == len)
 1846     {
 1847         return TLS_EOK;
 1848     }
 1849     else /* 0 <= error_code < len */
 1850     {
 1851         *errstr = xasprintf(_("cannot write to TLS connection: %s"),
 1852                 _("unknown error"));
 1853         return TLS_EIO;
 1854     }
 1855 
 1856 #endif /* HAVE_LIBGNUTLS */
 1857 
 1858 #ifdef HAVE_LIBSSL
 1859 
 1860     int error_code;
 1861 
 1862     if (len < 1)
 1863     {
 1864         /* nothing to be done */
 1865         return TLS_EOK;
 1866     }
 1867 
 1868     if ((error_code = SSL_write(tls->ssl, s, (int)len)) != (int)len)
 1869     {
 1870         if (errno == EINTR
 1871                 && ((SSL_get_error(tls->ssl, error_code) == SSL_ERROR_WANT_READ
 1872                         || SSL_get_error(tls->ssl, error_code)
 1873                         == SSL_ERROR_WANT_WRITE)))
 1874         {
 1875             *errstr = xasprintf(_("operation aborted"));
 1876         }
 1877         else
 1878         {
 1879             *errstr = openssl_io_error(error_code,
 1880                     SSL_get_error(tls->ssl, error_code),
 1881                     _("cannot write to TLS connection"));
 1882         }
 1883         return TLS_EIO;
 1884     }
 1885 
 1886     return TLS_EOK;
 1887 
 1888 #endif /* HAVE_LIBSSL */
 1889 }
 1890 
 1891 
 1892 /*
 1893  * tls_close()
 1894  *
 1895  * see tls.h
 1896  */
 1897 
 1898 void tls_close(tls_t *tls)
 1899 {
 1900     if (tls->is_active)
 1901     {
 1902 #ifdef HAVE_LIBGNUTLS
 1903         int e;
 1904         do
 1905         {
 1906             e = gnutls_bye(tls->session, GNUTLS_SHUT_WR);
 1907         }
 1908         while (e == GNUTLS_E_AGAIN);
 1909         gnutls_deinit(tls->session);
 1910         gnutls_certificate_free_credentials(tls->cred);
 1911 #endif /* HAVE_LIBGNUTLS */
 1912 #ifdef HAVE_LIBSSL
 1913         SSL_shutdown(tls->ssl);
 1914         SSL_free(tls->ssl);
 1915         SSL_CTX_free(tls->ssl_ctx);
 1916 #endif /* HAVE_LIBSSL */
 1917     }
 1918     if (tls->hostname)
 1919     {
 1920         free(tls->hostname);
 1921     }
 1922     tls_clear(tls);
 1923 }
 1924 
 1925 
 1926 /*
 1927  * tls_lib_deinit()
 1928  *
 1929  * see tls.h
 1930  */
 1931 
 1932 void tls_lib_deinit(void)
 1933 {
 1934 #ifdef HAVE_LIBGNUTLS
 1935     gnutls_global_deinit();
 1936 #endif /* HAVE_LIBGNUTLS */
 1937 }
 1938 
 1939 
 1940 /*
 1941  * tls_exitcode()
 1942  *
 1943  * see tls.h
 1944  */
 1945 
 1946 int tls_exitcode(int tls_error_code)
 1947 {
 1948     switch (tls_error_code)
 1949     {
 1950         case TLS_EIO:
 1951             return EX_IOERR;
 1952         case TLS_EFILE:
 1953             return EX_NOINPUT;
 1954         case TLS_EHANDSHAKE:
 1955             return EX_PROTOCOL;
 1956         case TLS_ECERT:
 1957             /* did not find anything better... */
 1958             return EX_UNAVAILABLE;
 1959         case TLS_ELIBFAILED:
 1960         case TLS_ESEED:
 1961         default:
 1962             return EX_SOFTWARE;
 1963     }
 1964 }