dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.42k stars 4.75k forks source link

RSACng Decryption throwing Internal Error Occurred exception #97027

Open aminemarckader opened 10 months ago

aminemarckader commented 10 months ago

I'm working with Safenet Token JC and I'm trying to deploy a service that interacts with it using .NET 8 and minimal API, the encryption and decryption processes are being executed using asymmetric keys from a certificates stored in Safenet token and retreived as X509Certificate2 Object; so far I go it to encrypt a string while debugging and decryption is fine but when I deploy the release exe as a service I always get this error

   at System.Security.Cryptography.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan`1 input, AsymmetricPaddingMode paddingMode, Void* paddingInfo, Boolean encrypt)
   at System.Security.Cryptography.RSACng.EncryptOrDecrypt(Byte[] data, RSAEncryptionPadding padding, Boolean encrypt)
   at Program.<<Main>$>g__DecryptDataOaepSha1|0_12(X509Certificate2 cert, Byte[] data)

this is the exact method i'm using to run the decryption process

byte[]? DecryptData(X509Certificate2? cert, byte[] data)
{
    try
    {
            using (RSACng? rSACng = cert?.GetRSAPrivateKey() as RSACng)
        {

            if (rSACng == null)
            {
                return null;
            }
            return rSACng.Decrypt(data, RSAEncryptionPadding.OaepSHA256);
        }
    }
    catch (CryptographicException ce)
    {
        EventLog.WriteEntry("Inside Decrypt try block decryption method RSACNG EXCEPTION CE", ce.Message, EventLogEntryType.Error);
        EventLog.WriteEntry("Inside Decrypt try block decryption method RSACNG EXCEPTION CE", ce.InnerException?.ToString(), EventLogEntryType.Error);
        EventLog.WriteEntry("Inside Decrypt try block decryption method RSACNG EXCEPTION CE", ce.StackTrace, EventLogEntryType.Error);
        throw;
    }
}
ghost commented 10 months ago

Tagging subscribers to this area: @dotnet/area-system-security, @bartonjs, @vcsjones See info in area-owners.md if you want to be subscribed.

Issue Details
I'm working with Safenet Token JC and I'm trying to deploy a service that interacts with it using .NET 8 and minimal API, the encryption and decryption processes are being executed using asymmetric keys from a certificates stored in Safenet token and retreived as X509Certificate2 Object; so far I go it to encrypt a string while debugging and decryption is fine but when I deploy the release exe as a service I always get this error at System.Security.Cryptography.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan`1 input, AsymmetricPaddingMode paddingMode, Void* paddingInfo, Boolean encrypt) at System.Security.Cryptography.RSACng.EncryptOrDecrypt(Byte[] data, RSAEncryptionPadding padding, Boolean encrypt) at Program.<
$>g__DecryptDataOaepSha1|0_12(X509Certificate2 cert, Byte[] data) this is the exact method i'm using to run the decryption process byte[]? DecryptData(X509Certificate2? cert, byte[] data) { try { using (RSACng? rSACng = cert?.GetRSAPrivateKey() as RSACng) { if (rSACng == null) { return null; } return rSACng.Decrypt(data, RSAEncryptionPadding.OaepSHA256); } } catch (CryptographicException ce) { EventLog.WriteEntry("Inside Decrypt try block decryption method RSACNG EXCEPTION CE", ce.Message, EventLogEntryType.Error); EventLog.WriteEntry("Inside Decrypt try block decryption method RSACNG EXCEPTION CE", ce.InnerException?.ToString(), EventLogEntryType.Error); EventLog.WriteEntry("Inside Decrypt try block decryption method RSACNG EXCEPTION CE", ce.StackTrace, EventLogEntryType.Error); throw; } }
Author: aminemarckader
Assignees: -
Labels: `area-System.Security`
Milestone: -
bartonjs commented 10 months ago

When using keys from something other than the builtin software key provider you're at the mercy of whatever error codes the provider-writer felt like offering.

Psychic debugging suggests either a) your service user doesn't have permission to the private key, or b) when running as a service the provider can't figure out a way to PIN prompt.

Try running as the same user account, but in a UI/interactive context; if that works, it's (b). If that fails, try as a different user (which might reveal (a)).

aminemarckader commented 10 months ago

Actually, I'm using Microsoft X509Certificate2 store to lookup the certificate in question than since I'm using .NET8, I had to use RSACng to read the private key, my dilemma is when I run the debug everything works when I run release (I used the administrator account in order to avoid the permissions issues), I've tried windows 10 and 11 same story, if Am at the mercy of the vendor why it works on debug and not on release. I'm willing to share my code with you to reproduce the issue!

vcsjones commented 10 months ago

I had to use RSACng to read the private key

CNG is a Windows feature that is based on Providers. Windows itself comes with a few providers, however Providers can be provided by 3rd parties, and frequently so, when the need arises for a Provider to bridge between a piece of hardware like a token and CNG. Providers are free to do whatever they need to bridge this interface between CNG and the Hardware. Some themselves have something like a sub-Provider, like SmartCards have MiniDrivers.

All that is to say, CNG is doing a lot of things under the covers any there are many failure points.

One place for us to start is to figure out what Provider your certificate and key are actually using. You should be able to do something like this:

RSACng rsa = GetYourKey();
string provider = rsa.Key.Provider.Provider;

If you log the value of provider that should tell us what Provider you are using and where we can better start troubleshooting.

I'm willing to share my code with you to reproduce the issue!

As Jeremy alluded to, this is much more likely to be an issue with the token or CNG Provider. I don't know that sharing the code would help, but if you have a small program that reproduces the issue, it would not hurt to provide one.

ghost commented 10 months ago

This issue has been marked needs-author-action and may be missing some important information.

aminemarckader commented 10 months ago

the provider is eToken Base Cryptographic Provider. My main issue is not the provider, my issue is when Ideploy the service and even change the service account to my own administrator account I can't access the private key to decrypt the data. When I run the application in debug mode it works fine, but when I run production RELEASE I get the error.

jeffhandley commented 2 weeks ago

@bartonjs Do you suspect this is an issue with the provider itself?

@aminemarckader I know a lot of time has passed on this issue; did you find a way past it already?

bartonjs commented 1 week ago

Either an issue with the provider, or with its permissions model, or something. And I definitely can't explain why it would change between debug and release (unless they are being launched from the IDE and have different launch profiles)

aminemarckader commented 1 week ago

Good evening everyone, thanks a lot for your efforts. Actually, the permissions.inf file has been modified with every permission possible. I made the service interactive, I've logged in with administrator account and for the profiles, that route I didn't pursue because I didn't touch any profile what so ever. I can provide the code if it helps. The real problem is with decrypt method encryption works perfectly but the decryption throws the issue

On Mon, Nov 11, 2024, 7:39 PM Jeremy Barton @.***> wrote:

Either an issue with the provider, or with its permissions model, or something. And I definitely can't explain why it would change between debug and release (unless they are being launched from the IDE and have different launch profiles)

— Reply to this email directly, view it on GitHub https://github.com/dotnet/runtime/issues/97027#issuecomment-2468810303, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHXTMMBUK4UCT5UAHM52NTL2AD2XDAVCNFSM6AAAAABRPTGHXKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINRYHAYTAMZQGM . You are receiving this because you were mentioned.Message ID: @.***>