OpenVPN
cryptoapi.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2004 Peter 'Luna' Runestig <peter@runestig.com>
3 * Copyright (c) 2018 Selva Nair <selva.nair@gmail.com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without modifi-
7 * cation, are permitted provided that the following conditions are met:
8 *
9 * o Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * o Redistributions in binary form must reproduce the above copyright no-
13 * tice, this list of conditions and the following disclaimer in the do-
14 * cumentation and/or other materials provided with the distribution.
15 *
16 * o The names of the contributors may not be used to endorse or promote
17 * products derived from this software without specific prior written
18 * permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LI-
24 * ABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN-
25 * TIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEV-
27 * ER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABI-
28 * LITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
29 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifdef HAVE_CONFIG_H
33#include "config.h"
34#endif
35
36#include "syshead.h"
37
38#ifdef ENABLE_CRYPTOAPI
39
40#include <openssl/ssl.h>
41#include <openssl/evp.h>
42#include <openssl/err.h>
43#include <windows.h>
44#include <wincrypt.h>
45#include <ncrypt.h>
46#include <stdio.h>
47#include <ctype.h>
48
49#include "buffer.h"
50#include "openssl_compat.h"
51#include "win32.h"
52#include "xkey_common.h"
53#include "crypto_openssl.h"
54
55#ifndef HAVE_XKEY_PROVIDER
56
57int
58SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
59{
60 msg(M_NONFATAL, "ERROR: this binary was built without cryptoapicert support");
61 return 0;
62}
63
64#else /* HAVE_XKEY_PROVIDER */
65
66static XKEY_EXTERNAL_SIGN_fn xkey_cng_sign;
67
68typedef struct _CAPI_DATA
69{
70 const CERT_CONTEXT *cert_context;
71 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov;
72 EVP_PKEY *pubkey;
73 DWORD key_spec;
74 BOOL free_crypt_prov;
75 int ref_count;
76} CAPI_DATA;
77
78/*
79 * Translate OpenSSL hash OID to CNG algorithm name. Returns
80 * "UNKNOWN" for unsupported algorithms and NULL for MD5+SHA1
81 * mixed hash used in TLS 1.1 and earlier.
82 */
83static const wchar_t *
84cng_hash_algo(int md_type)
85{
86 const wchar_t *alg = L"UNKNOWN";
87 switch (md_type)
88 {
89 case NID_md5:
90 alg = BCRYPT_MD5_ALGORITHM;
91 break;
92
93 case NID_sha1:
94 alg = BCRYPT_SHA1_ALGORITHM;
95 break;
96
97 case NID_sha256:
98 alg = BCRYPT_SHA256_ALGORITHM;
99 break;
100
101 case NID_sha384:
102 alg = BCRYPT_SHA384_ALGORITHM;
103 break;
104
105 case NID_sha512:
106 alg = BCRYPT_SHA512_ALGORITHM;
107 break;
108
109 case NID_md5_sha1:
110 case 0:
111 alg = NULL;
112 break;
113
114 default:
115 msg(M_WARN | M_INFO, "cryptoapicert: Unknown hash type NID=0x%x", md_type);
116 break;
117 }
118 return alg;
119}
120
121static void
122CAPI_DATA_free(CAPI_DATA *cd)
123{
124 if (!cd || cd->ref_count-- > 0)
125 {
126 return;
127 }
128 if (cd->free_crypt_prov && cd->crypt_prov)
129 {
130 if (cd->key_spec == CERT_NCRYPT_KEY_SPEC)
131 {
132 NCryptFreeObject(cd->crypt_prov);
133 }
134 else
135 {
136 CryptReleaseContext(cd->crypt_prov, 0);
137 }
138 }
139 if (cd->cert_context)
140 {
141 CertFreeCertificateContext(cd->cert_context);
142 }
143 EVP_PKEY_free(cd->pubkey); /* passing NULL is okay */
144
145 free(cd);
146}
147
156static DWORD
157parse_hexstring(const char *p, unsigned char *arr, DWORD capacity)
158{
159 DWORD i = 0;
160 for (; *p && i < capacity; p += 2)
161 {
162 /* skip spaces */
163 while (*p == ' ')
164 {
165 p++;
166 }
167 if (!*p) /* ending with spaces is not an error */
168 {
169 break;
170 }
171
172 unsigned int b;
173 if (!isxdigit(p[0]) || !isxdigit(p[1]) || sscanf(p, "%2x", &b) != 1)
174 {
175 return 0;
176 }
177 arr[i++] = (unsigned char)b;
178 }
179 return i;
180}
181
182static void *
183decode_object(struct gc_arena *gc, LPCSTR struct_type, const CRYPT_OBJID_BLOB *val, DWORD flags,
184 DWORD *cb)
185{
186 /* get byte count for decoding */
187 BYTE *buf;
188 if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct_type, val->pbData,
189 val->cbData, flags, NULL, cb))
190 {
191 return NULL;
192 }
193
194 /* do the actual decode */
195 buf = gc_malloc(*cb, false, gc);
196 if (!CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, struct_type, val->pbData,
197 val->cbData, flags, buf, cb))
198 {
199 return NULL;
200 }
201
202 return buf;
203}
204
205static const CRYPT_OID_INFO *
206find_oid(DWORD keytype, const void *key, DWORD groupid)
207{
208 const CRYPT_OID_INFO *info = NULL;
209
210 /* try proper resolve, also including AD */
211 info = CryptFindOIDInfo(keytype, (void *)key, groupid);
212
213 /* fall back to all groups if not found yet */
214 if (!info && groupid)
215 {
216 info = CryptFindOIDInfo(keytype, (void *)key, 0);
217 }
218
219 return info;
220}
221
222static bool
223test_certificate_template(const char *cert_prop, const CERT_CONTEXT *cert_ctx)
224{
225 const CERT_INFO *info = cert_ctx->pCertInfo;
226 const CERT_EXTENSION *ext;
227 DWORD cbext;
228 struct gc_arena gc = gc_new();
229 const WCHAR *tmpl_name = wide_string(cert_prop, &gc);
230
231 /* check for V2 extension (Windows 2003+) */
232 ext = CertFindExtension(szOID_CERTIFICATE_TEMPLATE, info->cExtension, info->rgExtension);
233 if (ext)
234 {
235 const void *pvext = decode_object(&gc, X509_CERTIFICATE_TEMPLATE, &ext->Value, 0, &cbext);
236 if (pvext && cbext >= sizeof(CERT_TEMPLATE_EXT))
237 {
238 const CERT_TEMPLATE_EXT *cte = (const CERT_TEMPLATE_EXT *)pvext;
239 if (!_stricmp(cert_prop, cte->pszObjId))
240 {
241 /* found direct OID match with certificate property specified */
242 gc_free(&gc);
243 return true;
244 }
245
246 const CRYPT_OID_INFO *tmpl_oid =
247 find_oid(CRYPT_OID_INFO_NAME_KEY, tmpl_name, CRYPT_TEMPLATE_OID_GROUP_ID);
248 if (tmpl_oid && !_stricmp(tmpl_oid->pszOID, cte->pszObjId))
249 {
250 /* found OID match in extension against resolved key */
251 gc_free(&gc);
252 return true;
253 }
254 }
255 }
256
257 /* no extension found, exit */
258 gc_free(&gc);
259 return false;
260}
261
262static const CERT_CONTEXT *
263find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
264{
265 /* Find, and use, the desired certificate from the store. The
266 * 'cert_prop' certificate search string can look like this:
267 * SUBJ:<certificate substring to match>
268 * THUMB:<certificate thumbprint hex value>, e.g.
269 * THUMB:f6 49 24 41 01 b4 fb 44 0c ce f4 36 ae d0 c4 c9 df 7a b6 28
270 * TMPL:<template name or OID>
271 * The first matching certificate that has not expired is returned.
272 */
273 const CERT_CONTEXT *rv = NULL;
274 DWORD find_type;
275 const void *find_param;
276 unsigned char hash[255];
277 CRYPT_HASH_BLOB blob = { .cbData = 0, .pbData = hash };
278 struct gc_arena gc = gc_new();
279
280 if (!strncmp(cert_prop, "SUBJ:", 5))
281 {
282 /* skip the tag */
283 find_param = wide_string(cert_prop + 5, &gc);
284 find_type = CERT_FIND_SUBJECT_STR_W;
285 }
286 else if (!strncmp(cert_prop, "ISSUER:", 7))
287 {
288 find_param = wide_string(cert_prop + 7, &gc);
289 find_type = CERT_FIND_ISSUER_STR_W;
290 }
291 else if (!strncmp(cert_prop, "THUMB:", 6))
292 {
293 find_type = CERT_FIND_HASH;
294 find_param = &blob;
295
296 blob.cbData = parse_hexstring(cert_prop + 6, hash, sizeof(hash));
297 if (blob.cbData == 0)
298 {
299 msg(M_WARN | M_INFO, "WARNING: cryptoapicert: error parsing <%s>.", cert_prop);
300 goto out;
301 }
302 }
303 else if (!strncmp(cert_prop, "TMPL:", 5))
304 {
305 cert_prop += 5;
306 find_param = NULL;
307 find_type = CERT_FIND_HAS_PRIVATE_KEY;
308 }
309 else
310 {
311 msg(M_NONFATAL, "Error in cryptoapicert: unsupported certificate specification <%s>",
312 cert_prop);
313 goto out;
314 }
315
316 while (true)
317 {
318 int validity = 1;
319 /* this frees previous rv, if not NULL */
320 rv = CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
321 find_type, find_param, rv);
322 if (!rv)
323 {
324 break;
325 }
326 /* if searching by template name, check now if it matches */
327 if (find_type == CERT_FIND_HAS_PRIVATE_KEY && !test_certificate_template(cert_prop, rv))
328 {
329 continue;
330 }
331 validity = CertVerifyTimeValidity(NULL, rv->pCertInfo);
332 if (validity == 0)
333 {
334 break;
335 }
336 msg(M_WARN | M_INFO, "WARNING: cryptoapicert: ignoring certificate in store %s.",
337 validity < 0 ? "not yet valid" : "that has expired");
338 }
339
340out:
341 gc_free(&gc);
342 return rv;
343}
344
346static int
347xkey_cng_ec_sign(CAPI_DATA *cd, unsigned char *sig, size_t *siglen, const unsigned char *tbs,
348 size_t tbslen)
349{
350 ASSERT(*siglen <= UINT_MAX);
351 ASSERT(tbslen <= UINT_MAX);
352 DWORD len = (DWORD)*siglen;
353
354 msg(D_LOW, "Signing using NCryptSignHash with EC key");
355
356 DWORD status = NCryptSignHash(cd->crypt_prov, NULL, (BYTE *)tbs, (DWORD)tbslen, sig, len, &len, 0);
357
358 if (status != ERROR_SUCCESS)
359 {
360 SetLastError(status);
361 msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: ECDSA signature using CNG failed.");
362 return 0;
363 }
364
365 /* NCryptSignHash returns r|s -- convert to DER encoded buffer expected by OpenSSL */
366 int derlen = ecdsa_bin2der(sig, (int)len, *siglen);
367 if (derlen <= 0)
368 {
369 return 0;
370 }
371 *siglen = derlen;
372 return 1;
373}
374
376static int
377xkey_cng_rsa_sign(CAPI_DATA *cd, unsigned char *sig, size_t *siglen, const unsigned char *tbs,
378 size_t tbslen, XKEY_SIGALG sigalg)
379{
380 dmsg(D_LOW, "In xkey_cng_rsa_sign");
381
382 ASSERT(cd);
383 ASSERT(sig);
384 ASSERT(*siglen <= UINT_MAX);
385 ASSERT(tbs);
386 ASSERT(tbslen <= INT_MAX);
387
388 DWORD status = ERROR_SUCCESS;
389 DWORD len = 0;
390
391 const wchar_t *hashalg = cng_hash_algo(OBJ_sn2nid(sigalg.mdname));
392
393 if (hashalg && wcscmp(hashalg, L"UNKNOWN") == 0)
394 {
395 msg(M_NONFATAL, "Error in cryptoapicert: Unknown hash name <%s>", sigalg.mdname);
396 return 0;
397 }
398
399 if (!strcmp(sigalg.padmode, "pkcs1"))
400 {
401 msg(D_LOW, "Signing using NCryptSignHash with PKCS1 padding: hashalg <%s>", sigalg.mdname);
402
403 BCRYPT_PKCS1_PADDING_INFO padinfo = { hashalg };
404 status = NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (DWORD)tbslen, sig,
405 (DWORD)*siglen, &len, BCRYPT_PAD_PKCS1);
406 }
407 else if (!strcmp(sigalg.padmode, "pss"))
408 {
409 int saltlen = (int)tbslen; /* digest size by default */
410 if (!strcmp(sigalg.saltlen, "max"))
411 {
412 saltlen = xkey_max_saltlen(EVP_PKEY_bits(cd->pubkey), saltlen);
413 if (saltlen < 0)
414 {
415 msg(M_NONFATAL, "Error in cryptoapicert: invalid salt length (%d)", saltlen);
416 return 0;
417 }
418 }
419
420 msg(D_LOW, "Signing using NCryptSignHash with PSS padding: hashalg <%s>, saltlen <%d>",
421 sigalg.mdname, saltlen);
422
423 /* cast is safe as saltlen >= 0 */
424 BCRYPT_PSS_PADDING_INFO padinfo = { hashalg, (DWORD)saltlen };
425 status = NCryptSignHash(cd->crypt_prov, &padinfo, (BYTE *)tbs, (DWORD)tbslen, sig,
426 (DWORD)*siglen, &len, BCRYPT_PAD_PSS);
427 }
428 else
429 {
430 msg(M_NONFATAL, "Error in cryptoapicert: Unsupported padding mode <%s>", sigalg.padmode);
431 return 0;
432 }
433
434 if (status != ERROR_SUCCESS)
435 {
436 SetLastError(status);
437 msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: RSA signature using CNG failed.");
438 return 0;
439 }
440
441 *siglen = len;
442 return (*siglen > 0);
443}
444
446static int
447xkey_cng_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned char *tbs,
448 size_t tbslen, XKEY_SIGALG sigalg)
449{
450 dmsg(D_LOW, "In xkey_cng_sign");
451
452 CAPI_DATA *cd = handle;
453 ASSERT(cd);
454 ASSERT(sig);
455 ASSERT(tbs);
456
457 unsigned char mdbuf[EVP_MAX_MD_SIZE];
458 size_t buflen = _countof(mdbuf);
459
460 /* compute digest if required */
461 if (!strcmp(sigalg.op, "DigestSign"))
462 {
463 if (!xkey_digest(tbs, tbslen, mdbuf, &buflen, sigalg.mdname))
464 {
465 return 0;
466 }
467 tbs = mdbuf;
468 tbslen = buflen;
469 }
470
471 if (!strcmp(sigalg.keytype, "EC"))
472 {
473 return xkey_cng_ec_sign(cd, sig, siglen, tbs, tbslen);
474 }
475 else if (!strcmp(sigalg.keytype, "RSA"))
476 {
477 return xkey_cng_rsa_sign(cd, sig, siglen, tbs, tbslen, sigalg);
478 }
479 else
480 {
481 return 0; /* Unknown keytype -- should not happen */
482 }
483}
484
485static char *
486get_cert_name(const CERT_CONTEXT *cc, struct gc_arena *gc)
487{
488 DWORD len = CertGetNameStringW(cc, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL, NULL, 0);
489 char *name = NULL;
490 if (len)
491 {
492 wchar_t *wname = gc_malloc(len * sizeof(wchar_t), false, gc);
493 if (!wname
494 || CertGetNameStringW(cc, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL, wname, len) == 0)
495 {
496 return NULL;
497 }
498 name = utf16to8(wname, gc);
499 }
500 return name;
501}
502
509static int
510Load_CryptoAPI_certificate(const char *cert_prop, X509 **cert, EVP_PKEY **privkey)
511{
512 HCERTSTORE cs;
513 CAPI_DATA *cd = calloc(1, sizeof(*cd));
514 struct gc_arena gc = gc_new();
515
516 if (cd == NULL)
517 {
518 msg(M_NONFATAL, "Error in cryptoapicert: out of memory");
519 goto err;
520 }
521 /* search CURRENT_USER first, then LOCAL_MACHINE */
522 cs = CertOpenStore((LPCSTR)CERT_STORE_PROV_SYSTEM, 0, 0,
523 CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_OPEN_EXISTING_FLAG
524 | CERT_STORE_READONLY_FLAG,
525 L"MY");
526 if (cs == NULL)
527 {
528 msg(M_NONFATAL | M_ERRNO, "Error in cryptoapicert: failed to open user certficate store");
529 goto err;
530 }
531 cd->cert_context = find_certificate_in_store(cert_prop, cs);
532 CertCloseStore(cs, 0);
533 if (!cd->cert_context)
534 {
535 cs = CertOpenStore((LPCSTR)CERT_STORE_PROV_SYSTEM, 0, 0,
536 CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_OPEN_EXISTING_FLAG
537 | CERT_STORE_READONLY_FLAG,
538 L"MY");
539 if (cs == NULL)
540 {
542 "Error in cryptoapicert: failed to open machine certficate store");
543 goto err;
544 }
545 cd->cert_context = find_certificate_in_store(cert_prop, cs);
546 CertCloseStore(cs, 0);
547 if (cd->cert_context == NULL)
548 {
549 msg(M_NONFATAL, "Error in cryptoapicert: certificate matching <%s> not found",
550 cert_prop);
551 goto err;
552 }
553 }
554
555 /* try to log the "name" of the selected certificate */
556 char *cert_name = get_cert_name(cd->cert_context, &gc);
557 if (cert_name)
558 {
559 msg(D_LOW, "cryptapicert: using certificate with name <%s>", cert_name);
560 }
561
562 /* cert_context->pbCertEncoded is the cert X509 DER encoded. */
563 *cert = d2i_X509(NULL, (const unsigned char **)&cd->cert_context->pbCertEncoded,
564 cd->cert_context->cbCertEncoded);
565 if (*cert == NULL)
566 {
567 msg(M_NONFATAL, "Error in cryptoapicert: X509 certificate decode failed");
568 goto err;
569 }
570
571 /* set up stuff to use the private key */
572 /* We support NCRYPT key handles only */
573 DWORD flags = CRYPT_ACQUIRE_COMPARE_KEY_FLAG | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG;
574 if (!CryptAcquireCertificatePrivateKey(cd->cert_context, flags, NULL, &cd->crypt_prov,
575 &cd->key_spec, &cd->free_crypt_prov))
576 {
577 /* private key may be in a token not available, or incompatible with CNG */
579 "Error in cryptoapicert: failed to acquire key. Key not present or "
580 "is in a legacy token not supported by Windows CNG API");
581 X509_free(*cert);
582 goto err;
583 }
584
585 /* the public key */
586 EVP_PKEY *pkey = X509_get_pubkey(*cert);
587 cd->pubkey = pkey; /* will be freed with cd */
588
589 *privkey = xkey_load_generic_key(tls_libctx, cd, pkey, xkey_cng_sign,
590 (XKEY_PRIVKEY_FREE_fn *)CAPI_DATA_free);
591 gc_free(&gc);
592 return 1; /* do not free cd -- its kept by xkey provider */
593
594err:
595 CAPI_DATA_free(cd);
596 gc_free(&gc);
597 return 0;
598}
599
600int
601SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
602{
603 X509 *cert = NULL;
604 EVP_PKEY *privkey = NULL;
605 int ret = 0;
606
607 if (!Load_CryptoAPI_certificate(cert_prop, &cert, &privkey))
608 {
609 return ret;
610 }
611 if (SSL_CTX_use_certificate(ssl_ctx, cert) && SSL_CTX_use_PrivateKey(ssl_ctx, privkey))
612 {
614 ret = 1;
615 }
616
617 /* Always free cert and privkey even if retained by ssl_ctx as
618 * they are reference counted */
619 X509_free(cert);
620 EVP_PKEY_free(privkey);
621 return ret;
622}
623
624#endif /* HAVE_XKEY_PROVIDER */
625#endif /* _WIN32 */
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:318
Buffer management functions and garbage collection.
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
void crypto_print_openssl_errors(const unsigned int flags)
Retrieve any occurred OpenSSL errors and print those errors.
Data Channel Cryptography OpenSSL-specific backend interface.
int SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
Definition cryptoapi.c:58
#define D_LOW
Definition errlevel.h:96
#define M_INFO
Definition errlevel.h:54
static SERVICE_STATUS status
Definition interactive.c:52
OpenSSL compatibility stub.
#define M_NONFATAL
Definition error.h:91
#define dmsg(flags,...)
Definition error.h:172
#define msg(flags,...)
Definition error.h:152
#define ASSERT(x)
Definition error.h:219
#define M_WARN
Definition error.h:92
#define M_ERRNO
Definition error.h:95
OSSL_LIB_CTX * tls_libctx
Definition ssl_openssl.c:78
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Definition list.h:56
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:152
struct gc_arena gc
Definition test_ssl.c:122
char * utf16to8(const wchar_t *utf16, struct gc_arena *gc)
Definition win32-util.c:119
WCHAR * wide_string(const char *utf8, struct gc_arena *gc)
Definition win32-util.c:40