tls.c
Go to the documentation of this file.
1 /* ========================================================================== */
2 /*! \file
3  * \brief Transport layer security
4  *
5  * Copyright (c) 2012-2022 by the developers. See the LICENSE file for details.
6  *
7  * If nothing else is specified, function return zero to indicate success
8  * and a negative value to indicate an error.
9  */
10 
11 
12 /* ========================================================================== */
13 /* Include headers */
14 
15 #include "posix.h" /* Include this first because of feature test macros */
16 
17 #include "config.h"
18 
19 #if CFG_USE_TLS /* This requires data from "config.h" */
20 # include <openssl/crypto.h>
21 # include <openssl/asn1.h>
22 # include <openssl/bio.h>
23 # include <openssl/err.h>
24 # include <openssl/evp.h>
25 # include <openssl/objects.h>
26 # include <openssl/opensslv.h>
27 # include <openssl/rand.h>
28 # include <openssl/rsa.h>
29 # include <openssl/ssl.h>
30 # include <openssl/x509.h>
31 # include <openssl/x509v3.h>
32 # include <openssl/x509_vfy.h>
33 #endif /* CFG_USE_TLS */
34 #include <string.h>
35 
36 #include "conf.h" /* For CRL update configuration */
37 #include "digest.h" /* For public key randomart images */
38 #include "encoding.h" /* For CRL update timestamp conversion */
39 #include "extutils.h" /* For CRL download */
40 #include "fileutils.h"
41 #include "main.h"
42 #include "tls.h"
43 #include "xdg.h"
44 
45 
46 /* ========================================================================== */
47 /*! \defgroup TLS TLS: Transport Layer Security
48  *
49  * This module provides optional support for an encrypted connection to the
50  * server. It is intended to follow RFC 2246, RFC 4346, RFC 5246, RFC 7366,
51  * RFC 7507, RFC 7627 and RFC 8446 (depending on the underlying OpenSSL
52  * library). OpenSSL 1.0.0 is the oldest supported version.
53  * For full functionality at least OpenSSL 3.0.0 is required.
54  *
55  * The server to client authentication based on X.509 certificates should be
56  * RFC 1422 and RFC 5280 conformant.
57  *
58  * \attention
59  * It is required that 'SSIZE_MAX' is at least 'INT_MAX' (must be checked by
60  * build system).
61  *
62  * \attention
63  * We have no own source for random numbers. OpenSSL must be configured to be
64  * able to fetch random numbers itself. If the operating system provides no
65  * random number generator (RNG), there must be a separate one installed that
66  * OpenSSL can use (consider egd or prngd if your OS provides no such option).
67  * If OpenSSL reports there is no RNG available, the program fails to start.
68  *
69  * By default only cipher suites using ephemeral Diffie-Hellman-Merkle key
70  * exchange (to provide forward secrecy) and strong symmetric data encryption
71  * algorithms are offered to the server.
72  * In the past (until RFC 8143 was released), RFC 4642 defined the weak cipher
73  * suite RSA-RSA-RC4-MD5 as mandatory. It can still be added to the list
74  * together with some other cipher suites that are considered weak (without
75  * forward secrecy or based on elliptic curves). This option is selected with
76  * a parameter of the \c tls_open() function.
77  * This will also add the weak cipher suite RSA-RSA-AES128-SHA that is defined
78  * as mandatory by RFC 5246.
79  *
80  * According to RFC 6176 and RFC 7568 the SSL protocol is never negotiated and
81  * the TLS protocol used instead.
82  *
83  * We never offer anonymous cipher suites to the server. Therefore while the
84  * encrypted connection is established, the server must present a certificate.
85  * This certificate can optionally be verified for server to client
86  * authentication with the function \c tls_cert_verify() . This will ensure
87  * that a trusted CA is the root of the certificate chain and that the subject
88  * of the last certificate contains the hostname we have resolved to connect the
89  * server.
90  */
91 /*! @{ */
92 
93 
94 #if CFG_USE_TLS
95 
96 
97 /* ========================================================================== */
98 /* Constants */
99 
100 /*! \brief Message prefix for TLS module */
101 #define MAIN_ERR_PREFIX "TLS: "
102 
103 /*! \brief Set this to 1 to accept wildcard for left-most component of X.509
104  * certificate subjects
105  *
106  * \note
107  * RFC 8143 specifies this as valid with regard to the NNTP protocol, therefore
108  * the value 1 is the default.
109  */
110 # define CFG_USE_TLS_WILDCARD_SUBJECT 1
111 
112 /*! \brief Cipher suite list for TLSv1.3
113  *
114  * This list of cipher suites is ignored for older protocol versions.
115  */
116 # define TLS_CIPHERS_TLS13 "TLS_AES_256_GCM_SHA384" \
117  ":TLS_CHACHA20_POLY1305_SHA256" \
118  ":TLS_AES_128_GCM_SHA256" \
119  ":TLS_AES_128_CCM_SHA256"
120 
121 /*! \brief Default (strong) cipher suite list for TLSv1.0 to TLSv1.2 protocols
122  *
123  * This list of cipher suites is the default. It is possible to use weaker
124  * cipher suites when a connection is opened. See \ref tls_open() for details.
125  *
126  * This list contains only cipher suites that provide forward secrecy by using
127  * ephemeral Diffie-Hellman-Merkle key exchange.
128  *
129  * TLSv1.2 protocol is preferred (if the OpenSSL library supports it).
130  *
131  * Cipher suites that use DSA or ECDSA based authentication are excluded
132  * because both are very dependent on a high quality RNG for its nonce and the
133  * key length of DSA for TLS is effectively limited to 1024 bit.
134  *
135  * ECC-based key exchange is excluded because the DHE group check code currently
136  * can't handle it.
137  *
138  * \note
139  * The size of the FFDHE group provided by the server is relevant for the
140  * strength of the encryption and the forward secrecy. Unfortunately it can't
141  * be checked with OpenSSL 1.0 (at least OpenSSL 1.1 API required).
142  * If the OpenSSL 3 API is available, the FFDHE groups defined in RFC 7919 are
143  * offered for negotiation.
144  *
145  * \note
146  * The tag \c !SSLv2 in the list means the corresponding cipher suites not the
147  * SSLv2 protocol.
148  *
149  * \attention
150  * Ensure that this list never contains anonymous cipher suites. Otherwise the
151  * server doesn't present a certificate and the authenticity check will fail.
152  */
153 # define TLS_CIPHERS_DEFAULT \
154  "!SSLv2:!RC2:!RC4:!DES:!3DES:!MD5:!kEECDH:!aNULL:!aDSS:!aECDSA" \
155  ":kEDH+HIGH@STRENGTH:-SSLv3:kEDH+HIGH:!AESCCM8"
156 
157 /*! \brief Optional (weak) cipher suite list for TLSv1.0 to TLSv1.2 protocols
158  *
159  * This list contains cipher suites that are considered weak for better
160  * compatibility to existing servers. Some obsolete standards like RFC 4642
161  * defined some of the weak algorithms as mandatory in the past and we support
162  * them for backward compatibility.
163  *
164  * \note
165  * The tag \c !SSLv2 in the list means the corresponding cipher suites not the
166  * SSLv2 protocol.
167  *
168  * \attention
169  * Ensure that this list never contains anonymous cipher suites. Otherwise the
170  * server doesn't present a certificate and the authenticity check will fail.
171  */
172 # define TLS_CIPHERS_WEAK \
173  "!SSLv2:!RC2:!DES:!aNULL:!aDSS:!aECDSA" \
174  /* Strong symmetric algorithms and forward secrecy first */ \
175  ":kEDH+HIGH:kEECDH+HIGH:-SSLv3:kEDH+HIGH:kEECDH+HIGH" \
176  ":-3DES:kEDH+HIGH:kEECDH+HIGH" \
177  /* Strong symmetric algorithms and no forward secrecy next */ \
178  ":AES256-GCM-SHA384:CAMELLIA256-SHA:AES128-SHA" \
179  /* Weak symmetric algorithms and no forward secrecy last */ \
180  ":RC4-MD5"
181 
182 /*! \brief Additional signature algorithms for TLSv1.3 protocol
183  *
184  * This list contains the signature algorithms offered in order of decreasing
185  * preference.
186  *
187  * For TLSv1.3 the signature scheme names as defined in RFC 8446 (Section 4.2.3)
188  * are supported by OpenSSL. We use them here to make it obvious which codes
189  * will be offered in the Client Hello message.
190  *
191  * \attention
192  * RFC 8446 defines the algorithm ecdsa_secp256r1_sha256 as mandatory for the
193  * TLSv1.3 protocol. Avoiding ECC is no longer allowed!
194  *
195  * \note
196  * The algorithms for TLSv1.2 above use RSASSA-PKCS1-v1_5. For TLSv1.3 they
197  * are no longer allowed except for certificates. We omit the separate
198  * negotiation for the certificate signature algorithms. The old algorithms
199  * below are appended to the end of this list (with lowest preference).
200  */
201 # define TLS_SIGALGS_TLS13 \
202  "rsa_pss_rsae_sha512:rsa_pss_rsae_sha384:rsa_pss_rsae_sha256" \
203  /* Offer ECC-based signatures for TLSv1.3 only */ \
204  ":ecdsa_secp521r1_sha512:ecdsa_secp256r1_sha256"
205 
206 /*! \brief Signature algorithms for TLSv1.2 protocol
207  *
208  * This list contains the signature algorithms offered in order of decreasing
209  * preference.
210  *
211  * The signature algorithm cannot be negotiated with the TLSv1.0 and TLSv1.1
212  * protocols.
213  * This algorithm list is intended for all signatures in the TLSv1.2 protocol
214  * (including key exchange and signatures in certificates).
215  *
216  * We only offer hash algorithms from the SHA-2 family (this means MD5 and SHA-1
217  * are not used for negotiation).
218  *
219  * \attention
220  * The asymmetric cipher must always be RSA because certificates with DSA or
221  * ECDSA keys are not supported for TLSv1.2 in strong mode.
222  */
223 # define TLS_SIGALGS "RSA+SHA512:RSA+SHA384:RSA+SHA256"
224 
225 /*! \brief ECDHE groups for TLSv1.3 protocol */
226 # define TLS_ECDHE_GROUPS_TLS13 "X448:X25519:P-256"
227 
228 /*! \brief FFDHE groups for TLSv1.2 and TLSv1.3 protocols
229  *
230  * \attention
231  * This list must not contain ECDHE groups because the group check code for
232  * TLSv1.2 currently doesn't support ECC!
233  */
234 # define TLS_FFDHE_GROUPS "ffdhe8192:ffdhe6144:ffdhe4096:ffdhe3072"
235 
236 
237 /* ========================================================================== */
238 /* Variables */
239 
240 static posix_locale_t tls_loc_ctype_posix = 0;
241 static SSL_CTX* tls_ctx = NULL; /* Global context for all connections */
242 # if CFG_USE_OPENSSL_API_1_1
243 static SSL_CONF_CTX* cctx; /* Global configuration context */
244 # endif /* CFG_USE_OPENSSL_API_1_1 */
245 static const char* tls_certpath = NULL;
246 # if !CFG_TLS_CRLS_DISABLE
247 static const char* tls_crlpath = NULL;
248 static int tls_crl_update_skip = 0; /* Don't update CRLs if nonzero */
249 # endif /* !CFG_TLS_CRLS_DISABLE */
250 
251 
252 /* ========================================================================== */
253 /* Check for root certificate
254  *
255  * \param[in] cc Pointer to certificate
256  * \param[out] is_root Result
257  * \param[in] bufsize Size of name buffers \e buf_i and \e buf_s
258  * \param[out] buf_i Pointer to issuer name buffer
259  * \param[out] buf_s Pointer to subject name buffer
260  *
261  * \note
262  * If the caller is not interested in the issuer or subject name, \e b_i and/or
263  * \e b_s are allowed to be \c NULL . If both are \c NULL , \e bufsize is
264  * ignored.
265  */
266 
267 static int tls_cert_check_root(X509* cc, int* is_root, size_t bufsize,
268  char* buf_i, char* buf_s)
269 {
270  int res = 0;
271  BIO* biop = BIO_new(BIO_s_mem());
272  X509_NAME* issuer;
273  X509_NAME* subject;
274  char* b_i = NULL;
275  char* b_s = NULL;
276  char* p = NULL;
277  size_t len = 0;
278 
279  /* Check BIO */
280  if(NULL == biop)
281  {
282  PRINT_ERROR("Creating BIO failed");
283  res = -1;
284  }
285 
286  /* Get Issuer of certificate */
287  if(!res)
288  {
289  issuer = X509_get_issuer_name(cc);
290  if(NULL == issuer)
291  {
292  PRINT_ERROR("Extraction of issuer from X.509 certificate failed");
293  res = -1;
294  }
295  else
296  {
297  X509_NAME_print_ex(biop, issuer, 0, XN_FLAG_ONELINE);
298  len = (size_t) BIO_get_mem_data(biop, &p);
299  if(!len) { res = -1; }
300  else
301  {
302  b_i = (char*) posix_malloc(len + (size_t) 1);
303  if(NULL == b_i) { res = -1; }
304  else
305  {
306  memcpy((void*) b_i, (void*) p, len);
307  b_i[len] = 0;
308  }
309  }
310  }
311  }
312 
313  /* Get Subject of certificate */
314  if(!res)
315  {
316  if(1 != BIO_reset(biop)) { res = -1; }
317  else
318  {
319  subject = X509_get_subject_name(cc);
320  if(NULL == subject)
321  {
322  PRINT_ERROR("Extraction of subject from X.509 certificate "
323  "failed");
324  res = -1;
325  }
326  else
327  {
328  X509_NAME_print_ex(biop, subject, 0, XN_FLAG_ONELINE);
329  len = (size_t) BIO_get_mem_data(biop, &p);
330  if(!len) { res = -1; }
331  else
332  {
333  b_s = (char*) posix_malloc(len + (size_t) 1);
334  if(NULL == b_s) { res = -1; }
335  else
336  {
337  memcpy((void*) b_s, (void*) p, len);
338  b_s[len] = 0;
339  }
340  }
341  }
342  }
343  }
344 
345  /* Compare subject with issuer */
346  if(!res)
347  {
348  *is_root = 0;
349  if(!strcmp(b_i, b_s))
350  {
351  /* Self signed (root) certificate */
352  *is_root = 1;
353  }
354  }
355 
356  /* Return strings (truncate them if necessary) */
357  if(!res && bufsize)
358  {
359  if(NULL != buf_i)
360  {
361  len = strlen(b_i);
362  if(bufsize - (size_t) 1 < len) { len = bufsize - (size_t) 1; }
363  memcpy((void*) buf_i, (void*) b_i, len);
364  buf_i[len] = 0;
365  }
366  if(NULL != buf_s)
367  {
368  len = strlen(b_s);
369  if(bufsize - (size_t) 1 < len) { len = bufsize - (size_t) 1; }
370  memcpy((void*) buf_s, (void*) b_s, len);
371  buf_s[len] = 0;
372  }
373  }
374 
375  /* Release memory */
376  posix_free((void*) b_i);
377  posix_free((void*) b_s);
378  if(NULL != biop) { BIO_free(biop); }
379 
380  return(res);
381 }
382 
383 
384 /* ========================================================================== */
385 /* Get certificate directory path
386  *
387  * \param[out] certpath Pointer to certificate path
388  *
389  * The caller is responsible to free the memory for the buffer on success.
390  */
391 
392 static int tls_get_certpath(const char** certpath)
393 {
394  static const char certdir[] = "certs";
395  const char* confdir = xdg_get_confdir(CFG_NAME);
396  int res = -1;
397  int rv;
398 
399  /* Init result so that 'free()' can be called in all cases */
400  *certpath = NULL;
401 
402  if(NULL != confdir)
403  {
404  *certpath = confdir;
405  rv = xdg_append_to_path(certpath, certdir);
406  if(0 == rv)
407  {
408  /* Create database directory if it doesn't exist */
409  res = fu_create_path(*certpath, (posix_mode_t) POSIX_S_IRWXU);
410  }
411  }
412 
413  /* Free memory on error */
414  if(res)
415  {
416  PRINT_ERROR("Cannot create certificate directory");
417  posix_free((void*) *certpath);
418  *certpath = NULL;
419  }
420 
421  return(res);
422 }
423 
424 
425 # if !CFG_TLS_CRLS_DISABLE
426 
427 
428 /* ========================================================================== */
429 /* Check for elapsed CRL update interval
430  *
431  * \return
432  * - 0 if CRLs are usable
433  * - 1 for elapsed update interval
434  * - -1 on error (if calculation failed)
435  */
436 
437 static int tls_check_crl_age(void)
438 {
439  int res;
440  posix_time_t ts;
441  core_time_t pts_last;
442  core_time_t pts_current;
443  core_time_t age;
444  core_time_t interval = 0;
445 
446  res = enc_convert_iso8601_to_posix(&pts_last, config[CONF_CRL_UPD_TS].val.s);
447  if(!res)
448  {
449  posix_time(&ts);
450  if((posix_time_t) 0 > ts) { res = -1; }
451  else
452  {
453  pts_current = (core_time_t) ts;
454  if(pts_last > pts_current)
455  {
456  PRINT_ERROR("Last CRL update timestamp is in the future");
457  res = -1;
458  }
459  else
460  {
461  age = pts_current - pts_last;
462  age /= (core_time_t) 3600;
463  /* Clamp negative intervals to zero */
464  if(0 > config[CONF_CRL_UPD_IV].val.i)
465  {
466  PRINT_ERROR("Negative CRL update interval was set to zero");
468  }
469  /* Clamp to 1 year upper limit */
470  if(8760 < config[CONF_CRL_UPD_IV].val.i)
471  {
472  PRINT_ERROR("Too large CRL update interval was clamped");
473  config[CONF_CRL_UPD_IV].val.i = 8760;
474  }
475  interval = (core_time_t) config[CONF_CRL_UPD_IV].val.i;
476  if(interval < age) { res = 1; }
477  }
478  }
479  }
480 
481  /* Check for error */
482  if(0 > res) { PRINT_ERROR("CRL update interval check failed"); }
483 
484  return(res);
485 }
486 
487 
488 /* ========================================================================== */
489 /* Update CRL update timestamp */
490 
491 static int tls_set_crl_age(void)
492 {
493  int res;
494  char isodate[21];
495 
496  res = enc_get_iso8601_utc(isodate);
497  if(!res) { res = conf_string_replace(&config[CONF_CRL_UPD_TS], isodate); }
498 
499  return(res);
500 }
501 
502 
503 /* ========================================================================== */
504 /* Reset CRL update timestamp to force update */
505 
506 static int tls_reset_crl_age(void)
507 {
508  int res;
509 
510  res = conf_string_replace(&config[CONF_CRL_UPD_TS], "1970-01-01T00:00:00Z");
511 
512  return(res);
513 }
514 
515 
516 /* ========================================================================== */
517 /* Get CRL directory path
518  *
519  * \param[out] certpath Pointer to CRL path
520  *
521  * The caller is responsible to free the memory for the buffer on success.
522  */
523 
524 static int tls_get_crlpath(const char** crlpath)
525 {
526  static const char crldir[] = "crls";
527  const char* confdir = xdg_get_confdir(CFG_NAME);
528  int res = -1;
529  int rv;
530 
531  /* Init result so that 'free()' can be called in all cases */
532  *crlpath = NULL;
533 
534  if(NULL != confdir)
535  {
536  *crlpath = confdir;
537  rv = xdg_append_to_path(crlpath, crldir);
538  if(0 == rv)
539  {
540  /* Create database directory if it doesn't exist */
541  res = fu_create_path(*crlpath, (posix_mode_t) POSIX_S_IRWXU);
542  }
543  }
544 
545  /* Free memory on error */
546  if(res)
547  {
548  PRINT_ERROR("Cannot create CRL directory");
549  posix_free((void*) *crlpath);
550  *crlpath = NULL;
551  }
552 
553  return(res);
554 }
555 
556 
557 /* ========================================================================== */
558 /* Fetch CRL from distribution point
559  *
560  * \param[in] cci Index in certificate chain
561  * \param[in] uri URI or certificate CRL to download
562  * \param[out] pn Pathname of downloaded file
563  *
564  * Using the filenames from the URIs of the certificates may lead to filename
565  * conflicts. Generic filenames are used (based on the index in the certificate
566  * chain) instead.
567  *
568  * On success the pathname of the file is written to \e pn and the caller is
569  * responsible to free the memory allocated for the buffer.
570  */
571 
572 static int tls_download_crl(int cci, const char* uri, char** pn)
573 {
574  int res = -1;
575  int rv;
576  char filename[8] = { '/', 'C', 'R', 'L', '_', '_', '_', 0 };
577  char* pathname = NULL;
578  size_t len;
579 
580  if(NULL == tls_crlpath)
581  {
582  PRINT_ERROR("Download of CRL failed, directory not available");
583  }
584  else
585  {
586  if(0 > cci || 999 < cci)
587  {
588  PRINT_ERROR("Download of CRL failed, invalid chain index");
589  }
590  else
591  {
592  rv = posix_snprintf(&filename[4], 4, "%d", cci);
593  if(1 > rv || 3 < rv)
594  {
595  PRINT_ERROR("Download of CRL failed, filename invalid");
596  }
597  else
598  {
599  len = strlen(tls_crlpath);
600  len += strlen(filename);
601  pathname = (char*) posix_malloc(++len);
602  if(NULL != pathname)
603  {
604  strcpy(pathname, tls_crlpath);
605  strcat(pathname, filename);
606  res = ext_download_file(pathname, uri);
607  }
608  }
609  }
610  }
611  *pn = pathname;
612 
613  /* Release memory for buffer on error */
614  if(res)
615  {
616  posix_free((void*) *pn);
617  *pn = NULL;
618  }
619 
620  return(res);
621 }
622 
623 
624 /* ========================================================================== */
625 /* Convert CRL from DER to PEM format
626  *
627  * \param[in] pn_der Pathname of CRL in DER format
628  * \param[out] pn_pem Pathname of CRL in PEM format
629  *
630  * On success the pathname of the PEM file is written to \e pn_pem and the
631  * caller is responsible to free the memory allocated for the buffer.
632  */
633 
634 static int tls_convert_crl_to_pem(const char* pn_der, char** pn_pem)
635 {
636  int res = 0;
637  int rv;
638  BIO* biop;
639  X509_CRL* crl = NULL;
640  size_t len;
641  int fd;
642  char pem_cmp[] = "-----BEGIN X509 CRL-----"; /* ASCII armor of PEM */
643  char pem_buf[] = " ";
644 
645  /* Prepare target filename */
646  len = strlen(pn_der);
647  len += 4; /* for ".pem" Extension */
648  *pn_pem = (char*) posix_malloc(++len);
649  if(NULL == *pn_pem)
650  {
651  PRINT_ERROR("Memory allocation failed for filename");
652  res = -1;
653  }
654  else
655  {
656  strcpy(*pn_pem, pn_der);
657  strcat(*pn_pem, ".pem");
658  }
659 
660  /* Load CRL */
661  if(!res)
662  {
663  res = -1;
664  biop = BIO_new(BIO_s_file());
665  if(NULL != biop)
666  {
667  rv = BIO_read_filename(biop, pn_der);
668  if(1 != rv)
669  {
670  PRINT_ERROR("BIO error while configuring DER filename of CRL");
671  }
672  else
673  {
674  /* Check whether CRL already is in PEM format */
675  len = strlen(pem_cmp);
676  rv = BIO_read(biop, pem_buf, len);
677  if(len == rv)
678  {
679  if(!memcmp((void*) pem_cmp, (void*) pem_buf, len))
680  {
681  /* CRL already in PEM format */
682  res = 1;
683  }
684  else
685  {
686  /* Assume CRL is in DER format */
687  rv = BIO_seek(biop, 0);
688  if(0 != rv)
689  {
690  PRINT_ERROR("I/O error while loading CRL");
691  }
692  else
693  {
694  crl = d2i_X509_CRL_bio(biop, NULL);
695  if(NULL == crl)
696  {
697  PRINT_ERROR("Loading CRL to memory failed");
698  }
699  else
700  {
701  /* CRL loaded to memory */
702  res = 0;
703  }
704  }
705  }
706  }
707  }
708  BIO_free(biop);
709  }
710  }
711 
712  /* Convert and store CRL */
713  if(!res)
714  {
715  res = -1;
716  /* Create CRL file with desired permissions, then reopen it via BIO */
717  /* Attention: Calling 'umask()' would affect other threads! */
718  rv = fu_open_file(*pn_pem, &fd, POSIX_O_WRONLY | POSIX_O_CREAT,
719  POSIX_S_IRUSR | POSIX_S_IWUSR);
720  if(!rv)
721  {
722  fu_close_file(&fd, NULL);
723  biop = BIO_new(BIO_s_file());
724  if(NULL != biop)
725  {
726  rv = BIO_write_filename(biop, *pn_pem);
727  if(1 != rv)
728  {
729  PRINT_ERROR(""
730  "BIO error while configuring PEM filename of CRL");
731  }
732  else
733  {
734  rv = PEM_write_bio_X509_CRL(biop, crl);
735  if(1 != rv)
736  {
737  PRINT_ERROR("Converting and storing CRL failed");
738  }
739  else
740  {
741  /* CRL stored in PEM format */
742  rv = BIO_get_fd(biop, NULL);
743  if(-1 != rv) { res = fu_sync(rv, NULL); }
744  }
745  }
746  BIO_free(biop);
747  }
748  }
749  }
750 
751  /* Create symlink if CRL is already in PEM format */
752  if(1 == res)
753  {
754  res = posix_symlink(pn_der, *pn_pem);
755  }
756 
757  /* Release memory for buffer on error */
758  if(res)
759  {
760  PRINT_ERROR("Conversion of CRL to PEM format failed");
761  posix_free((void*) *pn_pem);
762  *pn_pem = NULL;
763  }
764 
765  return(res);
766 }
767 
768 
769 /* ========================================================================== */
770 /* Create hash symlink to CRL
771  *
772  * \param[in] pn_pem Pathname of CRL in PEM format
773  * \param[in] cert Pointer to certificate
774  *
775  * The symlinks to CRLs need to have the following format for OpenSSL 1.0:
776  * \c HHHHHHHH.rD
777  *
778  * The field \c H is the hash that is searched for. The field \c D is used to
779  * distinguish duplicates (identical hash values for different files).
780  *
781  * \attention
782  * The caller is responsible to delete old symlinks in the directory where
783  * \e pn_pem resides before calling this function.
784  */
785 
786 static int tls_create_hash_symlink(const char* pn_pem, X509* cert)
787 {
788  int res = -1;
789  int rv;
790  unsigned long int issuer_hash;
791  size_t len;
792  char name_symlink[13];
793  char* pn_symlink = NULL;
794  unsigned int i = 0;
795  int abort = 0;
796 
797  if(NULL == tls_crlpath)
798  {
799  PRINT_ERROR("Creating of symlink failed, directory not available");
800  }
801  else
802  {
803  /* Limit to 9 duplicate names */
804  while(!abort && 9U >= i)
805  {
806  issuer_hash = X509_issuer_name_hash(cert);
807  /* See 'c_rehash' manual for the name format */
808  rv = posix_snprintf(name_symlink, 13, "/%08lx.r%u", issuer_hash, i);
809  if(12 != rv)
810  {
811  PRINT_ERROR("Creating of symlink failed, name not valid");
812  abort = 1;
813  }
814  else
815  {
816  len = strlen(tls_crlpath);
817  len += strlen(name_symlink);
818  pn_symlink = (char*) posix_malloc(++len);
819  if(NULL == pn_symlink) { abort = 1; }
820  else
821  {
822  strcpy(pn_symlink, tls_crlpath);
823  strcat(pn_symlink, name_symlink);
824  res = posix_symlink(pn_pem, pn_symlink);
825  if(!res)
826  {
827  /* Success */
828  abort = 1;
829  }
830  else
831  {
832  /* Check whether symlink already exist */
833  if(!(-1 == res && POSIX_EEXIST == posix_errno))
834  {
835  /* No => Creation failed => Abort */
836  PRINT_ERROR("Creating of symlink failed");
837  abort = 1;
838  }
839  }
840  posix_free((void*) pn_symlink);
841  }
842  }
843  ++i;
844  }
845  /* Check whether duplicate numbers gone out */
846  if(9 < i)
847  {
848  PRINT_ERROR("Creating of symlink failed, too many duplicates");
849  }
850  }
851 
852  return(res);
853 }
854 
855 
856 /* ========================================================================== */
857 /* Get mutex for CRL update
858  *
859  * \param[out] fd Pointer to filedescriptor of lockfile
860  */
861 
862 static int tls_crl_get_lock(int* fd)
863 {
864  int res = -1;
865  const char crl_lockfile[] = ".crl_lock";
866  const char* lockpathname = NULL;
867  int rv;
868 
869  lockpathname = xdg_get_confdir(CFG_NAME);
870  if(NULL != lockpathname)
871  {
872  rv = fu_create_path(lockpathname, (posix_mode_t) POSIX_S_IRWXU);
873  if(0 == rv)
874  {
875  /* Store lock file pathname */
876  rv = xdg_append_to_path(&lockpathname, crl_lockfile);
877  if(0 == rv)
878  {
879  rv = fu_open_file(lockpathname, fd,
880  POSIX_O_WRONLY | POSIX_O_CREAT,
881  POSIX_S_IRUSR | POSIX_S_IWUSR);
882  if(rv)
883  {
884  PRINT_ERROR("Cannot open mutex file for CRL directory");
885  }
886  else
887  {
888  if(fu_lock_file(*fd))
889  {
890  PRINT_ERROR("Cannot lock mutex file for CRL directory");
891  }
892  else
893  {
894  /* Mutex for CRL directory claimed */
895  res = 0;
896  }
897  }
898  }
899  }
900  }
901  posix_free((void*) lockpathname);
902 
903  return(res);
904 }
905 
906 
907 /* ========================================================================== */
908 /* Release mutex for CRL update
909  *
910  * \param[in,out] fd Pointer to filedescriptor of lockfile
911  */
912 
913 static void tls_crl_release_lock(int* fd)
914 {
915  fu_close_file(fd, NULL);
916 }
917 
918 
919 /* ========================================================================== */
920 /* Update CRLs for certificate chain
921  *
922  * \param[in] certificate_chain Pointer to certificate chain
923  *
924  * \return
925  * - 0 on success
926  * - Positive value if no CRLs are required (self signed server certificate)
927  * - -1 on unknown error
928  * - -2 if the lock for the mutex file can't be acquired
929  */
930 
931 static int tls_update_crls(STACK_OF(X509)* certificate_chain)
932 {
933  int res = -1;
934  int rv;
935  int crl_valid = 0;
936  int crls_required = 0;
937  int ccl; /* Length of certificate chain */
938  int cci; /* Index in certificate chain */
939  X509* cc; /* Current certificate */
940  int num, num2;
941  int i, i2;
942  STACK_OF(DIST_POINT)* dp = NULL;
943  DIST_POINT* dpi;
944  GENERAL_NAME* ani;
945  const size_t buflen = 256;
946  char b_i[buflen];
947  int is_root = 0;
948  char* p = NULL;
949  char* crl_pn_der; /* Pathname to raw CRL (expected in DER format) */
950  char* crl_pn_pem; /* Pathname of cooked CRL (in PEM format) */
951  int crlpath_ok = 0;
952  int lockfd = -1;
953 
954  /* Prepare and lock mutex file for CRL update */
955  if(tls_crl_get_lock(&lockfd)) { res = -2; }
956  else
957  {
958  /* Got lock => Automatic CRL update */
959  printf("%s: %s-----------------------------------------------------\n",
960  CFG_NAME, MAIN_ERR_PREFIX);
961  printf("%s: %sAutomatic CRL maintenance\n", CFG_NAME, MAIN_ERR_PREFIX);
962  /* Delete CRL directory */
963  if(NULL != tls_crlpath)
964  {
965  if(!fu_delete_tree(tls_crlpath))
966  {
967  if(!posix_mkdir(tls_crlpath, (posix_mode_t) POSIX_S_IRWXU))
968  {
969  /* Empty CRL directory is now available */
970  crlpath_ok = 1;
971  }
972  }
973  }
974  if(!crlpath_ok)
975  {
976  PRINT_ERROR("CRL update failed, directory not available");
977  }
978  else
979  {
980  /* Get length of certificate chain */
981  ccl = sk_X509_num(certificate_chain);
982  for(cci = 0; cci < ccl; ++cci)
983  {
984  /* Get next certificate */
985  cc = sk_X509_value(certificate_chain, cci);
986  if(NULL == cc)
987  {
988  PRINT_ERROR("Error while parsing certificate chain");
989  break;
990  }
991  rv = tls_cert_check_root(cc, &is_root, buflen, b_i, NULL);
992  if(rv) { break; }
993  /* Determine type of certificate */
994  if(!cci)
995  {
996  if(is_root)
997  {
998  printf("%s: %sSelf signed server certificate:\n",
999  CFG_NAME, MAIN_ERR_PREFIX);
1000  }
1001  else
1002  {
1003  printf("%s: %sServer certificate:\n",
1004  CFG_NAME, MAIN_ERR_PREFIX);
1005  }
1006  }
1007  else
1008  {
1009  if(is_root)
1010  {
1011  printf("%s: %sRoot certificate:\n",
1012  CFG_NAME, MAIN_ERR_PREFIX);
1013  }
1014  else
1015  {
1016  printf("%s: %sIntermediate certificate:\n",
1017  CFG_NAME, MAIN_ERR_PREFIX);
1018  }
1019  }
1020  /* Print issuer */
1021  printf("%s: %s Issuer: %s\n", CFG_NAME, MAIN_ERR_PREFIX, b_i);
1022  /* Get CRL of certificate */
1023  crl_valid = 0;
1024  if(is_root)
1025  {
1026  printf("%s: %s Always trusted if installed"
1027  " (Must be uninstalled for revocation)\n",
1028  CFG_NAME, MAIN_ERR_PREFIX);
1029  res = 0;
1030  }
1031  else
1032  {
1033  dp = X509_get_ext_d2i(cc, NID_crl_distribution_points, NULL,
1034  NULL);
1035  if(NULL == dp)
1036  {
1037  PRINT_ERROR(" No CRL distribution points found"
1038  " in certificate");
1039  }
1040  else
1041  {
1042  num2 = sk_DIST_POINT_num(dp);
1043  for(i2 = 0; i2 < num2; ++i2)
1044  {
1045  dpi = sk_DIST_POINT_value(dp, i2);
1046  if(NULL != dpi->distpoint)
1047  {
1048  num = sk_GENERAL_NAME_num(
1049  dpi->distpoint->name.fullname);
1050  for(i = 0; i < num; ++i)
1051  {
1052  ani = sk_GENERAL_NAME_value(
1053  dpi->distpoint->name.fullname, i);
1054  if(GEN_URI == ani->type)
1055  {
1056  p = (char*)
1057  ani->d.uniformResourceIdentifier->data;
1058  printf("%s: %s "
1059  "CRL distribution point %d: %s\n",
1060  CFG_NAME, MAIN_ERR_PREFIX, i2, p);
1061  /* Download CRL */
1062  crl_pn_der = NULL;
1063  crl_pn_pem = NULL;
1064  res = tls_download_crl(cci, p, &crl_pn_der);
1065  if(!res)
1066  {
1067  /* Convert CRL to PEM format */
1068  res = tls_convert_crl_to_pem(crl_pn_der,
1069  &crl_pn_pem);
1070  if(!res)
1071  {
1072  /* Create symlink to CRL in PEM format */
1073  res = tls_create_hash_symlink(crl_pn_pem,
1074  cc);
1075  }
1076  /* Check for success */
1077  if(!res)
1078  {
1079  crl_valid = 1;
1080  crls_required = 1;
1081  }
1082  }
1083  /* Release memory allocated for pathnames */
1084  posix_free((void*) crl_pn_pem);
1085  posix_free((void*) crl_pn_der);
1086  break;
1087  }
1088  }
1089  }
1090  if(crl_valid) { break; }
1091  }
1092  }
1093  }
1094  /* Check for error */
1095  if(res) { break; }
1096  }
1097  }
1098  printf("%s: %s-----------------------------------------------------\n",
1099  CFG_NAME, MAIN_ERR_PREFIX);
1100  /* Release lock of mutex file */
1101  tls_crl_release_lock(&lockfd);
1102  /* Return positive value if no CRLs are required */
1103  if(!res && !crls_required) { res = 1; }
1104  }
1105 
1106  /* Release memory */
1107  if(NULL != dp) { CRL_DIST_POINTS_free(dp); }
1108 
1109  return(res);
1110 }
1111 
1112 
1113 # endif /* !CFG_TLS_CRLS_DISABLE */
1114 
1115 
1116 /* ========================================================================== */
1117 /* Check certificate chain for signing key length and signature hash algorithm
1118  *
1119  * \param[in] certificate_chain Pointer to certificate chain
1120  * \param[in] proto Flag indicating TLS protocol minor number
1121  *
1122  * \attention
1123  * Checks for non-RSA keys are not implemented.
1124  * This should never happen for TLSv1.2 because of the signature algorithm
1125  * negotiation (we offer only RSA-based signature algorithms for TLSv1.2).
1126  *
1127  * If the modulus size of a RSA key is less than 1024 bits, the key is rejected.
1128  * If the modulus size of a RSA key is less than 3072 bits, a warning message
1129  * is generated.
1130  *
1131  * The signature hash algorithms MD2, MD4 and MD5 are rejected except for the
1132  * self signature of the root certificate (signature is not used in this case).
1133  * If the signature hash algorithm is SHA-1 or SHA-224, a warning message is
1134  * generated. This should never happen for TLSv1.2 because of the signature
1135  * algorithm negotiation.
1136  *
1137  * \return
1138  * - 0 on success (skipped ECC keys are not counted as errors)
1139  * - -1 on error
1140  */
1141 
1142 static int tls_chain_check_sigalgs(STACK_OF(X509)* certificate_chain,
1143  int proto)
1144 {
1145  int res = -1;
1146  int ccl; /* Length of certificate chain */
1147  int cci; /* Index in certificate chain */
1148  X509* cc; /* Current certificate */
1149  int rv;
1150  posix_ssize_t rv2;
1151  int is_root = 0;
1152  const char* s;
1153  EVP_PKEY* pkey = NULL;
1154 # if !CFG_USE_OPENSSL_API_3
1155  RSA* rsa_key = NULL;
1156 # endif /* !CFG_USE_OPENSSL_API_3 */
1157  int rsa_mod_size;
1158  int alg;
1159  const char* md_s;
1160  int md_ok;
1161  unsigned char* buf;
1162  int len;
1163  char prefix[80];
1164 
1165  /* Get length of certificate chain */
1166  ccl = sk_X509_num(certificate_chain);
1167  for(cci = 0; cci < ccl; ++cci)
1168  {
1169  /* Get next certificate */
1170  cc = sk_X509_value(certificate_chain, cci);
1171  if(NULL == cc)
1172  {
1173  PRINT_ERROR("Error while parsing certificate chain");
1174  break;
1175  }
1176  /* Check for root certificate */
1177  rv = tls_cert_check_root(cc, &is_root, 0, NULL, NULL);
1178  if(rv) { break; }
1179  s = "";
1180  if(!cci) { s = "(Server) "; }
1181  if(is_root) { s = "(Root) "; }
1182  printf("%s: %sCertificate level %d %sin chain:\n",
1183  CFG_NAME, MAIN_ERR_PREFIX, cci, s);
1184  /* Extract public key */
1185  pkey = X509_extract_key(cc);
1186  if(NULL == pkey)
1187  {
1188  PRINT_ERROR("Extraction of public key from X.509 certificate"
1189  " failed");
1190  break;
1191  }
1192 # if CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
1193  if(EVP_PKEY_RSA != EVP_PKEY_base_id(pkey))
1194 # else /* CFG_USE_OPENSSL_API_1_1 */
1195  if(EVP_PKEY_RSA != pkey->type)
1196 # endif /* CFG_USE_OPENSSL_API_1_1 */
1197  {
1198  /* ECC keys are mandatory for TLSv1.3 (return no error in this case) */
1199  if(3 <= proto)
1200  {
1201  PRINT_ERROR("Certificate doesn't use RSA key (skipped)");
1202  continue;
1203  }
1204  PRINT_ERROR("Certificate doesn't use RSA key (not supported)");
1205  break;
1206  }
1207 # if !CFG_USE_OPENSSL_API_3
1208  rsa_key = EVP_PKEY_get1_RSA(pkey);
1209  if(NULL == rsa_key)
1210  {
1211  PRINT_ERROR("Extraction of key from certificate failed");
1212  break;
1213  }
1214 # endif /* !CFG_USE_OPENSSL_API_3 */
1215 # if CFG_USE_OPENSSL_API_3
1216  rsa_mod_size = EVP_PKEY_bits(pkey);
1217  if(0 >= rsa_mod_size)
1218  {
1219  PRINT_ERROR("Calculation of key size failed");
1220  break;
1221  }
1222 # else /* CFG_USE_OPENSSL_API_3 */
1223  rsa_mod_size = RSA_size(rsa_key);
1224  if(0 >= rsa_mod_size || 8192 < rsa_mod_size)
1225  {
1226  PRINT_ERROR("Calculation of key size failed");
1227  break;
1228  }
1229  rsa_mod_size *= 8;
1230 # endif /* CFG_USE_OPENSSL_API_3 */
1231  printf("%s: %s RSA key modulus size: %d bit\n",
1232  CFG_NAME, MAIN_ERR_PREFIX, rsa_mod_size);
1233  if(1024 > rsa_mod_size)
1234  {
1235  PRINT_ERROR("RSA key modulus size of certificate rejected");
1236  break;
1237  }
1238  else if(3072 > rsa_mod_size)
1239  {
1240  /* 3072 bit would match a 128 bit symmetric cipher */
1241  printf("%s: %s Warning: RSA key modulus should be "
1242  "at least 3072 bit\n", CFG_NAME, MAIN_ERR_PREFIX);
1243  }
1244  if(!cci)
1245  {
1246  /* Print randomart image for key */
1247  buf = NULL;
1248 # if CFG_USE_OPENSSL_API_3
1249  len = i2d_PUBKEY(pkey, &buf);
1250 # else /* CFG_USE_OPENSSL_API_3 */
1251  len = i2d_RSA_PUBKEY(rsa_key, &buf);
1252 # endif /* CFG_USE_OPENSSL_API_3 */
1253  if(0 > len)
1254  {
1255  PRINT_ERROR("Extraction of key fingerprint failed");
1256  break;
1257  }
1258  else
1259  {
1260  /* 'SubjectPublicKeyInfo' structure now stored in buf */
1261  rv2 = posix_snprintf(prefix, 80, "%s: %s ",
1262  CFG_NAME, MAIN_ERR_PREFIX);
1263  if(0 > rv2)
1264  {
1265  PRINT_ERROR("Creating message prefix failed");
1266  break;
1267  }
1268  rv = digest_randomart(prefix, (const char*) buf, (size_t) len);
1269  OPENSSL_free(buf);
1270  if(rv)
1271  {
1272  PRINT_ERROR("Creating randomart for key failed");
1273  break;
1274  }
1275  }
1276  }
1277 # if !CFG_USE_OPENSSL_API_3
1278  RSA_free(rsa_key);
1279 # endif /* !CFG_USE_OPENSSL_API_3 */
1280  EVP_PKEY_free(pkey);
1281  /* Extract hash algorithm for signatures */
1282 # if CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
1283  alg = X509_get_signature_nid(cc);
1284 # else /* CFG_USE_OPENSSL_API_1_1 */
1285  alg = OBJ_obj2nid(cc->sig_alg->algorithm);
1286 # endif /* CFG_USE_OPENSSL_API_1_1 */
1287  if(NID_undef == alg)
1288  {
1289  PRINT_ERROR("Extraction of hash algorithm failed");
1290  break;
1291  }
1292  md_s = OBJ_nid2sn(alg);
1293  if(is_root)
1294  {
1295  printf("%s: %s Self signature is not used\n",
1296  CFG_NAME, MAIN_ERR_PREFIX);
1297  }
1298  else
1299  {
1300  printf("%s: %s Signature algorithm: %s\n",
1301  CFG_NAME, MAIN_ERR_PREFIX, md_s);
1302  md_ok = 0;
1303  switch(alg)
1304  {
1305  case NID_md2WithRSAEncryption:
1306  case NID_md4WithRSAEncryption:
1307  case NID_md5WithRSAEncryption:
1308  {
1309  /* Reject weak algorithms */
1310  PRINT_ERROR("Hash algorithm of signature rejected");
1311  break;
1312  }
1313  case NID_sha1WithRSAEncryption:
1314  case NID_sha224WithRSAEncryption:
1315  {
1316  /* SHA-256 would match a 128 bit symmetric cipher */
1317  printf("%s: %s Warning: At least SHA-256 should be "
1318  "used for signatures\n", CFG_NAME, MAIN_ERR_PREFIX);
1319 # if CFG_USE_OPENSSL_API_1_1
1320  if(2 <= proto)
1321  {
1322  /*
1323  * RFC 5246 requires that the certificate chain must use one
1324  * of the signature algorithms offered in negotiation.
1325  * But we have not offered this algorithm!
1326  */
1327  PRINT_ERROR(" Server has violated RFC 5246");
1328  }
1329 # endif /* CFG_USE_OPENSSL_API_1_1 */
1330  md_ok = 1;
1331  break;
1332  }
1333  case NID_sha256WithRSAEncryption:
1334  case NID_sha384WithRSAEncryption:
1335  case NID_sha512WithRSAEncryption:
1336  {
1337  /* This is what we have offered for negotiation with TLSv1.2 */
1338  md_ok = 1;
1339  break;
1340  }
1341  default:
1342  {
1343  PRINT_ERROR(" Unexpected hash algorithm rejected");
1344  if(2 <= proto)
1345  {
1346  PRINT_ERROR(" Server has violated RFC 5246");
1347  }
1348  break;
1349  }
1350  }
1351  if(!md_ok) { break; }
1352  }
1353  }
1354  if(cci == ccl) { res = 0; }
1355 
1356  return(res);
1357 }
1358 
1359 
1360 /* ========================================================================== */
1361 /* Verify that subject of certificate matches hostname
1362  *
1363  * \param[in] cn Common name from certificate
1364  * \param[in] subject Subject to match
1365  *
1366  * The comparison is done locale independent and case insensitive.
1367  *
1368  * \note
1369  * A wildcard for the first part of the subject is accepted if
1370  * \ref CFG_USE_TLS_WILDCARD_SUBJECT is defined to a nonzero value.
1371  */
1372 
1373 static int tls_subject_check(const char* cn, const char* subject)
1374 {
1375  int res = 0;
1376 # if CFG_USE_TLS_WILDCARD_SUBJECT
1377  int wildcard = 0;
1378  const char* p;
1379 
1380  /* Check for wildcard as first part of subject */
1381  if('*' == subject[0])
1382  {
1383  /* Yes => Compare only parts after first dot */
1384  wildcard = 1;
1385  res = -1;
1386  if('.' == subject[1])
1387  {
1388  subject = &subject[2];
1389  p = strchr(cn, (int) '.');
1390  if(NULL != p)
1391  {
1392  cn = ++p;
1393  res = 0;
1394  }
1395  }
1396  }
1397 # endif /* CFG_USE_TLS_WILDCARD_SUBJECT */
1398  if(!res)
1399  {
1400  /* Compare using POSIX locale */
1401  res = posix_strcasecmp_l(cn, subject, tls_loc_ctype_posix);
1402  }
1403  if(0 < res) { res = -res; }
1404 
1405  /* Print message for result */
1406  if(res) { printf(" (doesn't match hostname)\n"); }
1407 # if CFG_USE_TLS_WILDCARD_SUBJECT
1408  else if(wildcard) { printf(" (matches hostname using wildcard)\n"); }
1409 # endif /* CFG_USE_TLS_WILDCARD_SUBJECT */
1410  else { printf(" (matches hostname)\n"); }
1411 
1412  return(res);
1413 }
1414 
1415 
1416 /* ========================================================================== */
1417 /* Create context for TLS connection
1418  *
1419  * \param[in] weak Offer weak TLS versions to server
1420  *
1421  * We negotiate for TLSv1.2 or higher connections according to RFC 8996.
1422  * If the server doesn't support at least TLSv1.2, \e weak must be set to a
1423  * nonzero value (to add TLSv1.1 and TLSv1.0 for negotiation).
1424  *
1425  * To provide forward secrecy, only cipher suites with ephemeral
1426  * Diffie-Hellmann-Merkle key exchange are offered by default.
1427  * Session tickets and compression are disabled.
1428  *
1429  * \attention
1430  * With the initial configuration the server certificate is not automatically
1431  * checked. The caller must explicitly check the certificate for authentication
1432  * using the \ref tls_cert_verify() function.
1433  */
1434 
1435 static int tls_create_context(int weak)
1436 {
1437  int res = 0;
1438  long int mode = SSL_MODE_ENABLE_PARTIAL_WRITE
1439  | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
1440  long int options = SSL_OP_NO_TICKET | SSL_OP_NO_COMPRESSION
1441  | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
1442  unsigned long int parameters = X509_V_FLAG_X509_STRICT;
1443  X509_VERIFY_PARAM* para = NULL;
1444  long f;
1445  int rv;
1446  const char* cpp = NULL;
1447 # if !CFG_TLS_CRLS_DISABLE
1448  X509_LOOKUP* look = NULL;
1449 
1450  /* Configure context for CRL checks */
1451  if(config[CONF_CRL_CHECK].val.i)
1452  {
1453  parameters |= X509_V_FLAG_CRL_CHECK
1454  | X509_V_FLAG_CRL_CHECK_ALL
1455  | X509_V_FLAG_EXTENDED_CRL_SUPPORT
1456  | X509_V_FLAG_USE_DELTAS;
1457  }
1458 # endif /* !CFG_TLS_CRLS_DISABLE */
1459 
1460  /* Disable TLSv1.0 and TLSv1.1 according to RFC 8996 */
1461  if(!weak)
1462  {
1463  /* Negotiate TLSv1.1 and TLSv1.0 for weak mode only */
1464  options |= SSL_OP_NO_TLSv1;
1465 # ifdef SSL_OP_NO_TLSv1_1
1466  options |= SSL_OP_NO_TLSv1_1;
1467 # endif /* SSL_OP_NO_TLSv1_1 */
1468  }
1469 
1470  /* Create TLS context for client side */
1471  tls_ctx = SSL_CTX_new(SSLv23_client_method());
1472  if(NULL == tls_ctx)
1473  {
1474  PRINT_ERROR("Cannot allocate context");
1475  res = -1;
1476  }
1477  if(!res)
1478  {
1479 # if CFG_USE_OPENSSL_API_1_1
1480  /* Disable all internal checks */
1481  SSL_CTX_set_security_level(tls_ctx, 0);
1482 # endif /* CFG_USE_OPENSSL_API_1_1 */
1483  f = SSL_CTX_set_mode(tls_ctx, mode);
1484  if((f & mode) != mode)
1485  {
1486  PRINT_ERROR("Cannot configure context");
1487  res = -1;
1488  }
1489  }
1490  if(!res)
1491  {
1492  f = SSL_CTX_set_options(tls_ctx, options);
1493  if((f & options) != options)
1494  {
1495  PRINT_ERROR("Cannot set context options");
1496  res = -1;
1497  }
1498  }
1499 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L)
1500  if(!res)
1501  {
1502  /* This is used for TLSv1.3 negotiation only */
1503  rv = SSL_CTX_set_ciphersuites(tls_ctx, TLS_CIPHERS_TLS13);
1504  if(1 != rv)
1505  {
1506  PRINT_ERROR("No usable TLSv1.3 ciphers available, "
1507  "check your OpenSSL configuration");
1508  res = -1;
1509  }
1510  }
1511 # endif /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= xxx) */
1512  if(!res)
1513  {
1514  rv = SSL_CTX_set_cipher_list(tls_ctx, TLS_CIPHERS_DEFAULT);
1515  if(1 != rv)
1516  {
1517  PRINT_ERROR("No usable ciphers with EDH key agreement available, "
1518  "check your OpenSSL configuration");
1519  res = -1;
1520  }
1521  }
1522  if(!res)
1523  {
1524  SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_NONE, NULL); /* We do it manually */
1525  para = X509_VERIFY_PARAM_new();
1526  if(NULL == para)
1527  {
1528  PRINT_ERROR("Memory allocation for X.509 parameters failed ");
1529  res = -1;
1530  }
1531  else
1532  {
1533  rv = X509_VERIFY_PARAM_set_flags(para, parameters);
1534  if(1 != rv)
1535  {
1536  PRINT_ERROR("Cannot set X.509 parameters");
1537  res = -1;
1538  }
1539  if(!res)
1540  {
1541  rv = X509_VERIFY_PARAM_set_purpose(para, X509_PURPOSE_SSL_SERVER);
1542  if(1 != rv)
1543  {
1544  PRINT_ERROR("Cannot set X.509 verification purpose");
1545  res = -1;
1546  }
1547  }
1548  if(!res)
1549  {
1550  rv = SSL_CTX_set1_param(tls_ctx, para);
1551  if(1 != rv)
1552  {
1553  PRINT_ERROR("Cannot store X.509 parameters in TLS context");
1554  res = -1;
1555  }
1556  }
1557  X509_VERIFY_PARAM_free(para);
1558  }
1559  }
1560  if(!res)
1561  {
1562  /* OpenSSL up to 1.1.0 API has no SSL_CTX_set1_groups_list() function */
1563 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L)
1564 # if CFG_USE_OPENSSL_API_3
1565  /* DH group negotiation */
1566  rv = SSL_CTX_set1_groups_list(tls_ctx, TLS_FFDHE_GROUPS
1568 # else /* CFG_USE_OPENSSL_API_3 */
1569  /* Workaround (OpenSSL 1.1.1 doesn't support FFDHE groups) */
1570  printf("%s: %sWorkaround for OpenSSL 1.1.1: "
1571  "Ignore FFDHE group configuration\n", CFG_NAME, MAIN_ERR_PREFIX);
1572  /* This is only used for key exchange in TLSv1.3 handshakes */
1573  rv = SSL_CTX_set1_groups_list(tls_ctx, TLS_ECDHE_GROUPS_TLS13);
1574 # endif /* CFG_USE_OPENSSL_API_3 */
1575  if(1 != rv)
1576  {
1577  PRINT_ERROR("Cannot store DHE groups in TLS context");
1578  res = -1;
1579  }
1580 # else /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1581 # if CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
1582  /* LibreSSL has client TLSv1.3 support since version 3.1.1 */
1583  /* Workaround (LibreSSL 3.1.1 doesn't support FFDHE groups) */
1584  printf("%s: %sWorkaround for LibreSSL: "
1585  "Ignore FFDHE group configuration\n", CFG_NAME, MAIN_ERR_PREFIX);
1586  /* The list TLS_ECDHE_GROUPS_TLS13 is rejected too (tested with 3.2.2) */
1587  rv = SSL_CTX_set1_groups_list(tls_ctx, "X25519:P-256");
1588  if(1 != rv)
1589  {
1590  PRINT_ERROR("Cannot store DHE groups in TLS context");
1591  res = -1;
1592  }
1593 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 3.1.1) */
1594 # endif /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1595  }
1596 
1597 # if CFG_USE_OPENSSL_API_1_1
1598  if(!res)
1599  {
1600  /* Create configuration context */
1601  cctx = SSL_CONF_CTX_new();
1602  if(NULL == cctx)
1603  {
1604  PRINT_ERROR("Cannot create TLS configuration context");
1605  res = -1;
1606  }
1607  else
1608  {
1609  /* Init configuration context */
1610  SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_CLIENT
1611  | SSL_CONF_FLAG_SHOW_ERRORS);
1612  /* Assign current TLS context to configuration context */
1613  SSL_CONF_CTX_set_ssl_ctx(cctx, tls_ctx);
1614  /* Set signature algorithms for TLSv1.2 and higher */
1615 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L)
1616  /*
1617  * Append the list of signature algorithms for TLSv1.2
1618  * to allow PKCS1 v1_5 based signatures in certificates
1619  */
1620  rv = SSL_CONF_cmd(cctx, "SignatureAlgorithms", TLS_SIGALGS_TLS13
1621  ":" TLS_SIGALGS);
1622 # else /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1623  rv = SSL_CONF_cmd(cctx, "SignatureAlgorithms", TLS_SIGALGS);
1624 # endif /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1625  if(2 != rv)
1626  {
1627  PRINT_ERROR("Cannot store TLS signature algorithms");
1628  res = -1;
1629  }
1630  else
1631  {
1632  /* Attention: The OpenSSL documentation is wrong! */
1633  rv = SSL_CONF_CTX_finish(cctx);
1634  if(1 != rv)
1635  {
1636  PRINT_ERROR("Cannot store configuration context");
1637  res = -1;
1638  }
1639  }
1640  }
1641  }
1642 # endif /* CFG_USE_OPENSSL_API_1_1 */
1643 
1644  /* Use local root certificate on request (must be installed manually) */
1645  if(config[CONF_TLS_OWNCERTS].val.i)
1646  {
1647  if(!res) { res = tls_get_certpath(&cpp); }
1648  if(!res)
1649  {
1650  tls_certpath = cpp;
1651  printf("%s: %sLocation of X.509 root certificates: %s/\n",
1652  CFG_NAME, MAIN_ERR_PREFIX, tls_certpath);
1653 # if CFG_USE_OPENSSL_API_3
1654  rv = SSL_CTX_load_verify_dir(tls_ctx, tls_certpath);
1655 # else /* CFG_USE_OPENSSL_API_3 */
1656  rv = SSL_CTX_load_verify_locations(tls_ctx, NULL, tls_certpath);
1657 # endif /* CFG_USE_OPENSSL_API_3 */
1658  if(1 != rv)
1659  {
1660  PRINT_ERROR("Setup of certificate verification failed");
1661  res = -1;
1662  }
1663  }
1664  }
1665  else
1666  {
1667  /* Use default certificate location of OpenSSL */
1668  if(!res)
1669  {
1670  rv = SSL_CTX_set_default_verify_paths(tls_ctx);
1671  if(1 != rv)
1672  {
1673  PRINT_ERROR("Setup of certificate verification failed");
1674  res = -1;
1675  }
1676  }
1677  }
1678 
1679 # if !CFG_TLS_CRLS_DISABLE
1680  if(!res && config[CONF_CRL_CHECK].val.i)
1681  {
1682  /* Use CRLs vor certificate revocation checks */
1683  res = tls_get_crlpath(&cpp);
1684  if(!res)
1685  {
1686  tls_crlpath = cpp;
1687  printf("%s: %sLocation of X.509 CRLs: %s/\n",
1688  CFG_NAME, MAIN_ERR_PREFIX, tls_crlpath);
1689  }
1690  if(!res)
1691  {
1692  look = X509_STORE_add_lookup(SSL_CTX_get_cert_store(tls_ctx),
1693  X509_LOOKUP_hash_dir());
1694  if(NULL == look)
1695  {
1696  PRINT_ERROR("Cannot add CRL lookup method to TLS context");
1697  res = -1;
1698  }
1699  }
1700  if(!res)
1701  {
1702  rv = X509_LOOKUP_add_dir(look, tls_crlpath, X509_FILETYPE_PEM);
1703  if(1 != rv)
1704  {
1705  PRINT_ERROR("Cannot set CRL path");
1706  res = -1;
1707  }
1708  }
1709  }
1710  else
1711  {
1712  printf("%s: %sWarning: X.509 certificate revocation checks disabled "
1713  "in configfile\n", CFG_NAME, MAIN_ERR_PREFIX);
1714  }
1715 # else /* !CFG_TLS_CRLS_DISABLE */
1716  /* Do not check revocation of certificates */
1717  if(!res)
1718  {
1719  printf("%s: %sWarning: X.509 certificate revocation checks disabled "
1720  "by configuration\n", CFG_NAME, MAIN_ERR_PREFIX);
1721  }
1722 # endif /* !CFG_TLS_CRLS_DISABLE */
1723 
1724  /* For code review: The Cert/CRL paths are destroyed with the context! */
1725  return(res);
1726 }
1727 
1728 
1729 /* ========================================================================== */
1730 /* Destroy context for TLS connection */
1731 
1732 static void tls_destroy_context(void)
1733 {
1734 # if CFG_USE_OPENSSL_API_1_1
1735  /* Note: 'cctx' is allowed to be 'NULL' here */
1736  SSL_CONF_CTX_free(cctx);
1737 # endif /* CFG_USE_OPENSSL_API_1_1 */
1738 
1739  if(NULL != tls_ctx)
1740  {
1741  SSL_CTX_free(tls_ctx);
1742  tls_ctx = NULL;
1743  }
1744 
1745  posix_free((void*) tls_certpath);
1746  tls_certpath = NULL;
1747 # if !CFG_TLS_CRLS_DISABLE
1748  posix_free((void*) tls_crlpath);
1749  tls_crlpath = NULL;
1750 # endif /* !CFG_TLS_CRLS_DISABLE */
1751 }
1752 
1753 
1754 /* ========================================================================== */
1755 /*! \brief Init TLS subsystem
1756  *
1757  * \return
1758  * - 0 on success
1759  * - Negative value on error
1760  */
1761 
1762 int tls_init(void)
1763 {
1764  int res = 0;
1765 
1766  /* Create a locale object with LC_CTYPE == POSIX */
1767  tls_loc_ctype_posix = posix_newlocale(POSIX_LC_CTYPE_MASK, "POSIX",
1768  (posix_locale_t) 0);
1769  if((posix_locale_t) 0 == tls_loc_ctype_posix)
1770  {
1771  PRINT_ERROR("Cannot create locale object");
1772  res = -1;
1773  }
1774 
1775  if(!res)
1776  {
1777  /*
1778  * Since OpenSSL 1.1.0 explicit initialization is no longer required:
1779  * https://www.openssl.org/docs/manmaster/man3/OPENSSL_init_ssl.html
1780  */
1781 # if !CFG_USE_OPENSSL_API_1_1
1782  /* Load strings for human readable error messsages */
1783  SSL_load_error_strings();
1784  /* Register available ciphers and digests */
1785  SSL_library_init();
1786 # if OPENSSL_VERSION_NUMBER == 0x1000000FL
1787  /*
1788  * Quoted from the OpenSSL documentation:
1789  * OpenSSL [...] 1.0.0a and later added SHA2 algorithms to
1790  * SSL_library_init(). Applications which need to use SHA2 in earlier
1791  * versions of OpenSSL should call OpenSSL_add_all_algorithms() as well.
1792  */
1793  OpenSSL_add_all_algorithms();
1794 # endif /* OPENSSL_VERSION_NUMBER == 1.0.0 */
1795 # endif /* !CFG_USE_OPENSSL_API_1_1 */
1796 
1797  /* Ensure that Pseudo Random Number Generator (PRNG) is seeded */
1798  if(!RAND_status())
1799  {
1800  PRINT_ERROR("Seeding PRNG failed, "
1801  "check your OpenSSL configuration");
1802  res = -1;
1803  }
1804  }
1805 
1806  return(res);
1807 }
1808 
1809 
1810 /* ========================================================================== */
1811 /*! \brief Shutdown TLS subsystem */
1812 
1813 void tls_exit(void)
1814 {
1815  if((posix_locale_t) 0 != tls_loc_ctype_posix)
1816  {
1817  posix_freelocale(tls_loc_ctype_posix);
1818  }
1819 
1820  /* Since OpenSSL 1.1.0 explicit cleanup is no longer required */
1821 # if !CFG_USE_OPENSSL_API_1_1
1822  EVP_cleanup();
1823 # endif /* !CFG_USE_OPENSSL_API_1_1 */
1824 }
1825 
1826 
1827 /* ========================================================================== */
1828 /*! \brief Check TLS subsystem for known vulnerabilities
1829  *
1830  * \param[in] check Execute vulnerability checks
1831  *
1832  * If \e check is zero, only the library name and version number is printed
1833  *
1834  * \attention
1835  * Because the TLS subsystem may use dynamically linked OpenSSL libraries, this
1836  * check can't be done at compile time!
1837  *
1838  * OpenSSL version numbers since 0.9.5 are composed as follows:
1839  *
1840  * 0xMNNFFPPS (Major miNor Fix Patch Status)
1841  * <br>
1842  * <hr>
1843  * 0x00906023 (0.9.6b beta 3)
1844  * <br>
1845  * 0x1000107F (1.0.1g release)
1846  * <br>
1847  * 0x20000000 (2.0.0 dev, reported by LibreSSL)
1848  * <br>
1849  * 0x30000000 (3.0.0 dev, reported by OpenSSL Alpha versions)
1850  *
1851  * \note
1852  * LibreSSL always reports the same OpenSSL version.
1853  *
1854  * \return
1855  * - 0 on success
1856  * - Negative value if TLS subsystem may use code with known vulnerabilities
1857  */
1858 
1860 {
1861  int res = 0;
1862  /* Using function instead of the constant is required for shared library */
1863 # if CFG_USE_OPENSSL_API_1_1
1864  unsigned long int version = OpenSSL_version_num();
1865 # else /* CFG_USE_OPENSSL_API_1_1 */
1866 # if CFG_USE_LIBRESSL && defined(LIBRESSL_VERSION_NUMBER)
1867  /* Documentation says LIBRESSL_VERSION_NUMBER always ends with 00F */
1868  unsigned long int version = LIBRESSL_VERSION_NUMBER;
1869 # else /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1870  unsigned long int version = SSLeay();
1871 # endif /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1872 # endif /* CFG_USE_OPENSSL_API_1_1 */
1873  unsigned int major = (unsigned int) ((version & 0xF0000000UL) >> 28);
1874  unsigned int minor = (unsigned int) ((version & 0x0FF00000UL) >> 20);
1875  unsigned int fix = (unsigned int) ((version & 0x000FF000UL) >> 12);
1876  unsigned int patch = (unsigned int) ((version & 0x00000FF0UL) >> 4);
1877 # if ! CFG_USE_LIBRESSL && ! CFG_USE_OPENSSL_API_3
1878  char patch_letter;
1879  char patch_string[4] = { 0, 0, 0, 0 };
1880 
1881  if(patch)
1882  {
1883  if(25U >= patch)
1884  {
1885  /* Single character */
1886  patch_letter = (char) (0x60U + patch);
1887  }
1888  else if(50U >= patch)
1889  {
1890  /* Second character */
1891  patch_letter = (char) (0x60U + patch - 25U);
1892  patch_string[1] = patch_letter;
1893  /* First character */
1894  patch_letter = 'z';
1895  }
1896  else if(75U >= patch)
1897  {
1898  /* Third character */
1899  patch_letter = (char) (0x60U + patch - 50U);
1900  patch_string[2] = patch_letter;
1901  /* Second character */
1902  patch_string[1] = 'z';
1903  /* First character */
1904  patch_letter = 'z';
1905  }
1906  else
1907  {
1908  /* This will hopefully never be required */
1909  patch_letter = '?';
1910  }
1911  patch_string[0] = patch_letter;
1912  }
1913 # endif /* ! CFG_USE_LIBRESSL && ! CFG_USE_OPENSSL_API_3 */
1914 
1915  /* Print version */
1916 # if CFG_USE_LIBRESSL && defined(LIBRESSL_VERSION_NUMBER)
1917  /* LibreSSL */
1918  printf("%s: %sCompiled for LibreSSL\n", CFG_NAME, MAIN_ERR_PREFIX);
1919  printf("%s: %sLibreSSL library version: %X.%X.%X (0x%08lX)\n",
1920  CFG_NAME, MAIN_ERR_PREFIX, major, minor, fix, version);
1921 # else /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1922  /* OpenSSL */
1923 # if CFG_USE_OPENSSL_API_3
1924  printf("%s: %sOpenSSL library version: %X.%X.%X (0x%08lX)\n",
1925  CFG_NAME, MAIN_ERR_PREFIX, major, minor, patch, version);
1926 # else /* CFG_USE_OPENSSL_API_3 */
1927  printf("%s: %sOpenSSL library version: %X.%X.%X%s (0x%08lX)\n",
1928  CFG_NAME, MAIN_ERR_PREFIX, major, minor, fix, patch_string, version);
1929 # endif /* CFG_USE_OPENSSL_API_3 */
1930 # endif /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1931 
1932  /* Print message if TLSv1.3 is avialable */
1933 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L) \
1934  || CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
1935  printf("%s: %sProtocol version TLSv1.3 available for negotiation\n",
1936  CFG_NAME, MAIN_ERR_PREFIX);
1937 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
1938  /* || CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
1939 
1940  if(check)
1941  {
1942  /*
1943  * Check for potential certificate check "#OprahSSL" bug (CVE-2015-1793)
1944  * in OpenSSL (Vulnerable versions: 1.0.1n, 1.0.1o, 1.0.2b and 1.0.2c)
1945  */
1946  if(1U == major && 0U == minor)
1947  {
1948  if( (1U == fix && 0xEU <= patch && 0xFU >= patch)
1949  || (2U == fix && 0x2U <= patch && 0x3U >= patch) )
1950  {
1951  printf("%s: %sOpenSSL library possibly vulnerable to #OprahSSL!\n",
1952  CFG_NAME, MAIN_ERR_PREFIX);
1953  res = -1;
1954  }
1955  }
1956 
1957  /*
1958  * Check for potential heartbeat "Heartbleed" bug (CVE-2014-0160) in
1959  * OpenSSL (Vulnerable versions: 1.0.1 to 1.0.1f)
1960  */
1961  if(1U == major && 0U == minor && 1U == fix && 7U > patch)
1962  {
1963  printf("%s: %sOpenSSL library possibly vulnerable to Heartbleed!\n",
1964  CFG_NAME, MAIN_ERR_PREFIX);
1965  res = -1;
1966  }
1967 
1968  /*
1969  * Check for potential MITM vulnerability (CVE-2014-0224) in OpenSSL
1970  * (Vulnerable versions: 1.0.0 to 1.0.0l and 1.0.1 to 1.0.1g)
1971  */
1972  if(1U == major && 0U == minor)
1973  {
1974  if( (0U == fix && 0x0DU > patch) || (1U == fix && 8U > patch) )
1975  {
1976  printf("%s: %s"
1977  "OpenSSL library possibly vulnerable to MITM attacks!\n",
1978  CFG_NAME, MAIN_ERR_PREFIX);
1979  res = -1;
1980  }
1981  }
1982  }
1983 
1984  return(res);
1985 }
1986 
1987 
1988 /* ========================================================================== */
1989 /*! \brief Check whether server name used for connection is not an IP address
1990  *
1991  * \param[in] sn Pointer to server name string
1992  *
1993  * An IP address cannot be used for the SNI extension.
1994  * This function should be called to determine whether a TCP connection was
1995  * established based on DNS name or IP address.
1996  *
1997  * The result can be used as parameter \c sni for the function \ref tls_open() .
1998  *
1999  * \return
2000  * - \e sn on success
2001  * - \c NULL if \e sn is a valid ASCII representation of an IP address
2002  */
2003 
2004 const char* tls_sni(const char* sn)
2005 {
2006  const char* res = NULL;
2007  unsigned char buf[16];
2008 
2009  if(1 != posix_inet_pton(POSIX_AF_INET, sn, buf))
2010  {
2011 #if CFG_USE_IP6
2012  if(1 != posix_inet_pton(POSIX_AF_INET6, sn, buf))
2013  {
2014  res = sn;
2015  }
2016 #else /* CFG_USE_IP6 */
2017  res = sn;
2018 #endif /* CFG_USE_IP6 */
2019  }
2020 
2021  return(res);
2022 }
2023 
2024 
2025 /* ========================================================================== */
2026 /*! \brief Establish TLS encryption layer on top of open network connection
2027  *
2028  * \param[in] sd Socket descriptor
2029  * \param[out] co Pointer to connection object pointer
2030  * \param[in] weak Offer weak cipher suite(s) to server
2031  * \param[in] sni Hostname for SNI extension (or \c NULL )
2032  *
2033  * The socket descriptor \e sd must be assigned to an open connection.
2034  *
2035  * If \e sni is \c NULL, the SNI extension is not used (but this is forbidden
2036  * by RFC 8143).
2037  * If the caller wants to use the SNI extension, \e sni must point to the
2038  * hostname string used for DNS resolution when the connection associated
2039  * with \e sd was established.
2040  *
2041  * On success, a pointer to the connection object is stored at the location
2042  * pointed by \e co .
2043  *
2044  * \attention
2045  * RFC 5246 specifies the cipher suite RSA-RSA-AES128-SHA (0x00, 0x2F) as
2046  * mandatory.
2047  * RFC 4642 specified the cipher suite RSA-RSA-RC4-MD5 (0x00, 0x04) as mandatory
2048  * in the past (it is preserved for backward compatibility).
2049  * Both will provide no forward secrecy and the latter one in addition use the
2050  * weak RC4 symmetric encryption algorithm.
2051  * Therefore they are not included in the default list of ciphers we offer to
2052  * the server.
2053  *
2054  * To comply with RFC 5246 and nevertheless offer the disabled cipher suites, or
2055  * if the server doesn't support FFDHE key exchange, \e weak must be set to a
2056  * nonzero value.
2057  *
2058  * If OpenSSL API 1.1 is available, the FFDHE group from the server are verified
2059  * to be at least 1024 bits in size for FFDHE key exchange (if \e weak is set to
2060  * zero).
2061  *
2062  * If OpenSSL API 1.1 is available and at least TLSv1.2 is used, the signature
2063  * algorithm to use for TLS protocol is negotiated with the server.
2064  * The algorithms we offer are defined with \ref TLS_SIGALGS for TLSv1.2.
2065  * The algorithms we offer are defined with \ref TLS_SIGALGS_TLS13 for TLSv1.3.
2066  *
2067  * \note
2068  * TLSv1.3 allows to offer a separate list of signature algorithms for
2069  * certificates. We do not use this feature and the certificates must use
2070  * signature algorithms listed in \ref TLS_SIGALGS_TLS13 .
2071  *
2072  * \return
2073  * - 0 on success
2074  * - Negative value on error
2075  */
2076 
2077 int tls_open(int sd, void** co, int weak, const char* sni)
2078 {
2079  int res = -1;
2080  int rv;
2081  long int rv2;
2082  SSL** ssl;
2083  unsigned long int error;
2084  const char* sp = NULL;
2085  const char* tlsv = NULL;
2086  const char* cp = NULL;
2087  const char* kx = NULL;
2088  char b[200];
2089 # if CFG_USE_OPENSSL_API_1_1
2090  EVP_PKEY* key = NULL;
2091  int length;
2092 # endif /* CFG_USE_OPENSSL_API_1_1 */
2093 # if CFG_USE_OPENSSL_API_1_1
2094  const char* dp = NULL;
2095 # if (OPENSSL_VERSION_NUMBER >= 0x10101000L)
2096  int id;
2097 # endif /* (OPENSSL_VERSION_NUMBER >= 1.1.1) */
2098  int id2;
2099 # endif /* CFG_USE_OPENSSL_API_1_1 */
2100 
2101  if(NULL != co)
2102  {
2103  ssl = (SSL**) co;
2104 
2105  /* Create context */
2106  res = tls_create_context(weak);
2107 
2108  /* Create connection object */
2109  if(!res)
2110  {
2111  *ssl = SSL_new(tls_ctx);
2112  if(NULL == *ssl)
2113  {
2114  PRINT_ERROR("Cannot create connection object");
2115  res = -1;
2116  }
2117  }
2118 
2119  /* Configure RFC 6066 SNI extension */
2120  if(!res && NULL != sni)
2121  {
2122  printf("%s: %sUsing SNI extension with: %s\n",
2123  CFG_NAME, MAIN_ERR_PREFIX, sni);
2124  rv2 = SSL_set_tlsext_host_name(*ssl, sni);
2125  if(1 != rv2)
2126  {
2127  PRINT_ERROR("Adding SNI extension from RFC 6066 failed");
2128  res = -1;
2129  }
2130  }
2131 
2132  /* Add weak cipher suites on request */
2133  if(!res && weak)
2134  {
2135  rv = SSL_set_cipher_list(*ssl, TLS_CIPHERS_WEAK);
2136  if(1 != rv)
2137  {
2138  PRINT_ERROR("Adding weak cipher suites failed");
2139  res = -1;
2140  }
2141  else
2142  {
2143  printf("%s: %sWarning: Offering weak protocol versions "
2144  "and cipher suites to server\n",
2145  CFG_NAME, MAIN_ERR_PREFIX);
2146  }
2147  }
2148 
2149  /* Attach connection object to socket */
2150  if(!res)
2151  {
2152  rv = SSL_set_fd(*ssl, sd);
2153  if(1 != rv)
2154  {
2155  PRINT_ERROR("Cannot assign connection object to socket");
2156  res = -1;
2157  }
2158  }
2159 
2160  /* Initiate TLS handshake */
2161  if(!res)
2162  {
2163  rv = SSL_connect(*ssl);
2164  if(1 != rv)
2165  {
2166  PRINT_ERROR("Failed to establish TLS connection");
2167  /* Assignment in truth expression is intended */
2168  while((error = ERR_get_error()))
2169  {
2170  sp = ERR_reason_error_string(error);
2171  posix_snprintf(b, 200, "%sError: %s", MAIN_ERR_PREFIX, sp);
2172  print_error(b);
2173  }
2174  res = -1;
2175  }
2176  else
2177  {
2178  /* Print cipher suite */
2179  res = tls_get_ciphersuite((void**) ssl, &tlsv, &cp, &kx);
2180  if(res) { PRINT_ERROR("Reading negotiation result failed"); }
2181  else
2182  {
2183  printf("%s: %sUsing protocol: %s with cipher suite %s\n",
2184  CFG_NAME, MAIN_ERR_PREFIX, tlsv, cp);
2185 # if CFG_USE_OPENSSL_API_1_1
2186  if(SSL_get_peer_signature_nid(*ssl, &id2))
2187  {
2188  dp = "rsaEncryption";
2189 # if (OPENSSL_VERSION_NUMBER >= 0x10101000L)
2190  if(SSL_get_peer_signature_type_nid(*ssl, &id))
2191  {
2192  dp = OBJ_nid2sn(id);
2193  }
2194 # endif /* (OPENSSL_VERSION_NUMBER >= 1.1.1) */
2195  if(!strcmp("rsaEncryption", dp)) { dp = "RSASSA-PKCS1-v1_5"; }
2196  printf("%s: %sPeer signature algorithm: %s+%s\n",
2197  CFG_NAME, MAIN_ERR_PREFIX, dp, OBJ_nid2sn(id2));
2198  }
2199  else
2200  {
2201  /* '!weak' indicates DHE key exchange here */
2202  /* Up to TLSv1.1 the signature algorithm is not selectable */
2203  if(!weak && strcmp("TLSv1", tlsv) && strcmp("TLSv1.1", tlsv))
2204  {
2205  PRINT_ERROR("Signature algorithm negotiation failed");
2206  res = -1;
2207  }
2208  }
2209 # else /* CFG_USE_OPENSSL_API_1_1 */
2210  if(!weak && strcmp("TLSv1", tlsv) && strcmp("TLSv1.1", tlsv))
2211  {
2212  printf("%s: %sWarning: Signature algorithm "
2213  "negotiation not possible with OpenSSL API 1.0\n",
2214  CFG_NAME, MAIN_ERR_PREFIX);
2215  }
2216 # endif /* CFG_USE_OPENSSL_API_1_1 */
2217  if(strcmp("TLSv1", tlsv) && strcmp("TLSv1.1", tlsv)
2218  && strcmp("TLSv1.2", tlsv))
2219  {
2220  if(!strcmp("FFDHE", kx))
2221  {
2222  printf("%s: %sKey exchange algorithm: %s\n",
2223  CFG_NAME, MAIN_ERR_PREFIX, kx);
2224  }
2225  else
2226  {
2227  printf("%s: %sKey exchange algorithm: ECDHE (%s)\n",
2228  CFG_NAME, MAIN_ERR_PREFIX, kx);
2229  }
2230  }
2231  }
2232 # if CFG_USE_OPENSSL_API_1_1
2233  if(!res && !weak)
2234  {
2235  /* Check FFDHE group (no negotiation possible before TLSv1.3) */
2236  rv = SSL_get_server_tmp_key(*ssl, &key);
2237  if(!rv) { res = -1; }
2238  if(!res)
2239  {
2240  if(EVP_PKEY_DH == EVP_PKEY_id(key))
2241  {
2242  length = EVP_PKEY_bits(key);
2243  if(0 >= length) { res = -1; }
2244  else
2245  {
2246  printf("%s: %sFFDHE group size: %d bit\n",
2247  CFG_NAME, MAIN_ERR_PREFIX, length);
2248  if(1024 > length)
2249  {
2250  PRINT_ERROR("FFDHE group size rejected");
2251  res = -1;
2252  }
2253  else if(3072 > length)
2254  {
2255  /* 3072 bit would match a 128 bit symmetric cipher */
2256  printf("%s: %sWarning: FFDHE group size should be"
2257  " at least 3072 bit\n",
2258  CFG_NAME, MAIN_ERR_PREFIX);
2259  }
2260  }
2261  }
2262  EVP_PKEY_free(key);
2263  key = NULL;
2264  }
2265  /* Close connection on error */
2266  if(res)
2267  {
2268  PRINT_ERROR("FFDHE group size check failed");
2269  tls_close((void*) ssl);
2270  }
2271  }
2272 # else /* CFG_USE_OPENSSL_API_1_1 */
2273  if(!res)
2274  {
2275 # if CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
2276  /* LibreSSL supports TLSv1.3 since version 3.1.1, but no FFDHE */
2277  if(strcmp("TLSv1.3", tlsv))
2278  {
2279 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
2280  printf("%s: %sWarning: FFDHE group size check not possible "
2281  "with OpenSSL API 1.0\n", CFG_NAME, MAIN_ERR_PREFIX);
2282 # if CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
2283  }
2284 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
2285  }
2286 # endif /* CFG_USE_OPENSSL_API_1_1 */
2287  }
2288  }
2289  }
2290 
2291  return(res);
2292 }
2293 
2294 
2295 /* ========================================================================== */
2296 /*! \brief Terminate TLS encryption layer on top of network connection
2297  *
2298  * \param[in,out] co Pointer to connection object pointer
2299  *
2300  * \note
2301  * This function also destroys the TLS context that contains the certificate
2302  * CRLs. After CRLs are updated, it is not required to shutdown the whole module
2303  * via \ref tls_exit() . Calling this function is sufficient to invalidate any
2304  * CRLs in memory.
2305  *
2306  * \return
2307  * - 1 on success
2308  * - Negative value on error
2309  */
2310 
2311 int tls_close(void** co)
2312 {
2313  int res = -1;
2314 
2315  if(NULL != co && NULL != *((SSL**) co))
2316  {
2317  /* Close connection */
2318  res = SSL_shutdown(*((SSL**) co));
2319  if(!res) { res = SSL_shutdown(*((SSL**) co)); }
2320  if(0 <= res && 1 != res)
2321  {
2322  PRINT_ERROR("Error while closing TLS connection");
2323  res = -1;
2324  }
2325 
2326  /* Destroy connection object */
2327  SSL_free(*((SSL**) co));
2328  *((SSL**) co) = NULL;
2329 
2330  /* Destroy context (including buffered CRLs) */
2331  tls_destroy_context();
2332  }
2333 
2334  return(res);
2335 }
2336 
2337 
2338 /* ========================================================================== */
2339 /*! \brief Get protocol and cipher suite name that was negotiated for connection
2340  *
2341  * \param[in] co Pointer to connection object pointer
2342  * \param[out] pv Pointer to protocol version string
2343  * \param[out] cs Pointer to cipher suite string
2344  * \param[out] kx Pointer to key exchange algorithm
2345  *
2346  * \attention
2347  * The value returned for \e kx is only valid when the protocol version returned
2348  * for \e pv is \c TLSv1.3 (for older protocol versions the key exchange
2349  * algorithm is negotiated as part of the cipher suite).
2350  *
2351  * \note
2352  * If the caller is not interested in the information, the parameters \e pv and
2353  * \e cs it is allowed to pass \c NULL .
2354  *
2355  * \return
2356  * - 0 on success
2357  * - -1 on error
2358  */
2359 
2360 int tls_get_ciphersuite(void** co, const char** pv, const char** cs,
2361  const char** kx)
2362 {
2363  int res = -1;
2364  SSL** ssl;
2365  const SSL_CIPHER* cp;
2366 # if CFG_USE_OPENSSL_API_1_1
2367  EVP_PKEY* tmp_key;
2368 # endif /* CFG_USE_OPENSSL_API_1_1 */
2369 
2370  ssl = (SSL**) co;
2371  cp = SSL_get_current_cipher(*ssl);
2372  if(NULL == cp)
2373  {
2374  PRINT_ERROR("Reading negotiated protocol and cipher suite failed");
2375  }
2376  else
2377  {
2378  /*
2379  * Note:
2380  * Calling 'SSL_CIPHER_get_version()' is wrong, because this function
2381  * reports the TLS version in which the used cipher suite was defined.
2382  * But this function should return information about the protocol used for
2383  * the current connection corresponding to parameter 'co'.
2384  */
2385  if(NULL != pv) { *pv = SSL_get_version(*ssl); }
2386  if(NULL != cs) { *cs = SSL_CIPHER_get_name(cp); }
2387  if(NULL != kx)
2388  {
2389 # if CFG_USE_OPENSSL_API_1_1
2390  if(SSL_get_server_tmp_key(*ssl, &tmp_key))
2391  {
2392  switch(EVP_PKEY_id(tmp_key))
2393  {
2394  case EVP_PKEY_DH:
2395  {
2396  *kx = "FFDHE";
2397  break;
2398  }
2399  default:
2400  {
2401  *kx = OBJ_nid2sn(EVP_PKEY_id(tmp_key));
2402  break;
2403  }
2404  }
2405  EVP_PKEY_free(tmp_key);
2406  res = 0;
2407  }
2408 # else /* CFG_USE_OPENSSL_API_1_1 */
2409  *kx = "Unknown";
2410  res = 0;
2411 # endif /* CFG_USE_OPENSSL_API_1_1 */
2412  }
2413  else { res = 0; }
2414  res = 0;
2415  }
2416 
2417  return(res);
2418 }
2419 
2420 
2421 /* ========================================================================== */
2422 /*! \brief Check whether server has presented a certificate and verify it
2423  *
2424  * \param[in] co Pointer to connection object pointer
2425  * \param[out] cert Pointer to cerificate pointer
2426  * \param[in] cn Common name string the certificate should contain
2427  * \param[in] weak Disable some checks for better compatibility
2428  *
2429  * \attention
2430  * The parameter \e weak must be set to the same value that was used for the
2431  * call to \ref tls_open() .
2432  *
2433  * The verification executes the following steps:
2434  * - Ensure that the server has presented a certificate (chain)
2435  * - Optional: Check the signature algorithms and key lengths used in the
2436  * certificate chain (Setting \e weak to a nonzero value disables this step)
2437  * - Follow certificate chain back to the anchor and verify that it is trusted
2438  * - Optional: Verify that none of the certificates in the chain was revoked
2439  * (The CRLs for the revocation checks are downloaded automatically)
2440  * - Verify that the subject of the certificate contain \e cn
2441  *
2442  * According to RFC 8143 the following rules are applied:
2443  * - The matching of hostname \e cn must be case-insensitive => We do so.
2444  * - Wildcard \c * is allowed as left-most name component => We accept this.
2445  * - Hostnames listed via \c subjectAltName extension should be checked first
2446  * => We do so.
2447  * - If the certificate contains multiple names (e.g., more than one \c dNSName
2448  * field), then a match with any one of the fields is considered acceptable
2449  * => We accept any match.
2450  *
2451  * If the return value is not negative, the server has presented a certificate
2452  * and a pointer to it was written to \e cert .
2453  *
2454  * \note
2455  * The returned value for \e cert stay in memory until the connection object
2456  * \e co is destroyed.
2457  *
2458  * The return value \c -2 should be interpreted as a request to close the
2459  * connection and re-establish it again (and then using the new CRLs).
2460  *
2461  * \return
2462  * - 0 on success (Certificate was presented, is valid and trusted)
2463  * - 1 if the certificate is not trusted
2464  * - -1 on error
2465  * - -2 if the verification was not executed because CRLs have been updated
2466  */
2467 
2468 int tls_cert_verify(void** co, void** cert, const char* cn, int weak)
2469 {
2470  int res = 0;
2471  SSL** ssl = (SSL**) co;
2472  STACK_OF(X509)* certificate_chain = NULL;
2473  X509* certificate = NULL;
2474  X509_NAME* subject;
2475  X509_NAME_ENTRY* common_name;
2476  ASN1_STRING* common_name_string;
2477  BIO* biop = BIO_new(BIO_s_mem());
2478  long int rv;
2479  const char* sp = NULL;
2480  char b[256];
2481  const char* p = NULL;
2482  int i = -1;
2483  GENERAL_NAMES* an = NULL;
2484  GENERAL_NAME* ani;
2485  int num;
2486  int match = 0;
2487  const char* pv;
2488  int proto = 0;
2489 
2490  /* Extract whole certificate chain from connection object */
2491  certificate_chain = SSL_get_peer_cert_chain(*ssl);
2492  if(NULL == certificate_chain)
2493  {
2494  PRINT_ERROR("Extracting certificate chain failed");
2495  res = -1;
2496  }
2497  if(!res && weak)
2498  {
2499  printf("%s: %sWarning: Using weak certificate chain checks\n",
2500  CFG_NAME, MAIN_ERR_PREFIX);
2501  }
2502 
2503  /* Update CRLs for certificate chain */
2504 # if !CFG_TLS_CRLS_DISABLE
2505  if(!res && config[CONF_CRL_CHECK].val.i)
2506  {
2507  if(!tls_crl_update_skip && tls_check_crl_age())
2508  {
2509  res = tls_update_crls(certificate_chain);
2510  if(0 > res) { PRINT_ERROR("Updating of CRLs failed"); }
2511  else
2512  {
2513  /* CRLs successfully updated */
2514  tls_set_crl_age();
2515  if(0 < res)
2516  {
2517  /* Self signed root certificate */
2518  PRINT_ERROR("No CRLs required");
2519  res = 0;
2520  }
2521  else
2522  {
2523  /* Request to close and reopen connection */
2524  PRINT_ERROR("Verification of certificate aborted because "
2525  "of CRL update");
2526  SSL_get_verify_result(*ssl);
2527  res = -2;
2528  }
2529  }
2530  }
2531  }
2532 # endif /* !CFG_TLS_CRLS_DISABLE */
2533 
2534  /* Check algorithms and key length of signatures in certificate chain */
2535  if(!res && !weak)
2536  {
2537  res = tls_get_ciphersuite((void**) ssl, &pv, NULL, NULL);
2538  if(res) { PRINT_ERROR("Reading protocol version failed"); }
2539  else
2540  {
2541  /* Check for TLS protocol minor number */
2542  if(!strcmp("TLSv1", pv)) { proto = 0; }
2543  else if(!strcmp("TLSv1.1", pv)) { proto = 1; }
2544  else if(!strcmp("TLSv1.2", pv)) { proto = 2; }
2545  else { proto = 3; }
2546  }
2547  if(!res)
2548  {
2549  res = tls_chain_check_sigalgs(certificate_chain, proto);
2550  }
2551  }
2552 
2553  /* Verify server certificate */
2554  if(!res)
2555  {
2556 # if CFG_USE_OPENSSL_API_3
2557  certificate = SSL_get1_peer_certificate(*ssl);
2558 # else /* CFG_USE_OPENSSL_API_3 */
2559  certificate = SSL_get_peer_certificate(*ssl);
2560 # endif /* CFG_USE_OPENSSL_API_3 */
2561  if(NULL == certificate)
2562  {
2563  PRINT_ERROR("Server has presented no certificate");
2564  res = -1;
2565  }
2566  else
2567  {
2568  /* Certificate present */
2569  res = 1;
2570  *cert = (void*) certificate;
2571  /* Let OpenSSL check whether the certificate is trusted */
2572  rv = SSL_get_verify_result(*ssl);
2573  if(X509_V_OK != rv)
2574  {
2575  sp = X509_verify_cert_error_string(rv);
2576  /* printf("Errorcode: %d\n", ERR_GET_REASON(rv)); */
2577  posix_snprintf(b, 256,
2578  "%sAlert: Server X.509 certificate verification "
2579  "failed (%s)", MAIN_ERR_PREFIX, sp);
2580  print_error(b);
2581 # if !CFG_TLS_CRLS_DISABLE
2582  if(X509_V_ERR_UNABLE_TO_GET_CRL == rv
2583  || X509_V_ERR_CRL_HAS_EXPIRED == rv)
2584  {
2585  /* Reset CRL update timestamp to force new CRL update */
2586  PRINT_ERROR("Resetting CRL update timestamp");
2587  tls_reset_crl_age();
2588  }
2589 # endif /* !CFG_TLS_CRLS_DISABLE */
2590  }
2591  else
2592  {
2593  /* Verify subject */
2594  subject = X509_get_subject_name(certificate);
2595  if(NULL == subject)
2596  {
2597  PRINT_ERROR("Extraction of subject from X.509 certificate "
2598  "failed");
2599  }
2600  else
2601  {
2602  printf("%s: %sServer certificate:\n", CFG_NAME, MAIN_ERR_PREFIX);
2603  /* Extract alternative names first and compare with cn */
2604  an = X509_get_ext_d2i(certificate, NID_subject_alt_name,
2605  NULL, NULL);
2606  if(NULL != an)
2607  {
2608  num = sk_GENERAL_NAME_num(an);
2609  for(i = 0; i < num; ++i)
2610  {
2611  ani = sk_GENERAL_NAME_value(an, i);
2612  if(GEN_DNS == ani->type)
2613  {
2614 # if CFG_USE_OPENSSL_API_1_1
2615  p = (const char*) ASN1_STRING_get0_data(ani->d.dNSName);
2616 # else /* CFG_USE_OPENSSL_API_1_1 */
2617  /* This function is deprecated since API 1.1 */
2618  p = (const char*) ASN1_STRING_data(ani->d.dNSName);
2619 # endif /* CFG_USE_OPENSSL_API_1_1 */
2620  printf("%s: %s Subject Alternative Name: %s",
2621  CFG_NAME, MAIN_ERR_PREFIX, p);
2622  if(!tls_subject_check(cn, p)) { match = 1; break; }
2623  }
2624  }
2625  GENERAL_NAMES_free(an);
2626  }
2627  /* Extract common names from subject and compare with cn */
2628  if(!match)
2629  {
2630  while(1)
2631  {
2632  i = X509_NAME_get_index_by_NID(subject, NID_commonName, i);
2633  if(-1 == i) { break; }
2634  common_name = X509_NAME_get_entry(subject, i);
2635  common_name_string = X509_NAME_ENTRY_get_data(common_name);
2636 # if CFG_USE_OPENSSL_API_1_1
2637  p = (const char*) ASN1_STRING_get0_data(common_name_string);
2638 # else /* CFG_USE_OPENSSL_API_1_1 */
2639  /* This function is deprecated since API 1.1 */
2640  p = (const char*) ASN1_STRING_data(common_name_string);
2641 # endif /* CFG_USE_OPENSSL_API_1_1 */
2642  printf("%s: %s Subject Name: %s",
2643  CFG_NAME, MAIN_ERR_PREFIX, p);
2644  if(!tls_subject_check(cn, p)) { match = 1; break; }
2645  }
2646  }
2647  if(!match)
2648  {
2649  posix_snprintf(b, 256,
2650  "%sAlert: Server X.509 certificate "
2651  "verification failed "
2652  "(Subject doesn't match hostname %s)",
2653  MAIN_ERR_PREFIX, cn);
2654  print_error(b);
2655  }
2656  else
2657  {
2658  /* We trust the certificate and certificate match hostname */
2659 # if !CFG_TLS_CRLS_DISABLE
2660  if(config[CONF_CRL_CHECK].val.i)
2661  {
2662  printf("%s: %sServer certificate verification "
2663  "successful\n", CFG_NAME, MAIN_ERR_PREFIX);
2664  }
2665  else
2666  {
2667  printf("%s: %sServer certificate verification "
2668  "succesful (revocation checks were skipped)\n",
2669  CFG_NAME, MAIN_ERR_PREFIX);
2670  }
2671 # else /* !CFG_TLS_CRLS_DISABLE */
2672  printf("%s: %sServer certificate verification successful "
2673  "(revocation checks were skipped)\n",
2674  CFG_NAME, MAIN_ERR_PREFIX);
2675 # endif /* !CFG_TLS_CRLS_DISABLE */
2676  res = 0;
2677  }
2678  }
2679  }
2680  }
2681  }
2682 
2683  /* Clean up */
2684  if(NULL != certificate) { X509_free(certificate); }
2685  if(NULL != biop) { BIO_free(biop); }
2686 
2687  return(res);
2688 }
2689 
2690 
2691 /* ========================================================================== */
2692 /*! \brief Print certificate
2693  *
2694  * \param[in] cert Pointer to cerificate
2695  * \param[out] cbuf Pointer buffer pointer
2696  *
2697  * On success, a memory block is allocated for the certificate and a pointer to
2698  * it is written to \e cbuf. The caller is responsible to free the memory block
2699  * allocated for the certificate.
2700  *
2701  * \return
2702  * - 0 on success
2703  * - -1 on error
2704  */
2705 
2706 int tls_cert_get_string(void* cert, const char** cbuf)
2707 {
2708  int res = -1;
2709  X509* certificate;
2710  BIO* biop = BIO_new(BIO_s_mem());
2711  int rv;
2712  char* p = NULL;
2713  size_t len;
2714  char* buf = NULL;
2715 
2716  certificate = (X509*) cert;
2717  rv = X509_print(biop, certificate);
2718  if(1 == rv)
2719  {
2720  len = (size_t) BIO_get_mem_data(biop, &p);
2721  if(NULL != p && len)
2722  {
2723  buf = (char*) posix_malloc(len + (size_t) 1);
2724  if(NULL != buf)
2725  {
2726  memcpy((void*) buf, (void*) p, len);
2727  buf[len] = 0;
2728  *cbuf = buf;
2729  res = 0;
2730  }
2731  }
2732  }
2733 
2734  /* Clean up */
2735  if(NULL != biop) { BIO_free(biop); }
2736  if(res) { posix_free((void*) buf); }
2737 
2738  return(res);
2739 }
2740 
2741 
2742 /* ========================================================================== */
2743 /*! \brief Send data
2744  *
2745  * \param[in] co Pointer to connection object pointer
2746  * \param[in] buf Pointer to data buffer
2747  * \param[in] len Number of octets to send
2748  *
2749  * \return
2750  * - Number of bytes sent
2751  * - -1 on error
2752  */
2753 
2754 posix_ssize_t tls_send(void* co, const void* buf, size_t len)
2755 {
2756  posix_ssize_t res = -1;
2757  int num;
2758 
2759  /* Check size */
2760  if(POSIX_INT_MAX < len)
2761  {
2762  PRINT_ERROR("tls_send(): Data length too large");
2763  }
2764  num = (int) len;
2765 
2766  res = (posix_ssize_t) SSL_write((SSL*) co, buf, num);
2767  if(!res) { res = -1; }
2768 
2769  return(res);
2770 }
2771 
2772 
2773 /* ========================================================================== */
2774 /*! \brief Receive data
2775  *
2776  * \param[in] co Pointer to connection object pointer
2777  * \param[out] buf Pointer to data buffer
2778  * \param[in] len Number of octets to receive
2779  * \param[in] peek Data should stay available for reading if nonzero
2780  *
2781  * \attention
2782  * The \e peek flag doesn't work anymore since OpenSSL 1.1.0 and must be zero
2783  * in this case (otherwise a deadlock will occur).
2784  * This bug was fixed before OpenSSL 1.1.1 (works again now).
2785  *
2786  * \return
2787  * - Number of bytes received
2788  * - -1 on error
2789  */
2790 
2791 posix_ssize_t tls_recv(void* co, void* buf, size_t len, int peek)
2792 {
2793  posix_ssize_t res = -1;
2794  int num;
2795 
2796  /* Check size */
2797  if(POSIX_INT_MAX < len)
2798  {
2799  PRINT_ERROR("tls_recv(): Data length too large");
2800  }
2801  num = (int) len;
2802 
2803  /* Check for peek flag */
2804  if(peek)
2805  {
2806 # if CFG_USE_OPENSSL_API_1_1 && !CFG_USE_OPENSSL_API_3
2807  PRINT_ERROR("tls_recv(): "
2808  "Flag 'peek' not supported with OpenSSL 1.1.x");
2809 # else /* CFG_USE_OPENSSL_API_1_1 && !CFG_USE_OPENSSL_API_3 */
2810  res = (posix_ssize_t) SSL_peek((SSL*) co, buf, num);
2811 # endif /* CFG_USE_OPENSSL_API_1_1 && !CFG_USE_OPENSSL_API_3 */
2812  }
2813  else { res = (posix_ssize_t) SSL_read((SSL*) co, buf, num); }
2814  if(!res) { res = -1; }
2815 
2816  return(res);
2817 }
2818 
2819 
2820 /* ========================================================================== */
2821 /*! \brief Check whether CRL update interval has elapsed
2822  *
2823  * This function is exported for the UI module to check the CRL update interval
2824  * and give the user a choice to delay the CRL updates.
2825  * The function \ref tls_crl_update_control() is intended to enable and disable
2826  * the automatic CRL updates.
2827  *
2828  * \note
2829  * The update choice can be disabled with configuration option \c CONF_CRL_UPD_C
2830  * (if configured to zero, this function will alays return zero).
2831  *
2832  * \return
2833  * - 0 Do nothing
2834  * - 1 CRL update interval elapsed. Give user a choice to suppress update
2835  * - -1 on error
2836  */
2837 
2839 {
2840  int res = 0;
2841 
2842 # if !CFG_TLS_CRLS_DISABLE
2844  {
2845  res = tls_check_crl_age();
2846  }
2847 # endif /* !CFG_TLS_CRLS_DISABLE */
2848 
2849  return(res);
2850 }
2851 
2852 
2853 /* ========================================================================== */
2854 /*! \brief Enable or disable automatic CRL updates
2855  *
2856  * \param[in] crl_upd_disable Disable automatic CRL updates if nonzero
2857  *
2858  * \attention
2859  * If CRLs are used, they need to be present and valid! With this function the
2860  * update of CRLs can only be suppressed until they expire. After expiration of
2861  * the CRLs a TLS connection can no longer be established (if a certificate
2862  * chain is used for authentication).
2863  *
2864  * \note
2865  * When disabled, the CRL updates can be reenabled on the fly at any time by
2866  * calling this function again with \e crl_upd_disable set to zero.
2867  */
2868 
2869 void tls_crl_update_control(int crl_upd_disable)
2870 {
2871 # if !CFG_TLS_CRLS_DISABLE
2872  /* Store CRL update flag */
2873  tls_crl_update_skip = crl_upd_disable;
2874 # endif /* !CFG_TLS_CRLS_DISABLE */
2875 }
2876 
2877 
2878 /* ========================================================================== */
2879 /*! \brief Free an object allocated by TLS module
2880  *
2881  * Use this function to release dynamic memory that was allocated by the
2882  * TLS module.
2883  *
2884  * \param[in] p Pointer to object
2885  *
2886  * Release the memory for the object pointed to by \e p.
2887  *
2888  * \note
2889  * The pointer \e p is allowed to be \c NULL and no operation is performed in
2890  * this case.
2891  */
2892 
2893 void tls_free(void* p)
2894 {
2895  posix_free(p);
2896 }
2897 
2898 
2899 #endif /* CFG_USE_TLS */
2900 
2901 
2902 /*! @} */
2903 
2904 /* EOF */
enc_get_iso8601_utc
int enc_get_iso8601_utc(char *isodate)
Get current UTC date in ISO 8601 conformant format.
Definition: encoding.c:4395
tls_vulnerability_check
int tls_vulnerability_check(int check)
Check TLS subsystem for known vulnerabilities.
Definition: tls.c:1859
tls_exit
void tls_exit(void)
Shutdown TLS subsystem.
Definition: tls.c:1813
TLS_CIPHERS_DEFAULT
#define TLS_CIPHERS_DEFAULT
Default (strong) cipher suite list for TLSv1.0 to TLSv1.2 protocols.
Definition: tls.c:153
tls_free
void tls_free(void *p)
Free an object allocated by TLS module.
Definition: tls.c:2893
tls_send
posix_ssize_t tls_send(void *co, const void *buf, size_t len)
Send data.
Definition: tls.c:2754
tls_close
int tls_close(void **co)
Terminate TLS encryption layer on top of network connection.
Definition: tls.c:2311
CONF_CRL_CHECK
Definition: conf.h:64
tls_crl_update_check
int tls_crl_update_check(void)
Check whether CRL update interval has elapsed.
Definition: tls.c:2838
TLS_ECDHE_GROUPS_TLS13
#define TLS_ECDHE_GROUPS_TLS13
ECDHE groups for TLSv1.3 protocol.
Definition: tls.c:226
core_time_t
unsigned long int core_time_t
Time in seconds since the epoche (in terms of POSIX.1)
Definition: core.h:54
MAIN_ERR_PREFIX
#define MAIN_ERR_PREFIX
Message prefix for TLS module.
Definition: tls.c:101
tls_recv
posix_ssize_t tls_recv(void *co, void *buf, size_t len, int peek)
Receive data.
Definition: tls.c:2791
tls_cert_get_string
int tls_cert_get_string(void *cert, const char **cbuf)
Print certificate.
Definition: tls.c:2706
fu_lock_file
int fu_lock_file(int filedesc)
Lock file for writing.
Definition: fileutils.c:328
tls_get_ciphersuite
int tls_get_ciphersuite(void **co, const char **pv, const char **cs, const char **kx)
Get protocol and cipher suite name that was negotiated for connection.
Definition: tls.c:2360
config
struct conf config[CONF_NUM]
Global configuration.
Definition: conf.c:63
tls_open
int tls_open(int sd, void **co, int weak, const char *sni)
Establish TLS encryption layer on top of open network connection.
Definition: tls.c:2077
conf_string_replace
int conf_string_replace(struct conf *cfg, const char *s)
Replace configuration string.
Definition: conf.c:912
fu_create_path
int fu_create_path(const char *path, posix_mode_t perm)
Create path.
Definition: fileutils.c:119
digest_randomart
int digest_randomart(const char *prefix, const char *buf, size_t len)
Create randomart image of a key.
Definition: drunken_bishop.c:180
TLS_FFDHE_GROUPS
#define TLS_FFDHE_GROUPS
FFDHE groups for TLSv1.2 and TLSv1.3 protocols.
Definition: tls.c:234
TLS_CIPHERS_WEAK
#define TLS_CIPHERS_WEAK
Optional (weak) cipher suite list for TLSv1.0 to TLSv1.2 protocols.
Definition: tls.c:172
TLS_SIGALGS_TLS13
#define TLS_SIGALGS_TLS13
Additional signature algorithms for TLSv1.3 protocol.
Definition: tls.c:201
tls_init
int tls_init(void)
Init TLS subsystem.
Definition: tls.c:1762
conf_entry_val::i
int i
Definition: conf.h:102
tls_cert_verify
int tls_cert_verify(void **co, void **cert, const char *cn, int weak)
Check whether server has presented a certificate and verify it.
Definition: tls.c:2468
PRINT_ERROR
#define PRINT_ERROR(s)
Prepend module prefix and print error message.
Definition: main.h:19
tls_sni
const char * tls_sni(const char *sn)
Check whether server name used for connection is not an IP address.
Definition: tls.c:2004
ext_download_file
int ext_download_file(const char *lpn, const char *uri)
Download file from external source.
Definition: extutils.c:1064
xdg_get_confdir
const char * xdg_get_confdir(const char *)
Get configuration directory.
Definition: xdg.c:115
xdg_append_to_path
int xdg_append_to_path(const char **, const char *)
Append path component to buffer.
Definition: xdg.c:55
TLS_SIGALGS
#define TLS_SIGALGS
Signature algorithms for TLSv1.2 protocol.
Definition: tls.c:223
fu_delete_tree
int fu_delete_tree(const char *dir)
Delete directory tree.
Definition: fileutils.c:578
TLS_CIPHERS_TLS13
#define TLS_CIPHERS_TLS13
Cipher suite list for TLSv1.3.
Definition: tls.c:116
fu_sync
int fu_sync(int filedesc, FILE *stream)
Flush buffers of file.
Definition: fileutils.c:402
CONF_CRL_UPD_TS
Definition: conf.h:66
fu_close_file
void fu_close_file(int *filedesc, FILE **stream)
Close file (and potentially associated I/O stream)
Definition: fileutils.c:290
conf::val
union conf_entry_val val
Definition: conf.h:111
CONF_CRL_UPD_C
Definition: conf.h:67
CONF_TLS_OWNCERTS
Definition: conf.h:63
tls_crl_update_control
void tls_crl_update_control(int crl_upd_disable)
Enable or disable automatic CRL updates.
Definition: tls.c:2869
CONF_CRL_UPD_IV
Definition: conf.h:65
enc_convert_iso8601_to_posix
int enc_convert_iso8601_to_posix(core_time_t *pts, const char *isodate)
Convert ISO 8601 conformant UTC date and time to POSIX timestamp.
Definition: encoding.c:4450
fu_open_file
int fu_open_file(const char *pathname, int *filedesc, int mode, posix_mode_t perm)
Open file.
Definition: fileutils.c:243
print_error
void print_error(const char *)
Print error message.
Definition: main.cxx:276

Generated at 2024-04-27 using  doxygen