Re: Remove from mailing list

2021-05-28 Thread Matthias Apitz
El día sábado, mayo 29, 2021 a las 01:02:52a. m. -0400, Amber Shepherd escribió:

> Hi,
> Can you please let me know what I need to do in order to unsubscribe
> from this list?

Look into the header lines of the mails from the list for List-Unsubscribe:

matthias
-- 
Matthias Apitz, ✉ g...@unixarea.de, http://www.unixarea.de/ +49-176-38902045
Public GnuPG key: http://www.unixarea.de/key.pub
¡Con Cuba no te metas!  «»  Don't mess with Cuba!  «»  Leg Dich nicht mit Kuba 
an!
http://www.cubadebate.cu/noticias/2020/12/25/en-video-con-cuba-no-te-metas/


Remove from mailing list

2021-05-28 Thread Amber Shepherd
Hi,
Can you please let me know what I need to do in order to unsubscribe
from this list?

Thank you
Amber shepherd


Re: X509_verify_cert() rejects all trusted certs with "default" X509_VERIFY_PARAM

2021-05-28 Thread Viktor Dukhovni
On Fri, May 28, 2021 at 01:30:14PM +0200, Graham Leggett via openssl-users 
wrote:

> While running code that calls X509_verify_cert(), the trusted root
> certificates (“BEGIN TRUSTED CERTIFICATE”) loaded into the
> verification are failing verification with “certificate rejected”:

Typically, certififcates in the OpenSSL trust stores used by most users
aren't wrapped up as "TRUSTED CERTIFICATES" that are annotated with
explicit trust EKUs.  What sort of trust store are you using that has
these annotations?

Can you be more explicit about the "default" X509_VERIFY_PARAM?  Are you
referring to the default "purpose"?

If your root is CA is tagged with a restricted set of trust EKUs,
verification will only succeed for a purpose that matches one of
those trust EKUs.

> for (i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) {
> ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i);
> int nid = OBJ_obj2nid(obj);
> 
> if (nid == id || (nid == NID_anyExtendedKeyUsage &&
> (flags & X509_TRUST_OK_ANY_EKU)))
> return X509_TRUST_TRUSTED;
> }
> 
> We iterate through the above loop twice for our root certificate, once with a 
> nid of:
> 
> (lldb) print OBJ_nid2sn(nid)
> (const char *) $2 = 0x00010067b13d “emailProtection"
> 
> and a second time with a nid of:
> 
> (lldb) print OBJ_nid2sn(nid)
> (const char *) $3 = 0x00010067b0d2 “serverAuth"

Looks like your CA cert is annotated with "emailProtection" and
"serverAuth", and so can only be used to verify TLS server and
SMIME certficates, which don't match the "default" (unrestricted)
purpose.

> Neither “emailProtection” nor “serverAuth” are equal to
> “anyExtendedKeyUsage”, and so we drop to this line which triggers the
> rejection of our root certificate:

Specify a matching purpose, or use a root CA that is not annotated
with a limited set of trust EKUs.

> Can anyone explain why openssl would reject this certificate?
> 
> I am using the “default” X509_VERIFY_PARAM.

If you're using verify(1), you can set the purpose via the
"-purpose" option to one of:

- any
- crlsign
- nssslserver
- ocsphelper
- smimeencrypt
- smimesign
- sslclient
- sslserver
- timestampsign

> Alas the source code apps/verify.c makes no attempt to set the trust
> parameter,

This is set indirectly via the "-purpose" option.

-- 
Viktor.


FW: X509_verify_cert() rejects all trusted certs with "default" X509_VERIFY_PARAM

2021-05-28 Thread Michael Wojcik
Just realized I sent this directly to Graham instead of to the list.

-Original Message-
From: Michael Wojcik
Sent: Friday, 28 May, 2021 09:37
To: 'Graham Leggett' 
Subject: RE: X509_verify_cert() rejects all trusted certs with "default" 
X509_VERIFY_PARAM

> From: openssl-users  On Behalf Of Graham
> Leggett via openssl-users
> Sent: Friday, 28 May, 2021 06:30
>
> I am lost - I can fully understand what the code is doing, but I can’t see
> why openssl only trusts certs with “anyExtendedKeyUsage”.

Interesting. I wondered if this might be enforcing some RFC 5280 or CA / 
Browser Forum Baseline Requirements rule.

5280 4.2.1.12 says:

   In general, this
   extension will appear only in end entity certificates.

and

   If the extension is present, then the certificate MUST only be used
   for one of the purposes indicated.

Your certificate has serverAuth and emailProtection, yes? So it cannot be used 
to sign other certificates, and OpenSSL is correct as far as that goes. 5280 
doesn't define an EKU for signing certificates; so perhaps the intent of the 
OpenSSL code is "if EKU is present, this probably can't be used as a CA cert 
without violating 5280, but I'll look for this 'any' usage just in case and 
allow that".

The errata for 5280 and the RFCs which update it do not appear to affect this 
section.


The CA/BF BR 7.1.2.1, the part of the certificate profile that covers root 
certificates, says:

   d. extKeyUsage
  This extension MUST NOT be present.

Now, there's no particular reason for OpenSSL to enforce CA/BF BR, and good 
reason for it not to (the "CA" part refers to commercial CAs, and not all 
clients are browsers). But it's more evidence that root certificates, at least, 
should not have extKeyUsage because browsers can correctly reject those.

The CA/BF profile is more complicated regarding what it calls "subordinate" 
certificates, aka intermediates, so for non-root trust anchors there are cases 
where you can get away with extKeyUsage. But a good rule is "only put 
extKeyUsage on entity [leaf] certificates".


So that really leaves us with the question "do we want OpenSSL enforcing the 
extKeyUsage rules of RFC 5280?". And I'm tempted to say yes. In principle, the 
basicConstraints CA flag and the keyUsage keyCertSign option should suffice for 
this, but defense in depth, and in cryptographic protocols consistency is 
extremely important.

--
Michael Wojcik


ODP: CSR creation using pkcs11 dynamic engine

2021-05-28 Thread Piotr Lobacz
Hi Selva,
i have found the cause of the problem. It is the HasNoPrivateKey function which 
is in dotnet OpenSsl 
./src/Native/Unix/System.Security.Cryptography.Native/pal_rsa.c implementation. 
The crux of the problem is in these lines:

// The method has descibed itself as having the private key external to the 
structure.
// That doesn't mean it's actually present, but we can't tell.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
if (RSA_meth_get_flags((RSA_METHOD*)meth) & RSA_FLAG_EXT_PKEY)
#pragma clang diagnostic pop
{
return 0;
}

For some reason i suspect that i do not have this RSA_FLAG_EXT_PKEY flag set. 
Btw. when i am calling ENGINE_load_private_key method, the arguments i'm 
passing are the engine and the key. Both ui_method and callback_data are passed 
as NULLs. I talked with guys from dotnet in here 
https://github.com/dotnet/runtime/issues/53345 and i need to check RSA 
flags.But the thing that puzzles me is that shouldn't that flag be inserted by 
the engine during the call of ENGINE_load_private_key?

BR
Piotr

Od: Selva Nair 
Wysłane: piątek, 28 maja 2021 20:47
Do: Piotr Lobacz 
DW: openssl-users@openssl.org 
Temat: Re: CSR creation using pkcs11 dynamic engine

Hi,

On Fri, May 28, 2021 at 1:44 PM Piotr Lobacz  wrote:
>
> Ok, i have found out that dotnet OpenSsl library has it's own code for 
> verification is key private. For this it needs the whole data of private key 
> from which this method:
>
> static int HasNoPrivateKey(RSA* rsa)
>
>  which is in ./src/Native/Unix/System.Security.Cryptography.Native/pal_rsa.c 
> of dotnet verifies occurence of all private parameters. Unfortunately from 
> what i know private keys are not extractable from tokens because of 
> CKA_EXTRACTABLE=false parameter.
>
> Correct me if i'm wrong but from what i know about openssl, when i'm 
> switching to a closed engine the whole cryptography is being made by the 
> engine module. I think that there should be some other method verifing if key 
> is private. Maybe somebody could give me a hint?

Its not verifying, but signing operation that is failing. This sounds
like something wrong in the way you are using the dotnet interface or
possibly a bug in (or limitation of) that implementation itself. Like
its not meant to be used when keys are "external".  I have no idea
having never used C#.

But you are right, when the private key is loaded through the pkcs11
engine the key is external (can stay non-extractable), and the signing
operation gets delegated to the engine. Are you sure that the pkey
returned by the ENGINE_get_private_key() and rsa handle generated from
that pkey are valid? I see no error checks in your code unless dotnet
will automatically trigger exceptions on error.

You may get more relevant help in the dotnet community.


Selva
[https://softgent.com/wp-content/uploads/2020/01/Zasob-14.png]

Softgent Sp. z o.o., Budowlanych 31d, 80-298 Gdansk, POLAND

KRS: 674406, NIP: 9581679801, REGON: 367090912

www.softgent.com

Sąd Rejonowy Gdańsk-Północ w Gdańsku, VII Wydział Gospodarczy Krajowego 
Rejestru Sądowego

KRS 674406, Kapitał zakładowy: 25 000,00 zł wpłacony w całości.


Re: CSR creation using pkcs11 dynamic engine

2021-05-28 Thread Selva Nair
Hi,

On Fri, May 28, 2021 at 1:44 PM Piotr Lobacz  wrote:
>
> Ok, i have found out that dotnet OpenSsl library has it's own code for 
> verification is key private. For this it needs the whole data of private key 
> from which this method:
>
> static int HasNoPrivateKey(RSA* rsa)
>
>  which is in ./src/Native/Unix/System.Security.Cryptography.Native/pal_rsa.c 
> of dotnet verifies occurence of all private parameters. Unfortunately from 
> what i know private keys are not extractable from tokens because of 
> CKA_EXTRACTABLE=false parameter.
>
> Correct me if i'm wrong but from what i know about openssl, when i'm 
> switching to a closed engine the whole cryptography is being made by the 
> engine module. I think that there should be some other method verifing if key 
> is private. Maybe somebody could give me a hint?

Its not verifying, but signing operation that is failing. This sounds
like something wrong in the way you are using the dotnet interface or
possibly a bug in (or limitation of) that implementation itself. Like
its not meant to be used when keys are "external".  I have no idea
having never used C#.

But you are right, when the private key is loaded through the pkcs11
engine the key is external (can stay non-extractable), and the signing
operation gets delegated to the engine. Are you sure that the pkey
returned by the ENGINE_get_private_key() and rsa handle generated from
that pkey are valid? I see no error checks in your code unless dotnet
will automatically trigger exceptions on error.

You may get more relevant help in the dotnet community.


Selva


ODP: CSR creation using pkcs11 dynamic engine

2021-05-28 Thread Piotr Lobacz
Ok, i have found out that dotnet OpenSsl library has it's own code for 
verification is key private. For this it needs the whole data of private key 
from which this method:

static int HasNoPrivateKey(RSA* rsa)

 which is in ./src/Native/Unix/System.Security.Cryptography.Native/pal_rsa.c of 
dotnet verifies occurence of all private parameters. Unfortunately from what i 
know private keys are not extractable from tokens because of 
CKA_EXTRACTABLE=false parameter.

Correct me if i'm wrong but from what i know about openssl, when i'm switching 
to a closed engine the whole cryptography is being made by the engine module. I 
think that there should be some other method verifing if key is private. Maybe 
somebody could give me a hint?

BR
Piotr

Od: openssl-users  w imieniu użytkownika 
Piotr Lobacz 
Wysłane: piątek, 28 maja 2021 13:10
Do: openssl-users@openssl.org 
Temat: CSR creation using pkcs11 dynamic engine

Hi all,
i'm trying to generate CSR using C# System.SecurityCryptography.Openssl library 
together with pkcs11 token library. The whole proces for this in command line 
works without any problems. For execution of this process i use command:

openssl req -new -subj '/C=PL/ST=Gdansk/L=Gdansk/CN=softgent.com/' -sha256 
-engine pkcs11 -keyform engine -key 
"pkcs11:token=foo;object=tls;type=private;pin-value=1234567890"

The CSR is being generated and the output is like this:

-BEGIN CERTIFICATE REQUEST-
MIIBADCBqAIBADBGMQswCQYDVQQGEwJQTDEPMA0GA1UECAwGR2RhbnNrMQ8wDQYD
VQQHDAZHZGFuc2sxFTATBgNVBAMMDHNvZnRnZW50LmNvbTBZMBMGByqGSM49AgEG
CCqGSM49AwEHA0IABB7SwUzg8S+3iYNiqGPlidqwCdmuY8MV3RfKDiR5tL/I//Cn
9dGCBAfxTO23gb5pygIXB/qCARYuYLiGpE+tFo+gADAKBggqhkjOPQQDAgNHADBE
AiAI4kDGjeO/V3f7RWe34e00aZAubjLGuIRbxgmQosu7mQIgQDK3Nx22fJn80Cml
t3EQTa6x9oC4RtibFgWCxZ36Wyo=
-END CERTIFICATE REQUEST-

Now i'm trying to do all that programatically. In order to do that i have added 
some OpenSsl C# missing support for the engines and used the 
ENGINE_load_private_key method to retrieve SafeEvpPKeyHandle which is being 
retrieved (i have checked it with changing the key id value). The key which i'm 
using is "label_" + myKeyId i.e. "label_tls". The code looks like this:

public virtual SafeEvpPKeyHandle GetPrivKey(string label)
{
string keyId = "label_" + label;
SafeEvpPKeyHandle pkey = SafeNativeMethods.ENGINE_load_private_key(engine, 
keyId, IntPtr.Zero, IntPtr.Zero);
if(pkey.IsInvalid)
{
 throw new InvalidOperationException("engine: unable to find private 
key with label='{label}'");
}

return pkey;
}

This is being returnin me SafeEvpPKeyHandle. The problem is in calling 
CreateSigningRequest from System.Security.Cryptography.OpenSsl.dll. I have this 
method:

public virtual string GetCSR(SafeEvpPKeyHandle pkey, string ext, 
HashAlgorithmName name)
{
// FIXME: determine key type
RSA rsa = new RSAOpenSsl(pkey);

CertificateRequest req = new CertificateRequest("CN=potato", rsa, name, 
RSASignaturePadding.Pkcs1); // this method is only for RSA key different is for 
EC, DSA etc.
byte[] requestDer = req.CreateSigningRequest();
string requestPem = new string(PemEncoding.Write("CERTIFICATE REQUEST", 
requestDer));
return requestPem;
}

and i'm getting this error:

Unhandled exception. Interop+Crypto+OpenSslCryptographicException: 
error:04075093:rsa routines:RSA_sign:value missing
   at System.Security.Cryptography.RSAOpenSsl.TrySignHash(ReadOnlySpan`1 hash, 
Span`1 destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding 
padding, Boolean allocateSignature, Int32& bytesWritten, Byte[]& signature)
   at System.Security.Cryptography.RSAOpenSsl.SignHash(Byte[] hash, 
HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
   at System.Security.Cryptography.RSA.SignData(Byte[] data, Int32 offset, 
Int32 count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
   at System.Security.Cryptography.RSA.SignData(Byte[] data, HashAlgorithmName 
hashAlgorithm, RSASignaturePadding padding)
   at 
System.Security.Cryptography.X509Certificates.RSAPkcs1X509SignatureGenerator.SignData(Byte[]
 data, HashAlgorithmName hashAlgorithm)
   at 
System.Security.Cryptography.X509Certificates.Pkcs10CertificationRequestInfo.ToPkcs10Request(X509SignatureGenerator
 signatureGenerator, HashAlgorithmName hashAlgorithm)
   at 
System.Security.Cryptography.X509Certificates.CertificateRequest.CreateSigningRequest(X509SignatureGenerator
 signatureGenerator)
   at 
System.Security.Cryptography.X509Certificates.CertificateRequest.CreateSigningRequest()
   at System.Security.Cryptography.Engine.GetCSR(SafeEvpPKeyHandle pkey, String 
ext, HashAlgorithmName name) in 
/home/plobacz/workspace/OpenSsl.DynamicEngine/Engine.cs:line 72
   at Flexgent.Services.CryptoSubsystem.CryptoSubsystem.Configure(String 
config) in 
/home/plobacz/workspace/crypto-subsystem/flexgent/extensions/security/crypto-subsystem/src/CryptoSubsystem.cs:line
 145
   at 

Re: X509_verify_cert() rejects all trusted certs with "default" X509_VERIFY_PARAM

2021-05-28 Thread Tomas Mraz
Hello,

is this a regression when comparing with OpenSSL-1.1.1?

If so, it might be a good idea to report this as an issue to the
project in GitHub.

Tomas

On Fri, 2021-05-28 at 13:30 +0200, Graham Leggett via openssl-users
wrote:
> Hi all,
> 
> While running code that calls X509_verify_cert(), the trusted root
> certificates (“BEGIN TRUSTED CERTIFICATE”) loaded into the
> verification are failing verification with “certificate rejected”:
> 
> 2: CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE: verify
> failed: certificate rejected
> 
> The code path we’re following looks like this:
> 
>   * frame #0: 0x00010060b808 libcrypto.3.dylib`obj_trust(id=910,
> x=0x00010096da70, flags=8) at x509_trs.c:271:17
> frame #1: 0x00010060b672
> libcrypto.3.dylib`X509_check_trust(x=0x00010096da70, id=0,
> flags=0) at x509_trs.c:72:16
> frame #2: 0x00010061207b
> libcrypto.3.dylib`check_trust(ctx=0x0001009fe5b0,
> num_untrusted=2) at x509_vfy.c:776:17
> frame #3: 0x000100610e7e
> libcrypto.3.dylib`build_chain(ctx=0x0001009fe5b0) at
> x509_vfy.c:3124:37
> frame #4: 0x00010060d655
> libcrypto.3.dylib`verify_chain(ctx=0x0001009fe5b0) at
> x509_vfy.c:216:15
> frame #5: 0x00010060d27b
> libcrypto.3.dylib`X509_verify_cert(ctx=0x0001009fe5b0) at
> x509_vfy.c:295:15
> 
> In X509_check_trust() we get to this line of code which appears to
> ask “trust roots with NID_anyExtendedKeyUsage":
> 
> https://github.com/openssl/openssl/blob/master/crypto/x509/x509_trs.c#L72
> 
> int X509_check_trust(X509 *x, int id, int flags)
> {
> X509_TRUST *pt;
> int idx;
> 
> /* We get this as a default value */
> if (id == X509_TRUST_DEFAULT)
> return obj_trust(NID_anyExtendedKeyUsage, x,
>  flags | X509_TRUST_DO_SS_COMPAT);
> 
> This leads us to this code here:
> 
> https://github.com/openssl/openssl/blob/master/crypto/x509/x509_trs.c#L268
> 
> 
> for (i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) {
> ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i);
> int nid = OBJ_obj2nid(obj);
> 
> if (nid == id || (nid == NID_anyExtendedKeyUsage &&
> (flags & X509_TRUST_OK_ANY_EKU)))
> return X509_TRUST_TRUSTED;
> }
> 
> We iterate through the above loop twice for our root certificate,
> once with a nid of:
> 
> (lldb) print OBJ_nid2sn(nid)
> (const char *) $2 = 0x00010067b13d “emailProtection"
> 
> and a second time with a nid of:
> 
> (lldb) print OBJ_nid2sn(nid)
> (const char *) $3 = 0x00010067b0d2 “serverAuth"
> 
> Neither “emailProtection” nor “serverAuth” are equal to
> “anyExtendedKeyUsage”, and so we drop to this line which triggers the
> rejection of our root certificate:
> 
> return X509_TRUST_REJECTED;
> 
> I am lost - I can fully understand what the code is doing, but I
> can’t see why openssl only trusts certs with “anyExtendedKeyUsage”.
> 
> Can anyone explain why openssl would reject this certificate?
> 
> I am using the “default” X509_VERIFY_PARAM.
> 
> Alas the source code apps/verify.c makes no attempt to set the trust
> parameter, and the docs for X509_VERIFY_PARAM_set_trust() say "sets
> the trust setting in param to trust” but doesn’t explain what
> possible values there are for “trust” or their effect.
> 
> Regards,
> Graham
> —
> 
> 
-- 
Tomáš Mráz
No matter how far down the wrong road you've gone, turn back.
  Turkish proverb
[You'll know whether the road is wrong if you carefully listen to your
conscience.]




X509_verify_cert() rejects all trusted certs with "default" X509_VERIFY_PARAM

2021-05-28 Thread Graham Leggett via openssl-users
Hi all,

While running code that calls X509_verify_cert(), the trusted root certificates 
(“BEGIN TRUSTED CERTIFICATE”) loaded into the verification are failing 
verification with “certificate rejected”:

2: CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE: verify failed: 
certificate rejected

The code path we’re following looks like this:

  * frame #0: 0x00010060b808 libcrypto.3.dylib`obj_trust(id=910, 
x=0x00010096da70, flags=8) at x509_trs.c:271:17
frame #1: 0x00010060b672 
libcrypto.3.dylib`X509_check_trust(x=0x00010096da70, id=0, flags=0) at 
x509_trs.c:72:16
frame #2: 0x00010061207b 
libcrypto.3.dylib`check_trust(ctx=0x0001009fe5b0, num_untrusted=2) at 
x509_vfy.c:776:17
frame #3: 0x000100610e7e 
libcrypto.3.dylib`build_chain(ctx=0x0001009fe5b0) at x509_vfy.c:3124:37
frame #4: 0x00010060d655 
libcrypto.3.dylib`verify_chain(ctx=0x0001009fe5b0) at x509_vfy.c:216:15
frame #5: 0x00010060d27b 
libcrypto.3.dylib`X509_verify_cert(ctx=0x0001009fe5b0) at x509_vfy.c:295:15

In X509_check_trust() we get to this line of code which appears to ask “trust 
roots with NID_anyExtendedKeyUsage":

https://github.com/openssl/openssl/blob/master/crypto/x509/x509_trs.c#L72

int X509_check_trust(X509 *x, int id, int flags)
{
X509_TRUST *pt;
int idx;

/* We get this as a default value */
if (id == X509_TRUST_DEFAULT)
return obj_trust(NID_anyExtendedKeyUsage, x,
 flags | X509_TRUST_DO_SS_COMPAT);

This leads us to this code here:

https://github.com/openssl/openssl/blob/master/crypto/x509/x509_trs.c#L268


for (i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) {
ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i);
int nid = OBJ_obj2nid(obj);

if (nid == id || (nid == NID_anyExtendedKeyUsage &&
(flags & X509_TRUST_OK_ANY_EKU)))
return X509_TRUST_TRUSTED;
}

We iterate through the above loop twice for our root certificate, once with a 
nid of:

(lldb) print OBJ_nid2sn(nid)
(const char *) $2 = 0x00010067b13d “emailProtection"

and a second time with a nid of:

(lldb) print OBJ_nid2sn(nid)
(const char *) $3 = 0x00010067b0d2 “serverAuth"

Neither “emailProtection” nor “serverAuth” are equal to “anyExtendedKeyUsage”, 
and so we drop to this line which triggers the rejection of our root 
certificate:

return X509_TRUST_REJECTED;

I am lost - I can fully understand what the code is doing, but I can’t see why 
openssl only trusts certs with “anyExtendedKeyUsage”.

Can anyone explain why openssl would reject this certificate?

I am using the “default” X509_VERIFY_PARAM.

Alas the source code apps/verify.c makes no attempt to set the trust parameter, 
and the docs for X509_VERIFY_PARAM_set_trust() say "sets the trust setting in 
param to trust” but doesn’t explain what possible values there are for “trust” 
or their effect.

Regards,
Graham
—




CSR creation using pkcs11 dynamic engine

2021-05-28 Thread Piotr Lobacz
Hi all,
i'm trying to generate CSR using C# System.SecurityCryptography.Openssl library 
together with pkcs11 token library. The whole proces for this in command line 
works without any problems. For execution of this process i use command:

openssl req -new -subj '/C=PL/ST=Gdansk/L=Gdansk/CN=softgent.com/' -sha256 
-engine pkcs11 -keyform engine -key 
"pkcs11:token=foo;object=tls;type=private;pin-value=1234567890"

The CSR is being generated and the output is like this:

-BEGIN CERTIFICATE REQUEST-
MIIBADCBqAIBADBGMQswCQYDVQQGEwJQTDEPMA0GA1UECAwGR2RhbnNrMQ8wDQYD
VQQHDAZHZGFuc2sxFTATBgNVBAMMDHNvZnRnZW50LmNvbTBZMBMGByqGSM49AgEG
CCqGSM49AwEHA0IABB7SwUzg8S+3iYNiqGPlidqwCdmuY8MV3RfKDiR5tL/I//Cn
9dGCBAfxTO23gb5pygIXB/qCARYuYLiGpE+tFo+gADAKBggqhkjOPQQDAgNHADBE
AiAI4kDGjeO/V3f7RWe34e00aZAubjLGuIRbxgmQosu7mQIgQDK3Nx22fJn80Cml
t3EQTa6x9oC4RtibFgWCxZ36Wyo=
-END CERTIFICATE REQUEST-

Now i'm trying to do all that programatically. In order to do that i have added 
some OpenSsl C# missing support for the engines and used the 
ENGINE_load_private_key method to retrieve SafeEvpPKeyHandle which is being 
retrieved (i have checked it with changing the key id value). The key which i'm 
using is "label_" + myKeyId i.e. "label_tls". The code looks like this:

public virtual SafeEvpPKeyHandle GetPrivKey(string label)
{
string keyId = "label_" + label;
SafeEvpPKeyHandle pkey = SafeNativeMethods.ENGINE_load_private_key(engine, 
keyId, IntPtr.Zero, IntPtr.Zero);
if(pkey.IsInvalid)
{
 throw new InvalidOperationException("engine: unable to find private 
key with label='{label}'");
}

return pkey;
}

This is being returnin me SafeEvpPKeyHandle. The problem is in calling 
CreateSigningRequest from System.Security.Cryptography.OpenSsl.dll. I have this 
method:

public virtual string GetCSR(SafeEvpPKeyHandle pkey, string ext, 
HashAlgorithmName name)
{
// FIXME: determine key type
RSA rsa = new RSAOpenSsl(pkey);

CertificateRequest req = new CertificateRequest("CN=potato", rsa, name, 
RSASignaturePadding.Pkcs1); // this method is only for RSA key different is for 
EC, DSA etc.
byte[] requestDer = req.CreateSigningRequest();
string requestPem = new string(PemEncoding.Write("CERTIFICATE REQUEST", 
requestDer));
return requestPem;
}

and i'm getting this error:

Unhandled exception. Interop+Crypto+OpenSslCryptographicException: 
error:04075093:rsa routines:RSA_sign:value missing
   at System.Security.Cryptography.RSAOpenSsl.TrySignHash(ReadOnlySpan`1 hash, 
Span`1 destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding 
padding, Boolean allocateSignature, Int32& bytesWritten, Byte[]& signature)
   at System.Security.Cryptography.RSAOpenSsl.SignHash(Byte[] hash, 
HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
   at System.Security.Cryptography.RSA.SignData(Byte[] data, Int32 offset, 
Int32 count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
   at System.Security.Cryptography.RSA.SignData(Byte[] data, HashAlgorithmName 
hashAlgorithm, RSASignaturePadding padding)
   at 
System.Security.Cryptography.X509Certificates.RSAPkcs1X509SignatureGenerator.SignData(Byte[]
 data, HashAlgorithmName hashAlgorithm)
   at 
System.Security.Cryptography.X509Certificates.Pkcs10CertificationRequestInfo.ToPkcs10Request(X509SignatureGenerator
 signatureGenerator, HashAlgorithmName hashAlgorithm)
   at 
System.Security.Cryptography.X509Certificates.CertificateRequest.CreateSigningRequest(X509SignatureGenerator
 signatureGenerator)
   at 
System.Security.Cryptography.X509Certificates.CertificateRequest.CreateSigningRequest()
   at System.Security.Cryptography.Engine.GetCSR(SafeEvpPKeyHandle pkey, String 
ext, HashAlgorithmName name) in 
/home/plobacz/workspace/OpenSsl.DynamicEngine/Engine.cs:line 72
   at Flexgent.Services.CryptoSubsystem.CryptoSubsystem.Configure(String 
config) in 
/home/plobacz/workspace/crypto-subsystem/flexgent/extensions/security/crypto-subsystem/src/CryptoSubsystem.cs:line
 145
   at Flexgent.Core.Service.Flexgent.Core.IService.Configure(String config) in 
/home/plobacz/workspace/crypto-subsystem/flexgent/core/library/src/Classes/Service.cs:line
 42
   at Flexgent.Core.ServiceRunner`1.Run(ServiceRunnerOptions options, Action`1 
mainLoop, IEnumerable`1 standaloneConnectInterfaces) in 
/home/plobacz/workspace/crypto-subsystem/flexgent/core/library/src/Classes/ServiceRunner.cs:line
 50
   at 
Flexgent.Services.CryptoSubsystem.CryptoSubsystemMain.<>c.b__1_0(ServiceRunnerOptions
 o) in 
/home/plobacz/workspace/crypto-subsystem/flexgent/extensions/security/crypto-subsystem/src/ServiceMain.cs:line
 20
   at CommandLine.ParserResultExtensions.WithParsed[T](ParserResult`1 result, 
Action`1 action)
   at Flexgent.Services.CryptoSubsystem.CryptoSubsystemMain.Main(String[] args) 
in 
/home/plobacz/workspace/crypto-subsystem/flexgent/extensions/security/crypto-subsystem/src/ServiceMain.cs:line
 19

I suspect that this happens, because the