Repository navigation
Acl fix #392
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
Merged
Acl fix #392
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6d98828
Update SecurityService.cs: Add comment
whamm86 cca0c4e
Bug Fix: When multiple ACLs apply to a data record, ACLs granting dat…
whamm86 2c29e60
Always check for trust list, add token:realm_access, some refactioring
whamm86 9577821
Remove references to specific idp from default settings
whamm86 7a9132b
Adapt line endings of SecurityService to main
whamm86 a4cd9f6
Improve logging
whamm86 bf2e6fc
Further improve logging
whamm86 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| /******************************************************************************** | ||
| * Copyright (c) {2019 - 2024} Contributors to the Eclipse Foundation | ||
| * | ||
| * See the NOTICE file(s) distributed with this work for additional | ||
| * information regarding copyright ownership. | ||
| * | ||
| * This program and the accompanying materials are made available under the | ||
| * terms of the Apache License Version 2.0 which is available at | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| ********************************************************************************/ | ||
|
|
||
| using System.Collections.Concurrent; | ||
| using System.IdentityModel.Tokens.Jwt; | ||
| using System.Text.Json; | ||
| using AasSecurity.Models; | ||
| using AasxServerStandardBib.Services; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.IdentityModel.Tokens; | ||
|
|
||
| namespace AasSecurity | ||
| { | ||
| /// <summary> | ||
| /// Validates bearer tokens with a "kid" header against the JWKS of a trusted issuer. | ||
| /// Only issuers/kids from the trust list are accepted; JWKS urls are derived from the trust list | ||
| /// entry only, never from the token itself. | ||
| /// </summary> | ||
| internal static class JwksTokenValidator | ||
| { | ||
| private static readonly ConcurrentDictionary<TrustedServer, bool> _warnedNoAudience = new(); | ||
|
|
||
| /// <param name="httpGet">Fetches the content of a url (injected for testability).</param> | ||
| /// <param name="globalAudienceCsv">Fallback audiences (TOKEN_AUDIENCE) for entries without own audience.</param> | ||
| internal static bool TryValidate(string bearerToken, string? kid, string? iss, IReadOnlyList<TrustedServer> entries, | ||
| Func<string, string> httpGet, string? globalAudienceCsv, ILogger logger, out string domain) | ||
| { | ||
| domain = ""; | ||
|
|
||
| var entry = SecurityHelper.FindTrustedJwksEntry(entries, kid, iss); | ||
| if (entry == null) | ||
| { | ||
| logger.LogWarning("Token rejected: issuer {Issuer} / kid {Kid} is not in the trust list.", | ||
| LogSanitizer.Sanitize(iss), LogSanitizer.Sanitize(kid)); | ||
| return false; | ||
| } | ||
|
|
||
| var jwksUrl = ResolveJwksUrl(entry, httpGet, logger); | ||
| if (string.IsNullOrEmpty(jwksUrl)) | ||
| { | ||
| logger.LogWarning("Token rejected: no jwks url for issuer {Issuer} / kid {Kid}.", | ||
| LogSanitizer.Sanitize(iss), LogSanitizer.Sanitize(kid)); | ||
| return false; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var signingKeys = new JsonWebKeySet(httpGet(jwksUrl)).GetSigningKeys(); | ||
| var audiences = ResolveAudiences(entry, globalAudienceCsv); | ||
| if (audiences.Count == 0 && _warnedNoAudience.TryAdd(entry, true)) | ||
| { | ||
| logger.LogWarning("No audience configured for issuer {Issuer} / kid {Kid} and TOKEN_AUDIENCE is not set: audience is not validated.", | ||
| LogSanitizer.Sanitize(iss), LogSanitizer.Sanitize(kid)); | ||
| } | ||
|
|
||
| var validationParameters = BuildParameters(entry, signingKeys, audiences); | ||
| new JwtSecurityTokenHandler().ValidateToken(bearerToken, validationParameters, out _); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogWarning("Token rejected for issuer {Issuer} / kid {Kid}: {Reason}", | ||
| LogSanitizer.Sanitize(iss), LogSanitizer.Sanitize(kid), LogSanitizer.Sanitize(ex.Message)); | ||
| return false; | ||
| } | ||
|
Comment on lines
+69
to
+74
|
||
|
|
||
| domain = entry.Domain; | ||
| return true; | ||
| } | ||
|
|
||
| internal static string? ResolveJwksUrl(TrustedServer entry, Func<string, string> httpGet, ILogger logger) | ||
| { | ||
| if (!string.IsNullOrEmpty(entry.JwksUrl)) | ||
| { | ||
| return entry.JwksUrl; | ||
| } | ||
|
|
||
| var issuer = SecurityHelper.NormalizeIssuer(entry.Issuer); | ||
| if (issuer == "") | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| using var openIdConfig = JsonDocument.Parse(httpGet($"{issuer}/.well-known/openid-configuration")); | ||
| if (openIdConfig.RootElement.TryGetProperty("jwks_uri", out var jwksUri)) | ||
| { | ||
| return jwksUri.GetString(); | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogWarning("Could not access well-known from {Issuer}: {Reason}", LogSanitizer.Sanitize(issuer), LogSanitizer.Sanitize(ex.Message)); | ||
| } | ||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment on lines
+101
to
+104
|
||
|
|
||
| return $"{issuer}/jwks"; | ||
| } | ||
|
|
||
| internal static IReadOnlyList<string> ResolveAudiences(TrustedServer entry, string? globalAudienceCsv) | ||
| { | ||
| if (entry.Audiences.Count > 0) | ||
| { | ||
| return entry.Audiences; | ||
| } | ||
|
|
||
| return (globalAudienceCsv ?? "").Split(',').Select(a => a.Trim()).Where(a => a != "").ToList(); | ||
| } | ||
|
|
||
| internal static TokenValidationParameters BuildParameters(TrustedServer entry, IEnumerable<SecurityKey> signingKeys, | ||
| IReadOnlyList<string> audiences) | ||
| { | ||
| var parameters = new TokenValidationParameters | ||
| { | ||
| ValidateLifetime = true, | ||
| ValidateIssuerSigningKey = true, | ||
| RequireSignedTokens = true, | ||
| IssuerSigningKeys = signingKeys, | ||
| // Entries matched by kid only have no configured issuer; their keys are pinned by the configured jwks url. | ||
| ValidateIssuer = entry.Issuer != "", | ||
| ValidateAudience = audiences.Count > 0, | ||
| ValidAudiences = audiences | ||
| }; | ||
|
|
||
| if (entry.Issuer != "") | ||
| { | ||
| var normalized = SecurityHelper.NormalizeIssuer(entry.Issuer); | ||
| parameters.ValidIssuers = new[] { entry.Issuer, normalized, normalized + "/" }.Distinct().ToList(); | ||
| } | ||
|
|
||
| return parameters; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| /******************************************************************************** | ||
| * Copyright (c) {2019 - 2024} Contributors to the Eclipse Foundation | ||
| * | ||
| * See the NOTICE file(s) distributed with this work for additional | ||
| * information regarding copyright ownership. | ||
| * | ||
| * This program and the accompanying materials are made available under the | ||
| * terms of the Apache License Version 2.0 which is available at | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| ********************************************************************************/ | ||
|
|
||
| using System.Security.Cryptography.X509Certificates; | ||
|
|
||
| namespace AasSecurity.Models | ||
| { | ||
| /// <summary> | ||
| /// One trusted token issuer, read from trustlist.txt, trustlist.xml or the publicCertificate | ||
| /// of the SecuritySettingsForServer submodel. | ||
| /// A certificate entry (Certificate + CertFileName) validates tokens carrying a "serverName" claim. | ||
| /// A JWKS entry (Issuer and/or Kid, optional JwksUrl) validates tokens carrying a "kid" header. | ||
| /// </summary> | ||
| internal sealed class TrustedServer | ||
| { | ||
| public X509Certificate2? Certificate { get; init; } | ||
| public string CertFileName { get; init; } = ""; | ||
| public string Domain { get; init; } = ""; | ||
| public string JwksUrl { get; init; } = ""; | ||
| public string Issuer { get; init; } = ""; | ||
| public string Kid { get; init; } = ""; | ||
| public IReadOnlyList<string> Audiences { get; init; } = []; | ||
| public string Source { get; init; } = ""; | ||
|
|
||
| public bool IsJwksEntry => !string.IsNullOrEmpty(Issuer) || !string.IsNullOrEmpty(Kid); | ||
|
|
||
| public override string ToString() => | ||
| !string.IsNullOrEmpty(Issuer) ? $"issuer {Issuer} ({Source})" : | ||
| !string.IsNullOrEmpty(Kid) ? $"kid {Kid} ({Source})" : | ||
| $"certificate {CertFileName} ({Source})"; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.