Code Monkey home page Code Monkey logo

cryptopro / corefx Goto Github PK

View Code? Open in Web Editor NEW

This project forked from dotnet/corefx

27.0 27.0 8.0 471.3 MB

This repo contains the .NET Core foundational libraries, called CoreFX. It includes classes for collections, file systems, console, XML, async and many others. We welcome contributions.

Home Page: https://github.com/dotnet/core

License: MIT License

Batchfile 0.01% Shell 0.08% CMake 0.04% PowerShell 0.11% C# 96.02% HTML 0.01% C 2.05% C++ 0.01% Python 0.01% Makefile 0.01% DIGITAL Command Language 0.01% Roff 0.01% Perl 0.01% 1C Enterprise 0.15% OpenEdge ABL 0.07% XSLT 0.27% TSQL 0.05% Visual Basic .NET 1.12% ASP.NET 0.01%

corefx's People

Contributors

ahsonkhan avatar anipik avatar bartdesmet avatar bartonjs avatar chcosta avatar danmoseley avatar davidsh avatar dotnet-bot avatar dotnet-maestro-bot avatar dotnet-maestro[bot] avatar ellismg avatar ericstj avatar hughbe avatar jeremykuhne avatar jkotas avatar jonhanna avatar joperezr avatar justinvp avatar krwq avatar mattgal avatar mellinoe avatar mmitche avatar nguerrera avatar safern avatar shmao avatar stephentoub avatar tarekgh avatar viktorhofer avatar vsadov avatar weshaggard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

corefx's Issues

Избавиться от createdump в self-contained сборках на Linux

При dotnet publish в выходные файлы попадает утилита createdump. Это не устраивает регулятора, т.к. в в дистрибутиве не должно быть никаких средств отладки.
Простое удаление приводит в ошибке. Аналогичная проблема есть и в исходном .NET Core (dotnet/runtime#43716).
От этой утилиты необходимо избавиться.

Сборка не работает на Windows Server + IIS

Добрый день!
Пытаюсь запустить WebAPI c CoreFx на Windows Server 2012R2 + IIS. Возникает вот такая ошибка:

System.MissingMethodException: Method not found: 'System.Security.Cryptography.HashAlgorithmName System.Security.Cryptography.HashAlgorithmName.get_Gost3411_2012_256()'.\r\n 
  at Internal.Cryptography.PkcsHelpers.GetDigestAlgorithm(String oidValue, Boolean forVerification)\r\n   at System.Security.Cryptography.Pkcs.SignerInfo.GetDigestAlgorithm() in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignerInfo.cs:line 737\r\n  
 at System.Security.Cryptography.Pkcs.SignerInfo.PrepareDigest(Boolean compatMode) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignerInfo.cs:line 510\r\n 
  at System.Security.Cryptography.Pkcs.SignerInfo.VerifySignature(CmsSignature signatureProcessor, X509Certificate2 certificate, Boolean compatMode) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignerInfo.cs:line 698\r\n  
 at System.Security.Cryptography.Pkcs.SignerInfo.Verify(X509Certificate2Collection extraStore, X509Certificate2 certificate, Boolean verifySignatureOnly) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignerInfo.cs:line 647\r\n
  at System.Security.Cryptography.Pkcs.SignerInfo.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignerInfo.cs:line 415\r\n 
  at System.Security.Cryptography.Pkcs.SignedCms.CheckSignatures(SignerInfoCollection signers, X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignedCms.cs:line 595\r\n 
  at System.Security.Cryptography.Pkcs.SignedCms.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignedCms.cs:line 578\r\n  
 at System.Security.Cryptography.Pkcs.SignedCms.CheckSignature(Boolean verifySignatureOnly) in C:\\projects\\corefx\\src\\System.Security.Cryptography.Pkcs\\src\\System\\Security\\Cryptography\\Pkcs\\SignedCms.cs:line 569\r\n 

На локальной машине (Windows 10) всё работает.
На сервере устанавливал SDK и Hosting пакеты - не помогло. Даже полностью вычищал все установленные версии Net Core.
Что-то можно сделать?

Неправильно работает AsnEncodedData.Format на Linux

Эта проблема .NET CORE не относится к ГОСТ криптографии, но посмотрите пожалуйста - вдруг удастся легко исправить.

Метод AsnEncodedData.Format на linux работает неправильно.
Он возвращает не полный текст описания расширения, а только первую строку из него.
Видимо, где-то косяк с p/invoke, там через вызов метода из openssl все делается.
При этом сам openssl из командной строки показывает все правильно.
Пример вызова : Programs.cs.txt
Programs.cs.txt

Расширения 1.3.6.1.5.5.7.1.1, 2.5.29.32 и 2.5.29.31 нормально выводятся на windows (win.txt),
на linux через openssl x509 -inform der -in cert.cer -noout -text (openssl.txt)
и обрезаются на linux при выводе через .net core (linux.txt).
win.txt
linux.txt
openssl.txt

Кириллица в именах контейнеров (+cms)

Здравствуйте.
При вычислении подписи на некоторых сертификатах получаем ошибку

   at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
   at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.get_SafeProvHandle()
   at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.get_SafeKeyHandle()
   at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.GetKeyPair()
   at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider..ctor(CspParameters parameters)
   at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKey[T](X509Certificate2 certificate, Boolean silent, Boolean preferNCrypt)
   at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKeyForSigning[T](X509Certificate2 certificate, Boolean silent)
   at System.Security.Cryptography.Pkcs.CmsSignature.Gost2012_256CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& signatureAlgorithm, Byte[]& signatureValue)
   at System.Security.Cryptography.Pkcs.CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& oid, ReadOnlyMemory`1& signatureValue)
   at System.Security.Cryptography.Pkcs.CmsSigner.Sign(ReadOnlyMemory`1 data, String contentTypeOid, Boolean silent, X509Certificate2Collection& chainCerts)
   at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer, Boolean silent)
...

код для вычисления подписи

                var contentInfo = new ContentInfo(rawData);
                var signedCms = new SignedCms(contentInfo, true);
                var cmsSigner = new CmsSigner(gostCert);
                cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));
                signedCms.ComputeSignature(cmsSigner, true);

На тестовых сертификатах ошибка не воспроизводится, проявляется только на некоторых сертификатах пользователя и воспроизводится регулярно.
Причём прикреплённая подпись формируется без ошибок.

Версия криптопро - 5.0.12000
Сборка corefx из коммита задачи - #53

Кириллица в CN при создании сертификатов

В настоящий момент при варке сертификата через CertificateRequest в самом сертификате кириллица отображается неверно. Смотреть в сторону функции CertStrToName. Пробовал сделать её интероп на unicode, и с ручным переводом в массив байт unicode строки с byte[] интеропом. Пока не вышло.
Воспроизводится на Unix.

Тема на форуме:
https://www.cryptopro.ru/forum2/default.aspx?g=posts&m=125604#post125604

No private key set when using CmsSigner(X509Certificate2 certificate) constructor

my code:

var contentInfo = new ContentInfo(bytes);
var signedCms = new SignedCms(contentInfo, true);
var cmsSigner = new CmsSigner(_certificateProvider.Certificate);
                
signedCms.ComputeSignature(cmsSigner); //exception there
var encodedSignature = signedCms.Encode();

stacktrace:

at Internal.Cryptography.Pal.Windows.HelpersWindows.GetStringProvParam(SafeProvOrNCryptKeyHandle handle, CryptProvParam dwParam, Span`1& buf, Byte[]& rented, Int32 clearLen) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs:line 461
at Internal.Cryptography.Pal.Windows.HelpersWindows.GetProvParameters(SafeProvOrNCryptKeyHandle handle) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs:line 418
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKey[T](X509Certificate2 certificate, Boolean silent, Boolean preferNCrypt) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs:line 249
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKeyForSigning[T](X509Certificate2 certificate, Boolean silent) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs:line 181
at System.Security.Cryptography.Pkcs.CmsSignature.Gost2012_256CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& signatureAlgorithm, Byte[]& signatureValue) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.Gost2012_256.cs:line 71
at System.Security.Cryptography.Pkcs.CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& oid, ReadOnlyMemory`1& signatureValue) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs:line 104
at System.Security.Cryptography.Pkcs.CmsSigner.Sign(ReadOnlyMemory`1 data, String contentTypeOid, Boolean silent, X509Certificate2Collection& chainCerts) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs:line 251
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer, Boolean silent) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 323
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 274
at CCH.EsiaSigner.Controllers.GostController.Sign(String message) in /source/esia/Controllers/GostController.cs:line 33

OS: ubuntu:latest
Microsoft.Private.CoreFx.NETCoreApp Version: 4.7.0-dev.20465.1
CryptoPro version: 5.0

p.s. If y try to use CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate, AsymmetricAlgorithm privateKey) constructor and set privateKey directly then all will be ok.

Tests with private keys from certificates not running in appveyor

Local tests is ok. Privider is set correctly, container is installed correctly,

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : Provider type does not match registered value.
        Stack Trace:
          C:\projects\corefx\src\System.Security.Cryptography.Csp\src\System\Security\Cryptography\CapiHelper.Windows.cs(317,0): at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
          C:\projects\corefx\src\System.Security.Cryptography.Csp\src\System\Security\Cryptography\Gost3410CryptoServiceProvider.Windows.cs(772,0): at System.Security.Cryptography.Gost3410CryptoServiceProvider.get_SafeProvHandle()
          C:\projects\corefx\src\System.Security.Cryptography.Csp\src\System\Security\Cryptography\Gost3410CryptoServiceProvider.Windows.cs(799,0): at System.Security.Cryptography.Gost3410CryptoServiceProvider.get_SafeKeyHandle()
          C:\projects\corefx\src\System.Security.Cryptography.Csp\src\System\Security\Cryptography\Gost3410CryptoServiceProvider.Windows.cs(1066,0): at System.Security.Cryptography.Gost3410CryptoServiceProvider.GetKeyPair()
          C:\projects\corefx\src\System.Security.Cryptography.Csp\src\System\Security\Cryptography\Gost3410CryptoServiceProvider.Windows.cs(160,0): at System.Security.Cryptography.Gost3410CryptoServiceProvider..ctor(CspParameters parameters)
          C:\projects\corefx\src\System.Security.Cryptography.X509Certificates\src\Internal\Cryptography\Pal.Windows\CertificatePal.PrivateKey.cs(75,0): at Internal.Cryptography.Pal.CertificatePal.<>c.<GetGost3410PrivateKey>b__69_0(CspParameters csp)
          C:\projects\corefx\src\System.Security.Cryptography.X509Certificates\src\Internal\Cryptography\Pal.Windows\CertificatePal.PrivateKey.cs(221,0): at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
          C:\projects\corefx\src\System.Security.Cryptography.X509Certificates\src\Internal\Cryptography\Pal.Windows\CertificatePal.PrivateKey.cs(72,0): at Internal.Cryptography.Pal.CertificatePal.GetGost3410PrivateKey()
          C:\projects\corefx\src\System.Security.Cryptography.X509Certificates\src\Internal\Cryptography\CertificateExtensionsCommon.cs(63,0): at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
          C:\projects\corefx\src\System.Security.Cryptography.X509Certificates\src\System\Security\Cryptography\X509Certificates\Gost3410CertificateExtensions.cs(29,0): at System.Security.Cryptography.X509Certificates.Gost3410CertificateExtensions.GetGost3410PrivateKey(X509Certificate2 certificate)
          C:\projects\corefx\src\System.Security.Cryptography.Csp\tests\Gost3410CryptoServiceProviderTests.cs(145,0): at System.Security.Cryptography.Encryption.Gost3410.Tests.Gost3410CryptoServiceProviderTests.SignHashDefaultAlgorithmSuccess()
      System.Security.Cryptography.Encryption.Gost3410.Tests.Gost3410CryptoServiceProviderTests.Gost3410ValidateSignatureOnHash 

Unable to find an entry point named 'CertAddCertificateLinkToStore' in shared library 'libcapi20'

The following test code works on Windows and throws an exception on linux:

var contentInfo = new ContentInfo(new Oid("1.2.840.113549.1.7.1"), data);
var signedCms = new SignedCms(contentInfo, true);

// signerCert - X509Certificate2 object of Gost certificate
var cmsSigner = new CmsSigner(signerCert) { IncludeOption = X509IncludeOption.EndCertOnly };

cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime());
signedCms.ComputeSignature(cmsSigner);

var signerInfo = signedCms.SignerInfos[0];

// throws an exception
signerInfo.CheckSignature(true);
// also throws this exception
var cert = signerInfo.Certificate;
Exception stack trace:
"System.EntryPointNotFoundException" in System.Security.Cryptography.X509Certificates.dll: 'Unable to find an entry point named 'CertAddCertificateLinkToStore' in shared library 'libcapi20'.
   at Interop.crypt32.CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext)
   at Internal.Cryptography.Pal.StorePal.LinkFromCertificateCollection(X509Certificate2Collection certificates)
   at Internal.Cryptography.Pal.FindPal..ctor(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, Boolean validOnly)
   at Internal.Cryptography.Pal.FindPal.OpenPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, Boolean validOnly)
   at Internal.Cryptography.Pal.FindPal.FindFromCollection(X509Certificate2Collection coll, X509FindType findType, Object findValue, Boolean validOnly)
   at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Find(X509FindType findType, Object findValue, Boolean validOnly)
   at System.Security.Cryptography.Pkcs.SignerInfo.FindSignerCertificate(SubjectIdentifier signerIdentifier, X509Certificate2Collection extraStore)
   at System.Security.Cryptography.Pkcs.SignerInfo.FindSignerCertificate()
   at System.Security.Cryptography.Pkcs.SignerInfo.get_Certificate()
   at System.Security.Cryptography.Pkcs.SignerInfo.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly)
   at System.Security.Cryptography.Pkcs.SignerInfo.CheckSignature(Boolean verifySignatureOnly)

OS: Ubuntu 18.04.4 LTS, .net core 3.1 (SDK 3.1.202, runtime 3.1.4), Crypto-Pro CSP 5.0.11455 KC1, instruction Linux.md was used, corefx ver.3.1.1.241 (4.7.0-dev.20175.1) from link .

3.1.31 SignedXml.ComputeSignature CryptographicException: Failed to create signing key

Здравствуйте.
После обновления пакетов и рантайма из задачи #60, появились ошибки вычисления подписи в xml, на некоторых сертификатах, сделал тестовый проект на старой и новой версии рантайма, на старой версии ошибка не воспроизводится.
В стеке ничего особо информативного нет

System.Security.Cryptography.CryptographicException: Failed to create signing key.
   at System.Security.Cryptography.Xml.SignedXml.ComputeSignature()

Ссылки на примеры и тестовый сертификат (пароль на сертификат - пробел):
https://disk.yandex.ru/d/L487xFoXz6t-Hg
https://disk.yandex.ru/d/JTZYr2J7-XQSMA
https://disk.yandex.ru/d/KyTSixQutCmr6w

Вернуть методы работы с контейнерами в Gost_XXXX_CSP

Ранее присутствовали методы указания ключа на контейнер, выбор контейнера, предзагрузки контейнера.

Хорошо бы их вернуть. Отдельный вопрос как это будет работать на Unix.

Сообщение на форуме - https://www.cryptopro.ru/forum2/default.aspx?g=posts&m=123708#post123708

`get_Gost3411_2012_256()` Method not found

Здравствуйте.

Пытаюсь запустить приложение под линуксом.

  1. Добавил пропатченный NetStandard в nuget-фид.
  2. Выполнил build приложения.
  3. .dll и .pdb файл проекта, а также dll сторонних пакетов (по сути, все содержимое папки publish) положил в папку с рантаймом, которая была скачана из репозитория - файл runtime-debug-linux.zip
  4. В папке с рантаймом запускаю dll моего приложения.

Вижу такую ошибку:

{ "date": "2020-07-29 06:44:33.4152", "level": "ERROR", "logger": "CryptographyService", "message": "Method not found: 'System.Security.Cryptography.HashAlgorithmName System.Security.Cryptography.HashAlgorithmName.get_Gost3411_2012_256()'.", "eventProperties": {  }, "exception": "System.MissingMethodException: Method not found: 'System.Security.Cryptography.HashAlgorithmName System.Security.Cryptography.HashAlgorithmName.get_Gost3411_2012_256()'.\n  
at Internal.Cryptography.PkcsHelpers.GetDigestAlgorithm(String oidValue, Boolean forVerification)\n  
at System.Security.Cryptography.Pkcs.SignerInfo.GetDigestAlgorithm() in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignerInfo.cs:line 737\n  
at System.Security.Cryptography.Pkcs.SignerInfo.PrepareDigest(Boolean compatMode) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignerInfo.cs:line 510\n  
at System.Security.Cryptography.Pkcs.SignerInfo.VerifySignature(CmsSignature signatureProcessor, X509Certificate2 certificate, Boolean compatMode) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignerInfo.cs:line 698\n  
at System.Security.Cryptography.Pkcs.SignerInfo.Verify(X509Certificate2Collection extraStore, X509Certificate2 certificate, Boolean verifySignatureOnly) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignerInfo.cs:line 647\n  
at System.Security.Cryptography.Pkcs.SignerInfo.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignerInfo.cs:line 415\n  
at System.Security.Cryptography.Pkcs.SignedCms.CheckSignatures(SignerInfoCollection signers, X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignedCms.cs:line 595\n  
at System.Security.Cryptography.Pkcs.SignedCms.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignedCms.cs:line 578\n  
at System.Security.Cryptography.Pkcs.SignedCms.CheckSignature(Boolean verifySignatureOnly) in \/home\/appveyor\/projects\/corefx\/src\/System.Security.Cryptography.Pkcs\/src\/System\/Security\/Cryptography\/Pkcs\/SignedCms.cs:line 569\n  
at SignatureVerifier.Domain.Services.CryptographyService.VerifyDetachedSignature(Byte[] signedData, Byte[] signature) in \/app\/SignatureVerifier\/SignatureVerifier.Domain\/Services\/CryptographyService.cs:line 66" }

Подскажите, пожалуйста, исходя из логов, чего-то все-таки для запуска не хватает?
На что можно обратить внимание, чтобы понять, что пошло не так?

Проверка подписи на linux

Добрый день. Возникает ошибка при проверке подписи xml-файла на linux. На win10 всё хорошо отрабатывает.

Текст ошибки:
Unknown transform has been encountered.. at
System.Security.Cryptography.Xml.Reference.LoadXml(XmlElement value)\n at System.Security.Cryptography.Xml.SignedInfo.LoadXml(XmlElement value)\n at System.Security.Cryptography.Xml.Signature.LoadXml(XmlElement value)\n at System.Security.Cryptography.Xml.SignedXml.LoadXml(XmlElement value)\n

Код проверки:
XmlNodeList nodeList = document.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl);
foreach (XmlNode node in nodeList)
{
var signedXml = new SignedXml(document);
signedXml.SafeCanonicalizationMethods.Add("http://www.w3.org/TR/1999/REC-xslt-19991116");
signedXml.LoadXml((XmlElement)node); <- тут возникает исключение
var result = signedXml.CheckSignature();
}

Подскажите пожалуйста, в чём может быть проблема?

ошибка проверки открепленной подписи

ubuntu 22.04
при проверке только что созданной открепленной подписи возвращается ошибка

Unhandled exception. System.Security.Cryptography.CryptographicException: The hash value is not correct.
   at System.Security.Cryptography.Pkcs.SignerInfo.PrepareDigest(Boolean compatMode) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs:line 589
   at System.Security.Cryptography.Pkcs.SignerInfo.VerifySignature(CmsSignature signatureProcessor, X509Certificate2 certificate, Boolean compatMode) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs:line 698
   at System.Security.Cryptography.Pkcs.SignerInfo.Verify(X509Certificate2Collection extraStore, X509Certificate2 certificate, Boolean verifySignatureOnly) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs:line 647
   at System.Security.Cryptography.Pkcs.SignerInfo.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs:line 415
   at System.Security.Cryptography.Pkcs.SignedCms.CheckSignatures(SignerInfoCollection signers, X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 595
   at System.Security.Cryptography.Pkcs.SignedCms.CheckSignature(X509Certificate2Collection extraStore, Boolean verifySignatureOnly) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 578
   at System.Security.Cryptography.Pkcs.SignedCms.CheckSignature(Boolean verifySignatureOnly) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 569
   at cms_raw.Program.Main(String[] args)

на http://dss.cryptopro.ru/Verify/Verify/ проверка проходит успешно.
создание и проверка присоединенной подписи также проходит успешно

            bool detached = true;
            SignedCms verifySign = detached ? 
                new SignedCms(new ContentInfo(msg)) : 
                new SignedCms();
            verifySign.Decode(sign);
            verifySign.CheckSignature(true);

Getting SignerInfo.SignedAttributes throws an exception

The following test code works on Windows and throws an exception on linux:

var contentInfo = new ContentInfo(new Oid("1.2.840.113549.1.7.1"), data);
var signedCms = new SignedCms(contentInfo, true);

// signerCert - X509Certificate2 object of Gost certificate
var cmsSigner = new CmsSigner(signerCert) { IncludeOption = X509IncludeOption.EndCertOnly };

cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime());
signedCms.ComputeSignature(cmsSigner);

var signerInfo = signedCms.SignerInfos[0];

// throws an exception
var signedAttributes = signerInfo.SignedAttributes;
Exception stack trace:
"System.Reflection.TargetInvocationException" in System.Private.CoreLib.dll: 'Exception has been thrown by the target of an invocation.'
---> System.Security.Cryptography.CryptographicException: The OID value is invalid.
   at System.Security.Cryptography.Oid.FromOidValue(String oidValue, OidGroup group)
   at System.Security.Cryptography.Pkcs.Pkcs9ContentType..ctor()
   --- End of inner exception stack trace ---
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& hasNoDefaultCtor)
   at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
   at System.Activator.CreateInstance[T]()
   at Internal.Cryptography.PkcsHelpers.Upgrade[T](Pkcs9AttributeObject basicAttribute)
   at Internal.Cryptography.PkcsHelpers.CreateBestPkcs9AttributeObjectAvailable(Oid oid, Byte[] encodedAttribute)
   at System.Security.Cryptography.Pkcs.SignerInfo.MakeAttribute(AttributeAsn attribute)
   at System.Security.Cryptography.Pkcs.SignerInfo.MakeAttributeCollection(AttributeAsn[] attributes)
   at System.Security.Cryptography.Pkcs.SignerInfo.get_SignedAttributes()

Also for this code:

var contentInfo = new ContentInfo(data);
"System.Security.Cryptography.CryptographicException" in System.Security.Cryptography.Encoding.dll: 'The OID value is invalid.'
   в System.Security.Cryptography.Oid.FromOidValue(String oidValue, OidGroup group)
   в System.Security.Cryptography.Pkcs.ContentInfo..ctor(Byte[] content)

and this:

var signedCms = new SignedCms();
"System.TypeInitializationException" in System.Security.Cryptography.Pkcs.dll: 'The type initializer for 'System.Security.Cryptography.Pkcs.SignedCms' threw an exception.'
---> System.Security.Cryptography.CryptographicException : The OID value is invalid.
   в System.Security.Cryptography.Oid.FromOidValue(String oidValue, OidGroup group)
   в System.Security.Cryptography.Pkcs.SignedCms..cctor()

OS: Ubuntu 18.04.4 LTS, .net core 3.1 (SDK 3.1.202, runtime 3.1.4), Crypto-Pro CSP 5.0.11455 KC1, instruction Linux.md was used, corefx ver.3.1.1.241 (4.7.0-dev.20175.1) from link .

GetMethod GetPrivateKeyInfo missing

I'm unable to sign xml smev message since X509Certificate2 has no GetPrivateKeyInfo method.

        [Fact]
        public void GetPrivateKeyInfoMethodExists()
        {
            var getPrivateKeyInfoMethod = typeof(X509Certificate2).GetMethod("GetPrivateKeyInfo", BindingFlags.Static | BindingFlags.NonPublic);
            Assert.NotNull(getPrivateKeyInfoMethod);
        }

This test pass in Framework version using CryptoPro .net sdk and does not pass in current corefx fork version.

Вернуть функциональность метода ContainerCertificate для Gost_XXX_CryptoServiceProvider из Sharpei

Вернуть метод по заданию и получению сертификатов через открытый в CSP контейнер.

Основная проблема - невозможность использовать сборку X509 внутри сборки CSP. Возможно придётся делать полуметод в Csp сборке, и метод в x509Certificates, который его вызывает (в виде расширения?)

Incorrect keyType in CapiHelper SaveCspParameters()

Looks like for some reason keyType is set to CALG instead of AT_SIGNATURE and AT_EXCHANGE.

in CapiHelper.Windows

if (parameters.KeyNumber == -1 && (keyType != CspAlgorithmType.PROV_GOST_2001_DH))
            //end: sk
            {
                parameters.KeyNumber = keyType == CapiHelper.CspAlgorithmType.Dss ? (int)KeyNumber.Signature : (int)KeyNumber.Exchange;
            }
            else if (parameters.KeyNumber == CALG_DSS_SIGN || parameters.KeyNumber == CALG_RSA_SIGN)
            {
                parameters.KeyNumber = (int)KeyNumber.Signature;
            }
            else if (parameters.KeyNumber == CALG_RSA_KEYX)
            {
                parameters.KeyNumber = (int)KeyNumber.Exchange;
            }
            //add: sk
            else if (parameters.KeyNumber == -1)
            {
                if (keyType == CspAlgorithmType.PROV_GOST_2001_DH)
                {
                    parameters.KeyNumber = GostConstants.CALG_GR3410EL;
                }
                else if (keyType == CspAlgorithmType.PROV_GOST_2012_256)
                {
                    parameters.KeyNumber = GostConstants.CALG_GR3410_12_256;
                }
                else if (keyType == CspAlgorithmType.PROV_GOST_2012_512)
                {
                    parameters.KeyNumber = GostConstants.CALG_GR3410_12_512;
                }
                else
                {
                    parameters.KeyNumber = (int)KeyNumber.Signature;
                }
}

in CapiHelper.Gost.Unix.cs

if (parameters.KeyNumber == -1 && (keyType != CspAlgorithmType.PROV_GOST_2001_DH))
            //end: sk
            {
                parameters.KeyNumber = (int)KeyNumber.Exchange;
            }
            else if (parameters.KeyNumber == CALG_RSA_SIGN)
            {
                parameters.KeyNumber = (int)KeyNumber.Signature;
            }
            else if (parameters.KeyNumber == CALG_RSA_KEYX)
            {
                parameters.KeyNumber = (int)KeyNumber.Exchange;
            }
            //add: sk
            else if (parameters.KeyNumber == -1)
            {
                if (keyType == CspAlgorithmType.PROV_GOST_2001_DH)
                {
                    parameters.KeyNumber = GostConstants.CALG_GR3410EL;
                }
                else if (keyType == CspAlgorithmType.PROV_GOST_2012_256)
                {
                    parameters.KeyNumber = GostConstants.CALG_GR3410_12_256;
                }
                else if (keyType == CspAlgorithmType.PROV_GOST_2012_512)
                {
                    parameters.KeyNumber = GostConstants.CALG_GR3410_12_512;
                }
                else
                {
                    parameters.KeyNumber = (int)KeyNumber.Signature;
                }
}

Ошибка при попытке подписать сообщение подписью CMS/PKCS 7

При попытке подписать строку подписью CMS/PKCS 7 выдается ошибка:

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Cryptography error
at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.Gost3410_2012_256CryptoServiceProvider..ctor(CspParameters parameters)
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKey[T](X509Certificate2 certificate, Boolean silent, Boolean preferNCrypt) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs:line 266
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKeyForSigning[T](X509Certificate2 certificate, Boolean silent) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs:line 181
at System.Security.Cryptography.Pkcs.CmsSignature.Gost2012_256CmsSignature.Sign(ReadOnlySpan1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& signatureAlgorithm, Byte[]& signatureValue) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.Gost2012_256.cs:line 71 at System.Security.Cryptography.Pkcs.CmsSignature.Sign(ReadOnlySpan1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, Oid& oid, ReadOnlyMemory1& signatureValue) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs:line 104 at System.Security.Cryptography.Pkcs.CmsSigner.Sign(ReadOnlyMemory1 data, String contentTypeOid, Boolean silent, X509Certificate2Collection& chainCerts) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs:line 251
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer, Boolean silent) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 323
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs:line 274

Проект собирался с версией v3.1.1-cprocsp-preview3.291 по инструкции https://github.com/CryptoPro/DotnetCoreSampleProject/blob/master/docs/Linux.md
OS: Debian 9
КриптоПро 5.0 R2

не ищется сертификат по SubjectName

открываем хранилище на debian 10, csp 5.0.11998
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly);
при поиске по DN возвращается пустая коллекция
store.Certificates.Find(X509FindType.FindBySubjectName, "test2012", true);
если искать по отпечатку то сертификат находится.
store.Certificates.Find(X509FindType.FindByThumbprint, "86d6949e285376565406e1e84995e4967959bec2", true);
в certmgr -list
Subject : CN=test2012
SHA1 Hash : 86d6949e285376565406e1e84995e4967959bec2

Ошибка при получении закрытого ключа из сертификата (csp 5.0.11998 KC1)

За csp 5.0.11998 KC1 замечено изменение по работе с CNG. В частности метод

Interop.crypt32.CryptAcquireCertificatePrivateKey(
                    certificateContext,
                    CryptAcquireFlags.CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG,
                    IntPtr.Zero,
                    out privateKey,
                    out keySpec,
                    out freeKey

возвращает не "key not found", как раньше, а корректный хэндл ключа, что ломает текущую логику, в которой пытается создаться CNG ключ для ГОСТа, и падаем в стабный метод заглушку.

Поведение за версиями 5.0.11736 и 5.0.12099 замечено не было.

Надо поменять логику GetPrivateKey, добавив возможность передавать пустой createCng, что и делать для ГОСТов.

Поддержка устаревшего наименования xml алгоритма 34.10-2001

Добрый день. Могли бы вы добавить для поддержки совместимости старые наименования алгоритмов:
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411\">"
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#gostr3411\">" ?

Ранее использовал GostCryptography, но в связи с необходимостью переходить на .net core, больше нет такой возможности. Похожая проблема возникала и в том проекте AlexMAS/GostCryptography#11

Проблема с определением типа KeyWrap для 12 госта (unix)

Сейчас для совместимости с некоторыми сторонними реализациями (ФСС) необходимо осуществлять импорт ключа 12 госта с использование старого CryptoProKeyWrap. Так как определить тип KeyWrap по ключу внутри Xml невозможно, то делаем так

private SymmetricAlgorithm CryptoProUnwrap(byte[] wrapped)
{
    try
    {
        return this.CryptoProUnwrap(wrapped, GostConstants.CALG_PRO12_EXPORT);
    }
    catch (CryptographicException ex)
    {
        if (Marshal.GetHRForException(ex) == -2146893819)
        {
            // bad data - пробуем импорт на старом алгоритме
            return this.CryptoProUnwrap(wrapped, GostConstants.CALG_PRO_EXPORT);
        }
        else
        {
            throw;
        }
    }
}

Проблема возникает при использовании метода ImportKeyBlob

 internal static int ImportKeyBlob(byte[] keyBlob,
            SafeProvHandle hProv, CspProviderFlags flags,
            SafeKeyHandle hImportKey, out SafeKeyHandle hKey)
{
    int keyFlags = MapCspKeyFlags((int)flags);
    bool ret = CapiHelper.CryptImportKey(hProv, keyBlob,
        keyBlob.Length, hImportKey, keyFlags, out hKey);
    if (!ret)
        throw new CryptographicException(Marshal.GetLastWin32Error());
    int algid_class = BitConverter.ToInt32(keyBlob, 4) & (7 << 13);
    if (algid_class == (5 << 13))
        return (int)KeyNumber.Exchange;
    return (int)KeyNumber.Signature;
}

Так как для Unix Marshal.GetLastWin32Error() вернёт некорректный код ошибки. При исправлении на

internal static int ImportKeyBlob(byte[] keyBlob,
            SafeProvHandle hProv, CspProviderFlags flags,
            SafeKeyHandle hImportKey, out SafeKeyHandle hKey)
{
    int keyFlags = MapCspKeyFlags((int)flags);
    bool ret = CapiHelper.CryptImportKey(hProv, keyBlob,
        keyBlob.Length, hImportKey, keyFlags, out hKey);
    if (!ret)
    {
        var hr = Interop.CPError.GetHRForLastWin32Error();
        throw hr.ToCryptographicException();
    }
    int algid_class = BitConverter.ToInt32(keyBlob, 4) & (7 << 13);
    if (algid_class == (5 << 13))
        return (int)KeyNumber.Exchange;
    return (int)KeyNumber.Signature;
}

работает корректно.

Проблема технически может возникать и в других сценариях, ибо код CapiHelper полностью перенесён из Шарпея, и обработка ошибок полностью виндовая, на unix возможны и другие некорректные коды. С виду мы больше нигде по ним не ветвимся, поэтому править массово пока не будем (из за опасений, что получение кода ошибки в других методах теоретически может приходить к перетиранию кода, и тогда будем получать ошибку и на windows).

Хорошо добывать бы тест на это (возможно в рамках LibCore с переносом сюда).

[Вопрос] .NET Core 3.1 will reach End of Support on December 13, 2022

Доброго времени суток.
Данный проект основан на netcore3.1, который microsoft планирует остановить в поддержке.
Запланированы ли какие-либо изменения в проекте CryptoPro corefx, чтобы оставаться защищенным с точки зрения безопасности?

Реализация экспорта\транспорта\keyWrap\EncryptedXml

Ветка - https://github.com/CryptoPro/corefx/tree/gost_xml_encrypt

Большая доработка шифрование и экспорта.

Текущие изменения:

  • Возможность выбора провайдера для 28147
  • Транспорт и эфемерные провайдеры для 3410 (2001 + 2012)
  • Множество исправлений Get\Set KeyParam
  • Исправления для GostRngCryptoServiceProvider
  • Единый класс KeyExchangeFormatter для работы со всеми гостами
  • Исправления Agree методов для 2012 ГОСТов
  • Пересобран и переделан ASN по аналогии с КриптоПро.NET (удобнее перенос из CSP при использовании ASN компилятора)
  • CryptoPro12 key wrap по умолчанию для всех провайдеров (при unwrap как и раньше понимаем оба, даже если явно прередан CryptoPro, при явном указании как и раньше можно выбирать любой wrapMethod)

В настоящий успешно собирается с netstandatd'ом из одноименной ветки.

Функциональность Классы Состояние Описание
KeyExchange GostKeyExchangeFormatter done (win), done (unix) Код аналогичен KeyExchange.cs из КриптоПро.NET. VKO в сторону получателя
gEncrypt не реализованная функциональность в криптопро.NET и тут (явное шифрование на 3410)
gEncryptFileAgree GostSharedSecretAlgorithm done(win), done(unix) Код аналогичен gEncryptFileAgree .cs из КриптоПро.NET. Создание и использование ключа через согласование
gEncryptFileEphem GostSharedSecretAlgorithm done (win), done (unix) Исходный пример аналогичен gEncryptFileAgree, но ключи задаются сертификатами
gEncryptFileTransport GostKeyExchangeFormatter done (win), done (unix) Исходный пример аналогичен KeyExchange, но ключи задаются сертификатами
EncryptedXml (key container) done (win), done (unix) EncryptAKey
EncryptedXml (x509 certificate) done (win), done (unix) EncryptCertificate

Разворачивание в IIS (In-process hosting model)

Сейчас имеем ошибку после установки .NET Core Hosting Bundle (https://docs.microsoft.com/ru-ru/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1)

 HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
Common solutions to this issue:
The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
Troubleshooting steps:

    Check the system event log for error messages
    Enable logging the application process' stdout messages
    Attach a debugger to the application process and inspect

For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028526 

Когда нибудь придётся разобраться.

Fix ubuntu build on clang 10

/home/appveyor/projects/corefx/src/Native/Unix/System.Native/pal_io.c(917,64): error G8A08D350: use of function '__builtin_alloca' is discouraged; there is no way to check for failure but failure may still occur, resulting in a possibly exploitable security vulnerability [-Werror,-Walloca] [/home/appveyor/projects/corefx/src/Native/build-native.proj]
      struct pollfd* pollfds = (struct pollfd*)(useStackBuffer ? alloca(bufferSize) : malloc(bufferSize));
                                                                 ^
  /usr/include/alloca.h:35:23: note: expanded from macro 'alloca'
  # define alloca(size)   __builtin_alloca (size)
                          ^
  1 error generated.
  System.Native/CMakeFiles/System.Native.dir/build.make:121: recipe for target 'System.Native/CMakeFiles/System.Native.dir/pal_io.c.o' failed
  make[2]: *** [System.Native/CMakeFiles/System.Native.dir/pal_io.c.o] Error 1
  make[1]: *** [System.Native/CMakeFiles/System.Native.dir/all] Error 2
  CMakeFiles/Makefile2:340: recipe for target 'System.Native/CMakeFiles/System.Native.dir/all' failed
  Makefile:149: recipe for target 'all' failed
  make: *** [all] Error 2
  Failed to build corefx native components.
/home/appveyor/projects/corefx/src/Native/build-native.proj(36,5): error MSB3073: The command ""/home/appveyor/projects/corefx/src/Native/build-native.sh" x64 Debug Linux outconfig netcoreapp-Linux-Debug-x64 -portable" exited with code 1.

dotnet/runtime#33734

Gost ICryptoTransform не использет дубликат ключа.

При создании ICryptoTransform в объекте Gost28147CryptoServiceProvider используется оригинальный хэндл ключа, а не его созданная копия. В результате один и тот же хэндл управляется как провайдером, так и трансформом, в результате чего происходит двойной релиз ключа.

Ошибка работы с RSA в Linux

https://github.com/CryptoPro/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs

Строка 42

Сборка linux_x64 (обращаю внимание, что в сборку для linux попадает пространство имён .Windows., что в общем-то странно).

Загрузка в X509Certificate2 сертификата с открытым ключом и попытка извлечения открытого ключа (GetPublicKey()) в Linux вызывается вышеуказанный код с использованием CNG, которая в linux не поддерживается. В результате возникает ошибка 0x00000057 (87) The parameter is incorrect. Использование класса RSA (без CNG) решает эту проблему.

Пожалуйста, проверьте, чтобы в сборках под linux не использовались CNG.

Из-за данной проблемы в aspnetcore не работает валиадация JWT-токена (Bearer-схемы), при валидном сертификате RSA (а это серьёзная проблема):

{Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: '260A93852F5760A68378xxxxxx1475E7D501317', InternalId: 'JgqThS9XYKaDePxyHRFHXn1QExc'. , KeyId: 260A93852F5760A68378Fxxxxxx1475E7D501317
'.
kid: '260A93852F5760A68378Fxxxxxx1475E7D501317'.
Exceptions caught:
'Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The parameter is incorrect.

at Internal.Cryptography.Pal.X509Pal.DecodeKeyBlob(CryptDecodeObjectStructType lpszStructType, Byte[] encodedKeyValue)
at Internal.Cryptography.Pal.X509Pal.DecodePublicKey(Oid oid, Byte[] encodedKeyValue, Byte[] encodedParameters, ICertificatePal certificatePal)
at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPublicKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPublicKey(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PublicKey()
at Microsoft.IdentityModel.Tokens.SupportedAlgorithms.IsSupportedAlgorithm(String algorithm, SecurityKey key)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.IsSupportedAlgorithm(String algorithm, SecurityKey key)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures, Boolean cacheProvider)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey key, String algorithm, Boolean cacheProvider)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm, SecurityToken securityToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)

При генерации сертификата ГОСТ 2012 выставляется OID GOST3410EL

При использовании кода из примера с генерацией сертификата

private static void MakeMeCert()
{
    using (var parent = new Gost3410_2012_256CryptoServiceProvider())
    {
        var parentReq = new CertificateRequest(
            "CN=Experimental Issuing Authority",
            parent,
            HashAlgorithmName.Gost3411_2012_256);

        parentReq.CertificateExtensions.Add(
            new X509BasicConstraintsExtension(true, false, 0, true));

        parentReq.CertificateExtensions.Add(
            new X509SubjectKeyIdentifierExtension(parentReq.PublicKey, false));

        using (var parentCert = parentReq.CreateSelfSigned(
             DateTimeOffset.UtcNow.AddDays(-45),
             DateTimeOffset.UtcNow.AddDays(365)))
        {
             byte[] certData = parentCert.Export(X509ContentType.Pfx, "1");
             File.WriteAllBytes(@"MyCert.pfx", certData);
        }
    }
}

Создаётся сертификат с проставленным OID Gost3410EL:

using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.PushSequence();
writer.WriteObjectIdentifier(Oids.Gost3410EL);
writer.PopSequence();
return writer.Encode();
}

using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.PushSequence();
writer.WriteObjectIdentifier(Oids.Gost3410EL);
writer.PopSequence();
return writer.Encode();
}

Корректные oid - Oids.Gost3410_2012_256 Oids.Gost3410_2012_512.

Открытые .pfx сертификатов из файла в Non-Persist csp

Возвращаем старую функциональность по работе с pfx сертификатами без установки ключа в хранилище.

При использовании флага PKCS12_NO_PERSIST_KEY ключ сертификата можно получить через свойство CERT_KEY_PROV_INFO_PROP_ID.

ComputeSignature не формирует cades-bes подпись

debian 10, csp 5.0.11998
при использовании ComputeSignature в подписи отсутствуют необходимые обязательные подписанные аттрибуты cades-bes.
время подписания можно добавить указав
cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));
но для добавления подписанного аттрибута Signing certificate V2 (1.2.840.113549.1.9.16.2.47) нет удобных способов

Сломался Gost EnvelopedCMS на win, не работал на Linux

Поломался EnvelopedCms, скорее всего после очередного вливания из upstream. Тестов не было....

При вызове
envelopedCms.Encrypt(recip1);

вываливается
ASN1 bad tag value met

Проблема в том, что после одного из вливаний появился код в PkcsPalWindows.Encrypt.cs

 using (SafeCertContextHandle hCertContext = recipient.Certificate.CreateCertContextHandle())
 {
    CERT_CONTEXT* pCertContext = hCertContext.DangerousGetCertContext();
    CERT_INFO* pCertInfo = pCertContext->pCertInfo;

    CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* pEncodeInfo = (CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO)));

    pEncodeInfo->cbSize = sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO);

    RSAEncryptionPadding padding = recipient.RSAEncryptionPadding;

    if (padding is null)
    {
        if (recipient.Certificate.GetKeyAlgorithm() == Oids.RsaOaep)
        {
            byte[] parameters = recipient.Certificate.GetKeyAlgorithmParameters();

            if (parameters == null || parameters.Length == 0)
            {
                padding = RSAEncryptionPadding.OaepSHA1;
            }
            else if (!PkcsHelpers.TryGetRsaOaepEncryptionPadding(parameters, out padding, out _))
            {
                throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException();
            }
        }
        else
        {
            padding = RSAEncryptionPadding.Pkcs1;
        }
    }

    if (padding == RSAEncryptionPadding.Pkcs1)
    {
        // ГОСТ ПОПАДАЕТ СЮДА!
        // в результате в параметры и OID попадает RSA, а не гост
        pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.Rsa);
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaPkcsParameters.Length;
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaPkcsParameters);
    }
    else if (padding == RSAEncryptionPadding.OaepSHA1)
    {
        pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha1Parameters.Length;
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha1Parameters);
    }
    else if (padding == RSAEncryptionPadding.OaepSHA256)
    {
        pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha256Parameters.Length;
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha256Parameters);
    }
    else if (padding == RSAEncryptionPadding.OaepSHA384)
    {
        pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha384Parameters.Length;
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha384Parameters);
    }
    else if (padding == RSAEncryptionPadding.OaepSHA512)
    {
        pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha512Parameters.Length;
        pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha512Parameters);
    }
    else
    {
        throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException();
    }

    pEncodeInfo->pvKeyEncryptionAuxInfo = IntPtr.Zero;
    pEncodeInfo->hCryptProv = IntPtr.Zero;

    pEncodeInfo->RecipientPublicKey = pCertInfo->SubjectPublicKeyInfo.PublicKey;

    pEncodeInfo->RecipientId = EncodeRecipientId(recipient, hCertContext, pCertContext, pCertInfo, hb);

    return pEncodeInfo;
}

когда раньше было явное копирование

// KeyEncryptionAlgorithm.pszObjId
IntPtr pszObjId = new IntPtr((long) pKeyEncryptionAlgorithm + (long) Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId"));
Marshal.WriteIntPtr(pszObjId, encryptParam.rgszObjId[index].DangerousGetHandle());

// KeyEncryptionAlgorithm.Parameters
IntPtr pParameters = new IntPtr((long) pKeyEncryptionAlgorithm + (long) Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "Parameters"));

// KeyEncryptionAlgorithm.Parameters.cbData
IntPtr pcbData = new IntPtr((long) pParameters + (long) Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
Marshal.WriteInt32(pcbData, (int) certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.cbData);

// KeyEncryptionAlgorithm.Parameters.pbData
IntPtr ppbData = new IntPtr((long) pParameters + (long) Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
Marshal.WriteIntPtr(ppbData, certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.pbData);

Gost3410CryptoServiceProvider Constructor not working

Пустой конструктор от Gost3410CryptoServiceProvider, при попытке пользоваться ключом падает с "набор ключей не существует".

Причина - в разнице создания ключей у нас и у ms. ms.

EnvelopedCms.Decode throws an exception

The following test code works on Windows and throws an exception on linux:

var envelopedCms = new EnvelopedCms();

// throws an exception
envelopedCms.Decode(msg);

Exception stack trace:

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Unknown error (0x0)
   at Internal.Cryptography.Pal.Windows.HelpersWindows.GetMsgParamAsMemory(SafeCryptMsgHandle hCryptMsg, CryptMsgParamType paramType, Int32 index)
   at Internal.Cryptography.Pal.Windows.DecryptorPalWindows.Decode(Byte[] encodedMessage, Int32& version, ContentInfo& contentInfo, AlgorithmIdentifier& contentEncryptionAlgorithm, X509Certificate2Collection& originatorCerts, CryptographicAttributeObjectCollection& unprotectedAttributes)
   at Internal.Cryptography.Pal.Windows.PkcsPalWindows.Decode(Byte[] encodedMessage, Int32& version, ContentInfo& contentInfo, AlgorithmIdentifier& contentEncryptionAlgorithm, X509Certificate2Collection& originatorCerts, CryptographicAttributeObjectCollection& unprotectedAttributes)
   at System.Security.Cryptography.Pkcs.EnvelopedCms.Decode(Byte[] encodedMessage)

OS: Ubuntu 18.04.4 LTS, .net core 3.1 (SDK 3.1.202, runtime 3.1.4), Crypto-Pro CSP 5.0.11732 KC1, instruction Linux.md was used, corefx ver.3.1.1.241 (4.7.0-dev.20175.1) from link .

Создание и проверка подписи CAdES BES, CAdES X Long Type 1 на линуксе используя .net core

Здравствуйте!
Возможно ли на линуксе создать подпись типа CAdES BES и дополнить до типа CAdES X Long Type 1 на .net core?
Ниже приведен код на винде, где используются com-интерфейсы cadescom и capicom для создания подписи CAdES BES и
CAdES X Long Type 1. На python(pycades) увидел что есть аналог реализации подписи CAdES BES. Как ниже приведенный код переписать под линукс заменив com-интерфейсы, или заставить работать com-интерфейсы на линуксе(думаю это невозможно)? Спасибо:)

             //Создание УКЭП
    public string SignWithAdvancedEDS(byte[] fileBytes, X509Certificate2 certificate)
    {
        string signature = "";

        try
        {
            string tspServerAddress = @"http://qs.cryptopro.ru/tsp/tsp.srf";

            CPSigner cps = new CPSigner();
            cps.Certificate = GetCAPICOMCertificate(certificate.Thumbprint);
            cps.Options = CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN;
            cps.TSAAddress = tspServerAddress;

            CadesSignedData csd = new CadesSignedData();
            csd.ContentEncoding = CADESCOM_CONTENT_ENCODING_TYPE.CADESCOM_BASE64_TO_BINARY;
            csd.Content = Convert.ToBase64String(fileBytes);

            //Создание и проверка подписи CAdES BES
            signature = csd.SignCades(cps, CADESCOM_CADES_TYPE.CADESCOM_CADES_BES, true,
                CAdESCOM.CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
            //csd.VerifyCades(signature, CADESCOM_CADES_TYPE.CADESCOM_CADES_BES, true);

            //Дополнение и проверка подписи CAdES BES до подписи CAdES X Long Type 1 
            //(вторая подпись остается без изменения, так как она уже CAdES X Long Type 1)
            //signature = csd.EnhanceCades(CADESCOM_CADES_TYPE.CADESCOM_CADES_X_LONG_TYPE_1, tspServerAddress,
            //    CAdESCOM.CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
            //csd.VerifyCades(signature, CADESCOM_CADES_TYPE.CADESCOM_CADES_X_LONG_TYPE_1, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return signature;
    }

Версионность 3.1.30

ms Выставили версию Security.Xml в 4.0.3.1, при этом последняя версия пакета Microsoft.AspNetCore.App.Ref версии 3.1.10 использует 4.0.3.0, из за чего не получается подложить нашу сборку и получается конфликт загрузки классов (т.к. получается, что проект смотрит на сборку Security.Xml сразу двух версий). Пока просто руками возвращаем нужную версию.

Не работает чтение RSA сертификата из pfx в linux

В чём проблема

При попытке считать сертификат в патченном рантайме получаем либо ошибку Unknown error (0x80070002), либо ошибку сегментации.

Как воспроизвести

  • Выполнить инструкцию по установке под linux , версия 4.7.0-dev.20163.1
  • Создать самоподписанный сертификат с помощью PowerShell
  • Добавить код чтения сертификата

Если написатьnew X509Certificate2(certName, certPass), то падает с ошибкой

Unhandled exception. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Unknown error (0x80070002)
   at Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs:line 77
   at Internal.Cryptography.Pal.CertificatePal.FromFile(String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs:line 26
   at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs:line 137
   at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs:line 118
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password) in /home/appveyor/projects/corefx/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs:line 88

Если написать new X509Certificate2(File.ReadAllBytes(certName), certPass), то падает с ошибкой

Ошибка сегментирования

Если переложить скомпилированную dll в обычный netcore runtime 3.1, то код выполняется без ошибок.

reproduce_project.zip

Поддержка CRYPT_SILENT в ссылке на ключ

При чтении/установке X509Certificate2::PrivateKey теряется флаг CRYPT_SILENT, который может присутствовать в CRYPT_KEY_PROV_INFO::dwFlags.
Примерный сценарий для чтения:

// задача - сериализовать ссылку на ключ
X509Certificate2 cert = ... // поиск сертификата со ссылкой в хранилище, например установленым туда средствами УЦ 2.0
var key = cert.PrivateKey as Gost3410_2012_256CryptoServiceProvider;
var containerInfo = key.CspKeyContainerInfo;
// далее из containerInfo можно прочитать ProviderType, ProvideName и т.д., но из флагов будет доступен MachineKeyStore,
// а про Silent ничего узнать не получится - 
// хорошо бы иметь соответствующее свойство или вообще уметь получать CspParameters из классов *CryptoServiceProvider.

Примерный сценарий для записи:

var cert = new X509Certificate2("test.cer");
var p = new CspParameters(provType, provName, containerName)
{
    KeyNumber = 1,
    Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.NoPrompt,
};

var key = new Gost3410_2012_256CryptoServiceProvider(p);
cert.PrivateKey = key; // вот здесь в ссылку на ключ попадет только CRYPT_MACHINE_KEYSET, CRYPT_SILENT не попадет

Gost3410 Test

Gost3410XXXCryptoServiceProvider tests:

  • CryptoServiceProvider:
    • Hash and data signature (+)
    • Random key signature and validation test (empty constructor)
  • Params export-import
  • Create method test
  • x509 Tests
  • Cms signature
  • Key export

Non-Persist сертификаты в SignedCms

Не отрабатывают Non-Persist сертификаты в cms, т.к. сборка pkcs самостоятельно грузит ключ сертификата, не пользуясь сборкой x509 (т.е. не умеет работать с CERT_KEY_PROV_INFO_PROP_ID).

CspParameters cspParams = handle.GetProvParameters();
Debug.Assert((cspParams.Flags & CspProviderFlags.UseExistingKey) != 0);
cspParams.KeyNumber = (int)keySpec;
if (silent)
{
cspParams.Flags |= CspProviderFlags.NoPrompt;
}
if (typeof(T) == typeof(RSA))
return (T)(object)new RSACryptoServiceProvider(cspParams);
if (typeof(T) == typeof(DSA))
return (T)(object)new DSACryptoServiceProvider(cspParams);
//begin: gost
if (typeof(T) == typeof(Gost3410))
return (T)(object)new Gost3410CryptoServiceProvider(cspParams);
if (typeof(T) == typeof(Gost3410_2012_256))
return (T)(object)new Gost3410_2012_256CryptoServiceProvider(cspParams);
if (typeof(T) == typeof(Gost3410_2012_512))
return (T)(object)new Gost3410_2012_512CryptoServiceProvider(cspParams);
//end: gost

В результате падает код вида

using (var gostCert = new X509Certificate2(Gost2012_256Pfx, "1", X509KeyStorageFlags.CspNoPersistKeySet))
{
    var contentInfo = new ContentInfo(bytesToHash);
    var signedCms = new SignedCms(contentInfo, true);
    CmsSigner cmsSigner = new CmsSigner(gostCert);
    signedCms.ComputeSignature(cmsSigner);
    Console.WriteLine($"CMS Sign: {Convert.ToBase64String(signedCms.Encode())}");
}
Exception thrown: 'Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException' in System.Security.Cryptography.Pkcs.dll
An unhandled exception of type 'Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException' occurred in System.Security.Cryptography.Pkcs.dll
Bad UID

Сообщение на форуме

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.