From 3f7f484d103fd6f56b9bf984aae1ed82f41ca7f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 18:11:23 +0000 Subject: [PATCH] PrintVect 0.5.9: host key before every job, 8-character PINs, one-time proofs The owner's three follow-ups to the 0.5.8 security review: - TcpJobSender checks the PC at the printer's saved address before a job goes there: it must sign a challenge with the remembered host key (MovedHostCheck). A passed check is trusted for 5 minutes; a failed one is HostUnreachableException with the reason, so the job searches for the host and then waits for Retry, saying "Nothing was sent there". A printer without a key learns it here (HostKeyLearned: the app saves config.json). - New sharing PINs need 8 to 12 characters (PinDialog.MinLength, also the Turn on sharing window). A shorter saved PIN keeps working; Settings shows "Short" and a note, and Diagnostics "Sharing PIN is short". - NonceMemory: the host remembers every nonce it accepted until its proof expires (time + 24 h, capped at 100,000, soonest-to-expire dropped first) and refuses one that comes again, counting it as a wrong try. Memory only; a replayed job still cannot print twice after a restart. - Fix (0.5.8 regression): the PIN window is as tall as its content with room for the longest message; its four-line explanation had left the message row no room, so a refused PIN showed nothing. - Tests: the saved-address check (passes, cached, refused, learns), nonce memory rules, an exact copy of an accepted request refused while Retry still works. - Version 0.5.9; protocol.md, SECURITY.md, README, CLAUDE.md, CHANGELOG, testing.md steps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JFV1W7wPfiMU9itafQutsk --- CHANGELOG.md | 10 +++ CLAUDE.md | 6 +- Directory.Build.props | 6 +- README.md | 3 +- SECURITY.md | 6 +- docs/protocol.md | 7 ++ docs/testing.md | 14 ++++ installer/PrintVect.iss | 4 +- src/PrintVect.App/Client/ClientController.cs | 1 + src/PrintVect.App/Forms/PinDialog.cs | 26 +++++-- src/PrintVect.App/Forms/SettingsPage.cs | 12 +++- src/PrintVect.App/Strings.Designer.cs | 31 +++++++- src/PrintVect.App/Strings.resx | 15 +++- src/PrintVect.App/app.manifest | 2 +- src/PrintVect.Core/Client/IJobSender.cs | 73 ++++++++++++++++++- src/PrintVect.Core/Host/HostService.cs | 15 ++++ src/PrintVect.Core/Host/NonceMemory.cs | 76 ++++++++++++++++++++ src/PrintVect.Core/Protocol/PinProof.cs | 6 ++ src/PrintVect.Elevate/app.manifest | 2 +- src/PrintVect.Send/app.manifest | 2 +- tests/PrintVect.Tests/FloodLimitsTests.cs | 32 +++++++++ tests/PrintVect.Tests/HostIdentityTests.cs | 65 +++++++++++++++++ tests/PrintVect.Tests/HostTests.cs | 27 +++++++ 23 files changed, 414 insertions(+), 27 deletions(-) create mode 100644 src/PrintVect.Core/Host/NonceMemory.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index fe7d3fc..ee7e8b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ Newest first. Each version is a [release](https://github.com/rahulranjan-dev-py/ program; PCs that run PrintVect offer the newest one by themselves (Settings, Updates). **Tested** says how far the version was tried on the office's PCs (Windows 10 and 11). +## 0.5.9 + +Three more security fixes. Before a job leaves, the PC at the printer's saved address must prove it is the PC the +printer was added from (with its identity key, checked again every 5 minutes): before, that was checked only when the +address changed, so another PC that was given the old address could receive documents. New sharing PINs need at least +8 characters; a shorter PIN set before keeps working, and Settings shows a note ("Short") next to it. The PC with the +printer refuses a request whose one-time PIN proof it has already accepted, so a recorded request cannot be sent +again. The PIN window shows again why a PIN is not taken: in 0.5.8 its longer explanation left the message no room, +so Save PIN seemed to do nothing. **Tested:** awaiting test. + ## 0.5.8 Security fixes from a review of the design. diff --git a/CLAUDE.md b/CLAUDE.md index fa9a239..168022f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,7 +52,7 @@ polling, re-checks within 0.5 s; taken when exclusively openable and size stable (XpsFormatSniffer looks inside: namespace openxps.org = oxps; it also reads the docProps title; the v4 writer stores none, so the document name comes from EnumJobs on the virtual printer while the port writes) -> ClientService sends (3 tries, each IP then PC name; after the first failure one 3 s discovery search follows a host that moved (0.5.0); a new address or the name's -address is used only once it signs a challenge with the host key remembered for the printer (0.5.8, HostIdentity, MovedHostCheck); then pending\ +address is used only once it signs a challenge with the host key remembered for the printer (0.5.8, HostIdentity, MovedHostCheck; 0.5.9: the saved address too, before each job, passed checks kept 5 min in TcpJobSender); then pending\ and Retry resends under the same job id; sent\ kept 1 h, failed\ last 20) and polls status. Host: receive into spool\incoming\ -> verify size, sniff the real format -> HostPrintEngine -> reply JSON -> watch the job (up to 60 s before replying). One job at a time per printer, arrival order, on that printer's worker thread (never @@ -68,14 +68,14 @@ unit-tested with fakes over loopback TCP (tests never load System.Printing, whic printers} every 5 min to each host used -> its "PCs that use this PC". Refusals: drained, ok=false; "retry":true = keep for Retry (lost job, PIN). A job id already printed or still queued gets its state back, never printed twice. - Sharing PIN (0.5.8, PinProof): job and hello carry nonce, time, pinProof = PBKDF2-SHA256(PIN, salt nonce/time/printer/jobId/size, 20000); - time within 24 h; the old plain hash "pin" is refused; 5 wrong per address -> wait 15 min, doubling to 4 h (PinAttemptLimiter). + time within 24 h; the old plain hash "pin" is refused; 5 wrong per address -> wait 15 min, doubling to 4 h (PinAttemptLimiter); a nonce seen before is refused (NonceMemory, 0.5.9). New PINs 8-12 characters (0.5.9). Empty PIN = open on the LAN. Limits: file 200 MB, connect 5 s, header 15 s, transfer 5 min, discovery 2 s; host (0.5.8, ConnectionLimiter): 32 connections, 8 per address, 120/min per address; incoming <= 1 GB and 256 MB disk free (unused files evicted first, else retry), non-XPS deleted, unused files gone after 24 h (hourly). Manual IP/name entry always exists. ## Workflow - One milestone at a time (M0..M6 in the brief, section 9). Finish, build, hand over test steps, then wait for the owner's result before starting the next one. M4 (Windows 7 pass) is skipped: the office has no Windows 7 PC (owner, 2026-10-06); keep Windows 7 paths only where they cost nothing. M6: M6a - updates, M6b-1 new look, M6b-2 hardening; then 0.4.1 (jobs menu), 0.5.0 (redesign, colours, hotspot), 0.5.1-0.5.3 (look fixes), 0.5.4, 0.5.5 (no office words: homes too), 0.5.6 (menu fits), 0.5.7 (copies window), 0.5.8 (security review: PIN proof, host identity, Elevate link guard, host flood limits, strict updates, test releases). + updates, M6b-1 new look, M6b-2 hardening; then 0.4.1 (jobs menu), 0.5.0 (redesign, colours, hotspot), 0.5.1-0.5.3 (look fixes), 0.5.4, 0.5.5 (no office words: homes too), 0.5.6 (menu fits), 0.5.7 (copies window), 0.5.8 (security review: PIN proof, host identity, Elevate link guard, host flood limits, strict updates, test releases), 0.5.9 (host key before each job, 8-character PINs, nonce memory). - Build: `msbuild PrintVect.sln /p:Configuration=Release` (VS 2022 Build Tools + .NET Framework 4.8 targeting pack); `dotnet build PrintVect.sln -c Release` (.NET 8 SDK) too. - Tests: `dotnet test tests/PrintVect.Tests/PrintVect.Tests.csproj -c Release`. CI: .github/workflows/build.yml (windows-latest) builds, tests, makes the setup program; release.yml publishes a TEST version (pre-release, never "latest", so PCs skip it; text = CHANGELOG section via tools/release_notes.py); promote.yml makes it the latest release for every PC (0.5.8). diff --git a/Directory.Build.props b/Directory.Build.props index 5b9a605..ccd2bff 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -12,9 +12,9 @@ en - 0.5.8 - 0.5.8.0 - 0.5.8.0 + 0.5.9 + 0.5.9.0 + 0.5.9.0 PrintVect PrintVect PrintVect contributors diff --git a/README.md b/README.md index 48a7710..a523cfa 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,8 @@ report to copy. ports in Windows Firewall for PrintVect only, on private and domain networks only, never on public ones. - Without a sharing PIN, any PC on the same network can print to the shared printers; set the same PIN on every PC to limit that (Settings, Security). The PIN itself never crosses the network: each job carries a one-time - proof of it, and a PC that sends 5 wrong PINs has to wait. Longer PINs (8 or more characters) are harder to guess. + proof of it, and a PC that sends 5 wrong PINs has to wait. New PINs have at least 8 characters (0.5.9); a shorter + one set before keeps working, with a note in Settings. Print jobs are not encrypted on the network. - PrintVect runs as a normal user. Only its small helper, `PrintVect.Elevate.exe`, asks for administrator rights, for the few tasks that need them: adding or removing a printer, starting with Windows, making a network private. diff --git a/SECURITY.md b/SECURITY.md index fcf0d50..b223a18 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -20,14 +20,16 @@ These are known limits of the design, not vulnerabilities: - Without a sharing PIN, any PC on the same network can print to the shared printers. With a PIN (0.5.8), every job and hello carries a one-time proof of it (PBKDF2-SHA256 salted with that request), never the PIN or a plain hash of it, and a PC that sends 5 wrong PINs must wait 15 minutes, twice as long each further time. Someone who records the - network traffic can still try to guess a short PIN offline, so use 8 or more characters where that matters. Print + network traffic can still try to guess a short PIN offline, so new PINs have at least 8 characters (0.5.9). Each proof + is accepted once: the host remembers the one-time values it accepted until they expire and refuses a copy. Print jobs are not encrypted on the network. - config.json keeps the PIN and the PC's identity key protected with Windows DPAPI for that PC (0.5.8), so they do not show in the file or in a copy taken elsewhere. Any program running on that PC can still read them back, so the PIN protects against other PCs, not against other people who use the same PC. - A PC name and printer ids can be claimed by any PC on the network. Since 0.5.8 a printer follows its host to a new address only when the PC there proves, by signing a random challenge with the host's identity key, that it is the - PC the printer was added from. Someone who can intercept the network traffic itself (not just answer on it) is + PC the printer was added from. Since 0.5.9 the PC at the saved address must prove it too before a job goes there + (checked again every 5 minutes), in case another PC was given the host's old address. Someone who can intercept the network traffic itself (not just answer on it) is outside what PrintVect can stop. - Every user may write in `C:\ProgramData\PrintVect`. The administrator helper (`PrintVect.Elevate.exe`) checks that no folder it creates, gives rights on, deletes or writes its log and result in is a junction or symbolic link, and diff --git a/docs/protocol.md b/docs/protocol.md index 9dadfa7..8578549 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -62,6 +62,10 @@ address with the remembered key; one that claims the host's name or printers wit says why. A printer with no key yet remembers the first one proven to it; a host before 0.5.8 (no key) is followed as before. The signed address stops a PC from passing on the real host's answer from elsewhere. +Since 0.5.9 the client also checks the PC at the printer's saved address before it sends a job there: the same list +request with a challenge, trusted for 5 minutes once passed. When it fails, nothing is sent; the client treats the +host as not reachable at that address (it searches for it, then keeps the job for Retry with the reason). + ## Job header ```json @@ -91,6 +95,9 @@ without a proof with `retry:true`; a request with only the `pin` field of earlie refused with a message to update the sender. After 5 wrong proofs from one address the host refuses that address for 15 minutes without checking, twice as long after each further 5 (at most 4 hours); a right PIN or a day without a wrong one starts afresh. A hello proves the PIN the same way (with `printerId`, `jobId` and `size` empty and 0). +Since 0.5.9 the host remembers every `nonce` it accepted until its proof expires (`time` plus 24 hours) and refuses a +request that brings one again (a copy of a recorded request); that also counts as a wrong try. Every real send, +Retry included, makes a new nonce. `copies` (optional, default 1, at most 99) asks the host to print the document that many times; the client fills it from the XPS print ticket inside the file (`JobCopiesAllDocuments`), which Word and Excel set when the diff --git a/docs/testing.md b/docs/testing.md index 1c9c236..5d42033 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -737,6 +737,20 @@ was committed although the README plays the copy uploaded to GitHub. | 1 | On a PC that had a PIN before the update, open `C:\ProgramData\PrintVect\config.json` in Notepad. | No `"Pin": "…"` line; a long `"PinProtected"` value instead. The log of the first start: "the sharing PIN was kept in plain text; config.json now keeps it protected for this PC." Printing with the PIN works as before. | | 2 | Settings, Security, Change PIN; then look at config.json again. | Still no PIN in plain text; the other PCs need the new PIN as before. | +## 0.5.9: host key before every job, 8-character PINs, one-time proofs + +Three more fixes the owner asked for after 0.5.8 (2026-10-30). Use HOST (shares the printer) and CLIENT (prints), both +on 0.5.9. + +| # | Do this | Expect this | +|---|---------|-------------| +| 0 | Install the 0.5.9 test version on HOST and CLIENT (docs/releasing.md: download the setup from the release page). | "Version 0.5.9" under the menu. | +| 1 | Print a page from CLIENT, and another within 5 minutes. | Both print. CLIENT's log, first job only: "The PC at 192.168.… proved it is HOST (identity key checked; checked again after 5 minutes)." | +| 2 | (Optional, needs a spare PC) switch HOST off, give the spare PC HOST's old address (on the router, or as a fixed address), share a printer on it, wait 5 minutes and print from CLIENT. | Nothing prints on the spare PC. The job waits: "… is not HOST, the PC this printer was added from … Nothing was sent there." | +| 3 | On a PC whose PIN has fewer than 8 characters: Settings. | Sharing PIN shows an orange "Short" and the note "This PIN has 4 characters; new PINs need at least 8 …". Printing still works. Diagnostics: "Sharing PIN is short". | +| 4 | Change PIN…, type 1234 twice. | "The PIN needs 8 to 12 characters." Type an 8-character PIN: saved, "Short" gone. Set the same PIN on the other PCs. | +| 5 | Nothing to do for the one-time proofs: printing and Retry work as before. (A copied request would be refused with "its one-time PIN proof was already used"; the unit tests check that.) | | + ## Later Phase 2 items (brief section 9): raw port-9100 relay, Hindi UI, optional service host, job counter per user. diff --git a/installer/PrintVect.iss b/installer/PrintVect.iss index ed94935..43181bf 100644 --- a/installer/PrintVect.iss +++ b/installer/PrintVect.iss @@ -1,5 +1,5 @@ ; PrintVect installer (Inno Setup 6, milestone M5; silent in-app updates since M6a). -; CI builds it with: ISCC.exe /DAppVersion=0.5.8 /DSourceDir= installer\PrintVect.iss +; CI builds it with: ISCC.exe /DAppVersion=0.5.9 /DSourceDir= installer\PrintVect.iss ; The source folder is what the build workflow collects: PrintVect.App.exe, PrintVect.Core.dll, ; Newtonsoft.Json.dll, PrintVect.Elevate.exe, pvct-send.exe, Fonts\, the sample .xps files, README.md, LICENSE. ; An update from inside PrintVect runs this same program as PrintVect-Setup-.exe /SILENT /NORESTART /LOG=... @@ -7,7 +7,7 @@ ; PrintVect (PrepareToInstall below), installs over the old files and starts PrintVect again as the signed-in user. #ifndef AppVersion - #define AppVersion "0.5.8" + #define AppVersion "0.5.9" #endif #ifndef SourceDir #define SourceDir "..\artifacts\PrintVect" diff --git a/src/PrintVect.App/Client/ClientController.cs b/src/PrintVect.App/Client/ClientController.cs index e0610dd..50083ff 100644 --- a/src/PrintVect.App/Client/ClientController.cs +++ b/src/PrintVect.App/Client/ClientController.cs @@ -58,6 +58,7 @@ public ClientController(AppPaths paths, ConfigStore store, AppConfig config, Syn tracker.Changed += (s, record) => _history.QueueSave(); var sender = new TcpJobSender(); + sender.HostKeyLearned += (s, printer) => Post(() => TrySave()); // learned before a job (0.5.9) _service = new ClientService(paths, sender, tracker) { Pin = config.Pin, diff --git a/src/PrintVect.App/Forms/PinDialog.cs b/src/PrintVect.App/Forms/PinDialog.cs index ebc3108..0d5dda1 100644 --- a/src/PrintVect.App/Forms/PinDialog.cs +++ b/src/PrintVect.App/Forms/PinDialog.cs @@ -11,7 +11,11 @@ namespace PrintVect.App.Forms /// internal sealed class PinDialog : Form { - public const int MinLength = 4; + /// + /// 8 since 0.5.9 (was 4): someone who records the network can try every short PIN on their own computer. A + /// shorter PIN saved before keeps working; Settings shows a note next to it (IsShort). + /// + public const int MinLength = 8; public const int MaxLength = 12; private readonly InputBox _pin; @@ -37,7 +41,7 @@ public PinDialog(bool hasPin) var card = new Card { Dock = DockStyle.Fill, Margin = Ui.Pad(0) }; outer.Controls.Add(card); - TableLayoutPanel column = Make.Column(0, 0, 0, 0, 0, 0, 100, 0); + TableLayoutPanel column = Make.Column(0, 0, 0, 0, 0, 0, 0, 100, 0); column.Controls.Add(Make.Label(hasPin ? Strings.PinChangeTitle : Strings.PinSetTitle, ThemeFonts.Heading, Palette.Text, Ui.Pad(0, 0, 0, 8)), 0, 0); Label explain = Make.Muted(Strings.PinExplain); explain.Margin = Ui.Pad(0, 0, 0, 14); @@ -56,12 +60,20 @@ public PinDialog(bool hasPin) var cancel = new ThemedButton(Strings.CopiesCancel, ButtonKind.Secondary) { DialogResult = DialogResult.Cancel, Margin = Ui.Pad(0) }; FlowLayoutPanel buttons = Make.Row(save, cancel); buttons.Margin = Ui.Pad(0, 12, 0, 0); - column.Controls.Add(buttons, 0, 7); + column.Controls.Add(buttons, 0, 8); card.Controls.Add(column); Controls.Add(outer); AcceptButton = save; CancelButton = cancel; + + // As tall as the content with room for the longest message, which the empty row 7 gives back while there is + // none (0.5.9: with a fixed height a four-line explanation left the message no room, so a refused PIN + // showed nothing). + _problem.Text = Strings.PinMismatch; + int inner = ClientSize.Width - outer.Padding.Horizontal - card.Padding.Horizontal; + ClientSize = new Size(ClientSize.Width, outer.Padding.Vertical + card.Padding.Vertical + column.GetPreferredSize(new Size(inner, 0)).Height); + _problem.Text = ""; Ui.Solidify(this); } @@ -101,7 +113,13 @@ private void TrySave() Close(); } - /// Why the two entries cannot be saved, or null. The rule: 4 to 12 characters, no spaces at the ends, typed twice alike. + /// Why the two entries cannot be saved, or null. The rule: 8 to 12 characters (0.5.9; was 4), no spaces at the ends, typed twice alike. + /// A saved PIN shorter than new ones may be (set before 0.5.9). + internal static bool IsShort(string pin) + { + return !string.IsNullOrEmpty(pin) && pin.Length < MinLength; + } + internal static string Check(string pin, string again) { pin = pin ?? ""; diff --git a/src/PrintVect.App/Forms/SettingsPage.cs b/src/PrintVect.App/Forms/SettingsPage.cs index ee6eba9..5d48000 100644 --- a/src/PrintVect.App/Forms/SettingsPage.cs +++ b/src/PrintVect.App/Forms/SettingsPage.cs @@ -238,8 +238,12 @@ private void ShowValues() try { bool hasPin = !string.IsNullOrEmpty(_config.Pin); - _pinPill.Set(hasPin ? Strings.SettingsPinSetPill : Strings.SettingsPinNotSetPill, hasPin ? PillKind.Success : PillKind.Warning); - _pinText.Text = hasPin ? Strings.SettingsPinOn : Strings.SettingsPinOff; + bool shortPin = PinDialog.IsShort(_config.Pin); + _pinPill.Set(!hasPin ? Strings.SettingsPinNotSetPill : shortPin ? Strings.SettingsPinShortPill : Strings.SettingsPinSetPill, + hasPin && !shortPin ? PillKind.Success : PillKind.Warning); + _pinText.Text = !hasPin ? Strings.SettingsPinOff + : shortPin ? Strings.SettingsPinOn + " " + string.Format(CultureInfo.CurrentCulture, Strings.SettingsPinShort, _config.Pin.Length, PinDialog.MinLength) + : Strings.SettingsPinOn; _pinSet.Text = hasPin ? Strings.SettingsPinChange : Strings.SettingsPinSet; _pinSet.Kind = hasPin ? ButtonKind.Secondary : ButtonKind.Primary; _pinSet.Font = hasPin ? ThemeFonts.TextMedium : ThemeFonts.TextSemi; @@ -664,7 +668,9 @@ private void ShowChecks(Snapshot s) items.Add(string.IsNullOrEmpty(_config.Pin) ? Tuple.Create(CheckLevel.Warning, Strings.CheckPinOff, sharing ? Strings.CheckPinOffSharing : Strings.CheckPinOffText) - : Tuple.Create(CheckLevel.Ok, Strings.CheckPinOn, Strings.CheckPinOnText)); + : PinDialog.IsShort(_config.Pin) + ? Tuple.Create(CheckLevel.Warning, Strings.CheckPinShort, string.Format(CultureInfo.CurrentCulture, Strings.SettingsPinShort, _config.Pin.Length, PinDialog.MinLength)) + : Tuple.Create(CheckLevel.Ok, Strings.CheckPinOn, Strings.CheckPinOnText)); int remote = _client.Printers.Count; items.Add(sharing diff --git a/src/PrintVect.App/Strings.Designer.cs b/src/PrintVect.App/Strings.Designer.cs index 44b103f..7e93f31 100644 --- a/src/PrintVect.App/Strings.Designer.cs +++ b/src/PrintVect.App/Strings.Designer.cs @@ -369,6 +369,15 @@ internal static string CheckPinOnText { } } + /// + /// Looks up a localized string similar to Sharing PIN is short. + /// + internal static string CheckPinShort { + get { + return ResourceManager.GetString("CheckPinShort", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} · running since {1}. /// @@ -1855,7 +1864,7 @@ internal static string SettingsPinOff { } /// - /// Looks up a localized string similar to Set. Other PCs need the same PIN to print here, and this PC sends it with every job.. + /// Looks up a localized string similar to Set. Other PCs need the same PIN to print here, and this PC proves it with every job.. /// internal static string SettingsPinOn { get { @@ -1917,6 +1926,24 @@ internal static string SettingsPinSetPill { } } + /// + /// Looks up a localized string similar to This PIN has {0} characters; new PINs need at least {1}, because a short one can be guessed. It keep [rest of string was truncated]. + /// + internal static string SettingsPinShort { + get { + return ResourceManager.GetString("SettingsPinShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Short. + /// + internal static string SettingsPinShortPill { + get { + return ResourceManager.GetString("SettingsPinShortPill", resourceCulture); + } + } + /// /// Looks up a localized string similar to Every PC must use the same ports. They can only be changed in the settings file.. /// @@ -2467,7 +2494,7 @@ internal static string SharingDialogPinAgain { } /// - /// Looks up a localized string similar to Every PC that prints here needs the same PIN in its Settings. Use 4 to 12 characters (8 or more are [rest of string was truncated]. + /// Looks up a localized string similar to Every PC that prints here needs the same PIN in its Settings. Use 8 to 12 characters. Leave it blank [rest of string was truncated]. /// internal static string SharingDialogPinHelp { get { diff --git a/src/PrintVect.App/Strings.resx b/src/PrintVect.App/Strings.resx index 19eaa18..69a2dd8 100644 --- a/src/PrintVect.App/Strings.resx +++ b/src/PrintVect.App/Strings.resx @@ -455,7 +455,16 @@ Details: {0} Sharing PIN - Set. Other PCs need the same PIN to print here, and this PC sends it with every job. + Set. Other PCs need the same PIN to print here, and this PC proves it with every job. + + + This PIN has {0} characters; new PINs need at least {1}, because a short one can be guessed. It keeps working: Change PIN… sets a longer one (on every PC). + + + Short + + + Sharing PIN is short Without a PIN, any PC on the network can print to this PC's shared printers. @@ -496,7 +505,7 @@ Any PC on the network can then print here, and PCs that still ask for a PIN will Change the sharing PIN - Every PC that prints through PrintVect must have the same PIN: a PC that shares printers refuses jobs with a different one. Use 4 to 12 characters; 8 or more are much harder to guess. + Every PC that prints through PrintVect must have the same PIN: a PC that shares printers refuses jobs with a different one. Use 8 to 12 characters; letters and digits together are hardest to guess. New PIN @@ -1034,7 +1043,7 @@ Jobs that are still waiting or printing stay. Nothing is printed, cancelled or d Type the PIN again - Every PC that prints here needs the same PIN in its Settings. Use 4 to 12 characters (8 or more are much harder to guess). Leave it blank to share without a PIN. + Every PC that prints here needs the same PIN in its Settings. Use 8 to 12 characters. Leave it blank to share without a PIN. This PC already has a sharing PIN. Other PCs need the same PIN in their Settings to print here. diff --git a/src/PrintVect.App/app.manifest b/src/PrintVect.App/app.manifest index 522b8fd..258e55f 100644 --- a/src/PrintVect.App/app.manifest +++ b/src/PrintVect.App/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/src/PrintVect.Core/Client/IJobSender.cs b/src/PrintVect.Core/Client/IJobSender.cs index 605d76a..a1294f9 100644 --- a/src/PrintVect.Core/Client/IJobSender.cs +++ b/src/PrintVect.Core/Client/IJobSender.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; @@ -22,9 +23,22 @@ public interface IJobSender /// The real sender: TCP to the host's IP address first and, when that fails and a PC name is /// known, to the name (DHCP may have moved the host; brief 11.5). Any PC can answer to a name, so for a printer /// whose host key is remembered (0.5.8) the name is looked up and only an address that proves that key is used. + /// Before a job leaves, the PC at the saved address must prove that key too (0.5.9): another PC may have been given + /// the host's old address. A passed check holds for 5 minutes; a failed one counts as "not reachable there", so + /// the job searches for the host and then waits for Retry, saying why. /// public sealed class TcpJobSender : IJobSender { + public static readonly TimeSpan DefaultCheckPassedFor = TimeSpan.FromMinutes(5); + + private readonly Dictionary _passed = new Dictionary(StringComparer.OrdinalIgnoreCase); + + /// How long a passed identity check at an address is trusted before the next job checks again. + public TimeSpan CheckPassedFor { get; set; } = DefaultCheckPassedFor; + + /// Raised on the sending thread when a printer added before 0.5.8 learned its host's key before a job (save config.json). + public event EventHandler HostKeyLearned; + public async Task SendAsync(RemotePrinter printer, RequestHeader header, string filePath, CancellationToken ct) { if (printer == null) throw new ArgumentNullException(nameof(printer)); @@ -32,7 +46,10 @@ public async Task SendAsync(RemotePrinter printer, RequestHeader heade Addresses(printer, out first, out second); try { - return await Client(first, printer).SendJobAsync(header, filePath, null, ct).ConfigureAwait(false); + IPAddress literal; + string target = IPAddress.TryParse(first, out literal) ? first : await CheckedAsync(printer, first, ct).ConfigureAwait(false); + await EnsureHostAsync(printer, target, header.JobId, ct).ConfigureAwait(false); + return await Client(target, printer).SendJobAsync(header, filePath, null, ct).ConfigureAwait(false); } catch (HostUnreachableException ex) when (second != null) { @@ -74,6 +91,60 @@ public async Task HelloAsync(RemotePrinter printer, RequestHeader head } } + /// + /// Makes sure the PC at is the printer's host before a job goes there (0.5.9): it must + /// sign a challenge with the remembered key. A printer without one learns it here. Throws HostUnreachableException + /// (with the reason) when the PC there does not answer or is not the host. Passed checks are trusted for a while. + /// + private async Task EnsureHostAsync(RemotePrinter printer, string address, string jobId, CancellationToken ct) + { + DateTime now = DateTime.UtcNow; + string key = (printer.HostKeyId ?? "") + "|" + address + "|" + printer.Port; + lock (_passed) + { + DateTime passedAt; + if (_passed.TryGetValue(key, out passedAt) && now - passedAt < CheckPassedFor) + { + return; + } + } + MovedHostVerdict verdict = await MovedHostCheck.CheckAsync(printer, address, printer.Port, ct).ConfigureAwait(false); + if (verdict.Problem != null) + { + Log.Warn(jobId, "Not sending to " + address + ": " + verdict.Problem); + throw new HostUnreachableException(verdict.Problem + " Nothing was sent there."); + } + if (string.IsNullOrEmpty(printer.HostKeyId) && verdict.KeyId != null) + { + printer.HostKeyId = verdict.KeyId; + Log.Info(jobId, "Remembered the identity key of " + printer.HostName + " (" + verdict.KeyId.Substring(0, 16) + "…) for \"" + + printer.LocalPrinterName + "\"."); + RaiseHostKeyLearned(printer); + key = printer.HostKeyId + "|" + address + "|" + printer.Port; + } + lock (_passed) + { + foreach (string old in _passed.Where(p => now - p.Value >= CheckPassedFor).Select(p => p.Key).ToList()) + { + _passed.Remove(old); + } + _passed[key] = now; + } + if (!string.IsNullOrEmpty(printer.HostKeyId)) + { + Log.Info(jobId, "The PC at " + address + " proved it is " + printer.HostName + " (identity key checked; checked again after " + + CheckPassedFor.TotalMinutes + " minutes)."); + } + } + + private void RaiseHostKeyLearned(RemotePrinter printer) + { + EventHandler handler = HostKeyLearned; + if (handler == null) return; + try { handler(this, printer); } + catch (Exception ex) { Log.Error("Saving the learned identity key of " + printer.HostName + " failed.", ex); } + } + /// /// The PC name as it is for a printer without a remembered host key (as before 0.5.8); else the first address /// the name leads to that proves the key (MovedHostCheck). Throws HostUnreachableException when none does. diff --git a/src/PrintVect.Core/Host/HostService.cs b/src/PrintVect.Core/Host/HostService.cs index f869b7c..8d0c2db 100644 --- a/src/PrintVect.Core/Host/HostService.cs +++ b/src/PrintVect.Core/Host/HostService.cs @@ -30,6 +30,7 @@ public sealed class HostService : IDisposable private readonly IncomingSpool _spool; private readonly ConcurrentDictionary _connections = new ConcurrentDictionary(); private readonly PinAttemptLimiter _pinTries = new PinAttemptLimiter(); + private readonly NonceMemory _nonces = new NonceMemory(); private readonly Dictionary _refusedConnections = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly object _spaceGate = new object(); private long _reservedBytes; @@ -842,10 +843,24 @@ private string CheckPin(RequestHeader header, string address) return "Too many wrong sharing PINs came from " + sender + ", so " + host + " checks its PIN again in " + Minutes(wait) + ". " + again; } + string repeated = host + " refused this: its one-time PIN proof was already used, so it is a copy of an earlier request " + + "(0.5.9). " + again; + if (!string.IsNullOrEmpty(header.Nonce) && _nonces.WasUsed(header.Nonce, now)) + { + _pinTries.Failed(address, now); + Log.Warn(header.JobId, "A PIN proof came again from " + sender + " (" + address + "): a copy of an earlier request, refused."); + return repeated; + } switch (PinProof.Check(pin, header, now)) { case PinCheck.Open: case PinCheck.Accepted: + if (!_nonces.TryRemember(header.Nonce, PinProof.ExpiresUtc(header), now)) + { + _pinTries.Failed(address, now); + Log.Warn(header.JobId, "A PIN proof came twice at once from " + sender + " (" + address + "); the second is refused."); + return repeated; + } _pinTries.Succeeded(address); return null; case PinCheck.Outdated: diff --git a/src/PrintVect.Core/Host/NonceMemory.cs b/src/PrintVect.Core/Host/NonceMemory.cs new file mode 100644 index 0000000..06122bc --- /dev/null +++ b/src/PrintVect.Core/Host/NonceMemory.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace PrintVect.Core.Host +{ + /// + /// The nonces of PIN proofs this host accepted (0.5.9), each kept until its proof would be refused anyway (the + /// proof's time plus the clock tolerance, PinProof). A request that comes again with a nonce already used is a + /// recorded one sent again: refused. Every real send makes a new nonce, Retry included. Kept in memory only: after + /// a restart a replayed job still cannot print twice, because the host answers a job id it knows with its state. + /// + public sealed class NonceMemory + { + public const int DefaultMaxEntries = 100000; + + private readonly Dictionary _until = new Dictionary(StringComparer.Ordinal); + private readonly object _gate = new object(); + private DateTime _nextPrune = DateTime.MinValue; + + /// At most this many are kept; when full, the ones that expire soonest go first. + public int MaxEntries { get; set; } = DefaultMaxEntries; + + public int Count + { + get { lock (_gate) { return _until.Count; } } + } + + /// True when was seen before and has not expired. + public bool WasUsed(string nonce, DateTime utcNow) + { + lock (_gate) + { + DateTime until; + return _until.TryGetValue(nonce ?? "", out until) && until > utcNow; + } + } + + /// Remembers until . False when it was already used. + public bool TryRemember(string nonce, DateTime untilUtc, DateTime utcNow) + { + nonce = nonce ?? ""; + lock (_gate) + { + DateTime until; + if (_until.TryGetValue(nonce, out until) && until > utcNow) + { + return false; + } + if (utcNow >= _nextPrune || _until.Count >= MaxEntries) + { + Prune(utcNow); + } + _until[nonce] = untilUtc; + return true; + } + } + + private void Prune(DateTime utcNow) + { + foreach (string expired in _until.Where(e => e.Value <= utcNow).Select(e => e.Key).ToList()) + { + _until.Remove(expired); + } + int over = _until.Count - MaxEntries + 1; + if (over > 0) + { + foreach (string soonest in _until.OrderBy(e => e.Value).Take(over).Select(e => e.Key).ToList()) + { + _until.Remove(soonest); + } + } + _nextPrune = utcNow + TimeSpan.FromMinutes(10); + } + } +} diff --git a/src/PrintVect.Core/Protocol/PinProof.cs b/src/PrintVect.Core/Protocol/PinProof.cs index e4d5063..e58376e 100644 --- a/src/PrintVect.Core/Protocol/PinProof.cs +++ b/src/PrintVect.Core/Protocol/PinProof.cs @@ -71,6 +71,12 @@ public static PinCheck Check(string hostPin, RequestHeader header, DateTime utcN return FixedTimeEquals(Compute(hostPin, header), header.Proof.ToLowerInvariant()) ? PinCheck.Accepted : PinCheck.Wrong; } + /// When a proof made at the header's time stops being accepted (UTC): its nonce need not be kept longer. + public static DateTime ExpiresUtc(RequestHeader header) + { + return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(header.Time) + ClockTolerance; + } + /// The header's time as the host's local clock reads it, for messages. public static DateTime TimeOf(RequestHeader header) { diff --git a/src/PrintVect.Elevate/app.manifest b/src/PrintVect.Elevate/app.manifest index c140dc6..9598ac1 100644 --- a/src/PrintVect.Elevate/app.manifest +++ b/src/PrintVect.Elevate/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/src/PrintVect.Send/app.manifest b/src/PrintVect.Send/app.manifest index b5090fa..95544eb 100644 --- a/src/PrintVect.Send/app.manifest +++ b/src/PrintVect.Send/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/tests/PrintVect.Tests/FloodLimitsTests.cs b/tests/PrintVect.Tests/FloodLimitsTests.cs index 4aeb693..1f85c15 100644 --- a/tests/PrintVect.Tests/FloodLimitsTests.cs +++ b/tests/PrintVect.Tests/FloodLimitsTests.cs @@ -47,6 +47,38 @@ public void TooManyNewConnectionsInAMinute_AreRefusedUntilTheMinuteIsOver() } } + [TestClass] + public class NonceMemoryTests + { + private static readonly DateTime Now = new DateTime(2026, 10, 30, 9, 0, 0, DateTimeKind.Utc); + + [TestMethod] + public void ANonceIsAcceptedOnceUntilItsProofExpires() + { + var memory = new NonceMemory(); + Assert.IsTrue(memory.TryRemember("n1", Now.AddHours(24), Now)); + Assert.IsTrue(memory.WasUsed("n1", Now.AddHours(1))); + Assert.IsFalse(memory.TryRemember("n1", Now.AddHours(24), Now.AddHours(23))); + Assert.IsTrue(memory.TryRemember("n2", Now.AddHours(24), Now)); + Assert.IsFalse(memory.WasUsed("n1", Now.AddHours(25)), "after its proof expired it no longer needs keeping"); + } + + [TestMethod] + public void AFullMemoryDropsTheSoonestToExpire() + { + var memory = new NonceMemory { MaxEntries = 3 }; + memory.TryRemember("soon", Now.AddHours(1), Now); + memory.TryRemember("later", Now.AddHours(20), Now); + memory.TryRemember("latest", Now.AddHours(23), Now); + memory.TryRemember("new", Now.AddHours(24), Now); + + Assert.AreEqual(3, memory.Count); + Assert.IsFalse(memory.WasUsed("soon", Now)); + Assert.IsTrue(memory.WasUsed("latest", Now)); + Assert.IsTrue(memory.WasUsed("new", Now)); + } + } + [TestClass] public class IncomingSpoolTests { diff --git a/tests/PrintVect.Tests/HostIdentityTests.cs b/tests/PrintVect.Tests/HostIdentityTests.cs index e1d0a10..3edc8bc 100644 --- a/tests/PrintVect.Tests/HostIdentityTests.cs +++ b/tests/PrintVect.Tests/HostIdentityTests.cs @@ -106,6 +106,71 @@ public async Task ARealHostProvesItselfOverTheNetwork() } } + [TestMethod] + public async Task BeforeAJob_ThePcAtTheSavedAddressMustProveTheKey_AndAPassedCheckHoldsForAWhile() + { + using (var temp = new TempFolder()) + { + var paths = new AppPaths(temp.Path); + paths.EnsureDirectories(); + Log.Initialize(paths.LogsDir, "PrintVect"); + var engine = new FakePrintEngine(); + using (var host = new HostService(paths, engine, new FakePrinters(), new JobTracker()) { Identity = _real }) + { + host.UpdateSharedPrinters(new[] { new SharedPrinter { Id = "abc123", LocalName = "Fake Printer", FriendlyName = "Counter 1 Laser" } }); + host.Start(0); + string file = XpsPackages.Write(temp.File("job.xps"), false, "Checked", 2000); + // No PC name: only the saved address is tried. + var printer = new RemotePrinter { PrinterId = "abc123", HostIp = "127.0.0.1", Port = host.Port, HostKeyId = _real.KeyId }; + var sender = new TcpJobSender(); + + JobReply first = await sender.SendAsync(printer, RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null), file, CancellationToken.None); + Assert.IsTrue(first.Ok, first.Message); + + host.Identity = _impostor; // another PC now answers at the saved address + JobReply cached = await sender.SendAsync(printer, RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null), file, CancellationToken.None); + Assert.IsTrue(cached.Ok, "a passed check is trusted for 5 minutes"); + + sender.CheckPassedFor = TimeSpan.Zero; + HostUnreachableException refused = await Assert.ThrowsExceptionAsync( + () => sender.SendAsync(printer, RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null), file, CancellationToken.None)); + StringAssert.Contains(refused.Message, "Nothing was sent there"); + Assert.AreEqual(2, engine.Requests.Count, "the third job never reached the PC that could not prove the key"); + host.Stop(); + } + Log.Shutdown(); + } + } + + [TestMethod] + public async Task BeforeAJob_APrinterWithoutAKeyLearnsIt() + { + using (var temp = new TempFolder()) + { + var paths = new AppPaths(temp.Path); + paths.EnsureDirectories(); + Log.Initialize(paths.LogsDir, "PrintVect"); + using (var host = new HostService(paths, new FakePrintEngine(), new FakePrinters(), new JobTracker()) { Identity = _real }) + { + host.UpdateSharedPrinters(new[] { new SharedPrinter { Id = "abc123", LocalName = "Fake Printer", FriendlyName = "Counter 1 Laser" } }); + host.Start(0); + var printer = new RemotePrinter { PrinterId = "abc123", HostIp = "127.0.0.1", Port = host.Port }; + var sender = new TcpJobSender(); + RemotePrinter learned = null; + sender.HostKeyLearned += (s, p) => learned = p; + + JobReply reply = await sender.SendAsync(printer, RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null), + XpsPackages.Write(temp.File("job.xps"), false, "Learn", 2000), CancellationToken.None); + + Assert.IsTrue(reply.Ok, reply.Message); + Assert.AreEqual(_real.KeyId, printer.HostKeyId); + Assert.AreSame(printer, learned, "the app saves config.json"); + host.Stop(); + } + Log.Shutdown(); + } + } + [TestMethod] public void TheKeyIsKeptProtectedAndReadBack() { diff --git a/tests/PrintVect.Tests/HostTests.cs b/tests/PrintVect.Tests/HostTests.cs index 14eeb4c..2d76688 100644 --- a/tests/PrintVect.Tests/HostTests.cs +++ b/tests/PrintVect.Tests/HostTests.cs @@ -277,6 +277,33 @@ public async Task SendJob_AfterFiveWrongPins_EvenTheRightOneWaits() Assert.AreEqual(0, _engine.Requests.Count); } + [TestMethod] + public async Task SendJob_AnExactCopyOfAnAcceptedRequest_IsRefused() + { + _host.Pin = "12345678"; + string file = WriteXps(5000); + RequestHeader original = RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "Once", "12345678"); + JobReply first = await Client().SendJobAsync(original, file, null, CancellationToken.None); + Assert.IsTrue(first.Ok, first.Message); + + RequestHeader copy = RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "Once", null); + copy.JobId = original.JobId; + copy.Nonce = original.Nonce; + copy.Time = original.Time; + copy.Proof = original.Proof; // recorded on the network and sent again as it was + JobReply again = await Client().SendJobAsync(copy, file, null, CancellationToken.None); + + Assert.IsFalse(again.Ok); + StringAssert.Contains(again.Message, "already used"); + Assert.AreEqual(1, _engine.Requests.Count); + + RequestHeader honestRetry = RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "Once", "12345678"); + honestRetry.JobId = original.JobId; // Retry on the sender: same job, new nonce + JobReply retried = await Client().SendJobAsync(honestRetry, file, null, CancellationToken.None); + Assert.IsTrue(retried.Ok, retried.Message); + Assert.AreEqual(1, _engine.Requests.Count, "known job id: answered with its state, not printed twice"); + } + [TestMethod] public async Task SendJob_ARecordedProofDoesNotWorkForAnotherJob() {