The FreeRADIUS server  $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
ctx.c
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16 
17 /**
18  * $Id: 66d2d6b0dfab6d50005c83c585e958d72f9cbbe1 $
19  *
20  * @file tls/ctx.c
21  * @brief Initialise and configure SSL_CTX structures.
22  *
23  * @copyright 2001 hereUare Communications, Inc. (raghud@hereuare.com)
24  * @copyright 2003 Alan DeKok (aland@freeradius.org)
25  * @copyright 2006-2016 The FreeRADIUS server project
26  */
27 RCSID("$Id: 66d2d6b0dfab6d50005c83c585e958d72f9cbbe1 $")
28 USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
29 
30 #ifdef WITH_TLS
31 #define LOG_PREFIX "tls"
32 
33 #include <freeradius-devel/tls/log.h>
34 #include <freeradius-devel/tls/strerror.h>
35 #include <freeradius-devel/util/base16.h>
36 #include <freeradius-devel/util/debug.h>
37 #include <freeradius-devel/util/misc.h>
38 #include <freeradius-devel/util/strerror.h>
39 #include <freeradius-devel/util/syserror.h>
40 
41 #include "base.h"
42 #include "utils.h"
43 #include "log.h"
44 #include "cert.h"
45 
46 #include <openssl/rand.h>
47 #include <openssl/dh.h>
48 #include <openssl/x509v3.h>
49 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
50 # include <openssl/provider.h>
51 #endif
52 
53 #ifndef OPENSSL_NO_ECDH
54 static int ctx_ecdh_curve_set(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
55 {
56  char *list;
57 
58  if (!disable_single_dh_use) {
59  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
60  }
61 
62  if (!ecdh_curve || !*ecdh_curve) return 0;
63 
64  list = strdup(ecdh_curve);
65  if (SSL_CTX_set1_curves_list(ctx, list) == 0) {
66  free(list);
67  ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
68  return -1;
69  }
70  free(list);
71  return 0;
72 }
73 #endif
74 
75 /*
76  * TODO: Check for the type of key exchange * like conf->dh_key
77  */
78 static int ctx_dh_params_load(SSL_CTX *ctx, char *file)
79 {
80  BIO *bio;
81  int ret;
82 
83 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
84  EVP_PKEY *dh = NULL;
85 #else
86  DH *dh = NULL;
87 #endif
88 
89  if (!file) return 0;
90 
91  /*
92  * Prior to trying to load the file, check what OpenSSL will do with it.
93  *
94  * Certain downstreams (such as RHEL) will ignore user-provided dhparams
95  * in FIPS mode, unless the specified parameters are FIPS-approved.
96  * However, since OpenSSL >= 1.1.1 will automatically select parameters
97  * anyways, there's no point in attempting to load them.
98  *
99  * Change suggested by @t8m
100  */
101 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
102 # if OPENSSL_VERSION_NUMBER >= 0x30000000L
103  if (EVP_default_properties_is_fips_enabled(NULL)) {
104 # else
105  if (FIPS_mode() > 0) {
106 #endif
107  WARN(LOG_PREFIX ": Ignoring user-selected DH parameters in FIPS mode. Using defaults.");
108  return 0;
109  }
110 #endif
111 
112  if ((bio = BIO_new_file(file, "r")) == NULL) {
113  ERROR("Unable to open DH file - %s", file);
114  return -1;
115  }
116 
117 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
118  dh = PEM_read_bio_Parameters(bio, &dh);
119 #else
120  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
121 #endif
122  BIO_free(bio);
123  if (!dh) {
124  WARN("Unable to set DH parameters. DH cipher suites may not work!");
125  WARN("Fix this by generating the DH parameter file");
126  return 0;
127  }
128 
129 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
130  ret = SSL_CTX_set0_tmp_dh_pkey(ctx, dh);
131 #else
132  ret = SSL_CTX_set_tmp_dh(ctx, dh);
133  DH_free(dh);
134 #endif
135 
136  if (ret < 0) {
137  ERROR("Unable to set DH parameters");
138  return -1;
139  }
140 
141  return 0;
142 }
143 
144 static int tls_ctx_verify_chain_member(fr_unix_time_t *expires_first, X509 **self_signed,
145  SSL_CTX *ctx, X509 *to_verify,
146  fr_tls_chain_verify_mode_t verify_mode)
147 {
148  fr_unix_time_t not_after;
149 
150  STACK_OF(X509) *chain;
151  X509 *leaf;
152 
153  leaf = SSL_CTX_get0_certificate(ctx);
154  if (!leaf) {
155  ERROR("Chain does not contain a valid leaf certificate");
156  return -1;
157  }
158 
159  if (!SSL_CTX_get0_chain_certs(ctx, &chain)) {
160  fr_tls_log(NULL, "Failed retrieving chain certificates");
161  return -1;
162  }
163 
164  switch (fr_tls_cert_is_valid(NULL, &not_after, to_verify)) {
165  case -1:
166  fr_tls_chain_marker_log(NULL, L_ERR, chain, leaf, to_verify);
167  PERROR("Malformed certificate");
168  return -1;
169 
170  case -2:
171  case -3:
172  switch (verify_mode) {
173  case FR_TLS_CHAIN_VERIFY_SOFT:
174  fr_tls_chain_marker_log(NULL, L_WARN, chain, leaf, to_verify);
175  PWARN("Certificate validation failed");
176  break;
177 
178  case FR_TLS_CHAIN_VERIFY_HARD:
179  fr_tls_chain_marker_log(NULL, L_ERR, chain, leaf, to_verify);
180  PERROR("Certificate validation failed");
181  return -1;
182 
183  default:
184  break;
185  }
186 
187  }
188 
189  /*
190  * Check for self-signed certs
191  */
192  switch (verify_mode) {
193  case FR_TLS_CHAIN_VERIFY_SOFT:
194  case FR_TLS_CHAIN_VERIFY_HARD:
195  /*
196  * There can be only one... self signed
197  * cert in a chain.
198  *
199  * We have to do this check manually
200  * because the OpenSSL functions will
201  * only check to see if it can build
202  * a chain, not that all certificates
203  * in the chain are used.
204  *
205  * Having multiple self-signed certificates
206  * usually indicates someone has copied
207  * the wrong certificates into the
208  * server.pem file.
209  */
210  if (X509_name_cmp(X509_get_subject_name(to_verify),
211  X509_get_issuer_name(to_verify)) == 0) {
212  if (*self_signed) {
213  switch (verify_mode) {
214  case FR_TLS_CHAIN_VERIFY_SOFT:
215  WARN("Found multiple self-signed certificates in chain");
216  WARN("First certificate was:");
217  fr_tls_chain_marker_log(NULL, L_WARN,
218  chain, leaf, *self_signed);
219 
220  WARN("Second certificate was:");
221  fr_tls_chain_marker_log(NULL, L_WARN,
222  chain, leaf, to_verify);
223  break;
224 
225  case FR_TLS_CHAIN_VERIFY_HARD:
226  ERROR("Found multiple self-signed certificates in chain");
227  ERROR("First certificate was:");
228  fr_tls_chain_marker_log(NULL, L_ERR,
229  chain, leaf, *self_signed);
230 
231  ERROR("Second certificate was:");
232  fr_tls_chain_marker_log(NULL, L_ERR,
233  chain, leaf, to_verify);
234  return -1;
235 
236  default:
237  break;
238  }
239  }
240  *self_signed = to_verify;
241  }
242  break;
243 
244  default:
245  break;
246  }
247 
248  /*
249  * Record the time the first certificate in
250  * the chain expires so we can use it for
251  * runtime checks.
252  */
253  if (!fr_unix_time_ispos(*expires_first) ||
254  (fr_unix_time_gt(*expires_first, not_after))) *expires_first = not_after;
255 
256  return 0;
257 }
258 
259 static int tls_ctx_load_cert_chain(SSL_CTX *ctx, fr_tls_chain_conf_t *chain, bool allow_multi_self_signed)
260 {
261  char *password;
262 
263  /*
264  * Conf parser should ensure they're both populated
265  */
266  fr_assert(chain->certificate_file && chain->private_key_file);
267 
268  /*
269  * Set the password (this should have been retrieved earlier)
270  */
271  memcpy(&password, &chain->password, sizeof(password));
272  SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
273 
274  /*
275  * Always set the callback as it provides useful debug
276  * output if the certificate isn't set.
277  */
278  SSL_CTX_set_default_passwd_cb(ctx, fr_tls_session_password_cb);
279 
280  switch (chain->file_format) {
281  case SSL_FILETYPE_PEM:
282  if (!(SSL_CTX_use_certificate_chain_file(ctx, chain->certificate_file))) {
283  fr_tls_log(NULL, "Failed reading certificate file \"%s\"",
284  chain->certificate_file);
285  return -1;
286  }
287  break;
288 
289  case SSL_FILETYPE_ASN1:
290  if (!(SSL_CTX_use_certificate_file(ctx, chain->certificate_file, chain->file_format))) {
291  fr_tls_log(NULL, "Failed reading certificate file \"%s\"",
292  chain->certificate_file);
293  return -1;
294  }
295  break;
296 
297  default:
298  fr_assert(0);
299  break;
300  }
301 
302  if (!(SSL_CTX_use_PrivateKey_file(ctx, chain->private_key_file, chain->file_format))) {
303  fr_tls_log(NULL, "Failed reading private key file \"%s\"",
304  chain->private_key_file);
305  return -1;
306  }
307 
308  {
309  size_t extra_cnt, i;
310  /*
311  * Load additional chain certificates from other files
312  * This allows us to specify chains in DER format as
313  * well as PEM, and means we can keep the intermediaries
314  * CAs and client/server certs in separate files.
315  */
316  extra_cnt = talloc_array_length(chain->ca_files);
317  for (i = 0; i < extra_cnt; i++) {
318  FILE *fp;
319  X509 *cert;
320  char const *filename = chain->ca_files[i];
321 
322  fp = fopen(filename, "r");
323  if (!fp) {
324  ERROR("Failed opening ca_file \"%s\": %s", filename, fr_syserror(errno));
325  return -1;
326  }
327 
328  /*
329  * Load the PEM encoded X509 certificate
330  */
331  switch (chain->file_format) {
332  case SSL_FILETYPE_PEM:
333  cert = PEM_read_X509(fp, NULL, NULL, NULL);
334  break;
335 
336  case SSL_FILETYPE_ASN1:
337  cert = d2i_X509_fp(fp, NULL);
338  break;
339 
340  default:
341  fr_assert(0);
342  fclose(fp);
343  return -1;
344  }
345  fclose(fp);
346 
347  if (!cert) {
348  fr_tls_log(NULL, "Failed reading certificate file \"%s\"", filename);
349  return -1;
350  }
351  SSL_CTX_add0_chain_cert(ctx, cert);
352  }
353  }
354 
355  /*
356  * Check if the last loaded private key matches the last
357  * loaded certificate.
358  *
359  * Note: The call to SSL_CTX_use_certificate_chain_file
360  * can load in a private key too.
361  */
362  if (!SSL_CTX_check_private_key(ctx)) {
363  ERROR("Private key does not match the certificate public key");
364  return -1;
365  }
366 
367  /*
368  * Loop over the certificates checking validity periods.
369  * SSL_CTX_build_cert_chain does this too, but we can
370  * produce significantly better errors here.
371  *
372  * After looping over all the certs we figure out when
373  * the chain will next need refreshing.
374  */
375  {
376  fr_unix_time_t expires_first = fr_unix_time_wrap(0);
377  X509 *self_signed = NULL;
378  STACK_OF(X509) *our_chain;
379  int i;
380 
381  if (tls_ctx_verify_chain_member(&expires_first, &self_signed,
382  ctx, SSL_CTX_get0_certificate(ctx),
383  chain->verify_mode) < 0) return -1;
384 
385  if (!SSL_CTX_get0_chain_certs(ctx, &our_chain)) {
386  fr_tls_log(NULL, "Failed retrieving chain certificates");
387  return -1;
388  }
389 
390  if (allow_multi_self_signed) self_signed = NULL;
391 
393 DIAG_OFF(used-but-marked-unused) /* fix spurious warnings for sk macros */
394  for (i = sk_X509_num(our_chain); i > 0 ; i--) {
395  /*
396  * SSL_CTX_use_certificate_chain_file set the
397  * current cert to be the one loaded from
398  * that pem file.
399  */
400  if (tls_ctx_verify_chain_member(&expires_first, &self_signed,
401  ctx, sk_X509_value(our_chain, i - 1),
402  chain->verify_mode) < 0) return -1;
403 
404  if (allow_multi_self_signed) self_signed = NULL;
405  }
406 DIAG_ON(used-but-marked-unused) /* fix spurious warnings for sk macros */
408  /*
409  * Record this as a unix timestamp as
410  * internal time might not progress at
411  * the same rate as wallclock time.
412  */
413  chain->valid_until = expires_first;
414  }
415 
416  {
417  int mode = SSL_BUILD_CHAIN_FLAG_CHECK;
418 
419  if (!chain->include_root_ca) mode |= SSL_BUILD_CHAIN_FLAG_NO_ROOT;
420 
421  /*
422  * Explicitly check that the certificate chain
423  * we just loaded is sane.
424  *
425  * This operates on the last loaded certificate.
426  */
427  switch (chain->verify_mode) {
428  case FR_TLS_CHAIN_VERIFY_NONE:
429  mode |= SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR | SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR;
430  (void)SSL_CTX_build_cert_chain(ctx, mode);
431  break;
432 
433  /*
434  * Seems to be a bug where
435  * SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR trashes the error,
436  * so have the function fail as normal.
437  */
438  case FR_TLS_CHAIN_VERIFY_SOFT:
439  if (!SSL_CTX_build_cert_chain(ctx, mode)) {
440  fr_tls_strerror_printf(NULL);
441  PWARN("Failed verifying chain");
442  }
443  break;
444 
445  case FR_TLS_CHAIN_VERIFY_HARD:
446  if (!SSL_CTX_build_cert_chain(ctx, mode)) {
447  fr_tls_strerror_printf(NULL);
448  PERROR("Failed verifying chain");
449  return -1;
450  }
451  break;
452 
453  default:
454  break;
455  }
456  }
457 
458  return 0;
459 }
460 
461 static inline CC_HINT(always_inline)
462 int tls_ctx_version_set(
463 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
464  UNUSED
465 #endif
466  int *ctx_options, SSL_CTX *ctx, fr_tls_conf_t const *conf)
467 {
468 
469 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
470  /*
471  * SSL_CTX_set_(min|max)_proto_version was included in OpenSSL 1.1.0
472  *
473  * This version already defines macros for TLS1_2_VERSION and
474  * below, so we don't need to check for them explicitly.
475  *
476  * TLS1_3_VERSION is available in OpenSSL 1.1.1.
477  *
478  * TLS1_4_VERSION does not exist yet. But we allow it
479  * only if it is explicitly permitted by the
480  * administrator.
481  */
482  if (conf->tls_max_version > (float) 0.0) {
483  int max_version = 0;
484 
485  if (conf->tls_min_version > conf->tls_max_version) {
486  /*
487  * %f is actually %lg now (double). Compile complains about
488  * implicit promotion unless we cast args to double.
489  */
490  ERROR("tls_min_version (%f) must be <= tls_max_version (%f)",
491  (double)conf->tls_min_version, (double)conf->tls_max_version);
492  error:
493  return -1;
494  }
495 
496  if (conf->tls_max_version < (float) 1.0) {
497  ERROR("tls_max_version must be >= 1.0 as SSLv2 and SSLv3 are permanently disabled");
498  goto error;
499  }
500 
501 # ifdef TLS1_4_VERSION
502  else if (conf->tls_max_version >= (float) 1.4) max_version = TLS1_4_VERSION;
503 # endif
504 # ifdef TLS1_3_VERSION
505  else if (conf->tls_max_version >= (float) 1.3) max_version = TLS1_3_VERSION;
506 # endif
507  else if (conf->tls_max_version >= (float) 1.2) max_version = TLS1_2_VERSION;
508  else if (conf->tls_max_version >= (float) 1.1) max_version = TLS1_1_VERSION;
509  else max_version = TLS1_VERSION;
510 
511  /*
512  * Complain about insecure TLS versions.
513  */
514  if (max_version < TLS1_2_VERSION) {
515  WARN("TLS 1.0 and 1.1 are insecure and SHOULD NOT be used");
516  WARN("tls_max_version SHOULD be 1.2 or greater");
517  }
518 
519  if (!SSL_CTX_set_max_proto_version(ctx, max_version)) {
520  fr_tls_log(NULL, "Failed setting TLS maximum version");
521  goto error;
522  }
523  }
524 
525  {
526  int min_version;
527 
528  if (conf->tls_min_version < (float) 1.0) {
529  ERROR("tls_min_version must be >= 1.0 as SSLv2 and SSLv3 are permanently disabled");
530  goto error;
531  }
532 # ifdef TLS1_4_VERSION
533  else if (conf->tls_min_version >= (float) 1.4) min_version = TLS1_4_VERSION;
534 # endif
535 # ifdef TLS1_3_VERSION
536  else if (conf->tls_min_version >= (float) 1.3) min_version = TLS1_3_VERSION;
537 # endif
538  else if (conf->tls_min_version >= (float) 1.2) min_version = TLS1_2_VERSION;
539  else if (conf->tls_min_version >= (float) 1.1) min_version = TLS1_1_VERSION;
540  else min_version = TLS1_VERSION;
541 
542  /*
543  * Complain about insecure TLS versions.
544  */
545  if (min_version < TLS1_2_VERSION) {
546  WARN("TLS 1.0 and 1.1 are insecure and SHOULD NOT be used");
547  WARN("tls_min_version SHOULD be 1.2 or greater");
548  }
549 
550  if (!SSL_CTX_set_min_proto_version(ctx, min_version)) {
551  fr_tls_log(NULL, "Failed setting TLS minimum version");
552  goto error;
553  }
554  }
555 #else
556  /*
557  * OpenSSL < 1.1.0 - This doesn't need to change when new TLS versions are issued
558  * as new TLS versions will never be added to older OpenSSL versions.
559  */
560  {
561  int ctx_tls_versions = 0;
562 
563  /*
564  * We never want SSLv2 or SSLv3.
565  */
566  *ctx_options |= SSL_OP_NO_SSLv2;
567  *ctx_options |= SSL_OP_NO_SSLv3;
568 
569 # ifdef SSL_OP_NO_TLSv1
570  if (conf->tls_min_version > (float) 1.0) *ctx_options |= SSL_OP_NO_TLSv1;
571  ctx_tls_versions |= SSL_OP_NO_TLSv1;
572 # endif
573 # ifdef SSL_OP_NO_TLSv1_1
574  if (conf->tls_min_version > (float) 1.1) *ctx_options |= SSL_OP_NO_TLSv1_1;
575  if ((conf->tls_max_version > (float) 0.0) && (conf->tls_max_version < (float) 1.1)) {
576  *ctx_options |= SSL_OP_NO_TLSv1_1;
577  }
578  ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
579 # endif
580 # ifdef SSL_OP_NO_TLSv1_2
581  if (conf->tls_min_version > (float) 1.2) *ctx_options |= SSL_OP_NO_TLSv1_2;
582  if ((conf->tls_max_version > (float) 0.0) && (conf->tls_max_version < (float) 1.2)) {
583  *ctx_options |= SSL_OP_NO_TLSv1_2;
584  }
585  ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
586 # endif
587 
588  if ((*ctx_options & ctx_tls_versions) == ctx_tls_versions) {
589  ERROR("You have disabled all available TLS versions");
590  goto error;
591  }
592  }
593 #endif
594 
595  return 0;
596 }
597 
598 /** Create SSL context
599  *
600  * - Load the trusted CAs
601  * - Load the Private key & the certificate
602  * - Set the Context options & Verify options
603  *
604  * @param conf to read settings from.
605  * @param client If true SSL_CTX will be configured as a client context.
606  * @return
607  * - A new SSL_CTX on success.
608  * - NULL on failure.
609  */
610 SSL_CTX *fr_tls_ctx_alloc(fr_tls_conf_t const *conf, bool client)
611 {
612  SSL_CTX *ctx;
613  X509_STORE *cert_vpstore;
614  X509_STORE *verify_store;
615  int ctx_options = 0;
616 
617  ctx = SSL_CTX_new(TLS_method());
618  if (!ctx) {
619  fr_tls_log(NULL, "Failed creating TLS context");
620  return NULL;
621  }
622 
623  /*
624  * Save the config on the context so that callbacks which
625  * only get SSL_CTX* e.g. session persistence, can get at it.
626  */
627  SSL_CTX_set_ex_data(ctx, FR_TLS_EX_INDEX_CONF, UNCONST(void *, conf));
628 
629  /*
630  * Identify the type of certificates that needs to be loaded
631  */
632 #ifdef PSK_MAX_IDENTITY_LEN
633  /*
634  * A dynamic query exists. There MUST NOT be a
635  * statically configured identity and password.
636  */
637  if (conf->psk_query) {
638  if (!*conf->psk_query) {
639  ERROR("Invalid PSK Configuration: psk_query cannot be empty");
640  error:
641  SSL_CTX_free(ctx);
642  return NULL;
643  }
644 
645  if (conf->psk_identity && *conf->psk_identity) {
646  ERROR("Invalid PSK Configuration: psk_identity and psk_query cannot be used at the same time.");
647  goto error;
648  }
649 
650  if (conf->psk_password && *conf->psk_password) {
651  ERROR("Invalid PSK Configuration: psk_password and psk_query cannot be used at the same time.");
652  goto error;
653  }
654 
655  if (client) {
656  ERROR("Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
657  goto error;
658  }
659 
660  /*
661  * Now check that if PSK is being used, that the config is valid.
662  */
663  } else if (conf->psk_identity) {
664  if (!*conf->psk_identity) {
665  ERROR("Invalid PSK Configuration: psk_identity is empty");
666  goto error;
667  }
668 
669 
670  if (!conf->psk_password || !*conf->psk_password) {
671  ERROR("Invalid PSK Configuration: psk_identity is set, but there is no psk_password");
672  goto error;
673  }
674 
675  } else if (conf->psk_password) {
676  ERROR("Invalid PSK Configuration: psk_password is set, but there is no psk_identity");
677  goto error;
678  }
679 
680  /*
681  * Set the server PSK callback if necessary.
682  */
683  if (!client && (conf->psk_identity || conf->psk_query)) {
684  SSL_CTX_set_psk_server_callback(ctx, fr_tls_session_psk_server_cb);
685  }
686 
687  /*
688  * Do more sanity checking if we have a PSK identity. We
689  * check the password, and convert it to it's final form.
690  */
691  if (conf->psk_identity && *conf->psk_identity) {
692  size_t psk_len, hex_len;
693  uint8_t buffer[PSK_MAX_PSK_LEN];
694 
695  if (client) {
696  SSL_CTX_set_psk_client_callback(ctx, fr_tls_session_psk_client_cb);
697  }
698 
699  if (!conf->psk_password) goto error; /* clang is too dumb to catch the above checks */
700 
701  psk_len = strlen(conf->psk_password);
702  if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
703  ERROR("psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
704  goto error;
705  }
706 
707  /*
708  * Check the password now, so that we don't have
709  * errors at run-time.
710  */
711  hex_len = fr_base16_decode(NULL,
712  &FR_DBUFF_TMP(buffer, sizeof(buffer)),
713  &FR_SBUFF_IN(conf->psk_password, psk_len), false);
714  if (psk_len != (2 * hex_len)) {
715  ERROR("psk_hexphrase is not all hex");
716  goto error;
717  }
718 
719  goto post_ca;
720  }
721 #else
722  (void) client; /* -Wunused */
723 #endif
724 
725  /*
726  * Set mode before processing any certifictes
727  */
728  {
729  int mode = SSL_MODE_ASYNC;
730 
731  /*
732  * OpenSSL will automatically create certificate chains,
733  * unless we tell it to not do that. The problem is that
734  * it sometimes gets the chains right from a certificate
735  * signature view, but wrong from the clients view.
736  *
737  * It's better just to have users specify the complete
738  * chains.
739  */
740  mode |= SSL_MODE_NO_AUTO_CHAIN;
741 
742  if (client) {
743  mode |= SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
744  mode |= SSL_MODE_AUTO_RETRY;
745  }
746 
747  if (mode) SSL_CTX_set_mode(ctx, mode);
748  }
749 
750  /*
751  * Initialise a separate store for verifying user
752  * certificates.
753  *
754  * This makes the configuration cleaner as there's
755  * no mixing of chain certs and user certs.
756  */
757  MEM(verify_store = X509_STORE_new());
758 
759  /* Sets OpenSSL's (CERT *)->verify_store, overring (SSL_CTX *)->cert_store */
760  SSL_CTX_set0_verify_cert_store(ctx, verify_store);
761 
762  /* This isn't accessible to use later, i.e. there's no SSL_CTX_get0_verify_cert_store */
763  SSL_CTX_set_ex_data(ctx, FR_TLS_EX_CTX_INDEX_VERIFY_STORE, verify_store);
764 
765  /*
766  * Load the CAs we trust
767  */
768  if (conf->ca_file || conf->ca_path) {
769  /*
770  * This adds all the certificates to the store for conf->ca_file
771  * and adds a dynamic lookup for conf->ca_path.
772  *
773  * It's also possible to add extra virtual server lookups
774  */
775  if (!X509_STORE_load_locations(verify_store, conf->ca_file, conf->ca_path)) {
776  fr_tls_log(NULL, "Failed reading Trusted root CA list \"%s\"",
777  conf->ca_file);
778  goto error;
779  }
780 
781  /*
782  * These set the default parameters of the store when the
783  * store is involved in building chains.
784  *
785  * - X509_PURPOSE_SSL_CLIENT ensure the purpose of the
786  * client certificate is for peer authentication as
787  * a client.
788  */
789  X509_STORE_set_purpose(verify_store, X509_PURPOSE_SSL_CLIENT);
790 
791  /*
792  * Sets the list of CAs we send to the peer if we're
793  * requesting a certificate.
794  *
795  * This does not change the trusted certificate authorities,
796  * those are set above with SSL_CTX_load_verify_locations.
797  */
798  if (conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
799  } else {
800  X509_STORE_set_default_paths(verify_store);
801  }
802 
803  /*
804  * Load our certificate chains and keys
805  */
806  if (conf->chains) {
807  size_t chains_conf = talloc_array_length(conf->chains);
808 
809  /*
810  * Load our keys and certificates
811  *
812  * If certificates are of type PEM then we can make use
813  * of cert chain authentication using openssl api call
814  * SSL_CTX_use_certificate_chain_file. Please see how
815  * the cert chain needs to be given in PEM from
816  * openSSL.org
817  */
818  {
819  size_t i;
820 
821  for (i = 0; i < chains_conf; i++) {
822  if (tls_ctx_load_cert_chain(ctx, conf->chains[i], false) < 0) goto error;
823  }
824  }
825 
826  /*
827  * Print out our certificate chains.
828  *
829  * There may be up to three, one for RSA, DH, DSA and EC.
830  * OpenSSL internally and transparently stores completely
831  * separate and distinct RSA/DSA/DH/ECC key pairs and chains.
832  */
833  if (DEBUG_ENABLED2) {
834  size_t chains_set = 0;
835  int ret;
836 
837  /*
838  * Iterate over the different chain types we have
839  * RSA, DSA, DH, EC etc...
840  */
841  for (ret = SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_FIRST);
842  ret == 1;
843  ret = SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_NEXT)) chains_set++;
844 
845  /*
846  * Check for discrepancies
847  */
848 
849  DEBUG3("Found %zu server certificate chain(s)", chains_set);
850 
851  if (chains_set != chains_conf) {
852  WARN("Number of chains configured (%zu) does not match chains set (%zu)",
853  chains_conf, chains_set);
854  if (chains_conf > chains_set) WARN("Only one chain per key type is allowed, "
855  "check config for duplicates");
856  }
857 
858  for (ret = SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_FIRST);
859  ret == 1;
860  ret = SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_NEXT)) {
861  STACK_OF(X509) *our_chain;
862  X509 *our_cert;
863 
864  our_cert = SSL_CTX_get0_certificate(ctx);
865 
866  /*
867  * The pkey type of the server certificate
868  * determines which pkey slot OpenSSL
869  * uses to store the chain.
870  */
871  DEBUG3("%s chain", fr_tls_utils_x509_pkey_type(our_cert));
872  if (!SSL_CTX_get0_chain_certs(ctx, &our_chain)) {
873  fr_tls_log(NULL, "Failed retrieving chain certificates");
874  goto error;
875  }
876 
877  if (DEBUG_ENABLED3) fr_tls_chain_log(NULL, L_DBG, our_chain, our_cert);
878  }
879  (void)SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_FIRST); /* Reset */
880  }
881  }
882 
883 #ifdef PSK_MAX_IDENTITY_LEN
884 post_ca:
885 #endif
886  if (tls_ctx_version_set(&ctx_options, ctx, conf) < 0) goto error;
887 
888  /*
889  * SSL_OP_SINGLE_DH_USE must be used in order to prevent
890  * small subgroup attacks and forward secrecy. Always
891  * using SSL_OP_SINGLE_DH_USE has an impact on the
892  * computer time needed during negotiation, but it is not
893  * very large.
894  */
895  if (!conf->disable_single_dh_use) {
896  ctx_options |= SSL_OP_SINGLE_DH_USE;
897  }
898 
899 #ifdef SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS
900  /*
901  * Note: This flag isn't honoured by all OpenSSL forks.
902  */
903  if (conf->allow_renegotiation) {
904  ctx_options |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
905  }
906 #endif
907 
908  /*
909  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
910  * in Windows Vista client.
911  * http://www.openssl.org/~bodo/tls-cbc.txt
912  * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
913  */
914  ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
915 
916  /*
917  * SSL_OP_CIPHER_SERVER_PREFERENCE to follow best practice
918  * of nowday's TLS: do not allow poorly-selected ciphers from
919  * client to take preference
920  */
921  if (conf->cipher_server_preference) ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
922 
923  SSL_CTX_set_options(ctx, ctx_options);
924 
925  /*
926  * TODO: Set the RSA & DH
927  * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
928  * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
929  */
930 
931 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
932  /*
933  * Set the block size for record padding. This is only
934  * used in TLS 1.3.
935  */
936  if (conf->padding_block_size) SSL_CTX_set_block_padding(ctx, conf->padding_block_size);
937 #endif
938 
939  /*
940  * Set elliptical curve crypto configuration.
941  */
942 #ifndef OPENSSL_NO_ECDH
943  if (ctx_ecdh_curve_set(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) goto error;
944 #endif
945 
946 
947  /* Set Info callback */
948  SSL_CTX_set_info_callback(ctx, fr_tls_session_info_cb);
949 
950  /*
951  * Check the certificates for revocation.
952  */
953 #ifdef X509_V_FLAG_CRL_CHECK_ALL
954  if (conf->verify.check_crl) {
955  cert_vpstore = SSL_CTX_get_cert_store(ctx);
956  if (cert_vpstore == NULL) {
957  fr_tls_log(NULL, "Error reading Certificate Store");
958  goto error;
959  }
960  X509_STORE_set_flags(cert_vpstore, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
961 #ifdef X509_V_FLAG_USE_DELTAS
962  /*
963  * If set, delta CRLs (if present) are used to
964  * determine certificate status. If not set
965  * deltas are ignored.
966  *
967  * So it's safe to always set this flag.
968  */
969  X509_STORE_set_flags(cert_vpstore, X509_V_FLAG_USE_DELTAS);
970 #endif
971  }
972 #endif
973 
974  /*
975  * SSL_ctx_set_verify is now called in the session
976  * alloc functions so they can set custom behaviour
977  * depending on the code area the SSL * will be used
978  * and whether we're acting as a client or server.
979  */
980  if (conf->verify_depth) {
981  SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
982  }
983 
984 #ifdef HAVE_OPENSSL_OCSP_H
985  /*
986  * Configure OCSP stapling for the server cert
987  */
988  if (conf->staple.enable) {
989  SSL_CTX_set_tlsext_status_cb(ctx, fr_tls_ocsp_staple_cb);
990  SSL_CTX_set_tlsext_status_arg(ctx, UNCONST(fr_tls_ocsp_conf_t *, &(conf->staple)));
991  }
992 #endif
993 
994  /*
995  * Set the cipher list if we were told to
996  */
997  if (conf->cipher_list) {
998  if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
999  fr_tls_log(NULL, "Failed setting cipher list");
1000  goto error;
1001  }
1002  }
1003 
1004  /*
1005  * Print the actual cipher list
1006  */
1007  if (DEBUG_ENABLED3) {
1008  SSL *ssl;
1009  unsigned int i = 0;
1010  char const *cipher;
1011 
1012  ssl = SSL_new(ctx);
1013  if (!ssl) {
1014  fr_tls_log(NULL, "Failed creating temporary SSL session");
1015  goto error;
1016  }
1017 
1018  DEBUG3("Configured ciphers (by priority)");
1019 
1020  while ((cipher = SSL_get_cipher_list(ssl, i))) {
1021  DEBUG3("[%i] %s", i, cipher);
1022  i++; /* Print index starting at zero */
1023  }
1024 
1025  SSL_free(ssl);
1026  }
1027 
1028  /*
1029  * Load dh params
1030  */
1031  if (conf->dh_file && (ctx_dh_params_load(ctx, UNCONST(char *, conf->dh_file)) < 0)) goto error;
1032 
1033  /*
1034  * Setup session caching
1035  */
1036  if (fr_tls_cache_ctx_init(ctx, &conf->cache) < 0) goto error;
1037 
1038 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
1039  /*
1040  * Set the keylog file if the admin requested it.
1041  */
1042  if ((getenv("SSLKEYLOGFILE") != NULL) || (conf->keylog_file && *conf->keylog_file)) {
1043  SSL_CTX_set_keylog_callback(ctx, fr_tls_session_keylog_cb);
1044  }
1045 #endif
1046 
1047  return ctx;
1048 }
1049 #endif
static int const char char buffer[256]
Definition: acutest.h:574
int const char * file
Definition: acutest.h:702
#define fr_base16_decode(_err, _out, _in, _no_trailing)
Definition: base16.h:95
#define UNCONST(_type, _ptr)
Remove const qualification from a pointer.
Definition: build.h:165
#define USES_APPLE_DEPRECATED_API
Definition: build.h:431
#define RCSID(id)
Definition: build.h:444
#define DIAG_UNKNOWN_PRAGMAS
Definition: build.h:417
#define DIAG_ON(_x)
Definition: build.h:419
#define UNUSED
Definition: build.h:313
#define DIAG_OFF(_x)
Definition: build.h:418
#define FR_DBUFF_TMP(_start, _len_or_end)
Creates a compound literal to pass into functions which accept a dbuff.
Definition: dbuff.h:509
#define ERROR(fmt,...)
Definition: dhcpclient.c:41
free(array)
#define LOG_PREFIX
Definition: base.c:63
#define PERROR(_fmt,...)
Definition: log.h:228
#define DEBUG_ENABLED2
True if global debug level 1-2 messages are enabled.
Definition: log.h:258
#define DEBUG3(_fmt,...)
Definition: log.h:266
#define PWARN(_fmt,...)
Definition: log.h:227
#define DEBUG_ENABLED3
True if global debug level 1-3 messages are enabled.
Definition: log.h:259
@ L_WARN
Warning.
Definition: log.h:57
@ L_ERR
Error message.
Definition: log.h:56
@ L_DBG
Only displayed when debugging is enabled.
Definition: log.h:59
unsigned char uint8_t
Definition: merged_model.c:30
static size_t used
int fr_tls_ocsp_staple_cb(SSL *ssl, void *data)
OCSP Configuration.
Definition: ocsp.h:4
static fr_bio_t * bio
Definition: radclient-ng.c:86
#define WARN(fmt,...)
Definition: radclient.h:47
static rs_t * conf
Definition: radsniff.c:53
#define FR_SBUFF_IN(_start, _len_or_end)
fr_assert(0)
MEM(pair_append_request(&vp, attr_eap_aka_sim_identity) >=0)
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition: syserror.c:243
#define fr_unix_time_ispos(_a)
Definition: time.h:370
#define fr_unix_time_gt(_a, _b)
Definition: time.h:363
#define fr_unix_time_wrap(_time)
Definition: time.h:160
"Unix" time.
Definition: time.h:95
char const * fr_tls_utils_x509_pkey_type(X509 *cert)
Returns a friendly identifier for the public key type of a certificate.
Definition: utils.c:45