OpenVPN
pkcs11_openssl.c
Go to the documentation of this file.
1 /*
2  * OpenVPN -- An application to securely tunnel IP networks
3  * over a single TCP/UDP port, with support for SSL/TLS-based
4  * session authentication and key exchange,
5  * packet encryption, packet authentication, and
6  * packet compression.
7  *
8  * Copyright (C) 2002-2024 OpenVPN Inc <sales@openvpn.net>
9  * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2
13  * as published by the Free Software Foundation.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24 
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32 
33 #include "syshead.h"
34 
35 #if defined(ENABLE_PKCS11) && defined(ENABLE_CRYPTO_OPENSSL)
36 
37 #include "errlevel.h"
38 #include "pkcs11_backend.h"
39 #include "ssl_verify.h"
40 #include "xkey_common.h"
41 #include <pkcs11-helper-1.0/pkcs11h-openssl.h>
42 
43 #ifdef HAVE_XKEY_PROVIDER
44 static XKEY_EXTERNAL_SIGN_fn xkey_pkcs11h_sign;
45 
46 #if PKCS11H_VERSION > ((1<<16) | (27<<8)) /* version > 1.27 */
47 
48 /* Table linking OpenSSL digest NID with CKM and CKG constants in PKCS#11 */
49 #define MD_TYPE(n) {NID_sha ## n, CKM_SHA ## n, CKG_MGF1_SHA ## n}
50 static const struct
51 {
52  int nid;
53  unsigned long ckm_id;
54  unsigned long mgf_id;
55 } mdtypes[] = {MD_TYPE(224), MD_TYPE(256), MD_TYPE(384), MD_TYPE(512),
56  {NID_sha1, CKM_SHA_1, CKG_MGF1_SHA1}, /* SHA_1 naming is an oddity */
57  {NID_undef, 0, 0}};
58 
59 /* From sigalg, derive parameters for pss signature and fill in pss_params.
60  * Its of type CK_RSA_PKCS_PSS_PARAMS struct with three fields to be filled in:
61  * {enum hashAlg, enum mgf, ulong sLen}
62  * where hashAlg is CKM_SHA256 etc., mgf is CKG_MGF1_SHA256 etc.
63  */
64 static int
65 set_pss_params(CK_RSA_PKCS_PSS_PARAMS *pss_params, XKEY_SIGALG sigalg,
66  pkcs11h_certificate_t cert)
67 {
68  int ret = 0;
69  X509 *x509 = NULL;
70  EVP_PKEY *pubkey = NULL;
71 
72  if ((x509 = pkcs11h_openssl_getX509(cert)) == NULL
73  || (pubkey = X509_get0_pubkey(x509)) == NULL)
74  {
75  msg(M_WARN, "PKCS#11: Unable get public key");
76  goto cleanup;
77  }
78 
79  /* map mdname to CKM and CKG constants for hash and mgf algorithms */
80  int i = 0;
81  int nid = OBJ_sn2nid(sigalg.mdname);
82  while (mdtypes[i].nid != NID_undef && mdtypes[i].nid != nid)
83  {
84  i++;
85  }
86  pss_params->hashAlg = mdtypes[i].ckm_id;
87  pss_params->mgf = mdtypes[i].mgf_id;
88 
89  /* determine salt length */
90  const EVP_MD *md = EVP_get_digestbyname(sigalg.mdname);
91  if (!md)
92  {
93  msg(M_WARN, "WARN: set_pss_params: EVP_get_digestbyname returned NULL "
94  "for mdname = <%s>", sigalg.mdname);
95  goto cleanup;
96  }
97  int mdsize = EVP_MD_get_size(md);
98 
99  int saltlen = -1;
100  if (!strcmp(sigalg.saltlen, "digest")) /* same as digest size */
101  {
102  saltlen = mdsize;
103  }
104  else if (!strcmp(sigalg.saltlen, "max")) /* maximum possible value */
105  {
106  saltlen = xkey_max_saltlen(EVP_PKEY_get_bits(pubkey), mdsize);
107  }
108 
109  if (saltlen < 0 || pss_params->hashAlg == 0)
110  {
111  msg(M_WARN, "WARN: invalid RSA_PKCS1_PSS parameters: saltlen = <%s> "
112  "mdname = <%s>.", sigalg.saltlen, sigalg.mdname);
113  goto cleanup;
114  }
115  pss_params->sLen = (unsigned long) saltlen; /* saltlen >= 0 at this point */
116 
117  msg(D_XKEY, "set_pss_params: sLen = %lu, hashAlg = %lu, mgf = %lu",
118  pss_params->sLen, pss_params->hashAlg, pss_params->mgf);
119 
120  ret = 1;
121 
122 cleanup:
123  if (x509)
124  {
125  X509_free(x509);
126  }
127  return ret;
128 }
129 
130 #else /* if PKCS11H_VERSION > ((1<<16) | (27<<8)) */
131 
132 /* Make set_pss_params a no-op that always succeeds */
133 #define set_pss_params(...) (1)
134 
135 /* Use a wrapper for pkcs11h_certificate_signAny_ex() for versions < 1.28
136  * where its not available.
137  * We just call pkcs11h_certificate_signAny() unless the padding
138  * is PSS in which case we return an error.
139  */
140 static CK_RV
141 pkcs11h_certificate_signAny_ex(const pkcs11h_certificate_t cert,
142  const CK_MECHANISM *mech, const unsigned char *tbs,
143  size_t tbslen, unsigned char *sig, size_t *siglen)
144 {
145  if (mech->mechanism == CKM_RSA_PKCS_PSS)
146  {
147  msg(M_NONFATAL, "PKCS#11: Error: PSS padding is not supported by "
148  "this version of pkcs11-helper library.");
149  return CKR_MECHANISM_INVALID;
150  }
151  return pkcs11h_certificate_signAny(cert, mech->mechanism, tbs, tbslen, sig, siglen);
152 }
153 #endif /* PKCS11H_VERSION > 1.27 */
154 
160 static int
161 xkey_pkcs11h_sign(void *handle, unsigned char *sig,
162  size_t *siglen, const unsigned char *tbs, size_t tbslen, XKEY_SIGALG sigalg)
163 {
164  pkcs11h_certificate_t cert = handle;
165  CK_MECHANISM mech = {CKM_RSA_PKCS, NULL, 0}; /* default value */
166  CK_RSA_PKCS_PSS_PARAMS pss_params = {0};
167 
168  unsigned char buf[EVP_MAX_MD_SIZE];
169  size_t buflen = 0;
170  size_t siglen_max = *siglen;
171 
172  unsigned char enc[EVP_MAX_MD_SIZE + 32]; /* 32 bytes enough for DigestInfo header */
173  size_t enc_len = sizeof(enc);
174 
175  if (!strcmp(sigalg.op, "DigestSign"))
176  {
177  msg(D_XKEY, "xkey_pkcs11h_sign: computing digest");
178  if (xkey_digest(tbs, tbslen, buf, &buflen, sigalg.mdname))
179  {
180  tbs = buf;
181  tbslen = (size_t) buflen;
182  sigalg.op = "Sign";
183  }
184  else
185  {
186  return 0;
187  }
188  }
189 
190  if (!strcmp(sigalg.keytype, "EC"))
191  {
192  msg(D_XKEY, "xkey_pkcs11h_sign: signing with EC key");
193  mech.mechanism = CKM_ECDSA;
194  }
195  else if (!strcmp(sigalg.keytype, "RSA"))
196  {
197  msg(D_XKEY, "xkey_pkcs11h_sign: signing with RSA key: padmode = %s",
198  sigalg.padmode);
199  if (!strcmp(sigalg.padmode, "none"))
200  {
201  mech.mechanism = CKM_RSA_X_509;
202  }
203  else if (!strcmp(sigalg.padmode, "pss"))
204  {
205  mech.mechanism = CKM_RSA_PKCS_PSS;
206 
207  if (!set_pss_params(&pss_params, sigalg, cert))
208  {
209  return 0;
210  }
211 
212  mech.pParameter = &pss_params;
213  mech.ulParameterLen = sizeof(pss_params);
214  }
215  else if (!strcmp(sigalg.padmode, "pkcs1"))
216  {
217  /* CMA_RSA_PKCS needs pkcs1 encoded digest */
218 
219  if (!encode_pkcs1(enc, &enc_len, sigalg.mdname, tbs, tbslen))
220  {
221  return 0;
222  }
223  tbs = enc;
224  tbslen = enc_len;
225  }
226  else /* should not happen */
227  {
228  msg(M_WARN, "PKCS#11: Unknown padmode <%s>", sigalg.padmode);
229  }
230  }
231  else
232  {
233  ASSERT(0); /* coding error -- we couldnt have created any such key */
234  }
235 
236  if (CKR_OK != pkcs11h_certificate_signAny_ex(cert, &mech,
237  tbs, tbslen, sig, siglen))
238  {
239  return 0;
240  }
241  if (strcmp(sigalg.keytype, "EC"))
242  {
243  return 1;
244  }
245 
246  /* For EC keys, pkcs11 returns signature as r|s: convert to der encoded */
247  int derlen = ecdsa_bin2der(sig, (int) *siglen, siglen_max);
248 
249  if (derlen <= 0)
250  {
251  return 0;
252  }
253  *siglen = derlen;
254 
255  return 1;
256 }
257 
258 /* wrapper for handle free */
259 static void
260 xkey_handle_free(void *handle)
261 {
262  pkcs11h_certificate_freeCertificate(handle);
263 }
264 
265 
276 static int
277 xkey_load_from_pkcs11h(pkcs11h_certificate_t certificate,
278  struct tls_root_ctx *const ctx)
279 {
280  int ret = 0;
281 
282  X509 *x509 = pkcs11h_openssl_getX509(certificate);
283  if (!x509)
284  {
285  msg(M_WARN, "PKCS#11: Unable get x509 certificate object");
286  return 0;
287  }
288 
289  EVP_PKEY *pubkey = X509_get0_pubkey(x509);
290 
291  XKEY_PRIVKEY_FREE_fn *free_op = xkey_handle_free; /* it calls pkcs11h_..._freeCertificate() */
292  XKEY_EXTERNAL_SIGN_fn *sign_op = xkey_pkcs11h_sign;
293 
294  EVP_PKEY *pkey = xkey_load_generic_key(tls_libctx, certificate, pubkey, sign_op, free_op);
295  if (!pkey)
296  {
297  msg(M_WARN, "PKCS#11: Failed to load private key into xkey provider");
298  goto cleanup;
299  }
300  /* provider took ownership of the pkcs11h certificate object -- do not free below */
301  certificate = NULL;
302 
303  if (!SSL_CTX_use_cert_and_key(ctx->ctx, x509, pkey, NULL, 0))
304  {
306  msg(M_FATAL, "PKCS#11: Failed to set cert and private key for OpenSSL");
307  goto cleanup;
308  }
309  ret = 1;
310 
311 cleanup:
312  if (x509)
313  {
314  X509_free(x509);
315  }
316  if (pkey)
317  {
318  EVP_PKEY_free(pkey);
319  }
320  if (certificate)
321  {
322  pkcs11h_certificate_freeCertificate(certificate);
323  }
324  return ret;
325 }
326 #endif /* HAVE_XKEY_PROVIDER */
327 
328 int
329 pkcs11_init_tls_session(pkcs11h_certificate_t certificate,
330  struct tls_root_ctx *const ssl_ctx)
331 {
332 
333 #ifdef HAVE_XKEY_PROVIDER
334  return (xkey_load_from_pkcs11h(certificate, ssl_ctx) == 0); /* inverts the return value */
335 #else
336  int ret = 1;
337 
338  X509 *x509 = NULL;
339  EVP_PKEY *evp = NULL;
340  pkcs11h_openssl_session_t openssl_session = NULL;
341 
342  if ((openssl_session = pkcs11h_openssl_createSession(certificate)) == NULL)
343  {
344  msg(M_WARN, "PKCS#11: Cannot initialize openssl session");
345  goto cleanup;
346  }
347 
348  /*
349  * Will be released by openssl_session
350  */
351  certificate = NULL;
352 
353  if ((evp = pkcs11h_openssl_session_getEVP(openssl_session)) == NULL)
354  {
355  msg(M_WARN, "PKCS#11: Unable get evp object");
356  goto cleanup;
357  }
358 
359  if ((x509 = pkcs11h_openssl_session_getX509(openssl_session)) == NULL)
360  {
361  msg(M_WARN, "PKCS#11: Unable get certificate object");
362  goto cleanup;
363  }
364 
365  if (!SSL_CTX_use_PrivateKey(ssl_ctx->ctx, evp))
366  {
367  msg(M_WARN, "PKCS#11: Cannot set private key for openssl");
368  goto cleanup;
369  }
370 
371  if (!SSL_CTX_use_certificate(ssl_ctx->ctx, x509))
372  {
374  msg(M_FATAL, "PKCS#11: Cannot set certificate for openssl");
375  goto cleanup;
376  }
377  ret = 0;
378 
379 cleanup:
380  /*
381  * Certificate freeing is usually handled by openssl_session.
382  * If something went wrong, creating the session we have to do it manually.
383  */
384  if (certificate != NULL)
385  {
386  pkcs11h_certificate_freeCertificate(certificate);
387  certificate = NULL;
388  }
389 
390  /*
391  * openssl objects have reference
392  * count, so release them
393  */
394  X509_free(x509);
395  x509 = NULL;
396 
397  EVP_PKEY_free(evp);
398  evp = NULL;
399 
400  if (openssl_session != NULL)
401  {
402  pkcs11h_openssl_freeSession(openssl_session);
403  openssl_session = NULL;
404  }
405  return ret;
406 #endif /* ifdef HAVE_XKEY_PROVIDER */
407 }
408 
409 char *
410 pkcs11_certificate_dn(pkcs11h_certificate_t certificate, struct gc_arena *gc)
411 {
412  X509 *x509 = NULL;
413 
414  char *dn = NULL;
415 
416  if ((x509 = pkcs11h_openssl_getX509(certificate)) == NULL)
417  {
418  msg(M_FATAL, "PKCS#11: Cannot get X509");
419  goto cleanup;
420  }
421 
422  dn = x509_get_subject(x509, gc);
423 
424 cleanup:
425  X509_free(x509);
426  x509 = NULL;
427 
428  return dn;
429 }
430 
431 int
432 pkcs11_certificate_serial(pkcs11h_certificate_t certificate, char *serial,
433  size_t serial_len)
434 {
435  X509 *x509 = NULL;
436  BIO *bio = NULL;
437  int ret = 1;
438  int n;
439 
440  if ((x509 = pkcs11h_openssl_getX509(certificate)) == NULL)
441  {
442  msg(M_FATAL, "PKCS#11: Cannot get X509");
443  goto cleanup;
444  }
445 
446  if ((bio = BIO_new(BIO_s_mem())) == NULL)
447  {
448  msg(M_FATAL, "PKCS#11: Cannot create BIO");
449  goto cleanup;
450  }
451 
452  i2a_ASN1_INTEGER(bio, X509_get_serialNumber(x509));
453  n = BIO_read(bio, serial, serial_len-1);
454 
455  if (n<0)
456  {
457  serial[0] = '\x0';
458  }
459  else
460  {
461  serial[n] = 0;
462  }
463 
464  ret = 0;
465 
466 cleanup:
467  X509_free(x509);
468  x509 = NULL;
469 
470  return ret;
471 }
472 #endif /* defined(ENABLE_PKCS11) && defined(ENABLE_OPENSSL) */
M_FATAL
#define M_FATAL
Definition: error.h:89
M_NONFATAL
#define M_NONFATAL
Definition: error.h:90
xkey_common.h
ssl_verify.h
ASSERT
#define ASSERT(x)
Definition: error.h:195
M_WARN
#define M_WARN
Definition: error.h:91
pkcs11_backend.h
errlevel.h
syshead.h
D_XKEY
#define D_XKEY
Definition: errlevel.h:117
gc_arena
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
crypto_print_openssl_errors
void crypto_print_openssl_errors(const unsigned int flags)
Retrieve any occurred OpenSSL errors and print those errors.
Definition: crypto_openssl.c:235
tls_root_ctx
Structure that wraps the TLS context.
Definition: ssl_mbedtls.h:106
x509_get_subject
char * x509_get_subject(openvpn_x509_cert_t *cert, struct gc_arena *gc)
Definition: ssl_verify_openssl.c:367
config.h
tls_root_ctx::ctx
SSL_CTX * ctx
Definition: ssl_openssl.h:40
tls_libctx
OSSL_LIB_CTX * tls_libctx
Definition: ssl_openssl.c:72
msg
#define msg(flags,...)
Definition: error.h:144
cleanup
static int cleanup(void **state)
Definition: test_pkcs11.c:280