SSL_CLIENT_VERIFY: FAILED: невозможно проверить первый сертификат
Конфигурация Apache включает правильный сертификат корневого центра сертификации:
Код: Выделить всё
SSLCACertificateFile "conf/ssl.crt/testrootca-crt.pem"
SSL_CLIENT_VERIFY: SUCCESS
Где может заключаться проблема в реализации .NET или обработке цепочки сертификатов?
/>Желаемое поведение
Сервер PHP выводит статус проверки ($_SERVER["SSL_CLIENT_VERIFY"]). Статус проверки всегда должен содержать УСПЕХ, а не ОШИБКА: невозможно проверить первый сертификат
Консольное приложение C#:
Код: Выделить всё
using System;
using System.Data.SqlTypes;
using System.Net.Http;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
// Hello3
//
class Program
{
// Hauptprogramm
static async Task Main()
{
// Load Client Certifikate
// EC
//string certpath = "C:\\temp\\CAItest\\signed.p12";
// RSA
string certpath = "C:\\Austausch\\SSLneu2\\client-chain.p12";
Console.WriteLine(certpath);
byte[] rawCert = File.ReadAllBytes(certpath);
X509Certificate2Collection certificateCollection = X509CertificateLoader.LoadPkcs12Collection(
rawCert,
"David",
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet
);
Console.WriteLine("List content of Collection");
foreach (X509Certificate2 c in certificateCollection) Console.WriteLine($"{c.Subject} - HasPrivateKey={c.HasPrivateKey}");
Console.WriteLine($"Number of Certifikates in PFX: {certificateCollection.Count}");
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
// Accept all Server Certifikates
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
handler.ClientCertificates.AddRange(certificateCollection);
using HttpClient client = new HttpClient(handler);
string url = "https://localhost/mbbsim/test4.php?params=dotnet"; // Call PHP test mock
try
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // Exception, wenn der Statuscode nicht erfolgreich ist
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request-Fehler: {e.Message}");
}
}
}
Код: Выделить всё
menno
Моя среда:
Windows 11
Microsoft Visual Studio Community 2022 (64-разрядная версия) — текущая версия 17.14.14
Версия панели управления XAMPP: 3.3.0
Apache/2.4.58 (Win64) OpenSSL/3.1.3 PHP/8.2.12
Intellij IDEA 2024.3.4.1 (Community Edition) JDK 1.8
Используемые сертификаты (созданные с помощью 64-разрядной версии OpenSSL):
Клиент (C# или Java)
Код: Выделить всё
client-chain.p12 - certificate chain with client certificate with private Key and intermediate CA certificate
testrootca-crt.pem - self signed root certificate
Код: Выделить всё
SSLCertificateFile "conf/ssl.crt/apache-chain-crt.pem" - certificate chain with server certificate with private Key and intermediate CA certificate
SSLCertificateKeyFile "conf/ssl.key/apache-key.pem" - private Key of Apache Server
SSLCACertificateFile "conf/ssl.crt/testrootca-crt.pem" - CA certificate for client authentication (self signed root certificate)
Код: Выделить всё
c:\OpenSSL-Win64\bin\openssl.exe verify -CAfile "C:\Austausch\SSLneu2\testrootca-crt.pem" -untrusted "C:\Austausch\SSLneu2\testintermediate-crt.pem" "C:\Austausch\SSLneu2\client-chain-crt.pem"
Клиент C# подключается к серверу только в том случае, если
Код: Выделить всё
SSLVerifyClient optional_no_ca
Если клиент C# переключен на TLS 1.2 (вместо 1.3), сервер PHP теперь сообщает GENEROUS вместо FAILED.
Для Java и Python не имеет значения, какая версия TLS установлена; Всегда сообщается об УСПЕХЕ.
Я сравнил данные подключения клиента C#, клиента Java и клиента Python с помощью Wireshark (каждый с TLS 1.2). Для всех клиентов сервер получил два сертификата: сертификат клиента и промежуточный сертификат. Поэтому я не понимаю, почему C# ведет себя иначе, чем Python или Java.
Используемые сертификаты идентичны для клиента Java и клиента C#.
Если я запускаю тесты с помощью
Код: Выделить всё
SSLVerifyClient require
К сожалению, невозможно загружать файлы в stackoverfleow.
Клиент csharp останавливается с исключением:
Код: Выделить всё
Request error: The SSL connection could not be established, see inner exception.
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.
---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an untrusted certificate authority.
--- End of inner exception stack trace ---
После того, как я ввел свой собственный корневой сертификат в хранилище сертификатов «Доверенные корневые центры сертификации» в консоли управления и промежуточный сертификат в разделе «Промежуточные центры сертификации», все заработало как положено.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... cate-chain
Мобильная версия