tls.c
Go to the documentation of this file.
1 /* ========================================================================== */
2 /*! \file
3  * \brief Transport layer security
4  *
5  * Copyright (c) 2012-2024 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 api_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*) api_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*) api_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  api_posix_free((void*) b_i);
377  api_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, (api_posix_mode_t) API_POSIX_S_IRWXU);
410  }
411  }
412 
413  /* Free memory on error */
414  if(res)
415  {
416  PRINT_ERROR("Cannot create certificate directory");
417  api_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  api_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  api_posix_time(&ts);
450  if((api_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, (api_posix_mode_t) API_POSIX_S_IRWXU);
542  }
543  }
544 
545  /* Free memory on error */
546  if(res)
547  {
548  PRINT_ERROR("Cannot create CRL directory");
549  api_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 = api_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*) api_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  api_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*) api_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, API_POSIX_O_WRONLY | API_POSIX_O_CREAT,
719  API_POSIX_S_IRUSR | API_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 = api_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  api_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 = api_posix_snprintf(name_symlink, 13, "/%08lx.r%u", issuer_hash,
809  i);
810  if(12 != rv)
811  {
812  PRINT_ERROR("Creating of symlink failed, name not valid");
813  abort = 1;
814  }
815  else
816  {
817  len = strlen(tls_crlpath);
818  len += strlen(name_symlink);
819  pn_symlink = (char*) api_posix_malloc(++len);
820  if(NULL == pn_symlink) { abort = 1; }
821  else
822  {
823  strcpy(pn_symlink, tls_crlpath);
824  strcat(pn_symlink, name_symlink);
825  res = api_posix_symlink(pn_pem, pn_symlink);
826  if(!res)
827  {
828  /* Success */
829  abort = 1;
830  }
831  else
832  {
833  /* Check whether symlink already exist */
834  if(!(-1 == res && API_POSIX_EEXIST == api_posix_errno))
835  {
836  /* No => Creation failed => Abort */
837  PRINT_ERROR("Creating of symlink failed");
838  abort = 1;
839  }
840  }
841  api_posix_free((void*) pn_symlink);
842  }
843  }
844  ++i;
845  }
846  /* Check whether duplicate numbers gone out */
847  if(9 < i)
848  {
849  PRINT_ERROR("Creating of symlink failed, too many duplicates");
850  }
851  }
852 
853  return(res);
854 }
855 
856 
857 /* ========================================================================== */
858 /* Get mutex for CRL update
859  *
860  * \param[out] fd Pointer to filedescriptor of lockfile
861  */
862 
863 static int tls_crl_get_lock(int* fd)
864 {
865  int res = -1;
866  const char crl_lockfile[] = ".crl_lock";
867  const char* lockpathname = NULL;
868  int rv;
869 
870  lockpathname = xdg_get_confdir(CFG_NAME);
871  if(NULL != lockpathname)
872  {
873  rv = fu_create_path(lockpathname, (api_posix_mode_t) API_POSIX_S_IRWXU);
874  if(0 == rv)
875  {
876  /* Store lock file pathname */
877  rv = xdg_append_to_path(&lockpathname, crl_lockfile);
878  if(0 == rv)
879  {
880  rv = fu_open_file(lockpathname, fd,
881  API_POSIX_O_WRONLY | API_POSIX_O_CREAT,
882  API_POSIX_S_IRUSR | API_POSIX_S_IWUSR);
883  if(rv)
884  {
885  PRINT_ERROR("Cannot open mutex file for CRL directory");
886  }
887  else
888  {
889  if(fu_lock_file(*fd))
890  {
891  PRINT_ERROR("Cannot lock mutex file for CRL directory");
892  }
893  else
894  {
895  /* Mutex for CRL directory claimed */
896  res = 0;
897  }
898  }
899  }
900  }
901  }
902  api_posix_free((void*) lockpathname);
903 
904  return(res);
905 }
906 
907 
908 /* ========================================================================== */
909 /* Release mutex for CRL update
910  *
911  * \param[in,out] fd Pointer to filedescriptor of lockfile
912  */
913 
914 static void tls_crl_release_lock(int* fd)
915 {
916  fu_close_file(fd, NULL);
917 }
918 
919 
920 /* ========================================================================== */
921 /* Update CRLs for certificate chain
922  *
923  * \param[in] certificate_chain Pointer to certificate chain
924  *
925  * \return
926  * - 0 on success
927  * - Positive value if no CRLs are required (self signed server certificate)
928  * - -1 on unknown error
929  * - -2 if the lock for the mutex file can't be acquired
930  */
931 
932 static int tls_update_crls(STACK_OF(X509)* certificate_chain)
933 {
934  int res = -1;
935  int rv;
936  int crl_valid = 0;
937  int crls_required = 0;
938  int ccl; /* Length of certificate chain */
939  int cci; /* Index in certificate chain */
940  X509* cc; /* Current certificate */
941  int num, num2;
942  int i, i2;
943  STACK_OF(DIST_POINT)* dp = NULL;
944  DIST_POINT* dpi;
945  GENERAL_NAME* ani;
946  const size_t buflen = 256;
947  char b_i[buflen];
948  int is_root = 0;
949  char* p = NULL;
950  char* crl_pn_der; /* Pathname to raw CRL (expected in DER format) */
951  char* crl_pn_pem; /* Pathname of cooked CRL (in PEM format) */
952  int crlpath_ok = 0;
953  int lockfd = -1;
954 
955  /* Prepare and lock mutex file for CRL update */
956  if(tls_crl_get_lock(&lockfd)) { res = -2; }
957  else
958  {
959  /* Got lock => Automatic CRL update */
960  printf("%s: %s-----------------------------------------------------\n",
961  CFG_NAME, MAIN_ERR_PREFIX);
962  printf("%s: %sAutomatic CRL maintenance\n", CFG_NAME, MAIN_ERR_PREFIX);
963  /* Delete CRL directory */
964  if(NULL != tls_crlpath)
965  {
966  if(!fu_delete_tree(tls_crlpath))
967  {
968  if(!api_posix_mkdir(tls_crlpath,
969  (api_posix_mode_t) API_POSIX_S_IRWXU))
970  {
971  /* Empty CRL directory is now available */
972  crlpath_ok = 1;
973  }
974  }
975  }
976  if(!crlpath_ok)
977  {
978  PRINT_ERROR("CRL update failed, directory not available");
979  }
980  else
981  {
982  /* Get length of certificate chain */
983  ccl = sk_X509_num(certificate_chain);
984  for(cci = 0; cci < ccl; ++cci)
985  {
986  /* Get next certificate */
987  cc = sk_X509_value(certificate_chain, cci);
988  if(NULL == cc)
989  {
990  PRINT_ERROR("Error while parsing certificate chain");
991  break;
992  }
993  rv = tls_cert_check_root(cc, &is_root, buflen, b_i, NULL);
994  if(rv) { break; }
995  /* Determine type of certificate */
996  if(!cci)
997  {
998  if(is_root)
999  {
1000  printf("%s: %sSelf signed server certificate:\n",
1001  CFG_NAME, MAIN_ERR_PREFIX);
1002  }
1003  else
1004  {
1005  printf("%s: %sServer certificate:\n",
1006  CFG_NAME, MAIN_ERR_PREFIX);
1007  }
1008  }
1009  else
1010  {
1011  if(is_root)
1012  {
1013  printf("%s: %sRoot certificate:\n",
1014  CFG_NAME, MAIN_ERR_PREFIX);
1015  }
1016  else
1017  {
1018  printf("%s: %sIntermediate certificate:\n",
1019  CFG_NAME, MAIN_ERR_PREFIX);
1020  }
1021  }
1022  /* Print issuer */
1023  printf("%s: %s Issuer: %s\n", CFG_NAME, MAIN_ERR_PREFIX, b_i);
1024  /* Get CRL of certificate */
1025  crl_valid = 0;
1026  if(is_root)
1027  {
1028  printf("%s: %s Always trusted if installed"
1029  " (Must be uninstalled for revocation)\n",
1030  CFG_NAME, MAIN_ERR_PREFIX);
1031  res = 0;
1032  }
1033  else
1034  {
1035  dp = X509_get_ext_d2i(cc, NID_crl_distribution_points, NULL,
1036  NULL);
1037  if(NULL == dp)
1038  {
1039  PRINT_ERROR(" No CRL distribution points found"
1040  " in certificate");
1041  }
1042  else
1043  {
1044  num2 = sk_DIST_POINT_num(dp);
1045  for(i2 = 0; i2 < num2; ++i2)
1046  {
1047  dpi = sk_DIST_POINT_value(dp, i2);
1048  if(NULL != dpi->distpoint)
1049  {
1050  num = sk_GENERAL_NAME_num(
1051  dpi->distpoint->name.fullname);
1052  for(i = 0; i < num; ++i)
1053  {
1054  ani = sk_GENERAL_NAME_value(
1055  dpi->distpoint->name.fullname, i);
1056  if(GEN_URI == ani->type)
1057  {
1058  p = (char*)
1059  ani->d.uniformResourceIdentifier->data;
1060  printf("%s: %s "
1061  "CRL distribution point %d: %s\n",
1062  CFG_NAME, MAIN_ERR_PREFIX, i2, p);
1063  /* Download CRL */
1064  crl_pn_der = NULL;
1065  crl_pn_pem = NULL;
1066  res = tls_download_crl(cci, p, &crl_pn_der);
1067  if(!res)
1068  {
1069  /* Convert CRL to PEM format */
1070  res = tls_convert_crl_to_pem(crl_pn_der,
1071  &crl_pn_pem);
1072  if(!res)
1073  {
1074  /* Create symlink to CRL in PEM format */
1075  res = tls_create_hash_symlink(crl_pn_pem,
1076  cc);
1077  }
1078  /* Check for success */
1079  if(!res)
1080  {
1081  crl_valid = 1;
1082  crls_required = 1;
1083  }
1084  }
1085  /* Release memory allocated for pathnames */
1086  api_posix_free((void*) crl_pn_pem);
1087  api_posix_free((void*) crl_pn_der);
1088  break;
1089  }
1090  }
1091  }
1092  if(crl_valid) { break; }
1093  }
1094  }
1095  }
1096  /* Check for error */
1097  if(res) { break; }
1098  }
1099  }
1100  printf("%s: %s-----------------------------------------------------\n",
1101  CFG_NAME, MAIN_ERR_PREFIX);
1102  /* Release lock of mutex file */
1103  tls_crl_release_lock(&lockfd);
1104  /* Return positive value if no CRLs are required */
1105  if(!res && !crls_required) { res = 1; }
1106  }
1107 
1108  /* Release memory */
1109  if(NULL != dp) { CRL_DIST_POINTS_free(dp); }
1110 
1111  return(res);
1112 }
1113 
1114 
1115 # endif /* !CFG_TLS_CRLS_DISABLE */
1116 
1117 
1118 /* ========================================================================== */
1119 /* Check certificate chain for signing key length and signature hash algorithm
1120  *
1121  * \param[in] certificate_chain Pointer to certificate chain
1122  * \param[in] proto Flag indicating TLS protocol minor number
1123  *
1124  * \attention
1125  * Checks for non-RSA keys are not implemented.
1126  * This should never happen for TLSv1.2 because of the signature algorithm
1127  * negotiation (we offer only RSA-based signature algorithms for TLSv1.2).
1128  *
1129  * If the modulus size of a RSA key is less than 1024 bits, the key is rejected.
1130  * If the modulus size of a RSA key is less than 3072 bits, a warning message
1131  * is generated.
1132  *
1133  * The signature hash algorithms MD2, MD4 and MD5 are rejected except for the
1134  * self signature of the root certificate (signature is not used in this case).
1135  * If the signature hash algorithm is SHA-1 or SHA-224, a warning message is
1136  * generated. This should never happen for TLSv1.2 because of the signature
1137  * algorithm negotiation.
1138  *
1139  * \return
1140  * - 0 on success (skipped ECC keys are not counted as errors)
1141  * - -1 on error
1142  */
1143 
1144 static int tls_chain_check_sigalgs(STACK_OF(X509)* certificate_chain,
1145  int proto)
1146 {
1147  int res = -1;
1148  int ccl; /* Length of certificate chain */
1149  int cci; /* Index in certificate chain */
1150  X509* cc; /* Current certificate */
1151  int rv;
1152  api_posix_ssize_t rv2;
1153  int is_root = 0;
1154  const char* s;
1155  EVP_PKEY* pkey = NULL;
1156 # if !CFG_USE_OPENSSL_API_3
1157  RSA* rsa_key = NULL;
1158 # endif /* !CFG_USE_OPENSSL_API_3 */
1159  int rsa_mod_size;
1160  int alg;
1161  const char* md_s;
1162  int md_ok;
1163  unsigned char* buf;
1164  int len;
1165  char prefix[80];
1166 
1167  /* Get length of certificate chain */
1168  ccl = sk_X509_num(certificate_chain);
1169  for(cci = 0; cci < ccl; ++cci)
1170  {
1171  /* Get next certificate */
1172  cc = sk_X509_value(certificate_chain, cci);
1173  if(NULL == cc)
1174  {
1175  PRINT_ERROR("Error while parsing certificate chain");
1176  break;
1177  }
1178  /* Check for root certificate */
1179  rv = tls_cert_check_root(cc, &is_root, 0, NULL, NULL);
1180  if(rv) { break; }
1181  s = "";
1182  if(!cci) { s = "(Server) "; }
1183  if(is_root) { s = "(Root) "; }
1184  printf("%s: %sCertificate level %d %sin chain:\n",
1185  CFG_NAME, MAIN_ERR_PREFIX, cci, s);
1186  /* Extract public key */
1187  pkey = X509_extract_key(cc);
1188  if(NULL == pkey)
1189  {
1190  PRINT_ERROR("Extraction of public key from X.509 certificate"
1191  " failed");
1192  break;
1193  }
1194 # if CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
1195  if(EVP_PKEY_RSA != EVP_PKEY_base_id(pkey))
1196 # else /* CFG_USE_OPENSSL_API_1_1 */
1197  if(EVP_PKEY_RSA != pkey->type)
1198 # endif /* CFG_USE_OPENSSL_API_1_1 */
1199  {
1200  /* ECC keys are mandatory for TLSv1.3 (return no error in this case) */
1201  if(3 <= proto)
1202  {
1203  PRINT_ERROR("Certificate doesn't use RSA key (skipped)");
1204  continue;
1205  }
1206  PRINT_ERROR("Certificate doesn't use RSA key (not supported)");
1207  break;
1208  }
1209 # if !CFG_USE_OPENSSL_API_3
1210  rsa_key = EVP_PKEY_get1_RSA(pkey);
1211  if(NULL == rsa_key)
1212  {
1213  PRINT_ERROR("Extraction of key from certificate failed");
1214  break;
1215  }
1216 # endif /* !CFG_USE_OPENSSL_API_3 */
1217 # if CFG_USE_OPENSSL_API_3
1218  rsa_mod_size = EVP_PKEY_bits(pkey);
1219  if(0 >= rsa_mod_size)
1220  {
1221  PRINT_ERROR("Calculation of key size failed");
1222  break;
1223  }
1224 # else /* CFG_USE_OPENSSL_API_3 */
1225  rsa_mod_size = RSA_size(rsa_key);
1226  if(0 >= rsa_mod_size || 8192 < rsa_mod_size)
1227  {
1228  PRINT_ERROR("Calculation of key size failed");
1229  break;
1230  }
1231  rsa_mod_size *= 8;
1232 # endif /* CFG_USE_OPENSSL_API_3 */
1233  printf("%s: %s RSA key modulus size: %d bit\n",
1234  CFG_NAME, MAIN_ERR_PREFIX, rsa_mod_size);
1235  if(1024 > rsa_mod_size)
1236  {
1237  PRINT_ERROR("RSA key modulus size of certificate rejected");
1238  break;
1239  }
1240  else if(3072 > rsa_mod_size)
1241  {
1242  /* 3072 bit would match a 128 bit symmetric cipher */
1243  printf("%s: %s Warning: RSA key modulus should be "
1244  "at least 3072 bit\n", CFG_NAME, MAIN_ERR_PREFIX);
1245  }
1246  if(!cci)
1247  {
1248  /* Print randomart image for key */
1249  buf = NULL;
1250 # if CFG_USE_OPENSSL_API_3
1251  len = i2d_PUBKEY(pkey, &buf);
1252 # else /* CFG_USE_OPENSSL_API_3 */
1253  len = i2d_RSA_PUBKEY(rsa_key, &buf);
1254 # endif /* CFG_USE_OPENSSL_API_3 */
1255  if(0 > len)
1256  {
1257  PRINT_ERROR("Extraction of key fingerprint failed");
1258  break;
1259  }
1260  else
1261  {
1262  /* 'SubjectPublicKeyInfo' structure now stored in buf */
1263  rv2 = api_posix_snprintf(prefix, 80, "%s: %s ",
1264  CFG_NAME, MAIN_ERR_PREFIX);
1265  if(0 > rv2)
1266  {
1267  PRINT_ERROR("Creating message prefix failed");
1268  break;
1269  }
1270  rv = digest_randomart(prefix, (const char*) buf, (size_t) len);
1271  OPENSSL_free(buf);
1272  if(rv)
1273  {
1274  PRINT_ERROR("Creating randomart for key failed");
1275  break;
1276  }
1277  }
1278  }
1279 # if !CFG_USE_OPENSSL_API_3
1280  RSA_free(rsa_key);
1281 # endif /* !CFG_USE_OPENSSL_API_3 */
1282  EVP_PKEY_free(pkey);
1283  /* Extract hash algorithm for signatures */
1284 # if CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
1285  alg = X509_get_signature_nid(cc);
1286 # else /* CFG_USE_OPENSSL_API_1_1 */
1287  alg = OBJ_obj2nid(cc->sig_alg->algorithm);
1288 # endif /* CFG_USE_OPENSSL_API_1_1 */
1289  if(NID_undef == alg)
1290  {
1291  PRINT_ERROR("Extraction of hash algorithm failed");
1292  break;
1293  }
1294  md_s = OBJ_nid2sn(alg);
1295  if(is_root)
1296  {
1297  printf("%s: %s Self signature is not used\n",
1298  CFG_NAME, MAIN_ERR_PREFIX);
1299  }
1300  else
1301  {
1302  printf("%s: %s Signature algorithm: %s\n",
1303  CFG_NAME, MAIN_ERR_PREFIX, md_s);
1304  md_ok = 0;
1305  switch(alg)
1306  {
1307  case NID_md2WithRSAEncryption:
1308  case NID_md4WithRSAEncryption:
1309  case NID_md5WithRSAEncryption:
1310  {
1311  /* Reject weak algorithms */
1312  PRINT_ERROR("Hash algorithm of signature rejected");
1313  break;
1314  }
1315  case NID_sha1WithRSAEncryption:
1316  case NID_sha224WithRSAEncryption:
1317  {
1318  /* SHA-256 would match a 128 bit symmetric cipher */
1319  printf("%s: %s Warning: At least SHA-256 should be "
1320  "used for signatures\n", CFG_NAME, MAIN_ERR_PREFIX);
1321 # if CFG_USE_OPENSSL_API_1_1
1322  if(2 <= proto)
1323  {
1324  /*
1325  * RFC 5246 requires that the certificate chain must use one
1326  * of the signature algorithms offered in negotiation.
1327  * But we have not offered this algorithm!
1328  */
1329  PRINT_ERROR(" Server has violated RFC 5246");
1330  }
1331 # endif /* CFG_USE_OPENSSL_API_1_1 */
1332  md_ok = 1;
1333  break;
1334  }
1335  case NID_sha256WithRSAEncryption:
1336  case NID_sha384WithRSAEncryption:
1337  case NID_sha512WithRSAEncryption:
1338  {
1339  /* This is what we have offered for negotiation with TLSv1.2 */
1340  md_ok = 1;
1341  break;
1342  }
1343  default:
1344  {
1345  PRINT_ERROR(" Unexpected hash algorithm rejected");
1346  if(2 <= proto)
1347  {
1348  PRINT_ERROR(" Server has violated RFC 5246");
1349  }
1350  break;
1351  }
1352  }
1353  if(!md_ok) { break; }
1354  }
1355  }
1356  if(cci == ccl) { res = 0; }
1357 
1358  return(res);
1359 }
1360 
1361 
1362 /* ========================================================================== */
1363 /* Verify that subject of certificate matches hostname
1364  *
1365  * \param[in] cn Common name from certificate
1366  * \param[in] subject Subject to match
1367  *
1368  * The comparison is done locale independent and case insensitive.
1369  *
1370  * \note
1371  * A wildcard for the first part of the subject is accepted if
1372  * \ref CFG_USE_TLS_WILDCARD_SUBJECT is defined to a nonzero value.
1373  */
1374 
1375 static int tls_subject_check(const char* cn, const char* subject)
1376 {
1377  int res = 0;
1378 # if CFG_USE_TLS_WILDCARD_SUBJECT
1379  int wildcard = 0;
1380  const char* p;
1381 
1382  /* Check for wildcard as first part of subject */
1383  if('*' == subject[0])
1384  {
1385  /* Yes => Compare only parts after first dot */
1386  wildcard = 1;
1387  res = -1;
1388  if('.' == subject[1])
1389  {
1390  subject = &subject[2];
1391  p = strchr(cn, (int) '.');
1392  if(NULL != p)
1393  {
1394  cn = ++p;
1395  res = 0;
1396  }
1397  }
1398  }
1399 # endif /* CFG_USE_TLS_WILDCARD_SUBJECT */
1400  if(!res)
1401  {
1402  /* Compare using POSIX locale */
1403  res = api_posix_strcasecmp_l(cn, subject, tls_loc_ctype_posix);
1404  }
1405  if(0 < res) { res = -res; }
1406 
1407  /* Print message for result */
1408  if(res) { printf(" (doesn't match hostname)\n"); }
1409 # if CFG_USE_TLS_WILDCARD_SUBJECT
1410  else if(wildcard) { printf(" (matches hostname using wildcard)\n"); }
1411 # endif /* CFG_USE_TLS_WILDCARD_SUBJECT */
1412  else { printf(" (matches hostname)\n"); }
1413 
1414  return(res);
1415 }
1416 
1417 
1418 /* ========================================================================== */
1419 /* Create context for TLS connection
1420  *
1421  * \param[in] weak Offer weak TLS versions to server
1422  *
1423  * We negotiate for TLSv1.2 or higher connections according to RFC 8996.
1424  * If the server doesn't support at least TLSv1.2, \e weak must be set to a
1425  * nonzero value (to add TLSv1.1 and TLSv1.0 for negotiation).
1426  *
1427  * To provide forward secrecy, only cipher suites with ephemeral
1428  * Diffie-Hellmann-Merkle key exchange are offered by default.
1429  * Session tickets and compression are disabled.
1430  *
1431  * \attention
1432  * With the initial configuration the server certificate is not automatically
1433  * checked. The caller must explicitly check the certificate for authentication
1434  * using the \ref tls_cert_verify() function.
1435  */
1436 
1437 static int tls_create_context(int weak)
1438 {
1439  int res = 0;
1440  long int mode = SSL_MODE_ENABLE_PARTIAL_WRITE
1441  | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
1442  long int options = SSL_OP_NO_TICKET | SSL_OP_NO_COMPRESSION
1443  | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
1444  unsigned long int parameters = X509_V_FLAG_X509_STRICT;
1445  X509_VERIFY_PARAM* para = NULL;
1446  long f;
1447  int rv;
1448  const char* cpp = NULL;
1449 # if !CFG_TLS_CRLS_DISABLE
1450  X509_LOOKUP* look = NULL;
1451 
1452  /* Configure context for CRL checks */
1453  if(config[CONF_CRL_CHECK].val.i)
1454  {
1455  parameters |= X509_V_FLAG_CRL_CHECK
1456  | X509_V_FLAG_CRL_CHECK_ALL
1457  | X509_V_FLAG_EXTENDED_CRL_SUPPORT
1458  | X509_V_FLAG_USE_DELTAS;
1459  }
1460 # endif /* !CFG_TLS_CRLS_DISABLE */
1461 
1462  /* Disable TLSv1.0 and TLSv1.1 according to RFC 8996 */
1463  if(!weak)
1464  {
1465  /* Negotiate TLSv1.1 and TLSv1.0 for weak mode only */
1466  options |= SSL_OP_NO_TLSv1;
1467 # ifdef SSL_OP_NO_TLSv1_1
1468  options |= SSL_OP_NO_TLSv1_1;
1469 # endif /* SSL_OP_NO_TLSv1_1 */
1470  }
1471 
1472  /* Create TLS context for client side */
1473  tls_ctx = SSL_CTX_new(SSLv23_client_method());
1474  if(NULL == tls_ctx)
1475  {
1476  PRINT_ERROR("Cannot allocate context");
1477  res = -1;
1478  }
1479  if(!res)
1480  {
1481 # if CFG_USE_OPENSSL_API_1_1
1482  /* Disable all internal checks */
1483  SSL_CTX_set_security_level(tls_ctx, 0);
1484 # endif /* CFG_USE_OPENSSL_API_1_1 */
1485  f = SSL_CTX_set_mode(tls_ctx, mode);
1486  if((f & mode) != mode)
1487  {
1488  PRINT_ERROR("Cannot configure context");
1489  res = -1;
1490  }
1491  }
1492  if(!res)
1493  {
1494  f = SSL_CTX_set_options(tls_ctx, options);
1495  if((f & options) != options)
1496  {
1497  PRINT_ERROR("Cannot set context options");
1498  res = -1;
1499  }
1500  }
1501 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L)
1502  if(!res)
1503  {
1504  /* This is used for TLSv1.3 negotiation only */
1505  rv = SSL_CTX_set_ciphersuites(tls_ctx, TLS_CIPHERS_TLS13);
1506  if(1 != rv)
1507  {
1508  PRINT_ERROR("No usable TLSv1.3 ciphers available, "
1509  "check your OpenSSL configuration");
1510  res = -1;
1511  }
1512  }
1513 # endif /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= xxx) */
1514  if(!res)
1515  {
1516  rv = SSL_CTX_set_cipher_list(tls_ctx, TLS_CIPHERS_DEFAULT);
1517  if(1 != rv)
1518  {
1519  PRINT_ERROR("No usable ciphers with EDH key agreement available, "
1520  "check your OpenSSL configuration");
1521  res = -1;
1522  }
1523  }
1524  if(!res)
1525  {
1526  SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_NONE, NULL); /* We do it manually */
1527  para = X509_VERIFY_PARAM_new();
1528  if(NULL == para)
1529  {
1530  PRINT_ERROR("Memory allocation for X.509 parameters failed ");
1531  res = -1;
1532  }
1533  else
1534  {
1535  rv = X509_VERIFY_PARAM_set_flags(para, parameters);
1536  if(1 != rv)
1537  {
1538  PRINT_ERROR("Cannot set X.509 parameters");
1539  res = -1;
1540  }
1541  if(!res)
1542  {
1543  rv = X509_VERIFY_PARAM_set_purpose(para, X509_PURPOSE_SSL_SERVER);
1544  if(1 != rv)
1545  {
1546  PRINT_ERROR("Cannot set X.509 verification purpose");
1547  res = -1;
1548  }
1549  }
1550  if(!res)
1551  {
1552  rv = SSL_CTX_set1_param(tls_ctx, para);
1553  if(1 != rv)
1554  {
1555  PRINT_ERROR("Cannot store X.509 parameters in TLS context");
1556  res = -1;
1557  }
1558  }
1559  X509_VERIFY_PARAM_free(para);
1560  }
1561  }
1562  if(!res)
1563  {
1564  /* OpenSSL up to 1.1.0 API has no SSL_CTX_set1_groups_list() function */
1565 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L)
1566 # if CFG_USE_OPENSSL_API_3
1567  /* DH group negotiation */
1568  rv = SSL_CTX_set1_groups_list(tls_ctx, TLS_FFDHE_GROUPS
1570 # else /* CFG_USE_OPENSSL_API_3 */
1571  /* Workaround (OpenSSL 1.1.1 doesn't support FFDHE groups) */
1572  printf("%s: %sWorkaround for OpenSSL 1.1.1: "
1573  "Ignore FFDHE group configuration\n", CFG_NAME, MAIN_ERR_PREFIX);
1574  /* This is only used for key exchange in TLSv1.3 handshakes */
1575  rv = SSL_CTX_set1_groups_list(tls_ctx, TLS_ECDHE_GROUPS_TLS13);
1576 # endif /* CFG_USE_OPENSSL_API_3 */
1577  if(1 != rv)
1578  {
1579  PRINT_ERROR("Cannot store DHE groups in TLS context");
1580  res = -1;
1581  }
1582 # else /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1583 # if CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
1584  /* LibreSSL has client TLSv1.3 support since version 3.1.1 */
1585  /* Workaround (LibreSSL 3.1.1 doesn't support FFDHE groups) */
1586  printf("%s: %sWorkaround for LibreSSL: "
1587  "Ignore FFDHE group configuration\n", CFG_NAME, MAIN_ERR_PREFIX);
1588  /* The list TLS_ECDHE_GROUPS_TLS13 is rejected too (tested with 3.2.2) */
1589  rv = SSL_CTX_set1_groups_list(tls_ctx, "X25519:P-256");
1590  if(1 != rv)
1591  {
1592  PRINT_ERROR("Cannot store DHE groups in TLS context");
1593  res = -1;
1594  }
1595 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 3.1.1) */
1596 # endif /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1597  }
1598 
1599 # if CFG_USE_OPENSSL_API_1_1
1600  if(!res)
1601  {
1602  /* Create configuration context */
1603  cctx = SSL_CONF_CTX_new();
1604  if(NULL == cctx)
1605  {
1606  PRINT_ERROR("Cannot create TLS configuration context");
1607  res = -1;
1608  }
1609  else
1610  {
1611  /* Init configuration context */
1612  SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_CLIENT
1613  | SSL_CONF_FLAG_SHOW_ERRORS);
1614  /* Assign current TLS context to configuration context */
1615  SSL_CONF_CTX_set_ssl_ctx(cctx, tls_ctx);
1616  /* Set signature algorithms for TLSv1.2 and higher */
1617 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L)
1618  /*
1619  * Append the list of signature algorithms for TLSv1.2
1620  * to allow PKCS1 v1_5 based signatures in certificates
1621  */
1622  rv = SSL_CONF_cmd(cctx, "SignatureAlgorithms", TLS_SIGALGS_TLS13
1623  ":" TLS_SIGALGS);
1624 # else /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1625  rv = SSL_CONF_cmd(cctx, "SignatureAlgorithms", TLS_SIGALGS);
1626 # endif /* CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 1.1.1) */
1627  if(2 != rv)
1628  {
1629  PRINT_ERROR("Cannot store TLS signature algorithms");
1630  res = -1;
1631  }
1632  else
1633  {
1634  /* Attention: The OpenSSL documentation is wrong! */
1635  rv = SSL_CONF_CTX_finish(cctx);
1636  if(1 != rv)
1637  {
1638  PRINT_ERROR("Cannot store configuration context");
1639  res = -1;
1640  }
1641  }
1642  }
1643  }
1644 # endif /* CFG_USE_OPENSSL_API_1_1 */
1645 
1646  /* Use local root certificate on request (must be installed manually) */
1647  if(config[CONF_TLS_OWNCERTS].val.i)
1648  {
1649  if(!res) { res = tls_get_certpath(&cpp); }
1650  if(!res)
1651  {
1652  tls_certpath = cpp;
1653  printf("%s: %sLocation of X.509 root certificates: %s/\n",
1654  CFG_NAME, MAIN_ERR_PREFIX, tls_certpath);
1655 # if CFG_USE_OPENSSL_API_3
1656  rv = SSL_CTX_load_verify_dir(tls_ctx, tls_certpath);
1657 # else /* CFG_USE_OPENSSL_API_3 */
1658  rv = SSL_CTX_load_verify_locations(tls_ctx, NULL, tls_certpath);
1659 # endif /* CFG_USE_OPENSSL_API_3 */
1660  if(1 != rv)
1661  {
1662  PRINT_ERROR("Setup of certificate verification failed");
1663  res = -1;
1664  }
1665  }
1666  }
1667  else
1668  {
1669  /* Use default certificate location of OpenSSL */
1670  if(!res)
1671  {
1672  rv = SSL_CTX_set_default_verify_paths(tls_ctx);
1673  if(1 != rv)
1674  {
1675  PRINT_ERROR("Setup of certificate verification failed");
1676  res = -1;
1677  }
1678  }
1679  }
1680 
1681 # if !CFG_TLS_CRLS_DISABLE
1682  if(!res && config[CONF_CRL_CHECK].val.i)
1683  {
1684  /* Use CRLs vor certificate revocation checks */
1685  res = tls_get_crlpath(&cpp);
1686  if(!res)
1687  {
1688  tls_crlpath = cpp;
1689  printf("%s: %sLocation of X.509 CRLs: %s/\n",
1690  CFG_NAME, MAIN_ERR_PREFIX, tls_crlpath);
1691  }
1692  if(!res)
1693  {
1694  look = X509_STORE_add_lookup(SSL_CTX_get_cert_store(tls_ctx),
1695  X509_LOOKUP_hash_dir());
1696  if(NULL == look)
1697  {
1698  PRINT_ERROR("Cannot add CRL lookup method to TLS context");
1699  res = -1;
1700  }
1701  }
1702  if(!res)
1703  {
1704  rv = X509_LOOKUP_add_dir(look, tls_crlpath, X509_FILETYPE_PEM);
1705  if(1 != rv)
1706  {
1707  PRINT_ERROR("Cannot set CRL path");
1708  res = -1;
1709  }
1710  }
1711  }
1712  else
1713  {
1714  printf("%s: %sWarning: X.509 certificate revocation checks disabled "
1715  "in configfile\n", CFG_NAME, MAIN_ERR_PREFIX);
1716  }
1717 # else /* !CFG_TLS_CRLS_DISABLE */
1718  /* Do not check revocation of certificates */
1719  if(!res)
1720  {
1721  printf("%s: %sWarning: X.509 certificate revocation checks disabled "
1722  "by configuration\n", CFG_NAME, MAIN_ERR_PREFIX);
1723  }
1724 # endif /* !CFG_TLS_CRLS_DISABLE */
1725 
1726  /* For code review: The Cert/CRL paths are destroyed with the context! */
1727  return(res);
1728 }
1729 
1730 
1731 /* ========================================================================== */
1732 /* Destroy context for TLS connection */
1733 
1734 static void tls_destroy_context(void)
1735 {
1736 # if CFG_USE_OPENSSL_API_1_1
1737  /* Note: 'cctx' is allowed to be 'NULL' here */
1738  SSL_CONF_CTX_free(cctx);
1739 # endif /* CFG_USE_OPENSSL_API_1_1 */
1740 
1741  if(NULL != tls_ctx)
1742  {
1743  SSL_CTX_free(tls_ctx);
1744  tls_ctx = NULL;
1745  }
1746 
1747  api_posix_free((void*) tls_certpath);
1748  tls_certpath = NULL;
1749 # if !CFG_TLS_CRLS_DISABLE
1750  api_posix_free((void*) tls_crlpath);
1751  tls_crlpath = NULL;
1752 # endif /* !CFG_TLS_CRLS_DISABLE */
1753 }
1754 
1755 
1756 /* ========================================================================== */
1757 /*! \brief Init TLS subsystem
1758  *
1759  * \return
1760  * - 0 on success
1761  * - Negative value on error
1762  */
1763 
1764 int tls_init(void)
1765 {
1766  int res = 0;
1767 
1768  /* Create a locale object with LC_CTYPE == POSIX */
1769  tls_loc_ctype_posix = api_posix_newlocale(API_POSIX_LC_CTYPE_MASK, "POSIX",
1770  (api_posix_locale_t) 0);
1771  if((api_posix_locale_t) 0 == tls_loc_ctype_posix)
1772  {
1773  PRINT_ERROR("Cannot create locale object");
1774  res = -1;
1775  }
1776 
1777  if(!res)
1778  {
1779  /*
1780  * Since OpenSSL 1.1.0 explicit initialization is no longer required:
1781  * https://www.openssl.org/docs/manmaster/man3/OPENSSL_init_ssl.html
1782  */
1783 # if !CFG_USE_OPENSSL_API_1_1
1784  /* Load strings for human readable error messsages */
1785  SSL_load_error_strings();
1786  /* Register available ciphers and digests */
1787  SSL_library_init();
1788 # if OPENSSL_VERSION_NUMBER == 0x1000000FL
1789  /*
1790  * Quoted from the OpenSSL documentation:
1791  * OpenSSL [...] 1.0.0a and later added SHA2 algorithms to
1792  * SSL_library_init(). Applications which need to use SHA2 in earlier
1793  * versions of OpenSSL should call OpenSSL_add_all_algorithms() as well.
1794  */
1795  OpenSSL_add_all_algorithms();
1796 # endif /* OPENSSL_VERSION_NUMBER == 1.0.0 */
1797 # endif /* !CFG_USE_OPENSSL_API_1_1 */
1798 
1799  /* Ensure that Pseudo Random Number Generator (PRNG) is seeded */
1800  if(!RAND_status())
1801  {
1802  PRINT_ERROR("Seeding PRNG failed, "
1803  "check your OpenSSL configuration");
1804  res = -1;
1805  }
1806  }
1807 
1808  return(res);
1809 }
1810 
1811 
1812 /* ========================================================================== */
1813 /*! \brief Shutdown TLS subsystem */
1814 
1815 void tls_exit(void)
1816 {
1817  if((api_posix_locale_t) 0 != tls_loc_ctype_posix)
1818  {
1819  api_posix_freelocale(tls_loc_ctype_posix);
1820  }
1821 
1822  /* Since OpenSSL 1.1.0 explicit cleanup is no longer required */
1823 # if !CFG_USE_OPENSSL_API_1_1
1824  EVP_cleanup();
1825 # endif /* !CFG_USE_OPENSSL_API_1_1 */
1826 }
1827 
1828 
1829 /* ========================================================================== */
1830 /*! \brief Check TLS subsystem for known vulnerabilities
1831  *
1832  * \param[in] check Execute vulnerability checks
1833  *
1834  * If \e check is zero, only the library name and version number is printed
1835  *
1836  * \attention
1837  * Because the TLS subsystem may use dynamically linked OpenSSL libraries, this
1838  * check can't be done at compile time!
1839  *
1840  * OpenSSL version numbers since 0.9.5 are composed as follows:
1841  *
1842  * 0xMNNFFPPS (Major miNor Fix Patch Status)
1843  * <br>
1844  * <hr>
1845  * 0x00906023 (0.9.6b beta 3)
1846  * <br>
1847  * 0x1000107F (1.0.1g release)
1848  * <br>
1849  * 0x20000000 (2.0.0 dev, reported by LibreSSL)
1850  * <br>
1851  * 0x30000000 (3.0.0 dev, reported by OpenSSL Alpha versions)
1852  * <br>
1853  * 0x300000D0 (3.0.13 release)
1854  *
1855  * \note
1856  * LibreSSL always reports the same OpenSSL version.
1857  *
1858  * \return
1859  * - 0 on success
1860  * - Negative value if TLS subsystem may use code with known vulnerabilities
1861  */
1862 
1864 {
1865  int res = 0;
1866  /* Using function instead of the constant is required for shared library */
1867 # if CFG_USE_OPENSSL_API_1_1
1868  unsigned long int version = OpenSSL_version_num();
1869 # else /* CFG_USE_OPENSSL_API_1_1 */
1870 # if CFG_USE_LIBRESSL && defined(LIBRESSL_VERSION_NUMBER)
1871  /* Documentation says LIBRESSL_VERSION_NUMBER always ends with 00F */
1872  unsigned long int version = LIBRESSL_VERSION_NUMBER;
1873 # else /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1874  unsigned long int version = SSLeay();
1875 # endif /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1876 # endif /* CFG_USE_OPENSSL_API_1_1 */
1877  unsigned int major = (unsigned int) ((version & 0xF0000000UL) >> 28);
1878  unsigned int minor = (unsigned int) ((version & 0x0FF00000UL) >> 20);
1879  unsigned int fix = (unsigned int) ((version & 0x000FF000UL) >> 12);
1880  unsigned int patch = (unsigned int) ((version & 0x00000FF0UL) >> 4);
1881 # if ! CFG_USE_LIBRESSL && ! CFG_USE_OPENSSL_API_3
1882  char patch_letter;
1883  char patch_string[4] = { 0, 0, 0, 0 };
1884 
1885  if(patch)
1886  {
1887  if(25U >= patch)
1888  {
1889  /* Single character */
1890  patch_letter = (char) (0x60U + patch);
1891  }
1892  else if(50U >= patch)
1893  {
1894  /* Second character */
1895  patch_letter = (char) (0x60U + patch - 25U);
1896  patch_string[1] = patch_letter;
1897  /* First character */
1898  patch_letter = 'z';
1899  }
1900  else if(75U >= patch)
1901  {
1902  /* Third character */
1903  patch_letter = (char) (0x60U + patch - 50U);
1904  patch_string[2] = patch_letter;
1905  /* Second character */
1906  patch_string[1] = 'z';
1907  /* First character */
1908  patch_letter = 'z';
1909  }
1910  else
1911  {
1912  /* This will hopefully never be required */
1913  patch_letter = '?';
1914  }
1915  patch_string[0] = patch_letter;
1916  }
1917 # endif /* ! CFG_USE_LIBRESSL && ! CFG_USE_OPENSSL_API_3 */
1918 
1919  /* Print version */
1920 # if CFG_USE_LIBRESSL && defined(LIBRESSL_VERSION_NUMBER)
1921  /* LibreSSL */
1922  printf("%s: %sCompiled for LibreSSL\n", CFG_NAME, MAIN_ERR_PREFIX);
1923  printf("%s: %sLibreSSL library version: %u.%u.%u (0x%08lX)\n",
1924  CFG_NAME, MAIN_ERR_PREFIX, major, minor, fix, version);
1925 # else /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1926  /* OpenSSL */
1927 # if CFG_USE_OPENSSL_API_3
1928  printf("%s: %sOpenSSL library version: %u.%u.%u (0x%08lX)\n",
1929  CFG_NAME, MAIN_ERR_PREFIX, major, minor, patch, version);
1930 # else /* CFG_USE_OPENSSL_API_3 */
1931  printf("%s: %sOpenSSL library version: %u.%u.%u%s (0x%08lX)\n",
1932  CFG_NAME, MAIN_ERR_PREFIX, major, minor, fix, patch_string, version);
1933 # endif /* CFG_USE_OPENSSL_API_3 */
1934 # endif /* CFG_USE_LIBRESSL && LIBRESSL_VERSION_NUMBER */
1935 
1936  /* Print message if TLSv1.3 is available */
1937 # if CFG_USE_OPENSSL_API_1_1 && (OPENSSL_VERSION_NUMBER >= 0x10101000L) \
1938  || CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
1939  printf("%s: %sProtocol version TLSv1.3 available for negotiation\n",
1940  CFG_NAME, MAIN_ERR_PREFIX);
1941 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
1942  /* || CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
1943 
1944  if(check)
1945  {
1946  /*
1947  * Check for potential certificate check "#OprahSSL" bug (CVE-2015-1793)
1948  * in OpenSSL (Vulnerable versions: 1.0.1n, 1.0.1o, 1.0.2b and 1.0.2c)
1949  */
1950  if(1U == major && 0U == minor)
1951  {
1952  if( (1U == fix && 0xEU <= patch && 0xFU >= patch)
1953  || (2U == fix && 0x2U <= patch && 0x3U >= patch) )
1954  {
1955  printf("%s: %sOpenSSL library possibly vulnerable to #OprahSSL!\n",
1956  CFG_NAME, MAIN_ERR_PREFIX);
1957  res = -1;
1958  }
1959  }
1960 
1961  /*
1962  * Check for potential heartbeat "Heartbleed" bug (CVE-2014-0160) in
1963  * OpenSSL (Vulnerable versions: 1.0.1 to 1.0.1f)
1964  */
1965  if(1U == major && 0U == minor && 1U == fix && 7U > patch)
1966  {
1967  printf("%s: %sOpenSSL library possibly vulnerable to Heartbleed!\n",
1968  CFG_NAME, MAIN_ERR_PREFIX);
1969  res = -1;
1970  }
1971 
1972  /*
1973  * Check for potential MITM vulnerability (CVE-2014-0224) in OpenSSL
1974  * (Vulnerable versions: 1.0.0 to 1.0.0l and 1.0.1 to 1.0.1g)
1975  */
1976  if(1U == major && 0U == minor)
1977  {
1978  if( (0U == fix && 0x0DU > patch) || (1U == fix && 8U > patch) )
1979  {
1980  printf("%s: %s"
1981  "OpenSSL library possibly vulnerable to MITM attacks!\n",
1982  CFG_NAME, MAIN_ERR_PREFIX);
1983  res = -1;
1984  }
1985  }
1986  }
1987 
1988  return(res);
1989 }
1990 
1991 
1992 /* ========================================================================== */
1993 /*! \brief Check whether server name used for connection is not an IP address
1994  *
1995  * \param[in] sn Pointer to server name string
1996  *
1997  * An IP address cannot be used for the SNI extension.
1998  * This function should be called to determine whether a TCP connection was
1999  * established based on DNS name or IP address.
2000  *
2001  * The result can be used as parameter \c sni for the function \ref tls_open() .
2002  *
2003  * \return
2004  * - \e sn on success
2005  * - \c NULL if \e sn is a valid ASCII representation of an IP address
2006  */
2007 
2008 const char* tls_sni(const char* sn)
2009 {
2010  const char* res = NULL;
2011  unsigned char buf[16];
2012 
2013  if(1 != api_posix_inet_pton(API_POSIX_AF_INET, sn, buf))
2014  {
2015 #if CFG_USE_IP6
2016  if(1 != api_posix_inet_pton(API_POSIX_AF_INET6, sn, buf))
2017  {
2018  res = sn;
2019  }
2020 #else /* CFG_USE_IP6 */
2021  res = sn;
2022 #endif /* CFG_USE_IP6 */
2023  }
2024 
2025  return(res);
2026 }
2027 
2028 
2029 /* ========================================================================== */
2030 /*! \brief Establish TLS encryption layer on top of open network connection
2031  *
2032  * \param[in] sd Socket descriptor
2033  * \param[out] co Pointer to connection object pointer
2034  * \param[in] weak Offer weak cipher suite(s) to server
2035  * \param[in] sni Hostname for SNI extension (or \c NULL )
2036  *
2037  * The socket descriptor \e sd must be assigned to an open connection.
2038  *
2039  * If \e sni is \c NULL, the SNI extension is not used (but this is forbidden
2040  * by RFC 8143).
2041  * If the caller wants to use the SNI extension, \e sni must point to the
2042  * hostname string used for DNS resolution when the connection associated
2043  * with \e sd was established.
2044  *
2045  * On success, a pointer to the connection object is stored at the location
2046  * pointed by \e co .
2047  *
2048  * \attention
2049  * RFC 5246 specifies the cipher suite RSA-RSA-AES128-SHA (0x00, 0x2F) as
2050  * mandatory.
2051  * RFC 4642 specified the cipher suite RSA-RSA-RC4-MD5 (0x00, 0x04) as mandatory
2052  * in the past (it is preserved for backward compatibility).
2053  * Both will provide no forward secrecy and the latter one in addition use the
2054  * weak RC4 symmetric encryption algorithm.
2055  * Therefore they are not included in the default list of ciphers we offer to
2056  * the server.
2057  *
2058  * To comply with RFC 5246 and nevertheless offer the disabled cipher suites, or
2059  * if the server doesn't support FFDHE key exchange, \e weak must be set to a
2060  * nonzero value.
2061  *
2062  * If OpenSSL API 1.1 is available, the FFDHE group from the server are verified
2063  * to be at least 1024 bits in size for FFDHE key exchange (if \e weak is set to
2064  * zero).
2065  *
2066  * If OpenSSL API 1.1 is available and at least TLSv1.2 is used, the signature
2067  * algorithm to use for TLS protocol is negotiated with the server.
2068  * The algorithms we offer are defined with \ref TLS_SIGALGS for TLSv1.2.
2069  * The algorithms we offer are defined with \ref TLS_SIGALGS_TLS13 for TLSv1.3.
2070  *
2071  * \note
2072  * TLSv1.3 allows to offer a separate list of signature algorithms for
2073  * certificates. We do not use this feature and the certificates must use
2074  * signature algorithms listed in \ref TLS_SIGALGS_TLS13 .
2075  *
2076  * \return
2077  * - 0 on success
2078  * - Negative value on error
2079  */
2080 
2081 int tls_open(int sd, void** co, int weak, const char* sni)
2082 {
2083  int res = -1;
2084  int rv;
2085  long int rv2;
2086  SSL** ssl;
2087  unsigned long int error;
2088  const char* sp = NULL;
2089  const char* tlsv = NULL;
2090  const char* cp = NULL;
2091  const char* kx = NULL;
2092  char b[200];
2093 # if CFG_USE_OPENSSL_API_1_1
2094  EVP_PKEY* key = NULL;
2095  int length;
2096 # endif /* CFG_USE_OPENSSL_API_1_1 */
2097 # if CFG_USE_OPENSSL_API_1_1
2098  const char* dp = NULL;
2099 # if (OPENSSL_VERSION_NUMBER >= 0x10101000L)
2100  int id;
2101 # endif /* (OPENSSL_VERSION_NUMBER >= 1.1.1) */
2102  int id2;
2103 # endif /* CFG_USE_OPENSSL_API_1_1 */
2104 
2105  if(NULL != co)
2106  {
2107  ssl = (SSL**) co;
2108 
2109  /* Create context */
2110  res = tls_create_context(weak);
2111 
2112  /* Create connection object */
2113  if(!res)
2114  {
2115  *ssl = SSL_new(tls_ctx);
2116  if(NULL == *ssl)
2117  {
2118  PRINT_ERROR("Cannot create connection object");
2119  res = -1;
2120  }
2121  }
2122 
2123  /* Configure RFC 6066 SNI extension */
2124  if(!res && NULL != sni)
2125  {
2126  printf("%s: %sUsing SNI extension with: %s\n",
2127  CFG_NAME, MAIN_ERR_PREFIX, sni);
2128  rv2 = SSL_set_tlsext_host_name(*ssl, sni);
2129  if(1 != rv2)
2130  {
2131  PRINT_ERROR("Adding SNI extension from RFC 6066 failed");
2132  res = -1;
2133  }
2134  }
2135 
2136  /* Add weak cipher suites on request */
2137  if(!res && weak)
2138  {
2139  rv = SSL_set_cipher_list(*ssl, TLS_CIPHERS_WEAK);
2140  if(1 != rv)
2141  {
2142  PRINT_ERROR("Adding weak cipher suites failed");
2143  res = -1;
2144  }
2145  else
2146  {
2147  printf("%s: %sWarning: Offering weak protocol versions "
2148  "and cipher suites to server\n",
2149  CFG_NAME, MAIN_ERR_PREFIX);
2150  }
2151  }
2152 
2153  /* Attach connection object to socket */
2154  if(!res)
2155  {
2156  rv = SSL_set_fd(*ssl, sd);
2157  if(1 != rv)
2158  {
2159  PRINT_ERROR("Cannot assign connection object to socket");
2160  res = -1;
2161  }
2162  }
2163 
2164  /* Initiate TLS handshake */
2165  if(!res)
2166  {
2167  rv = SSL_connect(*ssl);
2168  if(1 != rv)
2169  {
2170  PRINT_ERROR("Failed to establish TLS connection");
2171  /* Assignment in truth expression is intended */
2172  while((error = ERR_get_error()))
2173  {
2174  sp = ERR_reason_error_string(error);
2175  api_posix_snprintf(b, 200, "%sError: %s", MAIN_ERR_PREFIX, sp);
2176  print_error(b);
2177  }
2178  res = -1;
2179  }
2180  else
2181  {
2182  /* Print cipher suite */
2183  res = tls_get_ciphersuite((void**) ssl, &tlsv, &cp, &kx);
2184  if(res) { PRINT_ERROR("Reading negotiation result failed"); }
2185  else
2186  {
2187  printf("%s: %sUsing protocol: %s with cipher suite %s\n",
2188  CFG_NAME, MAIN_ERR_PREFIX, tlsv, cp);
2189 # if CFG_USE_OPENSSL_API_1_1
2190  if(SSL_get_peer_signature_nid(*ssl, &id2))
2191  {
2192  dp = "rsaEncryption";
2193 # if (OPENSSL_VERSION_NUMBER >= 0x10101000L)
2194  if(SSL_get_peer_signature_type_nid(*ssl, &id))
2195  {
2196  dp = OBJ_nid2sn(id);
2197  }
2198 # endif /* (OPENSSL_VERSION_NUMBER >= 1.1.1) */
2199  if(!strcmp("rsaEncryption", dp)) { dp = "RSASSA-PKCS1-v1_5"; }
2200  printf("%s: %sPeer signature algorithm: %s+%s\n",
2201  CFG_NAME, MAIN_ERR_PREFIX, dp, OBJ_nid2sn(id2));
2202  }
2203  else
2204  {
2205  /* '!weak' indicates DHE key exchange here */
2206  /* Up to TLSv1.1 the signature algorithm is not selectable */
2207  if(!weak && strcmp("TLSv1", tlsv) && strcmp("TLSv1.1", tlsv))
2208  {
2209  PRINT_ERROR("Signature algorithm negotiation failed");
2210  res = -1;
2211  }
2212  }
2213 # else /* CFG_USE_OPENSSL_API_1_1 */
2214  if(!weak && strcmp("TLSv1", tlsv) && strcmp("TLSv1.1", tlsv))
2215  {
2216  printf("%s: %sWarning: Signature algorithm "
2217  "negotiation not possible with OpenSSL API 1.0\n",
2218  CFG_NAME, MAIN_ERR_PREFIX);
2219  }
2220 # endif /* CFG_USE_OPENSSL_API_1_1 */
2221  if(strcmp("TLSv1", tlsv) && strcmp("TLSv1.1", tlsv)
2222  && strcmp("TLSv1.2", tlsv))
2223  {
2224  if(!strcmp("FFDHE", kx))
2225  {
2226  printf("%s: %sKey exchange algorithm: %s\n",
2227  CFG_NAME, MAIN_ERR_PREFIX, kx);
2228  }
2229  else
2230  {
2231  printf("%s: %sKey exchange algorithm: ECDHE (%s)\n",
2232  CFG_NAME, MAIN_ERR_PREFIX, kx);
2233  }
2234  }
2235  }
2236 # if CFG_USE_OPENSSL_API_1_1
2237  if(!res && !weak)
2238  {
2239  /* Check FFDHE group (no negotiation possible before TLSv1.3) */
2240  rv = SSL_get_server_tmp_key(*ssl, &key);
2241  if(!rv) { res = -1; }
2242  if(!res)
2243  {
2244  if(EVP_PKEY_DH == EVP_PKEY_id(key))
2245  {
2246  length = EVP_PKEY_bits(key);
2247  if(0 >= length) { res = -1; }
2248  else
2249  {
2250  printf("%s: %sFFDHE group size: %d bit\n",
2251  CFG_NAME, MAIN_ERR_PREFIX, length);
2252  if(1024 > length)
2253  {
2254  PRINT_ERROR("FFDHE group size rejected");
2255  res = -1;
2256  }
2257  else if(3072 > length)
2258  {
2259  /* 3072 bit would match a 128 bit symmetric cipher */
2260  printf("%s: %sWarning: FFDHE group size should be"
2261  " at least 3072 bit\n",
2262  CFG_NAME, MAIN_ERR_PREFIX);
2263  }
2264  }
2265  }
2266  EVP_PKEY_free(key);
2267  key = NULL;
2268  }
2269  /* Close connection on error */
2270  if(res)
2271  {
2272  PRINT_ERROR("FFDHE group size check failed");
2273  tls_close((void*) ssl);
2274  }
2275  }
2276 # else /* CFG_USE_OPENSSL_API_1_1 */
2277  if(!res)
2278  {
2279 # if CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
2280  /* LibreSSL supports TLSv1.3 since version 3.1.1, but no FFDHE */
2281  if(strcmp("TLSv1.3", tlsv))
2282  {
2283 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
2284  printf("%s: %sWarning: FFDHE group size check not possible "
2285  "with OpenSSL API 1.0\n", CFG_NAME, MAIN_ERR_PREFIX);
2286 # if CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L)
2287  }
2288 # endif /* CFG_USE_LIBRESSL && (LIBRESSL_VERSION_NUMBER >= 0x30101000L) */
2289  }
2290 # endif /* CFG_USE_OPENSSL_API_1_1 */
2291  }
2292  }
2293  }
2294 
2295  return(res);
2296 }
2297 
2298 
2299 /* ========================================================================== */
2300 /*! \brief Terminate TLS encryption layer on top of network connection
2301  *
2302  * \param[in,out] co Pointer to connection object pointer
2303  *
2304  * \note
2305  * This function also destroys the TLS context that contains the certificate
2306  * CRLs. After CRLs are updated, it is not required to shutdown the whole module
2307  * via \ref tls_exit() . Calling this function is sufficient to invalidate any
2308  * CRLs in memory.
2309  *
2310  * \return
2311  * - 1 on success
2312  * - Negative value on error
2313  */
2314 
2315 int tls_close(void** co)
2316 {
2317  int res = -1;
2318 
2319  if(NULL != co && NULL != *((SSL**) co))
2320  {
2321  /* Close connection */
2322  res = SSL_shutdown(*((SSL**) co));
2323  if(!res) { res = SSL_shutdown(*((SSL**) co)); }
2324  if(0 <= res && 1 != res)
2325  {
2326  PRINT_ERROR("Error while closing TLS connection");
2327  res = -1;
2328  }
2329 
2330  /* Destroy connection object */
2331  SSL_free(*((SSL**) co));
2332  *((SSL**) co) = NULL;
2333 
2334  /* Destroy context (including buffered CRLs) */
2335  tls_destroy_context();
2336  }
2337 
2338  return(res);
2339 }
2340 
2341 
2342 /* ========================================================================== */
2343 /*! \brief Get protocol and cipher suite name that was negotiated for connection
2344  *
2345  * \param[in] co Pointer to connection object pointer
2346  * \param[out] pv Pointer to protocol version string
2347  * \param[out] cs Pointer to cipher suite string
2348  * \param[out] kx Pointer to key exchange algorithm
2349  *
2350  * \attention
2351  * The value returned for \e kx is only valid when the protocol version returned
2352  * for \e pv is \c TLSv1.3 (for older protocol versions the key exchange
2353  * algorithm is negotiated as part of the cipher suite).
2354  *
2355  * \note
2356  * If the caller is not interested in the information, the parameters \e pv and
2357  * \e cs it is allowed to pass \c NULL .
2358  *
2359  * \return
2360  * - 0 on success
2361  * - -1 on error
2362  */
2363 
2364 int tls_get_ciphersuite(void** co, const char** pv, const char** cs,
2365  const char** kx)
2366 {
2367  int res = -1;
2368  SSL** ssl;
2369  const SSL_CIPHER* cp;
2370 # if CFG_USE_OPENSSL_API_1_1
2371  EVP_PKEY* tmp_key;
2372 # endif /* CFG_USE_OPENSSL_API_1_1 */
2373 
2374  ssl = (SSL**) co;
2375  cp = SSL_get_current_cipher(*ssl);
2376  if(NULL == cp)
2377  {
2378  PRINT_ERROR("Reading negotiated protocol and cipher suite failed");
2379  }
2380  else
2381  {
2382  /*
2383  * Note:
2384  * Calling 'SSL_CIPHER_get_version()' is wrong, because this function
2385  * reports the TLS version in which the used cipher suite was defined.
2386  * But this function should return information about the protocol used for
2387  * the current connection corresponding to parameter 'co'.
2388  */
2389  if(NULL != pv) { *pv = SSL_get_version(*ssl); }
2390  if(NULL != cs) { *cs = SSL_CIPHER_get_name(cp); }
2391  if(NULL != kx)
2392  {
2393 # if CFG_USE_OPENSSL_API_1_1
2394  if(SSL_get_server_tmp_key(*ssl, &tmp_key))
2395  {
2396  switch(EVP_PKEY_id(tmp_key))
2397  {
2398  case EVP_PKEY_DH:
2399  {
2400  *kx = "FFDHE";
2401  break;
2402  }
2403  default:
2404  {
2405  *kx = OBJ_nid2sn(EVP_PKEY_id(tmp_key));
2406  break;
2407  }
2408  }
2409  EVP_PKEY_free(tmp_key);
2410  res = 0;
2411  }
2412 # else /* CFG_USE_OPENSSL_API_1_1 */
2413  *kx = "Unknown";
2414  res = 0;
2415 # endif /* CFG_USE_OPENSSL_API_1_1 */
2416  }
2417  else { res = 0; }
2418  res = 0;
2419  }
2420 
2421  return(res);
2422 }
2423 
2424 
2425 /* ========================================================================== */
2426 /*! \brief Check whether server has presented a certificate and verify it
2427  *
2428  * \param[in] co Pointer to connection object pointer
2429  * \param[out] cert Pointer to cerificate pointer
2430  * \param[in] cn Common name string the certificate should contain
2431  * \param[in] weak Disable some checks for better compatibility
2432  *
2433  * \attention
2434  * The parameter \e weak must be set to the same value that was used for the
2435  * call to \ref tls_open() .
2436  *
2437  * The verification executes the following steps:
2438  * - Ensure that the server has presented a certificate (chain)
2439  * - Optional: Check the signature algorithms and key lengths used in the
2440  * certificate chain (Setting \e weak to a nonzero value disables this step)
2441  * - Follow certificate chain back to the anchor and verify that it is trusted
2442  * - Optional: Verify that none of the certificates in the chain was revoked
2443  * (The CRLs for the revocation checks are downloaded automatically)
2444  * - Verify that the subject of the certificate contain \e cn
2445  *
2446  * According to RFC 8143 the following rules are applied:
2447  * - The matching of hostname \e cn must be case-insensitive => We do so.
2448  * - Wildcard \c * is allowed as left-most name component => We accept this.
2449  * - Hostnames listed via \c subjectAltName extension should be checked first
2450  * => We do so.
2451  * - If the certificate contains multiple names (e.g., more than one \c dNSName
2452  * field), then a match with any one of the fields is considered acceptable
2453  * => We accept any match.
2454  *
2455  * If the return value is not negative, the server has presented a certificate
2456  * and a pointer to it was written to \e cert .
2457  *
2458  * \note
2459  * The returned value for \e cert stay in memory until the connection object
2460  * \e co is destroyed.
2461  *
2462  * The return value \c -2 should be interpreted as a request to close the
2463  * connection and re-establish it again (and then using the new CRLs).
2464  *
2465  * \return
2466  * - 0 on success (Certificate was presented, is valid and trusted)
2467  * - 1 if the certificate is not trusted
2468  * - -1 on error
2469  * - -2 if the verification was not executed because CRLs have been updated
2470  */
2471 
2472 int tls_cert_verify(void** co, void** cert, const char* cn, int weak)
2473 {
2474  int res = 0;
2475  SSL** ssl = (SSL**) co;
2476  STACK_OF(X509)* certificate_chain = NULL;
2477  X509* certificate = NULL;
2478  X509_NAME* subject;
2479  X509_NAME_ENTRY* common_name;
2480  ASN1_STRING* common_name_string;
2481  BIO* biop = BIO_new(BIO_s_mem());
2482  long int rv;
2483  const char* sp = NULL;
2484  char b[256];
2485  const char* p = NULL;
2486  int i = -1;
2487  GENERAL_NAMES* an = NULL;
2488  GENERAL_NAME* ani;
2489  int num;
2490  int match = 0;
2491  const char* pv;
2492  int proto = 0;
2493 
2494  /* Extract whole certificate chain from connection object */
2495  certificate_chain = SSL_get_peer_cert_chain(*ssl);
2496  if(NULL == certificate_chain)
2497  {
2498  PRINT_ERROR("Extracting certificate chain failed");
2499  res = -1;
2500  }
2501  if(!res && weak)
2502  {
2503  printf("%s: %sWarning: Using weak certificate chain checks\n",
2504  CFG_NAME, MAIN_ERR_PREFIX);
2505  }
2506 
2507  /* Update CRLs for certificate chain */
2508 # if !CFG_TLS_CRLS_DISABLE
2509  if(!res && config[CONF_CRL_CHECK].val.i)
2510  {
2511  if(!tls_crl_update_skip && tls_check_crl_age())
2512  {
2513  res = tls_update_crls(certificate_chain);
2514  if(0 > res) { PRINT_ERROR("Updating of CRLs failed"); }
2515  else
2516  {
2517  /* CRLs successfully updated */
2518  tls_set_crl_age();
2519  if(0 < res)
2520  {
2521  /* Self signed root certificate */
2522  PRINT_ERROR("No CRLs required");
2523  res = 0;
2524  }
2525  else
2526  {
2527  /* Request to close and reopen connection */
2528  PRINT_ERROR("Verification of certificate aborted because "
2529  "of CRL update");
2530  SSL_get_verify_result(*ssl);
2531  res = -2;
2532  }
2533  }
2534  }
2535  }
2536 # endif /* !CFG_TLS_CRLS_DISABLE */
2537 
2538  /* Check algorithms and key length of signatures in certificate chain */
2539  if(!res && !weak)
2540  {
2541  res = tls_get_ciphersuite((void**) ssl, &pv, NULL, NULL);
2542  if(res) { PRINT_ERROR("Reading protocol version failed"); }
2543  else
2544  {
2545  /* Check for TLS protocol minor number */
2546  if(!strcmp("TLSv1", pv)) { proto = 0; }
2547  else if(!strcmp("TLSv1.1", pv)) { proto = 1; }
2548  else if(!strcmp("TLSv1.2", pv)) { proto = 2; }
2549  else { proto = 3; }
2550  }
2551  if(!res)
2552  {
2553  res = tls_chain_check_sigalgs(certificate_chain, proto);
2554  }
2555  }
2556 
2557  /* Verify server certificate */
2558  if(!res)
2559  {
2560 # if CFG_USE_OPENSSL_API_3
2561  certificate = SSL_get1_peer_certificate(*ssl);
2562 # else /* CFG_USE_OPENSSL_API_3 */
2563  certificate = SSL_get_peer_certificate(*ssl);
2564 # endif /* CFG_USE_OPENSSL_API_3 */
2565  if(NULL == certificate)
2566  {
2567  PRINT_ERROR("Server has presented no certificate");
2568  res = -1;
2569  }
2570  else
2571  {
2572  /* Certificate present */
2573  res = 1;
2574  *cert = (void*) certificate;
2575  /* Let OpenSSL check whether the certificate is trusted */
2576  rv = SSL_get_verify_result(*ssl);
2577  if(X509_V_OK != rv)
2578  {
2579  sp = X509_verify_cert_error_string(rv);
2580  /* printf("Errorcode: %d\n", ERR_GET_REASON(rv)); */
2581  api_posix_snprintf(b, 256,
2582  "%sAlert: Server X.509 certificate verification "
2583  "failed (%s)", MAIN_ERR_PREFIX, sp);
2584  print_error(b);
2585 # if !CFG_TLS_CRLS_DISABLE
2586  if(X509_V_ERR_UNABLE_TO_GET_CRL == rv
2587  || X509_V_ERR_CRL_HAS_EXPIRED == rv)
2588  {
2589  /* Reset CRL update timestamp to force new CRL update */
2590  PRINT_ERROR("Resetting CRL update timestamp");
2591  tls_reset_crl_age();
2592  }
2593 # endif /* !CFG_TLS_CRLS_DISABLE */
2594  }
2595  else
2596  {
2597  /* Verify subject */
2598  subject = X509_get_subject_name(certificate);
2599  if(NULL == subject)
2600  {
2601  PRINT_ERROR("Extraction of subject from X.509 certificate "
2602  "failed");
2603  }
2604  else
2605  {
2606  printf("%s: %sServer certificate:\n", CFG_NAME, MAIN_ERR_PREFIX);
2607  /* Extract alternative names first and compare with cn */
2608  an = X509_get_ext_d2i(certificate, NID_subject_alt_name,
2609  NULL, NULL);
2610  if(NULL != an)
2611  {
2612  num = sk_GENERAL_NAME_num(an);
2613  for(i = 0; i < num; ++i)
2614  {
2615  ani = sk_GENERAL_NAME_value(an, i);
2616  if(GEN_DNS == ani->type)
2617  {
2618 # if CFG_USE_OPENSSL_API_1_1
2619  p = (const char*) ASN1_STRING_get0_data(ani->d.dNSName);
2620 # else /* CFG_USE_OPENSSL_API_1_1 */
2621  /* This function is deprecated since API 1.1 */
2622  p = (const char*) ASN1_STRING_data(ani->d.dNSName);
2623 # endif /* CFG_USE_OPENSSL_API_1_1 */
2624  printf("%s: %s Subject Alternative Name: %s",
2625  CFG_NAME, MAIN_ERR_PREFIX, p);
2626  if(!tls_subject_check(cn, p)) { match = 1; break; }
2627  }
2628  }
2629  GENERAL_NAMES_free(an);
2630  }
2631  /* Extract common names from subject and compare with cn */
2632  if(!match)
2633  {
2634  while(1)
2635  {
2636  i = X509_NAME_get_index_by_NID(subject, NID_commonName, i);
2637  if(-1 == i) { break; }
2638  common_name = X509_NAME_get_entry(subject, i);
2639  common_name_string = X509_NAME_ENTRY_get_data(common_name);
2640 # if CFG_USE_OPENSSL_API_1_1
2641  p = (const char*) ASN1_STRING_get0_data(common_name_string);
2642 # else /* CFG_USE_OPENSSL_API_1_1 */
2643  /* This function is deprecated since API 1.1 */
2644  p = (const char*) ASN1_STRING_data(common_name_string);
2645 # endif /* CFG_USE_OPENSSL_API_1_1 */
2646  printf("%s: %s Subject Name: %s",
2647  CFG_NAME, MAIN_ERR_PREFIX, p);
2648  if(!tls_subject_check(cn, p)) { match = 1; break; }
2649  }
2650  }
2651  if(!match)
2652  {
2653  api_posix_snprintf(b, 256,
2654  "%sAlert: Server X.509 certificate "
2655  "verification failed "
2656  "(Subject doesn't match hostname %s)",
2657  MAIN_ERR_PREFIX, cn);
2658  print_error(b);
2659  }
2660  else
2661  {
2662  /* We trust the certificate and certificate match hostname */
2663 # if !CFG_TLS_CRLS_DISABLE
2664  if(config[CONF_CRL_CHECK].val.i)
2665  {
2666  printf("%s: %sServer certificate verification "
2667  "successful\n", CFG_NAME, MAIN_ERR_PREFIX);
2668  }
2669  else
2670  {
2671  printf("%s: %sServer certificate verification "
2672  "succesful (revocation checks were skipped)\n",
2673  CFG_NAME, MAIN_ERR_PREFIX);
2674  }
2675 # else /* !CFG_TLS_CRLS_DISABLE */
2676  printf("%s: %sServer certificate verification successful "
2677  "(revocation checks were skipped)\n",
2678  CFG_NAME, MAIN_ERR_PREFIX);
2679 # endif /* !CFG_TLS_CRLS_DISABLE */
2680  res = 0;
2681  }
2682  }
2683  }
2684  }
2685  }
2686 
2687  /* Clean up */
2688  if(NULL != certificate) { X509_free(certificate); }
2689  if(NULL != biop) { BIO_free(biop); }
2690 
2691  return(res);
2692 }
2693 
2694 
2695 /* ========================================================================== */
2696 /*! \brief Print certificate
2697  *
2698  * \param[in] cert Pointer to cerificate
2699  * \param[out] cbuf Pointer buffer pointer
2700  *
2701  * On success, a memory block is allocated for the certificate and a pointer to
2702  * it is written to \e cbuf. The caller is responsible to free the memory block
2703  * allocated for the certificate.
2704  *
2705  * \return
2706  * - 0 on success
2707  * - -1 on error
2708  */
2709 
2710 int tls_cert_get_string(void* cert, const char** cbuf)
2711 {
2712  int res = -1;
2713  X509* certificate;
2714  BIO* biop = BIO_new(BIO_s_mem());
2715  int rv;
2716  char* p = NULL;
2717  size_t len;
2718  char* buf = NULL;
2719 
2720  certificate = (X509*) cert;
2721  rv = X509_print(biop, certificate);
2722  if(1 == rv)
2723  {
2724  len = (size_t) BIO_get_mem_data(biop, &p);
2725  if(NULL != p && len)
2726  {
2727  buf = (char*) api_posix_malloc(len + (size_t) 1);
2728  if(NULL != buf)
2729  {
2730  memcpy((void*) buf, (void*) p, len);
2731  buf[len] = 0;
2732  *cbuf = buf;
2733  res = 0;
2734  }
2735  }
2736  }
2737 
2738  /* Clean up */
2739  if(NULL != biop) { BIO_free(biop); }
2740  if(res) { api_posix_free((void*) buf); }
2741 
2742  return(res);
2743 }
2744 
2745 
2746 /* ========================================================================== */
2747 /*! \brief Send data
2748  *
2749  * \param[in] co Pointer to connection object pointer
2750  * \param[in] buf Pointer to data buffer
2751  * \param[in] len Number of octets to send
2752  *
2753  * \return
2754  * - Number of bytes sent
2755  * - -1 on error
2756  */
2757 
2758 api_posix_ssize_t tls_send(void* co, const void* buf, size_t len)
2759 {
2760  api_posix_ssize_t res = -1;
2761  int num;
2762 
2763  /* Check size */
2764  if(API_POSIX_INT_MAX < len)
2765  {
2766  PRINT_ERROR("tls_send(): Data length too large");
2767  }
2768  num = (int) len;
2769 
2770  res = (api_posix_ssize_t) SSL_write((SSL*) co, buf, num);
2771  if(!res) { res = -1; }
2772 
2773  return(res);
2774 }
2775 
2776 
2777 /* ========================================================================== */
2778 /*! \brief Receive data
2779  *
2780  * \param[in] co Pointer to connection object pointer
2781  * \param[out] buf Pointer to data buffer
2782  * \param[in] len Number of octets to receive
2783  * \param[in] peek Data should stay available for reading if nonzero
2784  *
2785  * \attention
2786  * The \e peek flag doesn't work anymore since OpenSSL 1.1.0 and must be zero
2787  * in this case (otherwise a deadlock will occur).
2788  * This bug was fixed before OpenSSL 1.1.1 (works again now).
2789  *
2790  * \return
2791  * - Number of bytes received
2792  * - -1 on error
2793  */
2794 
2795 api_posix_ssize_t tls_recv(void* co, void* buf, size_t len, int peek)
2796 {
2797  api_posix_ssize_t res = -1;
2798  int num;
2799 
2800  /* Check size */
2801  if(API_POSIX_INT_MAX < len)
2802  {
2803  PRINT_ERROR("tls_recv(): Data length too large");
2804  }
2805  num = (int) len;
2806 
2807  /* Check for peek flag */
2808  if(peek)
2809  {
2810 # if CFG_USE_OPENSSL_API_1_1 && !CFG_USE_OPENSSL_API_3
2811  PRINT_ERROR("tls_recv(): "
2812  "Flag 'peek' not supported with OpenSSL 1.1.x");
2813 # else /* CFG_USE_OPENSSL_API_1_1 && !CFG_USE_OPENSSL_API_3 */
2814  res = (api_posix_ssize_t) SSL_peek((SSL*) co, buf, num);
2815 # endif /* CFG_USE_OPENSSL_API_1_1 && !CFG_USE_OPENSSL_API_3 */
2816  }
2817  else { res = (api_posix_ssize_t) SSL_read((SSL*) co, buf, num); }
2818  if(!res) { res = -1; }
2819 
2820  return(res);
2821 }
2822 
2823 
2824 /* ========================================================================== */
2825 /*! \brief Check whether CRL update interval has elapsed
2826  *
2827  * This function is exported for the UI module to check the CRL update interval
2828  * and give the user a choice to delay the CRL updates.
2829  * The function \ref tls_crl_update_control() is intended to enable and disable
2830  * the automatic CRL updates.
2831  *
2832  * \note
2833  * The update choice can be disabled with configuration option \c CONF_CRL_UPD_C
2834  * (if configured to zero, this function will alays return zero).
2835  *
2836  * \return
2837  * - 0 Do nothing
2838  * - 1 CRL update interval elapsed. Give user a choice to suppress update
2839  * - -1 on error
2840  */
2841 
2843 {
2844  int res = 0;
2845 
2846 # if !CFG_TLS_CRLS_DISABLE
2848  {
2849  res = tls_check_crl_age();
2850  }
2851 # endif /* !CFG_TLS_CRLS_DISABLE */
2852 
2853  return(res);
2854 }
2855 
2856 
2857 /* ========================================================================== */
2858 /*! \brief Enable or disable automatic CRL updates
2859  *
2860  * \param[in] crl_upd_disable Disable automatic CRL updates if nonzero
2861  *
2862  * \attention
2863  * If CRLs are used, they need to be present and valid! With this function the
2864  * update of CRLs can only be suppressed until they expire. After expiration of
2865  * the CRLs a TLS connection can no longer be established (if a certificate
2866  * chain is used for authentication).
2867  *
2868  * \note
2869  * When disabled, the CRL updates can be reenabled on the fly at any time by
2870  * calling this function again with \e crl_upd_disable set to zero.
2871  */
2872 
2873 void tls_crl_update_control(int crl_upd_disable)
2874 {
2875 # if !CFG_TLS_CRLS_DISABLE
2876  /* Store CRL update flag */
2877  tls_crl_update_skip = crl_upd_disable;
2878 # else /* !CFG_TLS_CRLS_DISABLE */
2879  (void) crl_upd_disable;
2880 # endif /* !CFG_TLS_CRLS_DISABLE */
2881 }
2882 
2883 
2884 /* ========================================================================== */
2885 /*! \brief Free an object allocated by TLS module
2886  *
2887  * Use this function to release dynamic memory that was allocated by the
2888  * TLS module.
2889  *
2890  * \param[in] p Pointer to object
2891  *
2892  * Release the memory for the object pointed to by \e p.
2893  *
2894  * \note
2895  * The pointer \e p is allowed to be \c NULL and no operation is performed in
2896  * this case.
2897  */
2898 
2899 void tls_free(void* p)
2900 {
2901  api_posix_free(p);
2902 }
2903 
2904 
2905 #endif /* CFG_USE_TLS */
2906 
2907 
2908 /*! @} */
2909 
2910 /* EOF */
enc_get_iso8601_utc
int enc_get_iso8601_utc(char *isodate)
Get current UTC date in ISO 8601 conformant format.
Definition: encoding.c:3412
tls_vulnerability_check
int tls_vulnerability_check(int check)
Check TLS subsystem for known vulnerabilities.
Definition: tls.c:1863
tls_exit
void tls_exit(void)
Shutdown TLS subsystem.
Definition: tls.c:1815
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:2899
tls_close
int tls_close(void **co)
Terminate TLS encryption layer on top of network connection.
Definition: tls.c:2315
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:2842
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_cert_get_string
int tls_cert_get_string(void *cert, const char **cbuf)
Print certificate.
Definition: tls.c:2710
fu_lock_file
int fu_lock_file(int filedesc)
Lock file for writing.
Definition: fileutils.c:335
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:2364
config
struct conf config[CONF_NUM]
Global configuration.
Definition: conf.c:63
tls_recv
api_posix_ssize_t tls_recv(void *co, void *buf, size_t len, int peek)
Receive data.
Definition: tls.c:2795
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:2081
conf_string_replace
int conf_string_replace(struct conf *cfg, const char *s)
Replace configuration string.
Definition: conf.c:918
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:1764
conf_entry_val::i
int i
Definition: conf.h:104
fu_create_path
int fu_create_path(const char *path, api_posix_mode_t perm)
Create path.
Definition: fileutils.c:122
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:2472
PRINT_ERROR
#define PRINT_ERROR(s)
Prepend module prefix and print error message.
Definition: main.h:19
tls_send
api_posix_ssize_t tls_send(void *co, const void *buf, size_t len)
Send data.
Definition: tls.c:2758
tls_sni
const char * tls_sni(const char *sn)
Check whether server name used for connection is not an IP address.
Definition: tls.c:2008
ext_download_file
int ext_download_file(const char *lpn, const char *uri)
Download file from external source.
Definition: extutils.c:1081
xdg_get_confdir
const char * xdg_get_confdir(const char *)
Get configuration directory.
Definition: xdg.c:116
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:591
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:409
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:297
conf::val
union conf_entry_val val
Definition: conf.h:113
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:2873
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:3467
fu_open_file
int fu_open_file(const char *pathname, int *filedesc, int mode, api_posix_mode_t perm)
Open file.
Definition: fileutils.c:246
print_error
void print_error(const char *)
Print error message.
Definition: main.cxx:276

Generated at 2026-01-27 using  doxygen