| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Globalization; |
| | 6 | | using System.IO; |
| | 7 | | using System.Net; |
| | 8 | | using System.Net.Sockets; |
| | 9 | | using System.Text; |
| | 10 | | using System.Text.Json; |
| | 11 | | using System.Threading; |
| | 12 | | using System.Threading.Tasks; |
| | 13 | | using Azure.Core; |
| | 14 | |
|
| | 15 | | namespace Azure.Identity |
| | 16 | | { |
| | 17 | | internal class ManagedIdentityClient |
| | 18 | | { |
| | 19 | | private const string AuthenticationResponseInvalidFormatError = "Invalid response, the authentication response w |
| | 20 | | private const string MsiEndpointInvalidUriError = "The environment variable MSI_ENDPOINT contains an invalid Uri |
| | 21 | | internal const string MsiUnavailableError = "ManagedIdentityCredential authentication unavailable. No Managed Id |
| | 22 | | internal const string IdentityUnavailableError = "ManagedIdentityCredential authentication unavailable. The requ |
| | 23 | |
|
| | 24 | | // IMDS constants. Docs for IMDS are available here https://docs.microsoft.com/en-us/azure/active-directory/mana |
| 2 | 25 | | private static readonly Uri s_imdsEndpoint = new Uri("http://169.254.169.254/metadata/identity/oauth2/token"); |
| 2 | 26 | | private static readonly IPAddress s_imdsHostIp = IPAddress.Parse("169.254.169.254"); |
| | 27 | | private const int s_imdsPort = 80; |
| | 28 | | private const string ImdsApiVersion = "2018-02-01"; |
| | 29 | | private const int ImdsAvailableTimeoutMs = 1000; |
| | 30 | |
|
| | 31 | | // MSI Constants. Docs for MSI are available here https://docs.microsoft.com/en-us/azure/app-service/overview-ma |
| | 32 | | private const string AppServiceMsiApiVersion = "2017-09-01"; |
| | 33 | |
|
| 2 | 34 | | private static readonly SemaphoreSlim _initLock = new SemaphoreSlim(1, 1); |
| | 35 | | private MsiType _msiType; |
| | 36 | | private Uri _endpoint; |
| | 37 | |
|
| | 38 | | private readonly CredentialPipeline _pipeline; |
| | 39 | |
|
| 0 | 40 | | protected ManagedIdentityClient() |
| | 41 | | { |
| 0 | 42 | | } |
| | 43 | |
|
| 70 | 44 | | public ManagedIdentityClient(CredentialPipeline pipeline, string clientId = null) |
| | 45 | | { |
| 70 | 46 | | _pipeline = pipeline; |
| | 47 | |
|
| 70 | 48 | | ClientId = clientId; |
| 70 | 49 | | } |
| | 50 | |
|
| 40 | 51 | | protected string ClientId { get; } |
| | 52 | |
|
| | 53 | | public virtual AccessToken Authenticate(string[] scopes, CancellationToken cancellationToken) |
| | 54 | | { |
| 32 | 55 | | MsiType msiType = GetMsiType(cancellationToken); |
| | 56 | |
|
| | 57 | | // if msi is unavailable or we were unable to determine the type return CredentialUnavailable exception that |
| 28 | 58 | | if (msiType == MsiType.Unavailable || msiType == MsiType.Unknown) |
| | 59 | | { |
| 16 | 60 | | throw new CredentialUnavailableException(MsiUnavailableError); |
| | 61 | | } |
| | 62 | |
|
| 12 | 63 | | using Request request = CreateAuthRequest(msiType, scopes); |
| | 64 | |
|
| 12 | 65 | | Response response = _pipeline.HttpPipeline.SendRequest(request, cancellationToken); |
| | 66 | |
|
| 12 | 67 | | if (response.Status == 200) |
| | 68 | | { |
| 12 | 69 | | AccessToken result = Deserialize(response.ContentStream); |
| | 70 | |
|
| 12 | 71 | | return result; |
| | 72 | | } |
| | 73 | |
|
| 0 | 74 | | if (response.Status == 400 && msiType == MsiType.Imds) |
| | 75 | | { |
| 0 | 76 | | _msiType = MsiType.Unavailable; |
| | 77 | |
|
| 0 | 78 | | string message = _pipeline.Diagnostics.CreateRequestFailedMessage(response, message: IdentityUnavailable |
| | 79 | |
|
| 0 | 80 | | throw new CredentialUnavailableException(message); |
| | 81 | | } |
| | 82 | |
|
| 0 | 83 | | throw _pipeline.Diagnostics.CreateRequestFailedException(response); |
| 12 | 84 | | } |
| | 85 | |
|
| | 86 | | public virtual async Task<AccessToken> AuthenticateAsync(string[] scopes, CancellationToken cancellationToken) |
| | 87 | | { |
| 30 | 88 | | MsiType msiType = await GetMsiTypeAsync(cancellationToken).ConfigureAwait(false); |
| | 89 | |
|
| | 90 | | // if msi is unavailable or we were unable to determine the type return CredentialUnavailable exception that |
| 26 | 91 | | if (msiType == MsiType.Unavailable || msiType == MsiType.Unknown) |
| | 92 | | { |
| 14 | 93 | | throw new CredentialUnavailableException(MsiUnavailableError); |
| | 94 | | } |
| | 95 | |
|
| 12 | 96 | | using Request request = CreateAuthRequest(msiType, scopes); |
| | 97 | |
|
| 12 | 98 | | Response response = await _pipeline.HttpPipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait |
| | 99 | |
|
| 12 | 100 | | if (response.Status == 200) |
| | 101 | | { |
| 12 | 102 | | AccessToken result = await DeserializeAsync(response.ContentStream, cancellationToken).ConfigureAwait(fa |
| | 103 | |
|
| 12 | 104 | | return result; |
| | 105 | | } |
| | 106 | |
|
| 0 | 107 | | if (response.Status == 400 && msiType == MsiType.Imds) |
| | 108 | | { |
| 0 | 109 | | _msiType = MsiType.Unavailable; |
| | 110 | |
|
| 0 | 111 | | string message = await _pipeline.Diagnostics.CreateRequestFailedMessageAsync(response, message: Identity |
| | 112 | |
|
| 0 | 113 | | throw new CredentialUnavailableException(message); |
| | 114 | | } |
| | 115 | |
|
| 0 | 116 | | throw await _pipeline.Diagnostics.CreateRequestFailedExceptionAsync(response).ConfigureAwait(false); |
| 12 | 117 | | } |
| | 118 | |
|
| | 119 | | protected virtual MsiType GetMsiType(CancellationToken cancellationToken) |
| | 120 | | { |
| | 121 | | // if we haven't already determined the msi type |
| 28 | 122 | | if (_msiType == MsiType.Unknown) |
| | 123 | | { |
| | 124 | | // acquire the init lock |
| 26 | 125 | | _initLock.Wait(cancellationToken); |
| | 126 | |
|
| | 127 | | try |
| | 128 | | { |
| | 129 | | // check again if the we already determined the msiType now that we hold the lock |
| 24 | 130 | | if (_msiType == MsiType.Unknown) |
| | 131 | | { |
| 24 | 132 | | string endpointEnvVar = EnvironmentVariables.MsiEndpoint; |
| 24 | 133 | | string secretEnvVar = EnvironmentVariables.MsiSecret; |
| | 134 | |
|
| | 135 | | // if the env var MSI_ENDPOINT is set |
| 24 | 136 | | if (!string.IsNullOrEmpty(endpointEnvVar)) |
| | 137 | | { |
| | 138 | | try |
| | 139 | | { |
| 8 | 140 | | _endpoint = new Uri(endpointEnvVar); |
| 8 | 141 | | } |
| 0 | 142 | | catch (FormatException ex) |
| | 143 | | { |
| 0 | 144 | | throw new AuthenticationFailedException(MsiEndpointInvalidUriError, ex); |
| | 145 | | } |
| | 146 | |
|
| | 147 | | // if BOTH the env vars MSI_ENDPOINT and MSI_SECRET are set the MsiType is AppService |
| 8 | 148 | | if (!string.IsNullOrEmpty(secretEnvVar)) |
| | 149 | | { |
| 4 | 150 | | _msiType = MsiType.AppService; |
| | 151 | | } |
| | 152 | | // if ONLY the env var MSI_ENDPOINT is set the MsiType is CloudShell |
| | 153 | | else |
| | 154 | | { |
| 4 | 155 | | _msiType = MsiType.CloudShell; |
| | 156 | | } |
| | 157 | | } |
| | 158 | | // if MSI_ENDPOINT is NOT set AND the IMDS endpoint is available the MsiType is Imds |
| 16 | 159 | | else if (ImdsAvailable(cancellationToken)) |
| | 160 | | { |
| 4 | 161 | | _endpoint = s_imdsEndpoint; |
| 4 | 162 | | _msiType = MsiType.Imds; |
| | 163 | | } |
| | 164 | | // if MSI_ENDPOINT is NOT set and IMDS endpoint is not available ManagedIdentity is not availabl |
| | 165 | | else |
| | 166 | | { |
| 12 | 167 | | _msiType = MsiType.Unavailable; |
| | 168 | | } |
| | 169 | | } |
| 12 | 170 | | } |
| | 171 | | // release the init lock |
| | 172 | | finally |
| | 173 | | { |
| 24 | 174 | | _initLock.Release(); |
| 24 | 175 | | } |
| | 176 | | } |
| | 177 | |
|
| 26 | 178 | | return _msiType; |
| | 179 | | } |
| | 180 | |
|
| | 181 | | protected virtual async Task<MsiType> GetMsiTypeAsync(CancellationToken cancellationToken) |
| | 182 | | { |
| | 183 | | // if we haven't already determined the msi type |
| 26 | 184 | | if (_msiType == MsiType.Unknown) |
| | 185 | | { |
| | 186 | | // acquire the init lock |
| 26 | 187 | | await _initLock.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | 188 | |
|
| | 189 | | try |
| | 190 | | { |
| | 191 | | // check again if the we already determined the msiType now that we hold the lock |
| 24 | 192 | | if (_msiType == MsiType.Unknown) |
| | 193 | | { |
| 24 | 194 | | string endpointEnvVar = EnvironmentVariables.MsiEndpoint; |
| 24 | 195 | | string secretEnvVar = EnvironmentVariables.MsiSecret; |
| | 196 | |
|
| | 197 | | // if the env var MSI_ENDPOINT is set |
| 24 | 198 | | if (!string.IsNullOrEmpty(endpointEnvVar)) |
| | 199 | | { |
| | 200 | | try |
| | 201 | | { |
| 8 | 202 | | _endpoint = new Uri(endpointEnvVar); |
| 8 | 203 | | } |
| 0 | 204 | | catch (FormatException ex) |
| | 205 | | { |
| 0 | 206 | | throw new AuthenticationFailedException(MsiEndpointInvalidUriError, ex); |
| | 207 | | } |
| | 208 | |
|
| | 209 | | // if BOTH the env vars MSI_ENDPOINT and MSI_SECRET are set the MsiType is AppService |
| 8 | 210 | | if (!string.IsNullOrEmpty(secretEnvVar)) |
| | 211 | | { |
| 4 | 212 | | _msiType = MsiType.AppService; |
| | 213 | | } |
| | 214 | | // if ONLY the env var MSI_ENDPOINT is set the MsiType is CloudShell |
| | 215 | | else |
| | 216 | | { |
| 4 | 217 | | _msiType = MsiType.CloudShell; |
| | 218 | | } |
| | 219 | | } |
| | 220 | | // if MSI_ENDPOINT is NOT set AND the IMDS endpoint is available the MsiType is Imds |
| 16 | 221 | | else if (await ImdsAvailableAsync(cancellationToken).ConfigureAwait(false)) |
| | 222 | | { |
| 4 | 223 | | _endpoint = s_imdsEndpoint; |
| 4 | 224 | | _msiType = MsiType.Imds; |
| | 225 | | } |
| | 226 | | // if MSI_ENDPOINT is NOT set and IMDS endpoint is not available ManagedIdentity is not availabl |
| | 227 | | else |
| | 228 | | { |
| 12 | 229 | | _msiType = MsiType.Unavailable; |
| | 230 | | } |
| | 231 | | } |
| 24 | 232 | | } |
| | 233 | | // release the init lock |
| | 234 | | finally |
| | 235 | | { |
| 24 | 236 | | _initLock.Release(); |
| | 237 | | } |
| | 238 | | } |
| | 239 | |
|
| 24 | 240 | | return _msiType; |
| 24 | 241 | | } |
| | 242 | |
|
| | 243 | | protected virtual bool ImdsAvailable(CancellationToken cancellationToken) |
| | 244 | | { |
| 12 | 245 | | AzureIdentityEventSource.Singleton.ProbeImdsEndpoint(s_imdsEndpoint); |
| | 246 | |
|
| | 247 | | bool available; |
| | 248 | | // try to create a TCP connection to the IMDS IP address. If the connection can be established |
| | 249 | | // we assume that IMDS is available. If connecting times out or fails to connect assume that |
| | 250 | | // IMDS is not available in this environment. |
| | 251 | | try |
| | 252 | | { |
| 12 | 253 | | using (var client = new TcpClient()) |
| | 254 | | { |
| 12 | 255 | | var result = client.BeginConnect(s_imdsHostIp, s_imdsPort, null, null); |
| | 256 | |
|
| 12 | 257 | | var success = result.AsyncWaitHandle.WaitOne(ImdsAvailableTimeoutMs); |
| | 258 | |
|
| 12 | 259 | | available = success && client.Connected; |
| 12 | 260 | | } |
| 12 | 261 | | } |
| 0 | 262 | | catch |
| | 263 | | { |
| 0 | 264 | | available = false; |
| 0 | 265 | | } |
| | 266 | |
|
| 12 | 267 | | if (available) |
| | 268 | | { |
| 0 | 269 | | AzureIdentityEventSource.Singleton.ImdsEndpointFound(s_imdsEndpoint); |
| | 270 | | } |
| | 271 | | else |
| | 272 | | { |
| 12 | 273 | | AzureIdentityEventSource.Singleton.ImdsEndpointUnavailable(s_imdsEndpoint); |
| | 274 | | } |
| | 275 | |
|
| 12 | 276 | | return available; |
| | 277 | | } |
| | 278 | |
|
| | 279 | | protected virtual async Task<bool> ImdsAvailableAsync(CancellationToken cancellationToken) |
| | 280 | | { |
| 12 | 281 | | AzureIdentityEventSource.Singleton.ProbeImdsEndpoint(s_imdsEndpoint); |
| | 282 | |
|
| | 283 | | bool available; |
| | 284 | | // try to create a TCP connection to the IMDS IP address. If the connection can be established |
| | 285 | | // we assume that IMDS is available. If connecting times out or fails to connect assume that |
| | 286 | | // IMDS is not available in this environment. |
| | 287 | | try |
| | 288 | | { |
| 12 | 289 | | using (var client = new TcpClient()) |
| | 290 | | { |
| 12 | 291 | | var result = client.BeginConnect(s_imdsHostIp, s_imdsPort, null, null); |
| | 292 | |
|
| 24 | 293 | | var success = await Task.Run<bool>(() => result.AsyncWaitHandle.WaitOne(ImdsAvailableTimeoutMs), can |
| | 294 | |
|
| 12 | 295 | | available = success && client.Connected; |
| 12 | 296 | | } |
| 12 | 297 | | } |
| 0 | 298 | | catch |
| | 299 | | { |
| 0 | 300 | | available = false; |
| 0 | 301 | | } |
| | 302 | |
|
| 12 | 303 | | if (available) |
| | 304 | | { |
| 0 | 305 | | AzureIdentityEventSource.Singleton.ImdsEndpointFound(s_imdsEndpoint); |
| | 306 | | } |
| | 307 | | else |
| | 308 | | { |
| 12 | 309 | | AzureIdentityEventSource.Singleton.ImdsEndpointUnavailable(s_imdsEndpoint); |
| | 310 | | } |
| | 311 | |
|
| 12 | 312 | | return available; |
| 12 | 313 | | } |
| | 314 | |
|
| | 315 | | private Request CreateAuthRequest(MsiType msiType, string[] scopes) |
| | 316 | | { |
| 24 | 317 | | return msiType switch |
| 24 | 318 | | { |
| 32 | 319 | | MsiType.Imds => CreateImdsAuthRequest(scopes), |
| 32 | 320 | | MsiType.AppService => CreateAppServiceAuthRequest(scopes), |
| 32 | 321 | | MsiType.CloudShell => CreateCloudShellAuthRequest(scopes), |
| 0 | 322 | | _ => default, |
| 24 | 323 | | }; |
| | 324 | | } |
| | 325 | |
|
| | 326 | | private Request CreateImdsAuthRequest(string[] scopes) |
| | 327 | | { |
| | 328 | | // covert the scopes to a resource string |
| 8 | 329 | | string resource = ScopeUtilities.ScopesToResource(scopes); |
| | 330 | |
|
| 8 | 331 | | Request request = _pipeline.HttpPipeline.CreateRequest(); |
| | 332 | |
|
| 8 | 333 | | request.Method = RequestMethod.Get; |
| | 334 | |
|
| 8 | 335 | | request.Headers.Add("Metadata", "true"); |
| | 336 | |
|
| 8 | 337 | | request.Uri.Reset(_endpoint); |
| | 338 | |
|
| 8 | 339 | | request.Uri.AppendQuery("api-version", ImdsApiVersion); |
| | 340 | |
|
| 8 | 341 | | request.Uri.AppendQuery("resource", resource); |
| | 342 | |
|
| 8 | 343 | | if (!string.IsNullOrEmpty(ClientId)) |
| | 344 | | { |
| 8 | 345 | | request.Uri.AppendQuery("client_id", ClientId); |
| | 346 | | } |
| | 347 | |
|
| 8 | 348 | | return request; |
| | 349 | | } |
| | 350 | |
|
| | 351 | | private Request CreateAppServiceAuthRequest(string[] scopes) |
| | 352 | | { |
| | 353 | | // covert the scopes to a resource string |
| 8 | 354 | | string resource = ScopeUtilities.ScopesToResource(scopes); |
| | 355 | |
|
| 8 | 356 | | Request request = _pipeline.HttpPipeline.CreateRequest(); |
| | 357 | |
|
| 8 | 358 | | request.Method = RequestMethod.Get; |
| | 359 | |
|
| 8 | 360 | | request.Headers.Add("secret", EnvironmentVariables.MsiSecret); |
| | 361 | |
|
| 8 | 362 | | request.Uri.Reset(_endpoint); |
| | 363 | |
|
| 8 | 364 | | request.Uri.AppendQuery("api-version", AppServiceMsiApiVersion); |
| | 365 | |
|
| 8 | 366 | | request.Uri.AppendQuery("resource", resource); |
| | 367 | |
|
| 8 | 368 | | if (!string.IsNullOrEmpty(ClientId)) |
| | 369 | | { |
| 4 | 370 | | request.Uri.AppendQuery("clientid", ClientId); |
| | 371 | | } |
| | 372 | |
|
| 8 | 373 | | return request; |
| | 374 | | } |
| | 375 | |
|
| | 376 | | private Request CreateCloudShellAuthRequest(string[] scopes) |
| | 377 | | { |
| | 378 | | // covert the scopes to a resource string |
| 8 | 379 | | string resource = ScopeUtilities.ScopesToResource(scopes); |
| | 380 | |
|
| 8 | 381 | | Request request = _pipeline.HttpPipeline.CreateRequest(); |
| | 382 | |
|
| 8 | 383 | | request.Method = RequestMethod.Post; |
| | 384 | |
|
| 8 | 385 | | request.Headers.Add(HttpHeader.Common.FormUrlEncodedContentType); |
| | 386 | |
|
| 8 | 387 | | request.Uri.Reset(_endpoint); |
| | 388 | |
|
| 8 | 389 | | request.Headers.Add("Metadata", "true"); |
| | 390 | |
|
| 8 | 391 | | var bodyStr = $"resource={Uri.EscapeDataString(resource)}"; |
| | 392 | |
|
| 8 | 393 | | if (!string.IsNullOrEmpty(ClientId)) |
| | 394 | | { |
| 4 | 395 | | bodyStr += $"&client_id={Uri.EscapeDataString(ClientId)}"; |
| | 396 | | } |
| | 397 | |
|
| 8 | 398 | | ReadOnlyMemory<byte> content = Encoding.UTF8.GetBytes(bodyStr).AsMemory(); |
| | 399 | |
|
| 8 | 400 | | request.Content = RequestContent.Create(content); |
| | 401 | |
|
| 8 | 402 | | return request; |
| | 403 | | } |
| | 404 | |
|
| | 405 | | private async Task<AccessToken> DeserializeAsync(Stream content, CancellationToken cancellationToken) |
| | 406 | | { |
| 12 | 407 | | using (JsonDocument json = await JsonDocument.ParseAsync(content, default, cancellationToken).ConfigureAwait |
| | 408 | | { |
| 12 | 409 | | return Deserialize(json.RootElement); |
| | 410 | | } |
| 12 | 411 | | } |
| | 412 | |
|
| | 413 | | private AccessToken Deserialize(Stream content) |
| | 414 | | { |
| 12 | 415 | | using (JsonDocument json = JsonDocument.Parse(content)) |
| | 416 | | { |
| 12 | 417 | | return Deserialize(json.RootElement); |
| | 418 | | } |
| 12 | 419 | | } |
| | 420 | |
|
| | 421 | | private AccessToken Deserialize(JsonElement json) |
| | 422 | | { |
| 24 | 423 | | string accessToken = null; |
| 24 | 424 | | JsonElement? expiresOnProp = null; |
| | 425 | |
|
| 144 | 426 | | foreach (JsonProperty prop in json.EnumerateObject()) |
| | 427 | | { |
| 48 | 428 | | switch (prop.Name) |
| | 429 | | { |
| | 430 | | case "access_token": |
| 24 | 431 | | accessToken = prop.Value.GetString(); |
| 24 | 432 | | break; |
| | 433 | |
|
| | 434 | | case "expires_on": |
| 24 | 435 | | expiresOnProp = prop.Value; |
| | 436 | | break; |
| | 437 | | } |
| | 438 | | } |
| | 439 | |
|
| 24 | 440 | | if (accessToken is null || !expiresOnProp.HasValue) |
| | 441 | | { |
| 0 | 442 | | throw new AuthenticationFailedException(AuthenticationResponseInvalidFormatError); |
| | 443 | | } |
| | 444 | |
|
| | 445 | | DateTimeOffset expiresOn; |
| | 446 | | // if s_msiType is AppService expires_on will be a string formatted datetimeoffset |
| 24 | 447 | | if (_msiType == MsiType.AppService) |
| | 448 | | { |
| 8 | 449 | | if (!DateTimeOffset.TryParse(expiresOnProp.Value.GetString(), CultureInfo.InvariantCulture, DateTimeStyl |
| | 450 | | { |
| 0 | 451 | | throw new AuthenticationFailedException(AuthenticationResponseInvalidFormatError); |
| | 452 | | } |
| | 453 | | } |
| | 454 | | // otherwise expires_on will be a unix timestamp seconds from epoch |
| | 455 | | else |
| | 456 | | { |
| | 457 | | // the seconds from epoch may be returned as a Json number or a Json string which is a number |
| | 458 | | // depending on the environment. If neither of these are the case we throw an AuthException. |
| 16 | 459 | | if (!(expiresOnProp.Value.ValueKind == JsonValueKind.Number && expiresOnProp.Value.TryGetInt64(out long |
| 16 | 460 | | !(expiresOnProp.Value.ValueKind == JsonValueKind.String && long.TryParse(expiresOnProp.Value.GetStri |
| | 461 | | { |
| 0 | 462 | | throw new AuthenticationFailedException(AuthenticationResponseInvalidFormatError); |
| | 463 | | } |
| | 464 | |
|
| 16 | 465 | | expiresOn = DateTimeOffset.FromUnixTimeSeconds(expiresOnSec); |
| | 466 | | } |
| | 467 | |
|
| 24 | 468 | | return new AccessToken(accessToken, expiresOn); |
| | 469 | | } |
| | 470 | |
|
| | 471 | | private struct Error |
| | 472 | | { |
| 0 | 473 | | public string Code { get; set; } |
| | 474 | |
|
| 0 | 475 | | public string Message { get; set; } |
| | 476 | | } |
| | 477 | | } |
| | 478 | | } |