Skip to contentSkip to conversation

Improvements for cryptoapi.c

PATCH In review [email protected]... 4 participants 21 messages Jan 28, 2023 – Feb 14, 2023

lore
Share & tools
lore
#0 lore raw

cover Improvements for cryptoapi.c

From: Selva Nair <[email protected]...>

1. Support selecting certificate using issuer name (goal: "planned obsolescence" of 2.6, already :)

2. Log the selected certificate's name

3. Remove Pre OpenSSL-3.01 support
(goal: leaner and meaner)

4. Simplify parsing of thumbprint hex string

 doc/man-sections/windows-options.rst |  13 +-
 src/openvpn/cryptoapi.c              | 629 +++------------------------
 src/openvpn/options.c                |   2 +-
 src/openvpn/win32-util.c             |  15 +
 src/openvpn/win32-util.h             |   3 +
 5 files changed, 84 insertions(+), 578 deletions(-)
Signature · 1 line
2.34.1
#1 lore raw

PATCH 1/4 Option --cryptoapicert: support issuer name as a selector

From: Selva Nair <[email protected]...>

- Certificate selection string can now specify a partial issuer name string as "--cryptoapicert ISSUER:<string>" where <string> is matched as a substring of the issuer (CA) name in the certificate.

Partial case-insensitive matching against the "issuer name" is used. Here "issuer name" is a text representation of the RDN's separated by commas.

E.g., "CA, Ontario, Toronto, Acme Inc., IT, Acme Root CA".

See MSDN docs on CertFindCertificateInStore() with CERT_FIND_ISSUER_STR as "FindType" for more details.

As the order of RDN's is not well-defined[*] and type names like "OU" or "CN" are not included, its best to match against a single attribute like the CN of the issuer:

  E.g., --cryptoapicert "ISSUER:Acme Root"

[*] Windows appears to order RDN's in the reverse order to which its written in the certificate but do not rely on this.

---
 doc/man-sections/windows-options.rst | 13 +++++++++++--
 src/openvpn/cryptoapi.c              |  5 +++++
 2 files changed, 16 insertions(+), 2 deletions(-)
doc/man-sections/windows-options.rst +11 -2
index 368f7b19..e87291f4 100644
@@ -41,13 +41,22 @@ Windows-Specific Options
 
      cryptoapicert "SUBJ:Peter Runestig"
 
-  To select a certificate, based on certificate's thumbprint:
+  To select a certificate, based on certificate's thumbprint (SHA1 hash):
   ::
 
      cryptoapicert "THUMB:f6 49 24 41 01 b4 ..."
 
   The thumbprint hex string can easily be copy-and-pasted from the Windows
-  Certificate Store GUI.
+  Certificate Store GUI. The embedded spaces in the hex string are optional.
+
+  To select a certificate based on a substring in certificate's
+  issuer name:
+  ::
+
+     cryptoapicert "ISSUER:Sample CA"
+
+  The first non-expired certificate found in the user's store or the
+  machine store that matches the select-string is used.
 
 --dhcp-release
   Ask Windows to release the TAP adapter lease on shutdown. This option
src/openvpn/cryptoapi.c +5 -0
index 661a9a6d..39eeec1b 100644
@@ -459,6 +459,11 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
         find_param = wide_string(cert_prop + 5, &gc);
         find_type = CERT_FIND_SUBJECT_STR_W;
     }
+    else if (!strncmp(cert_prop, "ISSUER:", 7))
+    {
+        find_param = wide_string(cert_prop + 7, &gc);
+        find_type = CERT_FIND_ISSUER_STR_W;
+    }
     else if (!strncmp(cert_prop, "THUMB:", 6))
     {
         const char *p;
Signature · 1 line
2.34.1
Acked-by on v1 1/4
#2 lore raw

[Openvpn-devel] [PATCH applied] Re: Option --cryptoapicert: support issuer name as a selector

I did hope that someone else would report back and say "I have tested this and it works great!". Nobody volunteered and I wanted this out of the way (and I think it's a useful addition with very little code needed).

Code looks good according to documentation of CertFindCertificateInStore() (though the microsoft documentation I found lacks the CERT_FIND...*_W defines... but it's symmetric to CERT_FIND_SUBJECT_STR_W)

MinGW and GH tell me that the code compiles fine :-)

Documentation addition is good and well-understandable.

Your patch has been applied to the master and release/2.6 branch.

commit b9e0e4060798ed88d2170702f2935754616b1200 (master) commit a8ff15ce49b69816b64387e3387b9a310891d12a (release/2.6)

Author: Selva Nair
Date:   Sat Jan 28 17:34:18 2023 -0500
     Option --cryptoapicert: support issuer name as a selector

     Signed-off-by: Selva Nair <[email protected]...>
     Acked-by: Gert Doering <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg26092.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#3 lore raw

PATCH 2/4 cyryptapi.c: log the selected certificate's name

In reply to [email protected]...

From: Selva Nair <[email protected]...>

- With various ways of specifying the selector-string to the "--cryptoapicert" option, its not immediately obvious which certificate gets selected from the store. Log it.

The "name" logged is a friendly name (if present), or a representative element of the subject (usually the common-name).

---
 src/openvpn/cryptoapi.c  | 29 +++++++++++++++++++++++++++++
 src/openvpn/win32-util.c | 15 +++++++++++++++
 src/openvpn/win32-util.h |  3 +++
 3 files changed, 47 insertions(+)
src/openvpn/cryptoapi.c +29 -0
index 39eeec1b..e3c0bc99 100644
@@ -939,12 +939,31 @@ xkey_cng_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned c
 
 #endif /* HAVE_XKEY_PROVIDER */
 
+static char *
+get_cert_name(const CERT_CONTEXT *cc, struct gc_arena *gc)
+{
+    DWORD len = CertGetNameStringW(cc, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL, NULL, 0);
+    char *name = NULL;
+    if (len)
+    {
+        wchar_t *wname = gc_malloc(len*sizeof(wchar_t), false, gc);
+        if (!wname
+            || CertGetNameStringW(cc, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL, wname, len) == 0)
+        {
+            return NULL;
+        }
+        name = utf16to8(wname, gc);
+    }
+    return name;
+}
+
 int
 SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
 {
     HCERTSTORE cs;
     X509 *cert = NULL;
     CAPI_DATA *cd = calloc(1, sizeof(*cd));
+    struct gc_arena gc = gc_new();
 
     if (cd == NULL)
     {
@@ -979,6 +998,13 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
         }
     }
 
+    /* try to log the "name" of the selected certificate */
+    char *cert_name = get_cert_name(cd->cert_context, &gc);
+    if (cert_name)
+    {
+        msg(D_LOW, "cryptapicert: using certificate with name <%s>", cert_name);
+    }
+
     /* cert_context->pbCertEncoded is the cert X509 DER encoded. */
     cert = d2i_X509(NULL, (const unsigned char **) &cd->cert_context->pbCertEncoded,
                     cd->cert_context->cbCertEncoded);
@@ -1022,6 +1048,7 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
     EVP_PKEY *privkey = xkey_load_generic_key(tls_libctx, cd, pkey,
                                               xkey_cng_sign, (XKEY_PRIVKEY_FREE_fn *) CAPI_DATA_free);
     SSL_CTX_use_PrivateKey(ssl_ctx, privkey);
+    gc_free(&gc);
     return 1; /* do not free cd -- its kept by xkey provider */
 
 #else  /* ifdef HAVE_XKEY_PROVIDER */
@@ -1047,12 +1074,14 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
         goto err;
     }
     CAPI_DATA_free(cd); /* this will do a ref_count-- */
+    gc_free(gc);
     return 1;
 
 #endif /* HAVE_XKEY_PROVIDER */
 
 err:
     CAPI_DATA_free(cd);
+    gc_free(&gc);
     return 0;
 }
 #endif                          /* _WIN32 */
src/openvpn/win32-util.c +15 -0
index 35f2a311..32f7a00b 100644
@@ -48,6 +48,21 @@ wide_string(const char *utf8, struct gc_arena *gc)
     return ucs16;
 }
 
+char *
+utf16to8(const wchar_t *utf16, struct gc_arena *gc)
+{
+    char *utf8 = NULL;
+    int n = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, NULL, NULL);
+    if (n > 0)
+    {
+        utf8 = gc_malloc(n, true, gc);
+        if (utf8)
+        {
+            WideCharToMultiByte(CP_UTF8, 0, utf16, -1, utf8, n, NULL, NULL);
+        }
+    }
+    return utf8;
+}
 
 /*
  * Return true if filename is safe to be used on Windows,
src/openvpn/win32-util.h +3 -0
index b24242c8..ac37979f 100644
@@ -34,6 +34,9 @@
 /* Convert a string from UTF-8 to UCS-2 */
 WCHAR *wide_string(const char *utf8, struct gc_arena *gc);
 
+/* Convert a string from UTF-16 to UTF-8 */
+char *utf16to8(const wchar_t *utf16, struct gc_arena *gc);
+
 /* return true if filename is safe to be used on Windows */
 bool win_safe_filename(const char *fn);
 
Signature · 1 line
2.34.1
Acked-by on v1 2/4
#4 lore raw

[Openvpn-devel] [PATCH applied] Re: cyryptapi.c: log the selected certificate's name

I think this is a useful addition. Code looks good according to the documentation for CertGetNameStringW() and WideCharToMultiByte().

Tested on a MinGW compile (yes, compiles :-) ). Not actually tested on a life windows system, as my "have p12 certs imported, reference them from .ovpn" project is still pending.

The 3 new gc_free() are a bit ugly, but unavoidable without either having "gc_free() in the middle of the function" (which we don't do) or restructure more & add "ret = 1 ; goto end" code... so it is what it is.

Your patch has been applied to the master and release/2.6 branch.

commit ddffcea2922905ec13e0e39239d106e0edbea5de (master) commit 0ccfce24b470d924d4184c8a3de08a50154c5e4c (release/2.6)

Author: Selva Nair
Date:   Sat Jan 28 17:34:19 2023 -0500
     cyryptapi.c: log the selected certificate's name

     Signed-off-by: Selva Nair <[email protected]...>
     Acked-by: Gert Doering <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg26093.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#5 lore raw

Re: [Openvpn-devel] [PATCH applied] Re: cyryptapi.c: log the selected certificate's name

Hi,

... and apologies for not fixing the Subject: - I saw the typo, it was on my "must fix" list, and then I read too much Microsoft documentation and was distracted...

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#6 lore raw

Re: [Openvpn-devel] [PATCH applied] Re: cyryptapi.c: log the selected certificate's name

In reply to Gert Doering

Hi,

Quoted 3 lines · Gert Doering

The 3 new gc_free() are a bit ugly, but unavoidable without either having "gc_free() in the middle of the function" (which we don't do) or restructure more & add "ret = 1 ; goto end" code... so it is what it is.

I did have a vague dislike for these gc_free(), but it turns out that one of them is actually *wrong*...

https://github.com/OpenVPN/openvpn/actions/runs/4174551447/jobs/7228274450

cryptoapi.c: In function `SSL_CTX_use_CryptoAPI_certificate':
426
cryptoapi.c:1072:13: error: incompatible type for argument 1 of `gc_free'
427
1072 | gc_free(gc);
428
| ^~
429
| |
430
| struct gc_arena
431
In file included from cryptoapi.c:52:
432
buffer.h:1019:26: note: expected struct gc_arena *' but argument is of type struct gc_arena' 433
1019 | gc_free(struct gc_arena *a)
434

      |         ~~~~~~~~~~~~~~~~~^

Sorry for not spotting this before merging - my MinGW build did not excercise the "right" code paths.

This is in the "no HAVE_XKEY_PROVIDER" branch, and I build with 3.0.7, so the test build never saw this.

Seems I need to merge the "remove pre-3.0 support" patch quickly, so this becomes moot ;-)

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#7 lore raw

PATCH 3/4 cryptoapi.c: remove pre OpenSSL-3.01 support

In reply to [email protected]...

From: Selva Nair <[email protected]...>

- Require xkey-provider (thus OpenSSL 3.01+) for --cryptoapicert

Note:
Ideally we should also make ENABLE_CRYPTOAPI conditional on HAVE_XKEY_PROVIDER but that looks hard unless we can agree to move HAVE_XKEY_PROVIDER to configure/config.h. Or move ENABLE_CRYPTOAPI out of syshead.h ?

---
 src/openvpn/cryptoapi.c | 555 +---------------------------------------
 src/openvpn/options.c   |   2 +-
 2 files changed, 11 insertions(+), 546 deletions(-)
src/openvpn/cryptoapi.c +10 -545
index e3c0bc99..6ff4fcb5 100644
@@ -55,17 +55,17 @@
 #include "xkey_common.h"
 
 #ifndef HAVE_XKEY_PROVIDER
-/* index for storing external data in EC_KEY: < 0 means uninitialized */
-static int ec_data_idx = -1;
 
-/* Global EVP_PKEY_METHOD used to override the sign operation */
-static EVP_PKEY_METHOD *pmethod;
-static int (*default_pkey_sign_init) (EVP_PKEY_CTX *ctx);
-static int (*default_pkey_sign) (EVP_PKEY_CTX *ctx, unsigned char *sig,
-                                 size_t *siglen, const unsigned char *tbs, size_t tbslen);
-#else  /* ifndef HAVE_XKEY_PROVIDER */
+int
+SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
+{
+    msg(M_NONFATAL, "ERROR: cryptoapicert not supported in this version");
+    return 0;
+}
+
+#else /* HAVE_XKEY_PROVIDER */
+
 static XKEY_EXTERNAL_SIGN_fn xkey_cng_sign;
-#endif /* HAVE_XKEY_PROVIDER */
 
 typedef struct _CAPI_DATA {
     const CERT_CONTEXT *cert_context;
@@ -146,127 +146,6 @@ CAPI_DATA_free(CAPI_DATA *cd)
     free(cd);
 }
 
-#ifndef HAVE_XKEY_PROVIDER
-
-/* Translate OpenSSL padding type to CNG padding type
- * Returns 0 for unknown/unsupported padding.
- */
-static DWORD
-cng_padding_type(int padding)
-{
-    DWORD pad = 0;
-
-    switch (padding)
-    {
-        case RSA_NO_PADDING:
-            break;
-
-        case RSA_PKCS1_PADDING:
-            pad = BCRYPT_PAD_PKCS1;
-            break;
-
-        case RSA_PKCS1_PSS_PADDING:
-            pad = BCRYPT_PAD_PSS;
-            break;
-
-        default:
-            msg(M_WARN|M_INFO, "cryptoapicert: unknown OpenSSL padding type %d.",
-                padding);
-    }
-
-    return pad;
-}
-
-/**
- * Sign the hash in 'from' using NCryptSignHash(). This requires an NCRYPT
- * key handle in cd->crypt_prov. On return the signature is in 'to'. Returns
- * the length of the signature or 0 on error.
- * This is used only for RSA and padding should be BCRYPT_PAD_PKCS1 or
- * BCRYPT_PAD_PSS.
- * If the hash_algo is not NULL, PKCS #1 DigestInfo header gets added
- * to |from|, else it is signed as is. Use NULL for MD5 + SHA1 hash used
- * in TLS 1.1 and earlier.
- * In case of PSS padding, |saltlen| should specify the size of salt to use.
- * If |to| is NULL returns the required buffer size.
- */
-static int
-priv_enc_CNG(const CAPI_DATA *cd, const wchar_t *hash_algo, const unsigned char *from,
-             int flen, unsigned char *to, int tlen, DWORD padding, DWORD saltlen)
-{
-    NCRYPT_KEY_HANDLE hkey = cd->crypt_prov;
-    DWORD len = 0;
-    ASSERT(cd->key_spec == CERT_NCRYPT_KEY_SPEC);
-
-    DWORD status;
-
-    msg(D_LOW, "Signing hash using CNG: data size = %d padding = %lu", flen, padding);
-
-    if (padding == BCRYPT_PAD_PKCS1)
-    {
-        BCRYPT_PKCS1_PADDING_INFO padinfo = {hash_algo};
-        status = NCryptSignHash(hkey, &padinfo, (BYTE *)from, flen,
-                                to, tlen, &len, padding);
-    }
-    else if (padding == BCRYPT_PAD_PSS)
-    {
-        BCRYPT_PSS_PADDING_INFO padinfo = {hash_algo, saltlen};
-        status = NCryptSignHash(hkey, &padinfo, (BYTE *)from, flen,
-                                to, tlen, &len, padding);
-    }
-    else
-    {
-        msg(M_NONFATAL, "Error in cryptoapicert: Unknown padding type");
-        return 0;
-    }
-
-    if (status != ERROR_SUCCESS)
-    {
-        SetLastError(status);
-        msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: NCryptSignHash failed");
-        len = 0;
-    }
-
-    /* Unlike CAPI, CNG signature is in big endian order. No reversing needed. */
-    return len;
-}
-
-/* called at RSA_free */
-static int
-rsa_finish(RSA *rsa)
-{
-    const RSA_METHOD *rsa_meth = RSA_get_method(rsa);
-    CAPI_DATA *cd = (CAPI_DATA *) RSA_meth_get0_app_data(rsa_meth);
-
-    if (cd == NULL)
-    {
-        return 0;
-    }
-    CAPI_DATA_free(cd);
-    RSA_meth_free((RSA_METHOD *) rsa_meth);
-    return 1;
-}
-
-static EC_KEY_METHOD *ec_method = NULL;
-
-/** EC_KEY_METHOD callback: called when the key is freed */
-static void
-ec_finish(EC_KEY *ec)
-{
-    EC_KEY_METHOD_free(ec_method);
-    ec_method = NULL;
-    CAPI_DATA *cd = EC_KEY_get_ex_data(ec, ec_data_idx);
-    CAPI_DATA_free(cd);
-    EC_KEY_set_ex_data(ec, ec_data_idx, NULL);
-}
-
-/** EC_KEY_METHOD callback sign_setup(): we do nothing here */
-static int
-ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
-{
-    return 1;
-}
-#endif /* HAVE_XKEY_PROVIDER */
-
 /**
  * Helper to convert ECDSA signature returned by NCryptSignHash
  * to an ECDSA_SIG structure.
@@ -301,141 +180,6 @@ err:
     return NULL;
 }
 
-#ifndef HAVE_XKEY_PROVIDER
-
-/** EC_KEY_METHOD callback sign_sig(): sign and return an ECDSA_SIG pointer. */
-static ECDSA_SIG *
-ecdsa_sign_sig(const unsigned char *dgst, int dgstlen,
-               const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *ec)
-{
-    ECDSA_SIG *ecsig = NULL;
-    CAPI_DATA *cd = (CAPI_DATA *)EC_KEY_get_ex_data(ec, ec_data_idx);
-
-    ASSERT(cd->key_spec == CERT_NCRYPT_KEY_SPEC);
-
-    NCRYPT_KEY_HANDLE hkey = cd->crypt_prov;
-    BYTE buf[512]; /* large enough buffer for signature to avoid malloc */
-    DWORD len = _countof(buf);
-
-    msg(D_LOW, "Cryptoapi: signing hash using EC key: data size = %d", dgstlen);
-
-    DWORD status = NCryptSignHash(hkey, NULL, (BYTE *)dgst, dgstlen, (BYTE *)buf, len, &len, 0);
-    if (status != ERROR_SUCCESS)
-    {
-        SetLastError(status);
-        msg(M_NONFATAL|M_ERRNO, "Error in cryptoapticert: NCryptSignHash failed");
-    }
-    else
-    {
-        /* NCryptSignHash returns r, s concatenated in buf[] */
-        ecsig = ecdsa_bin2sig(buf, len);
-    }
-    return ecsig;
-}
-
-/** EC_KEY_METHOD callback sign(): sign and return a DER encoded signature */
-static int
-ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig,
-           unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *ec)
-{
-    ECDSA_SIG *s;
-
-    *siglen = 0;
-    s = ecdsa_sign_sig(dgst, dgstlen, NULL, NULL, ec);
-    if (s == NULL)
-    {
-        return 0;
-    }
-
-    /* convert internal signature structure 's' to DER encoded byte array in sig */
-    int len = i2d_ECDSA_SIG(s, NULL);
-    if (len > ECDSA_size(ec))
-    {
-        ECDSA_SIG_free(s);
-        msg(M_NONFATAL, "Error in cryptoapicert: DER encoded ECDSA signature is too long (%d bytes)", len);
-        return 0;
-    }
-    *siglen = i2d_ECDSA_SIG(s, &sig);
-    ECDSA_SIG_free(s);
-
-    return 1;
-}
-
-static int
-ssl_ctx_set_eckey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey)
-{
-    EC_KEY *ec = NULL;
-    EVP_PKEY *privkey = NULL;
-
-    /* create a method struct with default callbacks filled in */
-    ec_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL());
-    if (!ec_method)
-    {
-        goto err;
-    }
-
-    /* We only need to set finish among init methods, and sign methods */
-    EC_KEY_METHOD_set_init(ec_method, NULL, ec_finish, NULL, NULL, NULL, NULL);
-    EC_KEY_METHOD_set_sign(ec_method, ecdsa_sign, ecdsa_sign_setup, ecdsa_sign_sig);
-
-    ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(pkey));
-    if (!ec)
-    {
-        goto err;
-    }
-    if (!EC_KEY_set_method(ec, ec_method))
-    {
-        goto err;
-    }
-
-    /* get an index to store cd as external data */
-    if (ec_data_idx < 0)
-    {
-        ec_data_idx = EC_KEY_get_ex_new_index(0, "cryptapicert ec key", NULL, NULL, NULL);
-        if (ec_data_idx < 0)
-        {
-            goto err;
-        }
-    }
-    EC_KEY_set_ex_data(ec, ec_data_idx, cd);
-
-    /* cd assigned to ec as ex_data, increase its refcount */
-    cd->ref_count++;
-
-    privkey = EVP_PKEY_new();
-    if (!EVP_PKEY_assign_EC_KEY(privkey, ec))
-    {
-        EC_KEY_free(ec);
-        goto err;
-    }
-    /* from here on ec will get freed with privkey */
-
-    if (!SSL_CTX_use_PrivateKey(ssl_ctx, privkey))
-    {
-        goto err;
-    }
-    EVP_PKEY_free(privkey); /* this will dn_ref or free ec as well */
-    return 1;
-
-err:
-    if (privkey)
-    {
-        EVP_PKEY_free(privkey);
-    }
-    else if (ec)
-    {
-        EC_KEY_free(ec);
-    }
-    if (ec_method) /* do always set ec_method = NULL after freeing it */
-    {
-        EC_KEY_METHOD_free(ec_method);
-        ec_method = NULL;
-    }
-    return 0;
-}
-
-#endif /* !HAVE_XKEY_PROVIDER */
-
 static const CERT_CONTEXT *
 find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
 {
@@ -541,254 +285,6 @@ out:
     return rv;
 }
 
-#ifndef HAVE_XKEY_PROVIDER
-
-static const CAPI_DATA *
-retrieve_capi_data(EVP_PKEY *pkey)
-{
-    const CAPI_DATA *cd = NULL;
-
-    if (pkey && EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
-    {
-        RSA *rsa = EVP_PKEY_get0_RSA(pkey);
-        if (rsa)
-        {
-            cd = (CAPI_DATA *)RSA_meth_get0_app_data(RSA_get_method(rsa));
-        }
-    }
-    return cd;
-}
-
-static int
-pkey_rsa_sign_init(EVP_PKEY_CTX *ctx)
-{
-    msg(D_LOW, "cryptoapicert: enter pkey_rsa_sign_init");
-
-    EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
-
-    if (pkey && retrieve_capi_data(pkey))
-    {
-        return 1; /* Return success */
-    }
-    else if (default_pkey_sign_init)  /* Not our key. Call the default method */
-    {
-        return default_pkey_sign_init(ctx);
-    }
-    return 1;
-}
-
-/**
- * Implementation of EVP_PKEY_sign() using CNG: sign the digest in |tbs|
- * and save the the signature in |sig| and its size in |*siglen|.
- * If |sig| is NULL the required buffer size is returned in |*siglen|.
- * Returns value is 1 on success, 0 or a negative integer on error.
- */
-static int
-pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
-              const unsigned char *tbs, size_t tbslen)
-{
-    EVP_PKEY *pkey = NULL;
-    const CAPI_DATA *cd = NULL;
-    EVP_MD *md = NULL;
-    const wchar_t *alg = NULL;
-
-    int padding = 0;
-    int hashlen = 0;
-    int saltlen = 0;
-
-    pkey = EVP_PKEY_CTX_get0_pkey(ctx);
-    if (pkey)
-    {
-        cd = retrieve_capi_data(pkey);
-    }
-
-    /*
-     * We intercept all sign requests, not just the one's for our key.
-     * Check the key and call the saved OpenSSL method for unknown keys.
-     */
-    if (!pkey || !cd)
-    {
-        if (default_pkey_sign)
-        {
-            return default_pkey_sign(ctx, sig, siglen, tbs, tbslen);
-        }
-        else  /* This should not happen */
-        {
-            msg(M_FATAL, "Error in cryptoapicert: Unknown key and no default sign operation to fallback on");
-            return -1;
-        }
-    }
-
-    if (!EVP_PKEY_CTX_get_rsa_padding(ctx, &padding))
-    {
-        padding = RSA_PKCS1_PADDING; /* Default padding for RSA */
-    }
-
-    if (EVP_PKEY_CTX_get_signature_md(ctx, &md))
-    {
-        hashlen = EVP_MD_size(md);
-        alg = cng_hash_algo(EVP_MD_type(md));
-
-        /*
-         * alg == NULL indicates legacy MD5+SHA1 hash, else alg should be a valid
-         * digest algorithm.
-         */
-        if (alg && wcscmp(alg, L"UNKNOWN") == 0)
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: Unknown hash algorithm <%d>", EVP_MD_type(md));
-            return -1;
-        }
-    }
-    else
-    {
-        msg(M_NONFATAL, "Error in cryptoapicert: could not determine the signature digest algorithm");
-        return -1;
-    }
-
-    if (tbslen != (size_t)hashlen)
-    {
-        msg(M_NONFATAL, "Error in cryptoapicert: data size does not match hash");
-        return -1;
-    }
-
-    /* If padding is PSS, determine parameters to pass to CNG */
-    if (padding == RSA_PKCS1_PSS_PADDING)
-    {
-        /*
-         * Ensure the digest type for signature and mask generation match.
-         * In CNG there is no option to specify separate hash functions for
-         * the two, but OpenSSL supports it. However, I have not seen the
-         * two being different in practice. Also the recommended practice is
-         * to use the same for both (rfc 8017 sec 8.1).
-         */
-        EVP_MD *mgf1md;
-        if (!EVP_PKEY_CTX_get_rsa_mgf1_md(ctx, &mgf1md)
-            || EVP_MD_type(mgf1md) != EVP_MD_type(md))
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: Unknown MGF1 digest type or does"
-                " not match the signature digest type.");
-            return -1;
-        }
-
-        if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, &saltlen))
-        {
-            msg(M_WARN|M_INFO, "cryptoapicert: unable to get the salt length from context."
-                " Using the default value.");
-            saltlen = -1;
-        }
-
-        /*
-         * In OpenSSL saltlen = -1 indicates to use the size of the digest as
-         * size of the salt. A value of -2 or -3 indicates maximum salt length
-         * that will fit. See RSA_padding_add_PKCS1_PSS_mgf1() of OpenSSL.
-         */
-        if (saltlen == -1)
-        {
-            saltlen = hashlen;
-        }
-        else if (saltlen < 0)
-        {
-            const RSA *rsa = EVP_PKEY_get0_RSA(pkey);
-            saltlen = RSA_size(rsa) - hashlen - 2; /* max salt length for RSASSA-PSS */
-            if (RSA_bits(rsa) &0x7) /* number of bits in the key not a multiple of 8 */
-            {
-                saltlen--;
-            }
-        }
-
-        if (saltlen < 0)
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: invalid salt length (%d). Digest too large for keysize?", saltlen);
-            return -1;
-        }
-        msg(D_LOW, "cryptoapicert: PSS padding using saltlen = %d", saltlen);
-    }
-
-    msg(D_LOW, "cryptoapicert: calling priv_enc_CNG with alg = %ls", alg);
-    *siglen = priv_enc_CNG(cd, alg, tbs, (int)tbslen, sig, (int)*siglen,
-                           cng_padding_type(padding), (DWORD)saltlen);
-
-    return (*siglen == 0) ? 0 : 1;
-}
-
-static int
-ssl_ctx_set_rsakey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey)
-{
-    RSA *rsa = NULL;
-    RSA_METHOD *my_rsa_method = NULL;
-    EVP_PKEY *privkey = NULL;
-    int ret = 0;
-
-    my_rsa_method = RSA_meth_new("Microsoft Cryptography API RSA Method",
-                                 RSA_METHOD_FLAG_NO_CHECK);
-    check_malloc_return(my_rsa_method);
-    RSA_meth_set_finish(my_rsa_method, rsa_finish); /* we use this callback to cleanup CAPI_DATA */
-    RSA_meth_set0_app_data(my_rsa_method, cd);
-
-    /* pmethod is global -- initialize only if NULL */
-    if (!pmethod)
-    {
-        pmethod = EVP_PKEY_meth_new(EVP_PKEY_RSA, 0);
-        if (!pmethod)
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: failed to create EVP_PKEY_METHOD");
-            return 0;
-        }
-        const EVP_PKEY_METHOD *default_pmethod = EVP_PKEY_meth_find(EVP_PKEY_RSA);
-        EVP_PKEY_meth_copy(pmethod, default_pmethod);
-
-        /* We want to override only sign_init() and sign() */
-        EVP_PKEY_meth_set_sign(pmethod, pkey_rsa_sign_init, pkey_rsa_sign);
-        EVP_PKEY_meth_add0(pmethod);
-
-        /* Keep a copy of the default sign and sign_init methods */
-
-        EVP_PKEY_meth_get_sign(default_pmethod, &default_pkey_sign_init,
-                               &default_pkey_sign);
-    }
-
-    rsa = EVP_PKEY_get1_RSA(pkey);
-
-    RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY);
-    if (!RSA_set_method(rsa, my_rsa_method))
-    {
-        goto cleanup;
-    }
-    my_rsa_method = NULL;  /* we do not want to free it in cleanup */
-    cd->ref_count++;       /* with method, cd gets assigned to the key as well */
-
-    privkey = EVP_PKEY_new();
-    if (!EVP_PKEY_assign_RSA(privkey, rsa))
-    {
-        goto cleanup;
-    }
-    rsa = NULL; /* privkey has taken ownership */
-
-    if (!SSL_CTX_use_PrivateKey(ssl_ctx, privkey))
-    {
-        goto cleanup;
-    }
-    ret = 1;
-
-cleanup:
-    if (rsa)
-    {
-        RSA_free(rsa);
-    }
-    if (my_rsa_method)
-    {
-        RSA_meth_free(my_rsa_method);
-    }
-    if (privkey)
-    {
-        EVP_PKEY_free(privkey);
-    }
-
-    return ret;
-}
-
-#else /* HAVE_XKEY_PROVIDER */
-
 /** Sign hash in tbs using EC key in cd and NCryptSignHash */
 static int
 xkey_cng_ec_sign(CAPI_DATA *cd, unsigned char *sig, size_t *siglen, const unsigned char *tbs,
@@ -937,8 +433,6 @@ xkey_cng_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned c
     }
 }
 
-#endif /* HAVE_XKEY_PROVIDER */
-
 static char *
 get_cert_name(const CERT_CONTEXT *cc, struct gc_arena *gc)
 {
@@ -1043,45 +537,16 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
     X509_free(cert);
     cert = NULL;
 
-#ifdef HAVE_XKEY_PROVIDER
-
     EVP_PKEY *privkey = xkey_load_generic_key(tls_libctx, cd, pkey,
                                               xkey_cng_sign, (XKEY_PRIVKEY_FREE_fn *) CAPI_DATA_free);
     SSL_CTX_use_PrivateKey(ssl_ctx, privkey);
     gc_free(&gc);
     return 1; /* do not free cd -- its kept by xkey provider */
 
-#else  /* ifdef HAVE_XKEY_PROVIDER */
-
-    if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
-    {
-        if (!ssl_ctx_set_rsakey(ssl_ctx, cd, pkey))
-        {
-            goto err;
-        }
-    }
-    else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC)
-    {
-        if (!ssl_ctx_set_eckey(ssl_ctx, cd, pkey))
-        {
-            goto err;
-        }
-    }
-    else
-    {
-        msg(M_WARN|M_INFO, "WARNING: cryptoapicert: key type <%d> not supported",
-            EVP_PKEY_id(pkey));
-        goto err;
-    }
-    CAPI_DATA_free(cd); /* this will do a ref_count-- */
-    gc_free(gc);
-    return 1;
-
-#endif /* HAVE_XKEY_PROVIDER */
-
 err:
     CAPI_DATA_free(cd);
     gc_free(&gc);
     return 0;
 }
+#endif  /* HAVE_XKEY_PROVIDER */
 #endif                          /* _WIN32 */
src/openvpn/options.c +1 -1
index f24af3d7..e18b3b39 100644
@@ -8864,7 +8864,7 @@ add_option(struct options *options,
             listend->next = newlist;
         }
     }
-#ifdef ENABLE_CRYPTOAPI
+#if defined(ENABLE_CRYPTOAPI) && defined(HAVE_XKEY_PROVIDER)
     else if (streq(p[0], "cryptoapicert") && p[1] && !p[2])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
Signature · 1 line
2.34.1
#8 lore raw

Re: [Openvpn-devel] [PATCH 3/4] cryptoapi.c: remove pre OpenSSL-3.01 support

Quoted 27 lines · On Sat, Jan 28, 2023 at 05:34:20PM -0500, [email protected]... wrote:

From: Selva Nair <[email protected]...>

- Require xkey-provider (thus OpenSSL 3.01+) for --cryptoapicert

Note:
Ideally we should also make ENABLE_CRYPTOAPI conditional on HAVE_XKEY_PROVIDER but that looks hard unless we can agree to move HAVE_XKEY_PROVIDER to configure/config.h. Or move ENABLE_CRYPTOAPI out of syshead.h ?

---
 src/openvpn/cryptoapi.c | 555 +---------------------------------------
 src/openvpn/options.c   |   2 +-
 2 files changed, 11 insertions(+), 546 deletions(-)
src/openvpn/cryptoapi.c +0 -2
index e3c0bc99..6ff4fcb5 100644
@@ -55,17 +55,17 @@
 #include "xkey_common.h"
 
 #ifndef HAVE_XKEY_PROVIDER
-/* index for storing external data in EC_KEY: < 0 means uninitialized */
-static int ec_data_idx = -1;
 

src/openvpn/cryptoapi.c line 62

Quoted 10 lines
src/openvpn/cryptoapi.c +4 -6
-/* Global EVP_PKEY_METHOD used to override the sign operation */
-static EVP_PKEY_METHOD *pmethod;
-static int (*default_pkey_sign_init) (EVP_PKEY_CTX *ctx);
-static int (*default_pkey_sign) (EVP_PKEY_CTX *ctx, unsigned char *sig,
-                                 size_t *siglen, const unsigned char *tbs, size_t tbslen);
-#else  /* ifndef HAVE_XKEY_PROVIDER */
+int
+SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
+{
+    msg(M_NONFATAL, "ERROR: cryptoapicert not supported in this version");

"in this version" sounds wrong to me. That might indicate to the user that they need a newer or older version of OpenVPN. Maybe
"this binary was compiled without cryptoapicert support"?

Regards,

Signature · 1 line
  Frank Lichtenheld
#9 lore raw

PATCH v2 3/4 cryptoapi.c: remove pre OpenSSL-3.01 support

In reply to [email protected]...

From: Selva Nair <[email protected]...>

- Require xkey-provider (thus OpenSSL 3.01+) for --cryptoapicert

Note:
Ideally we should also make ENABLE_CRYPTOAPI conditional on HAVE_XKEY_PROVIDER but that looks hard unless we can agree to move HAVE_XKEY_PROVIDER to configure/config.h.

v2: use "binary" instead of "version" in the error message

---
 src/openvpn/cryptoapi.c | 555 +---------------------------------------
 src/openvpn/options.c   |   2 +-
 2 files changed, 11 insertions(+), 546 deletions(-)
src/openvpn/cryptoapi.c +10 -545
index e3c0bc99..eafef1b1 100644
@@ -55,17 +55,17 @@
 #include "xkey_common.h"
 
 #ifndef HAVE_XKEY_PROVIDER
-/* index for storing external data in EC_KEY: < 0 means uninitialized */
-static int ec_data_idx = -1;
 
-/* Global EVP_PKEY_METHOD used to override the sign operation */
-static EVP_PKEY_METHOD *pmethod;
-static int (*default_pkey_sign_init) (EVP_PKEY_CTX *ctx);
-static int (*default_pkey_sign) (EVP_PKEY_CTX *ctx, unsigned char *sig,
-                                 size_t *siglen, const unsigned char *tbs, size_t tbslen);
-#else  /* ifndef HAVE_XKEY_PROVIDER */
+int
+SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
+{
+    msg(M_NONFATAL, "ERROR: this binary was built without cryptoapicert support");
+    return 0;
+}
+
+#else /* HAVE_XKEY_PROVIDER */
+
 static XKEY_EXTERNAL_SIGN_fn xkey_cng_sign;
-#endif /* HAVE_XKEY_PROVIDER */
 
 typedef struct _CAPI_DATA {
     const CERT_CONTEXT *cert_context;
@@ -146,127 +146,6 @@ CAPI_DATA_free(CAPI_DATA *cd)
     free(cd);
 }
 
-#ifndef HAVE_XKEY_PROVIDER
-
-/* Translate OpenSSL padding type to CNG padding type
- * Returns 0 for unknown/unsupported padding.
- */
-static DWORD
-cng_padding_type(int padding)
-{
-    DWORD pad = 0;
-
-    switch (padding)
-    {
-        case RSA_NO_PADDING:
-            break;
-
-        case RSA_PKCS1_PADDING:
-            pad = BCRYPT_PAD_PKCS1;
-            break;
-
-        case RSA_PKCS1_PSS_PADDING:
-            pad = BCRYPT_PAD_PSS;
-            break;
-
-        default:
-            msg(M_WARN|M_INFO, "cryptoapicert: unknown OpenSSL padding type %d.",
-                padding);
-    }
-
-    return pad;
-}
-
-/**
- * Sign the hash in 'from' using NCryptSignHash(). This requires an NCRYPT
- * key handle in cd->crypt_prov. On return the signature is in 'to'. Returns
- * the length of the signature or 0 on error.
- * This is used only for RSA and padding should be BCRYPT_PAD_PKCS1 or
- * BCRYPT_PAD_PSS.
- * If the hash_algo is not NULL, PKCS #1 DigestInfo header gets added
- * to |from|, else it is signed as is. Use NULL for MD5 + SHA1 hash used
- * in TLS 1.1 and earlier.
- * In case of PSS padding, |saltlen| should specify the size of salt to use.
- * If |to| is NULL returns the required buffer size.
- */
-static int
-priv_enc_CNG(const CAPI_DATA *cd, const wchar_t *hash_algo, const unsigned char *from,
-             int flen, unsigned char *to, int tlen, DWORD padding, DWORD saltlen)
-{
-    NCRYPT_KEY_HANDLE hkey = cd->crypt_prov;
-    DWORD len = 0;
-    ASSERT(cd->key_spec == CERT_NCRYPT_KEY_SPEC);
-
-    DWORD status;
-
-    msg(D_LOW, "Signing hash using CNG: data size = %d padding = %lu", flen, padding);
-
-    if (padding == BCRYPT_PAD_PKCS1)
-    {
-        BCRYPT_PKCS1_PADDING_INFO padinfo = {hash_algo};
-        status = NCryptSignHash(hkey, &padinfo, (BYTE *)from, flen,
-                                to, tlen, &len, padding);
-    }
-    else if (padding == BCRYPT_PAD_PSS)
-    {
-        BCRYPT_PSS_PADDING_INFO padinfo = {hash_algo, saltlen};
-        status = NCryptSignHash(hkey, &padinfo, (BYTE *)from, flen,
-                                to, tlen, &len, padding);
-    }
-    else
-    {
-        msg(M_NONFATAL, "Error in cryptoapicert: Unknown padding type");
-        return 0;
-    }
-
-    if (status != ERROR_SUCCESS)
-    {
-        SetLastError(status);
-        msg(M_NONFATAL|M_ERRNO, "Error in cryptoapicert: NCryptSignHash failed");
-        len = 0;
-    }
-
-    /* Unlike CAPI, CNG signature is in big endian order. No reversing needed. */
-    return len;
-}
-
-/* called at RSA_free */
-static int
-rsa_finish(RSA *rsa)
-{
-    const RSA_METHOD *rsa_meth = RSA_get_method(rsa);
-    CAPI_DATA *cd = (CAPI_DATA *) RSA_meth_get0_app_data(rsa_meth);
-
-    if (cd == NULL)
-    {
-        return 0;
-    }
-    CAPI_DATA_free(cd);
-    RSA_meth_free((RSA_METHOD *) rsa_meth);
-    return 1;
-}
-
-static EC_KEY_METHOD *ec_method = NULL;
-
-/** EC_KEY_METHOD callback: called when the key is freed */
-static void
-ec_finish(EC_KEY *ec)
-{
-    EC_KEY_METHOD_free(ec_method);
-    ec_method = NULL;
-    CAPI_DATA *cd = EC_KEY_get_ex_data(ec, ec_data_idx);
-    CAPI_DATA_free(cd);
-    EC_KEY_set_ex_data(ec, ec_data_idx, NULL);
-}
-
-/** EC_KEY_METHOD callback sign_setup(): we do nothing here */
-static int
-ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
-{
-    return 1;
-}
-#endif /* HAVE_XKEY_PROVIDER */
-
 /**
  * Helper to convert ECDSA signature returned by NCryptSignHash
  * to an ECDSA_SIG structure.
@@ -301,141 +180,6 @@ err:
     return NULL;
 }
 
-#ifndef HAVE_XKEY_PROVIDER
-
-/** EC_KEY_METHOD callback sign_sig(): sign and return an ECDSA_SIG pointer. */
-static ECDSA_SIG *
-ecdsa_sign_sig(const unsigned char *dgst, int dgstlen,
-               const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *ec)
-{
-    ECDSA_SIG *ecsig = NULL;
-    CAPI_DATA *cd = (CAPI_DATA *)EC_KEY_get_ex_data(ec, ec_data_idx);
-
-    ASSERT(cd->key_spec == CERT_NCRYPT_KEY_SPEC);
-
-    NCRYPT_KEY_HANDLE hkey = cd->crypt_prov;
-    BYTE buf[512]; /* large enough buffer for signature to avoid malloc */
-    DWORD len = _countof(buf);
-
-    msg(D_LOW, "Cryptoapi: signing hash using EC key: data size = %d", dgstlen);
-
-    DWORD status = NCryptSignHash(hkey, NULL, (BYTE *)dgst, dgstlen, (BYTE *)buf, len, &len, 0);
-    if (status != ERROR_SUCCESS)
-    {
-        SetLastError(status);
-        msg(M_NONFATAL|M_ERRNO, "Error in cryptoapticert: NCryptSignHash failed");
-    }
-    else
-    {
-        /* NCryptSignHash returns r, s concatenated in buf[] */
-        ecsig = ecdsa_bin2sig(buf, len);
-    }
-    return ecsig;
-}
-
-/** EC_KEY_METHOD callback sign(): sign and return a DER encoded signature */
-static int
-ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig,
-           unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *ec)
-{
-    ECDSA_SIG *s;
-
-    *siglen = 0;
-    s = ecdsa_sign_sig(dgst, dgstlen, NULL, NULL, ec);
-    if (s == NULL)
-    {
-        return 0;
-    }
-
-    /* convert internal signature structure 's' to DER encoded byte array in sig */
-    int len = i2d_ECDSA_SIG(s, NULL);
-    if (len > ECDSA_size(ec))
-    {
-        ECDSA_SIG_free(s);
-        msg(M_NONFATAL, "Error in cryptoapicert: DER encoded ECDSA signature is too long (%d bytes)", len);
-        return 0;
-    }
-    *siglen = i2d_ECDSA_SIG(s, &sig);
-    ECDSA_SIG_free(s);
-
-    return 1;
-}
-
-static int
-ssl_ctx_set_eckey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey)
-{
-    EC_KEY *ec = NULL;
-    EVP_PKEY *privkey = NULL;
-
-    /* create a method struct with default callbacks filled in */
-    ec_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL());
-    if (!ec_method)
-    {
-        goto err;
-    }
-
-    /* We only need to set finish among init methods, and sign methods */
-    EC_KEY_METHOD_set_init(ec_method, NULL, ec_finish, NULL, NULL, NULL, NULL);
-    EC_KEY_METHOD_set_sign(ec_method, ecdsa_sign, ecdsa_sign_setup, ecdsa_sign_sig);
-
-    ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(pkey));
-    if (!ec)
-    {
-        goto err;
-    }
-    if (!EC_KEY_set_method(ec, ec_method))
-    {
-        goto err;
-    }
-
-    /* get an index to store cd as external data */
-    if (ec_data_idx < 0)
-    {
-        ec_data_idx = EC_KEY_get_ex_new_index(0, "cryptapicert ec key", NULL, NULL, NULL);
-        if (ec_data_idx < 0)
-        {
-            goto err;
-        }
-    }
-    EC_KEY_set_ex_data(ec, ec_data_idx, cd);
-
-    /* cd assigned to ec as ex_data, increase its refcount */
-    cd->ref_count++;
-
-    privkey = EVP_PKEY_new();
-    if (!EVP_PKEY_assign_EC_KEY(privkey, ec))
-    {
-        EC_KEY_free(ec);
-        goto err;
-    }
-    /* from here on ec will get freed with privkey */
-
-    if (!SSL_CTX_use_PrivateKey(ssl_ctx, privkey))
-    {
-        goto err;
-    }
-    EVP_PKEY_free(privkey); /* this will dn_ref or free ec as well */
-    return 1;
-
-err:
-    if (privkey)
-    {
-        EVP_PKEY_free(privkey);
-    }
-    else if (ec)
-    {
-        EC_KEY_free(ec);
-    }
-    if (ec_method) /* do always set ec_method = NULL after freeing it */
-    {
-        EC_KEY_METHOD_free(ec_method);
-        ec_method = NULL;
-    }
-    return 0;
-}
-
-#endif /* !HAVE_XKEY_PROVIDER */
-
 static const CERT_CONTEXT *
 find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
 {
@@ -541,254 +285,6 @@ out:
     return rv;
 }
 
-#ifndef HAVE_XKEY_PROVIDER
-
-static const CAPI_DATA *
-retrieve_capi_data(EVP_PKEY *pkey)
-{
-    const CAPI_DATA *cd = NULL;
-
-    if (pkey && EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
-    {
-        RSA *rsa = EVP_PKEY_get0_RSA(pkey);
-        if (rsa)
-        {
-            cd = (CAPI_DATA *)RSA_meth_get0_app_data(RSA_get_method(rsa));
-        }
-    }
-    return cd;
-}
-
-static int
-pkey_rsa_sign_init(EVP_PKEY_CTX *ctx)
-{
-    msg(D_LOW, "cryptoapicert: enter pkey_rsa_sign_init");
-
-    EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
-
-    if (pkey && retrieve_capi_data(pkey))
-    {
-        return 1; /* Return success */
-    }
-    else if (default_pkey_sign_init)  /* Not our key. Call the default method */
-    {
-        return default_pkey_sign_init(ctx);
-    }
-    return 1;
-}
-
-/**
- * Implementation of EVP_PKEY_sign() using CNG: sign the digest in |tbs|
- * and save the the signature in |sig| and its size in |*siglen|.
- * If |sig| is NULL the required buffer size is returned in |*siglen|.
- * Returns value is 1 on success, 0 or a negative integer on error.
- */
-static int
-pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
-              const unsigned char *tbs, size_t tbslen)
-{
-    EVP_PKEY *pkey = NULL;
-    const CAPI_DATA *cd = NULL;
-    EVP_MD *md = NULL;
-    const wchar_t *alg = NULL;
-
-    int padding = 0;
-    int hashlen = 0;
-    int saltlen = 0;
-
-    pkey = EVP_PKEY_CTX_get0_pkey(ctx);
-    if (pkey)
-    {
-        cd = retrieve_capi_data(pkey);
-    }
-
-    /*
-     * We intercept all sign requests, not just the one's for our key.
-     * Check the key and call the saved OpenSSL method for unknown keys.
-     */
-    if (!pkey || !cd)
-    {
-        if (default_pkey_sign)
-        {
-            return default_pkey_sign(ctx, sig, siglen, tbs, tbslen);
-        }
-        else  /* This should not happen */
-        {
-            msg(M_FATAL, "Error in cryptoapicert: Unknown key and no default sign operation to fallback on");
-            return -1;
-        }
-    }
-
-    if (!EVP_PKEY_CTX_get_rsa_padding(ctx, &padding))
-    {
-        padding = RSA_PKCS1_PADDING; /* Default padding for RSA */
-    }
-
-    if (EVP_PKEY_CTX_get_signature_md(ctx, &md))
-    {
-        hashlen = EVP_MD_size(md);
-        alg = cng_hash_algo(EVP_MD_type(md));
-
-        /*
-         * alg == NULL indicates legacy MD5+SHA1 hash, else alg should be a valid
-         * digest algorithm.
-         */
-        if (alg && wcscmp(alg, L"UNKNOWN") == 0)
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: Unknown hash algorithm <%d>", EVP_MD_type(md));
-            return -1;
-        }
-    }
-    else
-    {
-        msg(M_NONFATAL, "Error in cryptoapicert: could not determine the signature digest algorithm");
-        return -1;
-    }
-
-    if (tbslen != (size_t)hashlen)
-    {
-        msg(M_NONFATAL, "Error in cryptoapicert: data size does not match hash");
-        return -1;
-    }
-
-    /* If padding is PSS, determine parameters to pass to CNG */
-    if (padding == RSA_PKCS1_PSS_PADDING)
-    {
-        /*
-         * Ensure the digest type for signature and mask generation match.
-         * In CNG there is no option to specify separate hash functions for
-         * the two, but OpenSSL supports it. However, I have not seen the
-         * two being different in practice. Also the recommended practice is
-         * to use the same for both (rfc 8017 sec 8.1).
-         */
-        EVP_MD *mgf1md;
-        if (!EVP_PKEY_CTX_get_rsa_mgf1_md(ctx, &mgf1md)
-            || EVP_MD_type(mgf1md) != EVP_MD_type(md))
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: Unknown MGF1 digest type or does"
-                " not match the signature digest type.");
-            return -1;
-        }
-
-        if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, &saltlen))
-        {
-            msg(M_WARN|M_INFO, "cryptoapicert: unable to get the salt length from context."
-                " Using the default value.");
-            saltlen = -1;
-        }
-
-        /*
-         * In OpenSSL saltlen = -1 indicates to use the size of the digest as
-         * size of the salt. A value of -2 or -3 indicates maximum salt length
-         * that will fit. See RSA_padding_add_PKCS1_PSS_mgf1() of OpenSSL.
-         */
-        if (saltlen == -1)
-        {
-            saltlen = hashlen;
-        }
-        else if (saltlen < 0)
-        {
-            const RSA *rsa = EVP_PKEY_get0_RSA(pkey);
-            saltlen = RSA_size(rsa) - hashlen - 2; /* max salt length for RSASSA-PSS */
-            if (RSA_bits(rsa) &0x7) /* number of bits in the key not a multiple of 8 */
-            {
-                saltlen--;
-            }
-        }
-
-        if (saltlen < 0)
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: invalid salt length (%d). Digest too large for keysize?", saltlen);
-            return -1;
-        }
-        msg(D_LOW, "cryptoapicert: PSS padding using saltlen = %d", saltlen);
-    }
-
-    msg(D_LOW, "cryptoapicert: calling priv_enc_CNG with alg = %ls", alg);
-    *siglen = priv_enc_CNG(cd, alg, tbs, (int)tbslen, sig, (int)*siglen,
-                           cng_padding_type(padding), (DWORD)saltlen);
-
-    return (*siglen == 0) ? 0 : 1;
-}
-
-static int
-ssl_ctx_set_rsakey(SSL_CTX *ssl_ctx, CAPI_DATA *cd, EVP_PKEY *pkey)
-{
-    RSA *rsa = NULL;
-    RSA_METHOD *my_rsa_method = NULL;
-    EVP_PKEY *privkey = NULL;
-    int ret = 0;
-
-    my_rsa_method = RSA_meth_new("Microsoft Cryptography API RSA Method",
-                                 RSA_METHOD_FLAG_NO_CHECK);
-    check_malloc_return(my_rsa_method);
-    RSA_meth_set_finish(my_rsa_method, rsa_finish); /* we use this callback to cleanup CAPI_DATA */
-    RSA_meth_set0_app_data(my_rsa_method, cd);
-
-    /* pmethod is global -- initialize only if NULL */
-    if (!pmethod)
-    {
-        pmethod = EVP_PKEY_meth_new(EVP_PKEY_RSA, 0);
-        if (!pmethod)
-        {
-            msg(M_NONFATAL, "Error in cryptoapicert: failed to create EVP_PKEY_METHOD");
-            return 0;
-        }
-        const EVP_PKEY_METHOD *default_pmethod = EVP_PKEY_meth_find(EVP_PKEY_RSA);
-        EVP_PKEY_meth_copy(pmethod, default_pmethod);
-
-        /* We want to override only sign_init() and sign() */
-        EVP_PKEY_meth_set_sign(pmethod, pkey_rsa_sign_init, pkey_rsa_sign);
-        EVP_PKEY_meth_add0(pmethod);
-
-        /* Keep a copy of the default sign and sign_init methods */
-
-        EVP_PKEY_meth_get_sign(default_pmethod, &default_pkey_sign_init,
-                               &default_pkey_sign);
-    }
-
-    rsa = EVP_PKEY_get1_RSA(pkey);
-
-    RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY);
-    if (!RSA_set_method(rsa, my_rsa_method))
-    {
-        goto cleanup;
-    }
-    my_rsa_method = NULL;  /* we do not want to free it in cleanup */
-    cd->ref_count++;       /* with method, cd gets assigned to the key as well */
-
-    privkey = EVP_PKEY_new();
-    if (!EVP_PKEY_assign_RSA(privkey, rsa))
-    {
-        goto cleanup;
-    }
-    rsa = NULL; /* privkey has taken ownership */
-
-    if (!SSL_CTX_use_PrivateKey(ssl_ctx, privkey))
-    {
-        goto cleanup;
-    }
-    ret = 1;
-
-cleanup:
-    if (rsa)
-    {
-        RSA_free(rsa);
-    }
-    if (my_rsa_method)
-    {
-        RSA_meth_free(my_rsa_method);
-    }
-    if (privkey)
-    {
-        EVP_PKEY_free(privkey);
-    }
-
-    return ret;
-}
-
-#else /* HAVE_XKEY_PROVIDER */
-
 /** Sign hash in tbs using EC key in cd and NCryptSignHash */
 static int
 xkey_cng_ec_sign(CAPI_DATA *cd, unsigned char *sig, size_t *siglen, const unsigned char *tbs,
@@ -937,8 +433,6 @@ xkey_cng_sign(void *handle, unsigned char *sig, size_t *siglen, const unsigned c
     }
 }
 
-#endif /* HAVE_XKEY_PROVIDER */
-
 static char *
 get_cert_name(const CERT_CONTEXT *cc, struct gc_arena *gc)
 {
@@ -1043,45 +537,16 @@ SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
     X509_free(cert);
     cert = NULL;
 
-#ifdef HAVE_XKEY_PROVIDER
-
     EVP_PKEY *privkey = xkey_load_generic_key(tls_libctx, cd, pkey,
                                               xkey_cng_sign, (XKEY_PRIVKEY_FREE_fn *) CAPI_DATA_free);
     SSL_CTX_use_PrivateKey(ssl_ctx, privkey);
     gc_free(&gc);
     return 1; /* do not free cd -- its kept by xkey provider */
 
-#else  /* ifdef HAVE_XKEY_PROVIDER */
-
-    if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
-    {
-        if (!ssl_ctx_set_rsakey(ssl_ctx, cd, pkey))
-        {
-            goto err;
-        }
-    }
-    else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC)
-    {
-        if (!ssl_ctx_set_eckey(ssl_ctx, cd, pkey))
-        {
-            goto err;
-        }
-    }
-    else
-    {
-        msg(M_WARN|M_INFO, "WARNING: cryptoapicert: key type <%d> not supported",
-            EVP_PKEY_id(pkey));
-        goto err;
-    }
-    CAPI_DATA_free(cd); /* this will do a ref_count-- */
-    gc_free(gc);
-    return 1;
-
-#endif /* HAVE_XKEY_PROVIDER */
-
 err:
     CAPI_DATA_free(cd);
     gc_free(&gc);
     return 0;
 }
+#endif  /* HAVE_XKEY_PROVIDER */
 #endif                          /* _WIN32 */
src/openvpn/options.c +1 -1
index f24af3d7..e18b3b39 100644
@@ -8864,7 +8864,7 @@ add_option(struct options *options,
             listend->next = newlist;
         }
     }
-#ifdef ENABLE_CRYPTOAPI
+#if defined(ENABLE_CRYPTOAPI) && defined(HAVE_XKEY_PROVIDER)
     else if (streq(p[0], "cryptoapicert") && p[1] && !p[2])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
Signature · 1 line
2.34.1
Acked-by on v2 3/4
#10 lore raw

[Openvpn-devel] [PATCH applied] Re: cryptoapi.c: remove pre OpenSSL-3.01 support

This patch looks large and complex, but all it does do is "rip out code parts that are inside #ifndef HAVE_XKEY_PROVIDER" (plus add a message as replacement). This is a welcome change, and in line with what we discussed some time ago regarding OpenSSL support for windows builds.

Applying this to the release/2.6 branch is bending the project rules for "what goes into a release branch" slightly, but we're still in 2.6.*0* and there is lots of cleanup going on - and, really, this is "long term support" since we do not intend to ever provide 2.6.x installers with pre-3.0 OpenSSL libraries, so it's (for all "the project" cares) dead code anyway.

Noter: this does not break compilation with 1.1.1, just remove cryptoapi support (https://github.com/cron2/openvpn/actions/runs/4174981083).

Your patch has been applied to the master and release/2.6 branch.

commit 4b28831e07a357476cb31a6f439becff3dc8c842 (master) commit f3dd050ed8d95001107a841fa7779d09f3efb944 (release/2.6)

Author: Selva Nair
Date:   Wed Feb 1 18:03:40 2023 -0500
     cryptoapi.c: remove pre OpenSSL-3.01 support

     Signed-off-by: Selva Nair <[email protected]...>
     Acked-by: Gert Doering <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg26131.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#11 lore raw

PATCH 4/4 cryptoapi.c: simplify parsing of thumbprint hex string

In reply to [email protected]...

From: Selva Nair <[email protected]...>

---
 src/openvpn/cryptoapi.c | 44 +++++++++++------------------------------
 1 file changed, 12 insertions(+), 32 deletions(-)
src/openvpn/cryptoapi.c +12 -32
index 6ff4fcb5..9fd5aea9 100644
@@ -210,49 +210,29 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
     }
     else if (!strncmp(cert_prop, "THUMB:", 6))
     {
-        const char *p;
-        int i, x = 0;
         find_type = CERT_FIND_HASH;
         find_param = &blob;
 
-        /* skip the tag */
-        cert_prop += 6;
-        for (p = cert_prop, i = 0; *p && i < sizeof(hash); i++)
+        int i = 0;
+
+        for (const char *p = cert_prop + 6; *p && i < sizeof(hash); p += 2)
         {
-            if (*p >= '0' && *p <= '9')
-            {
-                x = (*p - '0') << 4;
-            }
-            else if (*p >= 'A' && *p <= 'F')
+            /* skip spaces */
+            while (*p == ' ')
             {
-                x = (*p - 'A' + 10) << 4;
+                p++;
             }
-            else if (*p >= 'a' && *p <= 'f')
+            if (!*p) /* ending with spaces is not an error */
             {
-                x = (*p - 'a' + 10) << 4;
+                break;
             }
-            if (!*++p)  /* unexpected end of string */
+
+            if (!isxdigit(p[0]) || !isxdigit(p[1])
+                || sscanf(p, "%2hhx", &hash[i++]) != 1)
             {
-                msg(M_WARN|M_INFO, "WARNING: cryptoapicert: error parsing <THUMB:%s>.", cert_prop);
+                msg(M_WARN|M_INFO, "WARNING: cryptoapicert: error parsing <%s>.", cert_prop);
                 goto out;
             }
-            if (*p >= '0' && *p <= '9')
-            {
-                x += *p - '0';
-            }
-            else if (*p >= 'A' && *p <= 'F')
-            {
-                x += *p - 'A' + 10;
-            }
-            else if (*p >= 'a' && *p <= 'f')
-            {
-                x += *p - 'a' + 10;
-            }
-            hash[i] = x;
-            /* skip any space(s) between hex numbers */
-            for (p++; *p && *p == ' '; p++)
-            {
-            }
         }
         blob.cbData = i;
     }
Signature · 1 line
2.34.1
#12 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

src/openvpn/cryptoapi.c find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)

Quoted 12 lines · On Sat, Jan 28, 2023 at 05:34:21PM -0500, [email protected]... wrote:

From: Selva Nair <[email protected]...>

---
 src/openvpn/cryptoapi.c | 44 +++++++++++------------------------------
 1 file changed, 12 insertions(+), 32 deletions(-)
src/openvpn/cryptoapi.c +0 -0
index 6ff4fcb5..9fd5aea9 100644
@@ -210,49 +210,29 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)

This seems to ask for a unittest.

Regards,

Signature · 1 line
  Frank Lichtenheld
author
#13 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

Hi,

Quoted 8 lines · Frank Lichtenheld
Quoted 7 lines · On Sat, Jan 28, 2023 at 05:34:21PM -0500, [email protected]... wrote:

From: Selva Nair <[email protected]...>

---
 src/openvpn/cryptoapi.c | 44 +++++++++++------------------------------
 1 file changed, 12 insertions(+), 32 deletions(-)
Quoted 8 lines

src/openvpn/cryptoapi.c find_certificate_in_store(const char *cert_prop,

Quoted 5 lines
src/openvpn/cryptoapi.c +0 -0
index 6ff4fcb5..9fd5aea9 100644
@@ -210,49 +210,29 @@ find_certificate_in_store(const char *cert_prop,

HCERTSTORE cert_store)

This seems to ask for a unittest.

Would be nice indeed.

But, I've never tried to enable cmocka in our Windows build -- does it work? If it does, I would be inclined to add tests for this as well as some other functions in cryptoapi.c

Regards,

Selva

author
#14 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

Hi

Quoted 19 lines
Quoted 15 lines · Frank Lichtenheld

src/openvpn/cryptoapi.c find_certificate_in_store(const char *cert_prop,

Quoted 12 lines · On Sat, Jan 28, 2023 at 05:34:21PM -0500, [email protected]... wrote:

From: Selva Nair <[email protected]...>

---
 src/openvpn/cryptoapi.c | 44 +++++++++++------------------------------
 1 file changed, 12 insertions(+), 32 deletions(-)
src/openvpn/cryptoapi.c +0 -0
index 6ff4fcb5..9fd5aea9 100644
@@ -210,49 +210,29 @@ find_certificate_in_store(const char *cert_prop,

HCERTSTORE cert_store)

Quoted 9 lines
Quoted 1 line

This seems to ask for a unittest.

Would be nice indeed.

But, I've never tried to enable cmocka in our Windows build -- does it work? If it does, I would be inclined to add tests for this as well as some other functions in cryptoapi.c

Well, replying to myself:

I tried building the unit tests using cmocka for Windows (cross-compiling using mingw-w64 with locally built cmocka). Unfortunately, none of the tests could be built out of the box because of missing dependencies, so I guess no one is running these tests on Windows.

Good news is that I could get provider_testdriver to build and run on Windows with minor tweaks and a test for this patch could be easily written too.

I can follow up with a test patch, but wonder whether it's worth spending time on if no one else is building these tests for Windows.

Regards,

Selva

#15 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

Quoted 8 lines

Well, replying to myself:

I tried building the unit tests using cmocka for Windows (cross-compiling using mingw-w64 with locally built cmocka). Unfortunately, none of the tests could be built out of the box because of missing dependencies, so I guess no one is running these tests on Windows.

Good news is that I could get provider_testdriver to build and run on Windows with minor tweaks and a test for this patch could be easily written too.

I can follow up with a test patch, but wonder whether it's worth spending time on if no one else is building these tests for Windows.

I have a cmake build file for OpenVPN that actually builds part of the unit tests ("test_packet_id" "test_crypto" "test_ncp" "test_auth_token" "test_misc" "test_buffer" "test_provider" "test_pkt") and run them in the Github actions pipeline. But the cmake stuff is more "work in progress" and the general consensus was to stick with the autoconf approach.

I looked into building the test binaries as part of the normal MSVC build but gave up on trying to figure out how to deal with MSVC and their solutions, especially since you can nowadays just point it at a CmakeLists.txt and it will pick that up just fine.

If you want to take a look:

Cmake build file: https://github.com/schwabe/openvpn/blob/bloom/CMakeLists.txt

Running tests as part of GHA: https://github.com/schwabe/openvpn/blob/bloom/.github/workflows/build.yaml#L561

Arne

author
#16 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

Quoted 28 lines · Arne Schwabe
Quoted 9 lines

Well, replying to myself:

I tried building the unit tests using cmocka for Windows (cross-compiling using mingw-w64 with locally built cmocka). Unfortunately, none of the tests could be built out of the box because of missing dependencies, so I guess no one is running these tests on Windows.

Quoted 6 lines

Good news is that I could get provider_testdriver to build and run on Windows with minor tweaks and a test for this patch could be easily written too.

I can follow up with a test patch, but wonder whether it's worth spending time on if no one else is building these tests for Windows.

I have a cmake build file for OpenVPN that actually builds part of the unit tests ("test_packet_id" "test_crypto" "test_ncp" "test_auth_token" "test_misc" "test_buffer" "test_provider" "test_pkt") and run them in the Github actions pipeline. But the cmake stuff is more "work in progress" and the general consensus was to stick with the autoconf approach.

I looked into building the test binaries as part of the normal MSVC build but gave up on trying to figure out how to deal with MSVC and their solutions, especially since you can nowadays just point it at a CmakeLists.txt and it will pick that up just fine.

Quoted 8 lines

If you want to take a look:

Cmake build file:
https://github.com/schwabe/openvpn/blob/bloom/CMakeLists.txt

Running tests as part of GHA:

https://github.com/schwabe/openvpn/blob/bloom/.github/workflows/build.yaml#L561

Thanks a lot for that.

By adding win32-util.c and -lws2_32 where required, I can now build almost all tests using the autotools framework --- cmocka had to be cross-compiled using cmake which is a pain.

I do not particularly like cmake though it's convenient for Windows MSVC build, so sticking to autoconf/automake for now. Unless the "consensus" is to move to cmake --- hope not :)

Anyway, this is motivating to write some tests.

Selva

#17 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

Quoted 5 lines

Thanks a lot for that.

By adding win32-util.c and -lws2_32 where required, I can now build almost all tests using the autotools framework --- cmocka had to be cross-compiled using cmake which is a pain. I do not particularly like cmake though it's convenient for Windows MSVC build, so sticking to autoconf/automake for now. Unless the "consensus" is to move to cmake --- hope not :)

No. Other OpenVPN contributers have spoken out against CMake, so I never bothered to clean it up, so that the current cmake file is a mixture of clean stuff and hacks. It is pretty useful for me for doing remote build/debugging with Clion under macOS/Linux and also when I use Visual Studio or Clion under Windows. Even though I think that adding Cmake as unsupported build method is a good idea. This would allow others to have the same option/advantages like me that prefer cmake to autoconf/automake, this also does not seem to have a consensus, so I just maintain it for myself in my branch.

Arne

#18 lore raw

Re: [Openvpn-devel] [PATCH 4/4] cryptoapi.c: simplify parsing of thumbprint hex string

Hi,

Quoted 5 lines · Arne Schwabe

Even though I think that adding Cmake as
unsupported build method is a good idea. This would allow others to have the same option/advantages like me that prefer cmake to autoconf/automake, this also does not seem to have a consensus, so I just maintain it for myself in my branch.

I do not object to having "something cmake based" available for those that find it beneficial. I just do not want to move over completely, as I think on unix/linux, autoconf does a good job and *for me* cmake just adds complications.

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#19 lore raw

PATCH v2 4/4 cryptoapi.c: simplify parsing of thumbprint hex string

In reply to [email protected]...

From: Selva Nair <[email protected]...>

v2: Moved the "parse_hexstring" chunk to a function for clarity and to permit unit-testing.

A test is submitted as a follow up patch.

---
 src/openvpn/cryptoapi.c | 77 ++++++++++++++++++++---------------------
 1 file changed, 37 insertions(+), 40 deletions(-)
src/openvpn/cryptoapi.c +37 -40
index eafef1b1..136c6ffc 100644
@@ -180,6 +180,39 @@ err:
     return NULL;
 }
 
+/**
+ * Parse a hex string with optional embedded spaces into
+ * a byte array.
+ * @param p         pointer to the input string
+ * @param arr       on output contains the parsed bytes
+ * @param capacity  capacity of the byte array arr
+ * @returns the number of bytes parsed or 0 on error
+ */
+int
+parse_hexstring(const char *p, unsigned char *arr, size_t capacity)
+{
+    int i = 0;
+    for ( ; *p && i < capacity; p += 2)
+    {
+        /* skip spaces */
+        while (*p == ' ')
+        {
+            p++;
+        }
+        if (!*p) /* ending with spaces is not an error */
+        {
+            break;
+        }
+
+        if (!isxdigit(p[0]) || !isxdigit(p[1])
+            || sscanf(p, "%2hhx", &arr[i++]) != 1)
+        {
+            return 0;
+        }
+    }
+    return i;
+}
+
 static const CERT_CONTEXT *
 find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
 {
@@ -210,51 +243,15 @@ find_certificate_in_store(const char *cert_prop, HCERTSTORE cert_store)
     }
     else if (!strncmp(cert_prop, "THUMB:", 6))
     {
-        const char *p;
-        int i, x = 0;
         find_type = CERT_FIND_HASH;
         find_param = &blob;
 
-        /* skip the tag */
-        cert_prop += 6;
-        for (p = cert_prop, i = 0; *p && i < sizeof(hash); i++)
+        blob.cbData = parse_hexstring(cert_prop + 6, hash, sizeof(hash));
+        if (blob.cbData == 0)
         {
-            if (*p >= '0' && *p <= '9')
-            {
-                x = (*p - '0') << 4;
-            }
-            else if (*p >= 'A' && *p <= 'F')
-            {
-                x = (*p - 'A' + 10) << 4;
-            }
-            else if (*p >= 'a' && *p <= 'f')
-            {
-                x = (*p - 'a' + 10) << 4;
-            }
-            if (!*++p)  /* unexpected end of string */
-            {
-                msg(M_WARN|M_INFO, "WARNING: cryptoapicert: error parsing <THUMB:%s>.", cert_prop);
-                goto out;
-            }
-            if (*p >= '0' && *p <= '9')
-            {
-                x += *p - '0';
-            }
-            else if (*p >= 'A' && *p <= 'F')
-            {
-                x += *p - 'A' + 10;
-            }
-            else if (*p >= 'a' && *p <= 'f')
-            {
-                x += *p - 'a' + 10;
-            }
-            hash[i] = x;
-            /* skip any space(s) between hex numbers */
-            for (p++; *p && *p == ' '; p++)
-            {
-            }
+            msg(M_WARN|M_INFO, "WARNING: cryptoapicert: error parsing <%s>.", cert_prop);
+            goto out;
         }
-        blob.cbData = i;
     }
     else
     {
Signature · 1 line
2.34.1
Acked-by on v2 4/4
#20 lore raw

[Openvpn-devel] [PATCH applied] Re: cryptoapi.c: simplify parsing of thumbprint hex string

Patch looks reasonable, and compiles fine :-) - looking forward to merge the unit test patch for it.

There is a similar code piece in options.c::parse_hash_fingerprint(), but it has slightly different semantics wrt length and separators, so merging these (my initial thought) would lead to a typical OpenVPN blabla_ex() function 3 times as long with 10 arguments... so, no, this is simple enough (and while sscanf() might be inefficient, it's easier to read than the old the character manipulations, and for "once per connection", readability trumps "a few microseconds saved")

Your patch has been applied to the master and release/2.6 branch.

commit 94bbe98b2b135b2da74b694358e6c94c1defbffd (master) commit 5a70f5025a3f1aee53b531b2e7713dd99fa175bb (release/2.6)

Author: Selva Nair
Date:   Fri Feb 3 19:43:22 2023 -0500
     cryptoapi.c: simplify parsing of thumbprint hex string

     Signed-off-by: Selva Nair <[email protected]...>
     Acked-by: Gert Doering <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg26146.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering