Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connect-MgGraph - every now and then ClientCertificateCredential authentication failed: Key not valid for use in specified state. - #2430

Closed
MGBASF opened this issue Nov 10, 2023 · 8 comments
Assignees
Labels
no-recent-activity status:waiting-for-author-feedback Issue that we've responded but needs author feedback to close

Comments

@MGBASF
Copy link

MGBASF commented Nov 10, 2023

Thanks for reporting the bug. Please ensure you've gone through the following checklist before opening an issue:

Describe the bug

I schedule a powershell script to run every 5 minutes with "pwsh -file FILENAME" on
OS Name: Microsoft Windows Server 2019 Standard
OS Version: 10.0.17763 N/A Build 17763a
and use cmdlet
Connect-MgGraph -Verbose -ClientId "$clientId" -TenantId "$tenantID" -CertificateThumbprint "$Thumbprint"
which works most times but sometimes fails with the feedback
ClientCertificateCredential authentication failed: Key not valid for use in specified state.

To Reproduce
Steps to reproduce the behavior:

I never got the error when I run the script "manually" - I see it only from time to time when it is run by task manager
When I used a self-signed certiificate which wasn't exportable I noticed that the error starts and stayed until I run the script
"manually". I created a new self-signed certificate which is exportable. With this certificate the issue occurs sometimes but
sometimes it is working again without interaction!
I would be glad to be able to reproduce the issue, but it is so frustrading ....

Expected behavior

I expect that the cmdlet works and the connection is established or it provides a meaningful error code

Debug Output

Run the problematic command with -Debug and paste the resulting debug stream below.
⚠ ATTENTION: Be sure to remove any sensitive information that may be in the logs.

Module Version

Please run Get-Module Microsoft.Graph* after cmdlet execution and paste the output below.
ModuleType Version Name ExportedCommands


Script 2.8.0 Microsoft.Graph.Authentication {Add-MgEnvironment, Connect-MgGraph, Disconnect-MgGraph, Get-MgContext...}
Script 2.8.0 Microsoft.Graph.Security {Add-MgSecurityCaseEdiscoveryCaseCustodianHold, Add-MgSecurityCaseEdiscoveryCaseNoncustodialDataSourceHold, Add-MgSecurityCaseEdiscoveryCaseReviewSetQueryTag, Add-MgSecurit...

Environment Data

Please run $PSVersionTable and paste the output below. If running the Docker container image, indicate the tag of the image used and the version of Docker engine.
Name Value


PSVersion 7.3.9
PSEdition Core
GitCommitId 7.3.9
OS Microsoft Windows 10.0.17763
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

Screenshots

If applicable, add screenshots to help explain your problem.

Additional context

Add any other context about the problem here.

@MGBASF
Copy link
Author

MGBASF commented Nov 22, 2023

@timayabi2020 Here is more log information:
11/22/2023 16:26:09 Connect-MgGraph ....
DEBUG: ClientCertificateCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] MSAL MSAL.NetCore with assembly version '4.49.1.0'. CorrelationId(d6133833-b9be-4345-8556-e22ddfb3915a)
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] === AcquireTokenForClientParameters ===
SendX5C: False
ForceRefresh: False
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a]
=== Request Data ===
Authority Provided? - True
Scopes - https://graph.microsoft.com/.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenForClient
IsConfidentialClient - True
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - d6133833-b9be-4345-8556-e22ddfb3915a
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] === Token Acquisition (ClientCredentialRequest) started:
Scopes: https://graph.microsoft.com/.default
Authority Host: login.microsoftonline.com
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] [Instance Discovery] Instance discovery is enabled and will be performed
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] [Region discovery] Not using a regional authority.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] Fetching instance discovery from the network from host login.microsoftonline.com.
DEBUG: Request [a3170872-69bf-4add-95a5-2e46829b8241] GET https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=REDACTED
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
x-ms-client-request-id:a3170872-69bf-4add-95a5-2e46829b8241
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.9.0 (.NET 8.0.0; Microsoft Windows 10.0.17763)
client assembly: Azure.Identity
DEBUG: Response [a3170872-69bf-4add-95a5-2e46829b8241] 200 OK (00.2s)
Cache-Control:max-age=86400, private
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
Access-Control-Allow-Origin:REDACTED
Access-Control-Allow-Methods:REDACTED
P3P:REDACTED
client-request-id:REDACTED
x-ms-request-id:4281a7db-6bdd-4b9c-a87e-cf64eb049e00
x-ms-ests-server:REDACTED
X-XSS-Protection:REDACTED
Set-Cookie:REDACTED
Date:Wed, 22 Nov 2023 15:26:10 GMT
Content-Type:application/json; charset=utf-8
Content-Length:980
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] Authority validation enabled? True.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:10Z - d6133833-b9be-4345-8556-e22ddfb3915a] Authority validation - is known env? True.
DEBUG: False MSAL 4.49.1.0 MSAL.NetCore .NET 8.0.0 Microsoft Windows 10.0.17763 [2023-11-22 15:26:11Z - d6133833-b9be-4345-8556-e22ddfb3915a] Exception type: System.Security.Cryptography.CryptographicException

at System.Security.Cryptography.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.X509Certificates.CertificatePal.<>c.b__68_0(CspParameters csp)
at System.Security.Cryptography.X509Certificates.CertificatePal.GetPrivateKey[T](Func2 createCsp, Func2 createCng)
at System.Security.Cryptography.X509Certificates.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate1 matchesConstraints) at Microsoft.Identity.Client.PlatformsCommon.Shared.CommonCryptographyManager.SignWithCertificate(String message, X509Certificate2 certificate) at Microsoft.Identity.Client.Internal.JsonWebToken.Sign(X509Certificate2 certificate, String base64EncodedThumbprint, Boolean sendX5C) at Microsoft.Identity.Client.Internal.ClientCredential.CertificateAndClaimsClientCredential.AddConfidentialClientParametersAsync(OAuth2Client oAuth2Client, ILoggerAdapter logger, ICryptographyManager cryptographyManager, String clientId, String tokenEndpoint, Boolean sendX5C, CancellationToken cancellationToken) at Microsoft.Identity.Client.OAuth2.TokenClient.AddBodyParamsAndHeadersAsync(IDictionary2 additionalBodyParameters, String scopes, CancellationToken cancellationToken)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.FetchNewAccessTokenAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
DEBUG: ClientCertificateCredential.GetToken was unable to retrieve an access token. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId: Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ClientCertificateCredential authentication failed: Key not valid for use in specified state.
---> System.Security.Cryptography.CryptographicException (0x8009000b): Key not valid for use in specified state.
Connect-MgGraph: C:\Users\USERNAME\PowerShell\Provider\Check-ConnectMgGraph.ps1:14
Line |
14 | Connect-MgGraph -debug -Verbose -ClientId "$clientId" -TenantId "$ten …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ClientCertificateCredential authentication failed: Key not valid for use in specified state.
Connect-MgGraph: C:\Users\USERNAME\PowerShell\Provider\Check-ConnectMgGraph.ps1:14
Line |
14 | Connect-MgGraph -debug -Verbose -ClientId "$clientId" -TenantId "$ten …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ClientCertificateCredential authentication failed: Key not valid for use in specified state.

@MGBASF
Copy link
Author

MGBASF commented Dec 1, 2023

It seems to make no difference / it doesn't solve the issue when I use
Connect-MgGraph -debug -Verbose -ClientId "$clientId" -TenantId "$tenantID" -Certificate $certificate
instead of
Connect-MgGraph -debug -Verbose -ClientId "$clientId" -TenantId "$tenantID" -CertificateThumbprint "$Thumbprint"

I try it every minute in the meantime, in 10% of the connection tries I got the error message
ClientCertificateCredential authentication failed: Key not valid for use in specified state.

@MGBASF
Copy link
Author

MGBASF commented Dec 19, 2023

Does anybody have an idea to solve the issue?

@timayabi2020
Copy link
Contributor

Hi @MGBASF I haven't been able to reproduce your issue. However, this looks like a Microsoft Authentication Library (MSAL) issue since it's supposed to refresh the cached access token.
For now, could you try deleting .graph folder in C:\Users\{your_username}\ and try again.

@MGBASF
Copy link
Author

MGBASF commented Dec 19, 2023 via email

@petrhollayms
Copy link

Hi @MGBASF ,

Does the issue still persist? If so, could you please test with the latest SDK version i.e. 2.19 and share the output?

@petrhollayms petrhollayms added status:waiting-for-author-feedback Issue that we've responded but needs author feedback to close and removed Needs: Attention 👋 labels May 27, 2024
Copy link
Contributor

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment.

@1EDExg0ffyXfTEqdIUAYNZGnCeajIxMWd2vaQeP

bump

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-recent-activity status:waiting-for-author-feedback Issue that we've responded but needs author feedback to close
Projects
None yet
Development

No branches or pull requests

4 participants