diff --git a/CHANGELOG.md b/CHANGELOG.md index ee7e8b5..f05967e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ 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.10 + +When the PC with a printer was set up again (PrintVect or Windows installed again), it proves a new identity key and +jobs are refused until the person decides: the waiting job now says exactly that, instead of the "did not answer" of the +PC-name try that came after it, and Printers on other PCs shows **Trust it again** next to that printer. It checks the PC +once more and, after the person confirms, takes its new key. Hellos (the "PCs that use this PC" list) are now sent only +to a PC that passed the same identity check as jobs. Settings warns when the sharing PIN is digits only. **Tested:** +awaiting test. + ## 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 diff --git a/CLAUDE.md b/CLAUDE.md index 168022f..f1ea165 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; 0.5.9: the saved address too, before each job, passed checks kept 5 min in TcpJobSender); 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; 0.5.10: hellos too, HostIdentityException keeps the reason, Trust it again takes a re-proven new key after confirmation); 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 @@ -75,7 +75,7 @@ unit-tested with fakes over loopback TCP (tests never load System.Printing, whic - 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), 0.5.9 (host key before each job, 8-character PINs, nonce memory). + 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), 0.5.10 (changed key kept as reason, Trust it again, hello check, digits-only PIN warning). - 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 ccd2bff..4b72737 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -12,9 +12,9 @@ en - 0.5.9 - 0.5.9.0 - 0.5.9.0 + 0.5.10 + 0.5.10.0 + 0.5.10.0 PrintVect PrintVect PrintVect contributors diff --git a/README.md b/README.md index a523cfa..45c2f37 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ pvct-send status 192.168.1.5 `192.168.1.5` is the host PC's address (shown on its Share my printers page, and under Network in Settings, Diagnostics); a PC name works too. `PrintVect-test-page.xps` is a ready-made one-page test file. Any other `.xps` file works: print a document to "Microsoft XPS Document Writer" to make one. Options: -`/pin 1234` when the host has a PIN, `/doc "title"`, `/port 9151`, `/nowait`. +`/pin ` when the host has a PIN, `/doc "title"`, `/port 9151`, `/nowait`. If another PC cannot reach the host, the Windows Firewall on the host is blocking port 9151 (on a phone hotspot: see Troubleshooting). Without the installer, run this once on the host as administrator: @@ -263,7 +263,7 @@ netsh advfirewall firewall add rule name="PrintVect Discovery (UDP-In)" dir=in a | After an update PrintVect did not come back | Start it from the Start menu; the update itself is complete. Tell the person who supports PrintVect which version the window shows. | | A job waits with "asks for the sharing PIN" | The two PCs have different sharing PINs (or one has none). Set the same PIN in Settings on both, then press **Retry waiting** (Printers on other PCs) on the PC that printed. | | A job waits with "Too many wrong sharing PINs" | That PC sent 5 wrong PINs, so the PC with the printer ignores it for the minutes the message names (longer each time). Set the same PIN on both PCs, wait, then press **Retry waiting**. | -| A job waits with "it is not ..., the PC this printer was added from" | A PC answered with the name of the PC that has the printer but could not prove it is that PC, so nothing was sent to it. If the PC with the printer was set up again (new Windows, or PrintVect removed and installed again), remove its printer on this PC and add it again (Printers on other PCs). | +| A job waits with "proved a different identity key" or "it is not ..., the PC this printer was added from" | The PC at the printer's address could not prove it is the PC the printer was added from, so nothing was sent to it. If that PC was set up again (new Windows, or PrintVect removed and installed again), press **Trust it again** next to the printer on Printers on other PCs and confirm, or remove the printer and add it again; then press **Retry waiting**. If it was not set up again, find out which PC now has that address before trusting it. | | A job waits with "runs a PrintVect older than 0.5.8" | The PC with the printer has a sharing PIN and the PC that printed has an old PrintVect. Update it (Settings, Updates, Check now), then press **Retry waiting**. | | A job waits with "already holds ... of documents waiting to print" or "is nearly full" | The PC with the printer has 1 GB of documents waiting (a paused printer?) or little disk space left. Resume the printer or free some space on that PC, then press **Retry waiting**. | | A job waits with "is paused there" | Someone pressed **Pause** on the PC that has the printer. Press **Resume** there (Share my printers). | diff --git a/SECURITY.md b/SECURITY.md index b223a18..420f7b4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -29,7 +29,8 @@ These are known limits of the design, not vulnerabilities: - 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. 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 + (checked again every 5 minutes; hellos too since 0.5.10), in case another PC was given the host's old address. A PC + that proves a new key there (set up again) is trusted only after the person confirms it (Trust it again, 0.5.10). 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 8578549..3a7f981 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -62,9 +62,12 @@ 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). +Since 0.5.9 the client also checks the PC at the printer's saved address before it sends a job there (0.5.10: before +a hello too): the same list request with a challenge, trusted for 5 minutes once passed. When the PC there does not +answer, the client treats the host as not reachable at that address. When it answers but does not prove the key, +nothing is sent; the client searches for the host once and otherwise keeps the job for Retry with that reason as its +message (0.5.10). When it proves a different key with a valid signature for that address (set up again), the person +can take that key with **Trust it again** on Printers on other PCs, after a fresh check and a confirmation. ## Job header diff --git a/docs/testing.md b/docs/testing.md index 5d42033..a4d7fbd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -746,11 +746,27 @@ on 0.5.9. |---|---------|-------------| | 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." | +| 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. In 0.5.9 the job waits with the result of the PC-name try that comes after the refusal: "HOST did not answer (3 tries). HOST did not answer at 192.168.…, and its name leads nowhere (…)" (or "… leads to no other address."). The spare PC's own refusal is only in CLIENT's log: "Not sending to 192.168.…: A PC calling itself … but it is not HOST …". From 0.5.10 the job keeps that reason as its message (section 0.5.10, step 2). | | 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.) | | +## 0.5.10: a changed host key says so, Trust it again, hellos checked, digits-only PINs + +From the owner (2026-11-01). In 0.5.9 a PC that proved a different identity key at the saved address (PrintVect or +Windows installed again there) refused the job, but the PC-name try after it replaced that reason with "did not +answer". Now the reason stays, and Printers on other PCs offers **Trust it again**. Hellos get the same check as jobs. +Use HOST (shares the printer) and CLIENT (prints), both on 0.5.10. + +| # | Do this | Expect this | +|---|---------|-------------| +| 0 | Install the 0.5.10 test version on HOST and CLIENT (docs/releasing.md). | "Version 0.5.10" under the menu. Printing works as before. | +| 1 | On HOST: uninstall PrintVect (Windows Settings, Apps) and install 0.5.10 again; share the printer again and set the same sharing PIN. On CLIENT: print a page. | Nothing prints. The job waits: "The PC HOST at 192.168.… proved a different identity key than HOST had when this printer was added: PrintVect or Windows was installed again there, or it is another PC. Nothing was sent there. If HOST was set up again, press Trust it again …". Not "did not answer". | +| 2 | On CLIENT: Printers on other PCs. | HOST's printer shows an orange "Identity changed" and a **Trust it again** button in place of Test page. CLIENT's log: "… proved a different identity key than HOST had …; nothing is sent there until it is trusted again". Within 5 minutes also "Presence: HOST did not take the hello (…)": no hello went there. | +| 3 | Press **Trust it again**. | A question: "The PC at 192.168.…, which calls itself HOST, now proves a different identity key … Trust this PC as HOST from now on?" (No is the default). Press **No**: "Nothing changed …". Press Trust it again once more and **Yes**: "HOST is trusted again with its new identity key." The pill shows the printer status again. | +| 4 | Press **Retry waiting**. | The page prints. CLIENT's log: "Trust it again: the person confirmed the new identity key …", then "The PC at … proved it is HOST". | +| 5 | Settings on a PC whose PIN is 8 digits (for example 12345678). | Sharing PIN shows an orange "Digits only" and the note "This PIN has only digits, which anyone guessing tries first …". Diagnostics: "Sharing PIN is digits only". A PIN with letters and digits: "Set", no note. | + ## 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 43181bf..99fd3d6 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.9 /DSourceDir= installer\PrintVect.iss +; CI builds it with: ISCC.exe /DAppVersion=0.5.10 /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.9" + #define AppVersion "0.5.10" #endif #ifndef SourceDir #define SourceDir "..\artifacts\PrintVect" diff --git a/src/PrintVect.App/Client/ClientController.cs b/src/PrintVect.App/Client/ClientController.cs index 50083ff..76de404 100644 --- a/src/PrintVect.App/Client/ClientController.cs +++ b/src/PrintVect.App/Client/ClientController.cs @@ -40,6 +40,7 @@ internal sealed class ClientController : IDisposable private readonly PresenceAnnouncer _presence; private readonly HashSet _checking = new HashSet(StringComparer.OrdinalIgnoreCase); private readonly HashSet _refusedMoves = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _keyChanged = new HashSet(StringComparer.OrdinalIgnoreCase); public ClientController(AppPaths paths, ConfigStore store, AppConfig config, SynchronizationContext ui) { @@ -58,7 +59,8 @@ 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) + sender.HostKeyLearned += (s, printer) => Post(() => TrySave()); // learned before a job or hello (0.5.9) + sender.HostKeyChanged += (s, printer) => Post(() => MarkKeyChanged(printer)); // 0.5.10: Trust it again _service = new ClientService(paths, sender, tracker) { Pin = config.Pin, @@ -75,7 +77,6 @@ public ClientController(AppPaths paths, ConfigStore store, AppConfig config, Syn _service.JobFinished += (s, record) => Post(() => Raise(JobFinished, record)); _presence = new PresenceAnnouncer(sender, () => _service.WatchedPrinters) { Pin = config.Pin }; - _presence.HostAnswered += (s, printer) => Post(() => LearnHostKey(printer)); _discovery = new DiscoveryClient(config.DiscoveryPort); _discovery.HostsChanged += (s, e) => Post(OnHostsChanged); @@ -251,56 +252,60 @@ private static IEnumerable AddressesOf(DiscoveredHost host) } /// - /// On the UI thread: the host of took a hello. Printers of that host added before - /// 0.5.8 have no identity key remembered yet; ask the host to prove one at the printer's own address and keep it. + /// The PC at this printer's address proved a different identity key before a job or hello (0.5.10): the page offers + /// Trust it again. Kept until a check passes or the person trusts the new key; not saved. /// - private void LearnHostKey(RemotePrinter answered) + public bool HostKeyChanged(RemotePrinter printer) { - List unknown = _config.RemotePrinters - .Where(p => string.IsNullOrEmpty(p.HostKeyId) && string.Equals(p.HostIp, answered.HostIp, StringComparison.OrdinalIgnoreCase) - && p.Port == answered.Port) - .ToList(); - string key = "learn|" + answered.HostIp + ":" + answered.Port; - if (unknown.Count == 0 || !_checking.Add(key)) + return printer != null && _keyChanged.Contains(printer.PrinterId); + } + + private void MarkKeyChanged(RemotePrinter printer) + { + if (_keyChanged.Add(printer.PrinterId)) { - return; + Log.Warn("The PC at " + printer.HostIp + " proved a different identity key than " + printer.HostName + " had for \"" + + printer.LocalPrinterName + "\"; nothing is sent there until it is trusted again (Printers on other PCs)."); + Raise(PrintersChanged); } - RemotePrinter first = unknown[0]; - Task.Run(async () => + } + + /// Trust it again, step 1 (0.5.10): checks the PC at the printer's saved address once more. + public async Task RecheckHostAsync(RemotePrinter printer) + { + if (printer == null) throw new ArgumentNullException(nameof(printer)); + MovedHostVerdict verdict = await MovedHostCheck.CheckAsync(printer, printer.HostIp, printer.Port, CancellationToken.None).ConfigureAwait(true); + Log.Info("Trust it again: " + printer.HostName + " at " + printer.HostIp + " checked: " + + (verdict.Problem == null ? "the known identity key." : verdict.Problem)); + if (verdict.Problem == null && _keyChanged.Remove(printer.PrinterId)) { - MovedHostVerdict verdict; - try - { - verdict = await MovedHostCheck.CheckAsync(first, first.HostIp, first.Port, CancellationToken.None).ConfigureAwait(false); - } - catch (Exception ex) - { - verdict = new MovedHostVerdict { Problem = ex.Message }; - } - Post(() => - { - _checking.Remove(key); - if (verdict.Problem != null) - { - if (_refusedMoves.Add(key)) - { - Log.Warn("The identity key of " + first.HostName + " could not be learned: " + verdict.Problem); - } - return; - } - if (verdict.KeyId == null) - { - return; // a host before 0.5.8: nothing to learn yet - } - foreach (RemotePrinter printer in unknown.Where(p => string.IsNullOrEmpty(p.HostKeyId))) - { - printer.HostKeyId = verdict.KeyId; - } - Log.Info("Remembered the identity key of " + first.HostName + " (" + verdict.KeyId.Substring(0, 16) + "…) for " - + unknown.Count + " printer(s); jobs follow it to a new address only when it proves this key."); - TrySave(); - }); - }); + Raise(PrintersChanged); + } + return verdict; + } + + /// + /// Trust it again, step 2, after the person confirmed: every printer of that PC with the old key takes the new one, + /// which the PC there has just proven for its address. Jobs then go there again. + /// + public void TrustNewKey(RemotePrinter printer, string newKeyId) + { + if (printer == null) throw new ArgumentNullException(nameof(printer)); + if (string.IsNullOrEmpty(newKeyId)) throw new ArgumentException("A key fingerprint is required.", nameof(newKeyId)); + string old = printer.HostKeyId ?? ""; + List sameHost = _config.RemotePrinters + .Where(p => string.Equals(p.HostIp, printer.HostIp, StringComparison.OrdinalIgnoreCase) && p.Port == printer.Port + && string.Equals(p.HostKeyId ?? "", old, StringComparison.OrdinalIgnoreCase)) + .ToList(); + foreach (RemotePrinter p in sameHost) + { + p.HostKeyId = newKeyId; + _keyChanged.Remove(p.PrinterId); + } + Log.Warn("Trust it again: the person confirmed the new identity key " + newKeyId.Substring(0, 16) + "… of " + printer.HostName + " at " + + printer.HostIp + " (was " + (old.Length >= 16 ? old.Substring(0, 16) + "…" : "none") + ") for " + sameHost.Count + " printer(s)."); + TrySave(); + Raise(PrintersChanged); } /// Whether a job printed on this PC first asks how many copies (Settings, and "Don't ask again"). diff --git a/src/PrintVect.App/Forms/OfficePrintersPage.cs b/src/PrintVect.App/Forms/OfficePrintersPage.cs index 6da3dcf..2af766a 100644 --- a/src/PrintVect.App/Forms/OfficePrintersPage.cs +++ b/src/PrintVect.App/Forms/OfficePrintersPage.cs @@ -188,6 +188,10 @@ private void FillMine() /// A printer's pill: its status as its PC answered, "Looking…" while the search is young, else "Not answering". private Tuple PillOf(RemotePrinter printer, IList found) { + if (_controller.HostKeyChanged(printer)) + { + return Tuple.Create(Strings.OfficeKeyChangedPill, PillKind.Warning); // 0.5.10: nothing is sent there until trusted again + } PrinterInfo seen = found.SelectMany(h => h.Printers).FirstOrDefault(p => string.Equals(p.Id, printer.PrinterId, StringComparison.OrdinalIgnoreCase)); if (seen != null) { @@ -215,8 +219,19 @@ private Control MineRow(RemotePrinter printer, IList found) Control inWindows = Mixed(Strings.OfficeInPrintWindows, printer.LocalPrinterName, Palette.Faint, Palette.Faint); TableLayoutPanel text = Make.Stack(4, top, by, inWindows); - var test = new ThemedButton(Strings.OfficeTestPage, ButtonKind.Secondary, Glyph.Page); - test.Click += (s, e) => SendTestPage(printer); + ThemedButton test; + if (_controller.HostKeyChanged(printer)) + { + // The PC there proved a different identity key (0.5.10): checking it again comes before any test page. + test = new ThemedButton(Strings.OfficeTrustAgain, ButtonKind.Primary, Glyph.Lock) { Enabled = !_busy }; + test.AccessibleName = string.Format(Strings.OfficeTrustAgainAccessible, name); + test.Click += (s, e) => TrustAgain(printer); + } + else + { + test = new ThemedButton(Strings.OfficeTestPage, ButtonKind.Secondary, Glyph.Page); + test.Click += (s, e) => SendTestPage(printer); + } var retry = new ThemedButton(Strings.OfficeRetry, ButtonKind.Secondary, Glyph.Retry) { Enabled = waiting > 0 }; retry.Click += (s, e) => Retry(printer); var remove = new ThemedButton(Strings.UseRemove, ButtonKind.Danger, Glyph.Trash) { Margin = Ui.Pad(0) }; @@ -256,6 +271,60 @@ private void SendTestPage(RemotePrinter printer) } } + /// + /// Trust it again (0.5.10): checks the PC at the printer's address once more and, when it proves a new identity key + /// for that address, takes it only after the person confirms they know that PC was set up again. + /// + private async void TrustAgain(RemotePrinter printer) + { + if (_busy) return; + SetBusy(true); + try + { + MovedHostVerdict verdict = await _controller.RecheckHostAsync(printer); + if (IsDisposed) return; + if (verdict.Problem == null) + { + _shell.Say(string.Format(Strings.OfficeTrustSame, printer.HostName)); + return; + } + if (!verdict.KeyChanged) + { + MessageBox.Show(FindForm(), string.Format(Strings.OfficeTrustNotPossible, verdict.Problem), Strings.AppName, + MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + string answered = verdict.AnsweredName ?? "?"; + string question = string.Format(Strings.OfficeTrustConfirm, printer.HostIp, answered, printer.HostName, verdict.NewKeyId.Substring(0, 16)); + if (!string.Equals(answered, printer.HostName, StringComparison.OrdinalIgnoreCase)) + { + question += "\n\n" + string.Format(Strings.OfficeTrustOtherName, answered, printer.HostName); + } + if (MessageBox.Show(FindForm(), question, Strings.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, + MessageBoxDefaultButton.Button2) != DialogResult.Yes) + { + Log.Info("Trust it again: the person kept the old identity key of " + printer.HostName + "."); + _shell.Say(Strings.OfficeTrustKept); + return; + } + _controller.TrustNewKey(printer, verdict.NewKeyId); + _shell.Say(string.Format(Strings.OfficeTrustDone, printer.HostName)); + } + catch (Exception ex) + { + Log.Error("Trust it again failed for " + printer.HostName + ".", ex); + if (!IsDisposed) _shell.Say(string.Format(Strings.OfficeTrustNotPossible, ex.Message)); + } + finally + { + if (!IsDisposed) + { + SetBusy(false); + FillMine(); + } + } + } + private void Retry(RemotePrinter printer) { try diff --git a/src/PrintVect.App/Forms/PinDialog.cs b/src/PrintVect.App/Forms/PinDialog.cs index 0d5dda1..edee6ab 100644 --- a/src/PrintVect.App/Forms/PinDialog.cs +++ b/src/PrintVect.App/Forms/PinDialog.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Drawing; using System.Windows.Forms; using PrintVect.App.Theme; @@ -113,13 +114,19 @@ private void TrySave() Close(); } - /// 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; } + /// A PIN of digits only (0.5.10: Settings warns): those are tried first by anyone guessing. + internal static bool IsDigitsOnly(string pin) + { + return !string.IsNullOrEmpty(pin) && pin.All(c => c >= '0' && c <= '9'); + } + + /// 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. 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 5d48000..0de2d4c 100644 --- a/src/PrintVect.App/Forms/SettingsPage.cs +++ b/src/PrintVect.App/Forms/SettingsPage.cs @@ -238,12 +238,13 @@ private void ShowValues() try { bool hasPin = !string.IsNullOrEmpty(_config.Pin); - 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; + string advice = PinAdvice(_config.Pin); + _pinPill.Set(!hasPin ? Strings.SettingsPinNotSetPill + : PinDialog.IsShort(_config.Pin) ? Strings.SettingsPinShortPill + : PinDialog.IsDigitsOnly(_config.Pin) ? Strings.SettingsPinDigitsPill + : Strings.SettingsPinSetPill, + hasPin && advice == null ? PillKind.Success : PillKind.Warning); + _pinText.Text = !hasPin ? Strings.SettingsPinOff : advice == null ? Strings.SettingsPinOn : Strings.SettingsPinOn + " " + advice; _pinSet.Text = hasPin ? Strings.SettingsPinChange : Strings.SettingsPinSet; _pinSet.Kind = hasPin ? ButtonKind.Secondary : ButtonKind.Primary; _pinSet.Font = hasPin ? ThemeFonts.TextMedium : ThemeFonts.TextSemi; @@ -261,6 +262,16 @@ private void ShowValues() } } + /// What to say about a saved PIN that is easy to guess (shorter than new ones may be, or digits only), or null. + private static string PinAdvice(string pin) + { + if (PinDialog.IsShort(pin)) + { + return string.Format(CultureInfo.CurrentCulture, Strings.SettingsPinShort, pin.Length, PinDialog.MinLength); + } + return PinDialog.IsDigitsOnly(pin) ? Strings.SettingsPinDigitsOnly : null; + } + private void ChangeColours() { ThemeMode mode = _colours.SelectedIndex == 0 ? ThemeMode.Light : _colours.SelectedIndex == 1 ? ThemeMode.Dark : ThemeMode.System; @@ -669,8 +680,10 @@ private void ShowChecks(Snapshot s) items.Add(string.IsNullOrEmpty(_config.Pin) ? Tuple.Create(CheckLevel.Warning, Strings.CheckPinOff, sharing ? Strings.CheckPinOffSharing : Strings.CheckPinOffText) : 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)); + ? Tuple.Create(CheckLevel.Warning, Strings.CheckPinShort, PinAdvice(_config.Pin)) + : PinDialog.IsDigitsOnly(_config.Pin) + ? Tuple.Create(CheckLevel.Warning, Strings.CheckPinDigits, PinAdvice(_config.Pin)) + : Tuple.Create(CheckLevel.Ok, Strings.CheckPinOn, Strings.CheckPinOnText)); int remote = _client.Printers.Count; items.Add(sharing diff --git a/src/PrintVect.App/Forms/SharingDialog.cs b/src/PrintVect.App/Forms/SharingDialog.cs index f35786d..af0b170 100644 --- a/src/PrintVect.App/Forms/SharingDialog.cs +++ b/src/PrintVect.App/Forms/SharingDialog.cs @@ -12,9 +12,9 @@ namespace PrintVect.App.Forms { /// - /// "Share printers with the office?" (0.5.0, from the owner's redesign): which printers to share and, when this PC has - /// none yet, the office PIN, in one step before sharing is turned on. The same PIN rule as Settings: 4 to 12 - /// characters, typed twice, the same on every PC; blank shares without a PIN. + /// "Share printers with other PCs?" (0.5.0, from the owner's redesign): which printers to share and, when this PC has + /// none yet, the sharing PIN, in one step before sharing is turned on. The same PIN rule as Settings (PinDialog.Check): + /// 8 to 12 characters since 0.5.9, typed twice, the same on every PC; blank shares without a PIN. /// internal sealed class SharingDialog : Form { diff --git a/src/PrintVect.App/Strings.Designer.cs b/src/PrintVect.App/Strings.Designer.cs index 7e93f31..dc554c0 100644 --- a/src/PrintVect.App/Strings.Designer.cs +++ b/src/PrintVect.App/Strings.Designer.cs @@ -324,6 +324,15 @@ internal static string CheckNoNetworkText { } } + /// + /// Looks up a localized string similar to Sharing PIN is digits only. + /// + internal static string CheckPinDigits { + get { + return ResourceManager.GetString("CheckPinDigits", resourceCulture); + } + } + /// /// Looks up a localized string similar to Sharing PIN not set. /// @@ -1332,6 +1341,15 @@ internal static string OfficeIntro { } } + /// + /// Looks up a localized string similar to Identity changed. + /// + internal static string OfficeKeyChangedPill { + get { + return ResourceManager.GetString("OfficeKeyChangedPill", resourceCulture); + } + } + /// /// Looks up a localized string similar to Last checked {0}. /// @@ -1449,6 +1467,78 @@ internal static string OfficeTestPage { } } + /// + /// Looks up a localized string similar to Trust it again. + /// + internal static string OfficeTrustAgain { + get { + return ResourceManager.GetString("OfficeTrustAgain", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Trust the PC of {0} again. + /// + internal static string OfficeTrustAgainAccessible { + get { + return ResourceManager.GetString("OfficeTrustAgainAccessible", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The PC at {0}, which calls itself {1}, now proves a different identity key than {2} had when this pr [rest of string was truncated]. + /// + internal static string OfficeTrustConfirm { + get { + return ResourceManager.GetString("OfficeTrustConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is trusted again with its new identity key. Press Retry waiting to send what waits.. + /// + internal static string OfficeTrustDone { + get { + return ResourceManager.GetString("OfficeTrustDone", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Nothing changed: jobs still go only to the PC with the identity this PC knows.. + /// + internal static string OfficeTrustKept { + get { + return ResourceManager.GetString("OfficeTrustKept", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The PC could not be trusted again: {0}. + /// + internal static string OfficeTrustNotPossible { + get { + return ResourceManager.GetString("OfficeTrustNotPossible", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Careful: this PC calls itself {0}, not {1}. It may be a different PC that was given {1}'s address.. + /// + internal static string OfficeTrustOtherName { + get { + return ResourceManager.GetString("OfficeTrustOtherName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} proved the identity this PC knows: nothing to change. Press Retry waiting to send what waits.. + /// + internal static string OfficeTrustSame { + get { + return ResourceManager.GetString("OfficeTrustSame", resourceCulture); + } + } + /// /// Looks up a localized string similar to This PC is on {0} networks ({1}). A PC on another network may not appear above by itself: type its n [rest of string was truncated]. /// @@ -1845,6 +1935,24 @@ internal static string SettingsPinChange { } } + /// + /// Looks up a localized string similar to This PIN has only digits, which anyone guessing tries first. It keeps working: Change PIN… and mix i [rest of string was truncated]. + /// + internal static string SettingsPinDigitsOnly { + get { + return ResourceManager.GetString("SettingsPinDigitsOnly", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Digits only. + /// + internal static string SettingsPinDigitsPill { + get { + return ResourceManager.GetString("SettingsPinDigitsPill", resourceCulture); + } + } + /// /// Looks up a localized string similar to Not set. /// diff --git a/src/PrintVect.App/Strings.resx b/src/PrintVect.App/Strings.resx index 69a2dd8..cfb3129 100644 --- a/src/PrintVect.App/Strings.resx +++ b/src/PrintVect.App/Strings.resx @@ -460,6 +460,15 @@ Details: {0} 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). + + This PIN has only digits, which anyone guessing tries first. It keeps working: Change PIN… and mix in letters (on every PC). + + + Digits only + + + Sharing PIN is digits only + Short @@ -841,6 +850,37 @@ Jobs that are still waiting or printing stay. Nothing is printed, cancelled or d shares {0} printer(s) + + Identity changed + + + Trust it again + + + Trust the PC of {0} again + + + {0} proved the identity this PC knows: nothing to change. Press Retry waiting to send what waits. + + + The PC could not be trusted again: {0} + + + The PC at {0}, which calls itself {1}, now proves a different identity key than {2} had when this printer was added (new key {3}…). + +That is expected after PrintVect or Windows was installed again on {2}. Trust it only if you know that happened; if you are not sure, ask someone at {2} first. + +Trust this PC as {2} from now on? + + + Careful: this PC calls itself {0}, not {1}. It may be a different PC that was given {1}'s address. + + + Nothing changed: jobs still go only to the PC with the identity this PC knows. + + + {0} is trusted again with its new identity key. Press Retry waiting to send what waits. + Test page diff --git a/src/PrintVect.App/app.manifest b/src/PrintVect.App/app.manifest index 258e55f..a25f25c 100644 --- a/src/PrintVect.App/app.manifest +++ b/src/PrintVect.App/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/src/PrintVect.Core/Client/ClientService.cs b/src/PrintVect.Core/Client/ClientService.cs index 135442a..12767d5 100644 --- a/src/PrintVect.Core/Client/ClientService.cs +++ b/src/PrintVect.Core/Client/ClientService.cs @@ -478,6 +478,7 @@ private async Task SendWithRetriesAsync(RemotePrinter printer, ClientJobRecord r string jobId = record.JobId; string lastError = null; string refusal = null; + string identity = null; TimeSpan[] delays = RetryDelays == null || RetryDelays.Length == 0 ? new[] { TimeSpan.Zero } : RetryDelays; bool searched = false; bool foundAgain = false; @@ -510,6 +511,13 @@ private async Task SendWithRetriesAsync(RemotePrinter printer, ClientJobRecord r Log.Info(jobId, "Sending stopped because PrintVect is closing; the file stays in " + record.FilePath + "."); return; } + catch (HostIdentityException ex) + { + // 0.5.10: a PC answered at the printer's address but is not proven the host. Trying again does not change + // that; one search may still find the host elsewhere, and otherwise the reason itself is the message. + identity = ex.Message; + Log.Warn(jobId, "Try " + (attempt + 1) + " of " + delays.Length + " refused: " + ex.Message); + } catch (Exception ex) when (IsReachabilityProblem(ex)) { lastError = ex.Message; @@ -522,6 +530,32 @@ private async Task SendWithRetriesAsync(RemotePrinter printer, ClientJobRecord r return; } + if (identity != null) + { + if (!searched && FindHost != null && attempt + 1 < delays.Length) + { + searched = true; + try + { + HostSearchOutcome found = await SearchForHostAsync(printer, record, ct).ConfigureAwait(false); + if (found.Moved) + { + foundAgain = true; + identity = null; + continue; // the real host answers elsewhere: try there at once + } + } + catch (OperationCanceledException) + { + Log.Info(jobId, "Sending stopped because PrintVect is closing; the file stays in " + record.FilePath + "."); + return; + } + } + Finish(record, ClientJobStates.Pending, identity + " The document is kept on this PC; press Retry waiting once that is sorted out.", + ClientPrinterNames.PendingFolderName); + return; + } + if (!searched && FindHost != null && attempt + 1 < delays.Length) { searched = true; diff --git a/src/PrintVect.Core/Client/IJobSender.cs b/src/PrintVect.Core/Client/IJobSender.cs index a1294f9..6fe8874 100644 --- a/src/PrintVect.Core/Client/IJobSender.cs +++ b/src/PrintVect.Core/Client/IJobSender.cs @@ -23,9 +23,11 @@ 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. + /// Before a job or hello leaves (0.5.9, hellos 0.5.10), the PC at the saved address must prove that key too: another + /// PC may have been given the host's old address, or PrintVect may have been installed again there. A passed check + /// holds for 5 minutes. A PC that does not answer counts as "not reachable there" (HostUnreachableException: the + /// PC name is tried next); one that answers without proving the key raises HostIdentityException, whose reason the + /// job keeps even when the PC name leads nowhere better (0.5.10). /// public sealed class TcpJobSender : IJobSender { @@ -39,6 +41,9 @@ public sealed class TcpJobSender : IJobSender /// 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; + /// Raised on the sending thread when the PC at a printer's address proved a different key (0.5.10: offer Trust it again). + public event EventHandler HostKeyChanged; + public async Task SendAsync(RemotePrinter printer, RequestHeader header, string filePath, CancellationToken ct) { if (printer == null) throw new ArgumentNullException(nameof(printer)); @@ -57,6 +62,22 @@ public async Task SendAsync(RemotePrinter printer, RequestHeader heade string checkedAddress = await CheckedAsync(printer, second, ct).ConfigureAwait(false); return await Client(checkedAddress, printer).SendJobAsync(header, filePath, null, ct).ConfigureAwait(false); } + catch (HostIdentityException identity) when (second != null) + { + // The host may have moved and another PC got its address: the name may lead to it. If not, the reason stays. + Log.Warn(header.JobId, identity.Message + " Trying the PC name " + second + "."); + string checkedAddress; + try + { + checkedAddress = await CheckedAsync(printer, second, ct).ConfigureAwait(false); + } + catch (HostUnreachableException fallback) + { + Log.Warn(header.JobId, "The PC name " + second + " leads nowhere better (" + fallback.Message + ")."); + throw identity; + } + return await Client(checkedAddress, printer).SendJobAsync(header, filePath, null, ct).ConfigureAwait(false); + } } public async Task StatusAsync(RemotePrinter printer, string jobId, CancellationToken ct) @@ -82,7 +103,12 @@ public async Task HelloAsync(RemotePrinter printer, RequestHeader head Addresses(printer, out first, out second); try { - return await Client(first, printer).SendHelloAsync(header, ct).ConfigureAwait(false); + // The hello proves the PIN and names this PC: only to a PC that proved it is the host (0.5.10). A failed + // check throws, and PresenceAnnouncer skips this host until the next round. + IPAddress literal; + string target = IPAddress.TryParse(first, out literal) ? first : await CheckedAsync(printer, first, ct).ConfigureAwait(false); + await EnsureHostAsync(printer, target, null, ct).ConfigureAwait(false); + return await Client(target, printer).SendHelloAsync(header, ct).ConfigureAwait(false); } catch (HostUnreachableException) when (second != null) { @@ -92,9 +118,10 @@ 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. + /// Makes sure the PC at is the printer's host before a job or hello goes there (0.5.9): + /// it must sign a challenge with the remembered key. A printer without one learns it here. Throws + /// HostUnreachableException when the PC there does not answer, HostIdentityException (0.5.10) when it answers but + /// is not proven the host. Passed checks are trusted for a while. /// private async Task EnsureHostAsync(RemotePrinter printer, string address, string jobId, CancellationToken ct) { @@ -112,7 +139,18 @@ private async Task EnsureHostAsync(RemotePrinter printer, string address, string if (verdict.Problem != null) { Log.Warn(jobId, "Not sending to " + address + ": " + verdict.Problem); - throw new HostUnreachableException(verdict.Problem + " Nothing was sent there."); + if (verdict.Unreachable) + { + throw new HostUnreachableException(verdict.Problem + " Nothing was sent there."); + } + string host = string.IsNullOrWhiteSpace(printer.HostName) ? "that PC" : printer.HostName; + if (verdict.KeyChanged) + { + RaiseHostKeyChanged(printer); + throw new HostIdentityException(verdict.Problem + " Nothing was sent there. If " + host + " was set up again, press Trust it " + + "again next to this printer on Printers on other PCs, or remove the printer and add it again.", true); + } + throw new HostIdentityException(verdict.Problem + " Nothing was sent there.", false); } if (string.IsNullOrEmpty(printer.HostKeyId) && verdict.KeyId != null) { @@ -137,6 +175,14 @@ private async Task EnsureHostAsync(RemotePrinter printer, string address, string } } + private void RaiseHostKeyChanged(RemotePrinter printer) + { + EventHandler handler = HostKeyChanged; + if (handler == null) return; + try { handler(this, printer); } + catch (Exception ex) { Log.Error("Noting the changed identity key of " + printer.HostName + " failed.", ex); } + } + private void RaiseHostKeyLearned(RemotePrinter printer) { EventHandler handler = HostKeyLearned; diff --git a/src/PrintVect.Core/Client/MovedHostCheck.cs b/src/PrintVect.Core/Client/MovedHostCheck.cs index 7ee9729..4604d1f 100644 --- a/src/PrintVect.Core/Client/MovedHostCheck.cs +++ b/src/PrintVect.Core/Client/MovedHostCheck.cs @@ -35,6 +35,35 @@ public sealed class MovedHostVerdict { public string Problem { get; set; } public string KeyId { get; set; } + + /// The PC there did not answer the check at all (switched off, moved): not a matter of identity. + public bool Unreachable { get; set; } + + /// + /// 0.5.10: the PC there proved, with a valid signature for that address, a key other than the remembered one: + /// PrintVect or Windows was installed again there, or another PC got the address. NewKeyId is that key. + /// + public bool KeyChanged { get; set; } + + public string NewKeyId { get; set; } + + /// The PC name the PC there gave, for messages ("which calls itself …"). + public string AnsweredName { get; set; } + } + + /// + /// The PC at a printer's address answered but did not prove it is the PC the printer was added from (0.5.10). Unlike + /// HostUnreachableException, its message is the reason itself and must reach the person as it is. + /// + public sealed class HostIdentityException : Exception + { + public HostIdentityException(string message, bool keyChanged) : base(message) + { + KeyChanged = keyChanged; + } + + /// A different key was proven (Trust it again can take it), not just no proof. + public bool KeyChanged { get; } } /// @@ -66,40 +95,57 @@ public static async Task CheckAsync(RemotePrinter printer, str } catch (Exception ex) { - return new MovedHostVerdict { Problem = "the PC at " + address + " did not answer the identity check (" + ex.Message + ")." }; + return new MovedHostVerdict + { + Problem = "the PC at " + address + " did not answer the identity check (" + ex.Message + ").", + Unreachable = true + }; } - string keyId; - string problem = Judge(printer, address, challenge, reply, out keyId); - return new MovedHostVerdict { Problem = problem, KeyId = keyId }; + return Judge(printer, address, challenge, reply); } - /// The decision itself, for a reply already received. Null: follow. - public static string Judge(RemotePrinter printer, string address, string challenge, ListReply reply, out string keyId) + /// The decision itself, for a reply already received. Problem null: follow. + public static MovedHostVerdict Judge(RemotePrinter printer, string address, string challenge, ListReply reply) { - keyId = null; string host = string.IsNullOrWhiteSpace(printer.HostName) ? "the PC with this printer" : printer.HostName; - string claimed = reply == null || string.IsNullOrWhiteSpace(reply.Host) ? "A PC" : "A PC calling itself " + reply.Host.Trim(); + string answered = reply == null || string.IsNullOrWhiteSpace(reply.Host) ? null : reply.Host.Trim(); + string claimed = answered == null ? "A PC" : "A PC calling itself " + answered; + var verdict = new MovedHostVerdict { AnsweredName = answered }; if (reply == null || !reply.Ok) { - return "the PC at " + address + " refused the identity check" + (reply == null || string.IsNullOrEmpty(reply.Message) ? "." : ": " + reply.Message); + verdict.Problem = "the PC at " + address + " refused the identity check" + (reply == null || string.IsNullOrEmpty(reply.Message) ? "." : ": " + reply.Message); + return verdict; } if (string.IsNullOrEmpty(reply.HostKey)) { - return string.IsNullOrEmpty(printer.HostKeyId) + verdict.Problem = string.IsNullOrEmpty(printer.HostKeyId) ? null // a host before 0.5.8 and a printer that never learned a key: as before : claimed + " answers at " + address + " but cannot prove it is " + host + ", the PC this printer was added from."; + return verdict; } string offered = HostKeys.KeyIdOf(reply.HostKey); + bool signed = HostKeys.Verify(reply.HostKey, challenge, reply.Host, address, reply.HostSig); if (!string.IsNullOrEmpty(printer.HostKeyId) && !string.Equals(offered, printer.HostKeyId, StringComparison.OrdinalIgnoreCase)) { - return claimed + " answers at " + address + ", but it is not " + host + ", the PC this printer was added from (its identity key differs)."; + if (signed) + { + // A real key, properly proven for this address, just not the one remembered (0.5.10). + verdict.KeyChanged = true; + verdict.NewKeyId = offered; + verdict.Problem = (answered == null ? "The PC" : "The PC " + answered) + " at " + address + " proved a different identity key than " + + host + " had when this printer was added: PrintVect or Windows was installed again there, or it is another PC."; + return verdict; + } + verdict.Problem = claimed + " answers at " + address + ", but it is not " + host + ", the PC this printer was added from (its identity key differs)."; + return verdict; } - if (!HostKeys.Verify(reply.HostKey, challenge, reply.Host, address, reply.HostSig)) + if (!signed) { - return claimed + " answers at " + address + " but did not prove it is " + host + " (its identity check failed)."; + verdict.Problem = claimed + " answers at " + address + " but did not prove it is " + host + " (its identity check failed)."; + return verdict; } - keyId = offered; - return null; + verdict.KeyId = offered; + return verdict; } } } diff --git a/src/PrintVect.Core/Client/PresenceAnnouncer.cs b/src/PrintVect.Core/Client/PresenceAnnouncer.cs index 88ff4eb..f10f1f0 100644 --- a/src/PrintVect.Core/Client/PresenceAnnouncer.cs +++ b/src/PrintVect.Core/Client/PresenceAnnouncer.cs @@ -43,9 +43,6 @@ public PresenceAnnouncer(IJobSender sender, Func> printers) public TimeSpan Interval { get; set; } = DefaultInterval; - /// Raised on a thread-pool thread with one printer of a host that answered a hello (0.5.8: its key can be learned). - public event EventHandler HostAnswered; - /// The sharing PIN each hello proves; a change lets refused hosts hear from this PC again. public string Pin { @@ -131,10 +128,6 @@ public async Task AnnounceAsync(CancellationToken ct) + "changes on this PC or PrintVect starts again."); continue; } - if (answered) - { - RaiseHostAnswered(host.First()); - } } catch (OperationCanceledException) { @@ -149,14 +142,6 @@ public async Task AnnounceAsync(CancellationToken ct) } } - private void RaiseHostAnswered(RemotePrinter printer) - { - EventHandler handler = HostAnswered; - if (handler == null) return; - try { handler(this, printer); } - catch (Exception ex) { Log.Error("Presence: a listener for " + printer.HostName + "'s answer failed.", ex); } - } - private void NoteChange(string host, bool answered, string detail) { bool before; diff --git a/src/PrintVect.Elevate/app.manifest b/src/PrintVect.Elevate/app.manifest index 9598ac1..25fc563 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 95544eb..6b712e7 100644 --- a/src/PrintVect.Send/app.manifest +++ b/src/PrintVect.Send/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/tests/PrintVect.Tests/ClientServiceTests.cs b/tests/PrintVect.Tests/ClientServiceTests.cs index 4bbded0..64a59e3 100644 --- a/tests/PrintVect.Tests/ClientServiceTests.cs +++ b/tests/PrintVect.Tests/ClientServiceTests.cs @@ -833,6 +833,37 @@ public void AHostThatIsNotFoundIsSearchedForOnceAndTheJobWaits() } } + [TestMethod] + public void AChangedHostKey_IsTheJobsMessage_AfterOneSearch() + { + using (var temp = new TempFolder()) + { + const string reason = "The PC COUNTER1 at 192.168.10.20 proved a different identity key than COUNTER1 had when this printer was added. " + + "Nothing was sent there. If COUNTER1 was set up again, press Trust it again."; + var sender = new FakeJobSender { OnSend = h => { throw new HostIdentityException(reason, true); } }; + int searches = 0; + using (ClientService service = Service(temp, sender, 0, 10, 10)) + { + service.FindHost = (p, ct) => + { + Interlocked.Increment(ref searches); + return Task.FromResult(HostSearchOutcome.NotFound); + }; + var paths = new AppPaths(temp.Path); + RemotePrinter printer = Printer(); + service.StartWatching(printer); + + ClientJobRecord record = DropAndWait(service, paths, printer, true, "Reinstalled host"); + + Assert.AreEqual(ClientJobStates.Pending, record.State, "kept for Retry"); + StringAssert.StartsWith(record.Message, reason); + Assert.IsFalse(record.Message.Contains("did not answer"), record.Message); + Assert.AreEqual(1, searches); + Assert.AreEqual(1, sender.Sent.Count, "trying again does not change who answers there"); + } + } + } + [TestMethod] public void APcThatCannotProveItIsTheHostGetsNothing_AndTheJobSaysWhy() { diff --git a/tests/PrintVect.Tests/HostIdentityTests.cs b/tests/PrintVect.Tests/HostIdentityTests.cs index 3edc8bc..611b38e 100644 --- a/tests/PrintVect.Tests/HostIdentityTests.cs +++ b/tests/PrintVect.Tests/HostIdentityTests.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -47,37 +48,48 @@ public void ASignatureHoldsOnlyForItsChallengeNameAndAddress() public void APrinterFollowsOnlyTheHostWhoseKeyItRemembers() { string challenge = HostKeys.NewChallenge(); - string keyId; - Assert.IsNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.31", challenge, Answer(_real, challenge, "COUNTER1", "192.168.10.31"), out keyId)); - Assert.AreEqual(_real.KeyId, keyId); + MovedHostVerdict real = MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.31", challenge, Answer(_real, challenge, "COUNTER1", "192.168.10.31")); + Assert.IsNull(real.Problem); + Assert.AreEqual(_real.KeyId, real.KeyId); - string impostor = MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, Answer(_impostor, challenge, "COUNTER1", "192.168.10.66"), out keyId); - StringAssert.Contains(impostor, "not COUNTER1"); + // Another PC with its own key, properly signed: PrintVect installed again there, or another PC (0.5.10). + MovedHostVerdict other = MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, Answer(_impostor, challenge, "COUNTER1", "192.168.10.66")); + StringAssert.Contains(other.Problem, "proved a different identity key"); + Assert.IsTrue(other.KeyChanged); + Assert.AreEqual(_impostor.KeyId, other.NewKeyId, "what Trust it again would take after the person confirms"); + Assert.IsNull(other.KeyId, "but nothing is followed"); ListReply claimsTheRealKey = Answer(_impostor, challenge, "COUNTER1", "192.168.10.66"); claimsTheRealKey.HostKey = _real.PublicKey; // copied from the real host's discovery reply, but it cannot sign with it - Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, claimsTheRealKey, out keyId)); + MovedHostVerdict copied = MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, claimsTheRealKey); + Assert.IsNotNull(copied.Problem); + Assert.IsFalse(copied.KeyChanged); ListReply relayed = Answer(_real, challenge, "COUNTER1", "192.168.10.31"); // the real host's answer, passed on from another address - Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, relayed, out keyId)); + Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, relayed).Problem); + + ListReply foreignRelayed = Answer(_impostor, challenge, "OTHER", "192.168.10.31"); // another key, signed for another address + MovedHostVerdict notHere = MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, foreignRelayed); + Assert.IsNotNull(notHere.Problem); + Assert.IsFalse(notHere.KeyChanged, "a key not proven for this address is never offered for trust"); ListReply noKey = new ListReply { Host = "COUNTER1", Ip = "192.168.10.66", Port = 9151 }; - Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, noKey, out keyId), "a remembered key is never given up"); + Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, noKey).Problem, "a remembered key is never given up"); } [TestMethod] public void APrinterWithoutAKeyLearnsTheFirstProvenOne_AndFollowsAnOlderHostAsBefore() { string challenge = HostKeys.NewChallenge(); - string keyId; - Assert.IsNull(MovedHostCheck.Judge(Printer(null), "192.168.10.31", challenge, Answer(_real, challenge, "COUNTER1", "192.168.10.31"), out keyId)); - Assert.AreEqual(_real.KeyId, keyId); + MovedHostVerdict learned = MovedHostCheck.Judge(Printer(null), "192.168.10.31", challenge, Answer(_real, challenge, "COUNTER1", "192.168.10.31")); + Assert.IsNull(learned.Problem); + Assert.AreEqual(_real.KeyId, learned.KeyId); - Assert.IsNull(MovedHostCheck.Judge(Printer(null), "192.168.10.31", challenge, new ListReply { Host = "COUNTER1", Port = 9151 }, out keyId), - "a host before 0.5.8 has no key"); - Assert.IsNull(keyId); + MovedHostVerdict older = MovedHostCheck.Judge(Printer(null), "192.168.10.31", challenge, new ListReply { Host = "COUNTER1", Port = 9151 }); + Assert.IsNull(older.Problem, "a host before 0.5.8 has no key"); + Assert.IsNull(older.KeyId); } [TestMethod] @@ -132,9 +144,14 @@ public async Task BeforeAJob_ThePcAtTheSavedAddressMustProveTheKey_AndAPassedChe Assert.IsTrue(cached.Ok, "a passed check is trusted for 5 minutes"); sender.CheckPassedFor = TimeSpan.Zero; - HostUnreachableException refused = await Assert.ThrowsExceptionAsync( + RemotePrinter changed = null; + sender.HostKeyChanged += (s, p) => changed = p; + HostIdentityException 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"); + StringAssert.Contains(refused.Message, "Trust it again"); + Assert.IsTrue(refused.KeyChanged); + Assert.AreSame(printer, changed, "the page offers Trust it again"); Assert.AreEqual(2, engine.Requests.Count, "the third job never reached the PC that could not prove the key"); host.Stop(); } @@ -142,6 +159,63 @@ public async Task BeforeAJob_ThePcAtTheSavedAddressMustProveTheKey_AndAPassedChe } } + [TestMethod] + public async Task AChangedKey_StaysTheReason_WhenThePcNameLeadsNowhereBetter() + { + 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 = _impostor }) + { + host.UpdateSharedPrinters(new[] { new SharedPrinter { Id = "abc123", LocalName = "Fake Printer", FriendlyName = "Counter 1 Laser" } }); + host.Start(0); + // PrintVect installed again there: a new key. The PC name leads only to the same address. + var printer = new RemotePrinter { PrinterId = "abc123", HostName = "localhost", HostIp = "127.0.0.1", Port = host.Port, HostKeyId = _real.KeyId }; + + HostIdentityException refused = await Assert.ThrowsExceptionAsync(() => new TcpJobSender().SendAsync(printer, + RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null), XpsPackages.Write(temp.File("job.xps"), false, "Kept", 2000), CancellationToken.None)); + + StringAssert.Contains(refused.Message, "proved a different identity key"); + Assert.IsFalse(refused.Message.Contains("did not answer"), refused.Message); + Assert.AreEqual(0, engine.Requests.Count); + host.Stop(); + } + Log.Shutdown(); + } + } + + [TestMethod] + public async Task AHelloGoesOnlyToAPcThatProvesTheKey() + { + 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 = _impostor }) + { + host.Start(0); + var printer = new RemotePrinter { PrinterId = "abc123", HostIp = "127.0.0.1", Port = host.Port, HostKeyId = _real.KeyId }; + var sender = new TcpJobSender(); + RequestHeader hello = RequestHeader.ForHello("Windows 11 Pro", "0.5.10", new[] { "abc123" }); + hello.Client = "COUNTER3"; + + await Assert.ThrowsExceptionAsync(() => sender.HelloAsync(printer, hello, CancellationToken.None)); + Assert.AreEqual(0, host.Presence.All().Count, "the hello was not sent"); + + host.Identity = _real; + JobReply welcomed = await sender.HelloAsync(printer, hello, CancellationToken.None); + Assert.IsTrue(welcomed.Ok, welcomed.Message); + Assert.AreEqual("COUNTER3", host.Presence.All().Single().Name); + host.Stop(); + } + Log.Shutdown(); + } + } + [TestMethod] public async Task BeforeAJob_APrinterWithoutAKeyLearnsIt() {