|
15 | 15 | using Microsoft.Azure.Commands.Common.Authentication.Abstractions; |
16 | 16 | using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Models; |
17 | 17 | using Microsoft.Azure.Commands.Common.Authentication.Properties; |
| 18 | +using Microsoft.Azure.Commands.ResourceManager.Common; |
| 19 | +using Microsoft.Identity.Client; |
| 20 | +using Microsoft.Identity.Client.AuthScheme; |
| 21 | +using Microsoft.Identity.Client.Extensibility; |
18 | 22 | using Microsoft.Identity.Client.SSHCertificates; |
19 | 23 | using Microsoft.WindowsAzure.Commands.Utilities.Common; |
20 | 24 |
|
21 | 25 | using Newtonsoft.Json; |
22 | 26 |
|
23 | 27 | using System; |
24 | 28 | using System.Collections.Generic; |
| 29 | +using System.Security; |
25 | 30 | using System.Security.Cryptography; |
| 31 | +using System.Security.Cryptography.X509Certificates; |
26 | 32 | using System.Text; |
27 | 33 |
|
28 | 34 | namespace Microsoft.Azure.Commands.Common.Authentication.Factories |
@@ -62,29 +68,184 @@ public SshCredential GetSshCredential(IAzureContext context, RSAParameters rsaKe |
62 | 68 | throw new NullReferenceException(Resources.AuthenticationClientFactoryNotRegistered); |
63 | 69 | } |
64 | 70 |
|
65 | | - var publicClient = tokenCacheProvider.CreatePublicClient(context.Environment.ActiveDirectoryAuthority, context.Tenant.Id); |
66 | 71 | string scope = GetAuthScope(); |
67 | 72 | List<string> scopes = new List<string>() { scope }; |
68 | 73 | var jwk = CreateJwk(rsaKeyInfo, out string keyId); |
69 | 74 |
|
| 75 | + switch (context.Account.Type) |
| 76 | + { |
| 77 | + case AzureAccount.AccountType.User: |
| 78 | + return AcquireTokenForUser(tokenCacheProvider, context, scopes, jwk, keyId); |
| 79 | + case AzureAccount.AccountType.ServicePrincipal: |
| 80 | + return AcquireTokenForServicePrincipal(tokenCacheProvider, context, scopes, jwk, keyId); |
| 81 | + default: |
| 82 | + throw new InvalidOperationException(string.Format(Resources.UnsupportedAccountTypeForSshCertificate, context.Account.Type)); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + private SshCredential AcquireTokenForUser(PowerShellTokenCacheProvider tokenCacheProvider, IAzureContext context, List<string> scopes, string jwk, string keyId) |
| 87 | + { |
| 88 | + var publicClient = tokenCacheProvider.CreatePublicClient(context.Environment.ActiveDirectoryAuthority, context.Tenant.Id); |
| 89 | + |
70 | 90 | var account = publicClient.GetAccountAsync(context.Account.ExtendedProperties["HomeAccountId"]) |
71 | 91 | .ConfigureAwait(false).GetAwaiter().GetResult(); |
72 | 92 | var result = publicClient.AcquireTokenSilent(scopes, account) |
73 | 93 | .WithSSHCertificateAuthenticationScheme(jwk, keyId) |
74 | 94 | .ExecuteAsync(); |
75 | 95 | var accessToken = result.ConfigureAwait(false).GetAwaiter().GetResult(); |
76 | 96 |
|
77 | | - var resultToken = new SshCredential() |
| 97 | + return new SshCredential() |
78 | 98 | { |
79 | 99 | Credential = accessToken.AccessToken, |
80 | 100 | ExpiresOn = accessToken.ExpiresOn, |
81 | 101 | }; |
82 | | - return resultToken; |
| 102 | + } |
| 103 | + |
| 104 | + private SshCredential AcquireTokenForServicePrincipal(PowerShellTokenCacheProvider tokenCacheProvider, IAzureContext context, List<string> scopes, string jwk, string keyId) |
| 105 | + { |
| 106 | + string authority = context.Environment.ActiveDirectoryAuthority; |
| 107 | + string tenantId = context.Tenant.Id; |
| 108 | + string clientId = context.Account.Id; |
| 109 | + |
| 110 | + var confidentialClient = CreateConfidentialClientForServicePrincipal(tokenCacheProvider, authority, tenantId, clientId, context); |
| 111 | + |
| 112 | + var authExtension = new MsalAuthenticationExtension |
| 113 | + { |
| 114 | + AuthenticationOperation = new SshCertAuthOperation(keyId, jwk) |
| 115 | + }; |
| 116 | + |
| 117 | + var result = confidentialClient.AcquireTokenForClient(scopes) |
| 118 | + .WithForceRefresh(true) |
| 119 | + .WithAuthenticationExtension(authExtension) |
| 120 | + .ExecuteAsync() |
| 121 | + .ConfigureAwait(false).GetAwaiter().GetResult(); |
| 122 | + |
| 123 | + return new SshCredential() |
| 124 | + { |
| 125 | + Credential = result.AccessToken, |
| 126 | + ExpiresOn = result.ExpiresOn, |
| 127 | + }; |
| 128 | + } |
| 129 | + |
| 130 | + private IConfidentialClientApplication CreateConfidentialClientForServicePrincipal(PowerShellTokenCacheProvider tokenCacheProvider, string authority, string tenantId, string clientId, IAzureContext context) |
| 131 | + { |
| 132 | + // Try certificate thumbprint first |
| 133 | + string thumbprint = context.Account.GetProperty(AzureAccount.Property.CertificateThumbprint); |
| 134 | + if (!string.IsNullOrEmpty(thumbprint)) |
| 135 | + { |
| 136 | + var certificate = AzureSession.Instance.DataStore.GetCertificate(thumbprint); |
| 137 | + if (certificate != null) |
| 138 | + { |
| 139 | + return tokenCacheProvider.CreateConfidentialClient(authority, tenantId, clientId, certificate); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + // Try certificate path |
| 144 | + string certificatePath = context.Account.GetProperty(AzureAccount.Property.CertificatePath); |
| 145 | + if (!string.IsNullOrEmpty(certificatePath)) |
| 146 | + { |
| 147 | + SecureString certificatePassword = GetServicePrincipalSecureString(context, AzureAccount.Property.CertificatePassword); |
| 148 | + X509Certificate2 certificate = certificatePassword != null |
| 149 | + ? new X509Certificate2(certificatePath, certificatePassword) |
| 150 | + : new X509Certificate2(certificatePath); |
| 151 | + return tokenCacheProvider.CreateConfidentialClient(authority, tenantId, clientId, certificate); |
| 152 | + } |
| 153 | + |
| 154 | + // Try client secret |
| 155 | + string secret = context.Account.GetProperty(AzureAccount.Property.ServicePrincipalSecret); |
| 156 | + if (string.IsNullOrEmpty(secret)) |
| 157 | + { |
| 158 | + SecureString secureSecret = GetServicePrincipalSecureString(context, AzureAccount.Property.ServicePrincipalSecret); |
| 159 | + if (secureSecret != null) |
| 160 | + { |
| 161 | + secret = ConvertToPlainText(secureSecret); |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + if (!string.IsNullOrEmpty(secret)) |
| 166 | + { |
| 167 | + return tokenCacheProvider.CreateConfidentialClient(authority, tenantId, clientId, secret); |
| 168 | + } |
| 169 | + |
| 170 | + throw new InvalidOperationException(Resources.ServicePrincipalCredentialNotFound); |
| 171 | + } |
| 172 | + |
| 173 | + private SecureString GetServicePrincipalSecureString(IAzureContext context, string propertyName) |
| 174 | + { |
| 175 | + try |
| 176 | + { |
| 177 | + if (AzureSession.Instance.TryGetComponent(AzKeyStore.Name, out AzKeyStore keyStore)) |
| 178 | + { |
| 179 | + return keyStore.GetSecureString(new ServicePrincipalKey(propertyName, context.Account.Id, context.Tenant.Id)); |
| 180 | + } |
| 181 | + } |
| 182 | + catch |
| 183 | + { |
| 184 | + // Key not found in store, return null |
| 185 | + } |
| 186 | + return null; |
| 187 | + } |
| 188 | + |
| 189 | + private static string ConvertToPlainText(SecureString secureString) |
| 190 | + { |
| 191 | + if (secureString == null) |
| 192 | + { |
| 193 | + return null; |
| 194 | + } |
| 195 | + var ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secureString); |
| 196 | + try |
| 197 | + { |
| 198 | + return System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr); |
| 199 | + } |
| 200 | + finally |
| 201 | + { |
| 202 | + System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr); |
| 203 | + } |
83 | 204 | } |
84 | 205 |
|
85 | 206 | private string GetAuthScope() |
86 | 207 | { |
87 | 208 | return $"{AadSshLoginForLinuxServerAppId}/.default"; |
88 | 209 | } |
| 210 | + |
| 211 | + /// <summary> |
| 212 | + /// Custom IAuthenticationOperation that instructs MSAL to request and accept |
| 213 | + /// SSH certificate token type instead of bearer tokens. |
| 214 | + /// This is the equivalent of WithSSHCertificateAuthenticationScheme for confidential client flows. |
| 215 | + /// </summary> |
| 216 | + private class SshCertAuthOperation : IAuthenticationOperation |
| 217 | + { |
| 218 | + private const string SshCertTokenType = "ssh-cert"; |
| 219 | + private readonly string _jwk; |
| 220 | + |
| 221 | + public SshCertAuthOperation(string keyId, string jwk) |
| 222 | + { |
| 223 | + KeyId = keyId; |
| 224 | + _jwk = jwk; |
| 225 | + } |
| 226 | + |
| 227 | + public int TelemetryTokenType => 3; |
| 228 | + |
| 229 | + public string AuthorizationHeaderPrefix => |
| 230 | + throw new InvalidOperationException("SSH certificates cannot be used as HTTP authorization headers."); |
| 231 | + |
| 232 | + public string AccessTokenType => SshCertTokenType; |
| 233 | + |
| 234 | + public string KeyId { get; } |
| 235 | + |
| 236 | + public IReadOnlyDictionary<string, string> GetTokenRequestParams() |
| 237 | + { |
| 238 | + return new Dictionary<string, string> |
| 239 | + { |
| 240 | + { "token_type", SshCertTokenType }, |
| 241 | + { "req_cnf", _jwk } |
| 242 | + }; |
| 243 | + } |
| 244 | + |
| 245 | + public void FormatResult(AuthenticationResult authenticationResult) |
| 246 | + { |
| 247 | + // no-op |
| 248 | + } |
| 249 | + } |
89 | 250 | } |
90 | 251 | } |
0 commit comments