The FreeRADIUS server  $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
rlm_cipher.c
Go to the documentation of this file.
1 /*
2  * This program is 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 (at
5  * 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: 4fa8e1c270abb2153e1a77cc7fc6ae16449c52a8 $
19  * @file rlm_cipher.c
20  * @brief Creates dynamic expansions for encrypting/decrypting data.
21  *
22  * @author Arran Cudbard-Bell (a.cudbardb@freeradius.org)
23  *
24  * @copyright 2018 The FreeRADIUS server project
25  * @copyright 2018 Network RADIUS (legal@networkradius.com)
26  *
27  */
28 RCSID("$Id: 4fa8e1c270abb2153e1a77cc7fc6ae16449c52a8 $")
29 
30 #include <freeradius-devel/server/base.h>
31 #include <freeradius-devel/server/module_rlm.h>
32 #include <freeradius-devel/tls/base.h>
33 #include <freeradius-devel/tls/cert.h>
34 #include <freeradius-devel/tls/log.h>
35 #include <freeradius-devel/tls/strerror.h>
36 #include <freeradius-devel/util/debug.h>
37 #include <freeradius-devel/unlang/xlat_func.h>
38 #include <freeradius-devel/unlang/xlat.h>
39 
40 #include <freeradius-devel/tls/openssl_user_macros.h>
41 #include <openssl/crypto.h>
42 #include <openssl/pem.h>
43 #include <openssl/evp.h>
44 #include <openssl/rsa.h>
45 #include <openssl/x509.h>
46 
47 static int digest_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent,
48  CONF_ITEM *ci, UNUSED conf_parser_t const *rule);
49 static int cipher_rsa_padding_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent,
50  CONF_ITEM *ci, UNUSED conf_parser_t const *rule);
51 static int cipher_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent,
52  CONF_ITEM *ci, UNUSED conf_parser_t const *rule);
53 
54 static int cipher_rsa_private_key_file_load(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent,
55  CONF_ITEM *ci, UNUSED conf_parser_t const *rule);
56 static int cipher_rsa_certificate_file_load(TALLOC_CTX *ctx, void *out, UNUSED void *parent,
57  CONF_ITEM *ci, UNUSED conf_parser_t const *rule);
58 
59 typedef enum {
63 
64 /** Certificate validation modes
65  *
66  */
67 typedef enum {
69 
70  CIPHER_CERT_VERIFY_HARD, //!< Fail if the certificate isn't valid.
71  CIPHER_CERT_VERIFY_SOFT, //!< Warn if the certificate isn't valid.
72  CIPHER_CERT_VERIFY_NONE //!< Don't check to see if the we're between
73  ///< notBefore or notAfter.
75 
76 typedef enum {
77  CIPHER_CERT_ATTR_UNKNOWN = 0, //!< Unrecognised attribute.
78  CIPHER_CERT_ATTR_SERIAL, //!< Certificate's serial number.
79  CIPHER_CERT_ATTR_FINGERPRINT, //!< Dynamically calculated fingerprint.
80  CIPHER_CERT_ATTR_NOT_BEFORE, //!< Time the certificate becomes valid.
81  CIPHER_CERT_ATTR_NOT_AFTER //!< Time the certificate expires.
83 
84 /** Public key types
85  *
86  */
88  { L("DH"), EVP_PKEY_DH },
89  { L("DSA"), EVP_PKEY_DSA },
90  { L("EC"), EVP_PKEY_EC },
91  { L("RSA"), EVP_PKEY_RSA }
92 };
94 
95 /** The type of padding used
96  *
97  */
99  { L("none"), RSA_NO_PADDING },
100  { L("oaep"), RSA_PKCS1_OAEP_PADDING }, /* PKCS OAEP padding */
101  { L("pkcs"), RSA_PKCS1_PADDING }, /* PKCS 1.5 */
102 #if OPENSSL_VERSION_NUMBER < 0x30000000L
103  { L("ssl"), RSA_SSLV23_PADDING },
104 #endif
105  { L("x931"), RSA_X931_PADDING }
106 };
108 
110  { L("rsa"), RLM_CIPHER_TYPE_RSA }
111 };
113 
115  { L("hard"), CIPHER_CERT_VERIFY_HARD },
116  { L("none"), CIPHER_CERT_VERIFY_SOFT },
117  { L("soft"), CIPHER_CERT_VERIFY_NONE }
118 };
120 
121 /** Public key types
122  *
123  */
125  { L("fingerprint"), CIPHER_CERT_ATTR_FINGERPRINT },
126  { L("notAfter"), CIPHER_CERT_ATTR_NOT_AFTER },
127  { L("notBefore"), CIPHER_CERT_ATTR_NOT_BEFORE },
128  { L("serial"), CIPHER_CERT_ATTR_SERIAL },
129 };
131 
132 typedef struct {
133  EVP_PKEY_CTX *evp_encrypt_ctx; //!< Pre-allocated evp_pkey_ctx.
134  EVP_PKEY_CTX *evp_sign_ctx; //!< Pre-allocated evp_pkey_ctx.
135  EVP_PKEY_CTX *evp_decrypt_ctx; //!< Pre-allocated evp_pkey_ctx.
136  EVP_PKEY_CTX *evp_verify_ctx; //!< Pre-allocated evp_pkey_ctx.
137 
138  EVP_MD_CTX *evp_md_ctx; //!< Pre-allocated evp_md_ctx for sign and verify.
139  uint8_t *digest_buff; //!< Pre-allocated digest buffer.
141 
142 /** Configuration for the OAEP padding method
143  *
144  */
145 typedef struct {
146  EVP_MD *oaep_digest; //!< Padding digest type.
147  EVP_MD *mgf1_digest; //!< Masking function digest.
148 
149  char const *label; //!< Additional input to the hashing function.
151 
152 
153 
154 /** Configuration for RSA encryption/decryption/signing
155  *
156  */
157 typedef struct {
158  char const *private_key_password; //!< Password to decrypt the private key.
159  char const *random_file; //!< If set, we read 10K of data (or the complete file)
160  //!< and use it to seed OpenSSL's PRNG.
161 
162  EVP_PKEY *private_key_file; //!< Private key file.
163  EVP_PKEY *certificate_file; //!< Public (certificate) file.
164  X509 *x509_certificate_file; //!< Needed for extracting certificate attributes.
165 
166  cipher_cert_verify_mode_t verify_mode; //!< How hard we try to verify the certificate.
167  fr_unix_time_t not_before; //!< Certificate isn't valid before this time.
168  fr_unix_time_t not_after; //!< Certificate isn't valid after this time.
169 
170  int padding; //!< Type of padding to apply to the plaintext
171  ///< or ciphertext before feeding it to RSA crypto
172  ///< functions.
173 
174  EVP_MD *sig_digest; //!< Signature digest type.
175 
176  cipher_rsa_oaep_t *oaep; //!< OAEP can use a configurable message digest type
177 } cipher_rsa_t;
178 
179 /** Instance configuration
180  *
181  */
182 typedef struct {
183  cipher_type_t type; //!< Type of encryption to use.
184 
185  /** Supported cipher types
186  *
187  */
188  union {
189  cipher_rsa_t *rsa; //!< Use RSA encryption (with optional padding).
190  };
191 } rlm_cipher_t;
192 
193 /** Configuration for the RSA-PCKS1-OAEP padding scheme
194  *
195  */
196 static const conf_parser_t rsa_oaep_config[] = {
197  { FR_CONF_OFFSET_TYPE_FLAGS("oaep_digest", FR_TYPE_VOID, CONF_FLAG_NOT_EMPTY, cipher_rsa_oaep_t, oaep_digest), .func = digest_type_parse, .dflt = "sha256" },
198  { FR_CONF_OFFSET_TYPE_FLAGS("mgf1_digest", FR_TYPE_VOID, CONF_FLAG_NOT_EMPTY, cipher_rsa_oaep_t, mgf1_digest), .func = digest_type_parse, .dflt = "sha256" },
199  { FR_CONF_OFFSET("label", cipher_rsa_oaep_t, label) },
200 
202 };
203 
204 /** Configuration for the RSA cipher type
205  *
206  */
207 static const conf_parser_t rsa_config[] = {
208  { FR_CONF_OFFSET("verify_mode", cipher_rsa_t, verify_mode),
209  .func = cf_table_parse_int,
210  .uctx = &(cf_table_parse_ctx_t){
213  },
214  .dflt = "hard" }, /* Must come before certificate file */
215 
216  { FR_CONF_OFFSET_FLAGS("private_key_password", CONF_FLAG_SECRET, cipher_rsa_t, private_key_password) }, /* Must come before private_key */
219 
220  { FR_CONF_OFFSET("random_file", cipher_rsa_t, random_file) },
221 
222  { FR_CONF_OFFSET_TYPE_FLAGS("signature_digest", FR_TYPE_VOID, CONF_FLAG_NOT_EMPTY, cipher_rsa_t, sig_digest), .func = digest_type_parse, .dflt = "sha256" },
223 
224  { FR_CONF_OFFSET_TYPE_FLAGS("padding_type", FR_TYPE_VOID, CONF_FLAG_NOT_EMPTY, cipher_rsa_t, padding), .func = cipher_rsa_padding_type_parse, .dflt = "pkcs" },
225 
227  .subcs_size = sizeof(cipher_rsa_oaep_t), .subcs_type = "cipher_rsa_oaep_t" },
228 
230 };
231 
232 /*
233  * A mapping of configuration file names to internal variables.
234  */
235 static const conf_parser_t module_config[] = {
237  { FR_CONF_OFFSET_SUBSECTION("rsa", 0, rlm_cipher_t, rsa, rsa_config), .subcs_size = sizeof(cipher_rsa_t), .subcs_type = "cipher_rsa_t" },
238 
240 };
241 
242 /** Calls EVP_get_digestbyname() to convert the digest type
243  *
244  * @param[in] ctx to allocate data in.
245  * @param[out] out EVP_MD representing the OpenSSL digest type.
246  * @param[in] parent Base structure address.
247  * @param[in] ci #CONF_PAIR specifying the name of the digest.
248  * @param[in] rule unused.
249  * @return
250  * - 0 on success.
251  * - -1 on failure.
252  */
253 static int digest_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent,
254  CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
255 {
256  EVP_MD const *md;
257  char const *type_str;
258 
259  type_str = cf_pair_value(cf_item_to_pair(ci));
260  md = EVP_get_digestbyname(type_str);
261  if (!md) {
262  cf_log_err(ci, "Invalid digest type \"%s\"", type_str);
263  return -1;
264  }
265 
266  *((EVP_MD const **)out) = md;
267 
268  return 0;
269 }
270 
271 /** Checks if the specified padding type is valid
272  *
273  * @param[in] ctx to allocate data in.
274  * @param[out] out Padding type.
275  * @param[in] parent Base structure address.
276  * @param[in] ci #CONF_PAIR specifying the padding type..
277  * @param[in] rule unused.
278  * @return
279  * - 0 on success.
280  * - -1 on failure.
281  */
282 static int cipher_rsa_padding_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent,
283  CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
284 {
285  int type;
286  char const *type_str;
287 
288  type_str = cf_pair_value(cf_item_to_pair(ci));
290  if (type == -1) {
291  cf_log_err(ci, "Invalid padding type \"%s\"", type_str);
292  return -1;
293  }
294 
295  *((int *)out) = type;
296 
297  return 0;
298 }
299 
300 /** Checks if the specified cipher type is valid
301  *
302  * @param[in] ctx to allocate data in.
303  * @param[out] out Cipher enumeration type.
304  * @param[in] parent Base structure address.
305  * @param[in] ci #CONF_PAIR specifying the name of the type module.
306  * @param[in] rule unused.
307  * @return
308  * - 0 on success.
309  * - -1 on failure.
310  */
311 static int cipher_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
312 {
314  char const *type_str;
315 
316  type_str = cf_pair_value(cf_item_to_pair(ci));
318  switch (type) {
319  case RLM_CIPHER_TYPE_RSA:
320  break;
321 
323  cf_log_err(ci, "Invalid cipher type \"%s\"", type_str);
324  return -1;
325  }
326 
327  *((cipher_type_t *)out) = type;
328 
329  return 0;
330 }
331 
332 /** Return the static private key password we have configured
333  *
334  * @param[out] buf Where to write the password to.
335  * @param[in] size The length of buf.
336  * @param[in] rwflag
337  * - 0 if password used for decryption.
338  * - 1 if password used for encryption.
339  * @param[in] u The static password.
340  * @return
341  * - 0 on error.
342  * - >0 on success (the length of the password).
343  */
344 static int _get_private_key_password(char *buf, int size, UNUSED int rwflag, void *u)
345 {
346  char *pass;
347  size_t len;
348 
349  if (!u) {
350  ERROR("Certificate encrypted but no private_key_password configured");
351  return 0;
352  }
353 
354  pass = talloc_get_type_abort(u, char);
355  len = talloc_array_length(pass); /* Len includes \0 */
356  if (len > (size_t)size) {
357  ERROR("Password too long. Maximum length is %i bytes", size - 1);
358  return -1;
359  }
360  memcpy(buf, pass, len); /* Copy complete password including \0 byte */
361 
362  return len - 1;
363 }
364 
365 /** Talloc destructor for freeing an EVP_PKEY (representing a certificate)
366  *
367  * @param[in] pkey to free.
368  * @return 0
369  */
370 static int _evp_pkey_free(EVP_PKEY *pkey)
371 {
372  EVP_PKEY_free(pkey);
373 
374  return 0;
375 }
376 
377 /** Talloc destructor for freeing an X509 struct (representing a public certificate)
378  *
379  * @param[in] cert to free.
380  * @return 0
381  */
382 static int _x509_cert_free(X509 *cert)
383 {
384  X509_free(cert);
385 
386  return 0;
387 }
388 
389 /** Load and (optionally decrypt) an RSA private key using OpenSSL functions
390  *
391  * @param[in] ctx UNUSED. Although the EVP_PKEY struct will be allocated
392  * with talloc, we need to call the specialised free
393  * function anyway.
394  * @param[out] out Where to write the EVP_PKEY * representing the
395  * certificate we just loaded.
396  * @param[in] parent Base structure address.
397  * @param[in] ci Config item containing the certificate path.
398  * @param[in] rule this callback was attached to.
399  * @return
400  * - -1 on failure.
401  * - 0 on success.
402  */
403 static int cipher_rsa_private_key_file_load(TALLOC_CTX *ctx, void *out, void *parent,
404  CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
405 {
406  FILE *fp;
407  char const *filename;
408  cipher_rsa_t *rsa_inst = talloc_get_type_abort(parent, cipher_rsa_t);
409  EVP_PKEY *pkey;
410  int pkey_type;
411 
412  filename = cf_pair_value(cf_item_to_pair(ci));
413 
414  fp = fopen(filename, "r");
415  if (!fp) {
416  cf_log_err(ci, "Failed opening private_key file \"%s\": %s", filename, fr_syserror(errno));
417  return -1;
418  }
419 
420  pkey = PEM_read_PrivateKey(fp, (EVP_PKEY **)out, _get_private_key_password,
421  UNCONST(void *, rsa_inst->private_key_password));
422  fclose(fp);
423 
424  if (!pkey) {
425  fr_tls_strerror_printf(NULL);
426  cf_log_perr(ci, "Error loading private certificate file \"%s\"", filename);
427 
428  return -1;
429  }
430 
431  pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
432  if (pkey_type != EVP_PKEY_RSA) {
433  cf_log_err(ci, "Expected certificate to contain %s private key, got %s private key",
434  fr_table_str_by_value(pkey_types, EVP_PKEY_RSA, OBJ_nid2sn(pkey_type)),
435  fr_table_str_by_value(pkey_types, pkey_type, OBJ_nid2sn(pkey_type)));
436 
437  EVP_PKEY_free(pkey);
438  return -1;
439  }
440 
441  talloc_set_type(pkey, EVP_PKEY);
442  (void)talloc_steal(ctx, pkey); /* Bind lifetime to config */
443  talloc_set_destructor(pkey, _evp_pkey_free); /* Free pkey correctly on chunk free */
444 
445  return 0;
446 }
447 
448 /** Load an RSA public key using OpenSSL functions
449  *
450  * @param[in] ctx UNUSED. Although the EVP_PKEY struct will be allocated
451  * with talloc, we need to call the specialised free
452  * function anyway.
453  * @param[out] out Where to write the EVP_PKEY * representing the
454  * certificate we just loaded.
455  * @param[in] parent Base structure address.
456  * @param[in] ci Config item containing the certificate path.
457  * @param[in] rule this callback was attached to.
458  * @return
459  * - -1 on failure.
460  * - 0 on success.
461  */
462 static int cipher_rsa_certificate_file_load(TALLOC_CTX *ctx, void *out, void *parent,
463  CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
464 {
465  FILE *fp;
466  char const *filename;
467  cipher_rsa_t *rsa_inst = talloc_get_type_abort(parent, cipher_rsa_t);
468 
469  X509 *cert; /* X509 certificate */
470  EVP_PKEY *pkey; /* Wrapped public key */
471  int pkey_type;
472 
473  filename = cf_pair_value(cf_item_to_pair(ci));
474 
475  fp = fopen(filename, "r");
476  if (!fp) {
477  cf_log_err(ci, "Failed opening certificate_file \"%s\": %s", filename, fr_syserror(errno));
478  return -1;
479  }
480 
481  /*
482  * Load the PEM encoded X509 certificate
483  */
484  cert = PEM_read_X509(fp, NULL, NULL, NULL);
485  fclose(fp);
486 
487  if (!cert) {
488  fr_tls_strerror_printf(NULL);
489  cf_log_perr(ci, "Error loading certificate file \"%s\"", filename);
490 
491  return -1;
492  }
493 
494  /*
495  * Keep the x509 structure around as we may want
496  * to extract information from fields in the cert
497  * or calculate its fingerprint.
498  */
499  talloc_set_type(cert, X509);
500  (void)talloc_steal(ctx, cert); /* Bind lifetime to config */
501  talloc_set_destructor(cert, _x509_cert_free); /* Free x509 cert correctly on chunk free */
502 
503  /*
504  * Extract the public key from the certificate
505  */
506  pkey = X509_get_pubkey(cert);
507  if (!pkey) {
508  fr_tls_strerror_printf(NULL);
509  cf_log_perr(ci, "Failed extracting public key from certificate");
510 
511  return -1;
512  }
513 
514  pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
515  if (pkey_type != EVP_PKEY_RSA) {
516  cf_log_err(ci, "Expected certificate to contain %s public key, got %s public key",
517  fr_table_str_by_value(pkey_types, EVP_PKEY_RSA, "?Unknown?"),
518  fr_table_str_by_value(pkey_types, pkey_type, "?Unknown?"));
519  error:
520  EVP_PKEY_free(pkey);
521  return -1;
522  }
523 
524  /*
525  * Certificate validity checks
526  */
527  switch (fr_tls_cert_is_valid(&rsa_inst->not_before, &rsa_inst->not_after, cert)) {
528  case 0:
529  cf_log_debug(ci, "Certificate validity starts at %pV and ends at %pV",
530  fr_box_date(rsa_inst->not_before), fr_box_date(rsa_inst->not_after));
531  break;
532 
533  case -1:
534  cf_log_perr(ci, "Malformed certificate");
535  return -1;
536 
537  case -2:
538  case -3:
539  switch (rsa_inst->verify_mode) {
541  cf_log_pwarn(ci, "Certificate validation failed");
542  break;
543 
545  cf_log_perr(ci, "Certificate validation failed");
546  goto error;
547 
549  break;
550 
552  fr_assert(0);
553  break;
554  }
555  }
556 
557  talloc_set_type(pkey, EVP_PKEY);
558  (void)talloc_steal(cert, pkey); /* Bind lifetime to config */
559  talloc_set_destructor(pkey, _evp_pkey_free); /* Free pkey correctly on chunk free */
560 
561  rsa_inst->x509_certificate_file = cert; /* Not great, but shouldn't cause any issues */
562  *(EVP_PKEY **)out = pkey;
563 
564  return 0;
565 }
566 
568  { .required = true, .concat = true, .type = FR_TYPE_STRING },
570 };
571 
572 /** Encrypt input data
573  *
574  * Arguments are @verbatim(<plaintext>...)@endverbatim
575  *
576 @verbatim
577 %<inst>.encrypt(<plaintext>...)
578 @endverbatim
579  *
580  * If multiple arguments are provided they will be concatenated.
581  *
582  * @ingroup xlat_functions
583  */
585  xlat_ctx_t const *xctx,
586  request_t *request, fr_value_box_list_t *in)
587 {
588  rlm_cipher_rsa_thread_inst_t *t = talloc_get_type_abort(xctx->mctx->thread, rlm_cipher_rsa_thread_inst_t);
589 
590  char const *plaintext;
591  size_t plaintext_len;
592 
593  uint8_t *ciphertext;
594  size_t ciphertext_len;
595 
596  fr_value_box_t *vb;
597  fr_value_box_t *in_head = fr_value_box_list_head(in);
598 
599  plaintext = in_head->vb_strvalue;
600  plaintext_len = in_head->vb_length;
601 
602  /*
603  * Figure out the buffer we need
604  */
605  RHEXDUMP3((uint8_t const *)plaintext, plaintext_len, "Plaintext (%zu bytes)", plaintext_len);
606  if (EVP_PKEY_encrypt(t->evp_encrypt_ctx, NULL, &ciphertext_len,
607  (unsigned char const *)plaintext, plaintext_len) <= 0) {
608  fr_tls_log(request, "Failed getting length of encrypted plaintext");
609  return XLAT_ACTION_FAIL;
610  }
611 
612  MEM(vb = fr_value_box_alloc_null(ctx));
613  MEM(fr_value_box_mem_alloc(vb, &ciphertext, vb, NULL, ciphertext_len, false) == 0);
614  if (EVP_PKEY_encrypt(t->evp_encrypt_ctx, ciphertext, &ciphertext_len,
615  (unsigned char const *)plaintext, plaintext_len) <= 0) {
616  fr_tls_log(request, "Failed encrypting plaintext");
617  talloc_free(vb);
618  return XLAT_ACTION_FAIL;
619  }
620  RHEXDUMP3(ciphertext, ciphertext_len, "Ciphertext (%zu bytes)", ciphertext_len);
621  MEM(fr_value_box_mem_realloc(vb, NULL, vb, ciphertext_len) == 0);
622  fr_dcursor_append(out, vb);
623 
624  return XLAT_ACTION_DONE;
625 }
626 
627 
629  { .required = true, .concat = true, .type = FR_TYPE_STRING },
631 };
632 
633 /** Sign input data
634  *
635  * Arguments are @verbatim(<plaintext>...)@endverbatim
636  *
637 @verbatim
638 %<inst>.sign(<plaintext>...)
639 @endverbatim
640  *
641  * If multiple arguments are provided they will be concatenated.
642  *
643  * @ingroup xlat_functions
644  */
646  xlat_ctx_t const *xctx,
647  request_t *request, fr_value_box_list_t *in)
648 {
650  rlm_cipher_rsa_thread_inst_t *t = talloc_get_type_abort(xctx->mctx->thread, rlm_cipher_rsa_thread_inst_t);
651 
652  char const *msg;
653  size_t msg_len;
654 
655  uint8_t *sig;
656  size_t sig_len;
657 
658  unsigned int digest_len = 0;
659 
660  fr_value_box_t *vb;
661  fr_value_box_t *in_head = fr_value_box_list_head(in);
662 
663  msg = in_head->vb_strvalue;
664  msg_len = in_head->vb_length;
665 
666  /*
667  * First produce a digest of the message
668  */
669  if (unlikely(EVP_DigestInit_ex(t->evp_md_ctx, inst->rsa->sig_digest, NULL) <= 0)) {
670  fr_tls_log(request, "Failed initialising message digest");
671  return XLAT_ACTION_FAIL;
672  }
673 
674  if (EVP_DigestUpdate(t->evp_md_ctx, msg, msg_len) <= 0) {
675  fr_tls_log(request, "Failed ingesting message");
676  return XLAT_ACTION_FAIL;
677  }
678 
679  if (EVP_DigestFinal_ex(t->evp_md_ctx, t->digest_buff, &digest_len) <= 0) {
680  fr_tls_log(request, "Failed finalising message digest");
681  return XLAT_ACTION_FAIL;
682  }
683  fr_assert((size_t)digest_len == talloc_array_length(t->digest_buff));
684 
685  /*
686  * Then sign the digest
687  */
688  if (EVP_PKEY_sign(t->evp_sign_ctx, NULL, &sig_len, t->digest_buff, (size_t)digest_len) <= 0) {
689  fr_tls_log(request, "Failed getting length of digest");
690  return XLAT_ACTION_FAIL;
691  }
692 
693  MEM(vb = fr_value_box_alloc_null(ctx));
694  MEM(fr_value_box_mem_alloc(vb, &sig, vb, NULL, sig_len, false) == 0);
695  if (EVP_PKEY_sign(t->evp_sign_ctx, sig, &sig_len, t->digest_buff, (size_t)digest_len) <= 0) {
696  fr_tls_log(request, "Failed signing message digest");
697  talloc_free(vb);
698  return XLAT_ACTION_FAIL;
699  }
700  MEM(fr_value_box_mem_realloc(vb, NULL, vb, sig_len) == 0);
701  fr_dcursor_append(out, vb);
702 
703  return XLAT_ACTION_DONE;
704 }
705 
707  { .required = true, .concat = true, .type = FR_TYPE_OCTETS },
709 };
710 
711 /** Decrypt input data
712  *
713  * Arguments are @verbatim(<ciphertext>...)@endverbatim
714  *
715 @verbatim
716 %<inst>.decrypt(<ciphertext>...)
717 @endverbatim
718  *
719  * If multiple arguments are provided they will be concatenated.
720  *
721  * @ingroup xlat_functions
722  */
724  xlat_ctx_t const *xctx,
725  request_t *request, fr_value_box_list_t *in)
726 {
727  rlm_cipher_rsa_thread_inst_t *t = talloc_get_type_abort(xctx->mctx->thread, rlm_cipher_rsa_thread_inst_t);
728 
729  uint8_t const *ciphertext;
730  size_t ciphertext_len;
731 
732  char *plaintext;
733  size_t plaintext_len;
734 
735  fr_value_box_t *vb;
736  fr_value_box_t *in_head = fr_value_box_list_head(in);
737 
738  ciphertext = in_head->vb_octets;
739  ciphertext_len = in_head->vb_length;
740 
741  /*
742  * Decrypt the ciphertext
743  */
744  RHEXDUMP3(ciphertext, ciphertext_len, "Ciphertext (%zu bytes)", ciphertext_len);
745  if (EVP_PKEY_decrypt(t->evp_decrypt_ctx, NULL, &plaintext_len, ciphertext, ciphertext_len) <= 0) {
746  fr_tls_log(request, "Failed getting length of cleartext");
747  return XLAT_ACTION_FAIL;
748  }
749 
750  MEM(vb = fr_value_box_alloc_null(ctx));
751  MEM(fr_value_box_bstr_alloc(vb, &plaintext, vb, NULL, plaintext_len, true) == 0);
752  if (EVP_PKEY_decrypt(t->evp_decrypt_ctx, (unsigned char *)plaintext, &plaintext_len,
753  ciphertext, ciphertext_len) <= 0) {
754  fr_tls_log(request, "Failed decrypting ciphertext");
755  talloc_free(vb);
756  return XLAT_ACTION_FAIL;
757  }
758  RHEXDUMP3((uint8_t const *)plaintext, plaintext_len, "Plaintext (%zu bytes)", plaintext_len);
759  MEM(fr_value_box_bstr_realloc(vb, NULL, vb, plaintext_len) == 0);
760  fr_dcursor_append(out, vb);
761 
762  return XLAT_ACTION_DONE;
763 }
764 
766  { .required = true, .concat = false, .single = true, .type = FR_TYPE_VOID },
767  { .required = true, .concat = true, .type = FR_TYPE_STRING },
768  { .variadic = XLAT_ARG_VARIADIC_EMPTY_SQUASH, .concat = true, .type = FR_TYPE_STRING },
770 };
771 
772 /** Verify input data
773  *
774  * Arguments are @verbatim(<signature>, <plaintext>...)@endverbatim
775  *
776 @verbatim
777 %<inst>.verify(<signature>, <plaintext>...)
778 @endverbatim
779  *
780  * If multiple arguments are provided (after @verbatim<signature>@endverbatim)
781  * they will be concatenated.
782  *
783  * @ingroup xlat_functions
784  */
786  xlat_ctx_t const *xctx,
787  request_t *request, fr_value_box_list_t *in)
788 {
790  rlm_cipher_rsa_thread_inst_t *t = talloc_get_type_abort(xctx->mctx->thread, rlm_cipher_rsa_thread_inst_t);
791 
792  uint8_t const *sig;
793  size_t sig_len;
794 
795  char const *msg;
796  size_t msg_len;
797 
798  unsigned int digest_len = 0;
799 
800  fr_value_box_t *vb;
801  fr_value_box_t *in_head = fr_value_box_list_pop_head(in);
803 
804  /*
805  * Don't auto-cast to octets if the signature
806  * isn't already in that form.
807  * It could be hexits or base64 or some other encoding.
808  */
809  if (in_head->type != FR_TYPE_OCTETS) {
810  REDEBUG("Signature argument wrong type, expected %s, got %s. "
811  "Use %%base64.decode(<text>) or %%hex_decode(<text>) if signature is armoured",
813  fr_type_to_str(in_head->type));
814  return XLAT_ACTION_FAIL;
815  }
816  sig = in_head->vb_octets;
817  sig_len = in_head->vb_length;
818 
819  /*
820  * Concat (...) args to get message data
821  */
822  args = fr_value_box_list_head(in);
826  SIZE_MAX) < 0) {
827  REDEBUG("Failed concatenating arguments to form plaintext");
828  return XLAT_ACTION_FAIL;
829  }
830  msg = args->vb_strvalue;
831  msg_len = args->vb_length;
832 
833  if (msg_len == 0) {
834  REDEBUG("Zero length message data");
835  return XLAT_ACTION_FAIL;
836  }
837 
838  /*
839  * First produce a digest of the message
840  */
841  if (unlikely(EVP_DigestInit_ex(t->evp_md_ctx, inst->rsa->sig_digest, NULL) <= 0)) {
842  fr_tls_log(request, "Failed initialising message digest");
843  return XLAT_ACTION_FAIL;
844  }
845 
846  if (EVP_DigestUpdate(t->evp_md_ctx, msg, msg_len) <= 0) {
847  fr_tls_log(request, "Failed ingesting message");
848  return XLAT_ACTION_FAIL;
849  }
850 
851  if (EVP_DigestFinal_ex(t->evp_md_ctx, t->digest_buff, &digest_len) <= 0) {
852  fr_tls_log(request, "Failed finalising message digest");
853  return XLAT_ACTION_FAIL;
854  }
855  fr_assert((size_t)digest_len == talloc_array_length(t->digest_buff));
856 
857  /*
858  * Now check the signature matches what we expected
859  */
860  switch (EVP_PKEY_verify(t->evp_verify_ctx, sig, sig_len, t->digest_buff, (size_t)digest_len)) {
861  case 1: /* success (signature valid) */
862  MEM(vb = fr_value_box_alloc(ctx, FR_TYPE_BOOL, NULL));
863  vb->vb_bool = true;
864  fr_dcursor_append(out, vb);
865  break;
866 
867  case 0: /* failure (signature not valid) */
868  MEM(vb = fr_value_box_alloc(ctx, FR_TYPE_BOOL, NULL));
869  vb->vb_bool = false;
870  fr_dcursor_append(out, vb);
871  break;
872 
873  default:
874  fr_tls_log(request, "Failed validating signature");
875  return XLAT_ACTION_FAIL;
876  }
877 
878  return XLAT_ACTION_DONE;
879 }
880 
882  { .required = true, .concat = false, .single = true, .type = FR_TYPE_STRING },
883  { .required = false, .concat = false, .single = true, .type = FR_TYPE_STRING }, /* Optional hash for fingerprint mode */
885 };
886 
887 /** Return the fingerprint of the public certificate
888  *
889  * Arguments are @verbatim(<digest>)@endverbatim
890  *
891 @verbatim
892 %<inst>.certificate(fingerprint, <digest>)
893 @endverbatim
894  *
895  * @ingroup xlat_functions
896  */
898  xlat_ctx_t const *xctx,
899  request_t *request, fr_value_box_list_t *in)
900 {
902  char const *md_name;
903  EVP_MD const *md;
904  size_t md_len;
905  fr_value_box_t *vb;
906  uint8_t *digest;
907 
908  if (!fr_value_box_list_next(in, fr_value_box_list_head(in))) {
909  REDEBUG("Missing digest argument");
910  return XLAT_ACTION_FAIL;
911  }
912 
913  /*
914  * Second arg...
915  */
916  md_name = ((fr_value_box_t *)fr_value_box_list_next(in, fr_value_box_list_head(in)))->vb_strvalue;
917  md = EVP_get_digestbyname(md_name);
918  if (!md) {
919  REDEBUG("Specified digest \"%s\" is not a valid digest type", md_name);
920  return XLAT_ACTION_FAIL;
921  }
922 
923  md_len = EVP_MD_size(md);
924  MEM(vb = fr_value_box_alloc_null(ctx));
925  MEM(fr_value_box_mem_alloc(vb, &digest, vb, NULL, md_len, false) == 0);
926 
927  if (X509_digest(inst->rsa->x509_certificate_file, md, digest, (unsigned int *)&md_len) != 1) {
928  fr_tls_log(request, "Failed calculating certificate fingerprint");
929  talloc_free(vb);
930  return XLAT_ACTION_FAIL;
931  }
932 
933  fr_dcursor_append(out, vb);
934 
935  return XLAT_ACTION_DONE;
936 }
937 
938 /** Return the serial of the public certificate
939  *
940 @verbatim
941 %<inst>.certificate(serial)
942 @endverbatim
943  *
944  * @ingroup xlat_functions
945  */
947  xlat_ctx_t const *xctx,
948  request_t *request, UNUSED fr_value_box_list_t *in)
949 {
951  ASN1_INTEGER const *serial;
952  fr_value_box_t *vb;
953 
954  serial = X509_get0_serialNumber(inst->rsa->x509_certificate_file);
955  if (!serial) {
956  fr_tls_log(request, "Failed retrieving certificate serial");
957  return XLAT_ACTION_FAIL;
958  }
959 
960  MEM(vb = fr_value_box_alloc_null(ctx));
961  MEM(fr_value_box_memdup(vb, vb, NULL, serial->data, serial->length, true) == 0);
962 
963  fr_dcursor_append(out, vb);
964 
965  return XLAT_ACTION_DONE;
966 }
967 
969  xlat_ctx_t const *xctx,
970  request_t *request, fr_value_box_list_t *in)
971 {
973  char const *attribute = fr_value_box_list_head(in)->vb_strvalue;
974  fr_value_box_t *vb;
975 
977  default:
978  REDEBUG("Unknown certificate attribute \"%s\"", attribute);
979  return XLAT_ACTION_FAIL;
980 
982  return cipher_fingerprint_xlat(ctx, out, xctx, request, in);
983 
985  return cipher_serial_xlat(ctx, out, xctx, request, in);
986 
988  MEM(vb = fr_value_box_alloc(ctx, FR_TYPE_DATE, NULL));
989  vb->vb_date = inst->rsa->not_before;
990  vb->tainted = true;
991  fr_dcursor_append(out, vb);
992  return XLAT_ACTION_DONE;
993 
995  MEM(vb = fr_value_box_alloc(ctx, FR_TYPE_DATE, NULL));
996  vb->vb_date = inst->rsa->not_after;
997  vb->tainted = true;
998  fr_dcursor_append(out, vb);
999  return XLAT_ACTION_DONE;
1000  }
1001 }
1002 
1003 /** Talloc destructor for freeing an EVP_PKEY_CTX
1004  *
1005  * @param[in] evp_pkey_ctx to free.
1006  * @return 0
1007  */
1008 static int _evp_pkey_ctx_free(EVP_PKEY_CTX *evp_pkey_ctx)
1009 {
1010  EVP_PKEY_CTX_free(evp_pkey_ctx);
1011 
1012  return 0;
1013 }
1014 
1015 /** Talloc destructor for freeing an EVP_MD_CTX
1016  *
1017  * @param[in] evp_md_ctx to free.
1018  * @return 0
1019  */
1020 static int _evp_md_ctx_free(EVP_MD_CTX *evp_md_ctx)
1021 {
1022  EVP_MD_CTX_destroy(evp_md_ctx);
1023 
1024  return 0;
1025 }
1026 
1027 static int cipher_rsa_padding_params_set(EVP_PKEY_CTX *evp_pkey_ctx, cipher_rsa_t const *rsa_inst)
1028 {
1029  if (unlikely(EVP_PKEY_CTX_set_rsa_padding(evp_pkey_ctx, rsa_inst->padding)) <= 0) {
1030  fr_tls_strerror_printf(NULL);
1031  PERROR("%s: Failed setting RSA padding type", __FUNCTION__);
1032  return -1;
1033  }
1034 
1035  switch (rsa_inst->padding) {
1036  case RSA_NO_PADDING:
1037  case RSA_X931_PADDING:
1038 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1039  case RSA_SSLV23_PADDING:
1040 #endif
1041  case RSA_PKCS1_PADDING:
1042  return 0;
1043 
1044  /*
1045  * Configure OAEP advanced padding options
1046  */
1047  case RSA_PKCS1_OAEP_PADDING:
1048  if (unlikely(EVP_PKEY_CTX_set_rsa_oaep_md(evp_pkey_ctx, rsa_inst->oaep->oaep_digest) <= 0)) {
1049  fr_tls_strerror_printf(NULL);
1050  PERROR("%s: Failed setting OAEP digest", __FUNCTION__);
1051  return -1;
1052  }
1053 
1054  if (unlikely(EVP_PKEY_CTX_set_rsa_mgf1_md(evp_pkey_ctx, rsa_inst->oaep->mgf1_digest) <= 0)) {
1055  fr_tls_strerror_printf(NULL);
1056  PERROR("%s: Failed setting MGF1 digest", __FUNCTION__);
1057  return -1;
1058  }
1059 
1060  if (rsa_inst->oaep->label) {
1061  char *label;
1062  size_t label_len = talloc_array_length(rsa_inst->oaep->label) - 1;
1063 
1064  /*
1065  * OpenSSL does not duplicate the label when
1066  * EVP_PKEY_CTX_set0_rsa_oaep_label is called,
1067  * but happily frees it on subsequent calls
1068  * or when the EVP_PKEY_CTX is freed,
1069  * idiots...
1070  */
1071  MEM(label = talloc_bstrndup(evp_pkey_ctx, rsa_inst->oaep->label, label_len));
1072  if (unlikely(EVP_PKEY_CTX_set0_rsa_oaep_label(evp_pkey_ctx, label, label_len) <= 0)) {
1073  fr_tls_strerror_printf(NULL);
1074  PERROR("%s: Failed setting OAEP padding label", __FUNCTION__);
1075  OPENSSL_free(label);
1076  return -1;
1077  }
1078  }
1079  return 0;
1080 
1081  default:
1082  fr_assert(0);
1083  return -1;
1084  }
1085 }
1086 
1087 /** Pre-initialises the EVP_PKEY_CTX necessary for performing RSA encryption/decryption/sign/verify
1088  *
1089  * If reference counting is used for EVP_PKEY structs, should also prevent any mutex contention
1090  * associated with incrementing/decrementing those references.
1091  *
1092  * xlat functions MUST NOT interleave PKEY operations with yields
1093  *
1094  * @return 0.
1095  */
1097 {
1098  rlm_cipher_t const *inst = talloc_get_type_abort(mctx->inst->data, rlm_cipher_t);
1099  rlm_cipher_rsa_thread_inst_t *ti = talloc_get_type_abort(mctx->thread, rlm_cipher_rsa_thread_inst_t);
1100 
1101  /*
1102  * Pre-allocate different contexts for the different operations
1103  * The OpenSSL docs say this is fine, and it reduces the potential
1104  * for SEGVs and other random errors due to trying to change the
1105  * configuration of a context multiple times.
1106  */
1107  if (inst->rsa->certificate_file) {
1108  /*
1109  * Alloc encrypt
1110  */
1111  ti->evp_encrypt_ctx = EVP_PKEY_CTX_new(inst->rsa->certificate_file, NULL);
1112  if (!ti->evp_encrypt_ctx) {
1113  fr_tls_strerror_printf(NULL);
1114  PERROR("%s: Failed allocating encrypt EVP_PKEY_CTX", __FUNCTION__);
1115  return -1;
1116  }
1117  talloc_set_type(ti->evp_encrypt_ctx, EVP_PKEY_CTX);
1118  ti->evp_encrypt_ctx = talloc_steal(ti, ti->evp_encrypt_ctx); /* Bind lifetime to instance */
1119  talloc_set_destructor(ti->evp_encrypt_ctx, _evp_pkey_ctx_free); /* Free ctx correctly on chunk free */
1120 
1121  /*
1122  * Configure encrypt
1123  */
1124  if (unlikely(EVP_PKEY_encrypt_init(ti->evp_encrypt_ctx) <= 0)) {
1125  fr_tls_strerror_printf(NULL);
1126  PERROR("%s: Failed initialising encrypt EVP_PKEY_CTX", __FUNCTION__);
1127  return XLAT_ACTION_FAIL;
1128  }
1130  ERROR("%s: Failed setting padding for encrypt EVP_PKEY_CTX", __FUNCTION__);
1131  return -1;
1132  }
1133 
1134  /*
1135  * Alloc verify
1136  */
1137  ti->evp_verify_ctx = EVP_PKEY_CTX_new(inst->rsa->certificate_file, NULL);
1138  if (!ti->evp_verify_ctx) {
1139  fr_tls_strerror_printf(NULL);
1140  PERROR("%s: Failed allocating verify EVP_PKEY_CTX", __FUNCTION__);
1141  return -1;
1142  }
1143  talloc_set_type(ti->evp_verify_ctx, EVP_PKEY_CTX);
1144  ti->evp_verify_ctx = talloc_steal(ti, ti->evp_verify_ctx); /* Bind lifetime to instance */
1145  talloc_set_destructor(ti->evp_verify_ctx, _evp_pkey_ctx_free); /* Free ctx correctly on chunk free */
1146 
1147  /*
1148  * Configure verify
1149  */
1150  if (unlikely(EVP_PKEY_verify_init(ti->evp_verify_ctx) <= 0)) {
1151  fr_tls_strerror_printf(NULL);
1152  PERROR("%s: Failed initialising verify EVP_PKEY_CTX", __FUNCTION__);
1153  return XLAT_ACTION_FAIL;
1154  }
1155 
1156  /*
1157  * OAEP not valid for signing or verification
1158  */
1159  if (inst->rsa->padding != RSA_PKCS1_OAEP_PADDING) {
1161  ERROR("%s: Failed setting padding for verify EVP_PKEY_CTX", __FUNCTION__);
1162  return -1;
1163  }
1164  }
1165 
1166  if (unlikely(EVP_PKEY_CTX_set_signature_md(ti->evp_verify_ctx, inst->rsa->sig_digest)) <= 0) {
1167  fr_tls_strerror_printf(NULL);
1168  PERROR("%s: Failed setting signature digest type", __FUNCTION__);
1169  return XLAT_ACTION_FAIL;
1170  }
1171  }
1172 
1173  if (inst->rsa->private_key_file) {
1174  /*
1175  * Alloc decrypt
1176  */
1177  ti->evp_decrypt_ctx = EVP_PKEY_CTX_new(inst->rsa->private_key_file, NULL);
1178  if (!ti->evp_decrypt_ctx) {
1179  fr_tls_strerror_printf(NULL);
1180  PERROR("%s: Failed allocating decrypt EVP_PKEY_CTX", __FUNCTION__);
1181  return -1;
1182  }
1183  talloc_set_type(ti->evp_decrypt_ctx, EVP_PKEY_CTX);
1184  ti->evp_decrypt_ctx = talloc_steal(ti, ti->evp_decrypt_ctx); /* Bind lifetime to instance */
1185  talloc_set_destructor(ti->evp_decrypt_ctx, _evp_pkey_ctx_free); /* Free ctx correctly on chunk free */
1186 
1187  /*
1188  * Configure decrypt
1189  */
1190  if (unlikely(EVP_PKEY_decrypt_init(ti->evp_decrypt_ctx) <= 0)) {
1191  fr_tls_strerror_printf(NULL);
1192  PERROR("%s: Failed initialising decrypt EVP_PKEY_CTX", __FUNCTION__);
1193  return XLAT_ACTION_FAIL;
1194  }
1196  ERROR("%s: Failed setting padding for decrypt EVP_PKEY_CTX", __FUNCTION__);
1197  return -1;
1198  }
1199 
1200  /*
1201  * Alloc sign
1202  */
1203  ti->evp_sign_ctx = EVP_PKEY_CTX_new(inst->rsa->private_key_file, NULL);
1204  if (!ti->evp_sign_ctx) {
1205  fr_tls_strerror_printf(NULL);
1206  PERROR("%s: Failed allocating sign EVP_PKEY_CTX", __FUNCTION__);
1207  return -1;
1208  }
1209  talloc_set_type(ti->evp_sign_ctx, EVP_PKEY_CTX);
1210  ti->evp_sign_ctx = talloc_steal(ti, ti->evp_sign_ctx); /* Bind lifetime to instance */
1211  talloc_set_destructor(ti->evp_sign_ctx, _evp_pkey_ctx_free); /* Free ctx correctly on chunk free */
1212 
1213  /*
1214  * Configure sign
1215  */
1216  if (unlikely(EVP_PKEY_sign_init(ti->evp_sign_ctx) <= 0)) {
1217  fr_tls_strerror_printf(NULL);
1218  PERROR("%s: Failed initialising sign EVP_PKEY_CTX", __FUNCTION__);
1219  return XLAT_ACTION_FAIL;
1220  }
1221 
1222  /*
1223  * OAEP not valid for signing or verification
1224  */
1225  if (inst->rsa->padding != RSA_PKCS1_OAEP_PADDING) {
1227  ERROR("%s: Failed setting padding for sign EVP_PKEY_CTX", __FUNCTION__);
1228  return -1;
1229  }
1230  }
1231 
1232  if (unlikely(EVP_PKEY_CTX_set_signature_md(ti->evp_sign_ctx, inst->rsa->sig_digest)) <= 0) {
1233  fr_tls_strerror_printf(NULL);
1234  PERROR("%s: Failed setting signature digest type", __FUNCTION__);
1235  return XLAT_ACTION_FAIL;
1236  }
1237 
1238  /*
1239  * Alloc digest ctx for signing and verification
1240  */
1241  ti->evp_md_ctx = EVP_MD_CTX_create();
1242  if (!ti->evp_md_ctx) {
1243  fr_tls_strerror_printf(NULL);
1244  PERROR("%s: Failed allocating EVP_MD_CTX", __FUNCTION__);
1245  return -1;
1246  }
1247  talloc_set_type(ti->evp_md_ctx, EVP_MD_CTX);
1248  ti->evp_md_ctx = talloc_steal(ti, ti->evp_md_ctx); /* Bind lifetime to instance */
1249  talloc_set_destructor(ti->evp_md_ctx, _evp_md_ctx_free); /* Free ctx correctly on chunk free */
1250  MEM(ti->digest_buff = talloc_array(ti, uint8_t, EVP_MD_size(inst->rsa->sig_digest)));
1251  }
1252 
1253  return 0;
1254 }
1255 
1257 {
1258  rlm_cipher_t *inst = talloc_get_type_abort(mctx->inst->data, rlm_cipher_t);
1259 
1260  switch (inst->type) {
1261  case RLM_CIPHER_TYPE_RSA:
1262  talloc_set_type(mctx->thread, rlm_cipher_rsa_thread_inst_t);
1263  return cipher_rsa_thread_instantiate(mctx);
1264 
1266  fr_assert(0);
1267  }
1268 
1269  return 0;
1270 }
1271 
1272 /*
1273  * Do any per-module initialization that is separate to each
1274  * configured instance of the module. e.g. set up connections
1275  * to external databases, read configuration files, set up
1276  * dictionary entries, etc.
1277  */
1278 static int mod_bootstrap(module_inst_ctx_t const *mctx)
1279 {
1280  rlm_cipher_t *inst = talloc_get_type_abort(mctx->inst->data, rlm_cipher_t);
1281  CONF_SECTION *conf = mctx->inst->conf;
1282 
1283  switch (inst->type) {
1284  case RLM_CIPHER_TYPE_RSA:
1285  if (!inst->rsa) {
1286  cf_log_err(conf, "type = rsa, but no 'rsa { ... }' configuration section provided");
1287  return -1;
1288  }
1289 
1290  if (!inst->rsa->private_key_file && !inst->rsa->certificate_file) {
1291  cf_log_err(conf, "type = rsa, but neither "
1292  "'private_key_file' nor 'certificate_file' configured");
1293  return -1;
1294  }
1295 
1296  if (inst->rsa->private_key_file) {
1297  xlat_t *xlat;
1298 
1299  /*
1300  * Register decrypt xlat
1301  */
1304 
1305  /*
1306  * Verify sign xlat
1307  */
1310  }
1311 
1312  if (inst->rsa->certificate_file) {
1313  xlat_t *xlat;
1314 
1315  /*
1316  * If we have both public and private keys check they're
1317  * part of the same keypair. This isn't technically a requirement
1318  * but it fixes some obscure errors where the user uses the serial
1319  * xlat, expecting it to be the serial of the keypair containing
1320  * the private key.
1321  */
1322  if (inst->rsa->private_key_file && inst->rsa->x509_certificate_file) {
1323  if (X509_check_private_key(inst->rsa->x509_certificate_file,
1324  inst->rsa->private_key_file) == 0) {
1325  fr_tls_strerror_printf(NULL);
1326  cf_log_perr(conf, "Private key does not match the certificate public key");
1327  return -1;
1328  }
1329  }
1330 
1331  /*
1332  * Register encrypt xlat
1333  */
1336 
1337  /*
1338  * Register sign xlat
1339  */
1342 
1343  /*
1344  * FIXME: These should probably be split into separate xlats
1345  * so we can optimise for return types.
1346  */
1347  xlat = xlat_func_register_module(inst, mctx, "certificate", cipher_certificate_xlat, FR_TYPE_VOID);
1349  }
1350  break;
1351 
1352  /*
1353  * Populated by cipher_type_parse() so if
1354  * the value is unrecognised we've got an issue.
1355  */
1356  default:
1357  fr_assert(0);
1358  return -1;
1359  }
1360 
1361  return 0;
1362 }
1363 
1364 /*
1365  * The module name should be the only globally exported symbol.
1366  * That is, everything else should be 'static'.
1367  *
1368  * If the module needs to temporarily modify it's instantiation
1369  * data, the type should be changed to MODULE_TYPE_THREAD_UNSAFE.
1370  * The server will then take care of ensuring that the module
1371  * is single-threaded.
1372  */
1373 extern module_rlm_t rlm_cipher;
1375  .common = {
1376  .magic = MODULE_MAGIC_INIT,
1377  .name = "cipher",
1378  .flags = MODULE_TYPE_THREAD_SAFE,
1379  .inst_size = sizeof(rlm_cipher_t),
1380  .thread_inst_size = sizeof(rlm_cipher_rsa_thread_inst_t),
1381  .config = module_config,
1382  .bootstrap = mod_bootstrap,
1383  .thread_instantiate = mod_thread_instantiate
1384  }
1385 };
log_entry msg
Definition: acutest.h:794
va_list args
Definition: acutest.h:770
#define UNCONST(_type, _ptr)
Remove const qualification from a pointer.
Definition: build.h:165
#define RCSID(id)
Definition: build.h:444
#define L(_str)
Helper for initialising arrays of string literals.
Definition: build.h:207
#define unlikely(_x)
Definition: build.h:378
#define UNUSED
Definition: build.h:313
#define NUM_ELEMENTS(_t)
Definition: build.h:335
int cf_table_parse_int(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, conf_parser_t const *rule)
Generic function for parsing conf pair values as int.
Definition: cf_parse.c:1474
#define CONF_PARSER_TERMINATOR
Definition: cf_parse.h:626
#define FR_CONF_OFFSET(_name, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition: cf_parse.h:268
#define FR_CONF_OFFSET_FLAGS(_name, _flags, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition: cf_parse.h:256
#define FR_CONF_OFFSET_SUBSECTION(_name, _flags, _struct, _field, _subcs)
conf_parser_t which populates a sub-struct using a CONF_SECTION
Definition: cf_parse.h:297
@ CONF_FLAG_SECRET
Only print value if debug level >= 3.
Definition: cf_parse.h:410
@ CONF_FLAG_NOT_EMPTY
CONF_PAIR is required to have a non zero length value.
Definition: cf_parse.h:421
#define FR_CONF_OFFSET_TYPE_FLAGS(_name, _type, _flags, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition: cf_parse.h:241
Defines a CONF_PAIR to C data type mapping.
Definition: cf_parse.h:563
Common header for all CONF_* types.
Definition: cf_priv.h:49
A section grouping multiple CONF_PAIR.
Definition: cf_priv.h:89
CONF_PAIR * cf_item_to_pair(CONF_ITEM const *ci)
Cast a CONF_ITEM to a CONF_PAIR.
Definition: cf_util.c:629
char const * cf_pair_value(CONF_PAIR const *pair)
Return the value of a CONF_PAIR.
Definition: cf_util.c:1511
#define cf_log_err(_cf, _fmt,...)
Definition: cf_util.h:265
#define cf_log_perr(_cf, _fmt,...)
Definition: cf_util.h:272
#define cf_log_pwarn(_cf, _fmt,...)
Definition: cf_util.h:273
#define cf_log_debug(_cf, _fmt,...)
Definition: cf_util.h:268
static int fr_dcursor_append(fr_dcursor_t *cursor, void *v)
Insert a single item at the end of the list.
Definition: dcursor.h:405
#define ERROR(fmt,...)
Definition: dhcpclient.c:41
static fr_slen_t in
Definition: dict.h:645
void *_CONST data
Module instance's parsed configuration.
Definition: dl_module.h:165
#define MODULE_MAGIC_INIT
Stop people using different module/library/server versions together.
Definition: dl_module.h:65
CONF_SECTION *_CONST conf
Module's instance configuration.
Definition: dl_module.h:166
static xlat_action_t cipher_rsa_decrypt_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *in)
Decrypt input data.
Definition: rlm_cipher.c:723
static xlat_action_t cipher_rsa_encrypt_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *in)
Encrypt input data.
Definition: rlm_cipher.c:584
static xlat_action_t cipher_rsa_sign_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *in)
Sign input data.
Definition: rlm_cipher.c:645
static xlat_action_t cipher_serial_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, UNUSED fr_value_box_list_t *in)
Return the serial of the public certificate.
Definition: rlm_cipher.c:946
static xlat_action_t cipher_rsa_verify_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *in)
Verify input data.
Definition: rlm_cipher.c:785
static xlat_action_t cipher_fingerprint_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *in)
Return the fingerprint of the public certificate.
Definition: rlm_cipher.c:897
#define PERROR(_fmt,...)
Definition: log.h:228
#define RHEXDUMP3(_data, _len, _fmt,...)
Definition: log.h:705
talloc_free(reap)
@ FR_TYPE_STRING
String of printable characters.
Definition: merged_model.c:83
@ FR_TYPE_DATE
Unix time stamp, always has value >2^31.
Definition: merged_model.c:111
@ FR_TYPE_VOID
User data.
Definition: merged_model.c:127
@ FR_TYPE_BOOL
A truth value.
Definition: merged_model.c:95
@ FR_TYPE_OCTETS
Raw octets.
Definition: merged_model.c:84
unsigned char uint8_t
Definition: merged_model.c:30
void * thread
Thread specific instance data.
Definition: module_ctx.h:43
dl_module_inst_t const * inst
Dynamic loader API handle for the module.
Definition: module_ctx.h:52
void * thread
Thread instance data.
Definition: module_ctx.h:62
dl_module_inst_t const * inst
Dynamic loader API handle for the module.
Definition: module_ctx.h:42
dl_module_inst_t const * inst
Dynamic loader API handle for the module.
Definition: module_ctx.h:59
Temporary structure to hold arguments for instantiation calls.
Definition: module_ctx.h:51
Temporary structure to hold arguments for thread_instantiation calls.
Definition: module_ctx.h:58
module_t common
Common fields presented by all modules.
Definition: module_rlm.h:37
#define REDEBUG(fmt,...)
Definition: radclient.h:52
static rs_t * conf
Definition: radsniff.c:53
EVP_PKEY_CTX * evp_verify_ctx
Pre-allocated evp_pkey_ctx.
Definition: rlm_cipher.c:136
static size_t cipher_rsa_padding_len
Definition: rlm_cipher.c:107
static int cipher_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
Checks if the specified cipher type is valid.
Definition: rlm_cipher.c:311
static const conf_parser_t rsa_oaep_config[]
Configuration for the RSA-PCKS1-OAEP padding scheme.
Definition: rlm_cipher.c:196
static int cipher_rsa_private_key_file_load(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
cipher_rsa_oaep_t * oaep
OAEP can use a configurable message digest type.
Definition: rlm_cipher.c:176
X509 * x509_certificate_file
Needed for extracting certificate attributes.
Definition: rlm_cipher.c:164
cipher_cert_verify_mode_t verify_mode
How hard we try to verify the certificate.
Definition: rlm_cipher.c:166
static xlat_arg_parser_t const cipher_rsa_verify_xlat_arg[]
Definition: rlm_cipher.c:765
static fr_table_num_sorted_t const cipher_rsa_padding[]
The type of padding used.
Definition: rlm_cipher.c:98
static fr_table_num_sorted_t const cert_attributes[]
Public key types.
Definition: rlm_cipher.c:124
cipher_cert_verify_mode_t
Certificate validation modes.
Definition: rlm_cipher.c:67
@ CIPHER_CERT_VERIFY_HARD
Fail if the certificate isn't valid.
Definition: rlm_cipher.c:70
@ CIPHER_CERT_VERIFY_SOFT
Warn if the certificate isn't valid.
Definition: rlm_cipher.c:71
@ CIPHER_CERT_VERIFY_NONE
Don't check to see if the we're between notBefore or notAfter.
Definition: rlm_cipher.c:72
@ CIPHER_CERT_VERIFY_INVALID
Definition: rlm_cipher.c:68
static const conf_parser_t rsa_config[]
Configuration for the RSA cipher type.
Definition: rlm_cipher.c:207
static int cipher_rsa_padding_params_set(EVP_PKEY_CTX *evp_pkey_ctx, cipher_rsa_t const *rsa_inst)
Definition: rlm_cipher.c:1027
cipher_type_t type
Type of encryption to use.
Definition: rlm_cipher.c:183
static size_t cipher_cert_verify_mode_table_len
Definition: rlm_cipher.c:119
cipher_cert_attributes_t
Definition: rlm_cipher.c:76
@ CIPHER_CERT_ATTR_NOT_AFTER
Time the certificate expires.
Definition: rlm_cipher.c:81
@ CIPHER_CERT_ATTR_SERIAL
Certificate's serial number.
Definition: rlm_cipher.c:78
@ CIPHER_CERT_ATTR_UNKNOWN
Unrecognised attribute.
Definition: rlm_cipher.c:77
@ CIPHER_CERT_ATTR_FINGERPRINT
Dynamically calculated fingerprint.
Definition: rlm_cipher.c:79
@ CIPHER_CERT_ATTR_NOT_BEFORE
Time the certificate becomes valid.
Definition: rlm_cipher.c:80
char const * label
Additional input to the hashing function.
Definition: rlm_cipher.c:149
EVP_MD_CTX * evp_md_ctx
Pre-allocated evp_md_ctx for sign and verify.
Definition: rlm_cipher.c:138
static int _get_private_key_password(char *buf, int size, UNUSED int rwflag, void *u)
Return the static private key password we have configured.
Definition: rlm_cipher.c:344
int padding
Type of padding to apply to the plaintext or ciphertext before feeding it to RSA crypto functions.
Definition: rlm_cipher.c:170
static int mod_bootstrap(module_inst_ctx_t const *mctx)
Definition: rlm_cipher.c:1278
static int digest_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
Calls EVP_get_digestbyname() to convert the digest type.
Definition: rlm_cipher.c:253
uint8_t * digest_buff
Pre-allocated digest buffer.
Definition: rlm_cipher.c:139
EVP_MD * mgf1_digest
Masking function digest.
Definition: rlm_cipher.c:147
static xlat_arg_parser_t const cipher_rsa_decrypt_xlat_arg[]
Definition: rlm_cipher.c:706
static fr_table_num_sorted_t const cipher_cert_verify_mode_table[]
Definition: rlm_cipher.c:114
cipher_type_t
Definition: rlm_cipher.c:59
@ RLM_CIPHER_TYPE_RSA
Definition: rlm_cipher.c:61
@ RLM_CIPHER_TYPE_INVALID
Definition: rlm_cipher.c:60
static xlat_arg_parser_t const cipher_rsa_sign_xlat_arg[]
Definition: rlm_cipher.c:628
static int _evp_pkey_free(EVP_PKEY *pkey)
Talloc destructor for freeing an EVP_PKEY (representing a certificate)
Definition: rlm_cipher.c:370
fr_unix_time_t not_before
Certificate isn't valid before this time.
Definition: rlm_cipher.c:167
static xlat_arg_parser_t const cipher_rsa_encrypt_xlat_arg[]
Definition: rlm_cipher.c:567
fr_unix_time_t not_after
Certificate isn't valid after this time.
Definition: rlm_cipher.c:168
char const * private_key_password
Password to decrypt the private key.
Definition: rlm_cipher.c:158
static int cipher_rsa_thread_instantiate(module_thread_inst_ctx_t const *mctx)
Pre-initialises the EVP_PKEY_CTX necessary for performing RSA encryption/decryption/sign/verify.
Definition: rlm_cipher.c:1096
static int mod_thread_instantiate(module_thread_inst_ctx_t const *mctx)
Definition: rlm_cipher.c:1256
EVP_PKEY * certificate_file
Public (certificate) file.
Definition: rlm_cipher.c:163
EVP_PKEY * private_key_file
Private key file.
Definition: rlm_cipher.c:162
static size_t cipher_type_len
Definition: rlm_cipher.c:112
static int cipher_rsa_padding_type_parse(UNUSED TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
Checks if the specified padding type is valid.
Definition: rlm_cipher.c:282
static int _x509_cert_free(X509 *cert)
Talloc destructor for freeing an X509 struct (representing a public certificate)
Definition: rlm_cipher.c:382
static int _evp_md_ctx_free(EVP_MD_CTX *evp_md_ctx)
Talloc destructor for freeing an EVP_MD_CTX.
Definition: rlm_cipher.c:1020
module_rlm_t rlm_cipher
Definition: rlm_cipher.c:1374
static xlat_arg_parser_t const cipher_certificate_xlat_args[]
Definition: rlm_cipher.c:881
static fr_table_num_sorted_t const cipher_type[]
Definition: rlm_cipher.c:109
EVP_PKEY_CTX * evp_decrypt_ctx
Pre-allocated evp_pkey_ctx.
Definition: rlm_cipher.c:135
EVP_PKEY_CTX * evp_encrypt_ctx
Pre-allocated evp_pkey_ctx.
Definition: rlm_cipher.c:133
static const conf_parser_t module_config[]
Definition: rlm_cipher.c:235
static int cipher_rsa_certificate_file_load(TALLOC_CTX *ctx, void *out, UNUSED void *parent, CONF_ITEM *ci, UNUSED conf_parser_t const *rule)
static xlat_action_t cipher_certificate_xlat(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *in)
Definition: rlm_cipher.c:968
static size_t cert_attributes_len
Definition: rlm_cipher.c:130
EVP_PKEY_CTX * evp_sign_ctx
Pre-allocated evp_pkey_ctx.
Definition: rlm_cipher.c:134
static int _evp_pkey_ctx_free(EVP_PKEY_CTX *evp_pkey_ctx)
Talloc destructor for freeing an EVP_PKEY_CTX.
Definition: rlm_cipher.c:1008
static size_t pkey_types_len
Definition: rlm_cipher.c:93
EVP_MD * sig_digest
Signature digest type.
Definition: rlm_cipher.c:174
char const * random_file
If set, we read 10K of data (or the complete file) and use it to seed OpenSSL's PRNG.
Definition: rlm_cipher.c:159
static fr_table_num_sorted_t const pkey_types[]
Public key types.
Definition: rlm_cipher.c:87
EVP_MD * oaep_digest
Padding digest type.
Definition: rlm_cipher.c:146
Configuration for the OAEP padding method.
Definition: rlm_cipher.c:145
Configuration for RSA encryption/decryption/signing.
Definition: rlm_cipher.c:157
Instance configuration.
Definition: rlm_cipher.c:182
@ MODULE_TYPE_THREAD_SAFE
Module is threadsafe.
Definition: module.h:49
fr_assert(0)
MEM(pair_append_request(&vp, attr_eap_aka_sim_identity) >=0)
eap_aka_sim_process_conf_t * inst
fr_aka_sim_id_type_t type
eap_type_t type
The preferred EAP-Type of this instance of the EAP-SIM/AKA/AKA' state machine.
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition: syserror.c:243
#define fr_table_value_by_str(_table, _name, _def)
Convert a string to a value using a sorted or ordered table.
Definition: table.h:134
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition: table.h:253
An element in a lexicographically sorted array of name to num mappings.
Definition: table.h:45
char * talloc_bstrndup(TALLOC_CTX *ctx, char const *in, size_t inlen)
Binary safe strndup function.
Definition: talloc.c:452
#define talloc_get_type_abort_const
Definition: talloc.h:270
"Unix" time.
Definition: time.h:95
bool required
Argument must be present, and non-empty.
Definition: xlat.h:146
@ XLAT_ARG_VARIADIC_EMPTY_SQUASH
Empty argument groups are removed.
Definition: xlat.h:136
#define XLAT_ARG_PARSER_TERMINATOR
Definition: xlat.h:166
xlat_action_t
Definition: xlat.h:35
@ XLAT_ACTION_FAIL
An xlat function failed.
Definition: xlat.h:42
@ XLAT_ACTION_DONE
We're done evaluating this level of nesting.
Definition: xlat.h:41
Definition for a single argument consumend by an xlat function.
Definition: xlat.h:145
static fr_slen_t parent
Definition: pair.h:844
static char const * fr_type_to_str(fr_type_t type)
Return a static string containing the type name.
Definition: types.h:433
int fr_value_box_mem_alloc(TALLOC_CTX *ctx, uint8_t **out, fr_value_box_t *dst, fr_dict_attr_t const *enumv, size_t len, bool tainted)
Pre-allocate an octets buffer for filling by the caller.
Definition: value.c:4320
int fr_value_box_mem_realloc(TALLOC_CTX *ctx, uint8_t **out, fr_value_box_t *dst, size_t len)
Change the length of a buffer already allocated to a value box.
Definition: value.c:4353
int fr_value_box_bstr_alloc(TALLOC_CTX *ctx, char **out, fr_value_box_t *dst, fr_dict_attr_t const *enumv, size_t len, bool tainted)
Alloc and assign an empty \0 terminated string to a fr_value_box_t.
Definition: value.c:4020
int fr_value_box_bstr_realloc(TALLOC_CTX *ctx, char **out, fr_value_box_t *dst, size_t len)
Change the length of a buffer already allocated to a value box.
Definition: value.c:4053
int fr_value_box_memdup(TALLOC_CTX *ctx, fr_value_box_t *dst, fr_dict_attr_t const *enumv, uint8_t const *src, size_t len, bool tainted)
Copy a buffer to a fr_value_box_t.
Definition: value.c:4417
int fr_value_box_list_concat_in_place(TALLOC_CTX *ctx, fr_value_box_t *out, fr_value_box_list_t *list, fr_type_t type, fr_value_box_list_action_t proc_action, bool flatten, size_t max_size)
Concatenate a list of value boxes.
Definition: value.c:5725
@ FR_VALUE_BOX_LIST_FREE
Definition: value.h:214
#define fr_value_box_alloc(_ctx, _type, _enumv)
Allocate a value box of a specific type.
Definition: value.h:608
#define fr_value_box_alloc_null(_ctx)
Allocate a value box for later use with a value assignment function.
Definition: value.h:619
static size_t char ** out
Definition: value.h:984
#define fr_box_date(_val)
Definition: value.h:317
module_ctx_t const * mctx
Synthesised module calling ctx.
Definition: xlat_ctx.h:45
An xlat calling ctx.
Definition: xlat_ctx.h:42
int xlat_func_args_set(xlat_t *x, xlat_arg_parser_t const args[])
Register the arguments of an xlat.
Definition: xlat_func.c:360
int xlat_func_mono_set(xlat_t *x, xlat_arg_parser_t const args[])
Register the argument of an xlat.
Definition: xlat_func.c:392
xlat_t * xlat_func_register_module(TALLOC_CTX *ctx, module_inst_ctx_t const *mctx, char const *name, xlat_func_t func, fr_type_t return_type)
Register an xlat function for a module.
Definition: xlat_func.c:274