| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace Anichron.API.Services; |
| | | 5 | | |
| | | 6 | | public interface IPwnedPasswordClient |
| | | 7 | | { |
| | | 8 | | Task<bool> IsPwnedAsync(string password, CancellationToken ct); |
| | | 9 | | } |
| | | 10 | | |
| | 9 | 11 | | public sealed partial class PwnedPasswordClient(HttpClient http, ILogger<PwnedPasswordClient> logger) : IPwnedPasswordCl |
| | | 12 | | { |
| | | 13 | | public async Task<bool> IsPwnedAsync(string password, CancellationToken ct) |
| | 9 | 14 | | { |
| | 9 | 15 | | var passwordBytes = Encoding.UTF8.GetBytes(password); |
| | | 16 | | try |
| | 9 | 17 | | { |
| | | 18 | | // SHA1 is not a choice here: the HIBP range endpoint is defined in terms of SHA-1 |
| | | 19 | | // prefixes, so any other algorithm queries a namespace the service does not have. |
| | | 20 | | // S4790 is Sonar's equivalent of CA5350 and arrived with SonarAnalyzer 10.34; both |
| | | 21 | | // are listed so neither analyzer alone fails the build. |
| | | 22 | | #pragma warning disable CA5350, S4790 // SHA1 is required by the HIBP k-anonymity API protocol |
| | 9 | 23 | | var hash = Convert.ToHexString(SHA1.HashData(passwordBytes)); |
| | | 24 | | #pragma warning restore CA5350, S4790 |
| | 9 | 25 | | var prefix = hash[..5]; |
| | 9 | 26 | | var suffix = hash[5..]; |
| | | 27 | | |
| | 9 | 28 | | var body = await http.GetStringAsync($"range/{prefix}", ct); |
| | 7 | 29 | | return body.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries).Any(line => |
| | 7 | 30 | | line.StartsWith(suffix, StringComparison.OrdinalIgnoreCase)); |
| | | 31 | | } |
| | 2 | 32 | | catch (Exception ex) |
| | 2 | 33 | | { |
| | 2 | 34 | | Log.PwnedCheckUnavailable(logger, ex, ex.GetType().Name); |
| | 2 | 35 | | return false; |
| | | 36 | | } |
| | | 37 | | finally |
| | 9 | 38 | | { |
| | 9 | 39 | | CryptographicOperations.ZeroMemory(passwordBytes); |
| | 9 | 40 | | } |
| | 9 | 41 | | } |
| | | 42 | | |
| | | 43 | | private static partial class Log |
| | | 44 | | { |
| | | 45 | | [LoggerMessage(Level = LogLevel.Warning, Message = "Pwned Passwords check unavailable ({ExceptionType}); failing |
| | | 46 | | public static partial void PwnedCheckUnavailable(ILogger logger, Exception ex, string exceptionType); |
| | | 47 | | } |
| | | 48 | | } |