diff --git a/README.md b/README.md index 050db66..0c78558 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Die Pakete liegen unter [Releases](../../releases). |---|---|---| | **Windows** (x64) | `freizeichen--windows-x64.msi` ausführen | SmartScreen → „Weitere Informationen“ → „Trotzdem ausführen“ | | **macOS** | `.dmg` öffnen (`arm64` für Apple-Chips, `x64` für Intel), Freizeichen in „Programme“ ziehen | Rechtsklick auf Freizeichen.app → „Öffnen“ | -| **Linux** | kein Paket – aus dem Quellcode starten, siehe [For developers](#for-developers) | Port mit `rfcomm bind` anlegen | +| **Linux** | kein Paket – aus dem Quellcode bauen, siehe [For developers](#for-developers) | Port mit `rfcomm bind` anlegen; „Als Standard festlegen“ trägt Freizeichen für `tel:`-Links ein | Die Pakete sind noch nicht signiert. Ob ein Download unverändert ist, zeigt `SHA256SUMS.txt` im Release: `sha256sum -c SHA256SUMS.txt` (Linux) bzw. `shasum -a 256 -c SHA256SUMS.txt` (macOS). @@ -153,8 +153,9 @@ make screenshots # regenerate docs/screenshots/ for this README make help # everything else ``` -On Linux the phone appears as a serial port only after `sudo rfcomm bind 0 1`, and -the `tel:` handler is not registered automatically. +On Linux the phone appears as a serial port only after `sudo rfcomm bind 0 1`. +*Als Standard festlegen* writes `~/.local/share/applications/freizeichen.desktop`, pointing at the +running executable, and makes it the `x-scheme-handler/tel` default with `xdg-mime`. ### Layout diff --git a/SECURITY.md b/SECURITY.md index f4da26e..8d22c3b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -40,8 +40,9 @@ hand it input**. Whatever reaches the phone after `ATD` is executed by the phone - **Dialling without confirmation.** Every link must go through the confirm window, and a keypress in the first second after the window opens must not dial. Any path that places a call without the Lagebuchführer pressing *Wählen* is a vulnerability. -- **The `tel:` registration**, meaning the Windows registry entries and the macOS bundle claim. For - example, a way for Freizeichen's registration to be hijacked, or to hijack another scheme. +- **The `tel:` registration**, meaning the Windows registry entries, the macOS bundle claim and + the Linux desktop entry with its `Exec` line. For example, a way for Freizeichen's + registration to be hijacked, or to hijack another scheme. - **Settings file handling**, such as path or deserialization issues in the stored settings. - **The release supply chain**: the build workflows, pinned actions, and the published installers and `SHA256SUMS.txt`. diff --git a/src/Freizeichen.App/CompositionRoot.cs b/src/Freizeichen.App/CompositionRoot.cs index e1acab2..c7f01f0 100644 --- a/src/Freizeichen.App/CompositionRoot.cs +++ b/src/Freizeichen.App/CompositionRoot.cs @@ -29,6 +29,11 @@ private static ITelHandlerRegistration CreateRegistration() return new MacTelHandlerRegistration(); } + if (OperatingSystem.IsLinux()) + { + return new LinuxTelHandlerRegistration(); + } + return new UnsupportedTelHandlerRegistration(); } } diff --git a/src/Freizeichen.App/Platform/LinuxTelHandlerRegistration.cs b/src/Freizeichen.App/Platform/LinuxTelHandlerRegistration.cs new file mode 100644 index 0000000..c9ed84d --- /dev/null +++ b/src/Freizeichen.App/Platform/LinuxTelHandlerRegistration.cs @@ -0,0 +1,157 @@ +using System.Buffers; +using System.ComponentModel; +using System.Diagnostics; +using System.Text; +using Freizeichen.AppLogic; + +namespace Freizeichen.App.Platform; + +/// +/// Linux has no installer to declare the handler, so Freizeichen writes its own desktop entry to +/// the user's applications directory and asks xdg-mime (xdg-utils, present on every +/// desktop) to make it the default for x-scheme-handler/tel. The desktop opens the link +/// by running the entry's Exec line with the link as the argument, which is how +/// receives it. +/// +internal sealed class LinuxTelHandlerRegistration : ITelHandlerRegistration +{ + internal const string EntryName = "freizeichen.desktop"; + + private const string MimeType = "x-scheme-handler/tel"; + private static readonly TimeSpan XdgMimeTimeout = TimeSpan.FromSeconds(5); + + // The characters that force an Exec argument into quotes (Desktop Entry spec, "The Exec key"). + private static readonly SearchValues ExecReservedCharacters = SearchValues.Create(" \t\n\"'\\><~|&;$*?#()`"); + + private readonly string _applicationsDirectory; + private readonly string? _executablePath; + private readonly Func, string?> _xdgMime; + + public LinuxTelHandlerRegistration() + : this(DefaultApplicationsDirectory(), Environment.ProcessPath, RunXdgMime) + { + } + + /// Where the desktop entry goes, normally ~/.local/share/applications. + /// The program the entry runs; null when the process cannot tell. + /// Runs xdg-mime with the arguments and returns its output, or null when it failed. + internal LinuxTelHandlerRegistration(string applicationsDirectory, string? executablePath, Func, string?> xdgMime) + { + _applicationsDirectory = applicationsDirectory; + _executablePath = executablePath; + _xdgMime = xdgMime; + } + + public bool IsDefaultHandler() => + string.Equals(_xdgMime(["query", "default", MimeType])?.Trim(), EntryName, StringComparison.Ordinal); + + public async Task MakeDefaultAsync(CancellationToken cancellationToken = default) + { + if (string.IsNullOrEmpty(_executablePath) || _executablePath.AsSpan().IndexOfAny('\r', '\n') >= 0) + { + throw new InvalidOperationException("The executable path cannot be written to a desktop entry."); + } + + Directory.CreateDirectory(_applicationsDirectory); + await File.WriteAllTextAsync(Path.Join(_applicationsDirectory, EntryName), DesktopEntry(_executablePath), cancellationToken); + + if (_xdgMime(["default", EntryName, MimeType]) is null) + { + throw new InvalidOperationException("xdg-mime could not make Freizeichen the tel: handler."); + } + } + + private static string DesktopEntry(string executablePath) => + new StringBuilder() + .Append("[Desktop Entry]\n") + .Append("Type=Application\n") + .Append("Name=Freizeichen\n") + .Append("Comment=Wählt tel:-Links über ein Gigaset DL500A per Bluetooth\n") + .Append("Exec=").Append(QuoteExecArgument(executablePath)).Append(" %u\n") + .Append("Terminal=false\n") + .Append("Categories=Network;Telephony;\n") + .Append("MimeType=").Append(MimeType).Append(";\n") + .ToString(); + + // A path without the Desktop Entry spec's reserved characters is written bare: xdg-mime + // (xdg-utils 1.2) reads the first word of Exec literally, quotes included, and ignores a default + // whose program it cannot find. Any other path is quoted as the spec requires: double quotes, + // with ", `, $ and \ backslash-escaped inside them; the value as a whole is then a string, + // whose own escaping doubles every backslash. A literal % is always written %% so it is not + // read as a field code. + private static string QuoteExecArgument(string argument) + { + if (argument.AsSpan().IndexOfAny(ExecReservedCharacters) < 0) + { + return argument.Replace("%", "%%", StringComparison.Ordinal); + } + + var quoted = new StringBuilder("\""); + foreach (var c in argument) + { + switch (c) + { + case '"' or '`' or '$' or '\\': + quoted.Append(@"\\").Append(c == '\\' ? @"\\" : c.ToString()); + break; + case '%': + quoted.Append("%%"); + break; + default: + quoted.Append(c); + break; + } + } + + return quoted.Append('"').ToString(); + } + + private static string DefaultApplicationsDirectory() + { + var dataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); + if (string.IsNullOrEmpty(dataHome) || !Path.IsPathRooted(dataHome)) + { + dataHome = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share"); + } + + return Path.Join(dataHome, "applications"); + } + + // Arguments go through ArgumentList, never a command line, and none of them come from input. + private static string? RunXdgMime(IReadOnlyList arguments) + { + var start = new ProcessStartInfo("xdg-mime") + { + UseShellExecute = false, + RedirectStandardOutput = true, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + try + { + using var process = Process.Start(start); + if (process is null) + { + return null; + } + + // The answer is one line, far below the pipe buffer, so waiting before reading cannot + // block the process on a full pipe. + if (!process.WaitForExit(XdgMimeTimeout)) + { + process.Kill(); + return null; + } + + return process.ExitCode == 0 ? process.StandardOutput.ReadToEnd() : null; + } + catch (Win32Exception) + { + // xdg-utils is not installed: there is no desktop to register with. + return null; + } + } +} diff --git a/src/Freizeichen.App/Platform/UnsupportedTelHandlerRegistration.cs b/src/Freizeichen.App/Platform/UnsupportedTelHandlerRegistration.cs index 3ab2160..c59ee69 100644 --- a/src/Freizeichen.App/Platform/UnsupportedTelHandlerRegistration.cs +++ b/src/Freizeichen.App/Platform/UnsupportedTelHandlerRegistration.cs @@ -2,11 +2,11 @@ namespace Freizeichen.App.Platform; -/// Linux: Freizeichen dials there (it is where the DL500A is tested), but ships no handler registration. +/// Any other OS .NET runs on (FreeBSD): Freizeichen dials there, but registers no handler. internal sealed class UnsupportedTelHandlerRegistration : ITelHandlerRegistration { public bool IsDefaultHandler() => false; public Task MakeDefaultAsync(CancellationToken cancellationToken = default) => - throw new PlatformNotSupportedException("Freizeichen registers as the tel: handler on Windows and macOS only."); + throw new PlatformNotSupportedException("Freizeichen registers as the tel: handler on Windows, macOS and Linux only."); } diff --git a/src/Freizeichen.AppLogic/ViewModels/SettingsViewModel.cs b/src/Freizeichen.AppLogic/ViewModels/SettingsViewModel.cs index f1de335..8899652 100644 --- a/src/Freizeichen.AppLogic/ViewModels/SettingsViewModel.cs +++ b/src/Freizeichen.AppLogic/ViewModels/SettingsViewModel.cs @@ -144,7 +144,15 @@ private async Task MakeDefaultHandlerAsync() } [RelayCommand] - private void RefreshDefaultHandler() => IsDefaultHandler = _registration.IsDefaultHandler(); + private void RefreshDefaultHandler() + { + IsDefaultHandler = _registration.IsDefaultHandler(); + Show( + IsDefaultHandler + ? "Geprüft: Freizeichen öffnet tel:-Links." + : "Geprüft: Ein anderes Programm öffnet tel:-Links.", + isError: false); + } [SuppressMessage("Design", "CA1031", Justification = "Any failure of the test surfaces in Status.")] private async Task RunAsync(string port, Func> test) diff --git a/tests/Freizeichen.App.Tests/LinuxTelHandlerRegistrationTests.cs b/tests/Freizeichen.App.Tests/LinuxTelHandlerRegistrationTests.cs new file mode 100644 index 0000000..dbf1b34 --- /dev/null +++ b/tests/Freizeichen.App.Tests/LinuxTelHandlerRegistrationTests.cs @@ -0,0 +1,114 @@ +using Freizeichen.App.Platform; + +namespace Freizeichen.App.Tests; + +public sealed class LinuxTelHandlerRegistrationTests : IDisposable +{ + private readonly string _applications = Path.Join(Path.GetTempPath(), "freizeichen-tests-" + Guid.NewGuid().ToString("N")); + private readonly List _calls = []; + private string? _xdgMimeOutput = string.Empty; + + public void Dispose() + { + if (Directory.Exists(_applications)) + { + Directory.Delete(_applications, recursive: true); + } + } + + [Fact] + public async Task Writes_a_desktop_entry_that_opens_tel_links_with_this_executable() + { + await Registration("/opt/freizeichen/Freizeichen").MakeDefaultAsync(TestContext.Current.CancellationToken); + + var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken); + Assert.Equal("[Desktop Entry]", entry[0]); + Assert.Contains("Exec=/opt/freizeichen/Freizeichen %u", entry); + Assert.Contains("MimeType=x-scheme-handler/tel;", entry); + } + + // xdg-mime (xdg-utils 1.2) takes the first word of Exec literally, quotes included, and drops a + // default whose program it cannot find: a quoted plain path made "Prüfen" report another + // handler although the default was set. + [Theory] + [InlineData("/home/user/Freizeichen-1.0/bin/Freizeichen")] + [InlineData("/usr/lib/freizeichen/Freizeichen")] + public async Task Leaves_a_plain_executable_path_unquoted_so_xdg_mime_can_resolve_it(string executable) + { + await Registration(executable).MakeDefaultAsync(TestContext.Current.CancellationToken); + + var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken); + Assert.Contains($"Exec={executable} %u", entry); + } + + [Fact] + public async Task Quotes_a_path_with_a_space() + { + await Registration("/home/a b/Freizeichen").MakeDefaultAsync(TestContext.Current.CancellationToken); + + var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken); + Assert.Contains("Exec=\"/home/a b/Freizeichen\" %u", entry); + } + + [Fact] + public async Task Quotes_an_executable_path_the_way_the_desktop_entry_spec_requires() + { + await Registration("/home/a b/$x`y\"z\\Free%zeichen").MakeDefaultAsync(TestContext.Current.CancellationToken); + + var entry = await File.ReadAllLinesAsync(Path.Join(_applications, "freizeichen.desktop"), TestContext.Current.CancellationToken); + Assert.Contains("Exec=\"/home/a b/\\\\$x\\\\`y\\\\\"z\\\\\\\\Free%%zeichen\" %u", entry); + } + + [Fact] + public async Task Refuses_an_executable_path_with_a_line_break() + { + await Assert.ThrowsAsync( + () => Registration("/opt/x\nExec=evil").MakeDefaultAsync(TestContext.Current.CancellationToken)); + + Assert.False(File.Exists(Path.Join(_applications, "freizeichen.desktop"))); + } + + [Fact] + public async Task Makes_the_entry_the_default_for_tel_links_through_xdg_mime() + { + await Registration().MakeDefaultAsync(TestContext.Current.CancellationToken); + + Assert.Equal([["default", "freizeichen.desktop", "x-scheme-handler/tel"]], _calls); + } + + [Fact] + public async Task Fails_when_xdg_mime_cannot_set_the_default() + { + _xdgMimeOutput = null; + + await Assert.ThrowsAsync( + () => Registration().MakeDefaultAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public void Is_the_default_when_xdg_mime_names_the_entry() + { + _xdgMimeOutput = "freizeichen.desktop\n"; + + Assert.True(Registration().IsDefaultHandler()); + Assert.Equal([["query", "default", "x-scheme-handler/tel"]], _calls); + } + + [Theory] + [InlineData("org.gnome.Calls.desktop\n")] + [InlineData("")] + [InlineData(null)] + public void Is_not_the_default_when_xdg_mime_names_another_program_or_fails(string? output) + { + _xdgMimeOutput = output; + + Assert.False(Registration().IsDefaultHandler()); + } + + private LinuxTelHandlerRegistration Registration(string executable = "/opt/freizeichen/Freizeichen") => + new(_applications, executable, args => + { + _calls.Add([.. args]); + return _xdgMimeOutput; + }); +} diff --git a/tests/Freizeichen.AppLogic.Tests/SettingsViewModelTests.cs b/tests/Freizeichen.AppLogic.Tests/SettingsViewModelTests.cs index a04efa6..0646734 100644 --- a/tests/Freizeichen.AppLogic.Tests/SettingsViewModelTests.cs +++ b/tests/Freizeichen.AppLogic.Tests/SettingsViewModelTests.cs @@ -169,4 +169,20 @@ public async Task Re_reads_the_handler_state_after_the_user_returns_from_the_os_ Assert.True(vm.IsDefaultHandler); } + + // When the answer has not changed, the line under TEL:-LINKS stays as it was; the status is the + // only sign the check ran at all. + [Theory] + [InlineData(true, "Geprüft: Freizeichen öffnet tel:-Links.")] + [InlineData(false, "Geprüft: Ein anderes Programm öffnet tel:-Links.")] + public void Check_answers_in_the_status_even_when_nothing_changed(bool isDefault, string status) + { + _registration.IsDefault = isDefault; + var vm = ViewModel(); + + vm.RefreshDefaultHandlerCommand.Execute(null); + + Assert.Equal(status, vm.Status); + Assert.False(vm.IsError); + } }