diff --git a/BrowserGuard.Tests/Configuration/testconfig/01_all-disabled.json b/BrowserGuard.Tests/Configuration/testconfig/01_all-disabled.json index 5486dad..c0ee486 100644 --- a/BrowserGuard.Tests/Configuration/testconfig/01_all-disabled.json +++ b/BrowserGuard.Tests/Configuration/testconfig/01_all-disabled.json @@ -6,6 +6,11 @@ "Upload": false, "Download": false, "Print": false, + "Masking": { + "Level": "Full", + "UseStandardRules": true, + "Rules": [] + }, "LocalFile": { "Enabled": false, "Directory": "", diff --git a/BrowserGuard.Tests/Configuration/testconfig/02_strict.json b/BrowserGuard.Tests/Configuration/testconfig/02_strict.json index 419dc74..589133c 100644 --- a/BrowserGuard.Tests/Configuration/testconfig/02_strict.json +++ b/BrowserGuard.Tests/Configuration/testconfig/02_strict.json @@ -6,6 +6,11 @@ "Upload": true, "Download": true, "Print": true, + "Masking": { + "Level": "Full", + "UseStandardRules": true, + "Rules": [] + }, "LocalFile": { "Enabled": true, "Directory": "C:\\BrowserGuardTest\\NetLog\\%MACHINENAME%", diff --git a/BrowserGuard.Tests/NetLogger/NetLogMaskerTests.cs b/BrowserGuard.Tests/NetLogger/NetLogMaskerTests.cs new file mode 100644 index 0000000..c75fc1a --- /dev/null +++ b/BrowserGuard.Tests/NetLogger/NetLogMaskerTests.cs @@ -0,0 +1,241 @@ +/* +This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. + +Copyright (c) 2026 ClearCode Inc. +*/ + +using System; +using System.IO; +using System.Linq; +using System.Text.Json; +using BrowserGuard.Common; +using BrowserGuard.Configuration; +using BrowserGuard.NetLogger; +using BrowserGuard.UploadFileBridge; +using Xunit; + +namespace BrowserGuard.Tests.NetLogger +{ + public class NetLogMaskerTests + { + static NetLogMasker Masker(string level = "Full", params NetLogMaskRuleConfig[] rules) => + new(new NetLogMaskingConfig { Level = level, Rules = rules }); + + static NetLogMaskRuleConfig Rule(string pattern, string scope = "Part") => + new() { Pattern = pattern, Scope = scope }; + + [Theory] + [InlineData("card 4111 1111 1111 1111.", "card ***.")] + [InlineData("card 4111 1111 1111 1112.", "card 4111 1111 1111 1112.")] + [InlineData("id 1234-5678-9018", "id ***")] + [InlineData("id 1234-5678-9010", "id 1234-5678-9010")] + [InlineData("Quote for taro@example.co.jp (090-1234-5678) - Mail", "Quote for *** (***) - Mail")] + [InlineData("+81 90 1234 5678", "***")] + [InlineData("03-1234-5678", "***")] + [InlineData("https://example.com/?password=abc&x=1", "https://example.com/?password=***&x=1")] + [InlineData("https://example.com/?access_token=abc#top", "https://example.com/?access_token=***")] + [InlineData("https://taro:pw@example.com/", "https://taro:***@example.com/")] + [InlineData("Authorization: Bearer abcdefgh", "Authorization: Bearer ***")] + public void MasksWhatLooksConfidential(string text, string expected) => + Assert.Equal(expected, Masker().Apply(text)); + + [Theory] + [InlineData("https://example.com/a%20b?q=%E6%9D%B1%E4%BA%AC+x&n=10")] + [InlineData("C++ 100% の資料.pdf")] + [InlineData(@"C:\Users\taro\Downloads\report.xlsx")] + [InlineData("")] + public void LeavesTheRestAlone(string text) => + Assert.Equal(text, Masker().Apply(text)); + + [Theory] + [InlineData("https://e.com/?m=taro%40example.com&x=1", "https://e.com/?m=***&x=1")] + [InlineData("https://e.com/?m=taro%2540example.com&x=1", "https://e.com/?m=***&x=1")] + [InlineData("https://e.com/?c=4111+1111+1111+1111&x=1", "https://e.com/?c=***&x=1")] + [InlineData("https://e.com/?t=+81%2090%201234%205678&x=1", "https://e.com/?t=***&x=1")] + [InlineData("https://e.com/?u=https%3A%2F%2Fa%2F%3Ftoken%3Dabc&x=1", "https://e.com/?u=***&x=1")] + // Only seen across two components, so there is no part to point at. + [InlineData("https://e.com/?pass%77ord=abc", "***")] + public void SeesThroughPercentEncoding(string text, string expected) => + Assert.Equal(expected, Masker().Apply(text)); + + [Theory] + [InlineData("taro@example.com", "taro@example.com")] + [InlineData("EX-123456", "EX-123456")] + [InlineData("?token=abc", "?token=***")] + public void MasksOnlySecretsWhenLight(string text, string expected) => + Assert.Equal(expected, Masker("light", Rule("EX-??????")).Apply(text)); + + [Theory] + [InlineData("Ligh")] + [InlineData("")] + [InlineData(null)] + public void ReadsAnUnknownLevelAsFull(string? level) => + Assert.Equal("***", Masker(level!).Apply("taro@example.com")); + + [Fact] + public void CanLeaveTheStandardRulesOut() + { + var masker = new NetLogMasker(new NetLogMaskingConfig { UseStandardRules = false }); + + Assert.Equal("taro@example.com", masker.Apply("taro@example.com")); + Assert.Equal("token=***", masker.Apply("token=abc")); + } + + [Theory] + [InlineData("regex:EX-[0-9]{6}", "Part", "see ex-123456 now", "see *** now")] + [InlineData("EX-??", "Part", "see EX-12 now", "see *** now")] + [InlineData("a.b", "Part", "axb a.b", "axb ***")] + [InlineData("*社外秘*", "Whole", "資料(社外秘).pdf", "***")] + [InlineData("*社外秘*", "Whole", "https://e.com/%E7%A4%BE%E5%A4%96%E7%A7%98.pdf", "***")] + [InlineData("社外秘", "Whole", "資料(社外秘).pdf", "資料(社外秘).pdf")] + [InlineData("社外秘", "Part", "https://e.com/%E7%A4%BE%E5%A4%96%E7%A7%98.pdf?a=1", "https://e.com/***?a=1")] + [InlineData("regex:(?<=[?&](code|sig)=)[^&#]+", "Part", "https://e.com/?sig=a%2Bb&x=1", "https://e.com/?sig=***&x=1")] + [InlineData("", "Part", "plain", "plain")] + public void AppliesTheRulesOfTheOrganisation( + string pattern, string scope, string text, string expected) => + Assert.Equal(expected, Masker("Full", Rule(pattern, scope)).Apply(text)); + + [Fact] + public void MasksEverythingWhenARuleIsBroken() => + Assert.Equal("***", Masker("Full", Rule("regex:(")).Apply("plain")); + + [Fact] + public void MasksEverythingWhenARuleTakesTooLong() => + Assert.Equal("***", Masker("Full", Rule("regex:^(a+)+$")).Apply(new string('a', 60) + "!")); + + [Fact] + public void CutsWhatIsTooLongToCheck() + { + var masked = Masker().Apply(new string('x', NetLogMasker.MaxLength) + "token=abc"); + + Assert.EndsWith("x***", masked); + Assert.True(masked.Length <= NetLogMasker.MaxLength); + } + + // The standard rules must get through the longest text in time, or + // ordinary pages would come out masked as a whole. + [Theory] + [InlineData("x")] + [InlineData("1")] + [InlineData("%41")] + [InlineData("a%20+")] + [InlineData("a.")] + public void KeepsUpWithTheLongestText(string unit) + { + var text = "https://e.com/" + string.Concat(Enumerable.Repeat(unit, 8000 / unit.Length)); + + Assert.StartsWith("https://", Masker().Apply(text)); + } + + [Fact] + public void MasksEveryTextOfAnEntryButNotWhatIdentifiesIt() + { + var entry = """ + {"operation":"browsing","timestamp":"2026-07-01 10:00:00","name":"taro@example.com", + "extra":{"list":["token=abc",1,null,true]},"broken":"\ud800"} + """; + + Assert.Null(NetLogEntry.Compact(entry, out var line, Masker())); + + var root = JsonDocument.Parse(line).RootElement; + Assert.Equal("browsing", root.GetProperty("operation").GetString()); + Assert.Equal("2026-07-01 10:00:00", root.GetProperty("timestamp").GetString()); + Assert.Equal("***", root.GetProperty("name").GetString()); + Assert.Equal("""["token=***",1,null,true]""", root.GetProperty("extra").GetProperty("list").GetRawText()); + Assert.Equal("***", root.GetProperty("broken").GetString()); + Assert.Equal(NetLogIdentity.Account, root.GetProperty("user").GetString()); + } + + [Fact] + public void ReadsTheConfiguration() + { + var config = ConfigLoader.ParseConf(""" + {"NetLogger":{"Masking":{"Level":"Light","UseStandardRules":false, + "Rules":[{"Pattern":"EX-*","Scope":"Whole"}]}}} + """).NetLogger.Masking; + + Assert.Equal("Light", config.Level); + Assert.False(config.UseStandardRules); + Assert.Equal("EX-*", Assert.Single(config.Rules).Pattern); + Assert.Equal("Whole", config.Rules[0].Scope); + } + + // Leaving the group out, or emptying it, must not turn it off. + [Theory] + [InlineData("{}")] + [InlineData("""{"NetLogger":{"Masking":null}}""")] + [InlineData("""{"NetLogger":{"Masking":{"Level":null,"Rules":null}}}""")] + [InlineData("""{"NetLogger":{"Masking":{"Rules":[null]}}}""")] + public void MasksUnlessToldOtherwise(string json) + { + var masker = new NetLogMasker(ConfigLoader.ParseConf(json).NetLogger.Masking); + + Assert.Equal("***", masker.Apply("taro@example.com")); + } + + // Both the copy on this machine and what waits for the collector: the + // endpoint answers nothing, so the entry ends up in the spool. + [Fact] + public void NothingUnmaskedReachesTheDisk() + { + var directory = Path.Combine(Path.GetTempPath(), "browserguard-masker-" + Guid.NewGuid().ToString("N")); + try + { + var config = new NetLoggerConfig + { + Enabled = true, + LocalFile = new() { Enabled = true, Directory = directory }, + Sender = new() + { + Enabled = true, + Endpoint = "http://127.0.0.1:1/", + Spool = new() { Enabled = true }, + }, + }; + using (var recorder = new NetLogRecorder(() => config)) + { + Assert.Null(recorder.Record( + """{"operation":"browsing","url":"https://e.com/?password=hunter2"}""")); + } + + var written = Directory.GetFiles(directory).Select(File.ReadAllText).ToArray(); + Assert.Equal(2, written.Length); + Assert.All(written, text => Assert.Contains("password=***", text)); + Assert.All(written, text => Assert.DoesNotContain("hunter2", text)); + } + finally + { + try { Directory.Delete(directory, true); } catch { } + } + } + + [Fact] + public void MasksTheDiagnosticLogOfTheFileBridge() + { + var directory = Path.Combine(Path.GetTempPath(), "browserguard-masker-" + Guid.NewGuid().ToString("N")); + try + { + var logger = new Logger(directory); + FileBridge.Copy( + new UploadFileBridgeConfig + { + Enabled = true, + Destination = directory, + BlockedUrls = new[] { "example" }, + }, + @"C:\tmp\a.txt", "https://example.com/?token=hunter2", DateTime.Now, + logger, Masker().Apply); + + var text = File.ReadAllText(Path.Combine(directory, "BrowserGuard.log")); + Assert.Contains("token=***", text); + Assert.DoesNotContain("hunter2", text); + } + finally + { + try { Directory.Delete(directory, true); } catch { } + } + } + } +} diff --git a/BrowserGuard/BrowserGuard.sample.json b/BrowserGuard/BrowserGuard.sample.json index 1fc99ec..cf406e8 100644 --- a/BrowserGuard/BrowserGuard.sample.json +++ b/BrowserGuard/BrowserGuard.sample.json @@ -6,6 +6,11 @@ "Upload": false, "Download": false, "Print": false, + "Masking": { + "Level": "Full", + "UseStandardRules": true, + "Rules": [] + }, "LocalFile": { "Enabled": true, "Directory": "%LOCALAPPDATA%\\Chronos\\BrowserGuard\\NetLog", diff --git a/BrowserGuard/Host/Handlers/UploadFileBridgeHandler.cs b/BrowserGuard/Host/Handlers/UploadFileBridgeHandler.cs index 5fa4a43..7824887 100644 --- a/BrowserGuard/Host/Handlers/UploadFileBridgeHandler.cs +++ b/BrowserGuard/Host/Handlers/UploadFileBridgeHandler.cs @@ -59,8 +59,11 @@ internal UploadFileBridgeHandler(NetLogRecorder recorder, Logger? logger = null) } var now = DateTime.Now; + // The diagnostic log names the file and the URL too, so it is + // masked as the entries are. + var masker = new NetLogMasker(config.Value.NetLogger?.Masking, logger); var failure = FileBridge.Copy( - config.Value.UploadFileBridge, upload.File, upload.Url, now, logger); + config.Value.UploadFileBridge, upload.File, upload.Url, now, logger, masker.Apply); if (failure is not null) { RecordFailure(upload, failure, now); diff --git a/BrowserGuard/NetLogger/NetLogEntry.cs b/BrowserGuard/NetLogger/NetLogEntry.cs index 89b27d2..58db191 100644 --- a/BrowserGuard/NetLogger/NetLogEntry.cs +++ b/BrowserGuard/NetLogger/NetLogEntry.cs @@ -57,7 +57,8 @@ internal static string UploadFileBridgeFailed( // null when the entry is usable, and `line` holds it. Otherwise the // reason it cannot be used. - internal static string? Compact(string entry, out string line) + internal static string? Compact( + string entry, out string line, NetLogMasker? masker = null) { line = ""; try @@ -85,7 +86,15 @@ internal static string UploadFileBridgeFailed( { continue; } - property.WriteTo(writer); + if (masker is null || + property.NameEquals("operation") || + property.NameEquals("timestamp")) + { + property.WriteTo(writer); + continue; + } + writer.WritePropertyName(property.Name); + WriteMasked(writer, property.Value, masker); } writer.WriteString(HostProperty, NetLogIdentity.Host); writer.WriteString(UserProperty, NetLogIdentity.Account); @@ -105,5 +114,53 @@ internal static string UploadFileBridgeFailed( return $"entry is not valid JSON: {ex.Message}"; } } + + // Every text is masked, however deep, so that a field added to the + // entries later is covered without having to be listed here. + private static void WriteMasked( + Utf8JsonWriter writer, JsonElement value, NetLogMasker masker) + { + switch (value.ValueKind) + { + case JsonValueKind.String: + writer.WriteStringValue(MaskText(value, masker)); + break; + case JsonValueKind.Object: + writer.WriteStartObject(); + foreach (var property in value.EnumerateObject()) + { + writer.WritePropertyName(property.Name); + WriteMasked(writer, property.Value, masker); + } + writer.WriteEndObject(); + break; + case JsonValueKind.Array: + writer.WriteStartArray(); + foreach (var item in value.EnumerateArray()) + { + WriteMasked(writer, item, masker); + } + writer.WriteEndArray(); + break; + default: + value.WriteTo(writer); + break; + } + } + + private static string MaskText(JsonElement value, NetLogMasker masker) + { + string text; + try + { + text = value.GetString() ?? ""; + } + catch (InvalidOperationException) + { + // Half of a surrogate pair: it cannot be read, so not checked. + return NetLogMasker.Mask; + } + return masker.Apply(text); + } } } diff --git a/BrowserGuard/NetLogger/NetLogMasker.cs b/BrowserGuard/NetLogger/NetLogMasker.cs new file mode 100644 index 0000000..5770c88 --- /dev/null +++ b/BrowserGuard/NetLogger/NetLogMasker.cs @@ -0,0 +1,260 @@ +/* +This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. + +Copyright (c) 2026 ClearCode Inc. +*/ + +using System.Text.RegularExpressions; +using BrowserGuard.Common; + +namespace BrowserGuard.NetLogger +{ + // Replaces what looks confidential with ***, before an entry is kept or + // sent anywhere. The rules follow Chronos Tracer's, so that the same text + // comes out alike in both logs. + // + // A text that cannot be checked (a rule that does not compile, a match that + // takes too long) is replaced as a whole rather than let through. + internal sealed class NetLogMasker + { + internal const string Mask = "***"; + // Longer texts are cut here: the cost of checking one has to be bounded, + // and what was not checked must not be recorded. + internal const int MaxLength = 8192; + // Dropped from the end of a text that was cut, where a value may have + // been split into something the rules no longer recognise. + private const int CutTail = 32; + private const int MaxDecodings = 3; + + private const RegexOptions Options = + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant; + private static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(200); + + // Group 1 is kept and group 2, the value, is replaced. + private static readonly Regex[] Secrets = + { + Build(@"(Authorization\s*:\s*(?:(?:Bearer|Basic|Digest|Token|NTLM|Negotiate)\s+)?)([^\s""']+)"), + Build(@"(--?(?:token|password|passwd|pwd|secret|api[-_]?key|access[-_]?key|client[-_]?secret|auth)\s+)(?!-)(""[^""]*""|'[^']*'|[^\s""']+)"), + Build(@"((?:password|passwd|pwd|pass|secret|token|api[-_]?key|access[-_]?key|client[-_]?secret)\s*[=:]\s*)(""[^""]*""|'[^']*'|[^\s""';&]+)"), + Build(@"(\bBearer\s+)([A-Za-z0-9._~+/=\-]{8,})"), + Build(@"(://[^/\s:@]+:)([^@\s/]+)(?=@)"), + }; + + private static readonly (Regex Pattern, Func? Check)[] Standard = + { + // Card numbers, then the 12 digit individual number. + (Build(@"(? partRules = new(); + private readonly List wholeRules = new(); + private readonly Logger? logger; + private bool warnedTimeout; + + internal NetLogMasker(NetLogMaskingConfig? config, Logger? logger = null) + { + this.logger = logger; + config ??= new(); + + // Only an explicit Light lowers the protection; a misspelling does not. + if (string.Equals(config.Level?.Trim(), "Light", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + useStandard = config.UseStandardRules; + var number = 0; + foreach (var rule in config.Rules ?? Array.Empty()) + { + number++; + if (string.IsNullOrEmpty(rule?.Pattern)) + { + continue; + } + try + { + Add(rule); + } + catch (ArgumentException) + { + broken = true; + // The pattern may itself be confidential, so it is not named. + logger?.Log($"NetLogMasker: rule {number} is not a valid regular expression; every text is masked"); + } + } + } + + private void Add(NetLogMaskRuleConfig rule) + { + const string prefix = "regex:"; + if (rule.Pattern.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + partRules.Add(Build(rule.Pattern[prefix.Length..])); + return; + } + + var pattern = Regex.Escape(rule.Pattern).Replace(@"\*", ".*").Replace(@"\?", "."); + if (string.Equals(rule.Scope?.Trim(), "Whole", StringComparison.OrdinalIgnoreCase)) + { + wholeRules.Add(Build($@"\A(?:{pattern})\z", RegexOptions.Singleline)); + } + else + { + partRules.Add(Build(pattern, RegexOptions.Singleline)); + } + } + + internal string Apply(string text) + { + if (text.Length == 0) + { + return text; + } + if (broken) + { + return Mask; + } + try + { + return ApplyRules(Cut(text)); + } + catch (RegexMatchTimeoutException) + { + if (!warnedTimeout) + { + warnedTimeout = true; + logger?.Log("NetLogMasker: a rule took too long, so the whole text was masked"); + } + return Mask; + } + } + + private string ApplyRules(string text) + { + if (IsWhole(text) || Decodings(text).Any(IsWhole)) + { + return Mask; + } + + var masked = ReplaceParts(text); + // A value can be hidden from the rules by percent encoding. It is + // looked at decoded, but what is recorded stays as it was written. + masked = Component.Replace(masked, match => + Decodings(match.Value).Any(Changes) ? Mask : match.Value); + + // Something that only shows across several components cannot be + // pointed at in the original, so the whole of it goes. + return Decodings(masked).Any(Changes) ? Mask : masked; + } + + private bool IsWhole(string text) => wholeRules.Any(rule => rule.IsMatch(text)); + + private bool Changes(string text) => ReplaceParts(text) != text; + + private string ReplaceParts(string text) + { + foreach (var secret in Secrets) + { + text = secret.Replace(text, match => + match.Groups[2].Value == Mask ? match.Value : match.Groups[1].Value + Mask); + } + if (useStandard) + { + foreach (var (pattern, check) in Standard) + { + text = pattern.Replace(text, match => + check is null || check(match.Value) ? Mask : match.Value); + } + } + foreach (var rule in partRules) + { + text = rule.Replace(text, match => match.Length == 0 ? "" : Mask); + } + return text; + } + + // A + is a space in a query and itself elsewhere, so both are tried. + private static IEnumerable Decodings(string text) + { + foreach (var start in new[] { text, text.Replace('+', ' ') }.Distinct()) + { + if (start != text) + { + yield return start; + } + var current = start; + for (var round = 0; round < MaxDecodings; round++) + { + var decoded = Uri.UnescapeDataString(current); + if (decoded == current) + { + break; + } + yield return current = decoded; + } + } + } + + private static string Cut(string text) + { + if (text.Length <= MaxLength) + { + return text; + } + var length = MaxLength - CutTail; + if (char.IsHighSurrogate(text[length - 1])) + { + length--; + } + return text[..length] + Mask; + } + + private static Regex Build(string pattern, RegexOptions extra = RegexOptions.None) => + new(pattern, Options | extra, MatchTimeout); + + private static int[] Digits(string text) => + text.Where(char.IsAsciiDigit).Select(c => c - '0').ToArray(); + + // The Luhn check. + private static bool IsCardNumber(string text) + { + var sum = 0; + var doubled = false; + foreach (var digit in Digits(text).Reverse()) + { + var value = doubled ? digit * 2 : digit; + sum += value > 9 ? value - 9 : value; + doubled = !doubled; + } + return sum % 10 == 0; + } + + // The check digit of the individual number is its last digit. + private static bool IsIndividualNumber(string text) + { + var digits = Digits(text); + var sum = 0; + for (var n = 1; n <= 11; n++) + { + sum += digits[11 - n] * (n <= 6 ? n + 1 : n - 5); + } + var rest = sum % 11; + return digits[11] == (rest <= 1 ? 0 : 11 - rest); + } + } +} diff --git a/BrowserGuard/NetLogger/NetLogRecorder.cs b/BrowserGuard/NetLogger/NetLogRecorder.cs index bf86291..f454f19 100644 --- a/BrowserGuard/NetLogger/NetLogRecorder.cs +++ b/BrowserGuard/NetLogger/NetLogRecorder.cs @@ -23,6 +23,7 @@ internal sealed class NetLogRecorder : IDisposable private NetLogFileWriter? file; private NetLogSender? sender; + private NetLogMasker? masker; private bool resolved; internal NetLogRecorder(Func readConfig, Logger? logger = null) @@ -43,7 +44,7 @@ internal NetLogRecorder(Func readConfig, Logger? logger = null) // Checked once here, so that both destinations are handed the same // single line and a bad entry is refused before either sees it. - var rejection = NetLogEntry.Compact(entry, out var line); + var rejection = NetLogEntry.Compact(entry, out var line, masker); if (rejection is not null) { return rejection; @@ -74,6 +75,8 @@ private void Resolve() return; } + masker = new NetLogMasker(config.Masking, logger); + if (config.LocalFile.Enabled) { file = new NetLogFileWriter(config.LocalFile, logger); diff --git a/BrowserGuard/NetLogger/NetLoggerConfig.cs b/BrowserGuard/NetLogger/NetLoggerConfig.cs index e133e58..383ce46 100644 --- a/BrowserGuard/NetLogger/NetLoggerConfig.cs +++ b/BrowserGuard/NetLogger/NetLoggerConfig.cs @@ -17,10 +17,33 @@ internal class NetLoggerConfig public bool Download { get; set; } public bool Print { get; set; } + public NetLogMaskingConfig Masking { get; set; } = new(); public NetLogFileConfig LocalFile { get; set; } = new(); public NetLogSenderConfig Sender { get; set; } = new(); } + // What is replaced with *** before an entry is kept or sent. Both + // destinations are given the same masked entry. + internal class NetLogMaskingConfig + { + // "Full", or "Light" to leave everything but passwords and tokens as it + // is. Anything else is read as "Full". + public string Level { get; set; } = "Full"; + // Card numbers, individual numbers, mail addresses, telephone numbers. + public bool UseStandardRules { get; set; } = true; + public NetLogMaskRuleConfig[] Rules { get; set; } = []; + } + + internal class NetLogMaskRuleConfig + { + // Wildcards (* and ?), or "regex:" followed by a regular expression. + // Case is ignored either way. + public string Pattern { get; set; } = ""; + // "Part" masks what matched. "Whole", for a wildcard only, masks the + // whole text when all of it matches. + public string Scope { get; set; } = "Part"; + } + // Handing the log to the collector. The counterpart of NetLogFileConfig: // one says where the log goes on this machine, the other where it goes off it. internal class NetLogSenderConfig diff --git a/BrowserGuard/UploadFileBridge/FileBridge.cs b/BrowserGuard/UploadFileBridge/FileBridge.cs index 912a6e8..9831f9a 100644 --- a/BrowserGuard/UploadFileBridge/FileBridge.cs +++ b/BrowserGuard/UploadFileBridge/FileBridge.cs @@ -31,12 +31,14 @@ internal static class FileBridge string source, string url, DateTime now, - Logger? logger = null) + Logger? logger = null, + Func? mask = null) { - var failure = Attempt(config, source, url, now, logger); + Action log = text => logger?.Log(mask is null ? text : mask(text)); + var failure = Attempt(config, source, url, now, log); if (failure is not null) { - logger?.Log($"UploadFileBridge: no copy kept of {source}: {failure}"); + log($"UploadFileBridge: no copy kept of {source}: {failure}"); } return failure; } @@ -46,7 +48,7 @@ internal static class FileBridge string source, string url, DateTime now, - Logger? logger) + Action log) { if (!config.Enabled) { @@ -63,7 +65,7 @@ internal static class FileBridge // Where it was going and what it is called are settled first: they // are a look at two strings, where the size is a look at the file. - var refusal = AllowedUrl(config, url, logger) + var refusal = AllowedUrl(config, url, log) ?? AllowedExtension(config, source) ?? WithinSizeLimit(config, source); if (refusal is not null) @@ -86,7 +88,7 @@ internal static class FileBridge try { var copied = CopyWithoutOverwriting(source, destination); - logger?.Log($"UploadFileBridge: copied {source} to {copied}"); + log($"UploadFileBridge: copied {source} to {copied}"); return null; } catch (Exception ex) @@ -98,13 +100,13 @@ internal static class FileBridge // Read like the extension lists, and matched as regular expressions the // way UploadGuard matches its paths. private static string? AllowedUrl( - UploadFileBridgeConfig config, string url, Logger? logger) + UploadFileBridgeConfig config, string url, Action log) { - if (Matches(url, config.BlockedUrls, "blocked URL", logger)) + if (Matches(url, config.BlockedUrls, "blocked URL", log)) { return $"uploads to {url} are not kept"; } - if (config.AllowedUrls.Length > 0 && !Matches(url, config.AllowedUrls, "allowed URL", logger)) + if (config.AllowedUrls.Length > 0 && !Matches(url, config.AllowedUrls, "allowed URL", log)) { return $"uploads to {url} are not among those kept"; } @@ -115,7 +117,7 @@ internal static class FileBridge // silently turn the whole list into "match everything" or "match // nothing". The timeout is there so that a pattern that backtracks for // ever cannot hold the host up. - private static bool Matches(string url, string[] patterns, string list, Logger? logger) + private static bool Matches(string url, string[] patterns, string list, Action log) { foreach (var pattern in patterns) { @@ -123,13 +125,13 @@ private static bool Matches(string url, string[] patterns, string list, Logger? { if (Regex.IsMatch(url, pattern, RegexOptions.IgnoreCase, MatchTimeout)) { - logger?.Log($"UploadFileBridge: {url} matched the {list} pattern {pattern}"); + log($"UploadFileBridge: {url} matched the {list} pattern {pattern}"); return true; } } catch (Exception ex) when (ex is ArgumentException or RegexMatchTimeoutException) { - logger?.Log($"UploadFileBridge: ignoring the {list} pattern {pattern}: {ex.Message}"); + log($"UploadFileBridge: ignoring the {list} pattern {pattern}: {ex.Message}"); } } return false; diff --git a/README.md b/README.md index 3c72b16..552a042 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,58 @@ SetupOutput\ChronosBrowserGuardSetup-<バージョン>.exe /VERYSILENT /TASKS="e 各機能の有効・無効はこのファイルで切り替えます。初期状態ではすべて無効です。 +### 監査ログの機密情報の保護 (`NetLogger.Masking`) + +監査ログの機密情報は、ファイルへの保存、収集サーバーへの送信、未送信分の保管の**前**に`***` へ置き換えます。 + +置き換えの規則は 3 つのグループに分かれ、どれを適用するかを `Level` で決めます。 +`Full` はすべてのグループを、`Light` は秘密情報だけを置き換えます。 + +| グループ | 置き換えるもの | `Full` (既定) | `Light` | +| --- | --- | --- | --- | +| 秘密情報 | パスワードやトークンなど、認証に使う値 | ○ | ○ | +| 標準の規則 | カード番号、マイナンバー、メールアドレス、電話番号 | ○ (`UseStandardRules` が `false` なら ×) | × | +| 独自の規則 | `Rules` に書いたもの | ○ | × | + +秘密情報として置き換えるのは、次の値です (大文字小文字は区別しません)。 + +| 形式 | 対象 | +| --- | --- | +| `名前=値`、`名前:値` | 名前が `password`、`passwd`、`pwd`、`pass`、`secret`、`token`、`api_key`、`access_key`、`client_secret` で終わるもの (`_` は `-` でも、なしでもよい)。`access_token=` のほか、`compass=` のような無関係な名前も対象になる | +| `--名前 値`、`-名前 値` | 名前が `token`、`password`、`passwd`、`pwd`、`secret`、`api_key`、`access_key`、`client_secret`、`auth` のもの (`_` は同上) | +| 認証ヘッダー | `Authorization: 値`、`Bearer 値` (`Bearer` だけの場合は値が 8 文字以上のとき) | +| URL の認証情報 | `://user:値@` の値 | + +設定例: + +```json +"Masking": { + "Level": "Full", + "UseStandardRules": true, + "Rules": [ + { "Pattern": "regex:EX-[0-9]{6}" }, + { "Pattern": "regex:(?<=[?&](code|sig)=)[^&#]+" }, + { "Pattern": "*社外秘*", "Scope": "Whole" } + ] +} +``` + +| キー | 内容 | +| --- | --- | +| `Level` | `Full` (既定) か `Light`。不正な値は `Full` として扱う | +| `UseStandardRules` | 標準の規則を使うか。既定は `true` | +| `Rules` | 独自の規則。`Pattern` はワイルドカード (`*`、`?`) か `regex:<正規表現>` (大文字小文字は区別しない)。`Scope` は `Part` (既定) か、ワイルドカードのときだけ使える `Whole` (全体が一致したら全体を置き換える) | + +- 対象は `operation`、`timestamp` と、ホストが付ける `host`、`user`、`user_displayName`、`session` を除くすべての文字列です。 + UploadFileBridge が診断ログ (`BrowserGuard.log`) に書くファイル名と URL にも適用します。 +- `%40` のようにパーセントエンコードされた値も、デコードして検査します。一致した部分だけを特定できない場合は、その文字列全体を置き換えます。 +- `Masking` を省略すると `Full` になります。**既存の設定のままバージョンアップした場合も置き換えが始まります。** +- 正規表現が不正な場合や、照合が時間切れになった場合は、記録を漏らさないように文字列全体を `***` にします。 +- 8192 文字を超える文字列は切り詰め、末尾を `***` にします。`Level` が `Light` でも同じです。 +- `code=` や `sig=` のように名前から秘密と分からない値は置き換えません。必要なら上の例のように規則を追加してください。 +- 置き換える前の値は残らないため、元に戻せません。すでに書かれたログと、未送信で保管済みの分 (`NetLogPending.jsonl`) には適用されません。 +- UploadFileBridge が保存するファイルの名前と内容には適用されません。 + ## ドキュメント | ファイル | 内容 | diff --git a/Resources/BrowserGuard.json b/Resources/BrowserGuard.json index f7b7085..e4a65bb 100644 --- a/Resources/BrowserGuard.json +++ b/Resources/BrowserGuard.json @@ -6,6 +6,11 @@ "Upload": false, "Download": false, "Print": false, + "Masking": { + "Level": "Full", + "UseStandardRules": true, + "Rules": [] + }, "LocalFile": { "Enabled": false, "Directory": "",