L'authentification par certificat WinRM échoue avec une erreur 401 sur Windows Server 2022

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

L'authentification par certificat WinRM échoue avec une erreur 401 sur Windows Server 2022

Message par ForumBot »

J’ai un problème avec l’authentification par certificat WinRM sur une image Windows Server 2022 avec CIS STIGs.


Le serveur exécute le service WinRM, et je me connecte depuis un client Ubuntu Pro 20.04 FIPS en utilisant pywinrm (v0.5.0). Les deux certificats sont auto-signés (ACM PCA) et le certificat CA est ajouté aux magasins de confiance à la fois sur Windows et Ubuntu.


Commandes et configuration :


Sur Windows Server 2022 :

`> Get-ChildItem -Path Cert:\CurrentUser\Root

| Where-Object { $_.Thumbprint -eq “5A2F4E63BEBEDB186ED84BF722B54207E6664469” }

| Select-Object Subject, Thumbprint


Subject Thumbprint




L=TA, CN=example.com, S=TA, OU=RnD, O=Company, C=IL 5A2F4E63BEBEDB186ED84BF722B54207E6664469



winrm enumerate winrm/config/service/certmapping

CertMapping

URI = *

Subject = 50612F90702F2FEF1B777E987B7CD974DC99CE51

Issuer = 5A2F4E63BEBEDB186ED84BF722B54207E6664469

UserName = Administrator

Enabled = true

Password




winrm g winrm/config

Config

MaxEnvelopeSizekb = 500

MaxTimeoutms = 1800000

MaxBatchItems = 32000

MaxProviderRequests = 4294967295

Client

NetworkDelayms = 5000

URLPrefix = wsman

AllowUnencrypted = false [Source=“GPO”]

Auth

Basic = false [Source=“GPO”]

Digest = false [Source=“GPO”]

Kerberos = true

Negotiate = true

Certificate = true

CredSSP = false

DefaultPorts

HTTP = 5985

HTTPS = 5986

TrustedHosts

Service

RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)

MaxConcurrentOperations = 4294967295

MaxConcurrentOperationsPerUser = 1500

EnumerationTimeoutms = 240000

MaxConnections = 300

MaxPacketRetrievalTimeSeconds = 120

AllowUnencrypted = false [Source=“GPO”]

Auth

Basic = false [Source=“GPO”]

Kerberos = true

Negotiate = true

Certificate = true

CredSSP = true

CbtHardeningLevel = Relaxed

DefaultPorts

HTTP = 5985

HTTPS = 5986

IPv4Filter = *

IPv6Filter = *

EnableCompatibilityHttpListener = false

EnableCompatibilityHttpsListener = true

CertificateThumbprint

AllowRemoteAccess = true

Winrs

AllowRemoteShellAccess = true

IdleTimeout = 7200000

MaxConcurrentUsers = 2147483647

MaxShellRunTime = 2147483647

MaxProcessesPerShell = 2147483647

MaxMemoryPerShellMB = 1024

MaxShellsPerUser = 2147483647




winrm g winrm/config/service

Service

RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)

MaxConcurrentOperations = 4294967295

MaxConcurrentOperationsPerUser = 1500

EnumerationTimeoutms = 240000

MaxConnections = 300

MaxPacketRetrievalTimeSeconds = 120

AllowUnencrypted = false [Source=“GPO”]

Auth

Basic = false [Source=“GPO”]

Kerberos = true

Negotiate = true

Certificate = true

CredSSP = true

CbtHardeningLevel = Relaxed

DefaultPorts

HTTP = 5985

HTTPS = 5986

IPv4Filter = *

IPv6Filter = *

EnableCompatibilityHttpListener = false

EnableCompatibilityHttpsListener = true

CertificateThumbprint = 13F3C1844B7617270D1331BEB02AD347FAB74D9C

AllowRemoteAccess = true




**Sur Ubuntu Pro 20.04** :
`$ cert_path="/etc/nginx/certs/controller.example.com.crt.pem"
$ thumbprint=$(openssl x509 -in "$cert_path" -noout -fingerprint -sha1 | sed 's/://g' | awk -F= '{print $2}')
$ echo $thumbprint
50612F90702F2FEF1B777E987B7CD974DC99CE51

$ issuer_thumbprint=$(tac /etc/ssl/certs/ca-certificates.crt | awk 'BEGIN {c=0} /END CERTIFICATE/ {c++} {if (c==1) print}' | tac | openssl x509 -in /dev/stdin -noout -fingerprint -sha1 | sed 's/://g' | awk -F= '{print $2}')
$ echo $issuer_thumbprint
5A2F4E63BEBEDB186ED84BF722B54207E6664469


Test de connexion :


Je teste la connexion en utilisant pywinrm avec HTTPS et l’authentification par certificat. Voici la commande et le message d’erreur Invalid Credentials :


$ python -c "import winrm; winrm.Session('https://winrm.example.com:5986/wsman', auth=(None, None), transport='certificate', cert_key_pem='/etc/nginx/certs/controller.example.com.key.pem', cert_pem='/etc/nginx/certs/controller.example.com.crt.pem', server_cert_validation='validate', ca_trust_path='/etc/ssl/certs/ca-certificates.crt').run_cmd('ipconfig', ['/all']).std_out.decode()"

`Traceback (most recent call last):

File “/opt/venv3.11/lib/python3.11/site-packages/winrm/transport.py”, line 342, in _send_message_request

response.raise_for_status()

File “/opt/venv3.11/lib/python3.11/site-packages/requests/models.py”, line 1024, in raise_for_status

raise HTTPError(http_error_msg, response=self)

requests.exceptions.HTTPError: 401 Client Error: for url:

https://winrm.example.com:5986/wsman


During handling of the above exception, an invalid credentials exception occurred:


Traceback (most recent call last):

File “”, line 1, in

File “/opt/venv3.11/lib/python3.11/site-packages/winrm/init.py”, line 44, in run_cmd

shell_id = self.protocol.open_shell()

File “/opt/venv3.11/lib/python3.11/site-packages/winrm/protocol.py”, line 193, in open_shell

res = self.send_message(xmltodict.unparse(req))

File “/opt/venv3.11/lib/python3.11/site-packages/winrm/protocol.py”, line 263, in send_message

resp = self.transport.send_message(message)

File “/opt/venv3.11/lib/python3.11/site-packages/winrm/transport.py”, line 336, in send_message

response = self._send_message_request(session, prepared_request)

File “/opt/venv3.11/lib/python3.11/site-packages/winrm/transport.py”, line 346, in _send_message_request

raise InvalidCredentialsError(“the specified credentials were rejected by the server”)

winrm.exceptions.InvalidCredentialsError:


the specified credentials were rejected by the server



**Journaux du service WinRM** :
Sur le service WinRM, il y a un message d'erreur « accès refusé » erreur 5 :



Get-WinEvent -LogName “Microsoft-Windows-WinRM/Operational” -MaxEvents 1 | Format-List *



Message : The authorization of the user failed with error 5

Id : 192

RecordId : 5435

ProviderName : Microsoft-Windows-WinRM

LogName : Microsoft-Windows-WinRM/Operational

ProcessId : 3320

ThreadId : 3744

MachineName : winrm

UserId : S-1-5-20

TimeCreated : 4/8/2025 8:44:41 PM



Pourquoi la connexion avec l'authentification par certificat échoue-t-elle ? La poignée de main TLS semble correcte. J'ai également confirmé avec openssl s_client... obtenant verification OK.

Des suggestions ou idées s'il vous plaît !
Merci !!
ayi
Site Admin
Messages : 13176
Inscription : mer. avr. 22, 2026 5:21 pm

Re: L'authentification par certificat WinRM échoue avec une erreur 401 sur Windows Server 2022

Message par ayi »

Je pense qu’il manque une étape. Le certificat crt sans clé privée (c’est-à-dire la clé publique pem) du client qui s’authentifie doit être présent dans le magasin Trusted People (Personnes de confiance) sur le serveur.


Utilisez ce qui suit comme guide général et comparaison :


https://docs.ansible.com/ansible/latest/os_guide/windows_winrm_certificate.html#import-certificate-to-the-certificate-store


Ensuite, vous devez mapper le certificat client au compte LOCAL :


https://docs.ansible.com/ansible/latest/os_guide/windows_winrm_certificate.html#mapping-certificate-to-a-local-account

`# Will prompt for the password of the user.

$credential = Get-Credential local-user


$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(“cert.pem”)

$certChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()

[void]$certChain.Build($cert)

$caThumbprint = $certChain.ChainElements.Certificate[-1].Thumbprint


$certMapping = @{

Path = ‘WSMan:\localhost\ClientCertificate’

Subject = $cert.GetNameInfo(‘UpnName’, $false)

Issuer = $caThumbprint

Credential = $credential

Force = $true

}

New-Item @certMapping



« Le Subject est la valeur du userPrincipalName dans l'entrée SAN du certificat. L'Issuer est l'empreinte du certificat CA qui a émis notre certificat. Le Credential est le nom d'utilisateur et le mot de passe de l'utilisateur local auquel nous mappons le certificat. »
Répondre

Revenir à « Windows Server 2025 »