diff --git a/CHANGELOG.md b/CHANGELOG.md index 8613dad0..353fc633 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,181 @@ All notable changes to tacctl. The README and the manual page describe only the current behaviour; this file is where history lives. +## 0.2.28 (2026-11-09) + +1. **A support bundle from a Cisco IOS device no longer starts the identity + lines with the tail of the command.** Item 9 of 0.2.27 dropped the echo + of a command longer than the terminal is wide, but only when the first + line of the answer was the start of the command. On a Cisco 2811 the + `show running-config | include ^(hostname|ip domain|clock + timezone|snmp-server location|snmp-server contact)` file began with the + line `$clock timezone|snmp-server location|snmp-server contact)` (the `$` + is where the device cut its display) and then the `hostname` line: the + start of the echo was not a line of its own, so only the tail reached + the check, which wanted the start. The tail is dropped as well now: a + first line of `$` and pieces of the command, the last of which ends the + command, is the echo, whether or not the start of the echo stands before it. + Nothing else is dropped: a line with text that is not in the command, a + tail that does not end the command, and an output line that begins with + `$` stay. `docs/devices/support-bundle.md` and the manual page say so. + +2. **`tacctl rollback 0.2.27`, the release before this one, is a target.** It + converts nothing but the file transfer settings of `console.yaml` (item 3). + This release changed no other stored file 0.2.27 reads strictly (how the + answer of a Cisco IOS device to a long command is read, and the + documentation, are all that moved), so 0.2.27 reads everything else it + writes: with those settings unset the rollback removes no key and no field, + takes no snapshot and needs no `--yes`. The limits of the stored reports (`reports.max_size` and + `reports.max_count` in `tacctl.yaml`, and a user's own `reports_max_size` + and `reports_max_count` in `store.yaml`) stay, 0.2.27 has them, and so do + the chassis `members` of the pull records and every report in the users' + homes, the PDF ones included, which 0.2.27 reads, and the marker + `/var/lib/tacctl/pdf-tools-offered` with the packages `weasyprint` and + `fonts-dejavu-core`. The per-tier sudoers drop-in is left too: 0.2.27 and + this release write the same text. The break-glass firewall, the users' + email addresses, the SNMPv3 users, the covered staging entries, the server + name, the timing scale and an emergency lockdown with enrolled hosts, + which the older targets drop or refuse, stay as well. It is refused only + while a device's apply is not settled. The command ends with `tacctl + upgrade --branch 0.2.27` and, having nothing to avoid, has no closing note + unless it removed the file transfer settings (item 3). + `rollback 0.2.26` and older behave as before, and the lists of "every target + but" in the rollback pages and the manual page now include 0.2.27. The + top-level help, `docs/cli/conventions.md`, `docs/install/upgrading.md` + (Rolling back, To 0.2.27), `docs/releasing.md`, the manual page and the + completion list the new target, and `tacctl rollback` now takes fourteen + targets. The note that follows a rollback that took a snapshot names this + release, 0.2.28, as the state the snapshot holds ("Restore it with 0.2.28 + only"). + +3. **File transfer through the console: its settings, off by default.** The + console is to get a built-in file transfer, and a superuser decides who + has it. `tacctl console file-transfer enable|disable` opens it to a + tier and `tacctl console file-transfer user enable|disable|clear` + to one user, over the tier's setting in both directions, as `console + system-shell` does: an enable lasts only while the user stays in the tier + it was set for (a move to another tier leaves it listed as stale), a + disable holds in any tier, `clear` returns the user to the tier's setting, + and `user rename` and `user remove` move or drop a user's settings. It is + off for every tier but the superuser tier, which always has it and cannot + be disabled; unlike the system shell and forwarding the engineer tier is + not closed to it, because a transfer reaches the user's home only, and a + caller with no tier never has it. `console file-transfer quota` is the + bytes the whole home may hold, 256M for the readonly, operator and + engineer tiers and none for the superuser tier until it is set + (`quota |unlimited|default`, `quota user + |unlimited|clear`), and `console file-transfer rate` is the bytes a + second a transfer may go at, off by default (`rate |off`, + `rate user |off|clear`). A size is a number of bytes or a + number with `K`, `M`, `G` or `T` (powers of 1024, `512K`, `256M`, `2G`), + printed back in the largest unit that holds it exactly; zero, a negative + number, a fraction, an overflow and more than `1T` are refused, and a + user's value wins over the tier's. With no argument, `console + file-transfer`, `quota` and `rate` list the tiers and the users with a + setting of their own, and `console show` lists each tier's state, quota and + rate and each user's next to the system shell. The settings are + `settings.file_transfer` in `console.yaml` (written only when something in + it is not the built-in setting), apply from the next console login, are + logged as `console set key=file-transfer` at `auth.notice`, and reach the + console through `tacctl _console-policy` (`file_transfer=yes ft_quota= + ft_rate=` for a caller who has it). The settings decide who may transfer + files, and the console's file transfer (item 4) reads them. Setting them is the + superuser's, and so are the read forms: the verb has no row in the tier + table, so every form of `console file-transfer` is refused below the + superuser tier, while `console show`, which the operator tier and up can + run, lists every user's state, quota and rate. 0.2.27 and + every older release reject the key (their reader answers `settings: + unknown key 'file_transfer'`, the console falls back to its defaults and + writes fail), so every `tacctl rollback` target removes it with the + snapshot of `--apply`, keeps every other setting, needs no `--yes` and + ends with a note on what to avoid until the older release is installed. + `docs/cli/console.md`, `docs/security/login-console.md`, `docs/cli/user.md`, + `docs/security/audit.md`, `docs/install/upgrading.md` (Rolling back, To + 0.2.27) and the manual page say so. + +4. **The console serves SFTP to the accounts that have file transfer.** The + sftp subsystem, which sshd's `ForceCommand` hands to the console as the + `-c` string `/usr/lib/openssh/sftp-server` or `internal-sftp`, is no longer + refused for everyone: for an account that item 3's settings give file + transfer, the console serves the protocol itself on standard input and + output, as the logged-in user (no change of privilege). The user's home + directory, as the account database names it and never `$HOME`, is the root: + `/` is the home, `..` does not leave it, `.ssh` is not listed and every + request for it is refused, no symbolic link is followed, and neither a + symbolic link nor a hard link can be created through the console. A file + that already has more than one name (a hard link made outside SFTP) + cannot be opened, downloaded or written, and its mode and times cannot be + changed (refused, reason `link`); it can still be listed, renamed and + removed. Setting the mode of a directory without the owner's read and + search bits is refused. The size of a regular file can be set (cut, or + extended with zeros), which is what `scp` does after an upload to give the + file its final size; it counts against the quota like a write, and a request + that also asks for a new owner is refused whole. A new directory gets the + mode the client asks for and a new file 0644, both reduced by the console's + umask, 077; the set-user-ID, set-group-ID and sticky bits are ignored. + Changing a mode or times goes through `/proc/self/fd`, so file transfer + needs `/proc` mounted. A listing comes in the order of the file system, + not sorted (the OpenSSH `sftp` client sorts what its `ls` prints itself), + and a session has at most 256 files and listings open at once (reason + `too-many-open-files`). `sftp` and the `scp` of OpenSSH 9 or later (which + uses SFTP) work; `scp -O`, `rsync`, programs and shell words stay refused, + with a text that no longer says file transfer is unavailable: `the tacctl + console does not run programs or shell commands; file transfer is SFTP only + (sftp, scp of OpenSSH 9 or later)`. The quota (the bytes the home may hold: + the sizes of its regular files, each inode once, never directories, links + or inodes; the reports and support bundles of the user are included) + refuses a write that would go over it; an upload refused part way leaves + what was written before in the home (the client does not remove it), and + the OpenSSH `sftp` and `scp` show only `Failure` for it, the reason + (`reason=quota`) being in the console's audit log. It is measured per session, so N + sessions at once can reach about N times the quota; a deleted file that a + handle still holds stays counted until the handle is closed; and a + directory of the home that the session cannot read or search (for example + one owned by root with mode 0700) makes the home count as full, so every + upload that grows it is refused with `disk quota exceeded` until the + directory is readable. The rate (bytes a second, reads and writes + together, a burst of one second) slows the session. For an account without + file transfer the subsystem is refused with status 126 and `file transfer is + not enabled for this account; an administrator can switch it on (tacctl + console file-transfer)`, which `sftp` and `scp` show only as `Connection + closed` (sshd shows no error text of a subsystem; the audit log has + `reason=file-transfer`); a session held to a required password change, or + one whose policy cannot be read (a user who is no superuser), and a missing + home are refused with a text of their own. The console's idle timeout does + not apply to a transfer: it lasts as long as the connection, ends with + status 0 when the client closes it, and a protocol error ends it with + status 1 and one line on standard error; nothing but protocol is written + to standard output. A transfer is in the console's own log under the tag + `tacctl-console`: `console sftp start` (the tier, the home, the quota and the + rate in effect), `console sftp upload|download|delete|rename|mkdir|setstat` + (each with `tier=`, like the refusals), `console sftp DENY ... reason=` for a + refused request of any kind (`.ssh`, `outside-the-home`, `symlink`, `link`, + `quota`, `unsupported`, `bad-path`, `too-many-open-files`; a refused + `readlink` or `realpath` too) at `auth.warning`, `console sftp end` (the + bytes up and down, the requests, the refusals), and `mode=sftp` and + `reason=sftp` on the session's start and end lines; the successful `stat`, + listing, `readlink` and `realpath` are not logged. The subsystem refused is + `console DENY ... reason=file-transfer|password-change|policy|home|stream + subsystem=sftp`. A path is a file name, so unlike a refused command it is + logged, but as a double-quoted string with control characters, quotes, + backslashes and bytes that are not UTF-8 escaped, cut at 200 bytes of the + escaped text, so that no name forges a field or a line and `logger` keeps + the whole line (the error text does not repeat the path). If `logger` + cannot write a line, the warning `The audit line was not written (logger: + ); the command continues.` can appear on standard error during a + transfer and the transfer goes on, unaudited. sshd starts the subsystem only if its configuration defines + `Subsystem sftp ...`, which a `Match` block cannot: `console file-transfer` + with no argument and the server section of `console show` now print `sshd + sftp subsystem: ` or `none` (from `sshd -T`) and warn in red when + file transfer is on for a tier other than the superuser tier, or for a user, + and sshd defines none. The reading of `console file-transfer` is the + superuser's only (item 3 said the operator tier and up could read it: the + verb has no row for them in the tier table); every user's state, quota and + rate are in `console show`, which the operator tier and up can run. + `docs/cli/console.md` (File transfer), `docs/security/login-console.md`, + `docs/security/audit.md`, `docs/devices/reports.md`, `docs/cli/device.md` + and the manual page say so. + ## 0.2.27 (2026-11-09) 1. **A read-only user's device reports no longer hold what `device show` diff --git a/docs/cli/console.md b/docs/cli/console.md index 0fe1e127..43b1a220 100644 --- a/docs/cli/console.md +++ b/docs/cli/console.md @@ -2,7 +2,7 @@ [Documentation](../README.md) › [CLI reference](README.md) -The login console is the login shell of every tacctl user, of every tier, on the tacctl server: tacctl commands and ssh to registered devices, nothing else. There is no switch for it, and local accounts that are not tacctl users are never touched. Its settings are in `/etc/tacctl/console.yaml` (0600, snapshotted, in `backup diff` and `restore`; absent means the defaults). The settings commands change that file only (after a snapshot); they never change an account or sshd. The accounts' login shells and sshd's drop-in follow the sync of this server's accounts (`tacctl host sync `), which every change to agent forwarding or the forwarding settings prints. The idle timeout, the ssh escape, the space completion, the colour, the list threshold and the system shell are read by each console session when it starts. +The login console is the login shell of every tacctl user, of every tier, on the tacctl server: tacctl commands and ssh to registered devices, nothing else. There is no switch for it, and local accounts that are not tacctl users are never touched. Its settings are in `/etc/tacctl/console.yaml` (0600, snapshotted, in `backup diff` and `restore`; absent means the defaults). The settings commands change that file only (after a snapshot); they never change an account or sshd. The accounts' login shells and sshd's drop-in follow the sync of this server's accounts (`tacctl host sync `), which every change to agent forwarding or the forwarding settings prints. The idle timeout, the ssh escape, the space completion, the colour, the list threshold, the system shell and the file transfer settings are read by each console session when it starts. ```yaml version: 1 @@ -23,6 +23,13 @@ settings: # system_shell_users: # written only when a user has a setting of their own # jdoe: true # true gives the system shell, false takes it (console system-shell user) + # file_transfer: # written only when something is set (see File transfer) + # tiers: [superuser] # the tiers that have it; superuser always + # users: {alice: 'enable:operator', bob: disable} + # quota: {operator: 1G} # bytes the whole home may hold; unlimited = no limit + # quota_users: {alice: unlimited} + # rate: {operator: 1M} # bytes a second; a tier with none has no limit + # rate_users: {bob: 'off'} # password_cache_users: # written only when a user turned the cache on (see # Password cache); a map of user name to true # jdoe: true @@ -32,13 +39,14 @@ settings: # max: 8 # hours ``` -The keys: `settings.idle_timeout` (`console idle-timeout`), `settings.agent_forwarding` (`console agent-forwarding`), `settings.ssh_escape` (`console ssh-escape`), `settings.system_shell` (`console system-shell path`), `settings.system_shell_tiers` (`console system-shell enable|disable`; always holds `superuser`, never `engineer`), `settings.system_shell_users` (`console system-shell user`; written only when a user has a setting), `settings.forwarding_tiers` and `settings.gateway_ports` (`console forwarding tiers|gateway-ports`; the tiers are never `engineer`), `settings.list_max` (`console list-max`; 1 to 1000, or -1 to never ask), `settings.space_completion` (`console space-completion`; written only when off), `settings.color` (`console color`; written only when `on` or `off`) `settings.password_cache` (`console password-cache tiers|idle|max`; written only when set) and `settings.password_cache_users` (`console password-cache on|off` by each user, `console password-cache user`; written only when a user has turned it on). +The keys: `settings.idle_timeout` (`console idle-timeout`), `settings.agent_forwarding` (`console agent-forwarding`), `settings.ssh_escape` (`console ssh-escape`), `settings.system_shell` (`console system-shell path`), `settings.system_shell_tiers` (`console system-shell enable|disable`; always holds `superuser`, never `engineer`), `settings.system_shell_users` (`console system-shell user`; written only when a user has a setting), `settings.file_transfer` (`console file-transfer`; written only when something in it is not the built-in setting), `settings.forwarding_tiers` and `settings.gateway_ports` (`console forwarding tiers|gateway-ports`; the tiers are never `engineer`), `settings.list_max` (`console list-max`; 1 to 1000, or -1 to never ask), `settings.space_completion` (`console space-completion`; written only when off), `settings.color` (`console color`; written only when `on` or `off`) `settings.password_cache` (`console password-cache tiers|idle|max`; written only when set) and `settings.password_cache_users` (`console password-cache on|off` by each user, `console password-cache user`; written only when a user has turned it on). ``` console show - Settings, each user of this server's scope with its effective shell and why, and the server's - pieces (operator tier and up) + Settings, each user of this server's scope with its effective shell, system shell and file + transfer (state, quota and rate) and why, and the server's pieces, sshd's sftp subsystem + included (operator tier and up) console idle-timeout [] @@ -145,6 +153,44 @@ console system-shell path [] The system shell (default /bin/bash; absolute, executable, listed in /etc/shells); showing it is open to the operator tier and up, setting it is the superuser's +console file-transfer [ enable|disable] + + Without arguments, whether each tier has file transfer and the users with a setting of their + own, with their tier. A tier alone prints its state; with enable or disable it sets it. Every + form of the verb is the superuser's, the reads included (`console show` has the state of every + user, for the operator tier and up). Off for every tier by default; the superuser tier always + has it and cannot be disabled; the engineer tier can be given it (see File transfer) + +console file-transfer user [enable|disable|clear] + + Show or set file transfer for one user, over the tier's setting in both directions (clear: the + tier decides; without a word it prints the user's access and why). Disabling a superuser is + refused and enabling one stores nothing. An enable is for the tier the user has when it is + set: after a move to another tier it does nothing and is listed as "stale: set for operator, + now readonly" until it is set again. A disable holds in any tier. `user rename` moves the + user's settings (the switch, the quota and the rate) to the new name and `user remove` drops + them; an entry for a name that is no user is not honoured and is listed as "no such user" + +console file-transfer quota [ |unlimited|default] + + Without arguments, the quota of each tier (the bytes the whole home may hold) and the users + with one of their own; a tier alone prints its quota; with a size, unlimited or default it sets + it (default returns the tier to the built-in value) + +console file-transfer quota user [|unlimited|clear] + + Show or set the quota of one user, over the tier's (clear: the tier decides) + +console file-transfer rate [ |off] + + Without arguments, the rate of each tier (the bytes a second a transfer may go at) and the + users with one of their own; a tier alone prints its rate; with a size or off it sets it + +console file-transfer rate user [|off|clear] + + Show or set the rate of one user, over the tier's (off: no limit whatever their tier has; + clear: the tier decides) + console install Put the /etc/shells line and sshd's drop-ins (console users, engineers) in place (host sync of @@ -164,7 +210,46 @@ console check both lists (operator tier and up) ``` -`console show` lists the users of the scope of the host enrolled with `--local` with their effective shell (the console) and why, then the server's pieces: the `/usr/local/bin/tacctl-console` symlink, the `/etc/shells` line, sshd's drop-in and what `sshd -T -C user=` reports for a console user (`allowtcpforwarding`, `allowagentforwarding`, `forcecommand`, `pubkeyauthentication`). It warns in red when the drop-in is missing, sshd does not force the console, still allows forwarding, or allows key logins, because a console user could then forward ports past the device registry, run programs or sftp, or log in without TACACS+. A server that is not enrolled with `--local` says so. +`console show` lists the users of the scope of the host enrolled with `--local` with their effective shell (the console) and why, then the server's pieces: the `/usr/local/bin/tacctl-console` symlink, the `/etc/shells` line, sshd's drop-in and what `sshd -T -C user=` reports for a console user (`allowtcpforwarding`, `allowagentforwarding`, `forcecommand`, `pubkeyauthentication`). It warns in red when the drop-in is missing, sshd does not force the console, still allows forwarding, or allows key logins, because a console user could then forward ports past the device registry, run programs or sftp, or log in without TACACS+. The table has each user's file transfer (state, quota and rate, with the reason) next to the system shell's, and the server section says whether sshd defines an sftp subsystem (`sshd sftp subsystem: /usr/lib/openssh/sftp-server`, or `none`), with a red warning when file transfer is on for someone and sshd defines none (see File transfer). A server that is not enrolled with `--local` says so. + +## File transfer — `console file-transfer` + +The console serves one kind of file transfer, SFTP, to the accounts that have it. It is off for every tier but the superuser tier, which always has it, until a superuser opens it for a tier (`tacctl console file-transfer operator enable`) or for one user (`tacctl console file-transfer user alice enable`). It is settled like the system shell: a user's own setting wins over the tier's, in both directions; an enable lasts only while the user stays in the tier they had when it was set; and `console show` lists each tier's state and each user's access with the reason (and the quota and rate). Unlike the system shell and forwarding, the engineer tier is not closed to it: a transfer reaches the user's home only, where a shell or a forwarded port would reach the server's secrets. A caller with no tier is never given it. + +Every form of `console file-transfer` is the superuser's, the reads included (`console file-transfer`, `... `, `... user `, `... quota`, `... rate`): the verb has no row for the lower tiers. What each user has, the state, the quota and the rate, is in `console show`, which the operator tier and up can run; the read-only tier cannot. + +**What a user can do.** `sftp alice@tacacs.example.net` and the `scp` of OpenSSH 9 or later (which speaks SFTP unless it is given `-O`) work for an account that has file transfer. `scp -O` (the old protocol), `rsync`, any program and the shell's words are refused, as before, with `the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)` (exit 126). For an account that does not have file transfer the subsystem is refused with `file transfer is not enabled for this account; an administrator can switch it on (tacctl console file-transfer)` (exit 126), and so is the subsystem of a user held to a required password change. The console serves the protocol as the logged-in user, with no change of privilege, so the file system's permissions apply as they do in the user's shell. An account that does not have file transfer sees only `Connection closed` from `sftp` and `scp` (sshd does not show the error text of a subsystem; `ssh id`, a command request, does): the reason, `reason=file-transfer` with status 126, is in the console's audit log, and `console show` lists who has file transfer. + +**The root is the home.** The user's home directory, as the account database names it and never `$HOME`, is `/` for the client: a relative path starts there, and `..` does not climb out of it. `.ssh` is invisible (a listing does not show it) and every request for it, by any spelling, is refused; so is the request that would change the home directory itself. A symbolic link is never followed, and neither a symbolic link nor a hard link can be created through the console (the request is refused). A file that already has more than one name (a hard link made outside SFTP, for example in a shell with `ln`) cannot be opened, downloaded or written, and its mode and times cannot be changed (refused, reason `link`); it can still be listed, renamed and removed, since that acts on the name and not on the data. Setting the mode of a directory without the owner's read and search bits is refused too. The size of a regular file can be set (cut, or extended with zeros), which is what `scp` does after an upload to give the file its final size; it counts against the quota like a write (see below). The owner cannot be changed, and a request that asks for it is refused whole. A new directory gets the mode the client asks for and a new file 0644, both reduced by the umask of the console, 077 (so a directory is 0700 and a file 0600); the set-user-ID, set-group-ID and sticky bits are ignored, and a client that wants another mode sets it afterwards, which is applied as given. Changing the mode or the times of a file goes through `/proc/self/fd`, so file transfer needs `/proc` mounted on the server. A listing comes in the order of the file system, not sorted (the `sftp` client of OpenSSH sorts what its `ls` prints itself). A session has at most 256 files and directory listings open at once; an open past that fails and is audited (reason `too-many-open-files`). The reports (`device reports`) and the support bundles of the user are in the home, so a user can fetch them with `scp alice@tacacs.example.net:reports/devices/inventory-20261106.csv .`. + +**The quota and the rate.** The quota is the bytes the home may hold. It counts the sizes of the regular files in it, each inode once (a file with two names counts once): the reports and support bundles tacctl wrote there, `.ssh` and the files the user uploads. Directories, links and inodes do not count, and a sparse file counts its length. A write that would take the home over it is refused whole (`disk quota exceeded`) and audited, and so is a size that would grow a file over it; a smaller size gives the room back. An upload that is refused part way leaves what was written before the refusal in the home (the client does not remove it), and the `sftp` and `scp` of OpenSSH show only `Failure` for it: the reason, `reason=quota`, is in the console's audit log. A file that was deleted while a handle of the session still holds it stays counted until the handle is closed. The home is measured when the session starts and again, when a file is opened for writing, if the last measure is a few seconds old, so the quota is per session: N sessions of one user at once can each use the room that was free when they measured, and bring the home to about N times the quota. A directory in the home that the session cannot read or search (for example one owned by root with mode 0700) makes the home count as full: every upload that grows the home is refused with `disk quota exceeded` until the directory is readable, while reading, deleting and writes that do not grow the home go on. The rate is the bytes a second one session may move, reads and writes together, with a burst of one second; a transfer at its rate waits, it is not refused. Both are read when the session starts. + +**The audit.** A transfer is in the console's own log, under the tag `tacctl-console`: the session's start (`mode=sftp`), `console sftp start` (the tier, the home, the quota and the rate in effect), one line for each upload, download, delete, rename, mkdir and setstat (`console sftp upload ... tier=operator path="/reports/a.csv" bytes=431`; each of these lines names the caller's tier), `console sftp DENY` for each refused request (reason `.ssh`, `outside-the-home`, `symlink`, `link`, `quota`, `unsupported`, `bad-path` or `too-many-open-files`), `console sftp end` (the bytes up and down, the requests, the refusals) and the session's end. Refusals of every kind are logged, a refused `readlink` or `realpath` included; the successful `stat`, listing, `readlink` and `realpath` are not. A refused subsystem is `console DENY ... reason=file-transfer|password-change|policy|home|stream subsystem=sftp`. The paths are file names and are logged, but escaped like a Go string in double quotes (a newline or an escape sequence in a name is `\n` or `\x1b`, never itself) and cut at 200 bytes of the escaped text (a name that was cut ends with `...` after the closing quote); the error text of a request that failed is cut the same way and does not repeat the path, so a line stays short enough for `logger` to keep it whole. When `logger` cannot write a line, the warning `The audit line was not written (logger: ); the command continues.` can appear on standard error during a transfer, and the transfer goes on, unaudited, with standard output still the protocol's alone. See [Audit logging](../security/audit.md). + +**Ending.** The console's idle timeout does not apply to a transfer: the session lasts as long as the connection, as an sshd subsystem does, and ends with status 0 when the client closes it. A protocol error ends it with status 1 and one line on standard error (`tacctl-console: sftp: ...`). Nothing but protocol is written to standard output. + +**sshd must start the subsystem.** sshd starts the sftp subsystem only if its configuration defines `Subsystem sftp ...` (the stock `sshd_config` of Debian and Ubuntu has `Subsystem sftp /usr/lib/openssh/sftp-server`), and a `Match` block cannot define one: the line is global, and tacctl adds nothing global (the console's drop-in forces the console for every login and subsystem, which then hands the subsystem's command to it). `console file-transfer` with no argument and `console show` print `sshd sftp subsystem: ` or `none`, read from `sshd -T`, and warn in red when file transfer is on for a tier other than the superuser tier, or for a user, and sshd defines none: ``sshd defines no sftp subsystem: file transfer cannot start; add `Subsystem sftp ...` to sshd_config``. + +The quota is the bytes the whole home may hold. Nothing set means 256M for the readonly, operator and engineer tiers and unlimited for the superuser tier; a tier is set with `console file-transfer quota |unlimited|default` and one user with `quota user |unlimited|clear`. The rate is the bytes a second a transfer may go at, off (no limit) by default: `rate |off` and `rate user |off|clear`. A size is a number of bytes or a number with `K`, `M`, `G` or `T` (powers of 1024), such as `512K`, `256M` or `2G`, and is printed back in the largest unit that holds it exactly. Zero, a negative number, a fraction, a number that overflows and more than `1T` are refused. A user's quota or rate wins over the tier's, `unlimited` and `off` included; `clear` returns the user to the tier's value. + +The settings are kept in `settings.file_transfer` of `console.yaml` (`tiers`, `users`, `quota`, `quota_users`, `rate`, `rate_users`), written only when something in it is not the built-in setting. They apply from the next console login, are logged as `console set key=file-transfer item=|user:|quota:|quota-user:|rate:|rate-user:` at `auth.notice`, and reach the console through `tacctl _console-policy`, which carries `file_transfer=yes ft_quota= ft_rate=` for a caller who has it. The console fails closed: a policy it cannot read, or one that does not name file transfer, is no file transfer. + +```bash +tacctl console file-transfer operator enable +tacctl console file-transfer quota operator 1G +tacctl console file-transfer rate operator 1M +tacctl console file-transfer user alice enable +tacctl console file-transfer quota user alice unlimited +tacctl console file-transfer user alice clear +``` + +From a client: + +```bash +sftp alice@tacacs.example.net +scp alice@tacacs.example.net:reports/devices/inventory-20261106.csv . +``` + ## The console session — `tacctl-console` @@ -184,7 +269,7 @@ ssh carol@authsrv < lines.txt The lines as a batch; stops at the first failure ``` -`-c` accepts one line that starts with a tacctl command or `help`. Everything else — `scp`, `sftp`, `rsync`, any program, the shell's own words, an empty string — is refused with `the tacctl console does not run programs; file transfer is not available` (exit 126) and nothing runs; so is any other argument (`the tacctl console takes no options`). +`-c` accepts one line that starts with a tacctl command or `help`, and the sftp subsystem (`/usr/lib/openssh/sftp-server`, `internal-sftp`, which sshd's `ForceCommand` hands over in `SSH_ORIGINAL_COMMAND`) for the accounts that have file transfer (see File transfer): it is refused with `file transfer is not enabled for this account; an administrator can switch it on (tacctl console file-transfer)` for the others. Everything else — `scp -O`, `rsync`, any program, the shell's own words, an empty string — is refused with `the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)` (exit 126) and nothing runs; so is any other argument (`the tacctl console takes no options`). A word that starts with an underscore (`__help`, `__complete`, `_console-policy`: the entry points of the scripts, the key and the console itself) is no command at the prompt or in a batch: it is answered as any word that is no command (`Unknown command: '__help'`), and nothing runs. diff --git a/docs/cli/conventions.md b/docs/cli/conventions.md index 74b02c16..55d53761 100644 --- a/docs/cli/conventions.md +++ b/docs/cli/conventions.md @@ -42,8 +42,8 @@ tacctl uninstall [--yes] tacctl rollback [--apply] [--yes] [--hosts] - Prepare the state for the release before this one (0.2.26), for 0.2.25, 0.2.24, - 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 or for 0.2.3: a + Prepare the state for the release before this one (0.2.27), for 0.2.26, 0.2.25, + 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 or for 0.2.3: a dry run unless --apply; see install/upgrading.md, "Rolling back" tacctl status diff --git a/docs/cli/device.md b/docs/cli/device.md index c6dc663b..e6ddcd36 100644 --- a/docs/cli/device.md +++ b/docs/cli/device.md @@ -787,9 +787,10 @@ device reports list [--json] [--user | --all-users] device reports show [--content] When, by whom and with what command the report was made, its filters, the date of its oldest - datum, its size and the `scp` line that fetches it; `--content` adds its first 200 lines (a PDF - is binary: it says `binary PDF, bytes: use export`). A report is its name, or its file name - when two files share a name; a superuser names another user's as `/` (audited) + datum, its size and the `scp` line that fetches it (the console serves it only if file transfer + is enabled for you); `--content` adds its first 200 lines (a PDF is binary: it says `binary + PDF, bytes: use export`). A report is its name, or its file name when two files share a + name; a superuser names another user's as `/` (audited) device reports export [--out ] [--force] diff --git a/docs/cli/emergency.md b/docs/cli/emergency.md index f236cc2c..c7499b02 100644 --- a/docs/cli/emergency.md +++ b/docs/cli/emergency.md @@ -132,7 +132,7 @@ takes the group out of every lockdown, and `group edit tier superuser` (or a priv-lvl edit that makes the group a superuser's) is refused while the group is locked, since a superuser group is never locked. A rollback to a release before 0.2.19 is refused while a lockdown stands, and every rollback -but the ones to 0.2.26, 0.2.25, 0.2.24 and 0.2.23 is while a lockdown has enrolled hosts or a +but the ones to 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 is while a lockdown has enrolled hosts or a lifted one waits for a host (`tacctl rollback`; older releases cannot lift the drop-in). `config validate` warns while a lockdown stands and reports a record that names a scope or group that no diff --git a/docs/cli/user.md b/docs/cli/user.md index 35e1589c..0d1056c0 100644 --- a/docs/cli/user.md +++ b/docs/cli/user.md @@ -62,10 +62,11 @@ user reports-limit clear user remove - Remove a user (with confirmation); the user's `console system-shell user` and `console - password-cache` settings, if any, are dropped and the command says so. Refused, with nothing - changed, while console.yaml cannot be read (so that no setting is left for the next user of the - name); the same holds for `user add` and `user rename` + Remove a user (with confirmation); the user's `console system-shell user`, `console + file-transfer` (the switch, the quota and the rate) and `console password-cache` settings, if + any, are dropped and the command says so. Refused, with nothing changed, while console.yaml + cannot be read (so that no setting is left for the next user of the name); the same holds for + `user add` and `user rename` user passwd @@ -102,8 +103,9 @@ user enable user rename Rename a user; the new name is lower case and follows the rules of `user add`. The user's - `console system-shell user` setting moves to the new name, and the command says so. Changing - only the spelling (`user rename Alice alice`) fixes a name from before. Devices match the + `console system-shell user` setting and its `console file-transfer` settings (the switch, the + quota and the rate) move to the new name, and the command says so. Changing only the spelling + (`user rename Alice alice`) fixes a name from before. Devices match the typed login name exactly, so the rename changes what the person types at the device. The user keeps the Linux UID: the line of the old name in `linux-uids` becomes the new name's, in place, and the command says `UID follows the rename (linux-uids).` With enrolled hosts @@ -169,7 +171,7 @@ max-count:` line for a user who has an own limit, to every tier that can run `us accounting sink takes none. Setting a limit renders and restarts nothing and takes a snapshot, like any change of the store, and writes the detail line `user reports-limit name= key=max-size|max-count op=set|clear value=`. A release before 0.2.26 refuses the fields, so every `tacctl rollback` target before 0.2.26 -(0.2.25 and older; `rollback 0.2.26` keeps them) removes them after a snapshot, needs `--yes` while a user has one and names the users (see +(0.2.25 and older; `rollback 0.2.26` and `rollback 0.2.27` keep them) removes them after a snapshot, needs `--yes` while a user has one and names the users (see [Rolling back](../install/upgrading.md#rolling-back)). ``` @@ -211,7 +213,7 @@ only when set, so a store without one is unchanged. No mail is sent to it. in any other `user` verb, and `…(redacted)` in place of the rest. Like any word on a command line it is in sudo's own log. - *Older releases.* A release before 0.2.23 refuses the key, so every `tacctl - rollback` target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 (which read it) removes it after a + rollback` target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 (which read it) removes it after a snapshot that it keeps, and names the users; `backup recover` puts the addresses back (see [Rolling back](../install/upgrading.md#rolling-back)). @@ -343,7 +345,7 @@ only when set. the reason in `user show`), and one whom devices of a shared scope still accept `flagged, devices in a scope shared with the server still accept the password`; `status` names both groups. - *Older releases.* A release before 0.2.20 refuses the key, so every `tacctl rollback` target - but 0.2.26 to 0.2.20 (which read it) removes it after a snapshot and warns which users get their device access back (see + but 0.2.27 to 0.2.20 (which read it) removes it after a snapshot and warns which users get their device access back (see [Rolling back](../install/upgrading.md#rolling-back)). **A hash kept off the command line.** `--hash -` reads the hash from one line diff --git a/docs/devices/reports.md b/docs/devices/reports.md index 7b3e93c6..74e0b88c 100644 --- a/docs/devices/reports.md +++ b/docs/devices/reports.md @@ -149,6 +149,8 @@ Report inventory-20261106 Download: scp alice@tacacs.example.net:reports/devices/inventory-20261106.csv . ``` +The console serves that `scp` (OpenSSH 9 or later, which uses SFTP) and `sftp` only if file transfer is enabled for you: it is off for every tier but the superuser tier until a superuser switches it on ([File transfer](../cli/console.md#file-transfer--console-file-transfer)). Without it the console refuses with `file transfer is not enabled for this account`. + ## Looking after reports - **`list`** prints your reports, newest first, with the name, the type, the format, the size and when each was made (UTC), and the total; `--json` prints a list of objects with the same facts and the command line, the filters and the dates (a file that is not a report has `other: true` and the file, the name, the owner and the size only). A file tacctl did not make has the type `other`. The JSON list cleans every string as the text list does (a control or direction character in a file name or a metadata field is a `?`). @@ -248,7 +250,7 @@ A report that is too large can be made smaller (`--scope`, `--vendor`), printed ## Older releases -A release before 0.2.26 has no `device reports` verb. `tacctl rollback` to 0.2.25 or older (see [Rolling back](../install/upgrading.md#rolling-back)) leaves the reports and their metadata files where they are, because they are the users' own files, and says so; it removes the limits of this page (the two settings and the users' own limits, after a snapshot, and `--yes` while a user has one), and puts back the per-tier sudoers drop-in without the `device reports` rows. The `members` of the pull records stay too: an older release ignores them. `tacctl rollback 0.2.26` converts nothing: 0.2.26 has the verbs, the limits and the reports, and reads them as they are. +A release before 0.2.26 has no `device reports` verb. `tacctl rollback` to 0.2.25 or older (see [Rolling back](../install/upgrading.md#rolling-back)) leaves the reports and their metadata files where they are, because they are the users' own files, and says so; it removes the limits of this page (the two settings and the users' own limits, after a snapshot, and `--yes` while a user has one), and puts back the per-tier sudoers drop-in without the `device reports` rows. The `members` of the pull records stay too: an older release ignores them. `tacctl rollback 0.2.26` and `tacctl rollback 0.2.27` convert nothing: both have the verbs, the limits and the reports, and read them as they are (0.2.26 has no PDF format and shows a PDF report as text; 0.2.27 reads it as it is). ## Exit status diff --git a/docs/devices/support-bundle.md b/docs/devices/support-bundle.md index f47fda8c..bf121beb 100644 --- a/docs/devices/support-bundle.md +++ b/docs/devices/support-bundle.md @@ -92,7 +92,8 @@ first (see [Examples](../development/README.md#examples) for the values): added or taken away so that the columns after it stay where the device printed them (nothing is done at the end of a line); - a Cisco device that echoes a command longer than its terminal is wide, in several lines, leaves - none of the echo in the file: it starts with the device's answer. + none of the echo in the file: it starts with the device's answer; when only the tail of the echo + reaches the session (a line of `$` and the rest of the command), that tail is dropped as well. A text that still holds a value the scrubber learned to replace is not written, and nothing is. diff --git a/docs/install/upgrading.md b/docs/install/upgrading.md index 12ee95db..c0211925 100644 --- a/docs/install/upgrading.md +++ b/docs/install/upgrading.md @@ -110,22 +110,24 @@ Nothing is asked when both packages are installed, on a system without `apt-get` ## Rolling back -`tacctl rollback` takes thirteen targets: `0.2.26`, the release before this -one, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22`, `0.2.21`, `0.2.20`, `0.2.19`, `0.2.18`, `0.2.17`, `0.2.16`, `0.2.9` and +`tacctl rollback` takes fourteen targets: `0.2.27`, the release before this +one, `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22`, `0.2.21`, `0.2.20`, `0.2.19`, `0.2.18`, `0.2.17`, `0.2.16`, `0.2.9` and `0.2.3`. All are the dry run described below until `--apply` is given, all -refuse while an apply is not settled, all but `0.2.26`, `0.2.25`, `0.2.24`, +refuse while an apply is not settled, all but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22`, `0.2.21`, `0.2.20` and `0.2.19` while an emergency -lockdown locks a group, all but `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23` while an emergency lockdown has enrolled hosts, and each release's tool prepares the state for +lockdown locks a group, all but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23` while an emergency lockdown has enrolled hosts, and each release's tool prepares the state for the releases it knows. `0.2.4` to `0.2.8` and `0.2.2` and older are refused with the way there (one release at a time, or `tacctl backup restore` of a snapshot of the time); `0.2.10` to `0.2.15`, this release and any other word are refused with the targets named. -**The break-glass firewall (0.2.24).** Every target but `0.2.26`, `0.2.25` and `0.2.24` removes the firewall of the held addresses: `breakglass.firewall` from `tacctl.yaml` (every older release refuses the key, so the key goes after the snapshot like the others they do not know), the nftables table `inet tacctl` with `nft` (the rest of the ruleset is not touched), `/etc/tacctl/breakglass-firewall.nft` and the boot unit `tacctl-breakglass-firewall.service` (disabled first). The `nftables` package stays installed. The dry run lists the step when the file or the unit exists, and the report says what went. A hold that stands stays (0.2.5 and later releases have the record) and is taken over as it is, without the firewall: the older release's server completes the TCP handshake of the held address again, so a device that falls back to its local accounts only when the server is unreachable (WTI `On (Transport Failure)`, Junos `authentication-order [ tacplus password ]`) will not; the plan names the holds in a note. Until the older release is installed, run no verb that changes the holds, their device or host names, the listeners or the setting (`breakglass hold|release`, `device address`, `device|host rename`, `device rename --replace`, `backup restore`, `server listen`, `config breakglass-firewall`): each writes the table, the rules file and the boot unit again, and the setting writes the key the older release refuses. Run the rollback again if one was run. +**The break-glass firewall (0.2.24).** Every target but `0.2.27`, `0.2.26`, `0.2.25` and `0.2.24` removes the firewall of the held addresses: `breakglass.firewall` from `tacctl.yaml` (every older release refuses the key, so the key goes after the snapshot like the others they do not know), the nftables table `inet tacctl` with `nft` (the rest of the ruleset is not touched), `/etc/tacctl/breakglass-firewall.nft` and the boot unit `tacctl-breakglass-firewall.service` (disabled first). The `nftables` package stays installed. The dry run lists the step when the file or the unit exists, and the report says what went. A hold that stands stays (0.2.5 and later releases have the record) and is taken over as it is, without the firewall: the older release's server completes the TCP handshake of the held address again, so a device that falls back to its local accounts only when the server is unreachable (WTI `On (Transport Failure)`, Junos `authentication-order [ tacplus password ]`) will not; the plan names the holds in a note. Until the older release is installed, run no verb that changes the holds, their device or host names, the listeners or the setting (`breakglass hold|release`, `device address`, `device|host rename`, `device rename --replace`, `backup restore`, `server listen`, `config breakglass-firewall`): each writes the table, the rules file and the boot unit again, and the setting writes the key the older release refuses. Run the rollback again if one was run. -**The limits of the stored reports (0.2.26).** The settings `reports.max_size` and `reports.max_count` of `tacctl.yaml` (`config reports`) and a user's own limits, the fields `reports_max_size` and `reports_max_count` of the user in `store.yaml` (`user reports-limit`), are keys no release before 0.2.26 reads, so every target before 0.2.26 (`0.2.25` and older; `0.2.26` has them and keeps them) removes them. The settings go with the other keys the target does not know, after the snapshot `--apply` takes first, and need no answer. A user's own limit is data somebody chose for one user, so the dry run names each user with the values in a warning (`remove the report limits of bob (max-size 20 MiB, max-count 50 reports)`), `--apply` refuses without `--yes` while any user has one, the snapshot holds them, and the audit line of the rollback names the users (`limit-users=`, never a value). Once this release is installed again, `tacctl user reports-limit max-size|max-count ` sets them again from the list the rollback prints (`backup recover` does not bring them back). A store that cannot be read refuses every target before 0.2.26: a limit that cannot be seen is not hidden. The reports in the users' homes stay, as the users' own files (an older release has no `device reports` verb to list or remove them), and so do the chassis `members` of the pull records, which an older decoder ignores; the per-tier sudoers drop-in loses the rows of `device reports` (every target before 0.2.26 rewrites it as it did, and 0.2.25 and 0.2.24 with the text they wrote; `0.2.26` leaves it, it wrote the same text as this release). Until the older release is installed, run none of `config reports max-size`, `config reports max-count` and `user reports-limit`: they write what the older release refuses. If one did, run the rollback again (with `--yes` while a user has a limit of their own). Every target before 0.2.26 ends with a note that says that the reports stay and what to avoid; `0.2.26` has none, it has nothing to avoid. +**The limits of the stored reports (0.2.26).** The settings `reports.max_size` and `reports.max_count` of `tacctl.yaml` (`config reports`) and a user's own limits, the fields `reports_max_size` and `reports_max_count` of the user in `store.yaml` (`user reports-limit`), are keys no release before 0.2.26 reads, so every target before 0.2.26 (`0.2.25` and older; `0.2.27` and `0.2.26` have them and keep them) removes them. The settings go with the other keys the target does not know, after the snapshot `--apply` takes first, and need no answer. A user's own limit is data somebody chose for one user, so the dry run names each user with the values in a warning (`remove the report limits of bob (max-size 20 MiB, max-count 50 reports)`), `--apply` refuses without `--yes` while any user has one, the snapshot holds them, and the audit line of the rollback names the users (`limit-users=`, never a value). Once this release is installed again, `tacctl user reports-limit max-size|max-count ` sets them again from the list the rollback prints (`backup recover` does not bring them back). A store that cannot be read refuses every target before 0.2.26: a limit that cannot be seen is not hidden. The reports in the users' homes stay, as the users' own files (an older release has no `device reports` verb to list or remove them), and so do the chassis `members` of the pull records, which an older decoder ignores; the per-tier sudoers drop-in loses the rows of `device reports` (every target before 0.2.26 rewrites it as it did, and 0.2.25 and 0.2.24 with the text they wrote; `0.2.27` and `0.2.26` leave it, they wrote the same text as this release). Until the older release is installed, run none of `config reports max-size`, `config reports max-count` and `user reports-limit`: they write what the older release refuses. If one did, run the rollback again (with `--yes` while a user has a limit of their own). Every target before 0.2.26 ends with a note that says that the reports stay and what to avoid; `0.2.27` and `0.2.26` have none, they have nothing to avoid. -**PDF reports (0.2.27).** No target converts or removes them: a PDF report is a file of the user's home like the others, with a `.meta` file whose `format` is `pdf`, and the marker `/var/lib/tacctl/pdf-tools-offered` (see [PDF reports](#pdf-reports)) is a file no release reads but this one. The packages `weasyprint` and `fonts-dejavu-core` stay installed. An older release has no PDF format: 0.2.26 lists such a report and its `show --content` cleans the bytes as text, so fetch it with the `scp` line of `show` instead, and it must not be renamed with `device reports rename` (0.2.26 gives the file the new name without its `.pdf`); remove it or rename it before the rollback. +**The console's file transfer settings (0.2.28).** `console.yaml` holds `settings.file_transfer` once something in it is set (`console file-transfer`: the tiers and users that have file transfer, and the quota and the rate of tiers and users). No release before 0.2.28 reads the key, 0.2.27 included: its reader answers `settings: unknown key 'file_transfer'`, the console falls back to its defaults and the commands that write the file fail. So every target removes it: `--apply` takes the snapshot first, removes `settings.file_transfer` and keeps every other setting, and the dry run lists the key as a step of its own with what it held (the tiers, and how many user switches, quotas and rates). It needs no `--yes`. This is the one conversion of `0.2.27` and `0.2.26`, which otherwise convert nothing, and with the settings unset they still take no snapshot. When the key was removed the command ends with a note: until the older release is installed, run no `tacctl console file-transfer` that sets something (it writes the key again; run the rollback again if one was run), and the snapshot holds the 0.2.28 state, which only 0.2.28 restores (the older release would put back a `console.yaml` it cannot read). The settings are not kept anywhere else: set them again after the upgrade. + +**PDF reports (0.2.27).** No target converts or removes them: a PDF report is a file of the user's home like the others, with a `.meta` file whose `format` is `pdf`, and the marker `/var/lib/tacctl/pdf-tools-offered` (see [PDF reports](#pdf-reports)) is a file no release reads but 0.2.27 and the ones after it. The packages `weasyprint` and `fonts-dejavu-core` stay installed. `0.2.27` has the format and reads the reports as they are. A release before 0.2.27 has no PDF format: 0.2.26 lists such a report and its `show --content` cleans the bytes as text, so fetch it with the `scp` line of `show` instead, and it must not be renamed with `device reports rename` (0.2.26 gives the file the new name without its `.pdf`); remove it or rename it before a rollback to 0.2.26 or older. **A downgrade without the rollback.** `tacctl upgrade --branch ` onto 0.2.23 or earlier is not refused, and does not touch the table; those releases never update it. An address held and released under them stays refused on TCP, live and at boot, and `breakglass.firewall` in `tacctl.yaml` is a key they refuse. Prefer the rollback above, which removes all of it. Without it, as root and without tacctl, remove the key from `tacctl.yaml` and the firewall: @@ -143,18 +145,18 @@ systemctl daemon-reload **Every user's login to this server (0.2.21).** This release lets every user log in to the tacctl server and its console, unless disabled or of tier none, without the server's scope in the user's own scopes. Every older release -needs it there (0.2.21 to 0.2.26 have it themselves), so every target but -`0.2.26`, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22` and `0.2.21` adds the scope of this server's own login (`tacctl`) to +needs it there (0.2.21 to 0.2.27 have it themselves), so every target but +`0.2.27`, `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22` and `0.2.21` adds the scope of this server's own login (`tacctl`) to the scopes of each user who logs in to the server and lacks it (the plan counts and names them; a warning, so `--apply` needs `--yes`), after a -snapshot. Every target but `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23` and `0.2.22` removes the server name +snapshot. Every target but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23` and `0.2.22` removes the server name `server.name` (0.2.22, `tacctl server name`) from `tacctl.yaml`, and every -target but `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22` and `0.2.21` the server address `server.addresses` too; no older +target but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23`, `0.2.22` and `0.2.21` the server address `server.addresses` too; no older release knows them. The host registry keeps the address in this server's entry, which the older release reads, and the console shows the host name again. -**The timing scale (0.2.22).** Every target but `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23` and `0.2.22` also removes the +**The timing scale (0.2.22).** Every target but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24`, `0.2.23` and `0.2.22` also removes the timing scale (`tacctl device timeout-scale`, `scope timeout-scale`, `config devices timeout-scale`): `device.timeout_scale` and `timeout_scale_scope.` from `tacctl.yaml`, and the `timeout_scale` of @@ -166,7 +168,7 @@ distant device may not meet. The values stay in the snapshot `--apply` takes first. **Email addresses (0.2.23).** `users..email` (`tacctl user email`, `user -add --email`) is a key no older release reads: every target but `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23`, the +add --email`) is a key no older release reads: every target but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23`, the ones that return early and `0.2.22` included, removes it from `store.yaml` after a snapshot. The plan names the users who have an address (never the address), in a warning, so `--apply` needs `--yes`; a rollback of a store without an @@ -193,7 +195,7 @@ releases ignore a version 1 file there). A device's file follows its entry: it is saved version 2 while the device has no entry, written version 1 when an entry appears (any setting of the device) and the content fits version 1 (a pool of two stays version 2), and version 2 again when the entry is gone. No -older release reads version 2 ("unsupported version"), so every target but `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23` writes +older release reads version 2 ("unsupported version"), so every target but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23` writes each version 2 file in version 1 again, after the snapshot `--apply` takes first; a state with version 1 files only has nothing of this to convert. Version 1 holds one v3 user for each level: the default user stays and the @@ -225,7 +227,7 @@ rollback again. clone` at a bench address its scope answers already writes an entry marked `covered` to `state/staging` (no `/32` is added). An older release reads it as a plain entry, and its sweep and `scope staging remove` take that `/32` out of -the scope, a prefix of the scope's own included. So every target but `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23` drops these +the scope, a prefix of the scope's own included. So every target but `0.2.27`, `0.2.26`, `0.2.25`, `0.2.24` and `0.2.23` drops these entries from the file, after the snapshot; the plan names them, and nothing asks (no warning, no `--yes`). A clone that still waits for its `device rename --replace` loses its entry, and after a re-upgrade the verb refuses it as not @@ -241,7 +243,7 @@ rollback again. A record that locks nothing (a hand-edited, partial one) is removed by the rollback, because the older schemas refuse its keys. **An emergency lockdown that has enrolled hosts stops every rollback but the -one to 0.2.26, 0.2.25, 0.2.24 or 0.2.23**, the ones to 0.2.19 to 0.2.22 included (the dry run too). On a host the lockdown is +one to 0.2.27, 0.2.26, 0.2.25, 0.2.24 or 0.2.23**, the ones to 0.2.19 to 0.2.22 included (the dry run too). On a host the lockdown is an sshd drop-in that only this release writes and removes, and the record keeps the hosts it has not reached (a `pending` list that older releases refuse), so an older release could not lift it and the hosts would stay @@ -253,12 +255,12 @@ any more (`emergency lockdown enable ` or `disable` drops the name). A lockdown on a scope with no enrolled host is taken over as before. -**The password cache is the user's choice (0.2.20).** `console password-cache tiers` is now only the permission: a tier that is listed no longer has the cache on for everyone in it. Each user turns it on for themselves with `console password-cache on` (off by default), so a console that had the cache on for a tier has it off for every user until they do; `tacctl shell --password-cache` is unchanged. The choices are stored in `settings.password_cache_users` (written only when a user turned it on). No release before 0.2.20 reads that key: the rollback removes it for every target before 0.2.20 (0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 and 0.2.3; the plan names the users), and the older release then has the cache on for every user of a listed tier, as it always did (0.2.3 has no cache). The targets 0.2.26 to 0.2.20 read the key and leave it. +**The password cache is the user's choice (0.2.20).** `console password-cache tiers` is now only the permission: a tier that is listed no longer has the cache on for everyone in it. Each user turns it on for themselves with `console password-cache on` (off by default), so a console that had the cache on for a tier has it off for every user until they do; `tacctl shell --password-cache` is unchanged. The choices are stored in `settings.password_cache_users` (written only when a user turned it on). No release before 0.2.20 reads that key: the rollback removes it for every target before 0.2.20 (0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 and 0.2.3; the plan names the users), and the older release then has the cache on for every user of a listed tier, as it always did (0.2.3 has no cache). The targets 0.2.27 to 0.2.20 read the key and leave it. -**The system shell of single users.** `settings.system_shell_users` (`console system-shell user`, written only when a user has a setting) is a key no release before 0.2.20 reads: the rollback to a target before 0.2.20 removes it (the plan names the users and their setting), and the older release has the tiers' list `settings.system_shell_tiers` alone; the targets 0.2.26 to 0.2.20 read the key and leave it. That list always holds `superuser` once this release has written it. +**The system shell of single users.** `settings.system_shell_users` (`console system-shell user`, written only when a user has a setting) is a key no release before 0.2.20 reads: the rollback to a target before 0.2.20 removes it (the plan names the users and their setting), and the older release has the tiers' list `settings.system_shell_tiers` alone; the targets 0.2.27 to 0.2.20 read the key and leave it. That list always holds `superuser` once this release has written it. **The console switches of `console.yaml`.** The `tiers` and `users` mappings that this release -ignores stay in the file, and a release before 0.2.20 (the targets 0.2.19 and older; 0.2.26 to 0.2.20 +ignores stay in the file, and a release before 0.2.20 (the targets 0.2.19 and older; 0.2.27 to 0.2.20 ignore them too, and their rollback says nothing of it) reads them as it always did: a tier or a user switched off there gets a plain shell again at the next `host sync` of that release. A file without the mappings is read there as the console on for every tier. The rollback lists every user @@ -286,7 +288,7 @@ before the upgrade, or expect the errors. Targets 0.2.18, 0.2.17, 0.2.16 and `settings.list_max` of `-1` (`console list-max` with a negative number: never ask). No release before 0.2.20 reads either (it answers `unknown key 'color'` or `settings.list_max must be 1-1000`, the console falls back to its defaults and -its writes fail), so every target before 0.2.20 (0.2.19 and older; 0.2.26 to 0.2.20 read +its writes fail), so every target before 0.2.20 (0.2.19 and older; 0.2.27 to 0.2.20 read both) takes them out: `--apply` removes `settings.color`, writes `list_max: 1000` in place of `-1`, keeps every other setting, and takes the snapshot first. The dry run lists the change as a step @@ -295,7 +297,7 @@ of its own. **A scope's strict management filter mode.** The mode of the Junos management filter (`tacctl scope mgmt-acl mode`, 0.2.20) is stored as `scope_mgmt_acl.mode.` (only `strict` is stored), a key every release -before 0.2.20 refuses. Every target before 0.2.20 (0.2.19 and older; 0.2.26 to 0.2.20 read it +before 0.2.20 refuses. Every target before 0.2.20 (0.2.19 and older; 0.2.27 to 0.2.20 read it and leave it) therefore removes it from `tacctl.yaml` after a snapshot, and the dry run lists the scopes that were strict in a warning that `--apply` refuses without `--yes`. The older release renders and plans the `ssh-only` filter for them, which ends in a `default-accept` term, so its @@ -309,7 +311,7 @@ older release's plans. password before logging in to anything but tacctl (`password_change_required` in `store.yaml`, written only for a flagged user, 0.2.20). Every older release refuses the key (`user '': unknown field -'password_change_required'`), so every target but `0.2.26` to `0.2.20` (which read +'password_change_required'`), so every target but `0.2.27` to `0.2.20` (which read it) removes it from the store after a snapshot, and the dry run lists the flagged users. Those who are not superusers (the flag never binds a superuser) are named in a warning that `--apply` refuses without `--yes`: the older release renders them into every @@ -350,11 +352,23 @@ other line; the dry run lists each file. The files are derived and never in a snapshot; this release, if it stays, reads the two as missing until its next `device config pull`. +### To 0.2.27 + +0.2.27 reads every file this release writes but one setting of `console.yaml`: this release changed no other stored file it reads strictly (how the answer of a Cisco IOS device to a long command is read, and the documentation, are all that moved). So the rollback converts nothing, with one exception: it removes the file transfer settings of `console.yaml` (see above) when they are set, after the snapshot `--apply` takes first, and keeps every other setting. With none set it removes no key and no field, takes no snapshot, needs no `--yes` and leaves every file alone. The limits of the stored reports (`reports.max_size` and `reports.max_count` in `tacctl.yaml`, and a user's own limits in `store.yaml`) stay, 0.2.27 has them, as do the chassis `members` of the pull records and every report in the users' homes, the PDF ones included, which 0.2.27 reads. The marker `/var/lib/tacctl/pdf-tools-offered` stays, and so do the packages `weasyprint` and `fonts-dejavu-core`. The per-tier sudoers drop-in is left too: 0.2.27 and this release write the same text. The break-glass firewall, the users' email addresses, the SNMPv3 users, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (with or without enrolled hosts) all stay. It still refuses while an apply is not settled. `--hosts` is accepted and does nothing. The tacquito checkout in `/opt/tacquito-src` keeps pointing at the project's fork, which is what 0.2.27 pulls from. + +What this release changed outside the stored files is 0.2.27's to undo or keep. After the `tacctl upgrade --branch 0.2.27` that ends the rollback, the support bundle of a Cisco IOS device starts its identity lines with the tail of a long command's echo again, as it did in 0.2.27, when the device cuts its display of the command. The bundles made in between stay as they were made. + +```bash +tacctl rollback 0.2.27 # the dry run: steps, writes nothing +tacctl rollback 0.2.27 --apply +tacctl upgrade --branch 0.2.27 # install 0.2.27 +``` + ### To 0.2.26 -0.2.26 reads every file this release writes: this release changed no stored file it reads strictly (what the `show switch` reader accepts, what the reports of a user below the operator tier hold, the audit line of a prune of other users' reports, the wording of two notes and the documentation are all that moved). So the rollback converts nothing: it removes no key and no field, takes no snapshot, needs no `--yes` and leaves every file alone. The limits of the stored reports (`reports.max_size` and `reports.max_count` in `tacctl.yaml`, and a user's own limits in `store.yaml`) stay, 0.2.26 has them, as do the chassis `members` of the pull records and every report in the users' homes, which 0.2.26 reads. The per-tier sudoers drop-in is left too: 0.2.26 and this release write the same text. The break-glass firewall, the users' email addresses, the SNMPv3 users, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (with or without enrolled hosts) all stay. It still refuses while an apply is not settled. `--hosts` is accepted and does nothing. The tacquito checkout in `/opt/tacquito-src` keeps pointing at the project's fork, which is what 0.2.26 pulls from. +0.2.26 reads every file 0.2.27 and this release write but one setting of `console.yaml`: they changed no other stored file it reads strictly (what the `show switch` reader accepts, what the reports of a user below the operator tier hold, the audit line of a prune of other users' reports, the PDF format of the reports and the offer of its tools, how the answer of a Cisco IOS device to a long command is read, the wording of two notes and the documentation are all that moved). So the rollback converts nothing but the file transfer settings of `console.yaml` (see above): with none set it removes no key and no field, takes no snapshot, needs no `--yes` and leaves every file alone. The limits of the stored reports (`reports.max_size` and `reports.max_count` in `tacctl.yaml`, and a user's own limits in `store.yaml`) stay, 0.2.26 has them, as do the chassis `members` of the pull records and every report in the users' homes, which 0.2.26 reads. The per-tier sudoers drop-in is left too: 0.2.26, 0.2.27 and this release write the same text. The break-glass firewall, the users' email addresses, the SNMPv3 users, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (with or without enrolled hosts) all stay. It still refuses while an apply is not settled. `--hosts` is accepted and does nothing. The tacquito checkout in `/opt/tacquito-src` keeps pointing at the project's fork, which is what 0.2.26 pulls from. -What this release changed outside the stored files is 0.2.26's to undo or keep. After the `tacctl upgrade --branch 0.2.26` that ends the rollback, a row of `show switch` whose H/W version column is blank is not read again by the next `device config pull`, as in 0.2.26, and the reports a user below the operator tier makes hold the model, serial number, release and chassis members of a device again, as they did in 0.2.26. The reports made in between stay as they were made. +What 0.2.27 and this release changed outside the stored files is 0.2.26's to undo or keep. After the `tacctl upgrade --branch 0.2.26` that ends the rollback, a row of `show switch` whose H/W version column is blank is not read again by the next `device config pull`, as in 0.2.26, and the reports a user below the operator tier makes hold the model, serial number, release and chassis members of a device again, as they did in 0.2.26. The reports made in between stay as they were made. ```bash tacctl rollback 0.2.26 # the dry run: steps, writes nothing @@ -364,7 +378,7 @@ tacctl upgrade --branch 0.2.26 # install 0.2.26 ### To 0.2.25 -0.2.25 reads every file 0.2.26 and this release write but the limits of the stored reports, so the rollback removes those and converts nothing else (see above): the settings `reports.max_size` and `reports.max_count` from `tacctl.yaml`, and the users' own limits from `store.yaml`. With none of them set it converts nothing, takes no snapshot and does not need `--yes`; with a setting or a limit of a user it takes the snapshot first, and a limit of a user needs `--yes`. When it took a snapshot, the next steps say that it holds the 0.2.27 state and is to be restored with 0.2.27 only, and says what 0.2.25's restore refuses: a `tacctl.yaml` with a key it does not know when a setting was removed, a `store.yaml` with a field it does not know when only a user's own limit was, both when both were. It puts back the per-tier sudoers drop-in that 0.2.25 wrote, this release's without the rows of `device reports`, when the file is exactly this release's text: the dry run shows the step, `--apply` writes it after `visudo -cf` (no snapshot holds a sudoers file), and a file `tacctl` did not write is left. It leaves the `members` of the pull records (0.2.25 ignores the key) and every report in the users' homes, and ends with the note about them and about the three commands that write a limit again. The break-glass firewall, the users' email addresses, the SNMPv3 users, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (with or without enrolled hosts) all stay. It still refuses while an apply is not settled. `--hosts` is accepted and does nothing. The tacquito checkout in `/opt/tacquito-src` keeps pointing at the project's fork, which is what 0.2.25 pulls from. +0.2.25 reads every file 0.2.26, 0.2.27 and this release write but the limits of the stored reports, so the rollback removes those and converts nothing else but the file transfer settings of `console.yaml` (see above): the settings `reports.max_size` and `reports.max_count` from `tacctl.yaml`, and the users' own limits from `store.yaml`. With none of them set it converts nothing, takes no snapshot and does not need `--yes`; with a setting or a limit of a user it takes the snapshot first, and a limit of a user needs `--yes`. When it took a snapshot, the next steps say that it holds the 0.2.28 state and is to be restored with 0.2.28 only, and says what 0.2.25's restore refuses: a `tacctl.yaml` with a key it does not know when a setting was removed, a `store.yaml` with a field it does not know when only a user's own limit was, both when both were. It puts back the per-tier sudoers drop-in that 0.2.25 wrote, this release's without the rows of `device reports`, when the file is exactly this release's text: the dry run shows the step, `--apply` writes it after `visudo -cf` (no snapshot holds a sudoers file), and a file `tacctl` did not write is left. It leaves the `members` of the pull records (0.2.25 ignores the key) and every report in the users' homes, and ends with the note about them and about the three commands that write a limit again. The break-glass firewall, the users' email addresses, the SNMPv3 users, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (with or without enrolled hosts) all stay. It still refuses while an apply is not settled. `--hosts` is accepted and does nothing. The tacquito checkout in `/opt/tacquito-src` keeps pointing at the project's fork, which is what 0.2.25 pulls from. ```bash tacctl rollback 0.2.25 # the dry run: steps, writes nothing @@ -391,15 +405,15 @@ tacctl upgrade --branch 0.2.24 # install 0.2.24 ### To 0.2.23 -0.2.23 reads every file 0.2.24 to 0.2.26 and this release write but `breakglass.firewall` +0.2.23 reads every file 0.2.24 to 0.2.27 and this release write but `breakglass.firewall` (0.2.24's) and the limits of the stored reports (0.2.26's). The rollback removes the key when it is set, after a snapshot, with the table, the rules file and the boot unit of the break-glass firewall (above), and the limits as above (`--yes` while a user has one of their own). It converts no other file; with the key unset, no firewall file and no limit it takes no snapshot and does not need `--yes`. When it took one, the next steps say that the -snapshot holds the 0.2.27 state and is to be restored with 0.2.27 only: 0.2.23's +snapshot holds the 0.2.28 state and is to be restored with 0.2.28 only: 0.2.23's restore refuses the snapshot's `tacctl.yaml`, which has the key. It puts back 0.2.23's per-tier sudoers drop-in, without the operator's `log failures *` (0.2.23 has no log filters), when the -file is exactly the text 0.2.24 and 0.2.25 wrote, or the one 0.2.26 and this release write: the dry run shows the step, `--apply` +file is exactly the text 0.2.24 and 0.2.25 wrote, or the one 0.2.26, 0.2.27 and this release write: the dry run shows the step, `--apply` writes it after `visudo -cf`, and a file `tacctl` did not write is left. Every older target that rewrites the per-tier drop-in recognises this release's text, 0.2.25's and 0.2.23's as `tacctl`'s own and puts back its own. The users' email addresses, the SNMPv3 users, the covered staging entries, the @@ -419,7 +433,7 @@ tacctl upgrade --branch 0.2.23 # install 0.2.23 ### To 0.2.22 -0.2.22 reads every file 0.2.23 to 0.2.26 and this release write but the users' email addresses in +0.2.22 reads every file 0.2.23 to 0.2.27 and this release write but the users' email addresses in `store.yaml`, so the rollback removes those and the limits of the stored reports (above) and converts nothing else but the sudoers drop-in (below): the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (of @@ -626,7 +640,7 @@ tacctl upgrade --branch 0.2.3 # install 0.2.3: switches the clone to th `--apply` takes a snapshot first (`tacctl backup list`), then, in this order: 1. **`tacctl.yaml`**: removes `device.config.max_concurrency`, `device.config.transport`, `device.config.timeout`, `device.config.confirm_timeout`, `device.apply.confirm_timeout`, `device.apply.pause`, `device.apply.transport` and `audit.strict`, every `netconf_scope.`, `cisco.source_interface.` and `breakglass_hold.` key (the keys 0.2.5 added, and any other key 0.2.3 does not know). Every other key stays. A break-glass hold that stands stops the rollback instead, so no hold is ever dropped by it. -2. **`console.yaml`**: removes `settings.password_cache` (the password cache's tiers and lifetimes: 0.2.3's parser rejects the key, the console would fall back to the defaults and its writes would fail), so the cache is off again; `settings.color` and a `list_max` of `-1` go as for every target (above); every other setting stays, `tiers.engineer` and `settings.space_completion` included (they are 0.2.3's own). +2. **`console.yaml`**: removes `settings.password_cache` (the password cache's tiers and lifetimes: 0.2.3's parser rejects the key, the console would fall back to the defaults and its writes would fail), so the cache is off again; `settings.color`, a `list_max` of `-1` and `settings.file_transfer` go as for every target (above); every other setting stays, `tiers.engineer` and `settings.space_completion` included (they are 0.2.3's own). 3. **`devices.yaml`**: removes the `snmp:` map of every device (a device's own SNMP version, port, timeout and allowed clients: 0.2.3's parser answers `unknown key 'snmp'` and cannot read the registry) the `ios_syntax` key of every Cisco device that has one (`device 'x': unknown key 'ios_syntax'`) and the `netconf:` map of every Junos device that has one (`unknown key 'netconf'`). The devices are then read with their scope's or the default's settings, and the dry run warns that 0.2.3 compares a `legacy-ssh` Cisco device as IOS 12.x again; the locations and everything else stay. 4. **The sudoers drop-ins**: a per-tier drop-in (`/etc/sudoers.d/tacctl-tiers`) or a group drop-in (`config sudoers install `) that is exactly the text this release writes (or the one 0.2.4 to 0.2.8 wrote) is rewritten with the text 0.2.3 writes, after `visudo -cf` (it loses the `TACCTL_ASKPASS` alias and `env_keep` line, and, in the per-tier file, the rows of `device config`, `device snmp`, `device ios-syntax`, `breakglass list` and `console forget`). A file an administrator edited is left as it is; a drop-in that `visudo` refuses is left and named, and the rollback goes on (0.2.3's upgrade rewrites the per-tier file with its own text). 5. **Leaves** `snmp/devices/` (the devices' own SNMP credentials, mode 0600: 0.2.3 opens `snmp/.yaml` by name and never lists the directory, so it ignores the subdirectory; 0.2.5 ignores a device's file too until the device has settings of its own again (its `snmp:` map gates the file), and `device snmp clear` removes it; they are in the snapshot), the records of the configuration pulls in `/var/lib/tacctl` (`devices-config.json` and `device-config/`: derived from the devices and never in a snapshot, which 0.2.3 does not open and 0.2.5 rebuilds; `tacctl device config forget --all` of 0.2.5, before the rollback, deletes them), `store.yaml` (0.2.5 did not change its format) and the rendered backend files (nothing it removes reaches them, so nothing is re-rendered or restarted). diff --git a/docs/plans/backlog.md b/docs/plans/backlog.md index 41071d0d..99b706bc 100644 --- a/docs/plans/backlog.md +++ b/docs/plans/backlog.md @@ -33,7 +33,8 @@ Planned 2026-10-08; **solidified 2026-10-09 with the 0.2.4 plan** (`0.2.4-plan.m | **0.2.23 (released 2026-10-31; CHANGELOG `## 0.2.23`, items 1-20)** | **Stored-file changes with a `rollback 0.2.22`:** an optional email on users; the SNMPv3 user pool (one default per level, protocols per level); `device clone` and `device rename --replace` with the scope staging address (and `rename` carrying the staging line); lockdown on enrolled hosts (a static sshd `Match Group` drop-in, applied by `host sync`, pending list); carry-overs of 0.2.22; device-own AAA settings and the AAA source check (`device check|scan --sources`); an immediate sync of this server on user changes with an offer for the other hosts; `backup keep` and `backup recover`. Not in the release: naming a device from its configuration (section 3j). | | **0.2.24 (released 2026-11-05; CHANGELOG `## 0.2.24`, items 1-11)** | **Logs, forwarding and the tacquito source, with a `rollback 0.2.23` that converts nothing:** each accounting record names the device that sent it (`"Device"`, tacquito patch 0006; `log accounting` shows the device's name) and keeps `<`, `>` and `&` as they are; `--since`, `--until`, `--user`, `--device`, `--type` and `--json` on `log tail|search|failures|accounting`, with the operator's sudo rule `log failures *`; a user held to a password change forwards no port through the server in any tier (a `Match User` block ahead of the tier blocks of the console's sshd drop-in, checked by `console check`); the walkthroughs no longer set `single-connection` and `device config plan|apply` delete it from tacctl's server; tacquito built from the project's fork `rett/tacquito`, its pull a fetch and a fast-forward with a reset when it cannot; the git clones, fetches and pulls of `install`, `upgrade`, `config branch` and `config linux build` ask for nothing and drop a stalled transfer (an ssh remote needs its host key in `known_hosts`); a break-glass hold also loads an nftables table that refuses the held address's TCP connections to tacquito, so a device that falls back to its local accounts when the server is unreachable (WTI, Junos) does (`config breakglass-firewall reject|drop|off`, a boot unit, the `nftables` package, removed by `rollback`); `tacctl man` on groff 1.24; `make lint` in CI and the skipped tests counted by the gates. | | **0.2.25 (2026-11-05; CHANGELOG `## 0.2.25`, items 1-10)** | **Junos fixes from a live network, the shapes list and the apply explanation, with a `rollback 0.2.24` that converts nothing:** `device config shapes` keeps its table narrow (a count in `NOW`, the devices below it wrapped at 80 columns); "Applying a plan" opens with a rollout in five steps and explains shape, canary and confirmed; a Junos NETCONF hello that names its capabilities with the XML namespace's prefix is read as `hello ok`, the hello is read as the device prints it, and a failed hello says why; a slow device's late answer in front of a command's echo no longer fails a pull or an apply; a Junos virtual chassis of two members whose master prints its own label is applied to, and a refused commit answer shows up to 40 lines; text a device sends is shown with C1 controls, formatting characters and line separators replaced; `rollback 0.2.24`; small accuracy fixes (the snapshot note of `rollback 0.2.23`, "1 line differs", the `config apply` usage row, which targets remove the 0.2.20 keys). **Open:** a virtual chassis of three or more members that all print a label has no capture and is read one line per label. | -| **0.2.27 (CHANGELOG `## 0.2.27`, items 1-9)** | **PDF reports, a corrected support-bundle scrubber and home-only output paths, with a `rollback 0.2.26` that converts nothing:** `device reports generate --format pdf` (weasyprint, the upgrade offers `weasyprint` and `fonts-dejavu-core`); the scrubber keeps model names, object identifiers, column widths and vendors' public names and replaces serials by field, from the captures of real devices; every option that names a file to write is a path inside the caller's home (`device support-bundle --out` is a name); small report and rollback fixes. **Open:** chassis components (power supplies, fans, line cards, optics) of a member, file transfer through the console (built-in SFTP, off by default), a dual-RE or SRX-cluster capture and a standalone Catalyst capture. | +| **0.2.28 (CHANGELOG `## 0.2.28`, items 1-4)** | **File transfer through the console, with a `rollback 0.2.27` that converts only its settings:** the console serves SFTP (`sftp` and the `scp` of OpenSSH 9 or later) to the accounts that have it, as the user, rooted in the home with `.ssh` out of reach and no link followed; `console file-transfer` sets it per tier and per user (off by default, superusers always, engineers allowed) with a quota on the home (256M, none for superusers) and an optional rate; the support bundle of a Cisco IOS device drops the tail of a long command's echo. **Open:** honouring the mode a client asks for on an upload (a new file is 0644 under the umask 077, so `scp` keeps no executable bit); a rate-limited session that can stay a moment after the client leaves; chassis components (power supplies, fans, line cards, optics) of a member, a dual-RE or SRX-cluster capture and a standalone Catalyst capture. | +| **0.2.27 (CHANGELOG `## 0.2.27`, items 1-9)** | **PDF reports, a corrected support-bundle scrubber and home-only output paths, with a `rollback 0.2.26` that converts nothing:** `device reports generate --format pdf` (weasyprint, the upgrade offers `weasyprint` and `fonts-dejavu-core`); the scrubber keeps model names, object identifiers, column widths and vendors' public names and replaces serials by field, from the captures of real devices; every option that names a file to write is a path inside the caller's home (`device support-bundle --out` is a name); small report and rollback fixes. **Open:** chassis components (power supplies, fans, line cards, optics) of a member, a dual-RE or SRX-cluster capture and a standalone Catalyst capture. | | **0.2.26 (released 2026-11-06; CHANGELOG `## 0.2.26`, items 1-9)** | **Device reports with serial numbers and chassis members:** a good pull also stores the members of a Junos virtual chassis or Cisco stack (id, role, model, serial, release, status, priority); `device reports generate|list|show|export|rename|remove|prune` makes inventory, members, software and config reports as text, CSV or JSON in the user's own `~/reports/devices/`, from the stored records with no login (`--pull` reads first, engineer tier); superusers reach other users' reports with an audit line; `rollback 0.2.25`. **Out:** chassis components (0.2.27), PDF, `generate --as`. | | **0.2.10 (released 2026-10-15; `0.2.10-plan.md`, `0.2.10-lab.md`)** | **Apply over NETCONF as the second transport (pulled into 0.2.10 by the user, 2026-10-14; NETCONF is opt-in, the command line stays the default, `device config rollback` stays deferred) and the NETCONF service setting below; the account, break-glass and drift-detection items that follow are dropped (2026-10-15, `0.2.12-plan.md` section 2).** **A NETCONF service setting for Junos (decided with the user, 2026-10-14).** Three states, default `leave`: `enable` renders and plans `set system services netconf ssh` (with the optional connection-limit and rate-limit), `disable` plans `delete system services netconf`, `leave` plans and compares nothing (today's behaviour). Per scope with a per-device override, layered as SNMP and the blocks are: `scope netconf enable|disable|leave`, `device netconf enable|disable|leave`. The apply allow-list admits only those exact `system services netconf` statements; everything else under `system services` stays on the never-list (D133). Built, reviewed and run on the lab switch (`0.2.10-lab.md`). It supersedes `device config enable-netconf` (D93 of `apply-deferred.md`). **Provisioning/break-glass account rotation on devices** (new local user, proven by a fresh login, target switched, old one optionally removed last; new passwords generated and shown once unless decided otherwise); the rest of the per-user password handling, if any is left after 0.2.4. **From 0.2.4:** unattended drift detection (a timer running `device config pull --stale`) needs a credential no person types, which the never-stored rule forbids for users' passwords; it is designed here as a read-only service account on the devices (an ssh key held by the tacctl server, proved and rotated like the provisioning accounts), not before. **Break-glass users as a configuration block (filed 2026-10-12; open question, decide with the rotation design):** a vendor-native `login` block could carry a scope's break-glass accounts (Junos `system login user class authentication encrypted-password`, Cisco `username privilege secret 9 `), so every device of a scope gets the same account with compare, plan, back-out and the existing secret elision. *Gain:* consistent accounts, central rotation. *Cost:* it reverses the never-stored rule for a credential hash (at rest under `/etc/tacctl/blocks` and in every backup), makes one shared local-admin password per scope the easy path where a unique one per device is the usual practice, and a bad hash pasted fleet-wide breaks the one account meant for recovery (the helper's region check refuses login-user authentication today, and plans never emit the `breakglass` section, both on purpose). *Decide first:* store the hash (opt-in per scope, in a block, read-protected like an SNMP community) or keep it generated and shown once, which the rotation design above assumes; the two do not fit together. Until then: `scope breakglass` names and roles plus the walkthrough placeholder. Needs 0.2.9's apply to push a rotated account. | | **Apply (deferred, no release number)** | **NETCONF apply and rollback**, set aside by the user on 2026-10-10 ("stop netconf for now"). The approved plan is kept whole in `apply-deferred.md` (D77-D93: the transport interface with `Confirms()`, the private-session transaction, the ownership rule, the confirmed commit held on one session through a fresh login, the two-phase review, the canary, the records, `device config rollback`, the engineer pre-flight, `device config enable-netconf`; WP12.x). 0.2.5 reuses its planner and its guards as warnings; the NETCONF transport itself moved into 0.2.10 on 2026-10-14 (`0.2.10-plan.md`), the rest (rollback from history) waits. The 0.2.4 spike facts it rests on are in `0.2.4-spike.md` (d) and "Junos apply mechanics". **Amended by D129 (2026-10-13):** the transport interface is built in 0.2.9 with the Junos command line as its first implementation; what this plan keeps is the NETCONF transport (D78, D82), `enable-netconf` (D93, superseded by the 0.2.10 NETCONF service setting) and `rollback` from history (D86). | diff --git a/docs/release-notes-0.2.28.md b/docs/release-notes-0.2.28.md new file mode 100644 index 00000000..978ce4fd --- /dev/null +++ b/docs/release-notes-0.2.28.md @@ -0,0 +1,174 @@ +# tacctl 0.2.28 + +0.2.28 gives the tacctl console a built-in file transfer: SFTP, which `sftp` and the `scp` of +OpenSSH 9 or later speak. It is off by default for every tier but the superuser tier, and a +superuser decides who else has it, with a quota on the home and an optional rate. The release +also drops the tail of a long command's echo from the support bundle of a Cisco IOS device, +and `tacctl rollback 0.2.27` is a target. The numbered list in `CHANGELOG.md` (0.2.28) is +everything that differs from 0.2.27. + +## File transfer through the console + +In 0.2.27 the console refused `scp` and `sftp` as it refuses every program, so the `scp` line +that `device reports show` prints could not be used by a user whose login shell is the +console. This release serves that line. + +**File transfer through the console: its settings, off by default.** A superuser decides who has +the console's file transfer. Every form of `console +file-transfer` is the superuser's, the reads included. + +```bash +tacctl console file-transfer operator enable +tacctl console file-transfer user alice enable +tacctl console file-transfer user alice clear +tacctl console file-transfer +``` + +- `console file-transfer enable|disable` opens it to a tier and `console + file-transfer user enable|disable|clear` to one user, over the tier's setting in + both directions, as `console system-shell` does: an enable lasts only while the user stays + in the tier it was set for (a move to another tier leaves it listed as stale), a disable + holds in any tier, `clear` returns the user to the tier's setting, and `user rename` and + `user remove` move or drop a user's settings. +- It is off for every tier but the superuser tier, which always has it and cannot be + disabled. Unlike the system shell and forwarding, the engineer tier is not closed to it, + because a transfer reaches the user's home only. A caller with no tier never has it. +- The quota is the bytes the whole home may hold: 256M for the readonly, operator and + engineer tiers and none for the superuser tier until it is set (`console file-transfer + quota |unlimited|default`, `quota user |unlimited|clear`). The + rate is the bytes a second a transfer may go at, off by default (`rate |off`, + `rate user |off|clear`). A size is a number of bytes or a number with `K`, + `M`, `G` or `T` (powers of 1024: `512K`, `256M`, `2G`), printed back in the largest unit + that holds it exactly. Zero, a negative number, a fraction, an overflow and more than `1T` + are refused, and a user's value wins over the tier's. +- With no argument, `console file-transfer`, `quota` and `rate` list the tiers and the + users with a setting of their own. `console show`, which the operator tier and up can run, + lists each tier's state, quota and rate and each user's next to the system shell. +- The settings are `settings.file_transfer` in `console.yaml`, written only when something + in it is not the built-in setting. They apply from the next console login, are logged as + `console set key=file-transfer` at `auth.notice`, and reach the console through `tacctl + _console-policy`. The console fails closed: a policy it cannot read is no file transfer. + +**The console serves SFTP to the accounts that have file transfer.** The sftp subsystem, +which sshd's `ForceCommand` hands to the console, is no longer refused for everyone: for an +account that has file transfer the console serves the protocol itself, as the logged-in user +(no change of privilege), so the file system's permissions apply as they do in the user's +shell. + +- **Clients.** `sftp alice@tacacs.example.net` and the `scp` of OpenSSH 9 or later (which + speaks SFTP) work, for example + `scp alice@tacacs.example.net:reports/devices/inventory-20261106.csv .`. `scp -O`, `rsync`, + programs and shell words stay refused with `the tacctl console does not run programs or + shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)`. +- **The home is the root.** The user's home directory, as the account database names it and + never `$HOME`, is `/`, and `..` does not leave it. `.ssh` is not listed and every request + for it is refused. No symbolic link is followed, and neither a symbolic link nor a hard + link can be created through the console. A file that already has more than one name (a + hard link made outside SFTP) cannot be opened, downloaded or written, and its mode and + times cannot be changed (refused, reason `link`); it can still be listed, renamed and + removed. The owner cannot be changed. The reports and support bundles of the user are in + the home, so a user can fetch them. +- **The quota.** The home may hold 256M by default (none for superusers; per tier and per + user, see above). The quota counts the sizes of the regular files, each inode once, the + reports, the support bundles and `.ssh` included, never directories, links or inodes. A + write that would take the home over it is refused whole (`disk quota exceeded`), and so is + a size that would grow a file over it. The size of a regular file can be set (cut, or + extended with zeros), which is what `scp` does after an upload; it counts like a write. +- **The rate.** The rate is off by default. When set it is the bytes a second one session + moves, reads and writes together, with a burst of one second; a transfer at its rate + waits, it is not refused. +- **Modes.** The console's umask is 077. A new directory gets the mode the client asks for + and a new file 0644, both reduced by the umask, so a directory is 0700 and a file 0600; + the set-user-ID, set-group-ID and sticky bits are ignored. So a file uploaded with `scp` + has no executable bit; a client that wants another mode sets it afterwards (for example + the `chmod` of `sftp`), which is applied as given. Setting the mode of a directory without + the owner's read and search bits is refused. +- **What the clients show.** The OpenSSH `sftp` and `scp` show only `Failure` for a refused + write over the quota (the reason, `reason=quota`, is in the audit log), and an upload + refused part way leaves what was written before in the home. An account without file + transfer gets `file transfer is not enabled for this account; an administrator can switch + it on (tacctl console file-transfer)` (status 126), which the clients show only as + `Connection closed`, since sshd shows no error text of a subsystem; `reason=file-transfer` + is in the audit log. +- **The audit.** A transfer is in the console's own log under the tag `tacctl-console`: + `console sftp start` (the tier, the home, the quota and the rate in effect), one line for + each upload, download, delete, rename, mkdir and setstat, each with `tier=`, `console sftp + DENY ... reason=` for each refused request at `auth.warning` (`.ssh`, + `outside-the-home`, `symlink`, `link`, `quota`, `unsupported`, `bad-path`, + `too-many-open-files`), and `console sftp end` (the bytes up and down, the requests, the + refusals). A path is logged as a double-quoted string with control characters escaped and + cut at 200 bytes. A refused subsystem is `console DENY ... reason=file-transfer| + password-change|policy|home|stream subsystem=sftp`. A successful `stat`, listing, + `readlink` or `realpath` is not logged. +- **What sshd and the server need.** sshd starts the subsystem only if its configuration + defines `Subsystem sftp ...` (the stock `sshd_config` of Debian and Ubuntu does), which a + `Match` block cannot. `console file-transfer` with no argument and `console show` print + `sshd sftp subsystem: ` or `none` and warn in red when file transfer is on for a + tier other than the superuser tier, or for a user, and sshd defines none. Changing a mode + or times goes through `/proc/self/fd`, so `/proc` must be mounted. +- **The session.** The console's idle timeout does not apply to a transfer: it lasts as long + as the connection and ends with status 0 when the client closes it. A protocol error ends + it with status 1 and one line on standard error. A listing comes in the order of the file + system, not sorted, and a session has at most 256 files and listings open at once (reason + `too-many-open-files`). + +The pages are `docs/cli/console.md` (File transfer), `docs/security/login-console.md`, +`docs/security/audit.md`, `docs/devices/reports.md` and the manual page. + +## Known limits + +- The quota is measured per session, so N sessions of one user at once can reach about N + times the quota. +- The quota counts the sizes of regular files only. A file deleted while a session's handle + still holds it stays counted until the handle is closed, and a directory in the home that + the session cannot read or search (for example one owned by root with mode 0700) makes + the home count as full: every upload that grows it is refused with `disk quota exceeded` + until the directory is readable. +- The console does not honour the mode a client asks for on a new file: it is 0644 under the umask, + and the client sets another mode afterwards (see Modes). +- If `logger` cannot write an audit line, the warning `The audit line was not written + (logger: ); the command continues.` can appear on standard error and the transfer + goes on, unaudited. + +## The support bundle of a Cisco IOS device + +**A support bundle from a Cisco IOS device no longer starts the identity lines with the tail +of the command.** 0.2.27 dropped the echo of a command longer than the terminal is wide, but +only when the first line of the answer was the start of the command. On a Cisco 2811 the +file of `show running-config | include ^(hostname|ip domain|clock timezone|snmp-server +location|snmp-server contact)` began with the tail of the command after a `$` (the `$` is +where the device cut its display), and then the `hostname` line. The tail is dropped as well +now: a first line of `$` and pieces of the command, the last of which ends the command, is +the echo, whether or not the start of the echo stands before it. Nothing else is dropped: a +line with text that is not in the command, a tail that does not end the command, and an +output line that begins with `$` stay. The page is `docs/devices/support-bundle.md`. + +## Rollback + +**`tacctl rollback 0.2.27`, the release before this one, is a target.** It converts nothing +but the file transfer settings of `console.yaml`. 0.2.27 and every older release reject the +key `settings.file_transfer` (their reader answers `settings: unknown key 'file_transfer'`), +so every `tacctl rollback` target removes it. With those settings set, `--apply` takes a +snapshot first, removes the key, keeps every other setting, needs no `--yes` and ends with a +note: until the older release is installed, run no `tacctl console file-transfer` that sets +something, and the snapshot holds the 0.2.28 state, which only 0.2.28 restores. The settings +are kept nowhere else: set them again after the upgrade. + +With the settings unset, `rollback 0.2.27` removes no key and no field, takes no snapshot +and needs no `--yes`. The limits of the stored reports, the chassis members of the pull +records, every report in the users' homes (the PDF ones included), the marker +`/var/lib/tacctl/pdf-tools-offered` with its packages, the per-tier sudoers drop-in and the +other settings 0.2.27 knows all stay. It is refused while a device's apply is not settled, +and it ends with `tacctl upgrade --branch 0.2.27`. `rollback 0.2.26` and older behave as +before, and `tacctl rollback` now takes fourteen targets. What this release changed outside +the stored files is 0.2.27's to undo or keep: after the rollback the support bundle of a +Cisco IOS device starts its identity lines with the tail of a long command's echo again. + +## Upgrading + +`tacctl upgrade` converts nothing in this release. File transfer is off for every tier but +the superuser tier after the upgrade, so nothing changes for a user until a superuser runs +`tacctl console file-transfer`; superusers have it at once, with no quota. Before switching +it on for others, check that sshd defines `Subsystem sftp ...` and that `/proc` is mounted +(`tacctl console show` checks the first). Existing reports, bundles and settings are read as +they were. diff --git a/docs/releasing.md b/docs/releasing.md index f8e1e9f4..d32eea82 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -85,9 +85,9 @@ the fork catches up. Also before step 1, on `develop`: - **The rollback target.** Every release ships `tacctl rollback ` (0.2.17 to 0.2.26 each did). Check that the release before this - one is a constant in `internal/lifecycle/rollback.go` (`RollbackTarget0226` - for 0.2.27) and is the one the refusal names "(the release before this + release>` (0.2.17 to 0.2.27 each did). Check that the release before this + one is a constant in `internal/lifecycle/rollback.go` (`RollbackTarget0227` + for 0.2.28) and is the one the refusal names "(the release before this one)" (`internal/lifecycle/rollback_test.go`), that the `rollback` entry of `man/tacctl.1` lists it the same way, that the CHANGELOG has its item, and that `const rollbackFrom` in `internal/cli/rollback.go` is this release (the diff --git a/docs/security/audit.md b/docs/security/audit.md index fd669865..3fdb9ee4 100644 --- a/docs/security/audit.md +++ b/docs/security/audit.md @@ -95,7 +95,7 @@ config loglevel from=info to=debug by=alice sid=k3x9a0bq | `group privilege` | `name` `op=add\|remove\|seed` `count` | | `group preset` | `name` `preset=roles` `changes`; one line per group changed | | `config sudoers`, `config sudoers tiers` | `op=install\|remove` `file`, and `group` for the first | -| `console set` | `key` `item` `from` `to`: `key` is the setting (`system-shell`, `forwarding`, `agent-forwarding`, `ssh-escape`, `password-cache`, `idle-timeout`, `space-completion`, `color`, `list-max`) and `item` the tier, the user (`user:` for a system-shell setting of one user) or part of it; `auth.notice` for `system-shell` | +| `console set` | `key` `item` `from` `to`: `key` is the setting (`system-shell`, `file-transfer`, `forwarding`, `agent-forwarding`, `ssh-escape`, `password-cache`, `idle-timeout`, `space-completion`, `color`, `list-max`) and `item` the tier, the user (`user:` for a system-shell setting of one user; `quota:`, `quota-user:`, `rate:` and `rate-user:` for the limits of file transfer) or part of it; `auth.notice` for `system-shell` and `file-transfer` | | `backup restore` | `id` `pre` (the snapshot taken first) `keep-uids` `legacy`; `auth.notice` | | `backup keep` | `id` `note=yes\|no` `already=yes\|no`; the note is never written | | `backup unkeep` | `id` `only-copy=yes\|no` | @@ -293,7 +293,9 @@ with `reason=superuser` (the verb is the superuser's) or `reason=scope` (the thi Nothing else is redacted: free text such as `breakglass hold --reason` is why a device was taken out of AAA, and it is logged as typed, as are the arguments of `ssh` after `--`. A secret typed in the place of a name (`user passwd `) is logged as the name; only the words after the verb's own arguments are redacted. Whatever is typed on a command line is also in sudo's own log, which records the whole line, and `ps` shows it while the command runs. The forms that keep a value off the command line are `scope secret set` (a hidden prompt, or `--stdin`), `user add|passwd --hash -` (the hash on standard input), and the `community` and `v3-user add` verbs (a prompt or `--stdin`). -The login console's refusal of a `-c` string (`scp`, a program, a shell) is not a `cmd` line but `console DENY ... reason=command first=` under the tag `tacctl-console`. `first=` is a verb of tacctl or one of the console's own words (`help`, `history`, `exit`, `quit`, `system-shell`); any other first word, a program or a password typed at the prompt, is not logged: the line reads `first=- len=`, `n` the length of the string. A line refused because a password change is required of the user reads `console DENY ... reason=password-change first=|-` by the same rule, and the opening of such a session writes `console password-change required|done|failed` (the [login console](login-console.md) has the session). +The login console's refusal of a `-c` string (`scp -O`, a program, a shell) is not a `cmd` line but `console DENY ... reason=command first=` under the tag `tacctl-console`. `first=` is a verb of tacctl or one of the console's own words (`help`, `history`, `exit`, `quit`, `system-shell`); any other first word, a program or a password typed at the prompt, is not logged: the line reads `first=- len=`, `n` the length of the string. A line refused because a password change is required of the user reads `console DENY ... reason=password-change first=|-` by the same rule, and the opening of such a session writes `console password-change required|done|failed` (the [login console](login-console.md) has the session). + +A file transfer through the login console (the sftp subsystem; see [File transfer](../cli/console.md#file-transfer--console-file-transfer)) writes lines of its own under the same tag, `tacctl-console`, with the session id and the user: `console start ... mode=sftp`, `console sftp start ... tier= from=
home="" quota=|unlimited rate=|off`, one line for each upload, download and change (`console sftp upload|download|delete|rename|mkdir|setstat ... tier= path=""`, with `to=""` for a rename, `bytes=` for an upload and a download and `error=""` for a request that failed), `console sftp DENY ... tier= path="" reason=.ssh|outside-the-home|symlink|link|quota|unsupported|bad-path|too-many-open-files` at `auth.warning` for a request the server refused, `console sftp end ... up= down= ops= refused=` and the session's `console end ... reason=sftp`. Every event line names the caller's `tier=`. The reasons: `link` is a file with more than one name (a hard link) that was asked to be opened, read, written or have its mode or times set; `too-many-open-files` is the 257th handle of a session (at most 256 files and listings open at once). Refusals of every kind are logged, including a refused `readlink` and `realpath`; the successful `stat`, listing, `readlink` and `realpath` are not. The subsystem refused is `console DENY ... reason=file-transfer|password-change|policy|home|stream subsystem=sftp`. If `logger` cannot write a line during a transfer, the warning `The audit line was not written (logger: ); the command continues.` can appear on standard error and the transfer goes on, unaudited; standard output stays the protocol's. The console never logs a typed word that is not a verb, because it could be a password; a path is a file name, so it is logged, but as a double-quoted string in which a control character (a newline, an escape sequence), a quote, a backslash, a byte that is not UTF-8 and a character that does not print are escapes, cut at 200 bytes of the escaped text (a cut name ends with `...` after the closing quote; the error text is cut the same way and does not repeat the path, so a line stays under 1000 bytes and `logger` keeps its trailing fields): no name can end a line or forge a field. The test suite runs every verb that takes a secret with a marker in each position it can be typed in and fails when the marker is in any `logger` argument. diff --git a/docs/security/login-console.md b/docs/security/login-console.md index 0f4e747f..2727f758 100644 --- a/docs/security/login-console.md +++ b/docs/security/login-console.md @@ -2,13 +2,14 @@ [Documentation](../README.md) › [Security](README.md) -**On the tacctl server itself, every tacctl user's login shell becomes the login console once the server's accounts are synced** (`tacctl install` and `tacctl upgrade` set up this machine's own login and sync them; the `user` verbs that change an account run that sync themselves; `tacctl host sync ` after any other change; `tacctl host enroll --local` to rebuild, move or repair it); nothing changes for anyone before that sync. A console user who logs in over ssh gets a `> ` prompt (`` is the host name, or the name `tacctl server name` set) that runs tacctl commands (as `sudo tacctl …`, so the [tiers](tiers.md) apply line by line) and `tacctl ssh` to the registered devices of their scopes, and nothing else: no system shell, no file transfer, no port forwarding (superusers excepted by default: `console forwarding tiers`). `ssh 'user list'` runs one tacctl line; `scp`, `sftp` and `rsync` are refused. +**On the tacctl server itself, every tacctl user's login shell becomes the login console once the server's accounts are synced** (`tacctl install` and `tacctl upgrade` set up this machine's own login and sync them; the `user` verbs that change an account run that sync themselves; `tacctl host sync ` after any other change; `tacctl host enroll --local` to rebuild, move or repair it); nothing changes for anyone before that sync. A console user who logs in over ssh gets a `> ` prompt (`` is the host name, or the name `tacctl server name` set) that runs tacctl commands (as `sudo tacctl …`, so the [tiers](tiers.md) apply line by line) and `tacctl ssh` to the registered devices of their scopes, and nothing else: no system shell, no file transfer unless it is switched on for the account (superusers always have it), no port forwarding (superusers excepted by default: `console forwarding tiers`). `ssh 'user list'` runs one tacctl line; `rsync`, `scp -O` and every program are refused, and `sftp` (and the `scp` of OpenSSH 9 or later) works only for an account that has file transfer (see File transfer settings below). - **Who gets it.** Every tacctl user of every tier, with no switch: the next `host sync` of the server sets the console as the login shell (`usermod -s`) and the sshd drop-in forces it; `tacctl console show` lists each user's effective shell and why. Every user can log in to the server unless disabled or of tier none (a group without a priv-lvl). The engineer tier has the console or no login on this server: an account whose console cannot be provisioned (the `tacctl-console` link is missing) gets `/bin/bash` only if it has the system shell (a superuser always; others when a superuser opened it to their tier or to them) and `/usr/sbin/nologin` otherwise, an engineer included, as does an account whose tier is none. sshd's drop-in `/etc/ssh/sshd_config.d/00-tacctl-engineer.conf` (its own file, written at every sync of this server even when the console is not installed, named to be read before the console's) closes every forwarding and tunnel for the engineers whatever shell they have (agent forwarding follows `console agent-forwarding`); `console check` verifies that file on its own and also looks at the engineers: each member of `tac-engineer` has the console or a nologin shell, sshd closes forwarding for them, and every member of `tac-superuser` that is a tacctl account is a superuser-tier user (root excepted; a removed user whose UID is in tacctl's range is named red; a local administrator outside the UID range is listed as not a tacctl account and the check stays green). Lowering a tier with a group command (`group edit … tier`, `group edit … priv-lvl`, `group remove`, `group preset roles --force`, `group reset`) syncs this server's accounts at once; when that fails the command says `Members of '' keep their old groups on this server until: tacctl host sync `. The `user` verbs that change an account (`user add`, `remove`, `rename`, `move`, `enable`, `disable`, `scope`, `require-password-change`) sync it after every change, and a sync that fails is one warning with `tacctl host sync ` (exit 0). An engineer keeps this lockdown (no system shell, no forwarding) even when `tacctl.yaml` cannot be read and the gate treats them as an operator. - **A required password change.** A user who must change the password (`tacctl user require-password-change`, which `user add` and an administrator's `user passwd` do by default; never a superuser) gets, when the console starts, the notice `A password change is required of your account.` and the password change dialog straight away: no device accepts the login until the password is changed, nor any enrolled Linux host but this server (its next `host sync` expires the account there, SSH keys included), and nothing else runs in the console. Every other line, `help` and the other words of the console included, is refused (`A password change is required: nothing runs here until it is made but 'passwd' (and 'exit').`, status 1), Tab and `?` list the change only, and Up and Ctrl-R recall no earlier line. Once the password is changed the session goes on as any other. A console that cannot read the answer (sudo refuses, the store cannot be read) cannot tell whether a change is required and holds a user who is no superuser the same way, without the dialog; a superuser, known by the system group `tac-superuser`, is never held by a read error. Ctrl-C in the dialog ends the session; a wrong current password or a rejected new one leaves the locked prompt, where `passwd` tries again and `exit` leaves. `ssh 'user list'` and a batch are refused the same way, and a plain shell or `ssh tacctl ...` meets the same refusal in the command line (only `passwd`, `version` and `help` run). The lock holds the console, and sshd's drop-in holds the forwarding: a forwarding (`ssh -N -L`, `-R`, `-D`, `-J`) opens no session, so it never reaches the console, which is why the drop-in lists the users who must change the password in a block of its own before the tier blocks (`Match User ` with `DisableForwarding yes`, see below). Whatever their tier, even one of `console forwarding tiers`, a new connection of theirs forwards no port, X11 display or agent through the server until the password is changed. sshd applies the drop-in when a connection authenticates, so a connection the user already has open keeps the forwardings it had until it closes; tacctl does not end it (the administrator can: `loginctl terminate-user `). The list is rewritten by every sync of this server (the `user` verbs that change an account run it; so does `tacctl host sync `), by `console install` and `upgrade`, and by the verbs that change who is held, each at once and by itself, so that it is current whether or not a sync of this server follows and gets as far as the drop-in (a server that is not enrolled, a sync that stops at its checks, a scope in which no user gets the console): `user require-password-change` in every form, `user add`, `user remove`, `user rename`, `user move`, an administrator's `user passwd`, the user's own `passwd`, a group command that lowers a tier, `store import`, `backup restore` (a snapshot or an old-style backup) and `store rollback` (legacy mode holds nobody). The list is read and installed under the apply lock, so that two commands cannot leave a user out. Any other write of the store or of `tacctl.yaml` leaves the drop-in as it is until the next of those. With nobody held there is no block, and a superuser is never listed. Only a change that lowers a group's tier syncs this server (and so lists a flagged user whose group stops being a superuser's); raising a tier leaves the list as it was until the next rewrite, which can only close forwarding: a user who has become a superuser stays listed, and his new connections stay closed, until then. `console check` reports the drop-in as differing, with the two lists, when it is not the users held now; `tacctl console install` writes it again. The user must be able to get here: a user with no login on this server is never required to change the password (see [User Commands](../cli/user.md)). The sessions and refusals are in the log (`console password-change`, `console DENY ... reason=password-change`). - **Break-glass.** Local accounts that are not tacctl users (root, the administrators who installed the server) are never touched, so they keep their shells and their local passwords; a tacctl user has no plain shell on the server. -- **sshd's drop-in is the key line.** `Match Group tac-console` in `/etc/ssh/sshd_config.d/tacctl-console.conf` sets `ForceCommand /usr/local/bin/tacctl-console` (every login, remote command and subsystem, the sftp server included, reaches the console, which takes the client's command from `SSH_ORIGINAL_COMMAND` and lets only one tacctl line through), `DisableForwarding yes` with `AllowTcpForwarding no`, `AllowStreamLocalForwarding no`, `X11Forwarding no`, `AllowAgentForwarding no` and `PermitTunnel no` (agent forwarding only with `console agent-forwarding enable`). For each tier of `console forwarding tiers` (default: superuser) a block before it, `Match Group tac-console Group tac-`, sets `DisableForwarding no`, `AllowTcpForwarding yes` and `X11Forwarding yes`: sshd takes the first value it finds, so those users can `ssh -X`, `-L`, `-R`, `-D` and `-J` through the server (still into the console, still by password) while everyone else stays closed. Before those, when anyone must change the password (see above), comes `Match User ` (the names sorted, only those of a Linux account, at most 50 to a block: more users make further `Match User` blocks, all before the tier blocks), which sets `DisableForwarding yes` with the `Allow...` and `X11Forwarding` switches at `no`, `PermitTunnel no` and `GatewayPorts no`: the first value wins here too, so a new connection of a user held to a password change forwards nothing in any tier, and the block is not written when nobody is held. Forwarded ports on the server listen on loopback only (`GatewayPorts no` in the console's block) unless `console forwarding gateway-ports enable` adds `GatewayPorts clientspecified` to the tier blocks: an `ssh -R 0.0.0.0:8080:host:80` to the server then listens on every address, and the console's `tacctl ssh` takes `-g` and a bind address on `-L` and `-D`; anyone who reaches the server can connect to those ports. Then `PubkeyAuthentication no` (a key login would bypass TACACS+), and `ClientAliveInterval 300` / `ClientAliveCountMax 2`. Every change is checked with `sshd -t` and undone when sshd refuses it; sshd is reloaded otherwise. `/etc/ssh/sshd_config` must include `sshd_config.d/*.conf` (Debian, Ubuntu and RHEL 9 do). `tacctl console check` (operator and up) asks `sshd -T` what it applies to a console user and warns in red when anything is off; `console show` does the same. +- **sshd's drop-in is the key line.** `Match Group tac-console` in `/etc/ssh/sshd_config.d/tacctl-console.conf` sets `ForceCommand /usr/local/bin/tacctl-console` (every login, remote command and subsystem, the sftp server included, reaches the console, which takes the client's command from `SSH_ORIGINAL_COMMAND` and lets only one tacctl line through, or the sftp subsystem for an account that has file transfer), `DisableForwarding yes` with `AllowTcpForwarding no`, `AllowStreamLocalForwarding no`, `X11Forwarding no`, `AllowAgentForwarding no` and `PermitTunnel no` (agent forwarding only with `console agent-forwarding enable`). For each tier of `console forwarding tiers` (default: superuser) a block before it, `Match Group tac-console Group tac-`, sets `DisableForwarding no`, `AllowTcpForwarding yes` and `X11Forwarding yes`: sshd takes the first value it finds, so those users can `ssh -X`, `-L`, `-R`, `-D` and `-J` through the server (still into the console, still by password) while everyone else stays closed. Before those, when anyone must change the password (see above), comes `Match User ` (the names sorted, only those of a Linux account, at most 50 to a block: more users make further `Match User` blocks, all before the tier blocks), which sets `DisableForwarding yes` with the `Allow...` and `X11Forwarding` switches at `no`, `PermitTunnel no` and `GatewayPorts no`: the first value wins here too, so a new connection of a user held to a password change forwards nothing in any tier, and the block is not written when nobody is held. Forwarded ports on the server listen on loopback only (`GatewayPorts no` in the console's block) unless `console forwarding gateway-ports enable` adds `GatewayPorts clientspecified` to the tier blocks: an `ssh -R 0.0.0.0:8080:host:80` to the server then listens on every address, and the console's `tacctl ssh` takes `-g` and a bind address on `-L` and `-D`; anyone who reaches the server can connect to those ports. Then `PubkeyAuthentication no` (a key login would bypass TACACS+), and `ClientAliveInterval 300` / `ClientAliveCountMax 2`. Every change is checked with `sshd -t` and undone when sshd refuses it; sshd is reloaded otherwise. `/etc/ssh/sshd_config` must include `sshd_config.d/*.conf` (Debian, Ubuntu and RHEL 9 do). `tacctl console check` (operator and up) asks `sshd -T` what it applies to a console user and warns in red when anything is off; `console show` does the same. - **`system-shell`.** The console word `system-shell` starts the user's own system shell, logged. Superusers always have it; readonly and operator users do not until a superuser opens it for the tier (`tacctl console system-shell operator enable`) or for one user (`tacctl console system-shell user enable`; a user's setting wins over the tier's, in both directions; an enable lasts only while the user stays in the tier they had when it was set, so a demotion does not leave a shell behind); engineers never have it. Only a superuser sets it; the operator tier and up read it (`tacctl console system-shell`, `... `, `... user `, `... path`) and `console show` shows each user's access and why. +- **File transfer settings.** Whether a tier or a user may transfer files to and from their home through the console is a setting like `system-shell`: off for every tier but the superuser tier, which always has it; `tacctl console file-transfer enable|disable` or `... user enable|disable|clear` (a user's setting wins over the tier's; an enable lasts only while the user stays in the tier it was set for); the engineer tier is not closed to it, because a transfer reaches the home only. A quota (the bytes the whole home may hold, 256M by default, none for superusers) and a rate (bytes a second, off by default) can be set per tier and per user. Only a superuser reads or sets `console file-transfer`; each user's state, quota and rate are in `console show`, which the operator tier and up can run. The console serves SFTP only, to the accounts that have it, as the user, rooted in the home the account database names, with `.ssh` out of reach and no symbolic link followed, and a file with more than one name neither opened nor changed (the size of a file can be set, within the quota, which `scp` does after an upload; the owner cannot be changed); an account without file transfer sees only `Connection closed` from `sftp` and `scp`, and the reason (`reason=file-transfer`) is in the audit log; `scp -O`, `rsync` and every program stay refused. Uploads, downloads and changes are audited with the caller's tier, and a refused request of any kind is too (`console sftp ...`, with the file names escaped and cut); a successful `stat`, listing, `readlink` or `realpath` is not. The quota counts the regular files of the home, and a directory the session cannot read makes the home count as full (see File transfer). sshd must define `Subsystem sftp ...` itself, which `console show` and `console file-transfer` check. See [Console commands](../cli/console.md#file-transfer--console-file-transfer). - **Password cache.** `console password-cache tiers` says which tiers may keep a user's network password in the session's memory; for an allowed tier it is off until the user types `password-cache on` (`console password-cache on`) at the prompt, which saves the choice for later sessions and starts it in that one (`ssh` and `device ssh` then ask for the password themselves the first time, before they connect, and keep it). A user sets only their own choice; a superuser sees and clears the others' with `console password-cache user`. See [the shell](../cli/shell.md#password-cache). - **Pasted lines.** A line that starts with `tacctl`, `sudo tacctl` or `/usr/local/bin/tacctl` runs as the line without it (the console takes only the rest); see [the shell](../cli/shell.md). - **Logged.** Sessions, refused commands and system shells go to syslog (tag `tacctl-console`), every line to sudo's log, and every `tacctl ssh` session with `console=`. A refused `-c` string logs its first word (`first=`) only when it is a verb of tacctl or a console word; any other word, which can be a password typed at the prompt, reads `first=- len=`. diff --git a/go.mod b/go.mod index afff7144..850227c4 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ go 1.27.0 ignore ./tests/fixtures require ( + github.com/pkg/sftp v1.13.12 github.com/spf13/cobra v1.10.2 golang.org/x/crypto v0.57.0 golang.org/x/sys v0.48.0 @@ -16,5 +17,6 @@ require ( require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/kr/fs v0.1.0 // indirect github.com/spf13/pflag v1.0.10 // indirect ) diff --git a/go.sum b/go.sum index 2eb7128a..9d9fa386 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,22 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/pkg/sftp v1.13.12 h1:Myhzy/ZzLPnCtE2F2WtDHsgs8RfgMnH2gfbHuCJhkMU= +github.com/pkg/sftp v1.13.12/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= diff --git a/internal/cli/args.go b/internal/cli/args.go index 7eda36f1..947d6d0a 100644 --- a/internal/cli/args.go +++ b/internal/cli/args.go @@ -95,13 +95,19 @@ func After(word, kind string) string { return "@" + word + ":" + kind } // where the other verbs name a block). func Cond(word, a, b string) string { return "?" + word + ":" + a + ":" + b } +// Both is the kind of a positional that completion takes from kind a when +// both words are among the positionals typed before it, and from kind b +// when they are not ('console file-transfer quota user ' names a user +// where 'quota ' names a value). +func Both(w1, w2, a, b string) string { return "&" + w1 + ":" + w2 + ":" + a + ":" + b } + // Either is the kind of a positional that completion takes from each of // kinds, in order ('notice list|' offers the word and the names). func Either(kinds ...string) string { return strings.Join(kinds, "+") } // resolveKind is the kind a positional has, given the positional words typed -// before it: After and Cond are decided by them, and may nest in their last -// place ('console system-shell': a file after path, a user after user, else +// before it: After, Cond and Both are decided by them, and may nest in their +// last place ('console system-shell': a file after path, a user after user, else // enable|disable). func resolveKind(kind string, words []string) string { for { @@ -113,6 +119,17 @@ func resolveKind(kind string, words []string) string { } continue } + if rest, ok := strings.CutPrefix(kind, "&"); ok { + parts := strings.SplitN(rest, ":", 4) + kind = "" + if len(parts) == 4 { + kind = parts[3] + if slices.Contains(words, parts[0]) && slices.Contains(words, parts[1]) { + kind = parts[2] + } + } + continue + } if rest, ok := strings.CutPrefix(kind, "?"); ok { parts := strings.SplitN(rest, ":", 3) kind = "" diff --git a/internal/cli/audit.go b/internal/cli/audit.go index a9880ba4..abb0fcb5 100644 --- a/internal/cli/audit.go +++ b/internal/cli/audit.go @@ -456,6 +456,7 @@ var auditTable = map[string]auditEntry{ "console list-max": mixed(), "console ssh-escape": mixed(), "console system-shell": mixed().weighty(), + "console file-transfer": mixed().weighty(), "log tail": read(), "log search": read(), diff --git a/internal/cli/completion_test.go b/internal/cli/completion_test.go index 24f3a26a..661eb3ad 100644 --- a/internal/cli/completion_test.go +++ b/internal/cli/completion_test.go @@ -546,7 +546,7 @@ func TestCompleteThisReleasesWords(t *testing.T) { {[]string{"scope", "secret", "lab", "set", "--"}, []string{"--stdin"}, false}, {[]string{"user", "add", "x", "--"}, []string{"--hash"}, false}, {[]string{"user", "passwd", "x", "--"}, []string{"--hash"}, false}, - {[]string{"rollback", ""}, []string{"0.2.26", "0.2.25", "0.2.24", "0.2.23", "0.2.22", "0.2.21", "0.2.20", "0.2.19", "0.2.18", "0.2.17", "0.2.16", "0.2.9", "0.2.3"}, true}, + {[]string{"rollback", ""}, []string{"0.2.27", "0.2.26", "0.2.25", "0.2.24", "0.2.23", "0.2.22", "0.2.21", "0.2.20", "0.2.19", "0.2.18", "0.2.17", "0.2.16", "0.2.9", "0.2.3"}, true}, } for _, c := range cases { got, _ := completeWords(t, liveNames, c.words...) diff --git a/internal/cli/console.go b/internal/cli/console.go index 1ff5fc5c..c858b470 100644 --- a/internal/cli/console.go +++ b/internal/cli/console.go @@ -41,6 +41,11 @@ var consoleSpecs = map[string]Spec{ "list-max": {MaxArgs: 1, Args: []string{""}}, "system-shell": {MaxArgs: 3, Args: []string{"readonly|operator|engineer|superuser|user|path", Cond("path", KindFile, Cond("user", KindUsers, "enable|disable")), After("user", "enable|disable|clear")}}, + "file-transfer": {MaxArgs: 4, Args: []string{"readonly|operator|engineer|superuser|user|quota|rate", + Cond("user", KindUsers, Cond("quota", fileTransferTiers, Cond("rate", fileTransferTiers, "enable|disable"))), + Both("quota", "user", KindUsers, Both("rate", "user", KindUsers, + Cond("quota", "unlimited|default", Cond("rate", "off", After("user", "enable|disable|clear"))))), + Both("quota", "user", "unlimited|clear", Both("rate", "user", "off|clear", ""))}}, "forwarding": {MinArgs: 1, MaxArgs: 2, Args: []string{"tiers|gateway-ports", After("gateway-ports", "enable|disable")}}, "password-cache": {MaxArgs: 3, Args: []string{"tiers|idle|max|on|off|user", Cond("user", KindUsers, ""), After("user", "clear")}}, "forget": {MaxArgs: 0}, @@ -49,6 +54,9 @@ var consoleSpecs = map[string]Spec{ "check": {MaxArgs: 0}, } +// fileTransferTiers are the words after 'file-transfer quota' and 'rate'. +const fileTransferTiers = "readonly|operator|engineer|superuser|user" + // consoleVerbs are the verbs ({Use, Short}), in usage order. var consoleVerbs = [][2]string{ {"show", "The shell of each user, the system shell by tier, settings and the server's pieces"}, @@ -63,6 +71,12 @@ var consoleVerbs = [][2]string{ {"system-shell [ enable|disable]", "Show or set the system shell for a tier (superuser always has it, engineer never; default superuser only)"}, {"system-shell user [enable|disable|clear]", "Show or set the system shell for one user, over the tier's setting (clear: the tier decides)"}, {"system-shell path []", "Show or set the system shell (default /bin/bash; must be listed in /etc/shells)"}, + {"file-transfer [ enable|disable]", "Show or set file transfer through the console for a tier (default off)"}, + {"file-transfer user [enable|disable|clear]", "Show or set file transfer for one user, over the tier's setting (clear: the tier decides)"}, + {"file-transfer quota [ |unlimited|default]", "Show or set the bytes a home may hold (default 256M; unlimited for superusers)"}, + {"file-transfer quota user [|unlimited|clear]", "Show or set the quota of one user, over the tier's (clear: the tier decides)"}, + {"file-transfer rate [ |off]", "Show or set the bytes a second a transfer may go at (default off)"}, + {"file-transfer rate user [|off|clear]", "Show or set the rate of one user, over the tier's (clear: the tier decides)"}, {"password-cache [on|off]", "Show or set whether your sessions keep your password in memory"}, {"password-cache user []", "Show the users who turned the password cache on"}, {"password-cache user clear", "Clear the password cache setting of a user (back to off)"}, @@ -107,9 +121,10 @@ never touched. The settings commands change /etc/tacctl/console.yaml only. The accounts' login shells and sshd's drop-in follow it when this server's accounts are synced ('tacctl host sync '); idle-timeout, ssh-escape, -space-completion, color, list-max and system-shell are read by each console -session when it starts. sshd's drop-in makes the console the only program a console user's login -runs (no scp, sftp or remote programs), closes every forwarding but X11 and TCP +space-completion, color, list-max, system-shell and file-transfer are read by each +console session when it starts. sshd's drop-in makes the console the only program a console user's login +runs (no remote programs, and SFTP only for the accounts that have file +transfer), closes every forwarding but X11 and TCP ports for the tiers of 'forwarding tiers' (superusers by default: 'ssh -X', -L, -R, -D and -J through this server, and 'ssh -X|-L|-R|-D ' in the console), and turns key logins off. @@ -124,6 +139,23 @@ from the console ('scope block ... edit|adopt', 'device block ... edit|adopt': a editor can start a shell). Neither it nor forwarding is ever open to the engineer tier: a shell or a forwarded port on this server would reach its secrets. +'file-transfer' sets who may transfer files to and from their home through the +console. It is off for every tier but the superuser tier, which always has it, +until a superuser opens it ('file-transfer enable|disable') or gives it to +one user ('file-transfer user enable|disable|clear'; a user's setting wins +over the tier's, and clear returns the user to the tier's). Unlike the system +shell it can be opened to the engineer tier: a transfer reaches the home only. +'file-transfer quota' is the bytes the whole home may hold (256M for every tier +but the superuser tier, which has no limit; a size such as 512K, 256M or 2G, at +most 1T, or unlimited; 'default' returns a tier to the built-in value) and +'file-transfer rate' the bytes a second a transfer may go at (a size, or off, the +default); each can be set for a tier or for one user, whose own value wins +('quota user |unlimited|clear'). Only a superuser can read or set +them ('file-transfer', 'quota' and 'rate', alone or with words); every user's +own state, quota and rate are in 'show', which the operator tier and up can +run. The settings apply to the file transfer of the console, not to anything +else. + 'password-cache' lets a tier's shell and console sessions keep the user's network password in memory for the session, so a device pull or an ssh to a device asks once (off for every tier by default; plain 'tacctl shell' takes --password-cache). @@ -141,6 +173,8 @@ Examples: tacctl console show tacctl console system-shell operator enable tacctl console system-shell user jdoe enable + tacctl console file-transfer operator enable + tacctl console file-transfer quota operator 1G tacctl console idle-timeout 15 `) @@ -157,6 +191,7 @@ func (inv *invocation) console(args []string) error { run := map[string]func([]string) error{ "show": inv.consoleShow, "idle-timeout": inv.consoleIdle, "system-shell": inv.consoleSystemShell, "forwarding": inv.consoleForwarding, + "file-transfer": inv.consoleFileTransfer, "agent-forwarding": inv.consoleSwitch("agent-forwarding"), "ssh-escape": inv.consoleSwitch("ssh-escape"), "space-completion": inv.consoleSpace, "color": inv.consoleColor, "list-max": inv.consoleListMax, "password-cache": inv.consolePasswordCache, "forget": inv.consoleForget, @@ -1103,10 +1138,13 @@ func (inv *invocation) consolePolicyLine([]string) error { if n := a.Conf().ServerName(); n != "" { serverName = " name=" + n } + // File transfer (0.2.28): what the settings give the caller, for the + // console's transfers; off unless the line says it is on. + transfer := console.FileTransferFields(pol.FileTransfer(inv.callerStoreUser(), t)) inv.echo("shell=" + shell + " idle=" + strconv.Itoa(pol.File.Idle) + " system_shell=" + yesNo(sys) + " system_shell_path=" + path + " ssh_escape=" + yesNo(pol.SSHEscape()) + " agent=" + yesNo(pol.AgentForwarding()) + " forward=" + yesNo(pol.Forwarding(t)) + " tier=" + string(t) + gateField + " list_max=" + strconv.Itoa(pol.ListMax()) + - " space_completion=" + yesNo(pol.SpaceCompletion()) + " color=" + pol.Color() + cache + change + serverName) + " space_completion=" + yesNo(pol.SpaceCompletion()) + " color=" + pol.Color() + cache + change + serverName + transfer) return nil } @@ -1129,6 +1167,7 @@ func (inv *invocation) userSettingsMoved(m console.UserSettingsMove, oldname, ne // of the user is not known. out.Error("console.yaml could not be read or written (" + cutErr(m.Err) + "), so the console settings of '" + oldname + "' were not " + verb + ". The user is changed already. After repairing the file, check them: tacctl console system-shell user " + oldname + + ", tacctl console file-transfer user " + oldname + ", tacctl console file-transfer quota user " + oldname + ", tacctl console file-transfer rate user " + oldname + ", and tacctl console password-cache user " + oldname + " (each followed by clear to drop it)" + map[bool]string{true: "; a renamed user's settings are set again under '" + newname + "' by a superuser, and the user turns the password cache on again themselves", false: ""}[newname != ""] + ".") return exit(1) @@ -1144,6 +1183,9 @@ func (inv *invocation) userSettingsMoved(m console.UserSettingsMove, oldname, ne fix = append(fix, "tacctl console system-shell user "+newname+" "+onOff(m.ShellOn)) } } + if m.FileHad { + fix = append(fix, "tacctl console file-transfer user "+oldname+" clear (and the same with quota user and rate user; it was "+m.FileWhat+")") + } if m.CacheHad { fix = append(fix, "tacctl console password-cache user "+oldname+" clear") } @@ -1163,6 +1205,9 @@ func (inv *invocation) userSettingsMoved(m console.UserSettingsMove, oldname, ne if m.ShellHad { report("system-shell", "system-shell", onOff(m.ShellOn)) } + if m.FileHad { + report("file-transfer", "file-transfer", m.FileWhat) + } if m.CacheHad { report("password-cache", "password-cache", "on") } @@ -1182,7 +1227,7 @@ func cutErr(err error) string { // consoleSettingsReadable is checked by 'user add', 'user remove' and 'user // rename' before they change the store: console.yaml holds settings of users -// (the system shell, the password cache) that follow the user or are dropped +// (the system shell, file transfer, the password cache) that follow the user or are dropped // with them, and they cannot be dropped or moved from a file that cannot be // read. The store change is made only after the file is known to be readable // (an absent file is fine): the other order, the store first, leaves the user @@ -1192,7 +1237,7 @@ func cutErr(err error) string { func (inv *invocation) consoleSettingsReadable() error { if _, err := console.Load(inv.app.Paths.ConsoleFile); err != nil { return inv.usageErr("console.yaml could not be read: "+cutErr(err)+".", - "It holds settings of users (the system shell, the password cache) that this command drops or moves with the user, so that the next user of the name does not inherit them; nothing was changed. Repair the file, then run the command again.") + "It holds settings of users (the system shell, file transfer, the password cache) that this command drops or moves with the user, so that the next user of the name does not inherit them; nothing was changed. Repair the file, then run the command again.") } return nil } diff --git a/internal/cli/console_filetransfer.go b/internal/cli/console_filetransfer.go new file mode 100644 index 00000000..46a56904 --- /dev/null +++ b/internal/cli/console_filetransfer.go @@ -0,0 +1,480 @@ +package cli + +// 'console file-transfer': who may transfer files through the console, how +// much their home may hold (the quota) and how fast a transfer may go (the +// rate), per tier and per user. The settings are the system shell's in shape +// (console/filetransfer.go): the user's own setting wins over the tier's, an +// enable ends when the user moves to another tier, the superuser tier always +// has it, and the engineer tier is not closed to it. Unlike the system +// shell's, the verb has no row in the tier table (internal/tier), so the gate +// holds every form of it, the reads included, to the superuser tier (adding a +// row would change the sudoers text that the 0.2.27 rollback target freezes). +// What every user has is in 'console show', which the operator tier and up +// run. fileTransferWrites is the verb's own second check of the forms that +// set something. + +import ( + "slices" + "strings" + + "github.com/rett/tacctl/internal/console" + "github.com/rett/tacctl/internal/tier" + "github.com/rett/tacctl/internal/ui" +) + +// fileTransferState is the state of a tier's file transfer as the listings +// word it. +func fileTransferState(pol *console.Policy, t tier.Tier) string { + if t == tier.Superuser { + return "enabled (always)" + } + return map[bool]string{true: "enabled", false: "disabled"}[pol.FileTransferTier(t)] +} + +// fileTransferUserLine is one user with a switch of their own, for the +// listing: the setting and the user's tier (or why it counts for nothing). +func (inv *invocation) fileTransferUserLine(pol *console.Policy, tiers map[string]tier.Tier, name string) string { + word := map[bool]string{true: "enabled", false: "disabled"}[pol.File.FileTransferUsers[name]] + t, ok := tiers[name] + if was, stale := pol.FileTransferStale(name, t); ok && stale { + return name + ": " + word + " (stale: set for " + string(was) + ", now " + string(t) + ")" + } + switch { + case !ok: + return name + ": " + word + " (no such user)" + case t == tier.Superuser: + return name + ": " + word + " (superuser; the setting is ignored)" + } + return name + ": " + word + " (" + string(t) + ")" +} + +// fileTransferOpened reports whether file transfer is on for anyone but the +// superuser tier, which always has it: a tier that was opened to it, or a +// user who was given it and still is in the tier it was set for. The notice +// about sshd's subsystem warns for these; a server nobody opened it on has +// only the line. +func (inv *invocation) fileTransferOpened(pol *console.Policy) bool { + for _, t := range []tier.Tier{tier.Readonly, tier.Operator, tier.Engineer} { + if pol.FileTransferTier(t) { + return true + } + } + var tiers map[string]tier.Tier + for _, n := range pol.File.FileTransferUserNames() { + if !pol.File.FileTransferUsers[n] { + continue + } + if tiers == nil { + var err error + if tiers, err = inv.systemShellTiers(); err != nil { + // the tiers cannot be read: warn rather than stay quiet + return true + } + } + if t, ok := tiers[n]; ok { + if _, stale := pol.FileTransferStale(n, t); !stale && pol.FileTransferFor(n, t) { + return true + } + } + } + return false +} + +// sftpSubsystemNotice prints whether sshd defines an sftp subsystem (cmd, the +// result of console.SFTPSubsystem or SSHD.SFTP; err: the check could not be +// made) and, when file transfer is on for someone and it does not, the +// warning that the console cannot serve anyone: sshd never starts the +// subsystem, and a Match block cannot define it, so the line must be in +// sshd_config itself (tacctl adds nothing global). +func (inv *invocation) sftpSubsystemNotice(pol *console.Policy, cmd string, err error) { + switch { + case err != nil: + inv.echo("sshd sftp subsystem: could not be checked: " + strings.Join(msgs(err), " ")) + return + case cmd == "": + inv.echo("sshd sftp subsystem: none") + default: + inv.echo("sshd sftp subsystem: " + cmd) + } + if cmd == "" && inv.fileTransferOpened(pol) { + inv.echoE(ui.Red + sftpSubsystemWarning + ui.NC) + } +} + +// sftpSubsystemWarning is the warning for a server whose sshd starts no sftp +// subsystem while file transfer is on. +const sftpSubsystemWarning = "WARNING: sshd defines no sftp subsystem: file transfer cannot start; add `Subsystem sftp ...` to sshd_config." + +// fileTransferWrites reports whether the arguments of 'console +// file-transfer' set something. The reads are no argument, a tier alone, +// 'user ', 'quota' and 'rate' alone, 'quota|rate ' and +// 'quota|rate user '. +func fileTransferWrites(args []string) bool { + switch { + case len(args) == 0: + return false + case args[0] == "quota" || args[0] == "rate": + if len(args) >= 2 && args[1] == "user" { + return len(args) >= 4 + } + return len(args) >= 3 + case args[0] == "user": + return len(args) >= 3 + } + return len(args) >= 2 +} + +// sizeErr turns the refusal of a size into the line and the usage, exit 1. +func (inv *invocation) sizeErr(err error, usage string) error { + return inv.usageErr(strings.Join(msgs(err), " "), usage) +} + +// consoleFileTransfer is 'console file-transfer': with no argument the state +// of each tier and the users with a switch of their own; ' enable| +// disable' and 'user enable|disable|clear' set it; 'quota' and 'rate' +// show or set the limits of the tiers and the users. +func (inv *invocation) consoleFileTransfer(args []string) error { + p, err := inv.consoleParse("file-transfer", args) + if err != nil { + return err + } + usage := "Usage: tacctl console " + consoleUse("file-transfer") + if fileTransferWrites(p.Args) { + if err := inv.deviceVerbAllowed("console", "file-transfer", tier.Superuser); err != nil { + return err + } + } + pol, err := inv.consolePolicy() + if err != nil { + return err + } + if len(p.Args) == 0 { + for _, t := range console.Tiers { + inv.echo(string(t) + ": " + fileTransferState(pol, t)) + } + if names := pol.File.FileTransferUserNames(); len(names) > 0 { + tiers, err := inv.systemShellTiers() + if err != nil { + return err + } + inv.echo("") + inv.echo("Users with a setting of their own:") + for _, n := range names { + inv.echo(" " + inv.fileTransferUserLine(pol, tiers, n)) + } + } + inv.echo("") + cmd, err := console.SFTPSubsystem(inv.ctx, inv.app.Runner) + inv.sftpSubsystemNotice(pol, cmd, err) + return nil + } + switch p.Args[0] { + case "user": + return inv.consoleFileTransferUser(pol, p.Args[1:], usage) + case "quota", "rate": + return inv.consoleFileTransferLimit(pol, p.Args[0], p.Args[1:], usage) + } + t, ok := console.ParseTier(p.Args[0]) + if !ok { + return inv.usageErr("Unknown tier '"+p.Args[0]+"': expected readonly, operator, engineer or superuser.", usage) + } + if len(p.Args) == 1 { + inv.echo(fileTransferState(pol, t)) + return nil + } + if len(p.Args) > 2 { + return inv.usageErr("Unknown argument: '"+p.Args[2]+"'", usage) + } + on, err := inv.enableWord(p.Args[1], "file-transfer") + if err != nil { + return err + } + if t == tier.Superuser && on { + inv.app.Out.Info("The superuser tier always has file transfer. Nothing was changed.") + return nil + } + state := func(f *console.File) string { + return onOff((&console.Policy{File: f}).FileTransferTier(t)) + } + if err := inv.consoleWrite("file-transfer", string(t), state, func(f *console.File) error { return f.SetFileTransfer(t, on) }); err != nil { + return err + } + inv.app.Out.Info("File transfer is " + p.Args[1] + "d for the " + string(t) + " tier. It applies from the next console login.") + return nil +} + +// consoleFileTransferUser is 'console file-transfer user [enable| +// disable|clear]': args are the words after 'user'. +func (inv *invocation) consoleFileTransferUser(pol *console.Policy, args []string, usage string) error { + if len(args) == 0 { + return inv.usageErr("expected at least 1 argument(s), got 0", usage) + } + if len(args) > 2 { + return inv.usageErr("Unknown argument: '"+args[2]+"'", usage) + } + name := args[0] + exists, t, err := inv.fileTransferUser(name) + if err != nil { + return err + } + own, has := pol.File.FileTransferUsers[name] + userState := func(f *console.File) string { + on, ok := f.FileTransferUsers[name] + if !ok { + return "none" + } + return onOff(on) + } + if len(args) == 1 { + switch { + case !exists && !has: + return inv.usageErr("User '" + name + "' does not exist.") + case !exists: + inv.echo(onOff(own) + "d (user setting; no such user)") + default: + on, why := pol.FileTransferWhy(name, t) + inv.echo(map[bool]string{true: "enabled", false: "disabled"}[on] + " (" + why + ")") + } + return nil + } + if args[1] == "clear" { + if !has { + inv.app.Out.Info("'" + name + "' has no file transfer setting of their own.") + return nil + } + if err := inv.consoleWrite("file-transfer", "user:"+name, userState, + func(f *console.File) error { f.DropFileTransferUser(name); return nil }); err != nil { + return err + } + inv.app.Out.Info("The file transfer setting of '" + name + "' is cleared: the tier decides. It applies from the next console login.") + return nil + } + on, err := inv.enableWord(args[1], "file-transfer") + if err != nil { + return err + } + if !exists { + return inv.usageErr("User '" + name + "' does not exist.") + } + switch { + case t == tier.Superuser && !on: + return inv.usageErr("'" + name + "' is a superuser, and superusers always have file transfer; it cannot be disabled. Nothing was changed.") + case t == tier.Superuser: + // Already so: nothing to store, which a later change of the user's + // tier would revive. + inv.app.Out.Info("'" + name + "' is a superuser, who always has file transfer. Nothing was changed.") + return nil + case !slices.Contains([]tier.Tier{tier.Readonly, tier.Operator, tier.Engineer}, t): + return inv.usageErr("'" + name + "' has no tier (the account is disabled?), so file transfer cannot be switched for them. Nothing was changed.") + } + if err := inv.consoleWrite("file-transfer", "user:"+name, userState, + func(f *console.File) error { f.SetFileTransferUser(name, on, t); return nil }); err != nil { + return err + } + inv.app.Out.Info("File transfer is " + args[1] + "d for '" + name + "'" + map[bool]string{true: " while they are in the " + string(t) + " tier (a move to another tier ends it until it is set again)", false: ""}[on] + + ". It applies from the next console login.") + return nil +} + +// fileTransferUser is whether the user exists and the tier they have. +func (inv *invocation) fileTransferUser(name string) (exists bool, t tier.Tier, err error) { + m, err := inv.model() + if err != nil { + return false, "", err + } + if !m.Exists("users", name) { + return false, "", nil + } + return true, inv.userTier(name, m.UserPrivLvl(name)), nil +} + +// fileTransferLimit is what 'quota' and 'rate' differ in. +type fileTransferLimit struct { + key, noun string + // none is the word of no limit (unlimited, off), tierDefault whether a + // tier can be returned to a built-in default by the word 'default'. + none string + tierDefault bool + parse func(string) (int64, error) + word func(int64) string + value func(*console.Policy, string, tier.Tier) (int64, string) + tierSet func(*console.File) map[tier.Tier]int64 + userSet func(*console.File) map[string]int64 +} + +var fileTransferLimits = map[string]fileTransferLimit{ + "quota": {key: "quota", noun: "quota", none: console.Unlimited, tierDefault: true, parse: console.ParseQuota, word: console.QuotaWord, + value: func(p *console.Policy, u string, t tier.Tier) (int64, string) { return p.FileTransferQuota(u, t) }, + tierSet: func(f *console.File) map[tier.Tier]int64 { return f.FileTransferQuota }, + userSet: func(f *console.File) map[string]int64 { return f.FileTransferQuotaUsers }}, + "rate": {key: "rate", noun: "rate limit", none: console.RateOff, parse: console.ParseRate, word: console.RateWord, + value: func(p *console.Policy, u string, t tier.Tier) (int64, string) { return p.FileTransferRate(u, t) }, + tierSet: func(f *console.File) map[tier.Tier]int64 { return f.FileTransferRate }, + userSet: func(f *console.File) map[string]int64 { return f.FileTransferRateUsers }}, +} + +// limitText words a value with where it comes from, for the listings. +func (l fileTransferLimit) limitText(n int64, from string, t tier.Tier) string { + switch from { + case "tier setting": + return l.word(n) + " (set for the " + string(t) + " tier)" + case "default": + return l.word(n) + " (default)" + } + return l.word(n) + " (" + from + ")" +} + +// consoleFileTransferLimit is 'console file-transfer quota|rate ...': with no +// argument the value of each tier and the users with one of their own; +// '' shows one tier, ' ' sets it (the superuser's); +// 'user ' shows one user's, 'user ' sets it. +func (inv *invocation) consoleFileTransferLimit(pol *console.Policy, which string, args []string, usage string) error { + l := fileTransferLimits[which] + if len(args) == 0 { + for _, t := range console.Tiers { + n, from := l.value(pol, "", t) + inv.echo(string(t) + ": " + l.limitText(n, from, t)) + } + if names := sortedUsers(l.userSet(pol.File)); len(names) > 0 { + tiers, err := inv.systemShellTiers() + if err != nil { + return err + } + inv.echo("") + inv.echo("Users with a " + l.noun + " of their own:") + for _, n := range names { + who := "no such user" + if t, ok := tiers[n]; ok { + who = string(t) + } + inv.echo(" " + n + ": " + l.word(l.userSet(pol.File)[n]) + " (" + who + ")") + } + } + return nil + } + if args[0] == "user" { + return inv.consoleFileTransferLimitUser(pol, l, args[1:], usage) + } + t, ok := console.ParseTier(args[0]) + if !ok { + return inv.usageErr("Unknown tier '"+args[0]+"': expected readonly, operator, engineer, superuser or user.", usage) + } + if len(args) == 1 { + n, from := l.value(pol, "", t) + inv.echo(l.limitText(n, from, t)) + return nil + } + if len(args) > 2 { + return inv.usageErr("Unknown argument: '"+args[2]+"'", usage) + } + state := func(f *console.File) string { + if n, ok := l.tierSet(f)[t]; ok { + return l.word(n) + } + return "default" + } + var n int64 + def := args[1] == "default" && l.tierDefault + if !def { + var err error + if n, err = l.parse(args[1]); err != nil { + return inv.sizeErr(err, usage) + } + } + if err := inv.consoleWrite("file-transfer", l.key+":"+string(t), state, func(f *console.File) error { + if l.key == "quota" { + f.SetFileTransferQuota(t, n, def) + } else { + f.SetFileTransferRate(t, n) + } + return nil + }); err != nil { + return err + } + switch { + case def: + inv.app.Out.Info("The quota of the " + string(t) + " tier is back to its default (" + console.QuotaWord(console.DefaultTierQuota(t)) + "). It applies from the next console login.") + case n == 0: + inv.app.Out.Info("The " + string(t) + " tier has " + map[string]string{"quota": "no quota", "rate": "no rate limit"}[l.key] + ". It applies from the next console login.") + default: + inv.app.Out.Info("The " + l.noun + " of the " + string(t) + " tier is " + l.word(n) + map[string]string{"quota": "", "rate": " a second"}[l.key] + ". It applies from the next console login.") + } + return nil +} + +// consoleFileTransferLimitUser is 'console file-transfer quota|rate user +// [|clear]': args are the words after 'user'. +func (inv *invocation) consoleFileTransferLimitUser(pol *console.Policy, l fileTransferLimit, args []string, usage string) error { + if len(args) == 0 { + return inv.usageErr("expected at least 1 argument(s), got 0", usage) + } + if len(args) > 2 { + return inv.usageErr("Unknown argument: '"+args[2]+"'", usage) + } + name := args[0] + exists, t, err := inv.fileTransferUser(name) + if err != nil { + return err + } + own, has := l.userSet(pol.File)[name] + state := func(f *console.File) string { + if n, ok := l.userSet(f)[name]; ok { + return l.word(n) + } + return "none" + } + if len(args) == 1 { + switch { + case !exists && !has: + return inv.usageErr("User '" + name + "' does not exist.") + case !exists: + inv.echo(l.word(own) + " (user setting; no such user)") + default: + n, from := l.value(pol, name, t) + inv.echo(l.limitText(n, from, t)) + } + return nil + } + if args[1] == "clear" { + if !has { + inv.app.Out.Info("'" + name + "' has no " + l.noun + " of their own.") + return nil + } + if err := inv.consoleWrite("file-transfer", l.key+"-user:"+name, state, + func(f *console.File) error { delete(l.userSet(f), name); return nil }); err != nil { + return err + } + inv.app.Out.Info("The " + l.noun + " of '" + name + "' is cleared: the tier decides. It applies from the next console login.") + return nil + } + n, err := l.parse(args[1]) + if err != nil { + return inv.sizeErr(err, usage) + } + if !exists { + return inv.usageErr("User '" + name + "' does not exist.") + } + if err := inv.consoleWrite("file-transfer", l.key+"-user:"+name, state, + func(f *console.File) error { l.userSet(f)[name] = n; return nil }); err != nil { + return err + } + switch { + case n == 0 && l.key == "quota": + inv.app.Out.Info("'" + name + "' has no quota. It applies from the next console login.") + case n == 0: + inv.app.Out.Info("'" + name + "' has no rate limit, whatever their tier has. It applies from the next console login.") + default: + inv.app.Out.Info("The " + l.noun + " of '" + name + "' is " + l.word(n) + map[string]string{"quota": "", "rate": " a second"}[l.key] + ". It applies from the next console login.") + } + return nil +} + +// sortedUsers are the keys of m, sorted. +func sortedUsers(m map[string]int64) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + slices.Sort(out) + return out +} diff --git a/internal/cli/console_filetransfer_policy_test.go b/internal/cli/console_filetransfer_policy_test.go new file mode 100644 index 00000000..2c08f210 --- /dev/null +++ b/internal/cli/console_filetransfer_policy_test.go @@ -0,0 +1,85 @@ +package cli + +import ( + "strings" + "testing" + + "github.com/rett/tacctl/internal/console" + "github.com/rett/tacctl/internal/execx" + "github.com/rett/tacctl/internal/execx/fake" +) + +// policyLine is the _console-policy answer for user, in group. +func (sb *sandbox) policyLine(user, group string) string { + sb.t.Helper() + return plain(sb.cfgRun("", []string{"_console-policy"}, func(r *fake.Runner) { + r.On([]string{"id", "-nG", "--", user}, execx.Result{Stdout: []byte(user + " tac-users tac-" + group + "\n")}) + }, "SUDO_USER="+user, "SUDO_UID="+uidOf(user))) +} + +// The _console-policy line carries the caller's file transfer to the +// console's own process, which cannot read root's file: off unless the +// settings give it, with the quota and the rate when they do, and the +// console reads the line back as the settings (Remote.FileTransferSettings). +func TestConsolePolicyLineCarriesFileTransfer(t *testing.T) { + sb := consoleSandbox(t) + read := func(user, group string) console.FileTransfer { + sb.t.Helper() + r, ok := console.ParseRemote(sb.policyLine(user, group)) + if !ok { + t.Fatalf("%s: the line is not read", user) + } + return r.FileTransferSettings() + } + // the defaults: a superuser has it, with no quota; the others do not + if got := sb.policyLine("bob", "operator"); strings.Contains(got, "file_transfer") || strings.Contains(got, "ft_quota") { + t.Errorf("bob by default: %q", got) + } + if got := read("alice", "superuser"); got != (console.FileTransfer{Enabled: true}) { + t.Errorf("alice: %+v", got) + } + if got := read("carol", "readonly"); got != (console.FileTransfer{}) { + t.Errorf("carol: %+v", got) + } + // a tier: its quota (the default, then set) and its rate + sb.con("file-transfer", "operator", "enable") + if got := read("bob", "operator"); got != (console.FileTransfer{Enabled: true, Quota: 256 << 20}) { + t.Errorf("bob enabled: %+v", got) + } + if got := sb.policyLine("bob", "operator"); !strings.Contains(got, " file_transfer=yes ft_quota=268435456 ft_rate=0") { + t.Errorf("bob's line: %q", got) + } + sb.con("file-transfer", "quota", "operator", "1G") + sb.con("file-transfer", "rate", "operator", "512K") + if got := read("bob", "operator"); got != (console.FileTransfer{Enabled: true, Quota: 1 << 30, Rate: 512 << 10}) { + t.Errorf("bob with limits: %+v", got) + } + // a user's own values over the tier's, and a disable over the tier's enable + sb.con("file-transfer", "quota", "user", "bob", "unlimited") + sb.con("file-transfer", "rate", "user", "bob", "2M") + if got := read("bob", "operator"); got != (console.FileTransfer{Enabled: true, Quota: 0, Rate: 2 << 20}) { + t.Errorf("bob with his own: %+v", got) + } + sb.con("file-transfer", "user", "bob", "disable") + if got := read("bob", "operator"); got != (console.FileTransfer{}) { + t.Errorf("bob disabled: %+v", got) + } + // a user of a tier that has none, enabled for the tier + sb.con("file-transfer", "user", "carol", "enable") + if got := read("carol", "readonly"); got != (console.FileTransfer{Enabled: true, Quota: 256 << 20}) { + t.Errorf("carol enabled: %+v", got) + } + // a caller with no tier restriction (root) has none, whatever the file says + line := plain(sb.cfgRun("", []string{"_console-policy"}, nil)) + if r, ok := console.ParseRemote(line); !ok || r.FileTransferSettings() != (console.FileTransfer{}) { + t.Errorf("root: %q", line) + } + // a user who is no store user is not honoured under the name + sb.write("state/console.yaml", "version: 1\nsettings: {file_transfer: {tiers: [superuser], users: {mallory: 'enable:readonly'}}}\n", 0o600) + line = plain(sb.cfgRun("", []string{"_console-policy"}, func(r *fake.Runner) { + r.On([]string{"id", "-nG", "--", "mallory"}, execx.Result{Stdout: []byte("mallory tac-users tac-readonly\n")}) + }, "SUDO_USER=mallory", "SUDO_UID=4242")) + if r, _ := console.ParseRemote(line); r.FileTransferSettings() != (console.FileTransfer{}) { + t.Errorf("mallory: %q", line) + } +} diff --git a/internal/cli/console_filetransfer_subsystem_test.go b/internal/cli/console_filetransfer_subsystem_test.go new file mode 100644 index 00000000..4b6149c2 --- /dev/null +++ b/internal/cli/console_filetransfer_subsystem_test.go @@ -0,0 +1,83 @@ +package cli + +import ( + "strings" + "testing" + + "github.com/rett/tacctl/internal/execx" + "github.com/rett/tacctl/internal/execx/fake" +) + +// The list form of 'console file-transfer' and 'console show' say whether +// sshd defines an sftp subsystem (sshd -T through the runner), and warn when +// file transfer is on for someone and sshd starts none: the console is never +// started for it. The superuser tier, which always has file transfer, does +// not make a server warn by itself. +func TestConsoleFileTransferSubsystem(t *testing.T) { + sshd := func(subsystem string) func(*fake.Runner) { + return func(r *fake.Runner) { + r.On([]string{"sshd", "-T"}, execx.Result{Stdout: []byte("port 22\nallowtcpforwarding no\nallowagentforwarding no\n" + subsystem)}) + } + } + const warn = "WARNING: sshd defines no sftp subsystem: file transfer cannot start; add `Subsystem sftp ...` to sshd_config." + sb := consoleSandbox(t) + list := func(f func(*fake.Runner)) string { + sb.t.Helper() + return plain(sb.cfgRun("", []string{"console", "file-transfer"}, f)) + } + // defined: said, no warning, with or without file transfer opened + out := list(sshd("subsystem sftp /usr/lib/openssh/sftp-server\n")) + if sb.code != 0 || !strings.HasSuffix(out, "\nsshd sftp subsystem: /usr/lib/openssh/sftp-server\n") || strings.Contains(out, "WARNING") { + t.Errorf("defined: %d\n%s", sb.code, out) + } + if !sb.runner.Called("sshd", "-T", "-C", "user=root,host=localhost,addr=127.0.0.1") { + t.Errorf("calls: %q", sb.runner.Argvs()) + } + // none, and nobody but the superuser tier has file transfer: said, quiet + out = list(sshd("")) + if !strings.HasSuffix(out, "\nsshd sftp subsystem: none\n") || strings.Contains(out, "WARNING") { + t.Errorf("none, not opened:\n%s", out) + } + // none, and a tier has it: warned, in red + sb.con("file-transfer", "operator", "enable") + out = list(sshd("")) + if !strings.HasSuffix(out, "\nsshd sftp subsystem: none\n"+warn+"\n") { + t.Errorf("none, operator tier:\n%s", out) + } + if raw := sb.cfgRun("", []string{"console", "file-transfer"}, sshd("")); !strings.Contains(raw, "\x1b[0;31m"+warn) { + t.Errorf("the warning is not red: %q", raw) + } + sb.con("file-transfer", "operator", "disable") + // none, and one user has it: warned; a disable does not + sb.con("file-transfer", "user", "carol", "enable") + if out = list(sshd("")); !strings.Contains(out, warn) { + t.Errorf("none, a user:\n%s", out) + } + sb.con("file-transfer", "user", "carol", "disable") + if out = list(sshd("")); strings.Contains(out, "WARNING") { + t.Errorf("none, the user disabled:\n%s", out) + } + sb.con("file-transfer", "user", "carol", "clear") + // sshd that cannot answer: said, the verb still succeeds + out = list(func(r *fake.Runner) { r.Fail([]string{"sshd"}, 255, "no hostkeys available") }) + if sb.code != 0 || !strings.Contains(out, "sshd sftp subsystem: could not be checked: sshd -T failed: no hostkeys available") { + t.Errorf("sshd failure: %d\n%s", sb.code, out) + } + // a query of one tier does not ask sshd + if out = plain(sb.cfgRun("", []string{"console", "file-transfer", "operator"}, nil)); strings.Contains(out, "sshd") || sb.runner.Called("sshd") { + t.Errorf("a tier query:\n%s", out) + } + // console show reports it in the server section, with the same warning + sb.con("file-transfer", "operator", "enable") + show := func(subsystem string) string { + return plain(sb.cfgRun("", []string{"console", "show"}, sshd(subsystem))) + } + out = show("subsystem sftp internal-sftp\n") + if !strings.Contains(out, "\nsshd sftp subsystem: internal-sftp\n") || strings.Contains(out, warn) { + t.Errorf("show, defined:\n%s", out) + } + out = show("") + if !strings.Contains(out, "\nsshd sftp subsystem: none\n"+warn+"\n") { + t.Errorf("show, none:\n%s", out) + } +} diff --git a/internal/cli/console_filetransfer_test.go b/internal/cli/console_filetransfer_test.go new file mode 100644 index 00000000..6ecc97c4 --- /dev/null +++ b/internal/cli/console_filetransfer_test.go @@ -0,0 +1,532 @@ +package cli + +import ( + "strings" + "testing" + + "github.com/rett/tacctl/internal/execx" + "github.com/rett/tacctl/internal/execx/fake" + "github.com/rett/tacctl/internal/tier" +) + +// 'console file-transfer' end to end, on the sandbox of console_test.go +// (alice superuser, bob operator, carol readonly). + +// listing is the output of the list form without the line about sshd's sftp +// subsystem (console_filetransfer_subsystem_test.go). +func listing(out string) string { + head, _, _ := strings.Cut(out, "\nsshd sftp subsystem:") + return strings.TrimSpace(head) +} + +// With no argument the command lists each tier (the superuser tier always on, +// the others off by default), '' prints one, ' enable|disable' +// sets it, the engineer tier is not closed, and the file holds the tiers +// that have it. +func TestConsoleFileTransferPerTier(t *testing.T) { + sb := consoleSandbox(t) + const defaults = "readonly: disabled\noperator: disabled\nengineer: disabled\nsuperuser: enabled (always)" + if got := listing(sb.con("file-transfer")); got != defaults { + t.Errorf("defaults:\n%s", got) + } + if sb.consoleYAML() != "" { + t.Error("a listing wrote console.yaml") + } + out := sb.con("file-transfer", "operator", "enable") + if sb.code != 0 || !strings.Contains(out, "File transfer is enabled for the operator tier. It applies from the next console login.") { + t.Errorf("enable operator: %d %q", sb.code, out) + } + if got := strings.TrimSpace(sb.con("file-transfer", "operator")); got != "enabled" { + t.Errorf("operator: %q", got) + } + // unlike the system shell, the engineer tier can have it + if out = sb.con("file-transfer", "engineer", "enable"); sb.code != 0 || !strings.Contains(out, "enabled for the engineer tier") { + t.Errorf("enable engineer: %d %q", sb.code, out) + } + want := "readonly: disabled\noperator: enabled\nengineer: enabled\nsuperuser: enabled (always)" + if got := listing(sb.con("file-transfer")); got != want { + t.Errorf("both:\n%s", got) + } + if y := sb.consoleYAML(); !strings.Contains(y, "\n file_transfer:\n tiers: [operator, engineer, superuser]\n") { + t.Errorf("console.yaml:\n%s", y) + } + sb.con("file-transfer", "operator", "disable") + sb.con("file-transfer", "engineer", "disable") + if y := sb.consoleYAML(); strings.Contains(y, "file_transfer") { + t.Errorf("the key is left while everything is the default:\n%s", y) + } + // The superuser tier cannot be disabled and enabling it changes nothing. + before := sb.consoleYAML() + sb.con("file-transfer", "superuser", "disable") + sb.expect(1, "", "The superuser tier always has file transfer; it cannot be disabled. Nothing was changed.") + if out = sb.con("file-transfer", "superuser", "enable"); sb.code != 0 || !strings.Contains(out, "The superuser tier always has file transfer. Nothing was changed.") { + t.Errorf("superuser enable: %d %q", sb.code, out) + } + if sb.consoleYAML() != before { + t.Errorf("a refusal wrote console.yaml:\n%s", sb.consoleYAML()) + } + for _, c := range []struct { + args []string + want string + }{ + {[]string{"mode"}, "Unknown tier 'mode'"}, + {[]string{"root", "enable"}, "Unknown tier 'root'"}, + {[]string{"operator", "maybe"}, "Usage: tacctl console file-transfer"}, + {[]string{"operator", "enable", "x"}, "Unknown argument: 'x'"}, + {[]string{"quota", "operator", "1G", "x"}, "Unknown argument: 'x'"}, + {[]string{"user"}, "expected at least 1 argument(s), got 0"}, + {[]string{"user", "bob", "enable", "x"}, "Unknown argument: 'x'"}, + {[]string{"user", "bob", "maybe"}, "Usage: tacctl console file-transfer"}, + {[]string{"user", "zed"}, "User 'zed' does not exist."}, + {[]string{"user", "zed", "enable"}, "User 'zed' does not exist."}, + } { + sb.con(append([]string{"file-transfer"}, c.args...)...) + if sb.code != 1 || !strings.Contains(plain(sb.err.String()), c.want) { + t.Errorf("%v: exit %d, stderr %q, want %q", c.args, sb.code, sb.err.String(), c.want) + } + } + if sb.consoleYAML() != before { + t.Errorf("a refusal wrote console.yaml:\n%s", sb.consoleYAML()) + } +} + +// A user's setting beats the tier's in both directions, is listed with the +// user's tier, ends with a move to another tier, and a superuser cannot be +// disabled. +func TestConsoleFileTransferPerUser(t *testing.T) { + sb := consoleSandbox(t) + out := sb.con("file-transfer", "user", "carol", "enable") + if sb.code != 0 || !strings.Contains(out, "File transfer is enabled for 'carol' while they are in the readonly tier (a move to another tier ends it until it is set again). It applies from the next console login.") { + t.Errorf("enable carol: %d %q", sb.code, out) + } + for user, want := range map[string]string{"carol": "enabled (user setting)", "bob": "disabled (tier operator)", "alice": "enabled (always)"} { + if got := strings.TrimSpace(sb.con("file-transfer", "user", user)); got != want { + t.Errorf("%s: %q, want %q", user, got, want) + } + } + sb.con("file-transfer", "operator", "enable") + sb.con("file-transfer", "user", "bob", "disable") + if got := strings.TrimSpace(sb.con("file-transfer", "user", "bob")); got != "disabled (user setting)" { + t.Errorf("bob: %q", got) + } + list := strings.TrimSpace(sb.con("file-transfer")) + for _, w := range []string{"readonly: disabled\noperator: enabled\nengineer: disabled\nsuperuser: enabled (always)\n\nUsers with a setting of their own:\n", + " bob: disabled (operator)\n", " carol: enabled (readonly)"} { + if !strings.Contains(list+"\n", w) { + t.Errorf("listing lacks %q:\n%s", w, list) + } + } + if y := sb.consoleYAML(); !strings.Contains(y, "\n users: {bob: disable, carol: 'enable:readonly'}\n") { + t.Errorf("console.yaml:\n%s", y) + } + // console show lists the state next to the system shell's + show := sb.con("show") + for _, w := range []string{ + "File transfer (off by default; a user's own setting wins over the tier's):\n readonly: disabled, quota 256M (default), rate off (default)\n operator: enabled, quota 256M (default), rate off (default)\n" + + " engineer: disabled, quota 256M (default), rate off (default)\n superuser: enabled (always), quota unlimited (default), rate off (default)\n", + "SYSTEM SHELL", "FILE TRANSFER", "QUOTA", "RATE", + "enabled (always) unlimited off\n", + "disabled (user setting) - -\n", + "enabled (user setting) 256M off\n", + } { + if !strings.Contains(show, w) { + t.Errorf("show lacks %q:\n%s", w, show) + } + } + // clear: the tier decides again + sb.con("file-transfer", "user", "bob", "clear") + if out = sb.con("file-transfer", "user", "bob", "clear"); !strings.Contains(out, "'bob' has no file transfer setting of their own.") { + t.Errorf("clear twice: %q", out) + } + sb.con("file-transfer", "user", "carol", "clear") + sb.con("file-transfer", "operator", "disable") + if y := sb.consoleYAML(); strings.Contains(y, "file_transfer") { + t.Errorf("the key is left while everything is the default:\n%s", y) + } + // Superusers: disable is refused, enable is already so; neither writes. + before := sb.consoleYAML() + sb.con("file-transfer", "user", "alice", "disable") + sb.expect(1, "", "'alice' is a superuser, and superusers always have file transfer; it cannot be disabled. Nothing was changed.") + if out = sb.con("file-transfer", "user", "alice", "enable"); sb.code != 0 || !strings.Contains(out, "'alice' is a superuser, who always has file transfer. Nothing was changed.") { + t.Errorf("alice enable: %d %q", sb.code, out) + } + // The engineer tier can be given it, and an engineer user can be switched. + sb.write("state/tacctl.yaml", "tier:\n operator: engineer\n", 0o600) + if out = sb.con("file-transfer", "user", "bob", "enable"); sb.code != 0 || !strings.Contains(out, "while they are in the engineer tier") { + t.Errorf("engineer bob: %d %q", sb.code, out) + } + if got := strings.TrimSpace(sb.con("file-transfer", "user", "bob")); got != "enabled (user setting)" { + t.Errorf("engineer bob: %q", got) + } + sb.con("file-transfer", "user", "bob", "clear") + if sb.consoleYAML() != before { + t.Errorf("console.yaml:\n%s", sb.consoleYAML()) + } + // A setting of a user who is gone stays, is listed, and clear removes it. + sb.write("state/console.yaml", "version: 1\nsettings: {file_transfer: {tiers: [superuser], users: {ghost: 'enable:readonly'}}}\n", 0o600) + if list = strings.TrimSpace(sb.con("file-transfer")); !strings.Contains(list, " ghost: enabled (no such user)") { + t.Errorf("listing:\n%s", list) + } + if got := strings.TrimSpace(sb.con("file-transfer", "user", "ghost")); got != "enabled (user setting; no such user)" { + t.Errorf("ghost: %q", got) + } + if show = sb.con("show"); !strings.Contains(show, "File transfer settings of users that have no account here: ghost") { + t.Errorf("show:\n%s", show) + } + sb.con("file-transfer", "user", "ghost", "clear") + if sb.code != 0 || strings.Contains(sb.consoleYAML(), "ghost") { + t.Errorf("clear ghost: %d\n%s", sb.code, sb.consoleYAML()) + } +} + +// The quota and the rate: the built-in values, a tier's, a user's over the +// tier's, the words, and the refusals. +func TestConsoleFileTransferQuotaAndRate(t *testing.T) { + sb := consoleSandbox(t) + if got := strings.TrimSpace(sb.con("file-transfer", "quota")); got != + "readonly: 256M (default)\noperator: 256M (default)\nengineer: 256M (default)\nsuperuser: unlimited (default)" { + t.Errorf("quota:\n%s", got) + } + if got := strings.TrimSpace(sb.con("file-transfer", "rate")); got != + "readonly: off (default)\noperator: off (default)\nengineer: off (default)\nsuperuser: off (default)" { + t.Errorf("rate:\n%s", got) + } + out := sb.con("file-transfer", "quota", "operator", "1024M") + if sb.code != 0 || !strings.Contains(out, "The quota of the operator tier is 1G. It applies from the next console login.") { + t.Errorf("quota operator: %d %q", sb.code, out) + } + if out = sb.con("file-transfer", "rate", "operator", "512k"); sb.code != 0 || !strings.Contains(out, "The rate limit of the operator tier is 512K a second.") { + t.Errorf("rate operator: %d %q", sb.code, out) + } + if got := strings.TrimSpace(sb.con("file-transfer", "quota", "operator")); got != "1G (set for the operator tier)" { + t.Errorf("quota operator: %q", got) + } + if got := strings.TrimSpace(sb.con("file-transfer", "rate", "readonly")); got != "off (default)" { + t.Errorf("rate readonly: %q", got) + } + if y := sb.consoleYAML(); !strings.Contains(y, "\n quota: {operator: 1G}\n") || !strings.Contains(y, "\n rate: {operator: 512K}\n") { + t.Errorf("console.yaml:\n%s", y) + } + sb.con("file-transfer", "operator", "enable") + // unlimited and default + if out = sb.con("file-transfer", "quota", "superuser", "2G"); sb.code != 0 { + t.Errorf("quota superuser: %q", out) + } + if out = sb.con("file-transfer", "quota", "operator", "unlimited"); sb.code != 0 || !strings.Contains(out, "The operator tier has no quota.") { + t.Errorf("quota unlimited: %d %q", sb.code, out) + } + if out = sb.con("file-transfer", "quota", "operator", "default"); sb.code != 0 || !strings.Contains(out, "The quota of the operator tier is back to its default (256M).") { + t.Errorf("quota default: %d %q", sb.code, out) + } + if out = sb.con("file-transfer", "quota", "superuser", "default"); sb.code != 0 || !strings.Contains(out, "back to its default (unlimited)") { + t.Errorf("quota superuser default: %d %q", sb.code, out) + } + if out = sb.con("file-transfer", "rate", "operator", "off"); sb.code != 0 || !strings.Contains(out, "The operator tier has no rate limit.") { + t.Errorf("rate off: %d %q", sb.code, out) + } + if y := sb.consoleYAML(); strings.Contains(y, "quota") || strings.Contains(y, "rate") { + t.Errorf("a default is stored:\n%s", y) + } + + // per user: over the tier's, both ways; clear; listed + sb.con("file-transfer", "quota", "operator", "1G") + if out = sb.con("file-transfer", "quota", "user", "bob", "64M"); sb.code != 0 || !strings.Contains(out, "The quota of 'bob' is 64M.") { + t.Errorf("quota user: %d %q", sb.code, out) + } + sb.con("file-transfer", "quota", "user", "carol", "unlimited") + sb.con("file-transfer", "rate", "user", "bob", "2M") + sb.con("file-transfer", "rate", "operator", "10M") + if out = sb.con("file-transfer", "rate", "user", "carol", "off"); sb.code != 0 || !strings.Contains(out, "'carol' has no rate limit, whatever their tier has.") { + t.Errorf("rate user off: %d %q", sb.code, out) + } + for _, c := range []struct { + args []string + want string + }{ + {[]string{"quota", "user", "bob"}, "64M (user setting)"}, + {[]string{"quota", "user", "carol"}, "unlimited (user setting)"}, + {[]string{"quota", "user", "alice"}, "unlimited (default)"}, + {[]string{"rate", "user", "bob"}, "2M (user setting)"}, + {[]string{"rate", "user", "carol"}, "off (user setting)"}, + {[]string{"rate", "user", "alice"}, "off (default)"}, + } { + if got := strings.TrimSpace(sb.con(append([]string{"file-transfer"}, c.args...)...)); got != c.want { + t.Errorf("%v: %q, want %q", c.args, got, c.want) + } + } + list := sb.con("file-transfer", "quota") + if !strings.Contains(list, "Users with a quota of their own:\n bob: 64M (operator)\n carol: unlimited (readonly)\n") { + t.Errorf("quota listing:\n%s", list) + } + if list = sb.con("file-transfer", "rate"); !strings.Contains(list, "operator: 10M (set for the operator tier)") || + !strings.Contains(list, "Users with a rate limit of their own:\n bob: 2M (operator)\n carol: off (readonly)\n") { + t.Errorf("rate listing:\n%s", list) + } + sb.con("file-transfer", "user", "bob", "enable") + sb.con("file-transfer", "user", "carol", "enable") + show := sb.con("show") + for _, w := range []string{"enabled (user setting) 64M ", "enabled (user setting) unlimited off"} { + if !strings.Contains(show, w) { + t.Errorf("show lacks %q:\n%s", w, show) + } + } + if out = sb.con("file-transfer", "quota", "user", "bob", "clear"); sb.code != 0 || !strings.Contains(out, "The quota of 'bob' is cleared: the tier decides.") { + t.Errorf("quota clear: %d %q", sb.code, out) + } + if out = sb.con("file-transfer", "quota", "user", "bob", "clear"); !strings.Contains(out, "'bob' has no quota of their own.") { + t.Errorf("quota clear twice: %q", out) + } + sb.con("file-transfer", "rate", "user", "bob", "clear") + if out = sb.con("file-transfer", "rate", "user", "bob", "clear"); !strings.Contains(out, "'bob' has no rate limit of their own.") { + t.Errorf("rate clear twice: %q", out) + } + if got := strings.TrimSpace(sb.con("file-transfer", "quota", "user", "bob")); got != "1G (set for the operator tier)" { + t.Errorf("bob after clear: %q", got) + } + // a setting of a user who is gone + sb.write("state/console.yaml", "version: 1\nsettings: {file_transfer: {tiers: [superuser], quota_users: {ghost: 1M}, rate_users: {ghost: 'off'}}}\n", 0o600) + if got := strings.TrimSpace(sb.con("file-transfer", "quota", "user", "ghost")); got != "1M (user setting; no such user)" { + t.Errorf("ghost: %q", got) + } + if show = sb.con("show"); !strings.Contains(show, "File transfer settings of users that have no account here: ghost") { + t.Errorf("show:\n%s", show) + } + sb.con("file-transfer", "quota", "user", "ghost", "clear") + sb.con("file-transfer", "rate", "user", "ghost", "clear") + if strings.Contains(sb.consoleYAML(), "ghost") { + t.Errorf("ghost is left:\n%s", sb.consoleYAML()) + } + + // refusals, none of which writes the file + before := sb.consoleYAML() + for _, c := range []struct { + args []string + want string + }{ + {[]string{"quota", "operator", "0"}, "is zero"}, + {[]string{"quota", "operator", "-5M"}, "Unknown flag: '-5M'"}, + {[]string{"quota", "operator", "--", "-5M"}, "Invalid size '-5M'"}, + {[]string{"quota", "user", "bob", "--", "-1"}, "Invalid size '-1'"}, + {[]string{"quota", "operator", "1.5G"}, "Invalid size '1.5G'"}, + {[]string{"quota", "operator", "12X"}, "Invalid size '12X'"}, + {[]string{"quota", "operator", "2T"}, "too large"}, + {[]string{"quota", "operator", "99999999999999999999"}, "too large"}, + {[]string{"quota", "operator", "off"}, "Invalid size 'off'"}, + {[]string{"quota", "operator", ""}, "Invalid size ''"}, + {[]string{"quota", "operator"}, ""}, + {[]string{"rate", "operator", "0"}, "is zero"}, + {[]string{"rate", "operator", "unlimited"}, "Invalid size 'unlimited'"}, + {[]string{"rate", "operator", "default"}, "Invalid size 'default'"}, + {[]string{"rate", "operator", "2T"}, "too large"}, + {[]string{"quota", "root", "1G"}, "Unknown tier 'root'"}, + {[]string{"rate", "user", "bob", "fast"}, "Invalid size 'fast'"}, + {[]string{"quota", "user", "bob", "default"}, "Invalid size 'default'"}, + {[]string{"quota", "user", "zed", "1G"}, "User 'zed' does not exist."}, + {[]string{"quota", "user", "zed"}, "User 'zed' does not exist."}, + {[]string{"quota", "user"}, "expected at least 1 argument(s), got 0"}, + {[]string{"quota", "user", "bob", "1G", "x"}, "Unknown argument: 'x'"}, + } { + sb.con(append([]string{"file-transfer"}, c.args...)...) + failed := c.want != "" + if (failed && (sb.code != 1 || !strings.Contains(plain(sb.err.String()), c.want))) || (!failed && sb.code != 0) { + t.Errorf("%v: exit %d, stderr %q, want %q", c.args, sb.code, sb.err.String(), c.want) + } + } + if sb.consoleYAML() != before { + t.Errorf("a refusal wrote console.yaml:\n%s", sb.consoleYAML()) + } +} + +// Who may read and who may set: the verb reads for the operator tier and up +// and sets for the superuser only. The tier table has no row for the verb in +// this change, so the gate in front of it refuses everyone below the +// superuser tier; the row the later change adds is put in place here for the +// test, to show that the verb itself holds the line. +func TestConsoleFileTransferIsTheSuperusersToSet(t *testing.T) { + serial(t) + sb := consoleSandbox(t) + saved := tier.Rules + t.Cleanup(func() { tier.Rules = saved }) + tier.Rules = append(append([]tier.Rule{}, saved...), tier.Rule{Tier: tier.Operator, Cmd: "console", Sub: "file-transfer"}) + as := func(user, group string, args ...string) { + sb.cfgRun("", append([]string{"console", "file-transfer"}, args...), func(r *fake.Runner) { + r.On([]string{"id", "-nG", "--", user}, execx.Result{Stdout: []byte(user + " tac-users tac-" + group + "\n")}) + }, "SUDO_USER="+user, "SUDO_UID="+uidOf(user)) + } + writes := [][]string{ + {"operator", "enable"}, {"readonly", "disable"}, {"engineer", "enable"}, {"superuser", "disable"}, + {"user", "carol", "enable"}, {"user", "carol", "clear"}, + {"quota", "operator", "1G"}, {"quota", "operator", "default"}, {"quota", "user", "carol", "1G"}, {"quota", "user", "carol", "clear"}, + {"rate", "operator", "1M"}, {"rate", "operator", "off"}, {"rate", "user", "carol", "1M"}, {"rate", "user", "carol", "clear"}, + } + reads := []struct { + args []string + want string + }{ + {nil, "superuser: enabled (always)"}, {[]string{"readonly"}, "disabled"}, {[]string{"superuser"}, "enabled (always)"}, + {[]string{"user", "carol"}, "disabled (tier readonly)"}, + {[]string{"quota"}, "superuser: unlimited (default)"}, {[]string{"quota", "operator"}, "256M (default)"}, {[]string{"quota", "user", "carol"}, "256M (default)"}, + {[]string{"rate"}, "superuser: off (default)"}, {[]string{"rate", "operator"}, "off (default)"}, {[]string{"rate", "user", "carol"}, "off (default)"}, + } + for _, who := range []struct{ user, group, tier string }{{"bob", "operator", "operator"}} { + for _, r := range reads { + as(who.user, who.group, r.args...) + sb.expect(0, r.want, "") + } + for _, args := range writes { + as(who.user, who.group, args...) + sb.expect(1, "", "'tacctl console file-transfer' is not permitted for the "+who.tier+" tier.") + if !hasAuditPrefix(sb.runner, "auth.warning", "tier DENY user=bob tier=operator cmd=console file-transfer") { + t.Errorf("refusal of %v not logged: %q", args, sb.runner.Argvs()) + } + } + } + if sb.consoleYAML() != "" { + t.Errorf("a refusal wrote console.yaml:\n%s", sb.consoleYAML()) + } + // below the row the gate refuses the verb altogether + as("carol", "readonly") + sb.expect(1, "", "'tacctl console file-transfer' is not permitted for the readonly tier.") + // the superuser sets every form + for _, args := range [][]string{{"operator", "enable"}, {"user", "carol", "enable"}, {"user", "carol", "clear"}, {"quota", "operator", "1G"}, + {"quota", "user", "carol", "unlimited"}, {"rate", "operator", "1M"}, {"rate", "user", "carol", "off"}, {"operator", "disable"}} { + as("alice", "superuser", args...) + if sb.code != 0 { + t.Errorf("superuser %v: %d %q", args, sb.code, sb.stderr()) + } + } +} + +// Without the row in the tier table (this change), the verb is the +// superuser's alone; the gate says so. +func TestConsoleFileTransferGateWithoutARow(t *testing.T) { + sb := consoleSandbox(t) + sb.cfgRun("", []string{"console", "file-transfer"}, func(r *fake.Runner) { + r.On([]string{"id", "-nG", "--", "bob"}, execx.Result{Stdout: []byte("bob tac-users tac-operator\n")}) + }, "SUDO_USER=bob", "SUDO_UID="+uidOf("bob")) + sb.expect(1, "", "'tacctl console file-transfer' is not permitted for the operator tier.") +} + +// 'user remove' drops the file transfer settings of the user, 'user rename' +// moves them to the new name; both say so and are logged as 'console set'. +func TestFileTransferSettingsFollowTheUser(t *testing.T) { + sb := consoleSandbox(t) + sb.con("file-transfer", "user", "carol", "enable") + sb.con("file-transfer", "quota", "user", "carol", "1G") + sb.con("file-transfer", "rate", "user", "carol", "1M") + sb.con("file-transfer", "user", "bob", "disable") + out := plain(sb.cfgRun("", []string{"user", "rename", "carol", "erin"}, nil, "SUDO_USER=alice", "SUDO_UID=1001")) + if sb.code != 0 || !strings.Contains(out, "The file-transfer setting of 'carol' (enable:readonly, quota 1G, rate 1M) moves to 'erin'.") { + t.Fatalf("rename: %d %q\n%s", sb.code, sb.stderr(), out) + } + y := sb.consoleYAML() + for _, w := range []string{"users: {bob: disable, erin: 'enable:readonly'}", "quota_users: {erin: 1G}", "rate_users: {erin: 1M}"} { + if !strings.Contains(y, w) { + t.Errorf("console.yaml lacks %q:\n%s", w, y) + } + } + if strings.Contains(y, "carol") { + t.Errorf("carol is left:\n%s", y) + } + for _, w := range []string{ + "console set key=file-transfer item=user:carol from=\"enable:readonly, quota 1G, rate 1M\" to=none by=alice", + "console set key=file-transfer item=user:erin from=none to=\"enable:readonly, quota 1G, rate 1M\" by=alice", + } { + if !hasAuditPrefix(sb.runner, "auth.notice", w) { + t.Errorf("not logged: %s\n%q", w, sb.runner.Argvs()) + } + } + out = plain(sb.cfgRun("y\n", []string{"user", "remove", "erin"}, nil, "SUDO_USER=alice", "SUDO_UID=1001")) + if sb.code != 0 || !strings.Contains(out, "The file-transfer setting of 'erin' (enable:readonly, quota 1G, rate 1M) is dropped.") { + t.Fatalf("remove: %d %q\n%s", sb.code, sb.stderr(), out) + } + if y = sb.consoleYAML(); strings.Contains(y, "erin") || !strings.Contains(y, "bob: disable") { + t.Errorf("console.yaml after the removal:\n%s", y) + } +} + +// The completion of each position of the forms. +func TestConsoleFileTransferCompletionKinds(t *testing.T) { + args := consoleSpecs["file-transfer"].Args + const tiers = "readonly|operator|engineer|superuser|user" + for _, c := range []struct { + words []string + want string + }{ + {nil, "readonly|operator|engineer|superuser|user|quota|rate"}, + {[]string{"operator"}, "enable|disable"}, + {[]string{"user"}, "users"}, + {[]string{"quota"}, tiers}, + {[]string{"rate"}, tiers}, + {[]string{"user", "bob"}, "enable|disable|clear"}, + {[]string{"quota", "operator"}, "unlimited|default"}, + {[]string{"quota", "user"}, "users"}, + {[]string{"rate", "operator"}, "off"}, + {[]string{"rate", "user"}, "users"}, + {[]string{"quota", "user", "bob"}, "unlimited|clear"}, + {[]string{"rate", "user", "bob"}, "off|clear"}, + {[]string{"quota", "operator", "1G"}, ""}, + {[]string{"user", "bob", "enable"}, ""}, + } { + if len(c.words) >= len(args) { + continue + } + if got := resolveKind(args[len(c.words)], c.words); got != c.want { + t.Errorf("after %v: %q, want %q", c.words, got, c.want) + } + } +} + +// Every form of 'console file-transfer', the reads included, is the +// superuser's: the verb has no row in the tier table, which the sudoers text +// of the rollback target 0.2.27 freezes. What every user has (the state, the +// quota and the rate) is in 'console show', which the operator tier and up +// can run and the readonly tier cannot. +func TestConsoleFileTransferTierGate(t *testing.T) { + for _, c := range []struct { + t tier.Tier + sub string + want bool + }{ + {tier.Readonly, "file-transfer", false}, + {tier.Operator, "file-transfer", false}, + {tier.Engineer, "file-transfer", false}, + {tier.Superuser, "file-transfer", true}, + {tier.Readonly, "show", false}, + {tier.Operator, "show", true}, + {tier.Engineer, "show", true}, + } { + if got := tier.Permits(c.t, "console", c.sub); got != c.want { + t.Errorf("Permits(%s, console %s) = %v, want %v", c.t, c.sub, got, c.want) + } + } + sb := consoleSandbox(t) + as := func(user, group string, args ...string) { + sb.t.Helper() + sb.cfgRun("", args, func(r *fake.Runner) { + r.On([]string{"id", "-nG", "--", user}, execx.Result{Stdout: []byte(user + " tac-users tac-" + group + "\n")}) + }, "SUDO_USER="+user, "SUDO_UID="+uidOf(user)) + } + for _, args := range [][]string{ + {"console", "file-transfer"}, {"console", "file-transfer", "operator"}, {"console", "file-transfer", "user", "carol"}, + {"console", "file-transfer", "quota"}, {"console", "file-transfer", "rate", "user", "carol"}, + {"console", "file-transfer", "operator", "enable"}, {"console", "file-transfer", "quota", "operator", "1G"}, + } { + as("bob", "operator", args...) + sb.expect(1, "", "'tacctl console file-transfer' is not permitted for the operator tier.") + } + as("alice", "superuser", "console", "file-transfer", "user", "carol") + sb.expect(0, "disabled (tier readonly)", "") + // the operator's view of every user's state, quota and rate + as("bob", "operator", "console", "show") + sb.expect(0, "FILE TRANSFER", "") + out := plain(sb.out.String()) + for _, want := range []string{"File transfer (off by default; a user's own setting wins over the tier's):", " QUOTA", " RATE", + "carol readonly console managed user disabled (tier readonly) disabled (tier readonly) -"} { + if !strings.Contains(out, want) { + t.Errorf("console show for the operator lacks %q:\n%s", want, out) + } + } + as("carol", "readonly", "console", "show") + sb.expect(1, "", "'tacctl console show' is not permitted for the readonly tier.") +} diff --git a/internal/cli/console_mode.go b/internal/cli/console_mode.go index 3826a160..e2abbd59 100644 --- a/internal/cli/console_mode.go +++ b/internal/cli/console_mode.go @@ -10,7 +10,9 @@ package cli // // and one word of its own, system-shell. sshd starts it with '-c // ' for a remote command, scp, sftp and rsync: one tacctl line -// passes (console.Guard), everything else is refused with exit 126. +// passes (console.Guard), the sftp subsystem is served for the accounts that +// have file transfer (console_sftp.go), everything else is refused with exit +// 126. // Sessions, refusals and system shells are logged (syslog tag // tacctl-console). @@ -29,6 +31,7 @@ import ( "github.com/rett/tacctl/internal/console" "github.com/rett/tacctl/internal/execx" "github.com/rett/tacctl/internal/paths" + "github.com/rett/tacctl/internal/sftpd" "github.com/rett/tacctl/internal/tier" ) @@ -113,7 +116,12 @@ func (inv *invocation) runConsoleSession(args []string) error { } f, isFile := a.Stdin.(*os.File) mode := console.ModeBatch + // The one -c string the console serves besides a tacctl line: the sftp + // subsystem (console_sftp.go). + isSFTP := cmdMode && sftpd.IsSubsystemCommand(line) switch { + case isSFTP: + mode = console.ModeSFTP case cmdMode: mode = console.ModeCommand case isFile && term.IsTerminal(int(f.Fd())): @@ -125,6 +133,9 @@ func (inv *invocation) runConsoleSession(args []string) error { }} cs.log("auth.info", cs.sess.StartLine()) + if isSFTP { + return cs.serveSFTP(exe) + } if cmdMode { root := newRoot(inv) first, ok := console.Guard(line, consoleRootCommand(root)) diff --git a/internal/cli/console_mode_test.go b/internal/cli/console_mode_test.go index 580fd8a2..b8378d19 100644 --- a/internal/cli/console_mode_test.go +++ b/internal/cli/console_mode_test.go @@ -102,7 +102,7 @@ func TestConsoleLineArgv(t *testing.T) { func TestConsoleGuardRefusals(t *testing.T) { for _, line := range []string{ - "scp -t .", "scp -f /etc/passwd", "/usr/lib/openssh/sftp-server", "internal-sftp", "rsync --server -e.LsfxC . .", + "scp -t .", "scp -f /etc/passwd", "scp -O -f x", "rsync --server -e.LsfxC . .", "bash", "sh -c id", "system-shell", "exit", "quit", "history", "", "_console-policy", "user list\nbash", "env", "/bin/sh", "user 'list", } { @@ -365,14 +365,23 @@ func TestConsoleMainForcedCommand(t *testing.T) { t.Errorf("env %q: execs %+v", c.env, ex) } } - // After the re-exec (a clean environment) a forced sftp is refused. + // After the re-exec (a clean environment) a forced sftp is the subsystem: + // refused here, where the root side gives no answer (console_sftp_test.go + // serves it), and with its own text, not the one of a program. r := &fake.Runner{} errb.Reset() clean := []string{"USER=carol", "PATH=" + console.ConsolePath, "SHELL=" + paths.ConsoleCommand} if code := consoleMain(context.Background(), []string{"tacctl-console", "-c", "internal-sftp"}, clean, stdio, BuildInfo{}, testExe, 1000, r); code != console.RefusedStatus { t.Errorf("sftp: status %d", code) } + if strings.Contains(errb.String(), console.RefusedText) || errb.Len() == 0 || out.Len() != 0 { + t.Errorf("sftp: stderr %q stdout %q", errb.String(), out.String()) + } + errb.Reset() + if code := consoleMain(context.Background(), []string{"tacctl-console", "-c", "scp -f x"}, clean, stdio, BuildInfo{}, testExe, 1000, &fake.Runner{}); code != console.RefusedStatus { + t.Errorf("scp -f: status %d", code) + } if !strings.Contains(errb.String(), console.RefusedText) { - t.Errorf("sftp: %q", errb.String()) + t.Errorf("scp -f: %q", errb.String()) } } diff --git a/internal/cli/console_sftp.go b/internal/cli/console_sftp.go new file mode 100644 index 00000000..0759505c --- /dev/null +++ b/internal/cli/console_sftp.go @@ -0,0 +1,216 @@ +package cli + +// The console's file transfer: the sftp subsystem that sshd's ForceCommand +// hands to the console as a '-c' string (sftp-server, internal-sftp) is +// served by internal/sftpd on the process's standard input and output, as the +// logged-in user, rooted in the home directory the account database names. +// The protocol owns standard output: nothing is printed to it, and every +// refusal and error goes to standard error before the first protocol byte. +// The shell, its idle timeout and its history have no part in it. + +import ( + "context" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/rett/tacctl/internal/console" + "github.com/rett/tacctl/internal/sftpd" + "github.com/rett/tacctl/internal/ui" +) + +// The texts of the sftp subsystem refused before the protocol starts (the +// refusal for a policy that is off is console.SFTPOffText). +const ( + sftpPasswordText = "a password change is required of this account: log in to the console and change the password (passwd) before transferring files" + sftpUnknownText = "it could not be read whether a password change is required of this account, so file transfer is held: try again, or ask an administrator" + sftpPolicyText = "the console's policy could not be read, so file transfer is not available: try again, or ask an administrator" +) + +// serveSFTP is the session of the sftp subsystem, after the start line of +// the console: the policy is asked, the caller is held to the same rules as +// a line of the console (a required password change, the policy's file +// transfer setting), and then sftpd serves the stream. +func (cs *consoleSession) serveSFTP(exe string) error { + inv, a := cs.inv, cs.inv.app + marker := console.EnvMarker + "=" + cs.sess.ID + cs.pol = inv.consoleRemotePolicy(exe, marker) + inv.hooks.adjustConsolePolicy(&cs.pol) + groups := inv.callerGroups() + cs.tier = sudoTier(groups) + if cs.pol.Known { + cs.tier = cs.pol.Tier + } + switch lock := lockedBy(cs.pol, groups); { + case lock != nil && lock.unknown.Load(): + // it could not be read whether a password change is required of the + // caller (no answer from the root side counts): nothing is served + return cs.sftpRefused("password-change", sftpUnknownText, console.RefusedStatus) + case lock != nil: + // a password change is required: the session may run nothing but the + // change itself + return cs.sftpRefused("password-change", sftpPasswordText, console.RefusedStatus) + case !cs.pol.Known: + // a superuser, who is never held, with no policy to read + return cs.sftpRefused("policy", sftpPolicyText, console.RefusedStatus) + case !cs.pol.FileTransferSettings().Enabled: + return cs.sftpRefused("file-transfer", console.SFTPOffText, console.RefusedStatus) + } + ft := cs.pol.FileTransferSettings() + home, err := inv.hooks.homeOf(a.EUID) + if err != nil || !filepath.IsAbs(home) { + return cs.sftpRefused("home", "tacctl-console: cannot find the home directory of this account", 1) + } + if a.Stdin == nil || a.Out.Stdout == nil { + return cs.sftpRefused("stream", "tacctl-console: no standard input or output", 1) + } + conn := &sftpConn{r: a.Stdin, w: sftpStdout(a.Out.Stdout)} + // A signal (sshd closing the session) ends the transfer as a closed + // connection does. + stop := context.AfterFunc(inv.ctx, func() { _ = conn.Close() }) + defer stop() + + au := cs.newSFTPAudit() + cs.log("auth.info", cs.sess.SFTPStartLine(string(cs.tier), home, ft.Quota, ft.Rate)) + err = sftpd.Serve(conn, sftpd.Config{Home: home, Quota: ft.Quota, Rate: ft.Rate, Audit: au.event}) + t := au.finish() + cs.log("auth.info", cs.sess.SFTPEndLine(t.up, t.down, t.ops, t.refused)) + status := 0 + if err != nil && inv.ctx.Err() == nil { + // the one short line of what went wrong; stdout is the protocol's and + // is closed by now + _, _ = io.WriteString(a.Out.Stderr, "tacctl-console: sftp: "+oneLine(err.Error())+"\n") + status = console.SFTPStatus + } + cs.log("auth.info", cs.sess.EndLine(console.ReasonSFTP, t.ops, status)) + if status != 0 { + return exit(status) + } + return nil +} + +// sftpRefused answers the sftp subsystem with a refusal on standard error +// (the protocol has not started), logs it as a refused command is logged, and +// ends the session with status. +func (cs *consoleSession) sftpRefused(why, text string, status int) error { + _, _ = io.WriteString(cs.inv.app.Out.Stderr, text+"\n") + cs.log("auth.warning", cs.sess.SFTPDenyLine(why)) + cs.log("auth.info", cs.sess.EndLine(console.ReasonSFTP, 0, status)) + return exit(status) +} + +// sftpStdout is the stream the protocol is written to: the file behind +// standard output. The console's own output is wrapped to take the colour out +// of what it prints (app.New), which would damage binary packets. +func sftpStdout(w io.Writer) io.Writer { + if f, ok := ui.File(w); ok { + return f + } + return w +} + +// oneLine is s as one short line for standard error. +func oneLine(s string) string { + s = strings.Join(strings.Fields(s), " ") + if len(s) > 200 { + s = s[:200] + } + return s +} + +// sftpConn is standard input and output as the one stream sftpd serves. Close +// is safe to call from the signal handler and from Serve. +type sftpConn struct { + r io.Reader + w io.Writer + once sync.Once +} + +func (c *sftpConn) Read(p []byte) (int, error) { return c.r.Read(p) } +func (c *sftpConn) Write(p []byte) (int, error) { return c.w.Write(p) } + +// Close closes the input and the output when they can be closed (the +// process's own are: a read that waits is released). +func (c *sftpConn) Close() error { + var err error + c.once.Do(func() { + if cl, ok := c.r.(io.Closer); ok { + err = cl.Close() + } + if cl, ok := c.w.(io.Closer); ok { + err = errors.Join(err, cl.Close()) + } + }) + return err +} + +// sftpTotals are what the audit of a session counted. +type sftpTotals struct { + up, down int64 + ops, refused int +} + +// sftpAudit turns the events of the server into log lines, in order, off the +// goroutines that serve the requests (each line is a 'logger' process). +type sftpAudit struct { + cs *consoleSession + ch chan sftpd.Event + done chan struct{} + t sftpTotals +} + +func (cs *consoleSession) newSFTPAudit() *sftpAudit { + au := &sftpAudit{cs: cs, ch: make(chan sftpd.Event, 256), done: make(chan struct{})} + go au.run() + return au +} + +// event queues one event for the log. +func (au *sftpAudit) event(e sftpd.Event) { au.ch <- e } + +// finish waits for the lines queued and gives the totals; no event follows. +func (au *sftpAudit) finish() sftpTotals { + close(au.ch) + <-au.done + return au.t +} + +func (au *sftpAudit) run() { + defer close(au.done) + for e := range au.ch { + priority, line := au.cs.sess.SFTPEventLine(e.Op, string(au.cs.tier), e.Path, e.To, e.Bytes, errText(e.Err)) + au.cs.log(priority, line) + au.t.ops++ + switch e.Op { + case "refused": + au.t.refused++ + case "upload": + au.t.up += e.Bytes + case "download": + au.t.down += e.Bytes + } + } +} + +// errText is the text of an error for the log line of an event, without the +// path the error names: the line carries the path in its own field, and a +// second copy (the Go text of an os error is 'open : ') would +// double the length of the field a hostile name fills. +func errText(err error) string { + if err == nil { + return "" + } + var pe *fs.PathError + var le *os.LinkError + switch { + case errors.As(err, &pe): + return pe.Op + ": " + errText(pe.Err) + case errors.As(err, &le): + return le.Op + ": " + errText(le.Err) + } + return err.Error() +} diff --git a/internal/cli/console_sftp_test.go b/internal/cli/console_sftp_test.go new file mode 100644 index 00000000..2ec34e6f --- /dev/null +++ b/internal/cli/console_sftp_test.go @@ -0,0 +1,617 @@ +package cli + +// The console's file transfer through consoleMain's seam (runConsoleWith): +// the sftp subsystem as a '-c' string, served by internal/sftpd on the +// process's streams, with a real pkg/sftp client on the other end of two +// pipes (console_sftp.go). + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "syscall" + "testing" + + "github.com/pkg/sftp" + + "github.com/rett/tacctl/internal/console" +) + +// protocolTap keeps what the console wrote to its standard output, so that a +// test can check it is nothing but SFTP packets. +type protocolTap struct { + mu sync.Mutex + buf bytes.Buffer + w *io.PipeWriter +} + +func (p *protocolTap) Write(b []byte) (int, error) { + p.mu.Lock() + p.buf.Write(b) + p.mu.Unlock() + return p.w.Write(b) +} + +func (p *protocolTap) Close() error { return p.w.Close() } + +func (p *protocolTap) bytes() []byte { + p.mu.Lock() + defer p.mu.Unlock() + return append([]byte(nil), p.buf.Bytes()...) +} + +// wholePackets reports whether b is a sequence of SFTP packets (a 4-byte +// length, then that many bytes) with nothing before, between or after them. +func wholePackets(b []byte) bool { + for len(b) > 0 { + if len(b) < 4 { + return false + } + n := int(binary.BigEndian.Uint32(b)) + if n < 1 || len(b) < 4+n { + return false + } + b = b[4+n:] + } + return true +} + +// sftpRig is the console serving the sftp subsystem to a client. +type sftpRig struct { + t *testing.T + h *harness + home string + dotenv string // the directory $HOME names, which is not the home + tap *protocolTap + in *io.PipeWriter + out *io.PipeReader + done chan int +} + +// startSFTP starts the console with '-c ' on pipes, as the account +// carol, whose home in the account database is home (not $HOME). policy is +// the answer of the root side ("": sudo fails). +func startSFTP(t *testing.T, policy, line string) *sftpRig { + t.Helper() + return startSFTPCtx(t, context.Background(), policy, line) +} + +func startSFTPCtx(t *testing.T, ctx context.Context, policy, line string) *sftpRig { + t.Helper() + return startSFTPSetup(t, ctx, policy, line, nil) +} + +// startSFTPSetup is startSFTPCtx with a change to the harness (its fake +// commands) before the console starts. +func startSFTPSetup(t *testing.T, ctx context.Context, policy, line string, setup func(*harness)) *sftpRig { + t.Helper() + parallel(t) + h, _ := consoleHarness(t, "", "carol tac-users tac-readonly", policy, "-c", line) + if setup != nil { + setup(h) + } + r := &sftpRig{t: t, h: h, home: t.TempDir(), done: make(chan int, 1)} + r.dotenv = h.app.Env.Get("HOME") + h.hooks.homeOfUID = func(uid int) (string, error) { + if uid != 1000 { + return "", errors.New("unexpected uid") + } + return r.home, nil + } + inR, inW := io.Pipe() + outR, outW := io.Pipe() + r.in, r.out = inW, outR + r.tap = &protocolTap{w: outW} + h.app.Stdin = inR + h.app.Out.Stdout = r.tap + go func() { + r.done <- exitCode(runConsoleWith(ctx, h.app, BuildInfo{Version: "0.2.1-test"}, []string{"-c", line}, h.hooks), h.app.Out) + }() + return r +} + +// client connects an SFTP client to the console. +func (r *sftpRig) client() *sftp.Client { + r.t.Helper() + c, err := sftp.NewClientPipe(r.out, r.in) + if err != nil { + r.t.Fatal(err) + } + return c +} + +// finish closes the client, waits for the console to end and gives its status. +func (r *sftpRig) finish(c *sftp.Client) int { + r.t.Helper() + if c != nil { + _ = c.Close() + } + return <-r.done +} + +func sftpPolicy(ft console.FileTransfer) string { + return strings.TrimSuffix(consoleTestPolicy, "\n") + console.FileTransferFields(ft) + "\n" +} + +func put(t *testing.T, c *sftp.Client, name, content string) error { + t.Helper() + f, err := c.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC) + if err != nil { + return err + } + if _, err := f.Write([]byte(content)); err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +func get(t *testing.T, c *sftp.Client, name string) (string, error) { + t.Helper() + f, err := c.Open(name) + if err != nil { + return "", err + } + defer func() { _ = f.Close() }() + b, err := io.ReadAll(f) + return string(b), err +} + +func TestConsoleSFTPServes(t *testing.T) { + r := startSFTP(t, sftpPolicy(console.FileTransfer{Enabled: true}), "/usr/lib/openssh/sftp-server") + // The home of the account database is the root, not $HOME's directory. + if err := os.WriteFile(filepath.Join(r.home, "existing.txt"), []byte("old"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(r.dotenv, "decoy.txt"), []byte("decoy"), 0o600); err != nil { + t.Fatal(err) + } + c := r.client() + infos, err := c.ReadDir("/") + if err != nil { + t.Fatal(err) + } + var names []string + for _, fi := range infos { + names = append(names, fi.Name()) + } + if !slices.Equal(names, []string{"existing.txt"}) { + t.Errorf("the root lists %q, want the passwd home's files only", names) + } + if err := put(t, c, "up.txt", "hello"); err != nil { + t.Fatalf("upload: %v", err) + } + if b, err := os.ReadFile(filepath.Join(r.home, "up.txt")); err != nil || string(b) != "hello" { + t.Errorf("the uploaded file: %q %v", b, err) + } + if got, err := get(t, c, "/existing.txt"); err != nil || got != "old" { + t.Errorf("download: %q %v", got, err) + } + if err := c.Mkdir("d"); err != nil { + t.Errorf("mkdir: %v", err) + } + if err := c.Rename("up.txt", "d/moved.txt"); err != nil { + t.Errorf("rename: %v", err) + } + if err := c.Remove("existing.txt"); err != nil { + t.Errorf("remove: %v", err) + } + if status := r.finish(c); status != 0 { + t.Fatalf("status %d, stderr %q", status, r.h.err.String()) + } + if r.h.err.String() != "" { + t.Errorf("stderr %q", r.h.err.String()) + } + if !wholePackets(r.tap.bytes()) { + t.Errorf("standard output holds more than SFTP packets: %q", r.tap.bytes()) + } + // Run as the user: no sudo for the transfer but the policy question. + if n := r.h.runner.Count("sudo"); n != 1 { + t.Errorf("sudo ran %d times, want the policy question only: %q", n, r.h.runner.Argvs()) + } + log := consoleLog(r.h.runner) + want := []string{ + "auth.info console start session=", + "auth.info console sftp start session=", + "auth.info console sftp upload session=", + "auth.info console sftp download session=", + "auth.info console sftp mkdir session=", + "auth.info console sftp rename session=", + "auth.info console sftp delete session=", + "auth.info console sftp end session=", + "auth.info console end session=", + } + if len(log) != len(want) { + t.Fatalf("log:\n%s", strings.Join(log, "\n")) + } + for i, w := range want { + if !strings.HasPrefix(log[i], w) { + t.Errorf("log[%d] = %q, want it to start with %q", i, log[i], w) + } + } + for _, frag := range []struct { + i int + text string + }{ + {0, "mode=sftp"}, + {1, " user=carol tier=readonly from=192.0.2.9 home=" + `"` + r.home + `"` + " quota=unlimited rate=off"}, + {2, ` user=carol tier=readonly path="/up.txt" bytes=5`}, + {3, ` user=carol tier=readonly path="/existing.txt" bytes=3`}, + {4, ` user=carol tier=readonly path="/d"`}, + {5, ` user=carol tier=readonly path="/up.txt" to="/d/moved.txt"`}, + {6, ` user=carol tier=readonly path="/existing.txt"`}, + {7, " up=5 down=3 ops=5 refused=0"}, + {8, " user=carol reason=sftp lines=5 status=0"}, + } { + if !strings.Contains(log[frag.i], frag.text) { + t.Errorf("log[%d] = %q, want it to contain %q", frag.i, log[frag.i], frag.text) + } + } +} + +// logger failing is not a reason to stop a transfer: the warning is on +// standard error, standard output stays the protocol's, and the transfer +// goes on unaudited (the same as for a command of the console). +func TestConsoleSFTPLoggerDownKeepsStdoutTheProtocol(t *testing.T) { + r := startSFTPSetup(t, context.Background(), sftpPolicy(console.FileTransfer{Enabled: true}), "internal-sftp", + func(h *harness) { h.runner.Missing("logger") }) + c := r.client() + if err := put(t, c, "up.txt", "hello"); err != nil { + t.Fatalf("upload: %v", err) + } + if got, err := get(t, c, "up.txt"); err != nil || got != "hello" { + t.Errorf("download: %q %v", got, err) + } + if status := r.finish(c); status != 0 { + t.Fatalf("status %d, stderr %q", status, r.h.err.String()) + } + if b, err := os.ReadFile(filepath.Join(r.home, "up.txt")); err != nil || string(b) != "hello" { + t.Errorf("the uploaded file: %q %v", b, err) + } + if !wholePackets(r.tap.bytes()) { + t.Errorf("standard output holds more than SFTP packets: %q", r.tap.bytes()) + } + if !strings.Contains(r.h.err.String(), "The audit line was not written (logger: not found); the command continues.") { + t.Errorf("stderr lacks the warning: %q", r.h.err.String()) + } +} + +func TestConsoleSFTPQuotaRateAndTheStartLine(t *testing.T) { + r := startSFTP(t, sftpPolicy(console.FileTransfer{Enabled: true, Quota: 100, Rate: 1 << 30}), "internal-sftp") + c := r.client() + if err := put(t, c, "ok", strings.Repeat("a", 100)); err != nil { + t.Fatalf("a file that fits: %v", err) + } + err := put(t, c, "over", "b") + if err == nil || !strings.Contains(err.Error(), "quota") { + t.Errorf("one byte over the quota: %v", err) + } + if status := r.finish(c); status != 0 { + t.Fatalf("status %d", status) + } + log := strings.Join(consoleLog(r.h.runner), "\n") + for _, want := range []string{ + " quota=100 rate=1G", + "auth.warning console sftp DENY session=", + ` user=carol tier=readonly path="/over"`, " reason=quota", + } { + if !strings.Contains(log, want) { + t.Errorf("log lacks %q:\n%s", want, log) + } + } + if !strings.Contains(log, "refused=1") { + t.Errorf("the end line counts no refusal:\n%s", log) + } +} + +func TestConsoleSFTPRefusesSSHAndAudits(t *testing.T) { + r := startSFTP(t, sftpPolicy(console.FileTransfer{Enabled: true}), "sftp-server") + if err := os.Mkdir(filepath.Join(r.home, ".ssh"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(r.home, ".ssh", "authorized_keys"), []byte("key"), 0o600); err != nil { + t.Fatal(err) + } + c := r.client() + infos, err := c.ReadDir("/") + if err != nil { + t.Fatal(err) + } + for _, fi := range infos { + if fi.Name() == ".ssh" { + t.Error(".ssh is listed") + } + } + if _, err := get(t, c, ".ssh/authorized_keys"); err == nil { + t.Error(".ssh/authorized_keys was read") + } + if err := put(t, c, ".ssh/authorized_keys", "mine"); err == nil { + t.Error(".ssh/authorized_keys was written") + } + if status := r.finish(c); status != 0 { + t.Fatalf("status %d", status) + } + if b, _ := os.ReadFile(filepath.Join(r.home, ".ssh", "authorized_keys")); string(b) != "key" { + t.Errorf("authorized_keys is %q", b) + } + log := strings.Join(consoleLog(r.h.runner), "\n") + if !strings.Contains(log, `auth.warning console sftp DENY session=`) || !strings.Contains(log, ` tier=readonly path="/.ssh/authorized_keys"`) || + !strings.Contains(log, "reason=.ssh") { + t.Errorf("the refusals are not audited:\n%s", log) + } +} + +func TestConsoleSFTPAuditSanitisesNames(t *testing.T) { + r := startSFTP(t, sftpPolicy(console.FileTransfer{Enabled: true}), "internal-sftp") + c := r.client() + evil := "a\nconsole sftp DENY session=forged\x1b[31m\"x" + if err := put(t, c, evil, "x"); err != nil { + t.Fatalf("upload: %v", err) + } + long := strings.Repeat("n", 230) + if err := c.Mkdir(long); err != nil { + t.Fatalf("mkdir of a long name: %v", err) + } + if status := r.finish(c); status != 0 { + t.Fatalf("status %d", status) + } + var upload, mkdir string + for _, l := range consoleLog(r.h.runner) { + switch { + case strings.Contains(l, "console sftp upload"): + upload = l + case strings.Contains(l, "console sftp mkdir"): + mkdir = l + } + } + if !strings.Contains(upload, ` path="/a\nconsole sftp DENY session=forged\x1b[31m\"x" bytes=1`) { + t.Errorf("the upload line is not escaped: %q", upload) + } + for _, l := range consoleLog(r.h.runner) { + if strings.ContainsAny(l, "\n\r\x1b") { + t.Errorf("a control character reached the log: %q", l) + } + } + if !strings.Contains(mkdir, ` path="/`+strings.Repeat("n", console.NameMax-1)+`"... `) && !strings.HasSuffix(mkdir, ` path="/`+strings.Repeat("n", console.NameMax-1)+`"...`) { + t.Errorf("the long name is not cut: %q", mkdir) + } +} + +// A failed request on a hostile long name is one line that keeps its +// trailing fields (logger cuts a line at 1 KiB), and the error text does not +// repeat the path. +func TestConsoleSFTPAuditLineOfAFailedLongNameFits(t *testing.T) { + r := startSFTP(t, sftpPolicy(console.FileTransfer{Enabled: true}), "internal-sftp") + c := r.client() + hostile := "/" + strings.Repeat("\x01", 100) + strings.Repeat("n", 100) + if err := c.Remove(hostile); err == nil { + t.Fatal("removing a file that is not there worked") + } + if err := c.Rename(hostile, hostile+"2"); err == nil { + t.Fatal("renaming a file that is not there worked") + } + if status := r.finish(c); status != 0 { + t.Fatalf("status %d", status) + } + seen := 0 + for _, l := range consoleLog(r.h.runner) { + if !strings.Contains(l, "console sftp delete") && !strings.Contains(l, "console sftp rename") { + continue + } + seen++ + if len(l) >= 1000 { + t.Errorf("%d bytes: %s", len(l), l) + } + _, errField, ok := strings.Cut(l, " error=") + if !ok || strings.Contains(errField, `\x01`) || strings.Contains(errField, "nnnn") { + t.Errorf("the error repeats the path, or is lost: %s", l) + } + } + if seen < 2 { + t.Errorf("%d event lines, want at least 2", seen) + } +} + +func TestErrTextDropsThePath(t *testing.T) { + for _, c := range []struct { + err error + want string + }{ + {nil, ""}, + {errors.New("plain"), "plain"}, + {&fs.PathError{Op: "open", Path: "/home/user/x", Err: syscall.ENOENT}, "open: no such file or directory"}, + {&os.LinkError{Op: "rename", Old: "/a", New: "/b", Err: syscall.EEXIST}, "rename: file exists"}, + {fmt.Errorf("wrapped: %w", &fs.PathError{Op: "unlink", Path: "/x", Err: syscall.EACCES}), "unlink: permission denied"}, + } { + if got := errText(c.err); got != c.want { + t.Errorf("errText(%v) = %q, want %q", c.err, got, c.want) + } + } +} + +func TestConsoleSFTPPolicyOff(t *testing.T) { + for name, policy := range map[string]string{ + "not enabled": consoleTestPolicy, + "quota only": strings.TrimSuffix(consoleTestPolicy, "\n") + " ft_quota=100 ft_rate=100\n", + "enabled: no": strings.TrimSuffix(consoleTestPolicy, "\n") + " file_transfer=no\n", + } { + for _, line := range []string{"/usr/lib/openssh/sftp-server", "internal-sftp", "sftp-server -l INFO"} { + h, run := consoleHarness(t, "", "carol tac-users tac-readonly", policy, "-c", line) + if code := exitCode(run(), h.app.Out); code != console.RefusedStatus { + t.Errorf("%s %q: status %d", name, line, code) + } + if h.err.String() != console.SFTPOffText+"\n" || h.out.String() != "" { + t.Errorf("%s %q: stderr %q stdout %q", name, line, h.err.String(), h.out.String()) + } + log := consoleLog(h.runner) + if len(log) != 3 || !strings.Contains(log[0], "mode=sftp") || + !strings.Contains(log[1], "auth.warning console DENY session=") || !strings.HasSuffix(log[1], " user=carol reason=file-transfer subsystem=sftp") || + !strings.HasSuffix(log[2], "reason=sftp lines=0 status=126") { + t.Errorf("%s %q: log %q", name, line, log) + } + } + } + // The text says what is off and who can switch it on. + for _, want := range []string{"not enabled", "administrator", "switch it on"} { + if !strings.Contains(console.SFTPOffText, want) { + t.Errorf("the refusal does not say %q: %q", want, console.SFTPOffText) + } + } +} + +func TestConsoleSFTPHeldToAPasswordChange(t *testing.T) { + pol := strings.TrimSuffix(sftpPolicy(console.FileTransfer{Enabled: true}), "\n") + " password_change=yes\n" + h, run := consoleHarness(t, "", "carol tac-users tac-readonly", pol, "-c", "internal-sftp") + if code := exitCode(run(), h.app.Out); code != console.RefusedStatus { + t.Errorf("status %d", code) + } + if h.err.String() != sftpPasswordText+"\n" || h.out.String() != "" { + t.Errorf("stderr %q stdout %q", h.err.String(), h.out.String()) + } + log := consoleLog(h.runner) + if len(log) != 3 || !strings.HasSuffix(log[1], " reason=password-change subsystem=sftp") { + t.Errorf("log %q", log) + } +} + +func TestConsoleSFTPNoHome(t *testing.T) { + policy := sftpPolicy(console.FileTransfer{Enabled: true}) + for name, home := range map[string]func(int) (string, error){ + "no account": func(int) (string, error) { return "", errors.New("no such user") }, + "relative home": func(int) (string, error) { return "home/carol", nil }, + "empty home": func(int) (string, error) { return "", nil }, + } { + h, run := consoleHarness(t, "", "carol tac-users tac-readonly", policy, "-c", "internal-sftp") + h.hooks.homeOfUID = home + if code := exitCode(run(), h.app.Out); code != 1 { + t.Errorf("%s: status %d", name, code) + } + if !strings.Contains(h.err.String(), "cannot find the home directory") || h.out.String() != "" { + t.Errorf("%s: stderr %q stdout %q", name, h.err.String(), h.out.String()) + } + if log := consoleLog(h.runner); len(log) != 3 || !strings.HasSuffix(log[1], " reason=home subsystem=sftp") { + t.Errorf("%s: log %q", name, log) + } + } +} + +// Everything but the subsystem keeps the old refusal, whatever the policy. +func TestConsoleSFTPOnlyTheSubsystem(t *testing.T) { + policy := sftpPolicy(console.FileTransfer{Enabled: true}) + for _, line := range []string{ + "scp -f x", "scp -t .", "scp -O -f x", "rsync --server -e.LsfxC . .", "bash", "sh -c id", "/bin/sh", + "internal-sftp; id", "sftp-server && id", "/usr/lib/openssh/sftp-server `id`", "$(sftp-server)", "sftp", "sftp-server\nid", + } { + h, run := consoleHarness(t, "", "carol tac-users tac-readonly", policy, "-c", line) + if code := exitCode(run(), h.app.Out); code != console.RefusedStatus { + t.Errorf("%q: status %d", line, code) + } + if h.err.String() != console.RefusedText+"\n" || h.out.String() != "" { + t.Errorf("%q: stderr %q stdout %q", line, h.err.String(), h.out.String()) + } + if h.runner.Count("sudo") != 0 { + t.Errorf("%q: ran %q", line, h.runner.Argvs()) + } + if log := consoleLog(h.runner); len(log) != 3 || !strings.Contains(log[0], "mode=command") || + !strings.Contains(log[1], " reason=command ") { + t.Errorf("%q: log %q", line, log) + } + } + // The refusal's text no longer says that file transfer is unavailable, and + // says what the console does serve. + if strings.Contains(console.RefusedText, "not available") || !strings.Contains(console.RefusedText, "SFTP") || + !strings.Contains(console.RefusedText, "OpenSSH 9") { + t.Errorf("RefusedText: %q", console.RefusedText) + } +} + +// A client that ends the connection ends the session with status 0, the one +// that sends nothing keeps it open (the console's idle time is no part of it), +// and a protocol error is a short line on standard error and status 1. +func TestConsoleSFTPEnds(t *testing.T) { + policy := sftpPolicy(console.FileTransfer{Enabled: true}) + t.Run("closed input", func(t *testing.T) { + r := startSFTP(t, policy, "internal-sftp") + if status := r.finish(r.client()); status != 0 { + t.Errorf("status %d, stderr %q", status, r.h.err.String()) + } + if log := consoleLog(r.h.runner); len(log) != 4 || !strings.HasSuffix(log[2], " up=0 down=0 ops=0 refused=0") { + t.Errorf("log %q", log) + } + }) + t.Run("silent client", func(t *testing.T) { + r := startSFTP(t, policy, "internal-sftp") + select { + case status := <-r.done: + t.Fatalf("the session ended by itself with status %d", status) + default: + } + _ = r.in.Close() + if status := <-r.done; status != 0 { + t.Errorf("status %d, stderr %q", status, r.h.err.String()) + } + }) + t.Run("protocol error", func(t *testing.T) { + r := startSFTP(t, policy, "internal-sftp") + // a packet that claims more bytes than arrive, then the end + go func() { + _, _ = r.in.Write([]byte{0, 0, 0, 40, 1, 0, 0}) + _ = r.in.Close() + }() + go func() { _, _ = io.Copy(io.Discard, r.out) }() + status := <-r.done + if status != console.SFTPStatus { + t.Errorf("status %d", status) + } + msg := r.h.err.String() + if !strings.HasPrefix(msg, "tacctl-console: sftp: ") || strings.Count(msg, "\n") != 1 || len(msg) > 260 { + t.Errorf("stderr %q", msg) + } + }) + t.Run("cancelled", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + r := startSFTPCtx(t, ctx, policy, "internal-sftp") + c := r.client() + if _, err := c.ReadDir("/"); err != nil { + t.Fatal(err) + } + // a signal (sshd closing the session) ends the transfer like a closed connection + cancel() + if status := <-r.done; status != 0 { + t.Errorf("status %d, stderr %q", status, r.h.err.String()) + } + }) +} + +// Without an answer from the root side the transfer is not served: a caller +// who is no superuser is held as the console holds every line, a superuser +// (who is never held) is told the policy could not be read. +func TestConsoleSFTPWithoutAPolicyAnswer(t *testing.T) { + for _, c := range []struct { + groups, text, why string + }{ + {"carol tac-users tac-readonly", sftpUnknownText, "password-change"}, + {"carol tac-users", sftpUnknownText, "password-change"}, + {"carol tac-users tac-superuser", sftpPolicyText, "policy"}, + } { + h, run := consoleHarness(t, "", c.groups, "", "-c", "internal-sftp") + if code := exitCode(run(), h.app.Out); code != console.RefusedStatus { + t.Errorf("%s: status %d", c.groups, code) + } + if h.err.String() != c.text+"\n" || h.out.String() != "" { + t.Errorf("%s: stderr %q stdout %q", c.groups, h.err.String(), h.out.String()) + } + if log := consoleLog(h.runner); len(log) != 3 || !strings.HasSuffix(log[1], " reason="+c.why+" subsystem=sftp") { + t.Errorf("%s: log %q", c.groups, log) + } + } +} diff --git a/internal/cli/console_show.go b/internal/cli/console_show.go index f90a8ae1..ad42d66a 100644 --- a/internal/cli/console_show.go +++ b/internal/cli/console_show.go @@ -1,6 +1,7 @@ package cli import ( + "slices" "strconv" "strings" @@ -44,6 +45,13 @@ func (inv *invocation) consoleShow(args []string) error { inv.echo(" " + string(t) + ": " + systemShellState(pol, t)) } inv.echo("") + inv.echo("File transfer (off by default; a user's own setting wins over the tier's):") + for _, t := range console.Tiers { + q, qFrom := pol.FileTransferQuota("", t) + r, rFrom := pol.FileTransferRate("", t) + inv.echo(" " + string(t) + ": " + fileTransferState(pol, t) + ", quota " + console.QuotaWord(q) + fromDefault(qFrom) + ", rate " + console.RateWord(r) + fromDefault(rFrom)) + } + inv.echo("") consoleUsers, listed, err := inv.consoleUsersTable(pol) if err != nil { @@ -55,6 +63,14 @@ func (inv *invocation) consoleShow(args []string) error { return inv.consoleServerSection(pol, consoleUsers) } +// fromDefault marks a value that is the built-in one. +func fromDefault(from string) string { + if from == "default" { + return " (default)" + } + return "" +} + // listMaxWord is the list-max setting as 'console show' prints it. func listMaxWord(n int) string { if n == console.ListMaxNever { @@ -89,7 +105,7 @@ func (inv *invocation) consoleUsersTable(pol *console.Policy) (users []string, l return nil, false, err } title := "Users of " + e.Name + " (scope " + e.Scope + ")" - tb := ui.NewTable(title, ui.Left("USERNAME"), ui.Left("TIER"), ui.Left("SHELL"), ui.Left("WHY"), ui.Left("SYSTEM SHELL")) + tb := ui.NewTable(title, ui.Left("USERNAME"), ui.Left("TIER"), ui.Left("SHELL"), ui.Left("WHY"), ui.Left("SYSTEM SHELL"), ui.Left("FILE TRANSFER"), ui.Left("QUOTA"), ui.Left("RATE")) seen := map[string]bool{} rows := m.LinuxUsers(e.Scope) for _, r := range rows { @@ -103,7 +119,14 @@ func (inv *invocation) consoleUsersTable(pol *console.Policy) (users []string, l } seen[name] = true on, sysWhy := pol.SystemShellWhy(name, tr) - tb.Add(name, string(tr), shell, d.Why, map[bool]string{true: "enabled", false: "disabled"}[on]+" ("+sysWhy+")") + ft := pol.FileTransfer(name, tr) + ftOn, ftWhy := pol.FileTransferWhy(name, tr) + quota, rate := "-", "-" + if ft.Enabled { + quota, rate = console.QuotaWord(ft.Quota), console.RateWord(ft.Rate) + } + tb.Add(name, string(tr), shell, d.Why, map[bool]string{true: "enabled", false: "disabled"}[on]+" ("+sysWhy+")", + map[bool]string{true: "enabled", false: "disabled"}[ftOn]+" ("+ftWhy+")", quota, rate) } if tb.Len() == 0 { inv.echoE(ui.Bold + title + ui.NC) @@ -121,6 +144,15 @@ func (inv *invocation) consoleUsersTable(pol *console.Policy) (users []string, l if len(stray) > 0 { inv.echo("System-shell settings of users that have no account here: " + strings.Join(stray, ", ")) } + stray = nil + for _, u := range fileTransferSettingUsers(pol.File) { + if !seen[u] { + stray = append(stray, u) + } + } + if len(stray) > 0 { + inv.echo("File transfer settings of users that have no account here: " + strings.Join(stray, ", ")) + } return users, true, nil } @@ -151,16 +183,25 @@ func (inv *invocation) consoleServerSection(pol *console.Policy, consoleUsers [] problems = append(problems, "sshd's drop-in "+p.SSHDDropIn+" is missing") } probe := inv.consoleProbeUsers(pol, consoleUsers) + sftpChecked, sftpCmd := false, "" for _, u := range probe { st, err := console.SSHDCheck(inv.ctx, inv.app.Runner, u) if err != nil { inv.echo(" sshd for " + u + ": could not be checked: " + strings.Join(msgs(err), " ")) continue } + if !sftpChecked { + // sshd's subsystems are global (a Match block cannot define one), + // so the first answer is every user's + sftpChecked, sftpCmd = true, st.SFTP + } inv.echo(" sshd for " + u + ": allowtcpforwarding " + st.TCPForwarding + ", allowagentforwarding " + st.AgentForwarding + ", forcecommand " + dash(st.ForceCommand) + ", pubkeyauthentication " + dash(st.PubkeyAuth) + sshdGatewayPorts(st)) problems = append(problems, st.Problems(inv.userAgent(pol, u), inv.userForwards(pol, u), pol.GatewayPorts(), inv.app.Paths.ConsoleCommand)...) } + if sftpChecked { + inv.sftpSubsystemNotice(pol, sftpCmd, nil) + } problems = append(problems, inv.consoleFirstValueHint(pol, probe, problems)...) if len(problems) > 0 { inv.echoE(ui.Red + "WARNING: a console user can do more over ssh than the console allows (forward ports past the registry, run programs or sftp, log in by key): " + @@ -180,3 +221,18 @@ func userCSV(l []string) string { } return strings.Join(l, ", ") } + +// fileTransferSettingUsers are the users with any file transfer setting of +// their own (the switch, a quota or a rate), sorted. +func fileTransferSettingUsers(f *console.File) []string { + var out []string + for _, l := range [][]string{f.FileTransferUserNames(), f.FileTransferQuotaUserNames(), f.FileTransferRateUserNames()} { + for _, u := range l { + if !slices.Contains(out, u) { + out = append(out, u) + } + } + } + slices.Sort(out) + return out +} diff --git a/internal/cli/console_test.go b/internal/cli/console_test.go index f2d18e14..3edd003a 100644 --- a/internal/cli/console_test.go +++ b/internal/cli/console_test.go @@ -100,10 +100,10 @@ func TestConsoleShowDefaults(t *testing.T) { "System shell (the console's own word, for the tiers and users that have it):\n" + " readonly: disabled\n operator: disabled\n engineer: disabled (never)\n superuser: enabled (always)\n", "Users of authsrv (scope lab)\n", - " USERNAME TIER SHELL WHY SYSTEM SHELL\n", - " alice superuser console managed user enabled (always)\n", - " bob operator console managed user disabled (tier operator)\n", - " carol readonly console managed user disabled (tier readonly)\n", + " USERNAME TIER SHELL WHY SYSTEM SHELL", + " alice superuser console managed user enabled (always)", + " bob operator console managed user disabled (tier operator)", + " carol readonly console managed user disabled (tier readonly)", sb.consoleCommand() + ": missing", "does not list the console", "sshd drop-in " + sb.path("sshd_config.d", "tacctl-console.conf") + ": missing", } { if !strings.Contains(out, want) { @@ -237,9 +237,9 @@ func TestConsoleIgnoresStoredSwitches(t *testing.T) { sb.write("state/console.yaml", old, 0o600) out := sb.con("show") for _, w := range []string{ - " alice superuser console managed user enabled (always)\n", - " bob operator console managed user disabled (tier operator)\n", - " carol readonly console managed user disabled (tier readonly)\n", + " alice superuser console managed user enabled (always)", + " bob operator console managed user disabled (tier operator)", + " carol readonly console managed user disabled (tier readonly)", } { if !strings.Contains(out, w) { t.Errorf("show lacks %q:\n%s", w, out) @@ -445,7 +445,7 @@ func TestConsolePolicyLinePerTier(t *testing.T) { } const tail = " ssh_escape=no agent=no" for _, c := range []struct{ user, group, want string }{ - {"alice", "superuser", "shell=console idle=30 system_shell=yes system_shell_path=/bin/bash" + tail + " forward=yes tier=superuser list_max=40 space_completion=yes color=auto"}, + {"alice", "superuser", "shell=console idle=30 system_shell=yes system_shell_path=/bin/bash" + tail + " forward=yes tier=superuser list_max=40 space_completion=yes color=auto file_transfer=yes ft_quota=0 ft_rate=0"}, {"bob", "operator", "shell=console idle=30 system_shell=no system_shell_path=/bin/bash" + tail + " forward=no tier=operator list_max=40 space_completion=yes color=auto"}, {"carol", "readonly", "shell=console idle=30 system_shell=no system_shell_path=/bin/bash" + tail + " forward=no tier=readonly list_max=40 space_completion=yes color=auto"}, } { @@ -495,14 +495,14 @@ func TestConsolePolicyLinePerTier(t *testing.T) { t.Errorf("bob after carol's setting: %q", got) } sb.con("space-completion", "off") - if got := policy("alice", "superuser"); !strings.HasSuffix(got, " list_max=40 space_completion=no color=auto") { + if got := policy("alice", "superuser"); !strings.HasSuffix(got, " list_max=40 space_completion=no color=auto file_transfer=yes ft_quota=0 ft_rate=0") { t.Errorf("after space-completion off: %q", got) } sb.con("space-completion", "on") // The colour and the list threshold of 0.2.20 are in the line. sb.con("color", "on") sb.con("list-max", "-3") - if got := policy("alice", "superuser"); !strings.HasSuffix(got, " list_max=-1 space_completion=yes color=on") { + if got := policy("alice", "superuser"); !strings.HasSuffix(got, " list_max=-1 space_completion=yes color=on file_transfer=yes ft_quota=0 ft_rate=0") { t.Errorf("after color on and list-max -3: %q", got) } sb.con("color", "auto") @@ -563,7 +563,7 @@ func TestConsoleEngineerHasTheConsole(t *testing.T) { sb.write("state/tacctl.yaml", "tier:\n operator: engineer\n", 0o600) sb.write("state/console.yaml", "version: 1\ntiers: {readonly: enable, operator: enable, engineer: disable, superuser: enable}\nusers: {bob: disable}\n", 0o600) out := sb.con("show") - if w := " bob engineer console managed user disabled (never)\n"; !strings.Contains(out, w) { + if w := " bob engineer console managed user disabled (never)"; !strings.Contains(out, w) { t.Errorf("show lacks %q:\n%s", w, out) } out = plain(sb.cfgRun("", []string{"_console-policy"}, func(r *fake.Runner) { @@ -754,9 +754,9 @@ func TestConsoleSystemShellPerUser(t *testing.T) { } show := sb.con("show") for _, w := range []string{ - " alice superuser console managed user enabled (always)\n", - " bob operator console managed user disabled (user setting)\n", - " carol readonly console managed user enabled (user setting)\n", + " alice superuser console managed user enabled (always)", + " bob operator console managed user disabled (user setting)", + " carol readonly console managed user enabled (user setting)", } { if !strings.Contains(show, w) { t.Errorf("show lacks %q:\n%s", w, show) @@ -1027,7 +1027,7 @@ func TestSystemShellEnableIsForTheTierItWasSetFor(t *testing.T) { if out := sb.con("system-shell"); !strings.Contains(out, " bob: enabled ("+stale+")\n") { t.Errorf("listing:\n%s", out) } - if out := sb.con("show"); !strings.Contains(out, " bob readonly console managed user disabled (tier readonly; "+stale+")\n") { + if out := sb.con("show"); !strings.Contains(out, " bob readonly console managed user disabled (tier readonly; "+stale+")") { t.Errorf("show:\n%s", out) } if got := strings.TrimSpace(sb.con("system-shell", "user", "bob")); got != "disabled (tier readonly; "+stale+")" { diff --git a/internal/cli/device_support_bundle_test.go b/internal/cli/device_support_bundle_test.go index 2ad3cbbf..d2e5555f 100644 --- a/internal/cli/device_support_bundle_test.go +++ b/internal/cli/device_support_bundle_test.go @@ -211,10 +211,21 @@ func TestSupportBundleFolderThatLeavesTheHome(t *testing.T) { } // An IOS device that scrolls the echo of the long identity-lines command -// leaves none of it in the file, and the model names and serial numbers of +// (on lines, as the tail only, or redrawn in place) leaves none of it in the +// file, and the model names and serial numbers of // the inventory are told apart. func TestSupportBundleIOSHasNoEchoOfTheCommandAndKeepsModels(t *testing.T) { - b := newPullBox(t, fakedev.WithWrappedEcho(72)) + for name, opt := range map[string]fakedev.Option{ + "lines": fakedev.WithWrappedEcho(72), + "tail": fakedev.WithTailEcho(72), + "redrawn": fakedev.WithRedrawnEcho(72), + } { + t.Run(name, func(t *testing.T) { iosEchoBundle(t, opt) }) + } +} + +func iosEchoBundle(t *testing.T, opt fakedev.Option) { + b := newPullBox(t, opt) if err := os.WriteFile(filepath.Join(b.dir, "prompt"), []byte("lab-c#"), 0o644); err != nil { t.Fatal(err) } diff --git a/internal/cli/help_text.go b/internal/cli/help_text.go index 578a7202..14ceab72 100644 --- a/internal/cli/help_text.go +++ b/internal/cli/help_text.go @@ -25,7 +25,7 @@ Commands: --yes Answer yes to the confirmations upgrade [--branch ] Pull latest source, rebuild, update scripts and every enabled backend uninstall [--yes] Remove tacctl, its backends' services and all associated files - rollback [options] Prepare the state for the release before this one (0.2.26), for 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 or 0.2.3: a dry run unless --apply + rollback [options] Prepare the state for the release before this one (0.2.27), for 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 or 0.2.3: a dry run unless --apply --apply Take a snapshot, then convert the files the target cannot read (tacctl.yaml, sudoers; for 0.2.3 also console.yaml, devices.yaml) --yes Acknowledge the warnings that --apply refuses to go on without --hosts Accepted; the hosts need nothing for this target (no host is synced) diff --git a/internal/cli/man_gen_test.go b/internal/cli/man_gen_test.go index 946042af..73202bd7 100644 --- a/internal/cli/man_gen_test.go +++ b/internal/cli/man_gen_test.go @@ -680,6 +680,7 @@ var manConsoleDocs = map[string]struct{ typ, verb, desc string }{ "settings.system_shell": {"absolute path", setWith("console system-shell path"), "The program the console's system-shell word starts."}, "settings.system_shell_tiers": {"list of tiers (not engineer)", setWith("console system-shell"), "The tiers that may start the system shell. The superuser tier always may, and is written into the list; engineer never."}, "settings.system_shell_users": {"mapping of user name to disable or enable:", setWith("console system-shell user"), "The users with a system-shell setting of their own, which wins over their tier's: enable: gives it to a user of a tier that has none, for as long as the user is in that tier (readonly or operator), and disable takes it from a user of a tier that has it. Written to the file only when a user has one."}, + "settings.file_transfer": {"mapping (tiers, users, quota, quota_users, rate, rate_users)", setWith("console file-transfer"), "The console's file transfer: the tiers that have it (tiers, the superuser tier always among them), the users with a switch of their own (users, a mapping of user name to disable or enable:), the quota of the home in bytes (quota per tier and quota_users per user: a size such as 256M, or unlimited) and the rate in bytes per second (rate and rate_users: a size, and off for a user). Off for every tier but the superuser tier by default; a user's own value wins over the tier's. Written only when something in it is not the built-in setting."}, "settings.forwarding_tiers": {"list of tiers (not engineer)", setWith("console forwarding tiers"), "The tiers whose console logins may forward X11 and TCP ports."}, "settings.gateway_ports": {"true or false", setWith("console forwarding gateway-ports"), "Whether those tiers may bind forwarded ports to an address other than loopback."}, "settings.list_max": {"integer, 1 to " + strconv.Itoa(console.MaxListMax) + ", or " + strconv.Itoa(console.ListMaxNever) + " (never ask)", setWith("console list-max"), "The number of completions the console's shell lists without asking \"Show all N?\"."}, @@ -708,6 +709,9 @@ func manConsoleKeyRows(t *testing.T) []manKeyRow { full.SpaceCompletion = false full.Color = console.ColorOn full.SetSystemShellUser("jdoe", true, tier.Operator) + if err := full.SetFileTransfer(tier.Operator, true); err != nil { + t.Fatal(err) + } all, def := load(full), load(console.Defaults()) var rows []manKeyRow add := func(key, defText string) { @@ -736,6 +740,11 @@ func manConsoleKeyRows(t *testing.T) []manKeyRow { add("settings."+sk, "absent (no user has one)") continue } + if sk == "file_transfer" { + // A mapping, written only when something in it is set. + add("settings."+sk, "absent (nothing set)") + continue + } if x, ok := dm.Get(sk); ok { d = x } else { diff --git a/internal/cli/rollback.go b/internal/cli/rollback.go index 2ed4730e..5f6123cd 100644 --- a/internal/cli/rollback.go +++ b/internal/cli/rollback.go @@ -3,7 +3,7 @@ package cli // 'tacctl rollback [--apply] [--yes] [--hosts]' (docs/plans/ // 0.2.3-plan.md D50, docs/plans/0.2.4-plan.md D73, docs/plans/ // 0.2.9-rollout-plan.md D143, docs/plans/0.2.10-plan.md): prepare tacctl's -// state for the release before this one (0.2.26), for 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, for 0.2.9 or for 0.2.3. The plan and the conversions of +// state for the release before this one (0.2.27), for 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, for 0.2.9 or for 0.2.3. The plan and the conversions of // the files are internal/lifecycle's (rollback.go); this is the command // around them: the arguments, what is printed, the snapshot and the // sudoers installer. @@ -33,7 +33,7 @@ const rollbackUsage = "Usage: tacctl rollback [--apply] [--yes] [--hos var rollbackSpec = Spec{ Flags: []Flag{{Names: []string{"--apply"}}, {Names: []string{"--yes"}}, {Names: []string{"--hosts"}}}, MinArgs: 1, MaxArgs: 1, - Args: []string{lifecycle.RollbackTarget0226 + "|" + lifecycle.RollbackTarget0225 + "|" + lifecycle.RollbackTarget0224 + "|" + lifecycle.RollbackTarget0223 + "|" + lifecycle.RollbackTarget0222 + "|" + lifecycle.RollbackTarget0221 + "|" + lifecycle.RollbackTarget0220 + "|" + lifecycle.RollbackTarget0219 + "|" + lifecycle.RollbackTarget0218 + "|" + lifecycle.RollbackTarget0217 + "|" + lifecycle.RollbackTarget0216 + "|" + lifecycle.RollbackTarget029 + "|" + lifecycle.RollbackTarget}, + Args: []string{lifecycle.RollbackTarget0227 + "|" + lifecycle.RollbackTarget0226 + "|" + lifecycle.RollbackTarget0225 + "|" + lifecycle.RollbackTarget0224 + "|" + lifecycle.RollbackTarget0223 + "|" + lifecycle.RollbackTarget0222 + "|" + lifecycle.RollbackTarget0221 + "|" + lifecycle.RollbackTarget0220 + "|" + lifecycle.RollbackTarget0219 + "|" + lifecycle.RollbackTarget0218 + "|" + lifecycle.RollbackTarget0217 + "|" + lifecycle.RollbackTarget0216 + "|" + lifecycle.RollbackTarget029 + "|" + lifecycle.RollbackTarget}, } func rollbackCmd(inv *invocation) *cobra.Command { @@ -191,6 +191,9 @@ func (inv *invocation) rollback(args []string) error { a.Conf().Reload() inv.rollbackNextSteps(version, plan.PendingFiles(), len(plan.Keys()) > 0, len(plan.ReportLimitUserNames()) > 0) + if plan.FileTransferRemoved() { + inv.rollbackFileTransferNote(version) + } if plan.FirewallTodo() { inv.rollbackFirewallNote(version, plan) } @@ -266,8 +269,11 @@ func (inv *invocation) rollbackNextSteps(version string, snapshot, keys, fields defer inv.rollbackReportLimitsNote(version) } switch version { + case lifecycle.RollbackTarget0227: + inv.rollbackNextSteps0227(version, snapshot) + return case lifecycle.RollbackTarget0226: - inv.rollbackNextSteps0226(version) + inv.rollbackNextSteps0226(version, snapshot) return case lifecycle.RollbackTarget0225: inv.rollbackNextSteps0225(version, snapshot, keys, fields) @@ -318,7 +324,7 @@ func (inv *invocation) rollbackNextSteps(version string, snapshot, keys, fields // its snapshot. It moves with each release (docs/releasing.md, The rollback // target); TestRollbackFromIsTheReleaseOfTheChangelog compares it with the // first release heading of CHANGELOG.md. -const rollbackFrom = "0.2.27" +const rollbackFrom = "0.2.28" // rollbackSnapshotNote says where the state before the rollback is, when the // apply took a snapshot (it takes none when no file of tacctl's own is @@ -333,7 +339,7 @@ func (inv *invocation) rollbackSnapshotNote(snapshot bool, tail string) { } // rollbackFirewallNote says, after a rollback that removed the break-glass -// firewall (every target but 0.2.26, 0.2.25 and 0.2.24): what went and what stays, what a hold that stands +// firewall (every target but 0.2.27, 0.2.26, 0.2.25 and 0.2.24): what went and what stays, what a hold that stands // gets from the older release, and that the setting command writes the key it // refuses. func (inv *invocation) rollbackFirewallNote(version string, plan *lifecycle.RollbackPlan) { @@ -347,7 +353,7 @@ func (inv *invocation) rollbackFirewallNote(version string, plan *lifecycle.Roll } // rollbackEmailNote says, after a rollback that removed the users' email -// addresses (every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23), where they are and how they come back, and that +// addresses (every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23), where they are and how they come back, and that // the commands that set one write the key again. func (inv *invocation) rollbackEmailNote(version, snapID string, users []string) { n := len(users) @@ -430,21 +436,40 @@ func (inv *invocation) rollbackTimeoutScaleNote(version string) { inv.echo("If one did, run 'tacctl rollback " + version + " --apply' again (it removes it).") } -// rollbackNextSteps0226 is the next steps of the rollback to 0.2.26: the -// upgrade of the tag. 0.2.26 reads every file this release writes, so the -// rollback converted nothing, took no snapshot and leaves no command to avoid: -// the limits of the stored reports and the reports in the users' homes stay, -// 0.2.26 has them. -func (inv *invocation) rollbackNextSteps0226(version string) { +// rollbackFileTransferNote says, after a rollback that removed the console's +// file transfer settings (0.2.28), that the commands that set them write what +// the older release refuses until it is installed. +func (inv *invocation) rollbackFileTransferNote(version string) { + inv.echo("") + inv.echo("Until the upgrade, do not run 'tacctl console file-transfer' with a tier, a user, a quota or a rate to set: it writes the file transfer settings again, which " + version + " refuses (its console falls back to the defaults and 'console' commands that write fail).") + inv.echo("If one did, run 'tacctl rollback " + version + " --apply' again (it removes them).") +} + +// rollbackNextSteps0227 is the next steps of the rollback to 0.2.27: the +// upgrade of the tag. 0.2.27 reads every file this release writes but the +// file transfer settings of console.yaml, so the rollback converted nothing +// else and leaves no other command to avoid: the limits of the stored reports +// and the reports in the users' homes (the PDF ones too) stay, 0.2.27 has +// them. snapshot is whether it took the snapshot, which it does only for those +// settings; the note says why 0.2.27 cannot restore it. +func (inv *invocation) rollbackNextSteps0227(version string, snapshot bool) { inv.echo("") inv.echo(ui.Bold + "Next steps" + ui.NC) inv.echo(" 1. Install " + version + " with the upgrade (see Upgrading in the README), which switches the clone in " + inv.app.Paths.Deploy + " to the tag, builds it and re-executes it:") inv.echo(" tacctl upgrade --branch " + version) inv.echo(" 2. Check it: tacctl status; tacctl config validate") + inv.rollbackSnapshotNote(snapshot, "; "+version+"'s restore puts back a console.yaml with a setting it does not know.") +} + +// rollbackNextSteps0226 is the next steps of the rollback to 0.2.26: those of +// 0.2.27, which reads the same files (0.2.26 reads every file 0.2.27 and this +// release write but the file transfer settings). +func (inv *invocation) rollbackNextSteps0226(version string, snapshot bool) { + inv.rollbackNextSteps0227(version, snapshot) } // rollbackNextSteps0225 is the next steps of the rollback to 0.2.25: the -// upgrade of the tag. 0.2.25 reads every file 0.2.26 and this release write but the +// upgrade of the tag. 0.2.25 reads every file 0.2.26, 0.2.27 and this release write but the // limits of the stored reports (rollbackReportLimitsNote, printed after these // steps, says that the reports stay in the users' homes and what to avoid), so // the rollback converted a file only when a limit was set; snapshot is whether diff --git a/internal/cli/rollback0216_test.go b/internal/cli/rollback0216_test.go index 1a6304b8..90fa38d7 100644 --- a/internal/cli/rollback0216_test.go +++ b/internal/cli/rollback0216_test.go @@ -67,7 +67,7 @@ func TestRollback0216ApplyRoundTrip(t *testing.T) { hs.expect(0, "Applying.", "") out := hs.all() for _, want := range []string{"removed 1 key", "Next steps", "tacctl upgrade --branch 0.2.16", - "do not add the 'audit' setting (audit.strict)", "holds the 0.2.27 state"} { + "do not add the 'audit' setting (audit.strict)", "holds the 0.2.28 state"} { if !strings.Contains(out, want) { t.Errorf("--apply output lacks %q:\n%s", want, out) } diff --git a/internal/cli/rollback029_test.go b/internal/cli/rollback029_test.go index 114a3d63..75309bc3 100644 --- a/internal/cli/rollback029_test.go +++ b/internal/cli/rollback029_test.go @@ -113,7 +113,7 @@ func TestRollback029ApplyRoundTrip(t *testing.T) { out := hs.all() for _, want := range []string{"Config snapshot saved to", "state/tacctl.yaml: removed 4 keys", "state/devices.yaml: removed the NETCONF service setting of 1 device", - "Next steps", "tacctl upgrade --branch 0.2.9", "holds the 0.2.27 state. Restore it with 0.2.27 only"} { + "Next steps", "tacctl upgrade --branch 0.2.9", "holds the 0.2.28 state. Restore it with 0.2.28 only"} { if !strings.Contains(out, want) { t.Errorf("--apply output lacks %q:\n%s", want, out) } diff --git a/internal/cli/rollback_email_test.go b/internal/cli/rollback_email_test.go index 7c65c6dc..23e4a1b7 100644 --- a/internal/cli/rollback_email_test.go +++ b/internal/cli/rollback_email_test.go @@ -74,7 +74,7 @@ func TestRollbackWithAnEmailWarnsSnapshotsAndRemovesTheKey(t *testing.T) { for _, want := range []string{ "The email addresses of 2 users (bob, erin) were removed from the store; " + target + " does not know the key.", "They are in snapshot " + id + ", which is kept in " + kept + " (no retention reaches it; " + target + " prunes backups/ by its own):", - "once 0.2.27 is installed again, 'tacctl backup recover " + id + " --only email' puts them back; 'tacctl backup unkeep " + id + "' removes the kept copy after that.", + "once 0.2.28 is installed again, 'tacctl backup recover " + id + " --only email' puts them back; 'tacctl backup unkeep " + id + "' removes the kept copy after that.", "do not run 'tacctl user email' or 'tacctl user add --email'"} { if !strings.Contains(out, want) { t.Errorf("--apply lacks %q:\n%s", want, out) @@ -141,7 +141,7 @@ func TestRollback0222SnapshotFollowsTheAddress(t *testing.T) { hs.run(hs.runner(), "rollback", "0.2.22", "--apply", "--yes") hs.expect(0, "Applying.", "") out := hs.all() - if hs.snapshots() != snaps+1 || strings.Contains(out, "takes no snapshot") || !strings.Contains(out, "holds the 0.2.27 state. Restore it with 0.2.27 only") { + if hs.snapshots() != snaps+1 || strings.Contains(out, "takes no snapshot") || !strings.Contains(out, "holds the 0.2.28 state. Restore it with 0.2.28 only") { t.Errorf("with an address (snapshots %d -> %d):\n%s", snaps, hs.snapshots(), out) } if o := hs.overrides(); strings.Contains(o, "email") { diff --git a/internal/cli/rollback_firewall_test.go b/internal/cli/rollback_firewall_test.go index e765ffe0..b3303bab 100644 --- a/internal/cli/rollback_firewall_test.go +++ b/internal/cli/rollback_firewall_test.go @@ -55,7 +55,7 @@ func TestRollbackRemovesTheFirewall(t *testing.T) { "run no verb that changes the holds, their device or host names, the listeners or the setting ('tacctl breakglass hold|release', 'device address', 'device|host rename', 'device rename --replace', 'backup restore', 'server listen', 'config breakglass-firewall')", "each writes the table, its rules file and the boot unit again, and the setting 0.2.23 refuses", // the key was set: the apply took a snapshot, and the next steps say where the state is - "The snapshot the rollback took first (the newest entry of 'tacctl backup list') holds the 0.2.27 state. Restore it with 0.2.27 only:", + "The snapshot the rollback took first (the newest entry of 'tacctl backup list') holds the 0.2.28 state. Restore it with 0.2.28 only:", "0.2.23's restore refuses a tacctl.yaml with a key it does not know.", } { if !strings.Contains(out, want) { diff --git a/internal/cli/rollback_reports_test.go b/internal/cli/rollback_reports_test.go index 16e31e97..11d1a473 100644 --- a/internal/cli/rollback_reports_test.go +++ b/internal/cli/rollback_reports_test.go @@ -37,7 +37,7 @@ func TestRollbackRemovesTheReportLimitsOfTheConfig(t *testing.T) { hs.run(hs.runner(), "rollback", target, "--apply") hs.expect(0, "tacctl upgrade --branch "+target, "") out = hs.all() - for _, want := range []string{"holds the 0.2.27 state", "The reports in the users' homes stay", "'tacctl config reports max-size', 'config reports max-count' or 'tacctl user reports-limit'", + for _, want := range []string{"holds the 0.2.28 state", "The reports in the users' homes stay", "'tacctl config reports max-size', 'config reports max-count' or 'tacctl user reports-limit'", target + " has no 'device reports' verbs"} { if !strings.Contains(out, want) { t.Errorf("--apply lacks %q:\n%s", want, out) @@ -108,7 +108,7 @@ func TestRollbackRemovesTheUsersReportLimits(t *testing.T) { "The own limits of the stored reports were removed from the store for 2 users; " + target + " does not know the keys:", " bob: max-size 20 MiB, max-count 50 reports", " erin: max-count no cap", "'tacctl user reports-limit max-size|max-count ' sets them again", - "holds the 0.2.27 state", "The reports in the users' homes stay"} { + "holds the 0.2.28 state", "The reports in the users' homes stay"} { if !strings.Contains(out, want) { t.Errorf("--apply lacks %q:\n%s", want, out) } diff --git a/internal/cli/rollback_target0222_test.go b/internal/cli/rollback_target0222_test.go index 6370bf5a..cfd2bbb5 100644 --- a/internal/cli/rollback_target0222_test.go +++ b/internal/cli/rollback_target0222_test.go @@ -94,8 +94,8 @@ func TestRollback0222IsToldApartFromTheOlderTargets(t *testing.T) { if !strings.Contains(hs.all(), "Until the upgrade, do not run 'tacctl device timeout-scale'") { t.Errorf("0.2.21 lacks the note:\n%s", hs.all()) } - hs.run(hs.runner(), "rollback", "0.2.27") - hs.expect(1, "", "prepares the state for 0.2.26 (the release before this one), 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21") + hs.run(hs.runner(), "rollback", "0.2.28") + hs.expect(1, "", "prepares the state for 0.2.27 (the release before this one), 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21") } // The snapshot is announced, and its state named, only when the apply takes @@ -120,7 +120,7 @@ func TestRollbackSnapshotIsSpokenOfOnlyWhenTaken(t *testing.T) { if hs.snapshots() == snaps { t.Error("no snapshot was taken") } - for _, want := range []string{"--apply takes a snapshot of the state first", "holds the 0.2.27 state. Restore it with 0.2.27 only"} { + for _, want := range []string{"--apply takes a snapshot of the state first", "holds the 0.2.28 state. Restore it with 0.2.28 only"} { if !strings.Contains(out, want) { t.Errorf("0.2.21 with a file to convert lacks %q:\n%s", want, out) } diff --git a/internal/cli/rollback_target0225_test.go b/internal/cli/rollback_target0225_test.go index 38dff702..00b4d8da 100644 --- a/internal/cli/rollback_target0225_test.go +++ b/internal/cli/rollback_target0225_test.go @@ -64,7 +64,7 @@ func TestRollback0225ConvertsNothingWithoutLimits(t *testing.T) { } // The two settings of the file go after a snapshot and need no --yes; the -// users' own limits are data and need it. The snapshot holds the 0.2.27 state +// users' own limits are data and need it. The snapshot holds the 0.2.28 state // and the note says 0.2.25 cannot restore it; the reports in the homes and the // pull records are not touched. func TestRollback0225RemovesTheLimitsAfterASnapshot(t *testing.T) { @@ -112,7 +112,7 @@ func TestRollback0225RemovesTheLimitsAfterASnapshot(t *testing.T) { hs.expect(0, "Applying.", "") out = hs.all() for _, want := range []string{"tacctl.yaml: removed 2 keys", "store.yaml: removed the report limits of 1 user", " bob: max-count 7 reports", - "holds the 0.2.27 state", "0.2.25's restore refuses a tacctl.yaml with a key it does not know and a store.yaml with a field it does not know.", + "holds the 0.2.28 state", "0.2.25's restore refuses a tacctl.yaml with a key it does not know and a store.yaml with a field it does not know.", "tacctl upgrade --branch 0.2.25", "The reports in the users' homes stay", "0.2.25 has no 'device reports' verbs"} { if !strings.Contains(out, want) { t.Errorf("--apply lacks %q:\n%s", want, out) @@ -178,7 +178,7 @@ func TestRollbackSnapshotNoteNamesWhatTheRestoreRefuses(t *testing.T) { hs.run(hs.runner(), "rollback", c.target, "--apply", "--yes") hs.expect(0, "Applying.", "") out := hs.all() - if !strings.Contains(out, "holds the 0.2.27 state") || !strings.Contains(out, c.target+c.tail) { + if !strings.Contains(out, "holds the 0.2.28 state") || !strings.Contains(out, c.target+c.tail) { t.Errorf("the note lacks %q:\n%s", c.target+c.tail, out) } if c.tail == fieldsTail && strings.Contains(out, "a tacctl.yaml with a key") { diff --git a/internal/cli/rollback_target0226_test.go b/internal/cli/rollback_target0226_test.go index be55081c..2ccf2bfb 100644 --- a/internal/cli/rollback_target0226_test.go +++ b/internal/cli/rollback_target0226_test.go @@ -9,7 +9,7 @@ import ( "github.com/rett/tacctl/internal/tier" ) -// 'tacctl rollback 0.2.26', the release before this one, on the host sandbox +// 'tacctl rollback 0.2.26' on the host sandbox // with this server enrolled. The plan's own cases are internal/lifecycle's. // rollback0226State is rollback0221State with this release's per-tier sudoers @@ -150,12 +150,10 @@ func TestRollback0226LeavesTheDropIn(t *testing.T) { hs.expect(0, "put back the per-tier sudoers drop-in 0.2.25 writes", "") } -// 0.2.26 is the release before this one; this release is not a target, and -// the refusal names 0.2.26 first. -func TestRollback0226IsTheReleaseBeforeThisOne(t *testing.T) { +// 0.2.26 is a target, with or without the "v"; it is no longer the release +// before this one (0.2.27 is, rollback_target0227_test.go). +func TestRollback0226IsATarget(t *testing.T) { hs := rollback0226State(t) - hs.run(hs.runner(), "rollback", "0.2.27") - hs.expect(1, "", "prepares the state for 0.2.26 (the release before this one), 0.2.25, 0.2.24, 0.2.23") hs.run(hs.runner(), "rollback", "v0.2.26") hs.expect(0, "Roll back to 0.2.26 (dry run)", "") } diff --git a/internal/cli/rollback_target0227_test.go b/internal/cli/rollback_target0227_test.go new file mode 100644 index 00000000..46460a93 --- /dev/null +++ b/internal/cli/rollback_target0227_test.go @@ -0,0 +1,243 @@ +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/rett/tacctl/internal/tier" +) + +// 'tacctl rollback 0.2.27', the release before this one, on the host sandbox +// with this server enrolled. The plan's own cases are internal/lifecycle's. + +// rollback0227State is rollback0221State with this release's per-tier sudoers +// drop-in, which 0.2.27 wrote too: the rollback to 0.2.27 leaves it. +func rollback0227State(t *testing.T) *hostSandbox { + t.Helper() + hs := rollback0221State(t) + hs.write("sudoers.d/tacctl-tiers", tier.Sudoers(), 0o640) + return hs +} + +// This release changed no stored file 0.2.27 reads strictly, so 0.2.27 reads +// everything: the dry run lists nothing to do and --apply converts nothing, +// even with an email address in the store, the break-glass firewall set and +// the limits of the stored reports (the settings and a user's own; the +// 0.2.25 target removes them), takes no snapshot, asks for no --yes and +// leaves a pull record, a report (a PDF one too) and the marker of the offer +// of the PDF tools byte for byte. A second run does the same. +func TestRollback0227ConvertsNothing(t *testing.T) { + hs := rollback0227State(t) + hs.step("", "user", "email", "bob", "bob@example.net") + hs.step("", "server", "name", "core-1") + hs.step("", "config", "reports", "max-size", "20Mi") + hs.step("", "config", "reports", "max-count", "0") + hs.step("", "user", "reports-limit", "bob", "max-count", "7") + hs.write("state/tacctl.yaml", hs.read("state/tacctl.yaml")+"breakglass:\n firewall: drop\n", 0o640) + record := `{"version": 1, "devices": {"sw1": {"address": "192.0.2.11", "vendor": "juniper", "serial": "SN000001", + "members": [{"id": "0", "role": "master", "model": "EX4300-48T", "serial": "SN000001", "release": "21.4R3", "status": "present", "priority": 255, "components": []}]}}} +` + hs.write("var-lib/devices-config.json", record, 0o600) + report := filepath.Join(hs.dir, "home", "alice", "reports", "devices", "inventory-20261106.txt") + if err := os.MkdirAll(filepath.Dir(report), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(report, []byte("sw1 EX4300-48T SN000001\n"), 0o600); err != nil { + t.Fatal(err) + } + pdf := filepath.Join(hs.dir, "home", "alice", "reports", "devices", "inventory-20261107.pdf") + if err := os.WriteFile(pdf, []byte("%PDF-1.7\n"), 0o600); err != nil { + t.Fatal(err) + } + hs.write("var-lib/pdf-tools-offered", "tacctl 0.2.27 offered\n", 0o644) + before := tree(t, hs.dir) + hs.run(hs.runner(), "rollback", "0.2.27", "--hosts") + hs.expect(0, "This was a dry run: nothing was changed.", "") + out := hs.all() + for _, want := range []string{"Roll back to 0.2.27 (dry run)", "nothing to remove (every key of tacctl.yaml is one 0.2.27 knows)", + "--apply converts no file of tacctl's own and takes no snapshot", + "nothing to do for 0.2.27: this release changed nothing on the enrolled hosts", "To convert the state: tacctl rollback 0.2.27 --apply"} { + if !strings.Contains(out, want) { + t.Errorf("the dry run lacks %q:\n%s", want, out) + } + } + for _, not := range []string{"remove email", "remove server", "remove breakglass", "remove reports", "firewall", "[does]", "add scope", "Warnings", "--yes", "email", "report limits", "Limits of the stored"} { + if strings.Contains(out, not) { + t.Errorf("the dry run says %q:\n%s", not, out) + } + } + if got := changedFiles(before, tree(t, hs.dir)); len(got) != 0 { + t.Errorf("the dry run changed %q", got) + } + snaps := hs.snapshots() + for i := 0; i < 2; i++ { + hs.run(hs.runner(), "rollback", "0.2.27", "--apply") + hs.expect(0, "Nothing to convert: every file is one 0.2.27 can read.", "") + out = hs.all() + if !strings.Contains(out, "tacctl upgrade --branch 0.2.27") { + t.Errorf("--apply lacks the upgrade:\n%s", out) + } + for _, not := range []string{"holds the", "took first", "Until the upgrade", "firewall is removed", "The reports in the users' homes stay", "restore refuses"} { + if strings.Contains(out, not) { + t.Errorf("--apply (run %d) says %q:\n%s", i+1, not, out) + } + } + if hs.snapshots() != snaps { + t.Errorf("run %d took a snapshot: there is nothing to convert", i+1) + } + if got := changedFiles(before, tree(t, hs.dir)); len(got) != 0 { + t.Errorf("--apply (run %d) changed %q", i+1, got) + } + } + if got := hs.read("var-lib/devices-config.json"); got != record { + t.Errorf("the pull record changed:\n%s", got) + } + if got, err := os.ReadFile(report); err != nil || string(got) != "sw1 EX4300-48T SN000001\n" { + t.Errorf("the report: %q %v", got, err) + } + if got, err := os.ReadFile(pdf); err != nil || string(got) != "%PDF-1.7\n" { + t.Errorf("the PDF report: %q %v", got, err) + } + if got := hs.read("var-lib/pdf-tools-offered"); got != "tacctl 0.2.27 offered\n" { + t.Errorf("the marker of the PDF offer: %q", got) + } + o, s := hs.overrides(), hs.store() + if !strings.Contains(s, "email:") || !strings.Contains(o, "name: core-1") || !strings.Contains(o, "firewall: drop") || + !strings.Contains(o, "max_size: 20971520") || !strings.Contains(o, "max_count: 0") || !strings.Contains(s, "reports_max_count") { + t.Errorf("a key or a field was lost:\n%s\n%s", o, s) + } +} + +// The 0.2.25 target is told apart from 0.2.27 and 0.2.26: it removes the limits of the +// stored reports, which 0.2.27 keeps. An emergency lockdown on the scope the +// enrolled host answers stays in both, and the older targets refuse it. +func TestRollback0227IsToldApartFromTheOlderTargets(t *testing.T) { + hs := rollback0227State(t) + hs.step("", "config", "reports", "max-size", "20Mi") + hs.run(hs.runner(), "rollback", "0.2.25") + hs.expect(0, "remove reports.max_size", "") + hs.run(hs.runner(), "rollback", "0.2.27") + hs.expect(0, "nothing to remove (every key of tacctl.yaml is one 0.2.27 knows)", "") + if strings.Contains(hs.all(), "remove reports.max_size") { + t.Errorf("0.2.27 removes a setting it has:\n%s", hs.all()) + } + hs.run(hs.runner(), "rollback", "0.2.26") + hs.expect(0, "nothing to remove (every key of tacctl.yaml is one 0.2.26 knows)", "") + + if reg := hs.registry(); !strings.Contains(reg, "|tacctl|") { + t.Fatalf("the enrolled host is not in the scope the lockdown names:\n%s", reg) + } + hs.write("state/tacctl.yaml", hs.read("state/tacctl.yaml")+"emergency:\n lockdown:\n tacctl:\n groups:\n - operator\n since: '2026-10-25T12:00:00+00:00'\n by: alice\n reason: drill\n", 0o640) + before := tree(t, hs.dir) + hs.run(hs.runner(), "rollback", "0.2.27", "--apply") + hs.expect(0, "Nothing to convert: every file is one 0.2.27 can read.", "") + if o := hs.overrides(); !strings.Contains(o, "lockdown:") || !strings.Contains(o, "reason: drill") || !strings.Contains(o, "max_size") { + t.Errorf("tacctl.yaml after --apply:\n%s", o) + } + if got := changedFiles(before, tree(t, hs.dir)); len(got) != 0 { + t.Errorf("the rollback to 0.2.27 changed %q", got) + } + for _, v := range []string{"0.2.22", "0.2.21"} { + hs.run(hs.runner(), "rollback", v) + hs.expect(1, "", "Scope tacctl is locked down and has enrolled hosts (authsrv)") + } +} + +// The per-tier drop-in is this release's text and 0.2.27 wrote the same, so +// it is left; the 0.2.25 target puts back its own, without the rows of +// 'device reports'. +func TestRollback0227LeavesTheDropIn(t *testing.T) { + hs := rollback0227State(t) + before := tree(t, hs.dir) + hs.run(hs.runner(), "rollback", "0.2.27", "--apply") + hs.expect(0, "Nothing to convert: every file is one 0.2.27 can read.", "") + if got := hs.read("sudoers.d/tacctl-tiers"); got != tier.Sudoers() { + t.Errorf("the tiers drop-in changed:\n%s", got) + } + if got := changedFiles(before, tree(t, hs.dir)); len(got) != 0 { + t.Errorf("--apply changed %q", got) + } + hs.run(hs.runner(), "rollback", "0.2.25") + hs.expect(0, "put back the per-tier sudoers drop-in 0.2.25 writes", "") +} + +// 0.2.27 is the release before this one; this release is not a target, and +// the refusal names 0.2.27 first. +func TestRollback0227IsTheReleaseBeforeThisOne(t *testing.T) { + hs := rollback0227State(t) + hs.run(hs.runner(), "rollback", "0.2.28") + hs.expect(1, "", "prepares the state for 0.2.27 (the release before this one), 0.2.26, 0.2.25, 0.2.24, 0.2.23") + hs.run(hs.runner(), "rollback", "v0.2.27") + hs.expect(0, "Roll back to 0.2.27 (dry run)", "") +} + +// The one thing this release writes that 0.2.27 refuses is the console's file +// transfer settings (its console.yaml reader answers "settings: unknown key"): +// the dry run lists the key, --apply takes a snapshot, removes it and nothing +// else of console.yaml, says what to avoid until the upgrade and why the +// snapshot cannot be restored by 0.2.27, and a second run converts nothing. +// With the settings unset nothing of this is said (TestRollback0227ConvertsNothing). +func TestRollback0227RemovesTheFileTransferSettings(t *testing.T) { + hs := rollback0227State(t) + hs.step("", "console", "idle-timeout", "12") + hs.step("", "console", "file-transfer", "operator", "enable") + hs.step("", "console", "file-transfer", "quota", "operator", "1G") + hs.step("", "console", "file-transfer", "user", "bob", "disable") + if y := hs.read("state/console.yaml"); !strings.Contains(y, "file_transfer:") || !strings.Contains(y, "idle_timeout: 12") { + t.Fatalf("console.yaml:\n%s", y) + } + before := tree(t, hs.dir) + hs.run(hs.runner(), "rollback", "0.2.27") + hs.expect(0, "This was a dry run: nothing was changed.", "") + out := hs.all() + for _, want := range []string{"--apply takes a snapshot of the state first", "console.yaml: take out the settings 0.2.27 does not know [does]", + "remove settings.file_transfer: tiers operator,superuser, 1 user switch, 1 quota", "0.2.27's parser rejects the file transfer settings 0.2.28 added to console.yaml; everything else is kept"} { + if !strings.Contains(out, want) { + t.Errorf("the dry run lacks %q:\n%s", want, out) + } + } + if strings.Contains(out, "Warnings") || strings.Contains(out, "--yes") { + t.Errorf("the dry run asks for --yes:\n%s", out) + } + if got := changedFiles(before, tree(t, hs.dir)); len(got) != 0 { + t.Errorf("the dry run changed %q", got) + } + snaps := hs.snapshots() + hs.run(hs.runner(), "rollback", "0.2.27", "--apply") + hs.expect(0, "", "") + out = hs.all() + for _, want := range []string{"console.yaml: removed settings.file_transfer", "tacctl upgrade --branch 0.2.27", + "Restore it with 0.2.28 only", "0.2.27's restore puts back a console.yaml with a setting it does not know", + "Until the upgrade, do not run 'tacctl console file-transfer' with a tier, a user, a quota or a rate to set"} { + if !strings.Contains(out, want) { + t.Errorf("--apply lacks %q:\n%s", want, out) + } + } + if hs.snapshots() != snaps+1 { + t.Errorf("snapshots: %d, was %d", hs.snapshots(), snaps) + } + y := hs.read("state/console.yaml") + if strings.Contains(y, "file_transfer") || !strings.Contains(y, "idle_timeout: 12") { + t.Errorf("console.yaml after --apply:\n%s", y) + } + if got := hs.read("sudoers.d/tacctl-tiers"); got != tier.Sudoers() { + t.Error("the tiers drop-in changed") + } + // a second run has nothing to convert and takes no snapshot + snaps = hs.snapshots() + hs.run(hs.runner(), "rollback", "0.2.27", "--apply") + hs.expect(0, "Nothing to convert: every file is one 0.2.27 can read.", "") + if strings.Contains(hs.all(), "Until the upgrade") || hs.snapshots() != snaps { + t.Errorf("the second run:\n%s", hs.all()) + } + // the 0.2.26 target does the same, and it names its own version + hs.step("", "console", "file-transfer", "readonly", "enable") + hs.run(hs.runner(), "rollback", "0.2.26", "--apply") + hs.expect(0, "", "") + if out = hs.all(); !strings.Contains(out, "console.yaml: removed settings.file_transfer") || !strings.Contains(out, "0.2.26's restore puts back a console.yaml") || + !strings.Contains(out, "Until the upgrade, do not run 'tacctl console file-transfer'") || !strings.Contains(out, "run 'tacctl rollback 0.2.26 --apply' again") { + t.Errorf("0.2.26:\n%s", out) + } +} diff --git a/internal/cli/rollback_test.go b/internal/cli/rollback_test.go index d04cddb9..dbe50d6a 100644 --- a/internal/cli/rollback_test.go +++ b/internal/cli/rollback_test.go @@ -306,7 +306,7 @@ func TestRollbackRoundTrip(t *testing.T) { for _, want := range []string{"Config snapshot saved to", "state/tacctl.yaml: removed 3 keys", "state/console.yaml: removed settings.password_cache", "state/devices.yaml: removed the SNMP settings of 2 devices", "sudoers.d/tacctl-tiers: rewritten with the text 0.2.3 writes", "sudoers.d/tacctl: rewritten with the text 0.2.3 writes", - "Next steps", "tacctl upgrade --branch 0.2.3", "holds the 0.2.27 state. Restore it with 0.2.27 only"} { + "Next steps", "tacctl upgrade --branch 0.2.3", "holds the 0.2.28 state. Restore it with 0.2.28 only"} { if !strings.Contains(out, want) { t.Errorf("--apply output lacks %q:\n%s", want, out) } @@ -717,7 +717,7 @@ func TestRollbackCompletion(t *testing.T) { words []string want []string }{ - {[]string{"rollback", ""}, []string{"0.2.26", "0.2.25", "0.2.24", "0.2.23", "0.2.22", "0.2.21", "0.2.20", "0.2.19", "0.2.18", "0.2.17", "0.2.16", "0.2.9", "0.2.3"}}, + {[]string{"rollback", ""}, []string{"0.2.27", "0.2.26", "0.2.25", "0.2.24", "0.2.23", "0.2.22", "0.2.21", "0.2.20", "0.2.19", "0.2.18", "0.2.17", "0.2.16", "0.2.9", "0.2.3"}}, {[]string{"rollback", "0.2.3", ""}, []string{"--apply", "--yes", "--hosts"}}, {[]string{"rollback", "0.2.3", "--apply", ""}, []string{"--yes", "--hosts"}}, {[]string{"rollback", "0.2.3", "--apply", "--yes", "--hosts", ""}, nil}, diff --git a/internal/cli/testdata/usage/top.out b/internal/cli/testdata/usage/top.out index 71aef41f..7a1b18be 100644 --- a/internal/cli/testdata/usage/top.out +++ b/internal/cli/testdata/usage/top.out @@ -11,7 +11,7 @@ Commands: --yes Answer yes to the confirmations upgrade [--branch ] Pull latest source, rebuild, update scripts and every enabled backend uninstall [--yes] Remove tacctl, its backends' services and all associated files - rollback [options] Prepare the state for the release before this one (0.2.26), for 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 or 0.2.3: a dry run unless --apply + rollback [options] Prepare the state for the release before this one (0.2.27), for 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 or 0.2.3: a dry run unless --apply --apply Take a snapshot, then convert the files the target cannot read (tacctl.yaml, sudoers; for 0.2.3 also console.yaml, devices.yaml) --yes Acknowledge the warnings that --apply refuses to go on without --hosts Accepted; the hosts need nothing for this target (no host is synced) diff --git a/internal/console/config.go b/internal/console/config.go index fbc904a6..53a373ce 100644 --- a/internal/console/config.go +++ b/internal/console/config.go @@ -14,6 +14,7 @@ import ( "bytes" "errors" "io/fs" + "maps" "os" "path/filepath" "slices" @@ -165,6 +166,31 @@ type File struct { // rejects the key, and 'tacctl rollback 0.2.3' (Text023) removes it. PasswordCacheTiers []tier.Tier PasswordCacheIdle, PasswordCacheMax int + + // The file transfer settings (settings.file_transfer, a mapping written + // only when something in it is not the built-in setting; an older release + // rejects the key, and the rollback removes it, Keys0228). They are the + // system shell's, with a quota and a rate besides, and without Closed + // tiers (filetransfer.go). + // + // FileTransferTiers are the tiers with it enabled; the superuser tier + // always has it, whatever the list says (the setter writes it in). Off for + // the others by default. + FileTransferTiers []tier.Tier + // FileTransferUsers are the users with a switch of their own (true: + // enabled, false: disabled); an enable is valid for the tier it was set + // for (FileTransferUserTiers), as the system shell's is. + FileTransferUsers map[string]bool + FileTransferUserTiers map[string]tier.Tier + // FileTransferQuota and FileTransferRate are the tiers' own values, in + // bytes (quota 0: unlimited; a tier with no entry has the built-in + // default, DefaultTierQuota, and no rate limit); the two *Users maps + // are the users' own values, which win over the tier's (quota 0: + // unlimited, rate 0: no limit). + FileTransferQuota map[tier.Tier]int64 + FileTransferRate map[tier.Tier]int64 + FileTransferQuotaUsers map[string]int64 + FileTransferRateUsers map[string]int64 } // Defaults is the file that is not there. @@ -179,9 +205,18 @@ func Defaults() *File { SystemShellUserTiers: map[string]tier.Tier{}, PasswordCacheUsers: map[string]bool{}, ForwardingTiers: []tier.Tier{tier.Superuser}, - ListMax: DefaultListMax, - SpaceCompletion: true, - Color: ColorAuto, + + FileTransferTiers: []tier.Tier{tier.Superuser}, + FileTransferUsers: map[string]bool{}, + FileTransferUserTiers: map[string]tier.Tier{}, + FileTransferQuota: map[tier.Tier]int64{}, + FileTransferRate: map[tier.Tier]int64{}, + FileTransferQuotaUsers: map[string]int64{}, + FileTransferRateUsers: map[string]int64{}, + + ListMax: DefaultListMax, + SpaceCompletion: true, + Color: ColorAuto, PasswordCacheIdle: DefaultPasswordCacheIdle, PasswordCacheMax: DefaultPasswordCacheMax, @@ -214,6 +249,13 @@ func (f *File) Clone() *File { } c.ForwardingTiers = slices.Clone(f.ForwardingTiers) c.PasswordCacheTiers = slices.Clone(f.PasswordCacheTiers) + c.FileTransferTiers = slices.Clone(f.FileTransferTiers) + c.FileTransferUsers = maps.Clone(f.FileTransferUsers) + c.FileTransferUserTiers = maps.Clone(f.FileTransferUserTiers) + c.FileTransferQuota = maps.Clone(f.FileTransferQuota) + c.FileTransferRate = maps.Clone(f.FileTransferRate) + c.FileTransferQuotaUsers = maps.Clone(f.FileTransferQuotaUsers) + c.FileTransferRateUsers = maps.Clone(f.FileTransferRateUsers) return &c } @@ -420,6 +462,9 @@ func (f *File) check(userName func(string) bool) error { return fail("settings.system_shell_users: '" + u + "' must be disable or enable:readonly|operator.") } } + if err := f.checkFileTransfer(userName); err != nil { + return err + } for u := range f.PasswordCacheUsers { if !userName(u) { return fail("settings.password_cache_users: invalid user name '" + u + "'.") @@ -604,6 +649,14 @@ func parseSettings(f *File, m *yamlpy.Map) error { return bad } f.SystemShell = s + case "file_transfer": + m, ok := v.(*yamlpy.Map) + if !ok { + return fail("settings.file_transfer must be a mapping (tiers, users, quota, quota_users, rate, rate_users).") + } + if err := parseFileTransfer(f, m); err != nil { + return err + } case "system_shell_users": switch x := v.(type) { case nil: @@ -769,6 +822,11 @@ func (f *File) doc() *yamlpy.Map { } settings.Set("password_cache_users", users) } + if !f.fileTransferDefault() { + // Only when something is not the built-in setting, so a file that + // never touched file transfer is read by every release. + settings.Set("file_transfer", f.fileTransferDoc()) + } doc := yamlpy.NewMap("version", Version) if len(f.IgnoredTiers) > 0 { tiers := yamlpy.NewMap() diff --git a/internal/console/console_test.go b/internal/console/console_test.go index 3a9f1c59..1e744b9b 100644 --- a/internal/console/console_test.go +++ b/internal/console/console_test.go @@ -594,7 +594,7 @@ func TestSSHDCheck(t *testing.T) { } const fc = "forcecommand /usr/local/bin/tacctl-console\npubkeyauthentication no\n" s, r, err := run(execx.Result{Stdout: []byte("port 22\nallowtcpforwarding no\nallowagentforwarding no\nx11forwarding no\n" + fc)}) - if err != nil || s != (SSHD{"no", "no", "/usr/local/bin/tacctl-console", "no", "no", "", ""}) || !r.Called("sshd", "-T", "-C", "user=jdoe,host=localhost,addr=127.0.0.1") { + if err != nil || s != (SSHD{"no", "no", "/usr/local/bin/tacctl-console", "no", "no", "", "", ""}) || !r.Called("sshd", "-T", "-C", "user=jdoe,host=localhost,addr=127.0.0.1") { t.Errorf("closed: %+v %v %q", s, err, r.Argvs()) } if p := s.Problems(false, false, false, testConsole); len(p) != 0 { @@ -1020,3 +1020,46 @@ func TestShellWithoutTheConsole(t *testing.T) { } } } + +func TestSSHDSubsystem(t *testing.T) { + ctx := context.Background() + const base = "port 22\nallowtcpforwarding no\nallowagentforwarding no\nforcecommand /usr/local/bin/tacctl-console\npubkeyauthentication no\n" + for _, c := range []struct { + name, out, want string + }{ + {"openssh server", base + "subsystem sftp /usr/lib/openssh/sftp-server\n", "/usr/lib/openssh/sftp-server"}, + {"internal", base + "subsystem sftp internal-sftp\n", "internal-sftp"}, + {"with arguments", base + "subsystem sftp /usr/lib/openssh/sftp-server -l INFO\n", "/usr/lib/openssh/sftp-server -l INFO"}, + {"another subsystem only", base + "subsystem netconf /usr/bin/netconf\n", ""}, + {"none", base + "subsystem sftp none\n", ""}, + {"no line", base, ""}, + {"a name with a prefix", base + "subsystem sftpx internal-sftp\n", ""}, + } { + r := &fake.Runner{} + r.On([]string{"sshd"}, execx.Result{Stdout: []byte(c.out)}) + got, err := SFTPSubsystem(ctx, r) + if err != nil || got != c.want { + t.Errorf("%s: %q %v, want %q", c.name, got, err, c.want) + } + if !r.Called("sshd", "-T", "-C", "user=root,host=localhost,addr=127.0.0.1") { + t.Errorf("%s: ran %q", c.name, r.Argvs()) + } + } + // SSHDCheck carries it too. + r := &fake.Runner{} + r.On([]string{"sshd"}, execx.Result{Stdout: []byte(base + "subsystem sftp internal-sftp\n")}) + if s, err := SSHDCheck(ctx, r, "jdoe"); err != nil || s.SFTP != "internal-sftp" { + t.Errorf("SSHDCheck: %+v %v", s, err) + } + // A check that cannot be made is an error, not 'none'. + r = &fake.Runner{} + r.On([]string{"sshd"}, execx.Result{Code: 255, Stderr: []byte("no hostkeys available\n")}) + if got, err := SFTPSubsystem(ctx, r); err == nil || got != "" { + t.Errorf("failure: %q %v", got, err) + } + m := &fake.Runner{} + m.Missing("sshd") + if _, err := SFTPSubsystem(ctx, m); err == nil { + t.Error("missing sshd: no error") + } +} diff --git a/internal/console/filetransfer.go b/internal/console/filetransfer.go new file mode 100644 index 00000000..9d7a8b8b --- /dev/null +++ b/internal/console/filetransfer.go @@ -0,0 +1,439 @@ +package console + +// The console's file transfer settings (settings.file_transfer in +// console.yaml): who may transfer files to and from their home through the +// console, how much the home may hold (the quota) and how fast a transfer +// may go (the rate). The model is the system shell's, with three +// differences: it is off for every tier but the superuser tier by default, +// the engineer tier is not closed to it (a transfer is limited to the +// user's home, where a shell or a forwarded port would reach the server), +// and a tier or a user may also have a quota and a rate. + +import ( + "slices" + "strconv" + "strings" + + "github.com/rett/tacctl/internal/tier" + "github.com/rett/tacctl/internal/yamlpy" +) + +// The limits of the file transfer settings. +const ( + // DefaultQuota is the quota, in bytes, of a tier with no setting of + // its own, for every tier but the superuser tier, which has none. + DefaultQuota int64 = 256 << 20 + // MaxFileTransferSize is the largest quota or rate a setting can name: + // 1 TiB. + MaxFileTransferSize int64 = 1 << 40 + + // Unlimited and RateOff are the words of 'no quota' and 'no rate limit' + // on the command line and in the file. + Unlimited = "unlimited" + RateOff = "off" +) + +// FileTransfer is what the settings give a user at a tier: whether the +// console may transfer files for them, the quota of their home in bytes +// (0: unlimited) and the rate in bytes per second (0: no limit). +type FileTransfer struct { + Enabled bool + Quota, Rate int64 +} + +// fileTransferUserTiers are the tiers a user's enable can be set for (the +// superuser tier needs none). +var fileTransferUserTiers = []tier.Tier{tier.Readonly, tier.Operator, tier.Engineer} + +// ParseSize reads a size in bytes: plain bytes, or a number with the unit +// K, M, G or T (powers of 1024, in either case). Zero, a negative number, a +// fraction, an overflow and more than 1 TiB (MaxFileTransferSize) are +// refused. The words unlimited and off are the callers' business. +func ParseSize(s string) (int64, error) { + bad := fail("Invalid size '" + s + "': expected a number of bytes or a number with K, M, G or T (such as 512K, 256M or 2G), at most 1T.") + if s == "" { + return 0, bad + } + mult := int64(1) + digits := s + switch s[len(s)-1] { + case 'k', 'K': + mult = 1 << 10 + case 'm', 'M': + mult = 1 << 20 + case 'g', 'G': + mult = 1 << 30 + case 't', 'T': + mult = 1 << 40 + } + if mult != 1 { + digits = s[:len(s)-1] + } + if digits == "" { + // a unit with no number: 'K' + return 0, bad + } + for _, c := range digits { + if c < '0' || c > '9' { + return 0, bad + } + } + n, err := strconv.ParseInt(digits, 10, 64) + if err != nil { + // only overflow gets here: the characters are digits + return 0, fail("Size '" + s + "' is too large: at most 1T.") + } + if n == 0 { + return 0, fail("Size '" + s + "' is zero: give a size above zero, or unlimited for no limit.") + } + if n > MaxFileTransferSize/mult { + return 0, fail("Size '" + s + "' is too large: at most 1T.") + } + return n * mult, nil +} + +// FormatSize is a size in the largest unit that holds it exactly (1G, 512K, +// 1000 for bytes that fit none). +func FormatSize(n int64) string { + for _, u := range []struct { + div int64 + name string + }{{1 << 40, "T"}, {1 << 30, "G"}, {1 << 20, "M"}, {1 << 10, "K"}} { + if n >= u.div && n%u.div == 0 { + return strconv.FormatInt(n/u.div, 10) + u.name + } + } + return strconv.FormatInt(n, 10) +} + +// QuotaWord is a quota as the file and the listings write it. +func QuotaWord(n int64) string { + if n == 0 { + return Unlimited + } + return FormatSize(n) +} + +// RateWord is a rate as the file and the listings write it. +func RateWord(n int64) string { + if n == 0 { + return RateOff + } + return FormatSize(n) +} + +// ParseQuota reads a quota word: a size, or unlimited (0). +func ParseQuota(s string) (int64, error) { + if s == Unlimited { + return 0, nil + } + return ParseSize(s) +} + +// ParseRate reads a rate word: a size in bytes per second, or off (0). +func ParseRate(s string) (int64, error) { + if s == RateOff { + return 0, nil + } + return ParseSize(s) +} + +// FileTransferUserNames are the users with a file transfer switch of their +// own, by name. +func (f *File) FileTransferUserNames() []string { return sortedKeys(f.FileTransferUsers) } + +// FileTransferQuotaUserNames are the users with a quota of their own. +func (f *File) FileTransferQuotaUserNames() []string { return sortedKeys(f.FileTransferQuotaUsers) } + +// FileTransferRateUserNames are the users with a rate of their own. +func (f *File) FileTransferRateUserNames() []string { return sortedKeys(f.FileTransferRateUsers) } + +func sortedKeys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + slices.Sort(out) + return out +} + +// SetFileTransfer switches file transfer on or off for tier t. The +// superuser tier always has it. The list that is written is the tiers that +// have it, lowest first, the superuser tier included. +func (f *File) SetFileTransfer(t tier.Tier, on bool) error { + if t == tier.Superuser && !on { + return fail("The superuser tier always has file transfer; it cannot be disabled. Nothing was changed.") + } + var out []tier.Tier + for _, x := range Tiers { + has := x == tier.Superuser || slices.Contains(f.FileTransferTiers, x) + if x == t { + has = on + } + if has { + out = append(out, x) + } + } + f.FileTransferTiers = out + return nil +} + +// SetFileTransferUser gives the user a file transfer switch of their own: an +// enable is recorded with the tier it is set for (readonly, operator or +// engineer; the superuser tier needs none), a disable with none. +func (f *File) SetFileTransferUser(name string, on bool, t tier.Tier) { + f.FileTransferUsers[name] = on + if on { + f.FileTransferUserTiers[name] = t + } else { + delete(f.FileTransferUserTiers, name) + } +} + +// DropFileTransferUser removes the user's file transfer switch. +func (f *File) DropFileTransferUser(name string) { + delete(f.FileTransferUsers, name) + delete(f.FileTransferUserTiers, name) +} + +// SetFileTransferQuota sets the quota of tier t in bytes (0: unlimited), or +// returns it to the built-in default (def). +func (f *File) SetFileTransferQuota(t tier.Tier, n int64, def bool) { + if def { + delete(f.FileTransferQuota, t) + return + } + f.FileTransferQuota[t] = n +} + +// SetFileTransferRate sets the rate of tier t in bytes per second, 0: off +// (the default, so nothing is stored). +func (f *File) SetFileTransferRate(t tier.Tier, n int64) { + if n == 0 { + delete(f.FileTransferRate, t) + return + } + f.FileTransferRate[t] = n +} + +// fileTransferDefault reports whether the file has no file transfer setting +// but the built-in ones: nothing is written for it. +func (f *File) fileTransferDefault() bool { + return len(f.FileTransferUsers) == 0 && len(f.FileTransferQuota) == 0 && len(f.FileTransferQuotaUsers) == 0 && + len(f.FileTransferRate) == 0 && len(f.FileTransferRateUsers) == 0 && + slices.Equal(f.FileTransferTiers, []tier.Tier{tier.Superuser}) +} + +// DefaultTierQuota is the built-in quota of tier t in bytes: none for the +// superuser tier, 256 MiB for the others. +func DefaultTierQuota(t tier.Tier) int64 { + if t == tier.Superuser { + return 0 + } + return DefaultQuota +} + +// checkFileTransfer is the invariants of the file transfer settings. +func (f *File) checkFileTransfer(userName func(string) bool) error { + seen := map[tier.Tier]bool{} + for _, t := range f.FileTransferTiers { + if _, ok := ParseTier(string(t)); !ok || seen[t] { + return fail("settings.file_transfer.tiers: invalid or repeated tier '" + string(t) + "'.") + } + seen[t] = true + } + for u, on := range f.FileTransferUsers { + if !userName(u) { + return fail("settings.file_transfer.users: invalid user name '" + u + "'.") + } + if t := f.FileTransferUserTiers[u]; on && !slices.Contains(fileTransferUserTiers, t) { + return fail("settings.file_transfer.users: '" + u + "' must be disable or enable:readonly|operator|engineer.") + } + } + for key, m := range map[string]map[tier.Tier]int64{"quota": f.FileTransferQuota, "rate": f.FileTransferRate} { + for t, n := range m { + if _, ok := ParseTier(string(t)); !ok { + return fail("settings.file_transfer." + key + ": invalid tier '" + string(t) + "'.") + } + if n < 0 || n > MaxFileTransferSize || (key == "rate" && n == 0) { + return fail("settings.file_transfer." + key + ": invalid size for '" + string(t) + "'.") + } + } + } + for key, m := range map[string]map[string]int64{"quota_users": f.FileTransferQuotaUsers, "rate_users": f.FileTransferRateUsers} { + for u, n := range m { + if !userName(u) { + return fail("settings.file_transfer." + key + ": invalid user name '" + u + "'.") + } + if n < 0 || n > MaxFileTransferSize { + return fail("settings.file_transfer." + key + ": invalid size for '" + u + "'.") + } + } + } + return nil +} + +// parseFileTransfer reads settings.file_transfer. +func parseFileTransfer(f *File, m *yamlpy.Map) error { + for k, v := range m.All() { + bad := fail("settings.file_transfer: invalid value for '" + k + "'.") + switch k { + case "tiers": + var l []tier.Tier + switch x := v.(type) { + case nil: + case []any: + for _, e := range x { + s, ok := e.(string) + if !ok { + return bad + } + l = append(l, tier.Tier(s)) + } + default: + return bad + } + f.FileTransferTiers = l + case "users": + switch x := v.(type) { + case nil: + case *yamlpy.Map: + for name, uv := range x.All() { + s, ok := uv.(string) + word, tr, hasTier := strings.Cut(s, ":") + switch { + case !ok, word != "disable" && word != "enable", word == "disable" && hasTier, word == "enable" && !hasTier: + return fail("settings.file_transfer.users: '" + name + "' must be disable or enable:readonly|operator|engineer.") + } + f.FileTransferUsers[name] = word == "enable" + if word == "enable" { + f.FileTransferUserTiers[name] = tier.Tier(tr) + } + } + default: + return fail("settings.file_transfer.users must be a mapping of user to disable or enable:.") + } + case "quota", "rate": + x, ok := v.(*yamlpy.Map) + if v == nil { + continue + } + if !ok { + return fail("settings.file_transfer." + k + " must be a mapping of tier to a size.") + } + for name, sv := range x.All() { + n, err := sizeValue(sv, k == "quota") + if err != nil { + return fail("settings.file_transfer." + k + ": '" + name + "' must be a size" + map[bool]string{true: " or unlimited", false: " or off"}[k == "quota"] + ".") + } + switch { + case k == "quota": + f.FileTransferQuota[tier.Tier(name)] = n + case n != 0: + f.FileTransferRate[tier.Tier(name)] = n + } + // a tier's rate of off is the built-in setting: nothing is stored + } + case "quota_users", "rate_users": + x, ok := v.(*yamlpy.Map) + if v == nil { + continue + } + if !ok { + return fail("settings.file_transfer." + k + " must be a mapping of user to a size.") + } + for name, sv := range x.All() { + n, err := sizeValue(sv, k == "quota_users") + if err != nil { + return fail("settings.file_transfer." + k + ": '" + name + "' must be a size or " + map[bool]string{true: Unlimited, false: RateOff}[k == "quota_users"] + ".") + } + if k == "quota_users" { + f.FileTransferQuotaUsers[name] = n + } else { + f.FileTransferRateUsers[name] = n + } + } + default: + return fail("settings.file_transfer: unknown key '" + k + "'.") + } + } + return nil +} + +// sizeValue reads a size from the file: a number of bytes, a size word, or +// unlimited (quota) / off (rate). An unquoted off is a boolean to YAML 1.1: +// false is read as off too. +func sizeValue(v any, quota bool) (int64, error) { + switch x := v.(type) { + case int: + if x <= 0 { + return 0, fail("size") + } + if int64(x) > MaxFileTransferSize { + return 0, fail("size") + } + return int64(x), nil + case bool: + if !x && !quota { + return 0, nil + } + case string: + if quota { + return ParseQuota(x) + } + return ParseRate(x) + } + return 0, fail("size") +} + +// fileTransferDoc is settings.file_transfer, written only when something is +// not the built-in setting, so a file that never touched it is read by every +// release. +func (f *File) fileTransferDoc() *yamlpy.Map { + words := func(l []tier.Tier) []string { + out := make([]string, 0, len(l)) + for _, t := range l { + out = append(out, string(t)) + } + return out + } + m := yamlpy.NewMap("tiers", words(f.FileTransferTiers)) + if len(f.FileTransferUsers) > 0 { + users := yamlpy.NewMap() + for _, u := range f.FileTransferUserNames() { + if f.FileTransferUsers[u] { + users.Set(u, "enable:"+string(f.FileTransferUserTiers[u])) + } else { + users.Set(u, "disable") + } + } + m.Set("users", users) + } + tierMap := func(key string, vals map[tier.Tier]int64, word func(int64) string) { + if len(vals) == 0 { + return + } + out := yamlpy.NewMap() + for _, t := range Tiers { + if n, ok := vals[t]; ok { + out.Set(string(t), word(n)) + } + } + m.Set(key, out) + } + userMap := func(key string, vals map[string]int64, word func(int64) string) { + if len(vals) == 0 { + return + } + out := yamlpy.NewMap() + for _, u := range sortedKeys(vals) { + out.Set(u, word(vals[u])) + } + m.Set(key, out) + } + tierMap("quota", f.FileTransferQuota, QuotaWord) + userMap("quota_users", f.FileTransferQuotaUsers, QuotaWord) + tierMap("rate", f.FileTransferRate, RateWord) + userMap("rate_users", f.FileTransferRateUsers, RateWord) + return m +} diff --git a/internal/console/filetransfer_test.go b/internal/console/filetransfer_test.go new file mode 100644 index 00000000..5b030e14 --- /dev/null +++ b/internal/console/filetransfer_test.go @@ -0,0 +1,565 @@ +package console + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/rett/tacctl/internal/tier" +) + +func TestParseSize(t *testing.T) { + for _, c := range []struct { + in string + want int64 + }{ + {"1", 1}, {"1000", 1000}, {"512K", 512 << 10}, {"512k", 512 << 10}, {"256M", 256 << 20}, {"2G", 2 << 30}, + {"1T", 1 << 40}, {"1024G", 1 << 40}, {"1048576K", 1 << 30}, {"007", 7}, + } { + got, err := ParseSize(c.in) + if err != nil || got != c.want { + t.Errorf("ParseSize(%q) = %d, %v; want %d", c.in, got, err, c.want) + } + } + for _, in := range []string{ + "", "0", "0K", "-1", "-5M", "+5", "1.5G", "1e3", "G", "K", "12X", "12MB", "1 M", " 1", "0x10", "unlimited", "off", + "1025G", "2T", "9223372036854775807", "9223372036854775808", "99999999999999999999", "9007199254740993T", + } { + if n, err := ParseSize(in); err == nil { + t.Errorf("ParseSize(%q) = %d: accepted", in, n) + } + } + // Over 1 TiB is refused with a message that says so; zero says zero. + if _, err := ParseSize("2T"); err == nil || !strings.Contains(err.Error(), "too large") { + t.Errorf("2T: %v", err) + } + if _, err := ParseSize("0"); err == nil || !strings.Contains(err.Error(), "zero") { + t.Errorf("0: %v", err) + } + if _, err := ParseSize("9223372036854775808"); err == nil || !strings.Contains(err.Error(), "too large") { + t.Errorf("overflow: %v", err) + } + // A unit with no number is a malformed size, not a large one. + for _, in := range []string{"K", "k", "M", "G", "T"} { + if _, err := ParseSize(in); err == nil || !strings.Contains(err.Error(), "Invalid size '"+in+"'") || strings.Contains(err.Error(), "too large") { + t.Errorf("%s: %v", in, err) + } + } +} + +func TestFormatSize(t *testing.T) { + for in, want := range map[int64]string{ + 1: "1", 1000: "1000", 1024: "1K", 1536: "1536", 512 << 10: "512K", 1 << 20: "1M", 256 << 20: "256M", (1 << 20) + 1: "1048577", + 1 << 30: "1G", 3 << 30: "3G", 1 << 40: "1T", 1500 << 20: "1500M", + } { + if got := FormatSize(in); got != want { + t.Errorf("FormatSize(%d) = %q, want %q", in, got, want) + } + } + // what is printed is read back as the same number + for _, n := range []int64{1, 1000, 1024, 5 << 20, 7 << 30, 1 << 40, 123457} { + if back, err := ParseSize(FormatSize(n)); err != nil || back != n { + t.Errorf("%d: %q -> %d, %v", n, FormatSize(n), back, err) + } + } + if QuotaWord(0) != "unlimited" || RateWord(0) != "off" || QuotaWord(2<<20) != "2M" || RateWord(1<<10) != "1K" { + t.Error("the words of quota and rate") + } + if n, err := ParseQuota("unlimited"); err != nil || n != 0 { + t.Errorf("unlimited: %d %v", n, err) + } + if n, err := ParseRate("off"); err != nil || n != 0 { + t.Errorf("off: %d %v", n, err) + } + if _, err := ParseQuota("off"); err == nil { + t.Error("a quota of off") + } + if _, err := ParseRate("unlimited"); err == nil { + t.Error("a rate of unlimited") + } +} + +// The defaults: off for every tier but the superuser tier, quota 256 MiB +// (none for the superuser tier), no rate; nothing is written to the file. +func TestFileTransferDefaults(t *testing.T) { + p := &Policy{File: Defaults()} + for _, c := range []struct { + t tier.Tier + on bool + quota int64 + }{ + {tier.Readonly, false, 256 << 20}, {tier.Operator, false, 256 << 20}, {tier.Engineer, false, 256 << 20}, {tier.Superuser, true, 0}, + {tier.None, false, 0}, {tier.Unrestricted, false, 0}, + } { + got := p.FileTransfer("dave", c.t) + if got.Enabled != c.on || got.Rate != 0 { + t.Errorf("%s: %+v", c.t, got) + } + if c.on && got.Quota != c.quota { + t.Errorf("%s: quota %d", c.t, got.Quota) + } + } + if q, from := p.FileTransferQuota("dave", tier.Operator); q != 256<<20 || from != "default" { + t.Errorf("quota %d %q", q, from) + } + text, err := Defaults().Text() + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(text), "file_transfer") { + t.Errorf("the defaults write the key:\n%s", text) + } + // setting the superuser tier alone, or a tier on and off again, is the default + f := Defaults() + if err := f.SetFileTransfer(tier.Operator, true); err != nil { + t.Fatal(err) + } + if err := f.SetFileTransfer(tier.Operator, false); err != nil { + t.Fatal(err) + } + if text, err = f.Text(); err != nil || strings.Contains(string(text), "file_transfer") { + t.Errorf("%v\n%s", err, text) + } +} + +func TestSetFileTransfer(t *testing.T) { + f := Defaults() + for _, tr := range []tier.Tier{tier.Engineer, tier.Readonly} { + if err := f.SetFileTransfer(tr, true); err != nil { + t.Fatalf("%s: %v", tr, err) + } + } + // the engineer tier is not closed; the list is lowest first with the superuser tier in + if want := []tier.Tier{tier.Readonly, tier.Engineer, tier.Superuser}; !reflect.DeepEqual(f.FileTransferTiers, want) { + t.Errorf("tiers %v, want %v", f.FileTransferTiers, want) + } + if err := f.SetFileTransfer(tier.Superuser, false); err == nil || !strings.Contains(err.Error(), "always") { + t.Errorf("superuser off: %v", err) + } + if err := f.SetFileTransfer(tier.Superuser, true); err != nil { + t.Errorf("superuser on: %v", err) + } + if err := f.SetFileTransfer(tier.Readonly, false); err != nil { + t.Fatal(err) + } + if want := []tier.Tier{tier.Engineer, tier.Superuser}; !reflect.DeepEqual(f.FileTransferTiers, want) { + t.Errorf("tiers %v, want %v", f.FileTransferTiers, want) + } +} + +// The user's own setting wins over the tier's, in both directions, but for +// the superuser tier (always) and a caller with no tier (never); an enable is +// for the tier it was set for. +func TestFileTransferForUsers(t *testing.T) { + f := Defaults() + if err := f.SetFileTransfer(tier.Operator, true); err != nil { + t.Fatal(err) + } + f.SetFileTransferUser("carol", true, tier.Readonly) + f.SetFileTransferUser("bob", false, "") + f.SetFileTransferUser("alice", false, "") + f.SetFileTransferUser("erin", true, tier.Engineer) + f.SetFileTransferUser("gus", true, tier.Operator) + p := &Policy{File: f} + for _, c := range []struct { + user string + t tier.Tier + want bool + why string + }{ + {"carol", tier.Readonly, true, "user setting"}, + {"dave", tier.Readonly, false, "tier readonly"}, + {"bob", tier.Operator, false, "user setting"}, + {"eve", tier.Operator, true, "tier operator"}, + {"alice", tier.Superuser, true, "always"}, + {"erin", tier.Engineer, true, "user setting"}, // the engineer tier can be given it + {"carol", tier.None, false, "no tier; stale: set for readonly, now none"}, + {"gus", tier.Operator, true, "user setting"}, + {"gus", tier.Readonly, false, "tier readonly; stale: set for operator, now readonly"}, + {"gus", tier.Superuser, true, "always; stale: set for operator, now superuser"}, + {"carol", tier.Operator, true, "tier operator; stale: set for readonly, now operator"}, + {"bob", tier.Readonly, false, "user setting"}, + {"erin", tier.Operator, true, "tier operator; stale: set for engineer, now operator"}, + } { + if got := p.FileTransferFor(c.user, c.t); got != c.want { + t.Errorf("%s at %s: %v, want %v", c.user, c.t, got, c.want) + } + if on, why := p.FileTransferWhy(c.user, c.t); on != c.want || why != c.why { + t.Errorf("%s at %s: why %v %q, want %v %q", c.user, c.t, on, why, c.want, c.why) + } + if got := p.FileTransfer(c.user, c.t).Enabled; got != c.want { + t.Errorf("%s at %s: FileTransfer %v", c.user, c.t, got) + } + } + // a caller with no tier never has it, whatever the file says + f.SetFileTransferUser("dave", true, tier.None) + if p.FileTransferFor("dave", tier.Unrestricted) || p.FileTransferFor("dave", tier.None) || p.FileTransfer("dave", tier.Unrestricted) != (FileTransfer{}) { + t.Error("unrestricted or none has file transfer") + } + if was, stale := p.FileTransferStale("gus", tier.Readonly); !stale || was != tier.Operator { + t.Errorf("stale %v %v", was, stale) + } + if _, stale := p.FileTransferStale("bob", tier.Readonly); stale { + t.Error("a disable is never stale") + } +} + +// Quota and rate: the user's value wins over the tier's, the tier's over the +// built-in default; unlimited and off are values. +func TestFileTransferQuotaAndRate(t *testing.T) { + f := Defaults() + f.SetFileTransferQuota(tier.Operator, 1<<30, false) + f.SetFileTransferQuota(tier.Superuser, 2<<30, false) + f.SetFileTransferQuota(tier.Engineer, 0, false) // unlimited + f.FileTransferQuotaUsers["bob"] = 512 << 10 + f.FileTransferQuotaUsers["carol"] = 0 + f.SetFileTransferRate(tier.Operator, 1<<20) + f.FileTransferRateUsers["bob"] = 0 + f.FileTransferRateUsers["carol"] = 64 << 10 + for _, t2 := range Tiers { + if err := f.SetFileTransfer(t2, true); err != nil && t2 != tier.Superuser { + t.Fatal(err) + } + } + p := &Policy{File: f} + for _, c := range []struct { + user string + t tier.Tier + quota, rate int64 + qFrom string + }{ + {"dave", tier.Readonly, 256 << 20, 0, "default"}, + {"dave", tier.Operator, 1 << 30, 1 << 20, "tier setting"}, + {"dave", tier.Engineer, 0, 0, "tier setting"}, + {"dave", tier.Superuser, 2 << 30, 0, "tier setting"}, + {"bob", tier.Operator, 512 << 10, 0, "user setting"}, + {"carol", tier.Readonly, 0, 64 << 10, "user setting"}, + } { + got := p.FileTransfer(c.user, c.t) + if !got.Enabled || got.Quota != c.quota || got.Rate != c.rate { + t.Errorf("%s at %s: %+v, want quota %d rate %d", c.user, c.t, got, c.quota, c.rate) + } + if _, from := p.FileTransferQuota(c.user, c.t); from != c.qFrom { + t.Errorf("%s at %s: quota from %q", c.user, c.t, from) + } + } + // back to the default + f.SetFileTransferQuota(tier.Operator, 0, true) + f.SetFileTransferRate(tier.Operator, 0) + if got := p.FileTransfer("dave", tier.Operator); got.Quota != 256<<20 || got.Rate != 0 { + t.Errorf("after the reset: %+v", got) + } + // the user is not asked for with no name + if q, from := p.FileTransferQuota("", tier.Readonly); q != 256<<20 || from != "default" { + t.Errorf("no user: %d %q", q, from) + } +} + +const fileTransferText = Header + `version: 1 +settings: + idle_timeout: 30 + agent_forwarding: false + ssh_escape: false + system_shell: /bin/bash + system_shell_tiers: [superuser] + forwarding_tiers: [superuser] + gateway_ports: false + list_max: 40 + file_transfer: + tiers: [operator, engineer, superuser] + users: {bob: disable, carol: 'enable:readonly'} + quota: {operator: 1G, superuser: unlimited} + quota_users: {carol: 512K} + rate: {operator: 1M} + rate_users: {bob: 'off', carol: '1000'} +` + +// The settings are written and read back as they are set, sizes in the +// largest exact unit, in the order of the file above (the YAML writer quotes the words that are +// booleans or numbers to a plain reader); a file with them is +// rewritten to the same bytes. +func TestFileTransferRoundTrip(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "console.yaml") + _, err := Mutate(p, nil, func(f *File) error { + if err := f.SetFileTransfer(tier.Engineer, true); err != nil { + return err + } + if err := f.SetFileTransfer(tier.Operator, true); err != nil { + return err + } + f.SetFileTransferUser("carol", true, tier.Readonly) + f.SetFileTransferUser("bob", false, "") + f.SetFileTransferQuota(tier.Operator, 1<<30, false) + f.SetFileTransferQuota(tier.Superuser, 0, false) + f.FileTransferQuotaUsers["carol"] = 512 << 10 + f.SetFileTransferRate(tier.Operator, 1<<20) + f.FileTransferRateUsers["bob"] = 0 + f.FileTransferRateUsers["carol"] = 1000 + return nil + }) + if err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(p) + if string(got) != fileTransferText { + t.Errorf("the file:\n%s\nwant:\n%s", got, fileTransferText) + } + f, err := Load(p) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(f.FileTransferTiers, []tier.Tier{tier.Operator, tier.Engineer, tier.Superuser}) || + f.FileTransferUsers["bob"] || !f.FileTransferUsers["carol"] || f.FileTransferUserTiers["carol"] != tier.Readonly || + f.FileTransferQuota[tier.Operator] != 1<<30 || f.FileTransferQuota[tier.Superuser] != 0 || len(f.FileTransferQuota) != 2 || + f.FileTransferQuotaUsers["carol"] != 512<<10 || f.FileTransferRate[tier.Operator] != 1<<20 || + f.FileTransferRateUsers["bob"] != 0 || f.FileTransferRateUsers["carol"] != 1000 || len(f.FileTransferRateUsers) != 2 { + t.Errorf("read back: %+v", f) + } + if changed, err := Mutate(p, nil, func(*File) error { return nil }); err != nil || changed { + t.Errorf("a second write changed the file: %v %v", changed, err) + } + // the clone is deep + c := f.Clone() + c.FileTransferUsers["zed"] = true + c.FileTransferQuota[tier.Readonly] = 5 + c.FileTransferRateUsers["zed"] = 5 + c.FileTransferTiers[0] = tier.Readonly + if _, ok := f.FileTransferUsers["zed"]; ok || len(f.FileTransferQuota) != 2 || len(f.FileTransferRateUsers) != 2 || f.FileTransferTiers[0] != tier.Operator { + t.Error("Clone shares a map or a list") + } +} + +// A file with the user's rate written as an unquoted off (a boolean to YAML +// 1.1) is read as off. +func TestFileTransferRateUnquotedOff(t *testing.T) { + p := write(t, t.TempDir(), "console.yaml", "version: 1\nsettings:\n file_transfer:\n tiers: [superuser]\n rate_users: {bob: off}\n", 0o600) + f, err := Load(p) + if err != nil { + t.Fatal(err) + } + if n, ok := f.FileTransferRateUsers["bob"]; !ok || n != 0 { + t.Errorf("%v %v", n, ok) + } +} + +// A tier's rate of off (quoted or not) is the built-in setting, as it is for +// a user: it is read, and nothing is stored for the tier. +func TestFileTransferTierRateOff(t *testing.T) { + for _, body := range []string{"rate: {operator: 'off', engineer: 1M}", "rate: {operator: off, engineer: 1M}"} { + p := write(t, t.TempDir(), "console.yaml", "version: 1\nsettings:\n file_transfer:\n tiers: [superuser]\n "+body+"\n", 0o600) + f, err := Load(p) + if err != nil { + t.Fatalf("%s: %v", body, err) + } + if _, ok := f.FileTransferRate[tier.Operator]; ok || f.FileTransferRate[tier.Engineer] != 1<<20 { + t.Errorf("%s: %v", body, f.FileTransferRate) + } + } +} + +func TestFileTransferInvalidFiles(t *testing.T) { + for _, c := range []struct{ name, body, want string }{ + {"not a mapping", "file_transfer: yes\n", "must be a mapping"}, + {"unknown key", "file_transfer: {tiers: [superuser], rates: {}}\n", "unknown key 'rates'"}, + {"unknown tier", "file_transfer: {tiers: [admin]}\n", "invalid or repeated tier 'admin'"}, + {"repeated tier", "file_transfer: {tiers: [operator, operator]}\n", "invalid or repeated tier 'operator'"}, + {"none tier", "file_transfer: {tiers: [none]}\n", "invalid or repeated tier 'none'"}, + {"tier not a string", "file_transfer: {tiers: [1]}\n", "invalid value for 'tiers'"}, + {"user enable without tier", "file_transfer: {users: {bob: enable}}\n", "must be disable or enable"}, + {"user disable with tier", "file_transfer: {users: {bob: 'disable:operator'}}\n", "must be disable or enable"}, + {"user enable for superuser", "file_transfer: {users: {bob: 'enable:superuser'}}\n", "must be disable or enable"}, + {"user enable for none", "file_transfer: {users: {bob: 'enable:none'}}\n", "must be disable or enable"}, + {"bad user name", "file_transfer: {users: {'a.b': disable}}\n", "invalid user name 'a.b'"}, + {"bad quota user name", "file_transfer: {quota_users: {'a b': 1M}}\n", "invalid user name"}, + {"quota tier", "file_transfer: {quota: {admin: 1M}}\n", "invalid tier 'admin'"}, + {"quota zero", "file_transfer: {quota: {operator: 0}}\n", "must be a size or unlimited"}, + {"quota negative", "file_transfer: {quota: {operator: -5}}\n", "must be a size or unlimited"}, + {"quota too large", "file_transfer: {quota: {operator: 2T}}\n", "must be a size or unlimited"}, + {"quota int too large", "file_transfer: {quota: {operator: 9999999999999999}}\n", "must be a size or unlimited"}, + {"quota fraction", "file_transfer: {quota: {operator: 1.5G}}\n", "must be a size or unlimited"}, + {"quota off", "file_transfer: {quota: {operator: 'off'}}\n", "must be a size or unlimited"}, + {"rate unlimited", "file_transfer: {rate: {operator: unlimited}}\n", "must be a size"}, + {"rate list", "file_transfer: {rate_users: {bob: [1]}}\n", "must be a size or off"}, + {"quota users list", "file_transfer: {quota_users: [bob]}\n", "must be a mapping"}, + } { + p := write(t, t.TempDir(), "console.yaml", "version: 1\nsettings:\n "+c.body, 0o600) + _, err := Load(p) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("%s: %v, want %q", c.name, err, c.want) + } + } + // the writer refuses what the reader would + f := Defaults() + f.FileTransferQuota[tier.Operator] = -1 + if _, err := f.Text(); err == nil { + t.Error("a negative quota is written") + } + f = Defaults() + f.FileTransferRate[tier.Operator] = 0 + if _, err := f.Text(); err == nil { + t.Error("a zero rate for a tier is written") + } + f = Defaults() + f.FileTransferQuotaUsers["bob"] = MaxFileTransferSize + 1 + if _, err := f.Text(); err == nil { + t.Error("a quota over 1 TiB is written") + } + f = Defaults() + f.FileTransferUsers["bob"] = true // no tier stamp + if _, err := f.Text(); err == nil { + t.Error("an enable without a tier is written") + } +} + +// A file without the key is read and written as before: the sizes of the +// older settings do not move, and the key is added only when it is needed. +func TestFileTransferKeyIsOptional(t *testing.T) { + p := write(t, t.TempDir(), "console.yaml", "version: 1\nsettings:\n idle_timeout: 12\n", 0o600) + f, err := Load(p) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(f.FileTransferTiers, []tier.Tier{tier.Superuser}) || len(f.FileTransferUsers) != 0 { + t.Errorf("%+v", f) + } + // an empty tiers list in a file is no tier but the superuser tier's always + p = write(t, t.TempDir(), "console.yaml", "version: 1\nsettings:\n file_transfer: {tiers: []}\n", 0o600) + f, err = Load(p) + if err != nil { + t.Fatal(err) + } + if !(&Policy{File: f}).FileTransferTier(tier.Superuser) || (&Policy{File: f}).FileTransferTier(tier.Operator) { + t.Error("an empty list") + } +} + +// The user's settings follow a rename and go with a removal, and the upgrade's +// rename of a name with a period carries them. +func TestFileTransferFollowsTheUser(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "console.yaml") + if _, err := Mutate(p, nil, func(f *File) error { + f.SetFileTransferUser("alice", true, tier.Operator) + f.FileTransferQuotaUsers["alice"] = 1 << 30 + f.FileTransferRateUsers["alice"] = 1 << 20 + f.SetFileTransferUser("bob", false, "") + return nil + }); err != nil { + t.Fatal(err) + } + m := MoveUserSettings(p, "alice", "carol") + if m.Err != nil || !m.FileHad || m.FileWhat != "enable:operator, quota 1G, rate 1M" || !m.Had() || m.ShellHad || m.CacheHad { + t.Fatalf("move: %+v", m) + } + f, err := Load(p) + if err != nil { + t.Fatal(err) + } + if f.FileTransferUsers["carol"] != true || f.FileTransferUserTiers["carol"] != tier.Operator || f.FileTransferQuotaUsers["carol"] != 1<<30 || + f.FileTransferRateUsers["carol"] != 1<<20 || len(f.FileTransferUsers) != 2 || len(f.FileTransferQuotaUsers) != 1 || len(f.FileTransferRateUsers) != 1 { + t.Errorf("after the move: %+v", f) + } + // a removal leaves nothing for the next user of the name + m = MoveUserSettings(p, "carol", "") + if m.Err != nil || !m.FileHad { + t.Fatalf("drop: %+v", m) + } + f, _ = Load(p) + if len(f.FileTransferUsers) != 1 || len(f.FileTransferQuotaUsers) != 0 || len(f.FileTransferRateUsers) != 0 || f.FileTransferUsers["bob"] { + t.Errorf("after the drop: %+v", f) + } + // a user with no setting does not touch the file + before, _ := os.ReadFile(p) + if m = MoveUserSettings(p, "dave", "erin"); m.Had() || m.Err != nil { + t.Errorf("dave: %+v", m) + } + if after, _ := os.ReadFile(p); string(after) != string(before) { + t.Error("the file was rewritten") + } + + q := write(t, dir, "dotted.yaml", `version: 1 +settings: + file_transfer: + tiers: [operator, superuser] + users: {alice.smith: 'enable:operator', dave.x: disable} + quota_users: {alice.smith: 1G, erin.y: unlimited} + rate_users: {alice.smith: 1M} +`, 0o600) + res, err := RenameUsers(q, []UserRename{{"alice.smith", "alice_smith"}}) + if err != nil { + t.Fatal(err) + } + if !res.Moves[0].FileHad || strings.Join(res.Dropped, ",") != "dave.x,erin.y" { + t.Errorf("rename: %+v", res) + } + f, err = Load(q) + if err != nil { + t.Fatalf("the file written is not read: %v", err) + } + if !f.FileTransferUsers["alice_smith"] || f.FileTransferQuotaUsers["alice_smith"] != 1<<30 || f.FileTransferRateUsers["alice_smith"] != 1<<20 || + len(f.FileTransferUsers) != 1 || len(f.FileTransferQuotaUsers) != 1 { + t.Errorf("after the rename: %+v", f) + } + // DropDottedUserKeys names what it drops + r := write(t, dir, "old.yaml", "version: 1\nsettings:\n file_transfer:\n tiers: [superuser]\n users: {a.b: 'enable:readonly'}\n rate_users: {a.b: 1M}\n", 0o600) + text, dropped, err := DropDottedUserKeys(r) + if err != nil || len(dropped) != 1 || dropped[0] != (DroppedSetting{"a.b", "file transfer enable:readonly, rate 1M"}) { + t.Fatalf("dropped %v %v", dropped, err) + } + if strings.Contains(string(text), "a.b") { + t.Errorf("the text keeps the name:\n%s", text) + } +} + +// The console's own process reads the file transfer fields of the answer: a +// transfer is off unless the answer says it is on, a damaged number is left +// out (no limit, off), and the line the root side writes is read back to the +// same settings. +func TestParseRemoteFileTransfer(t *testing.T) { + r, ok := ParseRemote("shell=console tier=operator file_transfer=yes ft_quota=268435456 ft_rate=1048576") + if !ok || r.FileTransfer != (FileTransfer{Enabled: true, Quota: 256 << 20, Rate: 1 << 20}) || r.FileTransferSettings() != r.FileTransfer { + t.Errorf("on: %+v %v", r.FileTransfer, ok) + } + r, _ = ParseRemote("shell=console tier=superuser file_transfer=yes ft_quota=0 ft_rate=0") + if got := r.FileTransferSettings(); got != (FileTransfer{Enabled: true}) { + t.Errorf("unlimited: %+v", got) + } + for _, line := range []string{ + "shell=console tier=operator file_transfer=no", + "shell=console tier=operator", + "shell=console tier=operator file_transfer=maybe ft_quota=5", + "shell=console tier=operator ft_quota=5 ft_rate=5", // numbers without the switch + "shell=console tier=operator file_transfer=no ft_quota=5 ft_rate=5", + } { + r, ok := ParseRemote(line) + if !ok || r.FileTransferSettings().Enabled || (r.FileTransferSettings() != FileTransfer{}) { + t.Errorf("%q: %+v %v", line, r.FileTransferSettings(), ok) + } + } + // a damaged number is left out + r, _ = ParseRemote("shell=console tier=operator file_transfer=yes ft_quota=-1 ft_rate=x") + if got := r.FileTransferSettings(); got != (FileTransfer{Enabled: true}) { + t.Errorf("damaged: %+v", got) + } + r, _ = ParseRemote("shell=console tier=operator file_transfer=yes ft_quota=2199023255553 ft_rate=99999999999999999999") + if got := r.FileTransferSettings(); got != (FileTransfer{Enabled: true}) { + t.Errorf("out of range: %+v", got) + } + // no answer: no file transfer + if r, ok := ParseRemote(""); ok || r.FileTransferSettings() != (FileTransfer{}) || DefaultRemote().FileTransfer != (FileTransfer{}) { + t.Errorf("no answer: %+v %v", r.FileTransfer, ok) + } + // what the root side writes is what the console reads + for _, ft := range []FileTransfer{{}, {Enabled: true}, {Enabled: true, Quota: 5 << 30, Rate: 64 << 10}, {Enabled: true, Quota: MaxFileTransferSize, Rate: MaxFileTransferSize}} { + r, ok := ParseRemote("shell=console tier=readonly" + FileTransferFields(ft)) + if !ok || r.FileTransferSettings() != ft { + t.Errorf("%+v -> %q -> %+v", ft, FileTransferFields(ft), r.FileTransferSettings()) + } + } + if FileTransferFields(FileTransfer{Quota: 5, Rate: 5}) != "" { + t.Error("a disabled transfer writes its limits") + } +} diff --git a/internal/console/mode.go b/internal/console/mode.go index 1c4e5193..644f6ab8 100644 --- a/internal/console/mode.go +++ b/internal/console/mode.go @@ -6,7 +6,8 @@ package console // 'tacctl-console -c ' for a remote command, scp, sftp and rsync // (with the console's sshd drop-in, ForceCommand, always as the latter: // Forced); the -c guard lets one tacctl line through and refuses -// everything else. +// everything else, but the sftp subsystem, which the console serves itself +// for the accounts that have file transfer (internal/sftpd). import ( "path/filepath" @@ -22,8 +23,12 @@ const Name = "tacctl-console" // The console's refusals, each with exit status RefusedStatus. const ( // RefusedText is the answer to a -c string that is not one tacctl line - // (scp, sftp, rsync, a program, a shell word). - RefusedText = "the tacctl console does not run programs; file transfer is not available" + // (scp -O, rsync, a program, a shell word). The console serves one thing + // besides tacctl lines, the SFTP subsystem (SFTPOffText). + RefusedText = "the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)" + // SFTPOffText is the answer to the sftp subsystem when file transfer is + // not enabled for the caller (console file-transfer). + SFTPOffText = "file transfer is not enabled for this account; an administrator can switch it on (tacctl console file-transfer)" // NoOptionsText is the answer to any arguments but '-c '. NoOptionsText = "the tacctl console takes no options" // RefusedStatus is the exit status of a refusal (the shell's "cannot diff --git a/internal/console/policy.go b/internal/console/policy.go index 034c83d8..68a39b36 100644 --- a/internal/console/policy.go +++ b/internal/console/policy.go @@ -149,6 +149,107 @@ func (p *Policy) SystemShellWhy(user string, t tier.Tier) (on bool, why string) return p.SystemShell(t), "tier " + string(t) + stale } +// FileTransferTier reports whether file transfer is open to tier t by the +// tier's own setting: the superuser tier always has it, a caller with no +// tier (none) or no tier restriction (unrestricted, who has no console +// account) never, and the others when the tier is in settings.file_transfer. +// No tier is closed to it, the engineer tier included: a transfer reaches +// the user's home only. +func (p *Policy) FileTransferTier(t tier.Tier) bool { + switch t { + case tier.Superuser: + return true + case tier.Readonly, tier.Operator, tier.Engineer: + return slices.Contains(p.File.FileTransferTiers, t) + } + return false +} + +// FileTransferStale reports whether user has an enable of file transfer that +// was set for another tier than t, the tier they have now, and which tier +// that was. +func (p *Policy) FileTransferStale(user string, t tier.Tier) (was tier.Tier, stale bool) { + if on, ok := p.File.FileTransferUsers[user]; ok && on && p.File.FileTransferUserTiers[user] != t { + return p.File.FileTransferUserTiers[user], true + } + return "", false +} + +// FileTransferFor reports whether user, at tier t, may transfer files: the +// user's own setting wins over the tier's, in both directions, but for the +// superuser tier (always) and a caller with no tier (never), which no setting +// changes. A disable holds at any tier; an enable only at the tier it was +// set for (FileTransferStale), as the system shell's does. +func (p *Policy) FileTransferFor(user string, t tier.Tier) bool { + if t != tier.Readonly && t != tier.Operator && t != tier.Engineer { + return p.FileTransferTier(t) + } + if on, ok := p.File.FileTransferUsers[user]; ok && (!on || p.File.FileTransferUserTiers[user] == t) { + return on + } + return p.FileTransferTier(t) +} + +// FileTransferWhy is the state of user's file transfer and the reason, for +// the listings: "always" (superuser), "no tier", "user setting", or "tier +// ", with "; stale: set for , now " when an enable of the user +// is for another tier than they have now. +func (p *Policy) FileTransferWhy(user string, t tier.Tier) (on bool, why string) { + stale := "" + if was, ok := p.FileTransferStale(user, t); ok { + stale = "; stale: set for " + string(was) + ", now " + string(t) + } + switch { + case t == tier.Superuser: + return true, "always" + stale + case t != tier.Readonly && t != tier.Operator && t != tier.Engineer: + return false, "no tier" + stale + } + if _, ok := p.File.FileTransferUsers[user]; ok && stale == "" { + return p.FileTransferFor(user, t), "user setting" + } + return p.FileTransferTier(t), "tier " + string(t) + stale +} + +// FileTransferQuota is the quota of the home of user, at tier t, in bytes +// (0: unlimited), and where it comes from: "user setting", "tier setting" or +// "default". The user's own value wins over the tier's, and the tier's over +// the built-in default (DefaultQuota; none for the superuser tier). +func (p *Policy) FileTransferQuota(user string, t tier.Tier) (n int64, from string) { + if n, ok := p.File.FileTransferQuotaUsers[user]; ok && user != "" { + return n, "user setting" + } + if n, ok := p.File.FileTransferQuota[t]; ok { + return n, "tier setting" + } + return DefaultTierQuota(t), "default" +} + +// FileTransferRate is the rate limit of user, at tier t, in bytes per second +// (0: none), and where it comes from, as FileTransferQuota says; off by +// default. +func (p *Policy) FileTransferRate(user string, t tier.Tier) (n int64, from string) { + if n, ok := p.File.FileTransferRateUsers[user]; ok && user != "" { + return n, "user setting" + } + if n, ok := p.File.FileTransferRate[t]; ok { + return n, "tier setting" + } + return 0, "default" +} + +// FileTransfer is what the settings give user at tier t: the one answer the +// console's file transfer needs. A user who may not transfer has the zero +// value. +func (p *Policy) FileTransfer(user string, t tier.Tier) FileTransfer { + if !p.FileTransferFor(user, t) { + return FileTransfer{} + } + q, _ := p.FileTransferQuota(user, t) + r, _ := p.FileTransferRate(user, t) + return FileTransfer{Enabled: true, Quota: q, Rate: r} +} + // Forwarding reports whether tier t's console logins may forward X11 and // TCP ports (settings.forwarding_tiers). A caller with no tier restriction // may; none and the Closed tiers may not. diff --git a/internal/console/policyclient.go b/internal/console/policyclient.go index 5943b5ef..9432fe7e 100644 --- a/internal/console/policyclient.go +++ b/internal/console/policyclient.go @@ -53,6 +53,12 @@ type Remote struct { // a superuser, who is never locked out by a read error. An answer that // names no such field is a release before 0.2.20, which flags nobody. PasswordChangeUnknown bool + // FileTransfer is what the caller's file transfer settings give them + // (Policy.FileTransfer): the fields file_transfer (yes|no), ft_quota + // and ft_rate (bytes, bytes a second; 0: unlimited, off) of the answer. + // The zero value, no file transfer, is the default of an answer that + // does not name it: it is off unless the root side says it is on. + FileTransfer FileTransfer // Name is the name of this server the console shows in its prompt and // notices (0.2.22, server.name); "" when the answer has none: the host // name is shown. @@ -66,7 +72,7 @@ type Remote struct { } // DefaultRemote is the policy without an answer: idle 30 minutes, no -// system shell, no ssh escape, the default list threshold. +// system shell, no file transfer, no ssh escape, the default list threshold. func DefaultRemote() Remote { return Remote{ Idle: DefaultIdle * time.Minute, @@ -155,6 +161,22 @@ func ParseRemote(out string) (r Remote, ok bool) { if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= MaxPasswordCacheMax { r.PCMax, ok = time.Duration(n)*time.Hour, true } + case "file_transfer": + if b, good := yesNoValue(v); good { + r.FileTransfer.Enabled, ok = b, true + } + case "ft_quota", "ft_rate": + // bytes; a value out of range is left out, which is no limit for + // the quota and off for the rate, and the settings never write + // one, so it is a damaged answer + if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 0 && n <= MaxFileTransferSize { + if k == "ft_quota" { + r.FileTransfer.Quota = n + } else { + r.FileTransfer.Rate = n + } + ok = true + } case "name": // not a policy field: a line with a name and nothing else is no answer if names.ServerNameProblem(v) == "" { @@ -225,3 +247,28 @@ func yesNoValue(v string) (bool, bool) { } return false, false } + +// FileTransferSettings is what the caller's file transfer settings give them, +// as the root side's answer said: the one call the console's file transfer +// makes on the policy it fetched with 'tacctl _console-policy' (the cli's +// consoleRemotePolicy, which gives the defaults when there is no answer). No +// answer, an answer that does not name file transfer and an answer of an +// unknown caller are no file transfer: the zero value. +func (r Remote) FileTransferSettings() FileTransfer { + if !r.Known || !r.FileTransfer.Enabled { + return FileTransfer{} + } + return r.FileTransfer +} + +// FileTransferFields are the fields of the _console-policy line that carry +// the file transfer settings: " file_transfer=yes ft_quota= +// ft_rate=" when it is on, and nothing when it is off (a line without +// the field reads as off, and the quota and the rate then mean nothing). The +// console's process reads them back with ParseRemote. +func FileTransferFields(ft FileTransfer) string { + if !ft.Enabled { + return "" + } + return " file_transfer=yes ft_quota=" + strconv.FormatInt(ft.Quota, 10) + " ft_rate=" + strconv.FormatInt(ft.Rate, 10) +} diff --git a/internal/console/rollback.go b/internal/console/rollback.go index 8faef7ab..7c3b2b90 100644 --- a/internal/console/rollback.go +++ b/internal/console/rollback.go @@ -52,6 +52,15 @@ var Keys023 = []string{"settings.password_cache"} // and an older release has the tiers' setting alone. var Keys0220 = []string{"settings.color", "settings.list_max", "settings.system_shell_users", "settings.password_cache_users"} +// Keys0228 is the setting 0.2.28 added that every older release rejects, 0.2.27 +// included ("settings: unknown key 'file_transfer'", which makes the console +// fall back to its defaults and every console write fail): 'settings. +// file_transfer', the file transfer's tiers, users, quotas and rates, written +// only when something in it is not the built-in setting. The rollback to any +// release removes it (PlanRollbackSince0228 for the releases from 0.2.20 on, +// which read everything else; the other plans take it out with the rest). +var Keys0228 = []string{"settings.file_transfer"} + // RollbackPlan is what writing the file for an older release changes. type RollbackPlan struct { // Exists: the file is there. @@ -64,10 +73,25 @@ type RollbackPlan struct { // Text is the file as the release reads it; nil when nothing changes. Text []byte - // cache: the plan is for 0.2.3, which also rejects the password cache. - cache bool + // level says which settings the plan takes out (the rollbackLevel + // constants). + level rollbackLevel } +// rollbackLevel is how far back a plan goes. +type rollbackLevel int + +const ( + // levelSince0228 is the plan for a release that reads everything but the + // settings of 0.2.28: 0.2.20 to 0.2.27. + levelSince0228 rollbackLevel = iota + // levelSince0220 is the plan for a release with the password cache but + // before 0.2.20: the settings of 0.2.20 go too. + levelSince0220 + // levelAll is the plan for 0.2.3, which also rejects the password cache. + levelAll +) + // Summary says what writing the plan removes and sets, for the line that // reports it ('removed settings.password_cache, settings.color'). func (p RollbackPlan) Summary() string { @@ -92,14 +116,25 @@ func (p RollbackPlan) Summary() string { // read is an error, so the rollback refuses before it changes anything. A // missing file, and one without the keys, change nothing (it is not // rewritten: 0.2.3 reads it as it is). -func PlanRollback(path string) (RollbackPlan, error) { return planRollback(path, true) } +func PlanRollback(path string) (RollbackPlan, error) { return planRollback(path, levelAll) } // PlanRollbackSince0220 is PlanRollback for a release that has the password // cache (0.2.4 and later): only the settings of 0.2.20 go. -func PlanRollbackSince0220(path string) (RollbackPlan, error) { return planRollback(path, false) } +func PlanRollbackSince0220(path string) (RollbackPlan, error) { + return planRollback(path, levelSince0220) +} -func planRollback(path string, cache bool) (RollbackPlan, error) { - p := RollbackPlan{cache: cache} +// PlanRollbackSince0228 is PlanRollback for a release from 0.2.20 to 0.2.27, +// which reads the settings of 0.2.20 and the password cache: only the file +// transfer settings of 0.2.28 go. +func PlanRollbackSince0228(path string) (RollbackPlan, error) { + return planRollback(path, levelSince0228) +} + +func planRollback(path string, level rollbackLevel) (RollbackPlan, error) { + cache := level == levelAll + old := level != levelSince0228 + p := RollbackPlan{level: level} data, err := os.ReadFile(path) switch { case errors.Is(err, fs.ErrNotExist): @@ -122,25 +157,28 @@ func planRollback(path string, cache bool) (RollbackPlan, error) { if _, has := m.Get("password_cache"); has && cache { p.Remove = append(p.Remove, "settings.password_cache: "+cacheWord(f)) } - if _, has := m.Get("color"); has { + if _, has := m.Get("color"); has && old { p.Remove = append(p.Remove, "settings.color: "+f.Color) } - if _, has := m.Get("system_shell_users"); has { + if _, has := m.Get("system_shell_users"); has && old { p.Remove = append(p.Remove, "settings.system_shell_users: "+systemShellUsersWord(f)) } - if _, has := m.Get("password_cache_users"); has { + if _, has := m.Get("password_cache_users"); has && old { p.Remove = append(p.Remove, "settings.password_cache_users: "+strings.Join(f.PasswordCacheUserNames(), ", ")+" (on)") } + if _, has := m.Get("file_transfer"); has { + p.Remove = append(p.Remove, "settings.file_transfer: "+fileTransferWord(f)) + } } } } - if f.ListMax == ListMaxNever { + if f.ListMax == ListMaxNever && old { p.Set = append(p.Set, "settings.list_max to "+strconv.Itoa(MaxListMax)+" (it never asked)") } if len(p.Remove) == 0 && len(p.Set) == 0 { return p, nil } - text, err := f.rollbackText(cache) + text, err := f.rollbackText(level) if err != nil { return p, err } @@ -161,6 +199,35 @@ func systemShellUsersWord(f *File) string { return strings.Join(w, ", ") } +// fileTransferWord says what the file transfer settings are, for the plan: +// the tiers that have it and how many users, quotas and rates are set. +func fileTransferWord(f *File) string { + tiers := "none" + if len(f.FileTransferTiers) > 0 { + var w []string + for _, t := range f.FileTransferTiers { + w = append(w, string(t)) + } + tiers = strings.Join(w, ",") + } + out := "tiers " + tiers + for _, c := range []struct { + n int + one, several string + }{ + {len(f.FileTransferUsers), "user switch", "user switches"}, {len(f.FileTransferQuota) + len(f.FileTransferQuotaUsers), "quota", "quotas"}, + {len(f.FileTransferRate) + len(f.FileTransferRateUsers), "rate", "rates"}, + } { + switch { + case c.n == 1: + out += ", 1 " + c.one + case c.n > 1: + out += ", " + strconv.Itoa(c.n) + " " + c.several + } + } + return out +} + // cacheWord says what the cache's settings are, for the plan. func cacheWord(f *File) string { tiers := "none" @@ -180,27 +247,35 @@ func cacheWord(f *File) string { // the settings of 0.2.20 (Keys0220). Everything else is written as the // current tacctl writes it (0.2.4 writes 0.2.3's form of every other // setting), and read back with the reader the file is read with. -func (f *File) Text023() ([]byte, error) { return f.rollbackText(true) } +func (f *File) Text023() ([]byte, error) { return f.rollbackText(levelAll) } // Text0219 is the file as a release with the password cache and before -// 0.2.20 reads it: the settings of 0.2.20 (Keys0220) are gone. -func (f *File) Text0219() ([]byte, error) { return f.rollbackText(false) } +// 0.2.20 reads it: the settings of 0.2.20 (Keys0220) and of 0.2.28 (Keys0228) +// are gone. +func (f *File) Text0219() ([]byte, error) { return f.rollbackText(levelSince0220) } + +// Text0227 is the file as a release from 0.2.20 to 0.2.27 reads it: the file +// transfer settings of 0.2.28 (Keys0228) are gone, everything else stays. +func (f *File) Text0227() ([]byte, error) { return f.rollbackText(levelSince0228) } -func (f *File) rollbackText(cache bool) ([]byte, error) { +func (f *File) rollbackText(level rollbackLevel) ([]byte, error) { if err := f.validate(); err != nil { return nil, err } doc := f.doc() if settings, ok := doc.Get("settings"); ok { m := settings.(*yamlpy.Map) - if cache { + m.Delete("file_transfer") + if level == levelAll { m.Delete("password_cache") } - m.Delete("color") - m.Delete("system_shell_users") - m.Delete("password_cache_users") - if f.ListMax == ListMaxNever { - m.Set("list_max", MaxListMax) + if level != levelSince0228 { + m.Delete("color") + m.Delete("system_shell_users") + m.Delete("password_cache_users") + if f.ListMax == ListMaxNever { + m.Set("list_max", MaxListMax) + } } } out, err := yamlpy.EmitChecked(doc, yamlpy.StoreOptions, Header, pyyaml.LoadBytes) @@ -216,16 +291,22 @@ func (f *File) rollbackText(cache bool) ([]byte, error) { // through a temporary file (0600, fsync, rename). changed is false when // nothing needed changing. func Rollback(path string, before func() error) (changed bool, err error) { - return rollback(path, before, true) + return rollback(path, before, levelAll) } // RollbackSince0220 is Rollback for a release with the password cache: only // the settings of 0.2.20 are taken out. func RollbackSince0220(path string, before func() error) (changed bool, err error) { - return rollback(path, before, false) + return rollback(path, before, levelSince0220) +} + +// RollbackSince0228 is Rollback for a release from 0.2.20 to 0.2.27: only the +// file transfer settings of 0.2.28 are taken out. +func RollbackSince0228(path string, before func() error) (changed bool, err error) { + return rollback(path, before, levelSince0228) } -func rollback(path string, before func() error, cache bool) (changed bool, err error) { +func rollback(path string, before func() error, level rollbackLevel) (changed bool, err error) { if before != nil { if err := before(); err != nil { return false, err @@ -236,7 +317,7 @@ func rollback(path string, before func() error, cache bool) (changed bool, err e return false, err } defer unlock() - p, err := planRollback(path, cache) + p, err := planRollback(path, level) if err != nil || p.Text == nil { return false, err } diff --git a/internal/console/rollback_test.go b/internal/console/rollback_test.go index 27e4f30b..2c77a2ce 100644 --- a/internal/console/rollback_test.go +++ b/internal/console/rollback_test.go @@ -1,14 +1,19 @@ package console import ( + "context" "errors" "os" "path/filepath" "reflect" + "slices" "strings" "testing" + "github.com/rett/tacctl/internal/execx" + "github.com/rett/tacctl/internal/pyyaml" "github.com/rett/tacctl/internal/tier" + "github.com/rett/tacctl/internal/yamlpy" ) // A console.yaml as 0.2.4 writes it with every setting changed, the password @@ -218,3 +223,220 @@ func TestRollbackSnapshotsFirst(t *testing.T) { t.Errorf("order %q %v %v", order, changed, err) } } + +// accepts0227 is the part of 0.2.27's console.yaml parser that matters for a +// rollback to it, as a fixture (parse, parseSettings and parsePasswordCache of +// internal/console/config.go at the 0.2.27 tag, which +// TestTheFixtureOf0227IsThe0227Parser reads back): any key of its lists is +// known, any other +// makes it answer "settings: unknown key", and the console falls back to +// the defaults. +func accepts0227(text []byte) error { + v, err := pyyaml.LoadBytes(text) + if err != nil { + return err + } + root := v.(*yamlpy.Map) + for k := range root.All() { + if !slices.Contains([]string{"version", "tiers", "users", "settings"}, k) { + return errors.New("unknown key '" + k + "'") + } + } + settings, ok := root.Get("settings") + if !ok { + return nil + } + for k, sv := range settings.(*yamlpy.Map).All() { + switch k { + case "idle_timeout", "list_max", "agent_forwarding", "ssh_escape", "gateway_ports", "space_completion", "color", + "system_shell", "system_shell_users", "password_cache_users", "system_shell_tiers", "forwarding_tiers": + case "password_cache": + for pk := range sv.(*yamlpy.Map).All() { + if !slices.Contains([]string{"tiers", "idle", "max"}, pk) { + return errors.New("settings.password_cache: unknown key '" + pk + "'") + } + } + default: + return errors.New("settings: unknown key '" + k + "'") + } + } + return nil +} + +// The fixture of 0.2.27's parser holds what the tag holds: its source reports +// an unknown settings key, has none of the file transfer keys and has every +// settings key the fixture lists. Skipped where git or the tag is absent. +func TestTheFixtureOf0227IsThe0227Parser(t *testing.T) { + r := execx.Real{} + if _, err := r.LookPath("git"); err != nil { + t.Skip("git is not installed, so the 0.2.27 tag cannot be read") + } + if res, err := r.Run(context.Background(), execx.Cmd{Name: "git", Args: []string{"rev-parse", "-q", "--verify", "0.2.27^{commit}"}}); err != nil || res.Code != 0 { + t.Skip("the 0.2.27 tag is not in this repository (CI must fetch tags: git fetch --tags)") + } + res, err := r.Run(context.Background(), execx.Cmd{Name: "git", Args: []string{"show", "0.2.27:internal/console/config.go"}}) + if err != nil || res.Code != 0 { + t.Fatalf("cannot read the 0.2.27 tag's config.go: %v %s", err, res.Stderr) + } + src := string(res.Stdout) + for _, w := range []string{`fail("settings: unknown key '" + k + "'.")`, `fail("unknown key '" + k + "'.")`, `case "system_shell_users":`, `case "password_cache_users":`, `case "color"`} { + if !strings.Contains(src, w) { + t.Errorf("0.2.27's config.go lacks %q: the fixture accepts0227 is out of date", w) + } + } + if strings.Contains(src, "file_transfer") { + t.Error("0.2.27's config.go knows file_transfer: the rollback needs no step for it") + } + // the keys of the fixture are the cases of the tag's parseSettings + for _, k := range []string{"idle_timeout", "list_max", "agent_forwarding", "ssh_escape", "gateway_ports", "space_completion", "color", + "system_shell", "system_shell_users", "password_cache_users", "system_shell_tiers", "forwarding_tiers", "password_cache"} { + if !strings.Contains(src, `"`+k+`"`) { + t.Errorf("0.2.27's config.go has no key %q", k) + } + } + // and the file this release writes with every setting is rejected by it + if err := accepts0227(fileTransferFixture(t)); err == nil || !strings.Contains(err.Error(), "settings: unknown key 'file_transfer'") { + t.Errorf("the fixture of 0.2.27 reads the file transfer settings: %v", err) + } +} + +// fileTransferFixture is a console.yaml of this release with the file +// transfer settings and every older setting changed. +func fileTransferFixture(t *testing.T) []byte { + t.Helper() + f := Defaults() + f.Idle = 12 + f.AgentForwarding = true + f.ListMax = ListMaxNever + f.Color = ColorOn + f.SpaceCompletion = false + f.SystemShellTiers = []tier.Tier{tier.Operator, tier.Superuser} + f.SetSystemShellUser("bob", true, tier.Readonly) + f.PasswordCacheTiers = []tier.Tier{tier.Engineer, tier.Superuser} + f.PasswordCacheIdle, f.PasswordCacheMax = 30, 4 + f.PasswordCacheUsers["carol"] = true + if err := f.SetFileTransfer(tier.Operator, true); err != nil { + t.Fatal(err) + } + f.SetFileTransferUser("bob", true, tier.Readonly) + f.SetFileTransferQuota(tier.Operator, 1<<30, false) + f.FileTransferRateUsers["carol"] = 1 << 20 + text, err := f.Text() + if err != nil { + t.Fatal(err) + } + return text +} + +// The file written for 0.2.27 is accepted by the fixture of its parser, keeps +// every other setting (0.2.27 has them all: the colour, a list_max that never +// asks, the users' system shell, the password cache and its users), and is +// the file a plan for any older release also gives, as far as the file +// transfer goes. +func TestRollbackTextIsReadBy0227(t *testing.T) { + orig := fileTransferFixture(t) + if err := accepts0227(orig); err == nil { + t.Fatal("the fixture of this release's file is accepted by the 0.2.27 parser") + } + p := write(t, t.TempDir(), "console.yaml", string(orig), 0o600) + plan, err := PlanRollbackSince0228(p) + if err != nil { + t.Fatal(err) + } + want := []string{"settings.file_transfer: tiers operator,superuser, 1 user switch, 1 quota, 1 rate"} + if !plan.Exists || plan.Text == nil || !reflect.DeepEqual(plan.Remove, want) || len(plan.Set) != 0 { + t.Fatalf("plan %+v, want remove %q", plan, want) + } + if err := accepts0227(plan.Text); err != nil { + t.Errorf("0.2.27 rejects the converted file: %v\n%s", err, plan.Text) + } + if plan.Summary() != "removed settings.file_transfer" { + t.Errorf("summary %q", plan.Summary()) + } + // every other setting is as it was, and this release reads the file with + // the file transfer at its built-in settings + f, err := Load(p) + if err != nil { + t.Fatal(err) + } + f.FileTransferTiers = Defaults().FileTransferTiers + f.FileTransferUsers, f.FileTransferUserTiers = map[string]bool{}, map[string]tier.Tier{} + f.FileTransferQuota, f.FileTransferRateUsers = map[tier.Tier]int64{}, map[string]int64{} + wantText, err := f.Text() + if err != nil { + t.Fatal(err) + } + if string(plan.Text) != string(wantText) { + t.Errorf("the converted file:\n%s\nwant:\n%s", plan.Text, wantText) + } + g, err := Load(p) + if err != nil { + t.Fatal(err) + } + if text, err := g.Text0227(); err != nil || string(text) != string(plan.Text) { + t.Errorf("Text0227: %v\n%s", err, text) + } + changed, err := RollbackSince0228(p, nil) + if err != nil || !changed { + t.Fatalf("RollbackSince0228: %v %v", changed, err) + } + if got, _ := os.ReadFile(p); string(got) != string(plan.Text) { + t.Errorf("the file after the rollback:\n%s", got) + } + // done: nothing is left to take out, and a second run changes nothing + if again, err := PlanRollbackSince0228(p); err != nil || again.Text != nil || len(again.Remove) != 0 { + t.Errorf("second plan: %+v %v", again, err) + } + if changed, err := RollbackSince0228(p, nil); err != nil || changed { + t.Errorf("second RollbackSince0228: %v %v", changed, err) + } + // the plans for the older releases take the key out as well, and the + // other settings 0.2.27 reads go where they must: the colour and the + // users' settings for the releases before 0.2.20, the password cache for + // 0.2.3 + for _, c := range []struct { + name string + plan func(string) (RollbackPlan, error) + gone []string + kept []string + }{ + {"0.2.19", PlanRollbackSince0220, []string{"file_transfer", "color:", "system_shell_users", "password_cache_users"}, []string{"password_cache:", "space_completion", "list_max: 1000"}}, + {"0.2.3", PlanRollback, []string{"file_transfer", "color:", "system_shell_users", "password_cache_users", "password_cache:"}, []string{"space_completion", "list_max: 1000"}}, + } { + q := write(t, t.TempDir(), "console.yaml", string(orig), 0o600) + pl, err := c.plan(q) + if err != nil || pl.Text == nil { + t.Fatalf("%s: %+v %v", c.name, pl, err) + } + if !slices.ContainsFunc(pl.Remove, func(r string) bool { return strings.HasPrefix(r, "settings.file_transfer: ") }) { + t.Errorf("%s: the plan does not remove the file transfer: %q", c.name, pl.Remove) + } + for _, w := range c.gone { + if strings.Contains(string(pl.Text), w) { + t.Errorf("%s: the text keeps %q:\n%s", c.name, w, pl.Text) + } + } + for _, w := range c.kept { + if !strings.Contains(string(pl.Text), w) { + t.Errorf("%s: the text lost %q:\n%s", c.name, w, pl.Text) + } + } + } + // a file without the key is not rewritten, and a missing one is no error + plain, err := Defaults().Text() + if err != nil { + t.Fatal(err) + } + r := write(t, t.TempDir(), "console.yaml", string(plain), 0o600) + if pl, err := PlanRollbackSince0228(r); err != nil || pl.Text != nil || len(pl.Remove) != 0 { + t.Errorf("a file without the key: %+v %v", pl, err) + } + if pl, err := PlanRollbackSince0228(filepath.Join(t.TempDir(), "none.yaml")); err != nil || pl.Exists || pl.Text != nil { + t.Errorf("a missing file: %+v %v", pl, err) + } + // a file this release cannot read refuses the plan + bad := write(t, t.TempDir(), "console.yaml", "version: 1\nsettings: {file_transfer: {quota: {operator: 0}}}\n", 0o600) + if _, err := PlanRollbackSince0228(bad); err == nil { + t.Error("an unreadable file is planned") + } +} diff --git a/internal/console/server.go b/internal/console/server.go index aea693fb..f6c1a63e 100644 --- a/internal/console/server.go +++ b/internal/console/server.go @@ -57,6 +57,11 @@ type SSHD struct { // GatewayPorts is gatewayports: no, yes or clientspecified ("" when // sshd did not print it). GatewayPorts string + // SFTP is the program of the sftp subsystem (subsystem sftp : + // sftp-server, internal-sftp ...); "" when sshd defines none, and then it + // never starts the subsystem, whatever the console allows. A Match block + // cannot define a subsystem, so the value is the same for every user. + SFTP string } // SSHDCheck runs 'sshd -T -C user=,host=localhost,addr=127.0.0.1' @@ -64,6 +69,18 @@ type SSHD struct { // through the runner. An error is a check that could not be made (no sshd, // no such user, a configuration sshd refuses); its text is for the person. func SSHDCheck(ctx context.Context, r execx.Runner, user string) (SSHD, error) { + s, err := sshdConfig(ctx, r, user) + if err != nil { + return SSHD{}, err + } + if s.TCPForwarding == "" || s.AgentForwarding == "" { + return SSHD{}, fail("sshd -T printed no forwarding settings.") + } + return s, nil +} + +// sshdConfig runs 'sshd -T' for user and reads the settings it prints. +func sshdConfig(ctx context.Context, r execx.Runner, user string) (SSHD, error) { res, err := r.Run(ctx, execx.Cmd{Name: "sshd", Args: []string{"-T", "-C", "user=" + user + ",host=localhost,addr=127.0.0.1"}}) if err != nil { return SSHD{}, fail("sshd could not be run: " + err.Error()) @@ -93,14 +110,26 @@ func SSHDCheck(ctx context.Context, r execx.Runner, user string) (SSHD, error) { s.DisableForwarding = v case "gatewayports": s.GatewayPorts = v + case "subsystem": + if name, prog, _ := strings.Cut(v, " "); name == "sftp" && strings.TrimSpace(prog) != "" && strings.TrimSpace(prog) != "none" { + s.SFTP = strings.TrimSpace(prog) + } } } - if s.TCPForwarding == "" || s.AgentForwarding == "" { - return SSHD{}, fail("sshd -T printed no forwarding settings.") - } return s, nil } +// SFTPSubsystem is the program of the sftp subsystem sshd would start, as +// 'sshd -T' says ("" when it defines none): the question file transfer +// depends on, since the console serves the subsystem only when sshd starts +// it. It asks for the configuration as SSHDCheck does, for the user root, +// whose Match blocks cannot change the answer. An error is a check that could +// not be made, as SSHDCheck's. +func SFTPSubsystem(ctx context.Context, r execx.Runner) (string, error) { + s, err := sshdConfig(ctx, r, "root") + return s.SFTP, err +} + // Problems are the ways the connection could still do more than the console // intends: sshd does not force the console (command) on it, so a remote // command or the sftp subsystem would run without it; TCP forwarding is diff --git a/internal/console/sftp.go b/internal/console/sftp.go new file mode 100644 index 00000000..92e20610 --- /dev/null +++ b/internal/console/sftp.go @@ -0,0 +1,126 @@ +package console + +// The console's file transfer, from the console's side: how a session of the +// sftp subsystem is told apart in the log (internal/sftpd serves the +// protocol, internal/cli/console_sftp.go wires it). + +import ( + "strconv" + "strings" + "unicode/utf8" +) + +// ModeSFTP is the mode of a session that serves the sftp subsystem (the +// 'mode=' of its start line, next to interactive, command and batch). +const ModeSFTP = "sftp" + +// ReasonSFTP is the 'reason=' of the end line of a session that served the +// sftp subsystem, or refused it. +const ReasonSFTP = "sftp" + +// SFTPDenyLine is the log line of the sftp subsystem refused: why is +// "file-transfer" (it is not enabled for the account), "password-change" (a +// password change is required of the caller first, or it could not be read +// whether one is), "policy" (there is no answer to read, and the caller is no +// superuser who would be held anyway), "home" (the account's home directory +// is not known) or "stream" (the process has no standard input or output). +func (s Session) SFTPDenyLine(why string) string { + return "console DENY session=" + s.ID + " user=" + LogValue(s.User) + " reason=" + why + " subsystem=sftp" +} + +// SFTPStatus is the exit status of a session of the sftp subsystem that +// failed after the protocol started (a protocol error, the stream cut +// mid-packet). +const SFTPStatus = 1 + +// NameMax is the most bytes of the escaped text of a file name (a path) that +// one field of a log line carries. logger cuts a line at 1 KiB by default, so +// the fields after the longest ones (reason=, error=) would be lost if the +// escapes were not counted. +const NameMax = 200 + +// QuoteName is a path a client sent, made safe for one field of a log line. +// The audit never logs a typed word that is not a verb, because it could be a +// password; a path is a file name and is logged, but as a Go string literal +// in double quotes: a control character (a newline, an escape sequence), a +// quote, a backslash, a byte that is not UTF-8 and a character that does not +// print (a bidirectional override) become escapes, so that no name can end +// the field or the line, forge a field or move a terminal that reads the +// log. At most NameMax bytes of the escaped text are kept, never a part of an +// escape sequence or of a character; a name that was cut ends with '...' +// after the closing quote. +func QuoteName(s string) string { + var b strings.Builder + b.WriteByte('"') + kept := 0 + cut := false + for i := 0; i < len(s); { + _, n := utf8.DecodeRuneInString(s[i:]) + q := strconv.Quote(s[i : i+n]) + piece := q[1 : len(q)-1] + if kept+len(piece) > NameMax { + cut = true + break + } + b.WriteString(piece) + kept += len(piece) + i += n + } + b.WriteByte('"') + if cut { + b.WriteString("...") + } + return b.String() +} + +// SFTPStartLine is the log line of a file transfer opened: the tier of the +// caller, the home directory that is "/" for the client, and the quota and +// the rate in effect (the words of 'console file-transfer': 256M, unlimited, +// off). +func (s Session) SFTPStartLine(tier, home string, quota, rate int64) string { + return "console sftp start session=" + s.ID + " user=" + LogValue(s.User) + " tier=" + LogValue(tier) + + " from=" + LogValue(s.From) + " home=" + QuoteName(home) + " quota=" + QuotaWord(quota) + " rate=" + RateWord(rate) +} + +// SFTPEndLine is the log line of a file transfer closed: the bytes uploaded +// and downloaded, the requests audited (ops) and those of them that were +// refused. +func (s Session) SFTPEndLine(up, down int64, ops, refused int) string { + return "console sftp end session=" + s.ID + " user=" + LogValue(s.User) + " up=" + strconv.FormatInt(up, 10) + + " down=" + strconv.FormatInt(down, 10) + " ops=" + strconv.Itoa(ops) + " refused=" + strconv.Itoa(refused) +} + +// SFTPEventLine is the log line, and its syslog priority, of one thing a +// client did (sftpd.Event): op is upload, download, delete, rename, mkdir, +// setstat or refused. A request the server refused (.ssh, outside the home, a +// symbolic link, the quota, an unsupported request, a bad path) is +// 'console sftp DENY ... reason=' at auth.warning, like a refused command; +// the rest are info lines with the path (and the new name of a rename), the +// bytes moved by an upload or a download, and the error text of one that +// failed. Every line names the tier of the caller. errText is sanitised like a path; with a path, a new name and an +// error text each at NameMax, the line stays under 1000 bytes (logger cuts a +// line at 1 KiB). +func (s Session) SFTPEventLine(op, tier, path, to string, bytes int64, errText string) (priority, line string) { + head := "console sftp " + op + priority = "auth.info" + if op == "refused" { + head = "console sftp DENY" + priority = "auth.warning" + } + line = head + " session=" + s.ID + " user=" + LogValue(s.User) + + " tier=" + LogValue(tier) + " path=" + QuoteName(path) + if to != "" { + line += " to=" + QuoteName(to) + } + switch op { + case "upload", "download": + line += " bytes=" + strconv.FormatInt(bytes, 10) + } + switch { + case op == "refused": + line += " reason=" + LogValue(strings.ReplaceAll(errText, " ", "-")) + case errText != "": + line += " error=" + QuoteName(errText) + } + return priority, line +} diff --git a/internal/console/sftp_test.go b/internal/console/sftp_test.go new file mode 100644 index 00000000..02ef653c --- /dev/null +++ b/internal/console/sftp_test.go @@ -0,0 +1,171 @@ +package console + +import ( + "strconv" + "strings" + "testing" + "unicode/utf8" +) + +func TestQuoteName(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {"/a.txt", `"/a.txt"`}, + {"/dir/a b", `"/dir/a b"`}, + {"/é.txt", `"/é.txt"`}, + {"a\nb", `"a\nb"`}, + {"a\rb", `"a\rb"`}, + {"x\x1b[31mred", `"x\x1b[31mred"`}, + {"say \"hi\"", `"say \"hi\""`}, + {`back\slash`, `"back\\slash"`}, + {"a\x00b", `"a\x00b"`}, + {"bad\xffutf", `"bad\xffutf"`}, + {"rtl\u202eexe.txt", `"rtl\u202eexe.txt"`}, + {"nel\u0085x", `"nel\u0085x"`}, + {"", `""`}, + } { + if got := QuoteName(c.in); got != c.want { + t.Errorf("QuoteName(%q) = %s, want %s", c.in, got, c.want) + } + } +} + +func TestQuoteNameCapsTheLength(t *testing.T) { + long := strings.Repeat("n", NameMax+50) + if got, want := QuoteName(long), `"`+strings.Repeat("n", NameMax)+`"...`; got != want { + t.Errorf("long name: %s", got) + } + if got := QuoteName(long[:NameMax]); strings.HasSuffix(got, "...") { + t.Errorf("a name of exactly NameMax bytes was cut: %s", got) + } + // the cut falls inside a multi-byte character: the whole character goes + multi := strings.Repeat("n", NameMax-1) + "é" + "tail" + got := QuoteName(multi) + if want := `"` + strings.Repeat("n", NameMax-1) + `"...`; got != want { + t.Errorf("cut inside a character: %s", got) + } + if !utf8.ValidString(got) { + t.Errorf("cut name is not UTF-8: %q", got) + } +} + +// NameMax bounds the escaped text, and a cut never falls inside an escape +// sequence or a character: what is kept reads back as a Go string literal. +func TestQuoteNameBoundsTheEscapedText(t *testing.T) { + for name, in := range map[string]string{ + "control bytes": strings.Repeat("\x01", NameMax+50), + "invalid bytes": strings.Repeat("\xff", NameMax+50), + "quotes": strings.Repeat(`"`, NameMax+50), + "backslashes": strings.Repeat(`\`, NameMax+50), + "override marks": strings.Repeat("\u202e", NameMax+50), + "two-byte": strings.Repeat("é", NameMax+50), + "four-byte": strings.Repeat("\U0001F600", NameMax+50), + "plain then ctrl": strings.Repeat("n", NameMax-2) + "\x01\x01", + "plain then rtl": strings.Repeat("n", NameMax-5) + "\u202e", + } { + got := QuoteName(in) + inner := strings.TrimSuffix(got, "...") + if len(inner) > NameMax+2 { + t.Errorf("%s: %d bytes of text, more than NameMax", name, len(inner)-2) + } + if !utf8.ValidString(got) { + t.Errorf("%s: not UTF-8: %q", name, got) + } + if !strings.HasSuffix(got, "...") { + t.Errorf("%s: a name over NameMax was not marked as cut: %s", name, got) + } + if _, err := strconv.Unquote(inner); err != nil { + t.Errorf("%s: the cut falls inside an escape: %s: %v", name, got, err) + } + } + // the cut is as late as it can be: 199 plain bytes, then an escape that + // would not fit + if got, want := QuoteName(strings.Repeat("n", NameMax-1)+"\x01"), `"`+strings.Repeat("n", NameMax-1)+`"...`; got != want { + t.Errorf("late cut: %s", got) + } + // and an escape that fits exactly is kept, uncut + if got, want := QuoteName(strings.Repeat("n", NameMax-4)+"\x01"), `"`+strings.Repeat("n", NameMax-4)+`\x01"`; got != want { + t.Errorf("exact fit: %s", got) + } +} + +// A line of every kind, with the longest user, tier, path, new name and +// error text there are, and every byte of them an escape, fits in what +// logger keeps of a line (1 KiB by default); the trailing fields survive. +func TestSFTPEventLinesFitALogLine(t *testing.T) { + s := Session{ID: "0123456789ab", User: strings.Repeat("u", 80), From: strings.Repeat("1", 80), Mode: ModeSFTP} + hostile := strings.Repeat("\x01", 400) + check := func(kind, line string) { + t.Helper() + if len(line) >= 1000 { + t.Errorf("%s: %d bytes: %s", kind, len(line), line) + } + } + for _, op := range []string{"upload", "download", "delete", "rename", "mkdir", "setstat"} { + to := "" + if op == "rename" { + to = hostile + } + _, line := s.SFTPEventLine(op, "superuser", hostile, to, 1<<62, hostile) + check(op, line) + if !strings.Contains(line, " error=") { + t.Errorf("%s: the error field is lost: %s", op, line) + } + } + for _, why := range []string{".ssh", "outside the home", "symlink", "link", "quota", "unsupported", "bad path", "too many open files"} { + _, line := s.SFTPEventLine("refused", "superuser", hostile, hostile, 0, why) + check("refused "+why, line) + if !strings.HasSuffix(line, " reason="+strings.ReplaceAll(why, " ", "-")) { + t.Errorf("refused %s: the reason is lost: %s", why, line) + } + } + check("start", s.SFTPStartLine("superuser", hostile, 1<<62, 1<<62)) + check("end", s.SFTPEndLine(1<<62, 1<<62, 1<<30, 1<<30)) + check("deny", s.SFTPDenyLine("password-change")) +} + +func TestSFTPLines(t *testing.T) { + s := Session{ID: "0123456789ab", User: "carol", From: "192.0.2.9", Mode: ModeSFTP} + if got, want := s.SFTPStartLine("operator", "/home/user", 256<<20, 0), + `console sftp start session=0123456789ab user=carol tier=operator from=192.0.2.9 home="/home/user" quota=256M rate=off`; got != want { + t.Errorf("start:\n got %s\nwant %s", got, want) + } + if got, want := s.SFTPStartLine("superuser", "/home/user", 0, 1<<20), + `console sftp start session=0123456789ab user=carol tier=superuser from=192.0.2.9 home="/home/user" quota=unlimited rate=1M`; got != want { + t.Errorf("start, no quota:\n got %s\nwant %s", got, want) + } + if got, want := s.SFTPEndLine(10, 20, 4, 1), `console sftp end session=0123456789ab user=carol up=10 down=20 ops=4 refused=1`; got != want { + t.Errorf("end: %s", got) + } + if got, want := s.SFTPDenyLine("file-transfer"), `console DENY session=0123456789ab user=carol reason=file-transfer subsystem=sftp`; got != want { + t.Errorf("deny: %s", got) + } + for _, c := range []struct { + op, path, to string + bytes int64 + err string + priority string + want string + }{ + {"upload", "/a b", "", 12, "", "auth.info", `console sftp upload session=0123456789ab user=carol tier=operator path="/a b" bytes=12`}, + {"download", "/a", "", 3, "", "auth.info", `console sftp download session=0123456789ab user=carol tier=operator path="/a" bytes=3`}, + {"delete", "/a", "", 0, "", "auth.info", `console sftp delete session=0123456789ab user=carol tier=operator path="/a"`}, + {"rename", "/a", "/b\n", 0, "", "auth.info", `console sftp rename session=0123456789ab user=carol tier=operator path="/a" to="/b\n"`}, + {"mkdir", "/d", "", 0, "", "auth.info", `console sftp mkdir session=0123456789ab user=carol tier=operator path="/d"`}, + {"setstat", "/a", "", 0, "", "auth.info", `console sftp setstat session=0123456789ab user=carol tier=operator path="/a"`}, + {"delete", "/a", "", 0, "no such file", "auth.info", `console sftp delete session=0123456789ab user=carol tier=operator path="/a" error="no such file"`}, + {"refused", "/.ssh/k", "", 0, ".ssh", "auth.warning", `console sftp DENY session=0123456789ab user=carol tier=operator path="/.ssh/k" reason=.ssh`}, + {"refused", "/x", "", 0, "outside the home", "auth.warning", `console sftp DENY session=0123456789ab user=carol tier=operator path="/x" reason=outside-the-home`}, + {"refused", "/q", "", 0, "quota", "auth.warning", `console sftp DENY session=0123456789ab user=carol tier=operator path="/q" reason=quota`}, + } { + priority, line := s.SFTPEventLine(c.op, "operator", c.path, c.to, c.bytes, c.err) + if priority != c.priority || line != c.want { + t.Errorf("%s: %s %s\nwant %s %s", c.op, priority, line, c.priority, c.want) + } + } + // A user name with a space or a quote cannot forge a field. + forged := Session{ID: "0123456789ab", User: "x\" path=\"/y"} + _, line := forged.SFTPEventLine("delete", "operator", "/a", "", 0, "") + if strings.Contains(line, `path="/y`) || strings.Count(line, " path=") != 1 { + t.Errorf("forged user: %s", line) + } +} diff --git a/internal/console/usermove.go b/internal/console/usermove.go index 0bc0ecad..8bb8cff7 100644 --- a/internal/console/usermove.go +++ b/internal/console/usermove.go @@ -15,15 +15,72 @@ import ( // UserSettingsMove is what a move did to a user's own settings in the file: // the system shell (settings.system_shell_users: ShellHad, with value -// ShellOn) and the password cache (settings.password_cache_users: CacheHad, -// always on). Err says the file could not be read or written. +// ShellOn), the password cache (settings.password_cache_users: CacheHad, +// always on) and the file transfer settings (settings.file_transfer: FileHad, +// with FileWhat saying what they were, such as "enable:operator, quota 1G"). +// Err says the file could not be read or written. type UserSettingsMove struct { ShellHad, ShellOn, CacheHad bool + FileHad bool + FileWhat string Err error } // Had reports whether the user had any of them. -func (m UserSettingsMove) Had() bool { return m.ShellHad || m.CacheHad } +func (m UserSettingsMove) Had() bool { return m.ShellHad || m.CacheHad || m.FileHad } + +// fileTransferOf says what the user's own file transfer settings are +// ("enable:operator, quota 1G, rate 1M"), "" when there are none. +func (f *File) fileTransferOf(user string) string { + var w []string + if on, ok := f.FileTransferUsers[user]; ok { + w = append(w, word(on)) + if on { + w[0] += ":" + string(f.FileTransferUserTiers[user]) + } + } + if n, ok := f.FileTransferQuotaUsers[user]; ok { + w = append(w, "quota "+QuotaWord(n)) + } + if n, ok := f.FileTransferRateUsers[user]; ok { + w = append(w, "rate "+RateWord(n)) + } + return strings.Join(w, ", ") +} + +// moveFileTransfer carries the file transfer settings of oldname to newname +// (newname "": drops them) and says what they were. +func (f *File) moveFileTransfer(oldname, newname string) string { + what := f.fileTransferOf(oldname) + if what == "" { + return "" + } + on, hasOn := f.FileTransferUsers[oldname] + was := f.FileTransferUserTiers[oldname] + q, hasQ := f.FileTransferQuotaUsers[oldname] + r, hasR := f.FileTransferRateUsers[oldname] + f.dropFileTransferOf(oldname) + if newname != "" { + f.dropFileTransferOf(newname) + if hasOn { + f.SetFileTransferUser(newname, on, was) + } + if hasQ { + f.FileTransferQuotaUsers[newname] = q + } + if hasR { + f.FileTransferRateUsers[newname] = r + } + } + return what +} + +// dropFileTransferOf removes every file transfer setting of the user. +func (f *File) dropFileTransferOf(user string) { + f.DropFileTransferUser(user) + delete(f.FileTransferQuotaUsers, user) + delete(f.FileTransferRateUsers, user) +} // moveUser carries the settings of oldname to newname (newname "": drops // them) in f and says what it moved. An entry already under newname @@ -35,6 +92,8 @@ func (f *File) moveUser(oldname, newname string) UserSettingsMove { m := UserSettingsMove{ShellHad: shellHad, ShellOn: on, CacheHad: cacheHad} f.DropSystemShellUser(oldname) delete(f.PasswordCacheUsers, oldname) + m.FileWhat = f.moveFileTransfer(oldname, newname) + m.FileHad = m.FileWhat != "" if newname != "" { if shellHad { f.SetSystemShellUser(newname, on, was) @@ -58,7 +117,7 @@ func MoveUserSettings(path, oldname, newname string) UserSettingsMove { if err != nil { return UserSettingsMove{Err: err} } - if _, shell := f.SystemShellUsers[oldname]; !shell && !f.PasswordCacheUsers[oldname] { + if _, shell := f.SystemShellUsers[oldname]; !shell && !f.PasswordCacheUsers[oldname] && f.fileTransferOf(oldname) == "" { return UserSettingsMove{} } // What is carried is read under the file's lock, in the same step that @@ -167,19 +226,20 @@ func renamedText(path string, renames []UserRename) (data, text []byte, res User return data, text, res, nil } -// dropDotted removes every per-user key that has a period from the three -// mappings and returns the names, sorted. +// dropDotted removes every per-user key that has a period from the +// per-user mappings and returns the names, sorted. func (f *File) dropDotted() []string { out := f.dottedUsers() for _, u := range out { f.DropSystemShellUser(u) delete(f.PasswordCacheUsers, u) delete(f.IgnoredUsers, u) + f.dropFileTransferOf(u) } return out } -// dottedUsers are the names with a period in the three per-user mappings, +// dottedUsers are the names with a period in the per-user mappings, // sorted. func (f *File) dottedUsers() []string { seen := map[string]bool{} @@ -192,6 +252,15 @@ func (f *File) dottedUsers() []string { for u := range f.IgnoredUsers { seen[u] = true } + for u := range f.FileTransferUsers { + seen[u] = true + } + for u := range f.FileTransferQuotaUsers { + seen[u] = true + } + for u := range f.FileTransferRateUsers { + seen[u] = true + } var out []string for u := range seen { if strings.Contains(u, ".") { @@ -240,6 +309,9 @@ func DropDottedUserKeys(path string) (text []byte, dropped []DroppedSetting, err if on, ok := f.IgnoredUsers[u]; ok { dropped = append(dropped, DroppedSetting{u, "'users' override " + word(on)}) } + if what := f.fileTransferOf(u); what != "" { + dropped = append(dropped, DroppedSetting{u, "file transfer " + what}) + } } if len(dropped) == 0 { return data, nil, nil diff --git a/internal/devssh/cli.go b/internal/devssh/cli.go index bba244f3..496a79ee 100644 --- a/internal/devssh/cli.go +++ b/internal/devssh/cli.go @@ -1142,8 +1142,10 @@ const minWrappedCmd = 40 // carriage returns (dropped by normalise) in between. The echo is the lines // at the start of body that, cleaned of control characters, are pieces of cmd // (a '$' marks where the display was cut), up to the line whose last piece -// ends cmd, when the first line is the start of cmd. Anything else is output and body is -// left as it is (ok false). +// ends cmd. The first line is either the start of cmd, or, when the device +// redrew the line in place or the start of the echo is not in body, a '$' and +// the rest of cmd (the tail). Anything else is output and body is left as it +// is (ok false). func wrappedEcho(body, cmd string) (string, bool) { if len(cmd) < minWrappedCmd { return body, false @@ -1151,8 +1153,9 @@ func wrappedEcho(body, cmd string) (string, bool) { lines := strings.SplitAfter(body, "\n") n, ended := 0, false for i, l := range lines { - pieces := echoPieces(strings.TrimRight(l, "\n"), cmd) - if len(pieces) == 0 || i == 0 && (len(pieces[0]) < 8 || !strings.HasPrefix(cmd, pieces[0])) { + l = strings.TrimRight(l, "\n") + pieces := echoPieces(l, cmd) + if len(pieces) == 0 || i == 0 && !echoStart(l, pieces, cmd) { break } n = i + 1 @@ -1167,6 +1170,16 @@ func wrappedEcho(body, cmd string) (string, bool) { return strings.Join(lines[n:], ""), true } +// echoStart reports whether line, the first line of body and made of pieces +// of cmd, can start the echo: it is the start of cmd (8 characters or more), +// or it is a tail, a line the terminal shows as a '$' and the rest of cmd. +func echoStart(line string, pieces []string, cmd string) bool { + if len(pieces[0]) >= 8 && strings.HasPrefix(cmd, pieces[0]) { + return true + } + return strings.HasPrefix(strings.TrimSpace(cleanTerminal(line)), "$") +} + // echoPieces are the pieces of cmd a line of its echo holds, none when the // line is not made only of pieces of cmd. func echoPieces(line, cmd string) []string { diff --git a/internal/devssh/devssh_test.go b/internal/devssh/devssh_test.go index a2fc3b85..b07fa4b2 100644 --- a/internal/devssh/devssh_test.go +++ b/internal/devssh/devssh_test.go @@ -316,6 +316,40 @@ func TestShellDropsAWrappedEcho(t *testing.T) { } } +// A device whose echo of a long command reaches the reader as the tail only +// (the start of it is not a line of its own, or the line is redrawn in place +// and shows the tail) leaves none of it in the output either, and a line of +// the answer that is like the tail stays. +func TestShellDropsTheTailOfAWrappedEcho(t *testing.T) { + t.Parallel() + const cmd = "show running-config | include ^(hostname|ip domain|clock timezone|snmp-server location|snmp-server contact)" + const out = "hostname sw1.example.net\nip domain-name example.net\n$ snmp-server contact)\n" + for name, opt := range map[string]fakedev.Option{ + "tail lines": fakedev.WithTailEcho(72), + "narrow tail": fakedev.WithTailEcho(48), // the tail over two lines + "redrawn": fakedev.WithRedrawnEcho(72), + "redrawn narrow": fakedev.WithRedrawnEcho(48), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + dir := transcript(t, map[string]string{"prompt": "rtr1#", cmd + ".out": out}) + srv := serve(t, dir, opt) + s, err := dial(t, target(t, srv, nil)).CLI(devssh.VendorCisco, devssh.WithPTY()) + if err != nil { + t.Fatal(err) + } + for range 2 { // the second command starts from the state the first left + if got, err := s.Run(bg(), cmd); err != nil || got != out { + t.Fatalf("got %q, %v", got, err) + } + } + if got, err := s.Run(bg(), "show version"); err != nil || strings.Contains(got, "$") { + t.Fatalf("short command: %q, %v", got, err) + } + }) + } +} + func TestExecCLI(t *testing.T) { t.Parallel() dir := transcript(t, map[string]string{ diff --git a/internal/devssh/fakedev/fakedev.go b/internal/devssh/fakedev/fakedev.go index d5c22068..d0af119a 100644 --- a/internal/devssh/fakedev/fakedev.go +++ b/internal/devssh/fakedev/fakedev.go @@ -243,6 +243,22 @@ func WithEcho(on bool) Option { return func(s *Server) { s.echo = on } } // '$', each at most width-1 characters. func WithWrappedEcho(width int) Option { return func(s *Server) { s.wrap = width } } +// WithTailEcho is WithWrappedEcho for a device whose echo of the start of +// the command is not seen: only the lines that start with '$', the tail of +// the command, are written (the shape a real IOS 12.4 session left in a +// support bundle, 0.2.27). +func WithTailEcho(width int) Option { + return func(s *Server) { s.wrap, s.wrapStyle = width, wrapTail } +} + +// WithRedrawnEcho is WithWrappedEcho for a device that redraws the line in +// place instead of starting another: the first width characters, backspaces +// back over them and the '$' and the rest of the command over those, blanks +// to the end, all on one line, so the line a terminal shows is the tail. +func WithRedrawnEcho(width int) Option { + return func(s *Server) { s.wrap, s.wrapStyle = width, wrapRedrawn } +} + // WithHang stops the server answering at stage, for the timeout tests; the // connections are held until Stop. func WithHang(st Stage) Option { return func(s *Server) { s.hang, s.hangSet = st, true } } @@ -262,6 +278,7 @@ type Server struct { framing Framing echo bool wrap int // WithWrappedEcho + wrapStyle int // wrapLines, wrapTail or wrapRedrawn menuScreens string @@ -728,18 +745,36 @@ func (s *Server) shell(ch ssh.Channel) { } } +// The ways a wrapped echo (WithWrappedEcho) is written. +const ( + wrapLines = iota // the start of the command on a line, the tail on lines of their own + wrapTail // the tail lines only + wrapRedrawn // one line, redrawn in place +) + // echoOf is what the session writes back for the command typed. func (s *Server) echoOf(cmd string) string { if s.wrap <= 0 || len(cmd) <= s.wrap { return cmd + "\r\n" } - out := cmd[:s.wrap] + "\r\n" + var tail []string for rest := cmd[s.wrap:]; rest != ""; { n := min(s.wrap-1, len(rest)) - out += "$" + rest[:n] + "\r\n" + tail = append(tail, "$"+rest[:n]) rest = rest[n:] } - return out + switch s.wrapStyle { + case wrapTail: + return strings.Join(tail, "\r\n") + "\r\n" + case wrapRedrawn: + // Each tail line is drawn over the one before it, blanks and all. + out := cmd[:s.wrap] + for _, t := range tail { + out += strings.Repeat("\b", s.wrap) + t + strings.Repeat(" ", max(s.wrap-len(t), 0)) + } + return out + "\r\n" + } + return cmd[:s.wrap] + "\r\n" + strings.Join(tail, "\r\n") + "\r\n" } // page writes out, stopping after every pageLen lines for a key when diff --git a/internal/devssh/internal_test.go b/internal/devssh/internal_test.go index 58835296..1881b09e 100644 --- a/internal/devssh/internal_test.go +++ b/internal/devssh/internal_test.go @@ -214,6 +214,44 @@ func TestStripEchoOfAWrappedCommand(t *testing.T) { } } +// A device that scrolled the echo of a long command leaves a body that starts +// at the tail of it, the '$' and the rest of the command: the start of the +// echo is not a line of its own (IOS redraws the line in place, or the +// display is cut), and the tail is dropped as well. Nothing else is. +func TestStripEchoOfTheTailOfAWrappedCommand(t *testing.T) { + t.Parallel() + const cmd = "show running-config | include ^(hostname|ip domain|clock timezone|snmp-server location|snmp-server contact)" + const out = "hostname sw1.example.net\nip domain-name example.net\n" + tail := "$" + cmd[60:] + for name, c := range map[string]struct{ body, want string }{ + "tail only": {tail + "\n" + out, out}, + "tail, no output": {tail + "\n", ""}, + "tail of pieces": {"$" + cmd[40:60] + "$" + cmd[60:] + "\n" + out, out}, + "tail, backspaces": {"$" + cmd[60:] + "x\b \b\n" + out, out}, + "tail, escape": {"$" + cmd[60:] + "\x1b[K\n" + out, out}, + "tail in two": {"$" + cmd[50:80] + "\n$" + cmd[80:] + "\n" + out, out}, + "collapsed line": {cmd[:64] + strings.Repeat("\b", 64) + "$" + cmd[60:] + strings.Repeat(" ", 64-len(tail)) + "\n" + out, out}, + // not an echo: a piece that is not in the command, an end that is not the end of it, + // a line that is only like a piece, or a tail that is not the first line + "foreign piece": {"$" + cmd[60:] + "$ other text\n" + out, "$" + cmd[60:] + "$ other text\n" + out}, + "foreign tail": {"$clock timezone|snmp-server location|snmp-server contact) extra\n" + out, "$clock timezone|snmp-server location|snmp-server contact) extra\n" + out}, + "not the end": {"$" + cmd[60:90] + "\n" + out, "$" + cmd[60:90] + "\n" + out}, + "not the end, two": {"$" + cmd[40:60] + "\n$" + cmd[60:90] + "\n" + out, "$" + cmd[40:60] + "\n$" + cmd[60:90] + "\n" + out}, + "output with $": {"$ something\n" + out, "$ something\n" + out}, + "output with $, a piece": {"$ snmp-server\n" + out, "$ snmp-server\n" + out}, + "no $, a piece": {cmd[60:] + "\n" + out, cmd[60:] + "\n" + out}, + "after output": {out + tail + "\n", out + tail + "\n"}, + } { + if got := stripEcho(c.body, cmd); got != c.want { + t.Errorf("%s: stripEcho = %q, want %q", name, got, c.want) + } + } + // A short command never looks for pieces. + if got := stripEcho("$clock\nx\n", "show clock"); got != "$clock\nx\n" { + t.Errorf("short command: %q", got) + } +} + func TestStripEcho(t *testing.T) { t.Parallel() for _, c := range []struct{ body, cmd, want string }{ diff --git a/internal/lifecycle/rollback.go b/internal/lifecycle/rollback.go index 2592ce9b..e0645959 100644 --- a/internal/lifecycle/rollback.go +++ b/internal/lifecycle/rollback.go @@ -6,9 +6,10 @@ package lifecycle // one. The command (internal/cli/rollback.go) adds what needs the // invocation: the snapshot and the sudoers installer. // -// The targets are 0.2.26 (the release before this one: RollbackTarget0226; -// rollback0226.go: nothing, this release changed no stored file 0.2.26 reads -// strictly), 0.2.25 (RollbackTarget0225; rollback0225.go: the limits of the +// The targets are 0.2.27 (the release before this one: RollbackTarget0227; +// rollback0227.go: nothing, this release changed no stored file 0.2.27 reads +// strictly), 0.2.26 (RollbackTarget0226; rollback0226.go: nothing, 0.2.27 and +// this release changed no stored file it reads strictly), 0.2.25 (RollbackTarget0225; rollback0225.go: the limits of the // stored reports, which are keys and fields it refuses, and the per-tier // sudoers drop-in), 0.2.24 // (RollbackTarget0224; rollback0224.go: the same, 0.2.24 and 0.2.25 read the @@ -131,7 +132,7 @@ package lifecycle // // The SNMP credential files (0.2.23, version 2: a pool of v3 users and a // default) are a format every older release refuses, so every target but -// 0.2.26, 0.2.25, 0.2.24 and 0.2.23 writes them as version 1 again, keeping each level's +// 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 writes them as version 1 again, keeping each level's // default user and dropping the rest, with a warning that names the levels and counts the users, and refuses // a level with several users and no default (rollback_snmp_pool.go, an entry // of rollbackAdditions); 'tacctl backup recover --only snmp-users' puts the @@ -201,8 +202,8 @@ import ( // before the users' email addresses, RollbackTarget0223 the one before the // break-glass firewall, RollbackTarget0224 the one before the limits of the // stored reports (it reads what 0.2.25 reads), RollbackTarget0225 the one -// before the limits of the stored reports and RollbackTarget0226 the release -// before this one (0.2.10 to 0.2.16 changed no format 0.2.9 reads strictly, so 0.2.9 stays a +// before the limits of the stored reports, RollbackTarget0226 the one before +// the PDF reports and RollbackTarget0227 the release before this one (0.2.10 to 0.2.16 changed no format 0.2.9 reads strictly, so 0.2.9 stays a // target; 0.2.18 changed none 0.2.16 or 0.2.17 reads, so 0.2.16 stays one // too). const ( @@ -219,6 +220,7 @@ const ( RollbackTarget0224 = "0.2.24" RollbackTarget0225 = "0.2.25" RollbackTarget0226 = "0.2.26" + RollbackTarget0227 = "0.2.27" ) // RollbackRefusal is a version the command does not take: Lines say why. @@ -302,9 +304,9 @@ func pluralWord(n int, one, many string) string { var reVersion = regexp.MustCompile(`^v?([0-9]+)\.([0-9]+)\.([0-9]+)$`) -const rollbackUsage = "Usage: tacctl rollback " + RollbackTarget0226 + "|" + RollbackTarget0225 + "|" + RollbackTarget0224 + "|" + RollbackTarget0223 + "|" + RollbackTarget0222 + "|" + RollbackTarget0221 + "|" + RollbackTarget0220 + "|" + RollbackTarget0219 + "|" + RollbackTarget0218 + "|" + RollbackTarget0217 + "|" + RollbackTarget0216 + "|" + RollbackTarget029 + "|" + RollbackTarget + " [--apply] [--yes] [--hosts]" +const rollbackUsage = "Usage: tacctl rollback " + RollbackTarget0227 + "|" + RollbackTarget0226 + "|" + RollbackTarget0225 + "|" + RollbackTarget0224 + "|" + RollbackTarget0223 + "|" + RollbackTarget0222 + "|" + RollbackTarget0221 + "|" + RollbackTarget0220 + "|" + RollbackTarget0219 + "|" + RollbackTarget0218 + "|" + RollbackTarget0217 + "|" + RollbackTarget0216 + "|" + RollbackTarget029 + "|" + RollbackTarget + " [--apply] [--yes] [--hosts]" -// CheckRollbackVersion is the version a rollback is asked for ("0.2.26", "0.2.25", "0.2.24", "0.2.23", "0.2.22", "0.2.21", +// CheckRollbackVersion is the version a rollback is asked for ("0.2.27", "0.2.26", "0.2.25", "0.2.24", "0.2.23", "0.2.22", "0.2.21", // "0.2.20", "0.2.19", "0.2.18", "0.2.17", "0.2.16", "0.2.9", "0.2.3" or any with a "v"), or a *RollbackRefusal: 0.2.4 // to 0.2.8 and older than 0.2.3 (a release's tool prepares the state for the // releases it knows, so the way back is one release at a time), 0.2.10 to @@ -319,11 +321,11 @@ func CheckRollbackVersion(arg string) (string, error) { rollbackUsage}} } v := strings.TrimPrefix(arg, "v") - if v == RollbackTarget || v == RollbackTarget029 || v == RollbackTarget0216 || v == RollbackTarget0217 || v == RollbackTarget0218 || v == RollbackTarget0219 || v == RollbackTarget0220 || v == RollbackTarget0221 || v == RollbackTarget0222 || v == RollbackTarget0223 || v == RollbackTarget0224 || v == RollbackTarget0225 || v == RollbackTarget0226 { + if v == RollbackTarget || v == RollbackTarget029 || v == RollbackTarget0216 || v == RollbackTarget0217 || v == RollbackTarget0218 || v == RollbackTarget0219 || v == RollbackTarget0220 || v == RollbackTarget0221 || v == RollbackTarget0222 || v == RollbackTarget0223 || v == RollbackTarget0224 || v == RollbackTarget0225 || v == RollbackTarget0226 || v == RollbackTarget0227 { return v, nil } n := func(i int) int { x, _ := strconv.Atoi(m[i]); return x } - both := "'tacctl rollback' prepares the state for " + RollbackTarget0226 + " (the release before this one), " + RollbackTarget0225 + ", " + RollbackTarget0224 + ", " + RollbackTarget0223 + ", " + RollbackTarget0222 + ", " + RollbackTarget0221 + ", " + RollbackTarget0220 + ", " + RollbackTarget0219 + ", " + RollbackTarget0218 + ", " + RollbackTarget0217 + ", " + RollbackTarget0216 + ", " + RollbackTarget029 + " and " + RollbackTarget + " only" + both := "'tacctl rollback' prepares the state for " + RollbackTarget0227 + " (the release before this one), " + RollbackTarget0226 + ", " + RollbackTarget0225 + ", " + RollbackTarget0224 + ", " + RollbackTarget0223 + ", " + RollbackTarget0222 + ", " + RollbackTarget0221 + ", " + RollbackTarget0220 + ", " + RollbackTarget0219 + ", " + RollbackTarget0218 + ", " + RollbackTarget0217 + ", " + RollbackTarget0216 + ", " + RollbackTarget029 + " and " + RollbackTarget + " only" fallback := "The fallback that needs no tool is 'tacctl backup restore' of a snapshot of the time (see 'tacctl backup list')." switch { case n(1) == 0 && n(2) == 2 && n(3) > 3 && n(3) < 9: @@ -420,7 +422,7 @@ type RollbackInput struct { HasStore bool // WithHosts: the command was given --hosts. WithHosts bool - // Target is the release rolled back to: RollbackTarget0226, RollbackTarget0225, RollbackTarget0224, RollbackTarget0219, + // Target is the release rolled back to: RollbackTarget0227, RollbackTarget0226, RollbackTarget0225, RollbackTarget0224, RollbackTarget0219, // RollbackTarget0218, RollbackTarget0217, RollbackTarget0216, RollbackTarget029 or RollbackTarget (the zero value is 0.2.3, as // before 0.2.9). Target string @@ -462,6 +464,10 @@ type RollbackPlan struct { in RollbackInput keys []string console console.RollbackPlan + // consoleSince0228: console.yaml was planned by the addition of 0.2.28 + // (rollback_filetransfer.go) and not by the target's own plan, so only + // the file transfer settings go and the write is console.RollbackSince0228. + consoleSince0228 bool // managedUsers are the users the scope of this server's own login is // added to (rollback_managed.go): every target. managedUsers []string @@ -624,13 +630,19 @@ func planRollback(in RollbackInput) (*RollbackPlan, error) { if len(pend) > 0 { return nil, PendingRefusal(pend) } - // 0.2.26 reads every file this release writes: it converts nothing - // (rollback0226.go), and has the managed scope of the server's own login, + // 0.2.27 reads every file this release writes: it converts nothing + // (rollback0227.go), and has the managed scope of the server's own login, // so nothing is added to the users. + if in.Target == RollbackTarget0227 { + return planRollback0227(p) + } + // 0.2.26 reads every file 0.2.27 and this release write: it converts + // nothing (rollback0226.go), and has the managed scope of the server's own + // login, so nothing is added to the users. if in.Target == RollbackTarget0226 { return planRollback0226(p) } - // 0.2.25 reads every file 0.2.26 and this release write but what a step of + // 0.2.25 reads every file 0.2.26, 0.2.27 and this release write but what a step of // rollbackAdditions undoes and the key list (rollback0225.go): the limits // of the stored reports, and the per-tier sudoers drop-in; it has the // managed scope of the server's own login, so nothing is added to the @@ -881,7 +893,11 @@ func (p *RollbackPlan) addConsoleStep() { } cf := p.in.Paths.ConsoleFile s := RollbackStep{Title: cf + ": take out the settings " + p.target() + " does not know", Todo: true} - s.Lines = append(p.consoleChangeLines(), "("+p.target()+"'s parser rejects what 0.2.20 added to console.yaml (the colour setting, the system shell and the password cache of single users, a list_max of -1); everything else is kept)") + why := "what 0.2.20 added to console.yaml (the colour setting, the system shell and the password cache of single users, a list_max of -1) and the file transfer settings of 0.2.28" + if p.consoleSince0228 { + why = "the file transfer settings 0.2.28 added to console.yaml" + } + s.Lines = append(p.consoleChangeLines(), "("+p.target()+"'s parser rejects "+why+"; everything else is kept)") at := len(p.Steps) for i := range p.Steps { if p.Steps[i].Title == "leave every other file untouched" { @@ -1240,7 +1256,10 @@ func ApplyRollback(p *RollbackPlan) ([]string, error) { } if p.console.Text != nil { write := console.RollbackSince0220 - if p.target() == RollbackTarget { + switch { + case p.consoleSince0228: + write = console.RollbackSince0228 + case p.target() == RollbackTarget: write = console.Rollback } changed, err := write(pt.ConsoleFile, nil) diff --git a/internal/lifecycle/rollback0216_test.go b/internal/lifecycle/rollback0216_test.go index 77a35c4f..ab22c9d0 100644 --- a/internal/lifecycle/rollback0216_test.go +++ b/internal/lifecycle/rollback0216_test.go @@ -187,7 +187,7 @@ func TestCheckRollbackVersion0216(t *testing.T) { t.Errorf("%s: %q %v", ok, v, err) } } - for _, bad := range []string{"0.2.15", "0.2.10", "0.2.27", "0.2.160", "0.2.170"} { + for _, bad := range []string{"0.2.15", "0.2.10", "0.2.28", "0.2.160", "0.2.170"} { if _, err := CheckRollbackVersion(bad); err == nil { t.Errorf("%s was accepted", bad) } diff --git a/internal/lifecycle/rollback0218.go b/internal/lifecycle/rollback0218.go index d20bcf28..80724641 100644 --- a/internal/lifecycle/rollback0218.go +++ b/internal/lifecycle/rollback0218.go @@ -123,7 +123,7 @@ func (p *RollbackPlan) lockdownKeysStep(target string) RollbackStep { s.Lines = []string{"nothing to remove (no server address, server name or timeout scale is set)"} case RollbackTarget0221: s.Lines = []string{"nothing to remove (no server name or timeout scale is set)"} - case RollbackTarget0222, RollbackTarget0223, RollbackTarget0224, RollbackTarget0225, RollbackTarget0226: + case RollbackTarget0222, RollbackTarget0223, RollbackTarget0224, RollbackTarget0225, RollbackTarget0226, RollbackTarget0227: s.Lines = []string{"nothing to remove (every key of tacctl.yaml is one " + target + " knows)"} } return s diff --git a/internal/lifecycle/rollback0222.go b/internal/lifecycle/rollback0222.go index 6489e343..296c5d3c 100644 --- a/internal/lifecycle/rollback0222.go +++ b/internal/lifecycle/rollback0222.go @@ -1,10 +1,10 @@ package lifecycle // The rollback to 0.2.22, the release before 0.2.23 (rollback0223.go). -// 0.2.22 reads every file 0.2.23 to 0.2.26 and this release write but what a step of +// 0.2.22 reads every file 0.2.23 to 0.2.27 and this release write but what a step of // rollbackAdditions (rollback_additions.go) undoes, so the plan of the target converts nothing // of its own: it leaves every file alone but the per-tier sudoers drop-in -// when it is exactly this release's text (the same as 0.2.26's), 0.2.25's or 0.2.23's (it loses the engineer's +// when it is exactly this release's text (the same as 0.2.27's and 0.2.26's), 0.2.25's or 0.2.23's (it loses the engineer's // row of 'device clone', tier.Sudoers0222, and the same goes for 0.2.21 and // 0.2.20, which wrote the same text), and a change of this release that // 0.2.22 refuses (the users' email addresses, rollback_email.go) is a step of diff --git a/internal/lifecycle/rollback0223.go b/internal/lifecycle/rollback0223.go index 0e746580..cf0b4a4b 100644 --- a/internal/lifecycle/rollback0223.go +++ b/internal/lifecycle/rollback0223.go @@ -3,9 +3,9 @@ package lifecycle // The rollback to 0.2.23, the release before 0.2.24 (rollback0224.go). 0.2.24 // changed no stored file 0.2.23 reads strictly but the break-glass firewall // setting (a step of rollbackAdditions undoes it, rollback_firewall.go), so -// 0.2.23 reads every file 0.2.24 to 0.2.26 and this release write, and the plan of the +// 0.2.23 reads every file 0.2.24 to 0.2.27 and this release write, and the plan of the // target converts nothing but the per-tier sudoers drop-in: when it is -// exactly the text of 0.2.24 and 0.2.25, or the one 0.2.26 and this release +// exactly the text of 0.2.24 and 0.2.25, or the one 0.2.26, 0.2.27 and this release // write (with the rows of 'device reports' more), it is rewritten with // 0.2.23's (tier.Sudoers0223, without the operator's 'log failures *', which // 0.2.23 does not know; sudo would accept the row, but 0.2.23's upgrade @@ -50,7 +50,7 @@ func planRollback0223(p *RollbackPlan) (*RollbackPlan, error) { } // tiers0223Step plans the per-tier sudoers drop-in for the target: exactly -// the text of 0.2.24 and 0.2.25, or the one of 0.2.26 and this release, is rewritten with 0.2.23's (tier.Sudoers0223), which +// the text of 0.2.24 and 0.2.25, or the one of 0.2.26, 0.2.27 and this release, is rewritten with 0.2.23's (tier.Sudoers0223), which // takes out the operator's row of 'log failures *'. A file that is already // that text, or absent, needs no step; any other text is left and said so. func (p *RollbackPlan) tiers0223Step(target string) []RollbackStep { diff --git a/internal/lifecycle/rollback0224.go b/internal/lifecycle/rollback0224.go index dbbdd41a..05df10b0 100644 --- a/internal/lifecycle/rollback0224.go +++ b/internal/lifecycle/rollback0224.go @@ -7,10 +7,10 @@ package lifecycle // virtual chassis's commit answers and the cleaning of a device's text are // code only), so 0.2.24 reads the same files as 0.2.25 and the plan of the // target is the one of 0.2.25 (planRollbackAfter0224): it removes the limits -// of the stored reports of 0.2.26 and this release (the two keys of +// of the stored reports of 0.2.26 and the releases after it (the two keys of // tacctl.yaml, and the users' own limits through a step of // rollbackAdditions), puts back the per-tier sudoers drop-in of 0.2.24 and -// 0.2.25 (the same text) when the text 0.2.26 and this release write differs, +// 0.2.25 (the same text) when the text 0.2.26 and the releases after it write differs, // and leaves every other file alone. No other step of // rollbackAdditions fires for it: they undo what 0.2.24 and older releases // changed, for the targets older than the release that made the change, so diff --git a/internal/lifecycle/rollback0225.go b/internal/lifecycle/rollback0225.go index f1e30638..f8f30ec8 100644 --- a/internal/lifecycle/rollback0225.go +++ b/internal/lifecycle/rollback0225.go @@ -22,7 +22,7 @@ package lifecycle // 0.2.25, having no 'device reports' verb, never opens. It takes a snapshot // only when a key or a field is removed (PendingFiles), and the per-tier // sudoers drop-in is rewritten with 0.2.25's text only when the text 0.2.26 -// and this release write differs from it (the rows of 'device reports', +// and the releases after it write differs from it (the rows of 'device reports', // tier.Sudoers0225). import "github.com/rett/tacctl/internal/tier" diff --git a/internal/lifecycle/rollback0226.go b/internal/lifecycle/rollback0226.go index ed426ee7..61f85df5 100644 --- a/internal/lifecycle/rollback0226.go +++ b/internal/lifecycle/rollback0226.go @@ -1,32 +1,39 @@ package lifecycle -// The rollback to 0.2.26, the release before this one. This release changed -// no stored file 0.2.26 reads strictly: what it changed is the reader of the -// 'show switch' table of an IOS stack (a blank H/W version column), what the -// reports of a user below the operator tier hold (no model, serial number, -// release or chassis members, as 'device show' leaves them out), the audit -// line a prune of another user's reports writes, the wording of two notes, -// and the documentation. The stored state files, the per-tier sudoers text, -// the keys of tacctl.yaml, the fields of the store and the format of the pull -// records are all as 0.2.26 reads them. So 0.2.26 reads every file this one -// writes and the plan of the target converts nothing: it leaves every file -// alone, the per-tier sudoers drop-in included (0.2.26 and this release write -// the same text), removes no key (the limits of the stored reports, -// reports.max_size and reports.max_count in tacctl.yaml and a user's own -// limits in the store, stay: 0.2.26 has them) and takes no snapshot. The -// reports in the users' homes stay too: 0.2.26 reads them. No step of -// rollbackAdditions fires for it either: they undo what 0.2.26 and older +// The rollback to 0.2.26, the release before 0.2.27 (rollback0227.go). 0.2.27 +// changed no stored file 0.2.26 reads strictly: what it changed is the reader +// of the 'show switch' table of an IOS stack (a blank H/W version column), +// what the reports of a user below the operator tier hold (no model, serial +// number, release or chassis members, as 'device show' leaves them out), the +// audit line a prune of another user's reports writes, the PDF format of the +// reports and the offer of its tools (a report file in the user's home, and a +// marker no release reads but 0.2.27 and the ones after it), the wording of +// two notes, and the documentation. The stored state files, the per-tier +// sudoers text, the keys of tacctl.yaml, the fields of the store and the +// format of the pull records are all as 0.2.26 reads them. So 0.2.26 reads +// every file 0.2.27 and this release write and the plan of the target +// converts nothing: it leaves every file alone, the per-tier sudoers drop-in +// included (0.2.26, 0.2.27 and this release write the same text), removes no +// key (the limits of the stored reports, reports.max_size and +// reports.max_count in tacctl.yaml and a user's own limits in the store, stay: +// 0.2.26 has them) and takes no snapshot but for the file below. The reports in the users' homes +// stay too: 0.2.26 reads them (a PDF one as text, which is why the upgrade +// pages say to fetch it with the scp line of 'show'). The one file it does +// not read as this release writes it is console.yaml with the file transfer +// settings of 0.2.28 (settings.file_transfer, an unknown key to its reader), +// which an entry of rollbackAdditions removes (rollback_filetransfer.go). No +// other step of rollbackAdditions fires for it either: they undo what 0.2.26 and older // releases changed, for the targets older than the release that made the // change. // -// What this release changed outside the stored files is 0.2.26's to undo or -// keep, and needs no step here: the next 'device config pull' with 0.2.26 -// records a stack member with a blank H/W version column as it did before -// (the row is not read), and a report made by a user below the operator tier -// holds the facts of the pull again. +// What 0.2.27 and this release changed outside the stored files is 0.2.26's to +// undo or keep, and needs no step here: the next 'device config pull' with +// 0.2.26 records a stack member with a blank H/W version column as it did +// before (the row is not read), and a report made by a user below the +// operator tier holds the facts of the pull again. // planRollback0226 completes p (a plan whose tacctl.yaml was read and whose -// records hold no unsettled apply) for the release before this one. +// records hold no unsettled apply) for 0.2.26. func planRollback0226(p *RollbackPlan) (*RollbackPlan, error) { pt := p.in.Paths p.Steps = append(p.Steps, p.lockdownKeysStep(RollbackTarget0226)) diff --git a/internal/lifecycle/rollback0226_test.go b/internal/lifecycle/rollback0226_test.go index cb444957..6aa4d486 100644 --- a/internal/lifecycle/rollback0226_test.go +++ b/internal/lifecycle/rollback0226_test.go @@ -12,7 +12,7 @@ import ( ) // The rollback to 0.2.26 on the sandbox of rollback_test.go: this release -// changed no stored file 0.2.26 reads strictly, so the plan converts nothing, +// and 0.2.27 changed no stored file 0.2.26 reads strictly, so the plan converts nothing, // whatever 0.2.26 itself added to the state (the limits of the stored reports // and the break-glass firewall included). diff --git a/internal/lifecycle/rollback0227.go b/internal/lifecycle/rollback0227.go new file mode 100644 index 00000000..9631b82a --- /dev/null +++ b/internal/lifecycle/rollback0227.go @@ -0,0 +1,51 @@ +package lifecycle + +// The rollback to 0.2.27, the release before this one. This release changed +// one stored file 0.2.27 reads strictly: console.yaml, which gained +// settings.file_transfer (the console's file transfer, off by default, per +// tier and per user, with a quota and a rate), a key 0.2.27's reader answers +// with "settings: unknown key 'file_transfer'" (the console then falls back to +// its defaults and every 'console' command that writes the file fails). So +// when the key is there the plan removes it, after the snapshot --apply takes +// first, and keeps every other setting; rollback_filetransfer.go is that step, +// an entry of rollbackAdditions that every older target has too. With the +// settings unset the plan converts nothing, as the rest of this release's +// changes need no conversion. +// +// What else this release changed is the code that reads the answer of a +// Cisco IOS device to a long command (the tail of the echo that the device +// cuts and redraws is dropped as well, so a support bundle no longer starts +// its identity lines with it), and the documentation. The stored state files, +// the per-tier sudoers text, the keys of tacctl.yaml, the fields of the store, +// the format of the pull records and of the reports in the users' homes are +// all as 0.2.27 reads them. So 0.2.27 reads every other file this one writes +// and the plan of the target leaves them alone, the per-tier sudoers drop-in +// included (0.2.27 and this release write the same text), removes no key of +// tacctl.yaml (the limits of the stored reports, reports.max_size and +// reports.max_count in tacctl.yaml and a user's own limits in the store, stay: +// 0.2.27 has them) and takes a snapshot only for the file transfer settings. +// The reports in the users' homes stay too, the PDF ones included (0.2.27 +// reads them), and so does the marker /var/lib/tacctl/pdf-tools-offered, which +// this release and 0.2.27 write alike. No other step of rollbackAdditions +// fires for it either: they undo what 0.2.26 and older releases changed, for +// the targets older than the release that made the change. +// +// What this release changed outside the stored files is 0.2.27's to undo or +// keep, and needs no step here: the next support bundle of a device with +// 0.2.27 starts the identity lines of an IOS device with the tail of a long +// command's echo again, as it did before. + +// planRollback0227 completes p (a plan whose tacctl.yaml was read and whose +// records hold no unsettled apply) for the release before this one. +func planRollback0227(p *RollbackPlan) (*RollbackPlan, error) { + pt := p.in.Paths + p.Steps = append(p.Steps, p.lockdownKeysStep(RollbackTarget0227)) + p.Steps = append(p.Steps, RollbackStep{Title: "leave every other file untouched", + Lines: []string{pt.StoreFile + ", " + pt.DevicesFile + ", " + pt.ConsoleFile + ", the per-tier and the group sudoers drop-ins, the SNMP credentials, the pull records, the reports in the users' homes, the blocks, the apply state directory, the host registry and the rendered backend files are in formats " + RollbackTarget0227 + " reads;", + "nothing is re-rendered or restarted, and no device is contacted"}}) + if p.in.WithHosts { + p.Steps = append(p.Steps, RollbackStep{Title: "the enrolled Linux hosts (--hosts)", + Lines: []string{"nothing to do for " + RollbackTarget0227 + ": this release changed nothing on the enrolled hosts; no host is synced"}}) + } + return p, nil +} diff --git a/internal/lifecycle/rollback0227_test.go b/internal/lifecycle/rollback0227_test.go new file mode 100644 index 00000000..7806c4d8 --- /dev/null +++ b/internal/lifecycle/rollback0227_test.go @@ -0,0 +1,208 @@ +package lifecycle + +import ( + "context" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/rett/tacctl/internal/execx" + "github.com/rett/tacctl/internal/tier" +) + +// The rollback to 0.2.27 on the sandbox of rollback_test.go: this release +// changed no stored file 0.2.27 reads strictly, so the plan converts nothing, +// whatever 0.2.27 itself added to the state (the limits of the stored reports +// and the break-glass firewall included). + +func plan0227(t *testing.T, s *rbSandbox) *RollbackPlan { + t.Helper() + s.in.Target = RollbackTarget0227 + p, err := PlanRollback(s.in) + if err != nil { + t.Fatal(err) + } + return p +} + +// The plan leaves every file, asks for no --yes, takes no snapshot and keeps +// what 0.2.27 has and the older targets drop: the limits of the stored reports +// (the two settings and the users' own), the users' email addresses, a pool of +// SNMPv3 users, a staging entry marked covered, the break-glass firewall (its +// setting, its rules file and its boot unit) and the per-tier drop-in, which +// 0.2.27 and this release write alike. It writes nothing. +func TestPlanRollback0227ConvertsNothing(t *testing.T) { + s := poolState(t) + s.write(s.p.TierSudoersFile, tier.Sudoers(), 0o640) + rbStoreLimits(t, s, true) + s.write(s.p.StateDir+"/staging", stagingKept+stagingCovered, 0o600) + s.write(s.p.Overrides, "breakglass:\n firewall: drop\nreports:\n max_size: 20971520\n max_count: 0\n", 0o600) + s.in.Conf.Reload() + s.write(s.p.FirewallRules, "table inet tacctl\n", 0o600) + s.write(s.p.FirewallUnit, "[Unit]\n", 0o644) + calls := 0 + s.in.RemoveFirewall = func() ([]string, error) { calls++; return []string{"the nftables table inet tacctl"}, nil } + before := s.snapshotOf() + p := plan0227(t, s) + if p.Target != RollbackTarget0227 { + t.Errorf("target %q", p.Target) + } + st := stepText(p) + for _, w := range []string{s.p.Overrides + ": remove the keys 0.2.27 does not know", "nothing to remove (every key of tacctl.yaml is one 0.2.27 knows)", + "leave every other file untouched", "are in formats 0.2.27 reads", "the pull records, the reports in the users' homes"} { + if !strings.Contains(st, w) { + t.Errorf("steps lack %q:\n%s", w, st) + } + } + for _, not := range []string{"remove device.", "remove server.", "remove breakglass", "remove reports", "firewall: remove", "email", "v3 user", "staging", "add scope", "0.2.3", "0.2.9", "report limits", "sudoers drop-in 0.2"} { + if strings.Contains(strings.ToLower(st), not) { + t.Errorf("steps name %q:\n%s", not, st) + } + } + for _, step := range p.Steps { + if step.Todo { + t.Errorf("step %q does something", step.Title) + } + } + if len(p.Keys()) != 0 || p.Pending() || p.PendingFiles() || p.NeedsYes() || len(p.Notes) != 0 || len(p.Warnings) != 0 || p.FirewallTodo() || + len(p.todoSudoers()) != 0 || len(p.managedUsers) != 0 || len(p.EmailUsers()) != 0 || p.SNMPPoolDropped().Any() || len(p.ReportLimitUsers()) != 0 { + t.Errorf("keys %q pending %v yes %v notes %q warnings %d sudoers %d managed %d email %q", p.Keys(), p.Pending(), p.NeedsYes(), p.Notes, len(p.Warnings), len(p.todoSudoers()), len(p.managedUsers), p.EmailUsers()) + } + if after := s.snapshotOf(); !reflect.DeepEqual(after, before) { + t.Error("the plan wrote a file") + } + if done, err := ApplyRollback(p); err != nil || len(done) != 0 || calls != 0 { + t.Errorf("apply: %q %v (firewall removed %d times)", done, err, calls) + } + if after := s.snapshotOf(); !reflect.DeepEqual(after, before) { + t.Error("the apply wrote a file") + } + if got := string(mustRead(t, s.p.TierSudoersFile)); got != tier.Sudoers() { + t.Error("the per-tier drop-in was rewritten") + } + // the 0.2.26 target converts nothing either, and the 0.2.25 target, on the + // same state, does convert (it is told apart) + s.in.Target = RollbackTarget0226 + if r, err := PlanRollback(s.in); err != nil || len(r.Keys()) != 0 || r.PendingFiles() || r.NeedsYes() { + t.Errorf("the 0.2.26 target converts something here: %v", err) + } + s.in.Target = RollbackTarget0225 + q, err := PlanRollback(s.in) + if err != nil { + t.Fatal(err) + } + if len(q.Keys()) == 0 || !q.PendingFiles() || !q.NeedsYes() { + t.Errorf("the 0.2.25 target converts nothing here: keys %q files %v yes %v", q.Keys(), q.PendingFiles(), q.NeedsYes()) + } +} + +// With no limit set, nothing is different: the plan converts nothing and +// asks for nothing, and the second plan after the apply is the first. +func TestPlanRollback0227ConvertsNothingWithoutLimits(t *testing.T) { + s := newRBSandbox(t) + before := s.snapshotOf() + p := plan0227(t, s) + if len(p.Keys()) != 0 || p.PendingFiles() || p.NeedsYes() || len(p.Warnings) != 0 || len(p.ReportLimitUsers()) != 0 { + t.Errorf("keys %q files %v yes %v warnings %d", p.Keys(), p.PendingFiles(), p.NeedsYes(), len(p.Warnings)) + } + if done, err := ApplyRollback(p); err != nil || len(done) != 0 { + t.Errorf("apply: %q %v", done, err) + } + if after := s.snapshotOf(); !reflect.DeepEqual(after, before) { + t.Error("the apply wrote a file") + } + p = plan0227(t, s) + if len(p.Keys()) != 0 || p.PendingFiles() { + t.Error("the second plan has something to do") + } +} + +// The pull records' members, the reports in the homes (a PDF one included), +// the marker of the offer of the PDF tools and the limits of the stored reports +// are left alone, bytes and all: the plan and the apply write none of them. +func TestPlanRollback0227LeavesTheRecordsTheReportsAndTheLimits(t *testing.T) { + s := newRBSandbox(t) + s.write(s.p.ConfigRecords, `{"version": 1, "devices": {"sw1": {"address": "192.0.2.11", "vendor": "juniper", "serial": "SN000001", + "members": [{"id": "0", "role": "master", "model": "EX4300-48T", "serial": "SN000001", "release": "21.4R3", "status": "present", "priority": 255, "components": []}]}}} +`, 0o600) + report := filepath.Join(s.w, "home", "alice", "reports", "devices", "inventory-20261106.txt") + s.write(report, "sw1 EX4300-48T SN000001\n", 0o600) + s.write(report+".meta", "{}\n", 0o600) + pdf := filepath.Join(s.w, "home", "alice", "reports", "devices", "inventory-20261107.pdf") + s.write(pdf, "%PDF-1.7\n", 0o600) + s.write(pdf+".meta", "{\"format\": \"pdf\"}\n", 0o600) + s.write(s.p.PDFOfferMarker, "tacctl 0.2.27 offered\n", 0o644) + s.write(s.p.Overrides, rbConf+"reports:\n max_count: 5\n", 0o640) + s.reload() + rbStoreLimits(t, s, false) + was := s.snapshotOf() + p := plan0227(t, s) + if _, err := ApplyRollback(p); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(was, s.snapshotOf()) { + t.Error("the rollback changed a pull record, a report, the PDF marker, tacctl.yaml or the store") + } + if got := string(mustRead(t, s.p.PDFOfferMarker)); got != "tacctl 0.2.27 offered\n" { + t.Errorf("the PDF marker: %q", got) + } + if got := string(mustRead(t, s.p.StoreFile)); !strings.Contains(got, "reports_max_size") || !strings.Contains(got, "reports_max_count") { + t.Errorf("the store lost a limit:\n%s", got) + } + if got := string(mustRead(t, s.p.Overrides)); !strings.Contains(got, "max_count: 5") { + t.Errorf("tacctl.yaml lost the setting:\n%s", got) + } +} + +// --hosts is accepted and says nothing is done. +func TestPlanRollback0227WithHosts(t *testing.T) { + s := newRBSandbox(t) + s.in.WithHosts = true + p := plan0227(t, s) + if st := stepText(p); !strings.Contains(st, "nothing to do for 0.2.27: this release changed nothing on the enrolled hosts") { + t.Errorf("steps:\n%s", st) + } +} + +// A device whose apply is not settled refuses the target, as it does every +// other (the dry run too). +func TestPlanRollback0227RefusesAnUnsettledApply(t *testing.T) { + s := newRBSandbox(t) + s.in.Target = RollbackTarget0227 + s.write(s.p.ConfigRecords, `{"version": 1, "devices": { + "sw1": {"address": "192.0.2.11", "vendor": "juniper", + "applied": {"at": "2026-10-13T10:00:00Z", "until": "2026-10-13T12:10:00Z", "by": "alice", "result": "pending", "id": "tacctl-20261013T100000Z-ab12", "kind": "apply", "via": "netconf"}}}} +`, 0o600) + if _, err := PlanRollback(s.in); err == nil || !strings.Contains(err.Error(), "sw1") { + t.Errorf("an unsettled apply was not refused: %v", err) + } +} + +// What the plan promises of the 0.2.27 reader holds in its source: the +// tacctl.yaml schema and the user record validator know the limits of the +// stored reports (so nothing is removed), and the pull record decoder skips +// what it does not know. Skipped where git or the tag is absent (CI must fetch +// tags). +func TestRollback0227ReaderKnowsTheLimits(t *testing.T) { + r := execx.Real{} + if _, err := r.LookPath("git"); err != nil { + t.Skip("git is not installed, so the 0.2.27 tag cannot be read") + } + if res, err := r.Run(context.Background(), execx.Cmd{Name: "git", Args: []string{"rev-parse", "-q", "--verify", "0.2.27^{commit}"}}); err != nil || res.Code != 0 { + t.Skip("the 0.2.27 tag is not in this repository (CI must fetch tags: git fetch --tags)") + } + show := func(file string) string { + res, err := r.Run(context.Background(), execx.Cmd{Name: "git", Args: []string{"show", "0.2.27:" + file}}) + if err != nil || res.Code != 0 { + t.Fatalf("cannot read %s of the 0.2.27 tag: %v %s", file, err, res.Stderr) + } + return string(res.Stdout) + } + if !strings.Contains(show("internal/store/validate.go"), "name: ReportsMaxSizeKey") || !strings.Contains(show("internal/conf/schema.go"), "ReportsMaxSizeKey:") { + t.Error("0.2.27 does not know the limits of the stored reports: the target would have to remove them") + } + if !strings.Contains(show("internal/devconf/store.go"), "json.Unmarshal(data, r)") { + t.Error("the 0.2.27 record decoder is not a plain json.Unmarshal") + } +} diff --git a/internal/lifecycle/rollback_additions.go b/internal/lifecycle/rollback_additions.go index 5c3c9230..fb4ba7da 100644 --- a/internal/lifecycle/rollback_additions.go +++ b/internal/lifecycle/rollback_additions.go @@ -5,7 +5,7 @@ package lifecycle // // A target's own plan (rollback0222.go, rollback0221.go, ...) says what that // target converts, and several of them return before the generic steps run -// (0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21 and 0.2.20 read most of what this release writes). A change +// (0.2.27, 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21 and 0.2.20 read most of what this release writes). A change // that every older release refuses, such as the timing scale, does not belong // in each of those plans: it is one entry of rollbackAdditions, and // PlanRollback adds its steps, warnings and notes after the target's plan, for @@ -46,7 +46,8 @@ type rollbackAddition struct { // is rollback_snmp_pool.go, the lockdown on hosts is // rollback_lockdown_hosts.go and the covered staging entries are // rollback_staging.go, the break-glass firewall is rollback_firewall.go, and the users' own limits of -// the stored reports are rollback_reportlimits.go. +// the stored reports are rollback_reportlimits.go, and the console's file +// transfer settings are rollback_filetransfer.go. var rollbackAdditions = []rollbackAddition{ {Release: "0.2.22", Read: (*RollbackPlan).planTimeoutScale, Add: (*RollbackPlan).addTimeoutScale}, {Release: "0.2.23", Read: (*RollbackPlan).planEmail, Add: (*RollbackPlan).addEmail}, @@ -55,6 +56,7 @@ var rollbackAdditions = []rollbackAddition{ {Release: "0.2.23", Read: (*RollbackPlan).planStagingCovered, Add: (*RollbackPlan).addStagingCovered}, {Release: "0.2.24", Read: (*RollbackPlan).planFirewall, Add: (*RollbackPlan).addFirewall}, {Release: "0.2.26", Read: (*RollbackPlan).planReportLimits, Add: (*RollbackPlan).addReportLimits}, + {Release: fileTransferRelease, Read: (*RollbackPlan).planConsoleFileTransfer, Add: (*RollbackPlan).addConsoleFileTransfer}, } // addReleaseChanges runs the entries of additions that apply to p's target. diff --git a/internal/lifecycle/rollback_email.go b/internal/lifecycle/rollback_email.go index a42ee347..979415bf 100644 --- a/internal/lifecycle/rollback_email.go +++ b/internal/lifecycle/rollback_email.go @@ -3,7 +3,7 @@ package lifecycle // The email address of a user (0.2.23, users..email in store.yaml) in a // rollback. Every release before 0.2.23 refuses the key ("user '': // unknown field 'email'" on every store command, and 'backup restore' -// refuses a snapshot that has it), so every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 +// refuses a snapshot that has it), so every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 // removes it from the store (store.RollbackEmail), after the snapshot --apply // takes first. Unlike the // files 0.2.22 reads as they are, this makes the 0.2.22 target convert a diff --git a/internal/lifecycle/rollback_filetransfer.go b/internal/lifecycle/rollback_filetransfer.go new file mode 100644 index 00000000..9f2db86a --- /dev/null +++ b/internal/lifecycle/rollback_filetransfer.go @@ -0,0 +1,62 @@ +package lifecycle + +// The console's file transfer settings (0.2.28, settings.file_transfer in +// console.yaml) in a rollback. Every older release refuses the key, 0.2.27 +// included: its console.yaml reader answers "settings: unknown key +// 'file_transfer'", so the console falls back to its defaults and every +// 'console' command that writes the file fails. So every target removes it +// (console.Keys0228), after the snapshot --apply takes first, and says what it +// held. +// +// The targets before 0.2.20 take it out with the other settings they remove +// (console.PlanRollbackSince0220 and console.PlanRollback read the file for +// them). The targets from 0.2.20 to 0.2.27 read the rest of the file as it is +// and have no plan of the file, so this addition plans it for them +// (console.PlanRollbackSince0228) and adds the step; it is one entry of +// rollbackAdditions. + +import ( + "strings" + + "github.com/rett/tacctl/internal/console" +) + +// fileTransferRelease is the release that made the change (its entry in +// rollbackAdditions). +const fileTransferRelease = "0.2.28" + +// planConsoleFileTransfer plans console.yaml for the targets whose own plan +// does not read it. The earlier ones read it already, with the file transfer +// key among what they remove. +func (p *RollbackPlan) planConsoleFileTransfer() error { + if p.console.Exists { + return nil + } + cp, err := console.PlanRollbackSince0228(p.in.Paths.ConsoleFile) + if err != nil { + return err + } + p.console = cp + p.consoleSince0228 = cp.Text != nil + return nil +} + +// addConsoleFileTransfer adds the step that takes the key out of console.yaml, +// for the targets planned above. +func (p *RollbackPlan) addConsoleFileTransfer() { + if p.consoleSince0228 { + p.addConsoleStep() + } +} + +// FileTransferRemoved reports whether the plan takes the file transfer +// settings out of console.yaml (they were set): the command then says that +// the commands that set them write them again until the upgrade. +func (p *RollbackPlan) FileTransferRemoved() bool { + for _, r := range p.console.Remove { + if strings.HasPrefix(r, "settings.file_transfer: ") { + return true + } + } + return false +} diff --git a/internal/lifecycle/rollback_filetransfer_test.go b/internal/lifecycle/rollback_filetransfer_test.go new file mode 100644 index 00000000..c0f81907 --- /dev/null +++ b/internal/lifecycle/rollback_filetransfer_test.go @@ -0,0 +1,153 @@ +package lifecycle + +import ( + "strings" + "testing" + + "github.com/rett/tacctl/internal/console" +) + +// The console's file transfer settings (0.2.28, settings.file_transfer) are +// rejected by the console.yaml reader of every release a rollback goes to, +// 0.2.27 included (its source answers "settings: unknown key"; the test in +// internal/console reads the tag): each target's plan takes the key out, says +// what it held, keeps every other setting, asks for no --yes, and leaves a +// file without it alone. +func TestRollbackTakesOutTheFileTransferSettings(t *testing.T) { + const ft = " file_transfer:\n tiers: [operator, superuser]\n users: {bob: 'enable:readonly', carol: disable}\n quota: {operator: 1G}\n quota_users: {bob: unlimited}\n rate_users: {carol: 1M}\n" + consoleWith := strings.Replace(rbConsole, " space_completion: false\n", " space_completion: false\n"+ft, 1) + if !strings.Contains(consoleWith, "file_transfer") { + t.Fatal("the fixture lacks the setting") + } + for _, target := range []string{RollbackTarget0227, RollbackTarget0226, RollbackTarget0225, RollbackTarget0224, RollbackTarget0223, RollbackTarget0222, + RollbackTarget0221, RollbackTarget0220, RollbackTarget0219, RollbackTarget0218, RollbackTarget0217, RollbackTarget0216, RollbackTarget029, RollbackTarget} { + s := newRBSandbox(t) + // a file without the key: no console step, and the file is not written + s.in.Target = target + before := string(mustRead(t, s.p.ConsoleFile)) + p, err := PlanRollback(s.in) + if err != nil { + t.Fatalf("%s: %v", target, err) + } + if strings.Contains(stepText(p), "file_transfer") || strings.Contains(stepText(p), "file transfer") { + t.Errorf("%s: a step for a file without the key:\n%s", target, stepText(p)) + } + + s.write(s.p.ConsoleFile, consoleWith, 0o600) + s.reload() + s.in.Target = target + p, err = PlanRollback(s.in) + if err != nil { + t.Fatalf("%s: %v", target, err) + } + st := stepText(p) + if !p.PendingFiles() || !p.Pending() { + t.Errorf("%s: the console.yaml change is not a file to back up", target) + } + if !strings.Contains(st, "remove settings.file_transfer: tiers operator,superuser, 2 user switches, 2 quotas, 1 rate") { + t.Errorf("%s: steps do not name the file transfer settings:\n%s", target, st) + } + if target != RollbackTarget { + if !strings.Contains(st, s.p.ConsoleFile+": take out the settings "+target+" does not know") { + t.Errorf("%s: no console step:\n%s", target, st) + } + // the file is no longer among the ones left alone + if i := strings.Index(st, "leave every other file untouched"); i >= 0 && strings.Contains(st[i:], s.p.ConsoleFile) { + t.Errorf("%s: console.yaml is said to be left alone:\n%s", target, st) + } + } + for _, w := range p.Warnings { + if strings.Contains(strings.Join(w.Lines, " "), "file_transfer") || strings.Contains(w.Title, "file transfer") { + t.Errorf("%s: the file transfer settings are a warning: %v", target, w) + } + } + if target == RollbackTarget0227 && p.NeedsYes() { + t.Errorf("%s: the file transfer settings need --yes: %v", target, p.Warnings) + } + done, err := ApplyRollback(p) + if err != nil { + t.Fatalf("%s: %v", target, err) + } + found := false + for _, d := range done { + found = found || (strings.HasPrefix(d, s.p.ConsoleFile+": ") && strings.Contains(d, "settings.file_transfer")) + } + if !found { + t.Errorf("%s: done %q", target, done) + } + got := string(mustRead(t, s.p.ConsoleFile)) + if strings.Contains(got, "file_transfer") || !strings.Contains(got, "idle_timeout: 12") || !strings.Contains(got, "space_completion: false") || !strings.Contains(got, "system_shell_tiers:") { + t.Errorf("%s: the file after the apply:\n%s", target, got) + } + // the password cache's own settings stay for the targets that have them + if hasCache := strings.Contains(got, "password_cache:"); hasCache != (target != RollbackTarget) { + t.Errorf("%s: password_cache kept: %v\n%s", target, hasCache, got) + } + // done: the plan again has nothing to take out + s.reload() + s.in.Target = target + if p, err = PlanRollback(s.in); err != nil || strings.Contains(stepText(p), "file_transfer") { + t.Errorf("%s: second plan: %v\n%s", target, err, stepText(p)) + } + // a file without the key is not written by the targets that read the + // rest of it as it is + if RollbackUndoes(target, "0.2.20") { + continue + } + s2 := newRBSandbox(t) + s2.in.Target = target + p2, err := PlanRollback(s2.in) + if err != nil { + t.Fatal(err) + } + if _, err := ApplyRollback(p2); err != nil { + t.Fatal(err) + } + if after := string(mustRead(t, s2.p.ConsoleFile)); after != before { + t.Errorf("%s: a file without the key was rewritten:\n%s", target, after) + } + } +} + +// The target of the release before this one: the plan converts the file +// (and takes the snapshot of --apply) only when the key is there, and then +// converts nothing else, leaves the per-tier sudoers drop-in and the rest of +// console.yaml as they are, and the second plan is the first of a clean state. +func TestPlanRollback0227TakesOnlyTheFileTransferSettings(t *testing.T) { + s := poolState(t) + s.write(s.p.ConsoleFile, "version: 1\nsettings:\n idle_timeout: 12\n color: true\n list_max: -1\n system_shell_users: {bob: 'enable:operator'}\n password_cache_users: {carol: true}\n"+ + " file_transfer: {tiers: [engineer, superuser], rate: {engineer: 64K}}\n", 0o600) + s.reload() + was := s.snapshotOf() + p := plan0227(t, s) + if len(p.Keys()) != 0 || !p.PendingFiles() || p.NeedsYes() || len(p.Warnings) != 0 || len(p.console.Set) != 0 { + t.Errorf("keys %q files %v yes %v set %q", p.Keys(), p.PendingFiles(), p.NeedsYes(), p.console.Set) + } + if got := strings.Join(p.console.Remove, "; "); got != "settings.file_transfer: tiers engineer,superuser, 1 rate" { + t.Errorf("remove: %q", got) + } + if _, err := ApplyRollback(p); err != nil { + t.Fatal(err) + } + got := string(mustRead(t, s.p.ConsoleFile)) + for _, w := range []string{"idle_timeout: 12", "color: true", "list_max: -1", "system_shell_users:", "password_cache_users:"} { + if !strings.Contains(got, w) { + t.Errorf("the file lost %q:\n%s", w, got) + } + } + if strings.Contains(got, "file_transfer") { + t.Errorf("the file keeps the key:\n%s", got) + } + // nothing else is written: the state is the one before but console.yaml + if after := s.snapshotOf(); after[s.p.ConsoleFile] == was[s.p.ConsoleFile] { + t.Error("console.yaml was not written") + } else { + after[s.p.ConsoleFile] = was[s.p.ConsoleFile] + for f, text := range after { + // the lock file beside console.yaml is the one new file + if old, had := was[f]; (!had && !strings.HasSuffix(f, "/"+console.LockName)) || (had && text != old) { + t.Errorf("the rollback wrote %s", f) + } + } + } +} diff --git a/internal/lifecycle/rollback_firewall.go b/internal/lifecycle/rollback_firewall.go index 550837b3..e2491893 100644 --- a/internal/lifecycle/rollback_firewall.go +++ b/internal/lifecycle/rollback_firewall.go @@ -2,10 +2,10 @@ package lifecycle // The break-glass firewall (0.2.24) in a rollback. It is a setting and a set of // files every older release lacks: breakglass.firewall in tacctl.yaml, which -// conf.Added0224 lists so that the key list of every target but 0.2.26, 0.2.25 and 0.2.24 removes +// conf.Added0224 lists so that the key list of every target but 0.2.27, 0.2.26, 0.2.25 and 0.2.24 removes // it (a 0.2.23 binary refuses the key), the nftables table inet tacctl in the // kernel, the rules file under the state directory and the boot unit -// tacctl-breakglass-firewall.service. Every target but 0.2.26, 0.2.25 and 0.2.24 (which have them) +// tacctl-breakglass-firewall.service. Every target but 0.2.27, 0.2.26, 0.2.25 and 0.2.24 (which have them) // removes the last three, through RollbackInput.RemoveFirewall (the command's // seam over the runner; nil lists the step and does nothing), and says so; the nftables package stays, // and so does every hold: an older release that has holds (0.2.5 and later) diff --git a/internal/lifecycle/rollback_lockdown_hosts.go b/internal/lifecycle/rollback_lockdown_hosts.go index d230729c..69184047 100644 --- a/internal/lifecycle/rollback_lockdown_hosts.go +++ b/internal/lifecycle/rollback_lockdown_hosts.go @@ -7,7 +7,7 @@ package lifecycle // older schema refuses). A release before 0.2.23 cannot lift a lockdown on a // host: its 'emergency lockdown disable' renders the devices and its 'host // sync' never removes the file, so the host would stay closed with nothing -// that says so. Every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 is therefore refused, in the +// that says so. Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 is therefore refused, in the // dry run and --apply alike, while a lockdown stands on a scope that has an // enrolled host, or a lifted one still waits for a host to drop the file; the // lockdowns of scopes with no host, which the 0.2.19 to 0.2.22 targets take over as they stand, diff --git a/internal/lifecycle/rollback_snmp_pool.go b/internal/lifecycle/rollback_snmp_pool.go index 043ccf36..67fc6906 100644 --- a/internal/lifecycle/rollback_snmp_pool.go +++ b/internal/lifecycle/rollback_snmp_pool.go @@ -8,7 +8,7 @@ package lifecycle // without an snmp: entry (snmpcred.Creds.Text chooses; a community and one // default user are saved in version 1). Every release before 0.2.23 reads // version 1 only, with one v3 user, and its strict parser refuses a version 2 -// file ("unsupported version"), so every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 writes +// file ("unsupported version"), so every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 writes // each version 2 file as version 1 again, after the snapshot --apply takes // first (rollback_additions.go). A state with version 1 files only has nothing to // convert: no step, no snapshot, no --yes. diff --git a/internal/lifecycle/rollback_staging.go b/internal/lifecycle/rollback_staging.go index bda524a4..b0e8bfff 100644 --- a/internal/lifecycle/rollback_staging.go +++ b/internal/lifecycle/rollback_staging.go @@ -7,7 +7,7 @@ package lifecycle // other staging entry and writes it back without the field, and its sweep // and 'scope staging remove' take the /32 of the entry out of the scope: if // the scope holds that exact /32 as a real prefix, a real prefix goes. So -// every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 drops these lines from the file. The +// every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 drops these lines from the file. The // plan names them, the snapshot --apply takes first holds the file, and // nothing needs an answer: no warning and no --yes. A clone still waiting for its 'device rename // --replace' loses its entry: a re-upgrade cannot write it again, so the plan diff --git a/internal/lifecycle/rollback_test.go b/internal/lifecycle/rollback_test.go index 6360c395..a21c0c9f 100644 --- a/internal/lifecycle/rollback_test.go +++ b/internal/lifecycle/rollback_test.go @@ -17,13 +17,13 @@ import ( ) func TestCheckRollbackVersion(t *testing.T) { - for in, want := range map[string]string{"0.2.3": "0.2.3", "v0.2.3": "0.2.3", "0.2.9": "0.2.9", "v0.2.9": "0.2.9", "0.2.16": "0.2.16", "v0.2.16": "0.2.16", "0.2.17": "0.2.17", "v0.2.17": "0.2.17", "0.2.18": "0.2.18", "0.2.19": "0.2.19", "v0.2.19": "0.2.19", "0.2.20": "0.2.20", "v0.2.20": "0.2.20", "0.2.21": "0.2.21", "v0.2.21": "0.2.21", "0.2.22": "0.2.22", "v0.2.22": "0.2.22", "0.2.23": "0.2.23", "v0.2.23": "0.2.23", "0.2.24": "0.2.24", "v0.2.24": "0.2.24", "0.2.25": "0.2.25", "v0.2.25": "0.2.25", "0.2.26": "0.2.26", "v0.2.26": "0.2.26"} { + for in, want := range map[string]string{"0.2.3": "0.2.3", "v0.2.3": "0.2.3", "0.2.9": "0.2.9", "v0.2.9": "0.2.9", "0.2.16": "0.2.16", "v0.2.16": "0.2.16", "0.2.17": "0.2.17", "v0.2.17": "0.2.17", "0.2.18": "0.2.18", "0.2.19": "0.2.19", "v0.2.19": "0.2.19", "0.2.20": "0.2.20", "v0.2.20": "0.2.20", "0.2.21": "0.2.21", "v0.2.21": "0.2.21", "0.2.22": "0.2.22", "v0.2.22": "0.2.22", "0.2.23": "0.2.23", "v0.2.23": "0.2.23", "0.2.24": "0.2.24", "v0.2.24": "0.2.24", "0.2.25": "0.2.25", "v0.2.25": "0.2.25", "0.2.26": "0.2.26", "v0.2.26": "0.2.26", "0.2.27": "0.2.27", "v0.2.27": "0.2.27"} { if v, err := CheckRollbackVersion(in); err != nil || v != want { t.Errorf("%q: %q %v", in, v, err) } } for _, c := range []struct{ in, want string }{ - {"0.2.2", "'tacctl rollback' prepares the state for 0.2.26 (the release before this one), 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 and 0.2.3 only (0.2.2 is older)"}, + {"0.2.2", "'tacctl rollback' prepares the state for 0.2.27 (the release before this one), 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 and 0.2.3 only (0.2.2 is older)"}, {"v0.2.2", "is older"}, {"0.2.1", "is older"}, {"0.1.16", "is older"}, @@ -31,9 +31,9 @@ func TestCheckRollbackVersion(t *testing.T) { {"0.2.7", "and 0.2.3 only (0.2.7 is further back)"}, {"v0.2.7", "and 0.2.3 only (0.2.7 is further back)"}, {"0.2.8", "and 0.2.3 only (0.2.8 is further back)"}, - {"0.2.10", "'0.2.10' is not a release to roll back to: 'tacctl rollback' prepares the state for 0.2.26 (the release before this one), 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 and 0.2.3 only"}, + {"0.2.10", "'0.2.10' is not a release to roll back to: 'tacctl rollback' prepares the state for 0.2.27 (the release before this one), 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20, 0.2.19, 0.2.18, 0.2.17, 0.2.16, 0.2.9 and 0.2.3 only"}, {"0.2.15", "'0.2.15' is not a release to roll back to"}, - {"0.2.27", "'0.2.27' is not a release to roll back to"}, + {"0.2.28", "'0.2.28' is not a release to roll back to"}, {"0.2.28", "'0.2.28' is not a release to roll back to"}, {"0.3.0", "and 0.2.3 only"}, {"1.0.0", "and 0.2.3 only"}, @@ -58,7 +58,7 @@ func TestCheckRollbackVersion(t *testing.T) { } // The refusal of 0.2.12 names the targets and promises no route there. _, err212 := CheckRollbackVersion("0.2.12") - if !strings.Contains(err212.Error(), "Usage: tacctl rollback 0.2.26|0.2.25|0.2.24|0.2.23|0.2.22|0.2.21|0.2.20|0.2.19|0.2.18|0.2.17|0.2.16|0.2.9|0.2.3") || strings.Contains(err212.Error(), "one release at a time") || strings.Contains(err212.Error(), "rollback 0.2.16 --apply") { + if !strings.Contains(err212.Error(), "Usage: tacctl rollback 0.2.27|0.2.26|0.2.25|0.2.24|0.2.23|0.2.22|0.2.21|0.2.20|0.2.19|0.2.18|0.2.17|0.2.16|0.2.9|0.2.3") || strings.Contains(err212.Error(), "one release at a time") || strings.Contains(err212.Error(), "rollback 0.2.16 --apply") { t.Errorf("0.2.12 refusal: %v", err212) } // The refusal of 0.2.2 names the two steps and the fallback. diff --git a/internal/sftpd/audit_test.go b/internal/sftpd/audit_test.go new file mode 100644 index 00000000..9429a72a --- /dev/null +++ b/internal/sftpd/audit_test.go @@ -0,0 +1,484 @@ +package sftpd + +import ( + "errors" + "io" + "os" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/sys/unix" +) + +// 6. The audit events. + +// describe lists "op path [-> to] [bytes] [!error]" for the events, in order. +func describe(ev []Event) []string { + var out []string + for _, e := range ev { + s := e.Op + " " + e.Path + if e.To != "" { + s += " -> " + e.To + } + if e.Bytes != 0 { + s += " " + strconv.FormatInt(e.Bytes, 10) + } + if e.Err != nil { + s += " !" + e.Err.Error() + } + out = append(out, s) + } + return out +} + +func wantEvents(t *testing.T, e *env, want ...string) { + t.Helper() + got := describe(e.rec.all()) + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("events:\n %s\nwant:\n %s", strings.Join(got, "\n "), strings.Join(want, "\n ")) + } +} + +func TestAuditUploadDownload(t *testing.T) { + e := newEnv(t, nil) + e.put("/up.txt", "hello world") + wantEvents(t, e, "upload /up.txt 11") + e.rec.reset() + + if got, err := e.get("up.txt"); err != nil || got != "hello world" { + t.Fatal(got, err) + } + wantEvents(t, e, "download /up.txt 11") + e.rec.reset() + + // An empty upload and a partial download are events too. + e.put("empty", "") + f, err := e.client.Open("up.txt") + if err != nil { + t.Fatal(err) + } + if _, err := f.ReadAt(make([]byte, 5), 0); err != nil { + t.Fatal(err) + } + _ = f.Close() + wantEvents(t, e, "upload /empty", "download /up.txt 5") + e.rec.reset() + + // A read-write handle audits both directions. + h, err := e.client.OpenFile("rw", os.O_RDWR|os.O_CREATE) + if err != nil { + t.Fatal(err) + } + _, _ = h.WriteAt([]byte("abc"), 0) + _, _ = h.ReadAt(make([]byte, 2), 0) + _ = h.Close() + wantEvents(t, e, "upload /rw 3", "download /rw 2") +} + +func TestAuditUploadCutShortByTheSession(t *testing.T) { + e := newEnv(t, nil) + f, err := e.client.OpenFile("cut", os.O_WRONLY|os.O_CREATE) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt([]byte("12345"), 0); err != nil { + t.Fatal(err) + } + // The client goes away without closing the handle. + if err := e.stop(); err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { + t.Logf("Serve: %v", err) + } + got := e.rec.all() + if len(got) != 1 || got[0].Op != "upload" || got[0].Bytes != 5 || got[0].Err == nil { + t.Errorf("events = %v, want one upload of 5 bytes with the error", describe(got)) + } +} + +func TestAuditChanges(t *testing.T) { + e := newEnv(t, nil) + if err := e.client.Mkdir("/d"); err != nil { + t.Fatal(err) + } + e.rec.reset() + if err := e.client.Mkdir("d/e"); err != nil { + t.Fatal(err) + } + e.write("d/f", "x") + if err := e.client.Rename("d/f", "d/g"); err != nil { + t.Fatal(err) + } + if err := e.client.PosixRename("d/g", "h"); err != nil { + t.Fatal(err) + } + if err := e.client.Chmod("h", 0o600); err != nil { + t.Fatal(err) + } + if err := e.client.Chtimes("h", time.Now(), time.Now()); err != nil { + t.Fatal(err) + } + if err := e.client.Remove("h"); err != nil { + t.Fatal(err) + } + if err := e.client.RemoveDirectory("d/e"); err != nil { + t.Fatal(err) + } + wantEvents(t, e, + "mkdir /d/e", + "rename /d/f -> /d/g", + "rename /d/g -> /h", + "setstat /h", + "setstat /h", + "delete /h", + "delete /d/e", + ) +} + +func TestAuditFailedChanges(t *testing.T) { + e := newEnv(t, nil) + _ = e.client.Remove("missing") + _ = e.client.Mkdir("a/b") + // The client retries a failed Remove as RemoveDirectory: two deletes. + ev := e.rec.all() + if len(ev) != 3 || ev[0].Op != "delete" || ev[1].Op != "delete" || ev[2].Op != "mkdir" { + t.Fatalf("events = %v, want two deletes and a mkdir", describe(ev)) + } + for _, x := range ev { + if x.Err == nil { + t.Errorf("event %+v has no error", x) + } + } +} + +func TestAuditRefusals(t *testing.T) { + e := sshEnv(t) + _ = e.client.Remove("a/../.ssh/authorized_keys") + _ = e.client.Rename("plain", ".ssh/x") + _ = e.client.Symlink("plain", "l") + _ = e.client.Link("plain", "h") + _ = e.client.Chown("plain", 1, 1) + _ = e.client.RemoveDirectory("/") + if err := os.Symlink("plain", e.home+"/lnk"); err != nil { + t.Fatal(err) + } + _, _ = e.client.Open("lnk") + wantEvents(t, e, + "refused /.ssh/authorized_keys !.ssh", // the client retries a Remove as RemoveDirectory + "refused /.ssh/authorized_keys !.ssh", + "refused /plain -> /.ssh/x !.ssh", + "refused /plain -> /l !symlink", + "refused /plain -> /h !unsupported", + "refused /plain !unsupported", + "refused / !outside the home", + "refused /lnk !symlink", + ) + for _, ev := range e.rec.all() { + if ev.Op != "refused" || ev.Err == nil { + t.Errorf("event %+v is not a refusal with a reason", ev) + } + } +} + +func TestAuditNotForReadOnlyRequests(t *testing.T) { + e := newEnv(t, nil) + e.write("d/f", "x") + _, _ = e.client.Stat("d/f") + _, _ = e.client.Lstat("d") + _, _ = e.client.ReadDir("d") + _, _ = e.client.ReadDir("/") + _, _ = e.client.RealPath("d/..") + _, _ = e.client.Getwd() + _, _ = e.client.Stat("missing") + f, _ := e.client.Open("d/f") + _, _ = f.Stat() + wantEvents(t, e) // the download is audited at close, not before + _ = f.Close() + wantEvents(t, e, "download /d/f") +} + +func TestAuditNilIsFine(t *testing.T) { + e := newEnv(t, func(c *Config) { c.Audit = nil }) + e.put("f", "x") + _ = e.client.Remove("../.ssh/x") + _ = e.client.Symlink("f", "l") + if _, err := e.get("f"); err != nil { + t.Fatal(err) + } +} + +// 7. Hostile input. + +func TestHostilePaths(t *testing.T) { + e := newEnv(t, nil) + long := strings.Repeat("a", 300) + huge := strings.Repeat("d/", 3000) + paths := []string{ + "a\x00b", "\x00", ".ssh\x00", "d/\x00/x", long, "d/" + long, huge, "/" + strings.Repeat("a/", 3000) + "x", + "d/../" + long, + } + for _, p := range paths { + check := func(op string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s %.20q succeeded", op, p) + } + } + _, err := e.client.Stat(p) + check("stat", err) + _, err = e.client.Lstat(p) + check("lstat", err) + _, err = e.client.ReadDir(p) + check("list", err) + _, err = e.client.Open(p) + check("open", err) + _, err = e.client.Create(p) + check("create", err) + check("mkdir", e.client.Mkdir(p)) + check("remove", e.client.Remove(p)) + check("rename", e.client.Rename(p, "x")) + check("rename to", e.client.Rename("plain", p)) + check("chmod", e.client.Chmod(p, 0o600)) + } + // The session is alive and the home untouched. + if _, err := e.client.RealPath("."); err != nil { + t.Errorf("session after hostile paths: %v", err) + } + ents, _ := os.ReadDir(e.home) + if len(ents) != 0 { + t.Errorf("home has %d entries after the hostile paths", len(ents)) + } + if _, err := e.client.RealPath("a\x00b"); err == nil { + t.Error("RealPath of a path with a NUL succeeded") + } + for _, r := range refusals(e.rec.all()) { + if r != "bad path" { + t.Errorf("refusal %q, want bad path", r) + } + } +} + +func TestHostileLegalNames(t *testing.T) { + e := newEnv(t, nil) + // Names that are odd but legal work like any other. + for _, n := range []string{"\xff\xfe", "a\nb", "-rf", " ", "..."} { + e.put(n, "x") + if got, err := e.get(n); err != nil || got != "x" { + t.Errorf("name %q: %q, %v", n, got, err) + } + } +} + +func TestHandlerPanicBecomesAStatus(t *testing.T) { + s := &server{cfg: Config{}} + f := func() (err error) { + defer s.guard(&err, &sftp.Request{Filepath: "/x"}) + panic("boom") + } + err := f() + if !errors.Is(err, sftp.ErrSSHFxFailure) { + t.Errorf("panic became %v, want a failure status", err) + } +} + +func TestBadAttributesGetAStatus(t *testing.T) { + // A setstat whose attributes are cut short (as the library parses + // them to nil) is a bad request, not a panic. + e := newEnv(t, nil) + e.write("f", "x") + s := &server{home: mustHome(t, e.home), cfg: Config{}} + r := &sftp.Request{Method: "Setstat", Filepath: "/f", Flags: 0x4 /* permissions */, Attrs: []byte{1}} + err := s.Filecmd(r) + if err == nil || reasonOf(err) != reasonBadPath { + t.Errorf("setstat with short attributes = %v", err) + } +} + +func mustHome(t *testing.T, dir string) *home { + t.Helper() + h, err := openHome(dir) + if err != nil { + t.Fatal(err) + } + t.Cleanup(h.close) + return h +} + +func TestServeWritesNothingToStdoutOrStderr(t *testing.T) { + // Not parallel: it points the process's descriptors 1 and 2 (what a + // write to os.Stdout, os.Stderr or the C library's stdio reaches) at a + // pipe for the length of a session. + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + saved := [2]int{} + for i, fd := range []int{1, 2} { + if saved[i], err = unix.Dup(fd); err != nil { + t.Fatal(err) + } + } + restore := sync.OnceFunc(func() { + for i, fd := range []int{1, 2} { + _ = unix.Dup3(saved[i], fd, 0) + _ = unix.Close(saved[i]) + } + }) + defer restore() + for _, fd := range []int{1, 2} { + if err := unix.Dup3(int(w.Fd()), fd, 0); err != nil { + t.Fatal(err) + } + } + e := newEnv(t, nil) + e.write(".ssh/k", "x") + e.put("f", "x") + _, _ = e.get("f") + _, _ = e.client.Stat(".ssh/k") + _ = e.client.Symlink("f", "l") + _, _ = e.client.Open("a\x00b") + _ = e.client.Mkdir("f") + _, _ = e.client.ReadDir("/") + _ = e.stop() + restore() + _ = w.Close() + b, _ := io.ReadAll(r) + if len(b) != 0 { + t.Errorf("Serve wrote %q", b) + } +} + +func TestServeEndsWhenTheClientDoes(t *testing.T) { + e := newEnv(t, nil) + if err := e.stop(); err != nil { + t.Errorf("Serve after a clean close = %v, want nil", err) + } +} + +// IsSubsystemCommand. + +func TestIsSubsystemCommand(t *testing.T) { + cases := []struct { + cmd string + want bool + }{ + {"/usr/lib/openssh/sftp-server", true}, + {"/usr/libexec/sftp-server", true}, + {"internal-sftp", true}, + {"/usr/lib/openssh/internal-sftp", true}, + {"sftp-server", true}, + {"sftp-server -l INFO", true}, + {"/usr/lib/openssh/sftp-server -f AUTH -l VERBOSE", true}, + {" sftp-server", true}, + {"sftp-server\t-e", true}, + {"/opt/my dir/sftp-server", false}, // the first word is /opt/my + {"'/opt/my dir/sftp-server'", false}, + {"sftp-server; id", false}, + {"sftp-server -l INFO; id", false}, + {"sftp-server && id", false}, + {"sftp-server | cat", false}, + {"sftp-server `id`", false}, + {"sftp-server $(id)", false}, + {"sftp-server > /x", false}, + {"sftp-server\nid", false}, + {"sftp-server;id", false}, + {"", false}, + {" ", false}, + {"scp -t x", false}, + {"scp -f /etc/passwd", false}, + {"rsync --server", false}, + {"sftp", false}, + {"my-sftp-server", false}, + {"sftp-server2", false}, + {"/usr/lib/sftp-server/", false}, + {"/usr/lib/sftp-server/x", false}, + {"internal-sftp-x", false}, + {"SFTP-SERVER", false}, + {"id sftp-server", false}, + {"sh -c sftp-server", false}, + } + for _, c := range cases { + if got := IsSubsystemCommand(c.cmd); got != c.want { + t.Errorf("IsSubsystemCommand(%q) = %v, want %v", c.cmd, got, c.want) + } + } +} + +// Every request that fails in the kernel is audited with its operation and +// the error; one that is refused is audited as a refusal with its reason. +func TestAuditFailedOperations(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root writes to a read-only file") + } + e := newEnv(t, nil) + e.write("ro", "x") + e.write("d/f", "x") + if err := os.Chmod(e.home+"/ro", 0o444); err != nil { + t.Fatal(err) + } + cases := []struct { + name string + do func() error + want string // the operation of the event (the first one), "" for a refusal + path string + }{ + {"upload over a read-only file", func() error { return putFile(e.client, "ro", "y") }, "upload", "/ro"}, + {"upload into a missing directory", func() error { return putFile(e.client, "nodir/f", "y") }, "upload", "/nodir/f"}, + {"read-write open of a read-only file", func() error { + _, err := e.client.OpenFile("ro", os.O_RDWR) + return err + }, "upload", "/ro"}, + {"download of a missing file", func() error { _, err := e.client.Open("missing"); return err }, "download", "/missing"}, + {"download of a directory", func() error { _, err := e.client.Open("d"); return err }, "download", "/d"}, + {"delete of a missing file", func() error { return e.client.Remove("missing") }, "delete", "/missing"}, + {"rmdir of a directory with content", func() error { return e.client.RemoveDirectory("d") }, "delete", "/d"}, + {"rename of a missing file", func() error { return e.client.Rename("missing", "x") }, "rename", "/missing"}, + {"rename onto an existing file", func() error { return e.client.Rename("ro", "d/f") }, "rename", "/ro"}, + {"mkdir over an existing directory", func() error { return e.client.Mkdir("d") }, "mkdir", "/d"}, + {"mkdir below a missing directory", func() error { return e.client.Mkdir("a/b") }, "mkdir", "/a/b"}, + {"setstat of a missing file", func() error { return e.client.Chmod("missing", 0o600) }, "setstat", "/missing"}, + {"a refused request", func() error { _, err := e.client.Open(".ssh/k"); return err }, "refused", "/.ssh/k"}, + } + for _, c := range cases { + e.rec.reset() + if err := c.do(); err == nil { + t.Errorf("%s succeeded", c.name) + continue + } + ev := e.rec.all() + if len(ev) == 0 { + t.Errorf("%s: no event", c.name) + continue + } + if ev[0].Op != c.want || ev[0].Path != c.path || ev[0].Err == nil { + t.Errorf("%s: first event %+v, want op %s on %s with an error", c.name, ev[0], c.want, c.path) + } + } + if e.read("ro") != "x" { + t.Error("a failed upload changed the file") + } +} + +// Readlink and RealPath do not go through the guard of the handlers, and +// their refusals are audited all the same; an answer to RealPath is not. +func TestAuditReadlinkAndRealPathRefusals(t *testing.T) { + e := sshEnv(t) + if err := os.Symlink("plain", e.home+"/lnk"); err != nil { + t.Fatal(err) + } + _, _ = e.client.ReadLink("lnk") + _, _ = e.client.ReadLink("plain") + _, _ = e.client.RealPath("a\x00b") + wantEvents(t, e, + "refused /lnk !symlink", + "refused /plain !symlink", + "refused a\x00b !bad path", + ) + e.rec.reset() + if got, err := e.client.RealPath("a/../plain"); err != nil || got != "/plain" { + t.Fatalf("RealPath = %q, %v", got, err) + } + wantEvents(t, e) +} diff --git a/internal/sftpd/doc.go b/internal/sftpd/doc.go new file mode 100644 index 00000000..0efe5093 --- /dev/null +++ b/internal/sftpd/doc.go @@ -0,0 +1,58 @@ +// Package sftpd is the console's built-in SFTP server: a library that runs +// the SFTP protocol on a byte stream, rooted in one directory, with the +// user's .ssh directory out of reach, no symbolic links followed, and an +// audit callback for what the client changes. +// +// A regular file that has more than one name (a hard link, made outside +// SFTP: the server makes none) is not served at all: it cannot be opened, +// read, written or have its attributes set, and the refusal is audited with +// the reason "link". Such a name is still listed, and can be renamed or +// removed, since that acts on the name and never on the data; so a name made +// for the data of a key file in .ssh can be seen and removed, not read or +// changed. The open is judged on the opened file; a setstat pins the entry +// with an O_PATH descriptor (no link followed), judges the descriptor and +// sets the mode and times through /proc/self/fd, so a name that is made to +// mean another file between the check and the change (a rename) is not +// followed. What is not caught is a name added to the pinned file by +// something outside SFTP after the check. The change through /proc/self/fd +// needs /proc mounted. +// +// A session has at most 256 handles open at once, files and directory +// listings together (each holds a descriptor); an open past that fails with a +// failure status and is audited as a refusal ("too many open files"). A +// listing reads the directory as the client asks for the entries, a batch at +// a time, and is not sorted: it comes in the order of the file system. +// +// What the quota guarantees. A write is refused, whole, when it would take the +// usage the session has measured over the limit; that is all. The usage is +// measured when the session starts and again when a file is opened for writing +// and the last measure is more than a few seconds old, and between measures it +// follows what the session itself does. A part of the home the walk could not +// see (a directory without read or search permission, a tree deeper than the +// walk goes, no descriptor left) makes the measure incomplete, and then the +// home counts as full until a later walk is complete: nothing that makes it +// bigger is accepted, while reading, deleting and writing in place go on. A +// removed or replaced file that a handle of the session still has open keeps +// its room until the handle closes. Sessions are independent of each other: +// N sessions of one home that write at once can each use the room that was +// free at their last measure, so the home can come to about N times the +// quota (and programs outside the server write as they like). Only the sizes +// of regular files count, once per inode: not the inodes, the directory +// blocks, the disk blocks (a sparse file counts its length), or what a +// removed file's data takes after the session ended. +// +// The server answers fstat and fsetstat of a handle through the library, +// which looks at the handle's path name and not at the open file. After the +// file was renamed, or its name was given to another file, they act on whatever +// the name is now (or fail), not on the file the handle holds. Confinement does +// not depend on it: the name goes through the same resolution as any path of +// the client (no link followed, nothing outside the home), it can never name +// something in .ssh since a rename into .ssh is refused, and the attribute +// rules of setstat (no owner change, the link rule, the directory rule, the +// quota for a growing size) apply to it as to a setstat by path. Reads and writes use the open +// file itself. +// +// It adds no command and prints nothing: a caller (the console) hands it the +// stream of the sftp subsystem and the home directory, and gets a status +// back when the client ends the session. +package sftpd diff --git a/internal/sftpd/errors.go b/internal/sftpd/errors.go new file mode 100644 index 00000000..05f4d629 --- /dev/null +++ b/internal/sftpd/errors.go @@ -0,0 +1,78 @@ +package sftpd + +import ( + "errors" + + "github.com/pkg/sftp" +) + +// The reasons a request is refused; they are the Err text of an Event with +// Op "refused". +const ( + reasonSSH = ".ssh" + reasonOutside = "outside the home" + reasonSymlink = "symlink" + reasonLink = "link" + reasonQuota = "quota" + reasonUnsupported = "unsupported" + reasonBadPath = "bad path" + reasonTooMany = "too many open files" +) + +// statusError is an error that carries its SFTP status: the code the +// library sends (it finds it through Unwrap) and the message the client +// shows. A non-empty reason marks a refusal, which is audited. +type statusError struct { + reason string + code error + msg string +} + +func (e *statusError) Error() string { return e.msg } +func (e *statusError) Unwrap() error { return e.code } + +// refuse is a refusal with permission-denied status. +func refuse(reason, msg string) error { + return &statusError{reason: reason, code: sftp.ErrSSHFxPermissionDenied, msg: msg} +} + +func errSSH() error { + return refuse(reasonSSH, "permission denied") +} + +func errSymlink() error { + return refuse(reasonSymlink, "permission denied: symbolic links are not followed") +} + +func errLink() error { + return refuse(reasonLink, "permission denied: a file with more than one name is not served") +} + +func errOutside() error { + return refuse(reasonOutside, "permission denied: the home directory itself cannot be changed") +} + +func errUnsupported(what string) error { + return &statusError{reason: reasonUnsupported, code: sftp.ErrSSHFxOpUnsupported, msg: what + " is not supported"} +} + +func errBadPath(msg string) error { + return &statusError{reason: reasonBadPath, code: sftp.ErrSSHFxFailure, msg: msg} +} + +func errTooMany() error { + return &statusError{reason: reasonTooMany, code: sftp.ErrSSHFxFailure, msg: "too many open files"} +} + +func errQuota() error { + return &statusError{reason: reasonQuota, code: sftp.ErrSSHFxFailure, msg: "disk quota exceeded"} +} + +// reasonOf is the refusal reason in err, or "" when err is not a refusal. +func reasonOf(err error) string { + var se *statusError + if errors.As(err, &se) { + return se.reason + } + return "" +} diff --git a/internal/sftpd/file.go b/internal/sftpd/file.go new file mode 100644 index 00000000..835e307f --- /dev/null +++ b/internal/sftpd/file.go @@ -0,0 +1,257 @@ +package sftpd + +import ( + "os" + "sync" + "sync/atomic" + + "github.com/pkg/sftp" + "golang.org/x/sys/unix" +) + +// file is an open regular file of a client: the handle behind a download, +// an upload or a read-write open. The library calls ReadAt and WriteAt from +// several goroutines and Close once the client closes the handle (or the +// session ends). +type file struct { + s *server + f *os.File + key inode // the file on the disk, for the quota's book of open files + v vpath + write bool // opened for upload + wonly bool // opened for upload and not for reading: no READ request may reach WriteAt + append bool + quota *quota // nil when there is no quota + rate *bucket // nil when there is no rate limit + + quotaNoted atomic.Bool + readNoted atomic.Bool + + read, written atomic.Int64 + + mu sync.Mutex + xferr error // the error that ended the session with the handle open + closed sync.Once +} + +// openFile opens the file of r. write says the open is for an upload (the +// handle can write); otherwise it is a download. +func (s *server) openFile(r *sftp.Request, write bool) (*file, error) { + if err := s.handles.acquire(); err != nil { + return nil, err + } + opened := false + defer func() { + if !opened { + s.handles.release() // an open that failed (or panicked) holds no place + } + }() + v, err := s.path(r.Filepath) + if err != nil { + return nil, err + } + t, err := s.home.resolve(v) + if err != nil { + return nil, err + } + defer t.close() + pf := r.Pflags() + + // O_NONBLOCK so that opening a FIFO neither blocks the session nor + // waits for a peer; the type is checked before anything is read or + // written, and the flag is cleared for a regular file. The file is + // not truncated by the open: the size it had is needed, and a FIFO or + // device must not be touched. + if write && s.quota != nil { + s.quota.refresh() + } + flags := unix.O_NONBLOCK + mode := uint32(0o644) // the attributes of an open are not parsed: the client sets the mode with setstat + if write { + flags |= unix.O_WRONLY + if pf.Read { + flags = flags&^unix.O_WRONLY | unix.O_RDWR + } + if pf.Creat { + flags |= unix.O_CREAT + } + if pf.Excl { + flags |= unix.O_EXCL + } + if pf.Append { + flags |= unix.O_APPEND + } + } else { + flags |= unix.O_RDONLY + } + fd, err := t.open(flags, mode) + if err != nil { + return nil, err + } + var st unix.Stat_t + if err := unix.Fstat(fd, &st); err != nil { + _ = unix.Close(fd) + return nil, t.pathErr("stat", err) + } + switch st.Mode & unix.S_IFMT { + case unix.S_IFREG: + // Judged on the open file, so that nothing between a look and the + // open can change what it is. Nothing has been truncated yet. + if st.Nlink > 1 { + _ = unix.Close(fd) + return nil, errLink() + } + case unix.S_IFDIR: + _ = unix.Close(fd) + return nil, &os.PathError{Op: "open", Path: v.String(), Err: unix.EISDIR} + default: + _ = unix.Close(fd) + return nil, &statusError{reason: reasonUnsupported, code: sftp.ErrSSHFxOpUnsupported, msg: "not a regular file"} + } + if err := unix.SetNonblock(fd, false); err != nil { + _ = unix.Close(fd) + return nil, t.pathErr("open", err) + } + if write && pf.Trunc { + if s.beforeTruncate != nil { + s.beforeTruncate() + } + if err := s.truncate(fd, t); err != nil { + _ = unix.Close(fd) + return nil, err + } + } + f := &file{ + s: s, + f: os.NewFile(uintptr(fd), v.String()), + key: inode{u64(st.Dev), u64(st.Ino)}, + v: v, + write: write, + wonly: write && !pf.Read, + append: write && pf.Append, + quota: s.quota, + rate: s.rate, + } + if f.quota != nil { + f.quota.hold(f) + } + opened = true + return f, nil +} + +// truncate empties the open file fd and takes the size it had off the usage. +// With a quota the size is read, the file cut and the usage lowered as one step +// under the quota's lock, like a write: a write on another handle of the same +// file has either finished before (its growth is in the size read here) or +// starts after (it sees the empty file), and the usage never lags the disk. +func (s *server) truncate(fd int, t *target) error { + cut := func() (int64, error) { + var cur unix.Stat_t + if err := unix.Fstat(fd, &cur); err != nil { + return 0, t.pathErr("stat", err) + } + if err := unix.Ftruncate(fd, 0); err != nil { + return 0, t.pathErr("truncate", err) + } + return cur.Size, nil + } + if s.quota == nil { + _, err := cut() + return err + } + return s.quota.truncating(cut) +} + +func (f *file) ReadAt(p []byte, off int64) (int, error) { + n, err := f.f.ReadAt(p, off) + f.read.Add(int64(n)) + f.rate.take(int64(n)) + return n, err +} + +// readSlack is the room the library leaves behind the data of a READ +// request (the header of the reply: its dataHeaderLen); the data of a WRITE +// request is cut from the packet that came in and has none unless the client +// sent bytes after it. +const readSlack = 4 + 1 + 4 + 4 + +// isReadRequest reports whether the buffer p that the library hands to WriteAt +// is the buffer of a READ request, not the data of a WRITE. +// +// For a handle opened only for writing the library has one entry for both +// kinds of request, and calls WriteAt with a buffer of zeros for a READ: the +// request would write zeros at the offset it asks for. WriteAt is given no +// other sign of the request, so the buffer is told by its capacity (the +// library allocates a READ's buffer with room for the reply header). A client +// cannot make a READ look like a WRITE; a WRITE followed by exactly readSlack +// bytes of padding looks like a READ and is refused, which hurts only the +// client that sent it. TestReadOnWriteOnlyHandleWritesNothing pins this to the +// vendored library: a change of its allocation fails that test. +func isReadRequest(p []byte) bool { return cap(p)-len(p) == readSlack } + +func (f *file) WriteAt(p []byte, off int64) (int, error) { + if f.wonly && isReadRequest(p) { + err := errUnsupported("read of a handle opened only for writing") + if f.readNoted.CompareAndSwap(false, true) { + f.s.noteRefusal(err, f.v.String(), "") // once per handle + } + return 0, err + } + w := func() (int, error) { + if f.append { + // The file is open with O_APPEND, which the kernel honours for + // every write and Go's WriteAt refuses; the offset is ignored, + // as it is for the OpenSSH server. + return f.f.Write(p) + } + return f.f.WriteAt(p, off) + } + var n int + var err error + if f.quota != nil { + n, err = f.quota.write(f.f, len(p), off, f.append, w) + if reasonOf(err) == reasonQuota && f.quotaNoted.CompareAndSwap(false, true) { + f.s.noteRefusal(err, f.v.String(), "") // once per handle, not once per packet + } + } else { + n, err = w() + } + f.written.Add(int64(n)) + f.rate.take(int64(n)) // what was written, after it: a refused write costs nothing + return n, err +} + +// TransferError is called by the library when the session ends with the +// handle still open. +func (f *file) TransferError(err error) { + f.mu.Lock() + f.xferr = err + f.mu.Unlock() +} + +// Close closes the file and audits the transfer: an upload for a handle +// opened to write (with the bytes written), a download for one that was +// read from (with the bytes read). It is safe to call twice. +func (f *file) Close() error { + var cerr error + f.closed.Do(func() { + if f.quota != nil { + f.quota.unhold(f) // while the descriptor is still open + } + cerr = f.f.Close() + f.s.handles.release() + f.mu.Lock() + err := f.xferr + f.mu.Unlock() + if cerr != nil { + err = cerr + } + if f.write { + f.s.audit(Event{Op: "upload", Path: f.v.String(), Bytes: f.written.Load(), Err: err}) + } + if !f.write || f.read.Load() > 0 { + f.s.audit(Event{Op: "download", Path: f.v.String(), Bytes: f.read.Load(), Err: err}) + } + }) + return cerr +} diff --git a/internal/sftpd/fs.go b/internal/sftpd/fs.go new file mode 100644 index 00000000..2952ef12 --- /dev/null +++ b/internal/sftpd/fs.go @@ -0,0 +1,241 @@ +package sftpd + +import ( + "errors" + "os" + "strconv" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// How the home is reached +// +// The home is held open as a directory descriptor, and every client path is +// resolved against it one component at a time with openat(2), each +// directory component opened with O_NOFOLLOW|O_DIRECTORY. The last +// component is then used with the *at calls of its parent descriptor +// (openat with O_NOFOLLOW, mkdirat, unlinkat, renameat2, fstatat with +// AT_SYMLINK_NOFOLLOW); a change of attributes pins the entry with an O_PATH +// descriptor and goes through /proc/self/fd (see pinned). +// +// This is os.Root's confinement without its symbolic-link following: an +// os.Root resolves links inside the root, so a link that points at .ssh +// would be followed, and a check made before the call (Lstat, then Open) +// could lose a race to a rename that puts a link where the directory was. +// Here no call resolves a name through a link at all: each kernel lookup is +// a single component, and a link in that position makes the call fail +// (ELOOP, or ENOTDIR with O_DIRECTORY), whatever happened between our last +// look and the call. A descriptor that is held cannot be redirected by a +// rename of its name. ".." never reaches the kernel (parsePath removes it +// lexically, and a component that is a link is never entered), so a path +// cannot climb out of the home, and neither can a link. + +// dirFlags opens a directory component without following a link. +const dirFlags = unix.O_RDONLY | unix.O_DIRECTORY | unix.O_NOFOLLOW | unix.O_CLOEXEC + +// home is the home directory, held open. +type home struct{ fd int } + +// openHome opens the home. The home path itself may be reached through a +// link (it is the caller's configuration, not the client's). +func openHome(dir string) (*home, error) { + if dir == "" { + return nil, errors.New("sftpd: no home directory") + } + fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + return nil, &os.PathError{Op: "open", Path: dir, Err: err} + } + return &home{fd: fd}, nil +} + +func (h *home) close() { _ = unix.Close(h.fd) } + +// target is a resolved client path: the open directory that holds the last +// component, and that component's name. For the home itself the directory +// is the home and the name ".". +type target struct { + v vpath + dir int + name string + own bool // dir is ours to close +} + +func (t *target) close() { + if t.own { + _ = unix.Close(t.dir) + } +} + +// resolve opens the directories above the last component of v, without +// following a link at any step, and returns the target. +func (h *home) resolve(v vpath) (*target, error) { + if v.isRoot() { + return &target{v: v, dir: h.fd, name: "."}, nil + } + fd := h.fd + for _, c := range v.parent() { + next, err := unix.Openat(fd, c, dirFlags, 0) + if err != nil { + err = classify(fd, c, err, "open", v) + if fd != h.fd { + _ = unix.Close(fd) + } + return nil, err + } + if fd != h.fd { + _ = unix.Close(fd) + } + fd = next + } + return &target{v: v, dir: fd, name: v.name(), own: fd != h.fd}, nil +} + +// classify turns the errno of a failed *at call on dir/name into the error +// for the client: a refusal when a symbolic link stopped it (the lookup +// said ELOOP or, with O_DIRECTORY, ENOTDIR, and the entry is a link), else +// a path error with the virtual path. The lstat here only names the cause +// of a failure that already happened; it decides nothing. +func classify(dir int, name string, err error, op string, v vpath) error { + if errors.Is(err, unix.ELOOP) || errors.Is(err, unix.ENOTDIR) { + var st unix.Stat_t + if unix.Fstatat(dir, name, &st, unix.AT_SYMLINK_NOFOLLOW) == nil && st.Mode&unix.S_IFMT == unix.S_IFLNK { + return errSymlink() + } + } + return &os.PathError{Op: op, Path: v.String(), Err: err} +} + +// pathErr wraps an errno of a call on t. +func (t *target) pathErr(op string, err error) error { + if err == nil { + return nil + } + return classify(t.dir, t.name, err, op, t.v) +} + +// lstat is fstatat without following a link. +func (t *target) lstat() (unix.Stat_t, error) { + var st unix.Stat_t + err := unix.Fstatat(t.dir, t.name, &st, unix.AT_SYMLINK_NOFOLLOW) + return st, t.pathErr("stat", err) +} + +// open opens the last component, never following a link. +func (t *target) open(flags int, mode uint32) (int, error) { + fd, err := unix.Openat(t.dir, t.name, flags|unix.O_NOFOLLOW|unix.O_CLOEXEC, mode) + if err != nil { + return -1, t.pathErr("open", err) + } + return fd, nil +} + +// openDir opens the last component, which must be a directory. +func (t *target) openDir() (int, error) { + fd, err := unix.Openat(t.dir, t.name, dirFlags, 0) + if err != nil { + return -1, t.pathErr("open", err) + } + return fd, nil +} + +// fileInfo is a directory entry or a stat, as the library wants it. +type fileInfo struct { + name string + st unix.Stat_t +} + +func (f *fileInfo) Name() string { return f.name } +func (f *fileInfo) Size() int64 { return f.st.Size } +func (f *fileInfo) Mode() os.FileMode { return modeOf(f.st.Mode) } +func (f *fileInfo) IsDir() bool { return f.st.Mode&unix.S_IFMT == unix.S_IFDIR } +func (f *fileInfo) ModTime() time.Time { return time.Unix(f.st.Mtim.Unix()) } + +// Sys gives the library the owner for the long listing. +func (f *fileInfo) Sys() any { return &syscall.Stat_t{Uid: f.st.Uid, Gid: f.st.Gid} } + +func modeOf(m uint32) os.FileMode { + fm := os.FileMode(m & 0o777) + switch m & unix.S_IFMT { + case unix.S_IFDIR: + fm |= os.ModeDir + case unix.S_IFLNK: + fm |= os.ModeSymlink + case unix.S_IFIFO: + fm |= os.ModeNamedPipe + case unix.S_IFSOCK: + fm |= os.ModeSocket + case unix.S_IFBLK: + fm |= os.ModeDevice + case unix.S_IFCHR: + fm |= os.ModeDevice | os.ModeCharDevice + } + if m&unix.S_ISUID != 0 { + fm |= os.ModeSetuid + } + if m&unix.S_ISGID != 0 { + fm |= os.ModeSetgid + } + if m&unix.S_ISVTX != 0 { + fm |= os.ModeSticky + } + return fm +} + +// pinned is an entry held by an O_PATH descriptor: the inode that was found +// under the name at the time of the open, whatever the name is later made to +// mean. Its attributes are read from the descriptor (st) and changed through +// /proc/self/fd, which names that inode and nothing else. +type pinned struct { + fd int + t *target + st unix.Stat_t +} + +// pin opens the last component without following a link (O_NOFOLLOW with +// O_PATH gives the link itself, which the caller refuses) and reads its +// attributes from the descriptor. +func (t *target) pin(op string) (*pinned, error) { + fd, err := unix.Openat(t.dir, t.name, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return nil, t.pathErr(op, err) + } + p := &pinned{fd: fd, t: t} + if err := unix.Fstat(fd, &p.st); err != nil { + p.close() + return nil, t.pathErr(op, err) + } + return p, nil +} + +func (p *pinned) close() { _ = unix.Close(p.fd) } + +// proc is the path that names the pinned inode. +func (p *pinned) proc() string { return "/proc/self/fd/" + strconv.Itoa(p.fd) } + +// chmod sets the permission bits of the pinned inode. +func (p *pinned) chmod(mode uint32) error { + return p.t.pathErr("chmod", unix.Chmod(p.proc(), mode)) +} + +// utimes sets the access and modification times (seconds) of the pinned +// inode. +func (p *pinned) utimes(atime, mtime uint32) error { + ts := []unix.Timespec{{Sec: int64(atime)}, {Sec: int64(mtime)}} + return p.t.pathErr("chtimes", unix.UtimesNano(p.proc(), ts)) +} + +// restat reads the attributes of the pinned inode again. +func (p *pinned) restat() (unix.Stat_t, error) { + var st unix.Stat_t + err := unix.Fstat(p.fd, &st) + return st, p.t.pathErr("stat", err) +} + +// truncate sets the size of the pinned inode (a regular file; the caller +// judged it): the file is cut, or extended with zeros. +func (p *pinned) truncate(size int64) error { + return p.t.pathErr("truncate", unix.Truncate(p.proc(), size)) +} diff --git a/internal/sftpd/handlers.go b/internal/sftpd/handlers.go new file mode 100644 index 00000000..2e781a42 --- /dev/null +++ b/internal/sftpd/handlers.go @@ -0,0 +1,498 @@ +package sftpd + +import ( + "errors" + "io" + "os" + + "github.com/pkg/sftp" + "golang.org/x/sys/unix" +) + +// server holds one session's state and implements the library's handler +// interfaces. The library calls the handlers from several goroutines at +// once: the fields below are read-only after Serve builds them, and what a +// handler changes is held by the file it works on or guarded by its own +// lock. +type server struct { + home *home + cfg Config + quota *quota // nil when the session has no quota + rate *bucket // nil when the session has no rate limit + + handles handleCount // the open files and directory listings + + beforeTruncate func() // a test's hooks, see seams + afterPin func() +} + +var ( + _ sftp.FileReader = (*server)(nil) + _ sftp.OpenFileWriter = (*server)(nil) + _ sftp.PosixRenameFileCmder = (*server)(nil) + _ sftp.StatVFSFileCmder = (*server)(nil) + _ sftp.LstatFileLister = (*server)(nil) + _ sftp.RealPathFileLister = (*server)(nil) + _ sftp.ReadlinkFileLister = (*server)(nil) +) + +func (s *server) audit(e Event) { + if s.cfg.Audit != nil { + s.cfg.Audit(e) + } +} + +// display is a client path for an event: cleaned when it can be, else cut. +func display(p string) string { + if v, err := parsePath(p); err == nil { + return v.String() + } + if len(p) > maxName { + p = p[:maxName] + "..." + } + return p +} + +// noteRefusal audits err when it is a refusal. +func (s *server) noteRefusal(err error, path, to string) { + reason := reasonOf(err) + if reason == "" { + return + } + e := Event{Op: "refused", Path: display(path), Err: errors.New(reason)} + if to != "" { + e.To = display(to) + } + s.audit(e) +} + +// guard is deferred by every handler: a panic (the input is hostile) +// becomes a failure status, and a refusal is audited. +func (s *server) guard(err *error, r *sftp.Request) { + if p := recover(); p != nil { + *err = &statusError{code: sftp.ErrSSHFxFailure, msg: "internal error"} + } + s.noteRefusal(*err, r.Filepath, r.Target) +} + +// path is a client path for an operation: cleaned, and refused when it is +// .ssh or under it. +func (s *server) path(p string) (vpath, error) { + v, err := parsePath(p) + if err != nil { + return nil, err + } + if v.inSSH() { + return nil, errSSH() + } + return v, nil +} + +// changePath is path for an operation that changes the entry: the home +// itself is not one that can be removed, renamed or created. +func (s *server) changePath(p string) (vpath, error) { + v, err := s.path(p) + if err != nil { + return nil, err + } + if v.isRoot() { + return nil, errOutside() + } + return v, nil +} + +// RealPath answers realpath without touching the file system: the cleaned +// virtual path ("." is "/"). Links are not resolved, as none is followed. The +// library calls it outside the handlers that guard audits, so a refusal (a +// path that is not one) is audited here; an answer is not, clients ask for it +// all the time. +func (s *server) RealPath(p string) (string, error) { + v, err := parsePath(p) + if err != nil { + s.noteRefusal(err, p, "") + return "", err + } + return v.String(), nil +} + +// Readlink is refused: a link is never followed, and its target is not +// shown. The refusal is audited here, as for RealPath. +func (s *server) Readlink(p string) (string, error) { + err := errSymlink() + s.noteRefusal(err, p, "") + return "", err +} + +// listerAt serves a few entries held in memory (a stat) to the library. +type listerAt []os.FileInfo + +func (l listerAt) ListAt(ls []os.FileInfo, off int64) (int, error) { + if off >= int64(len(l)) { + return 0, io.EOF + } + n := copy(ls, l[off:]) + if n < len(ls) { + return n, io.EOF + } + return n, nil +} + +// Filelist serves list, stat and readlink. +func (s *server) Filelist(r *sftp.Request) (la sftp.ListerAt, err error) { + defer s.guard(&err, r) + switch r.Method { + case "List": + return s.listRequest(r) + case "Stat": + return s.stat(r, true) + default: + return nil, errUnsupported(r.Method) + } +} + +// Lstat is stat without following a link. +func (s *server) Lstat(r *sftp.Request) (la sftp.ListerAt, err error) { + defer s.guard(&err, r) + return s.stat(r, false) +} + +func (s *server) listRequest(r *sftp.Request) (sftp.ListerAt, error) { + v, err := s.path(r.Filepath) + if err != nil { + return nil, err + } + l, err := s.list(v) + if err != nil { + return nil, err + } + return l, nil +} + +// stat answers stat (follow) and lstat. A link is lstat'ed as a link; stat +// of a link would follow it, so it is refused. +func (s *server) stat(r *sftp.Request, follow bool) (sftp.ListerAt, error) { + v, err := s.path(r.Filepath) + if err != nil { + return nil, err + } + t, err := s.home.resolve(v) + if err != nil { + return nil, err + } + defer t.close() + st, err := t.lstat() + if err != nil { + return nil, err + } + if follow && st.Mode&unix.S_IFMT == unix.S_IFLNK { + return nil, errSymlink() + } + name := "/" + if !v.isRoot() { + name = v.name() + } + return listerAt{&fileInfo{name: name, st: st}}, nil +} + +// Filecmd serves the requests that change something. +func (s *server) Filecmd(r *sftp.Request) (err error) { + defer s.guard(&err, r) + switch r.Method { + case "Setstat": + return s.setstat(r) + case "Rename": + return s.rename(r, false) + case "Rmdir": + return s.remove(r, true) + case "Remove": + return s.remove(r, false) + case "Mkdir": + return s.mkdir(r) + case "Symlink": + return errSymlink() + case "Link": + return errUnsupported("hard link") + default: + return errUnsupported(r.Method) + } +} + +// PosixRename is rename that replaces an existing target. +func (s *server) PosixRename(r *sftp.Request) (err error) { + defer s.guard(&err, r) + return s.rename(r, true) +} + +func (s *server) mkdir(r *sftp.Request) (err error) { + v, err := s.changePath(r.Filepath) + if err != nil { + return err + } + defer func() { s.audit(Event{Op: "mkdir", Path: v.String(), Err: err}) }() + t, err := s.home.resolve(v) + if err != nil { + return err + } + defer t.close() + mode := uint32(0o755) + if r.AttrFlags().Permissions { + if a := r.Attributes(); a != nil { + mode = a.Mode & 0o777 + } + } + return t.pathErr("mkdir", unix.Mkdirat(t.dir, t.name, mode)) +} + +// remove deletes a file or link (the entry itself, never what a link points +// at) or, with dir, an empty directory. +func (s *server) remove(r *sftp.Request, dir bool) (err error) { + v, err := s.changePath(r.Filepath) + if err != nil { + return err + } + defer func() { s.audit(Event{Op: "delete", Path: v.String(), Err: err}) }() + t, err := s.home.resolve(v) + if err != nil { + return err + } + defer t.close() + flags := 0 + op := "remove" + if dir { + flags = unix.AT_REMOVEDIR + op = "rmdir" + } + unlink := func() error { return t.pathErr(op, unix.Unlinkat(t.dir, t.name, flags)) } + if s.quota != nil { + return s.quota.unlinking(t, unlink) + } + return unlink() +} + +// rename moves an entry; a link is moved as the link it is. Plain rename +// fails when the target exists (as OpenSSH's server does), posix-rename +// replaces it. +func (s *server) rename(r *sftp.Request, replace bool) (err error) { + src, err := s.changePath(r.Filepath) + if err != nil { + return err + } + dst, err := s.changePath(r.Target) + if err != nil { + return err + } + defer func() { s.audit(Event{Op: "rename", Path: src.String(), To: dst.String(), Err: err}) }() + ts, err := s.home.resolve(src) + if err != nil { + return err + } + defer ts.close() + td, err := s.home.resolve(dst) + if err != nil { + return err + } + defer td.close() + move := func() error { return ts.pathErr("rename", renameat(ts, td, replace)) } + // A rename that replaces a file frees that file's room, unless source and + // target are the same inode (then it does nothing). + if replace && s.quota != nil && !sameEntry(ts, td) { + return s.quota.unlinking(td, move) + } + return move() +} + +// sameEntry reports whether two targets name the same inode. +func sameEntry(a, b *target) bool { + var sa, sb unix.Stat_t + if unix.Fstatat(a.dir, a.name, &sa, unix.AT_SYMLINK_NOFOLLOW) != nil || + unix.Fstatat(b.dir, b.name, &sb, unix.AT_SYMLINK_NOFOLLOW) != nil { + return false + } + return sa.Dev == sb.Dev && sa.Ino == sb.Ino +} + +func renameat(ts, td *target, replace bool) error { + if replace { + return unix.Renameat2(ts.dir, ts.name, td.dir, td.name, 0) + } + err := unix.Renameat2(ts.dir, ts.name, td.dir, td.name, unix.RENAME_NOREPLACE) + if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOSYS) { + // A file system without RENAME_NOREPLACE: look, then rename. + var st unix.Stat_t + if unix.Fstatat(td.dir, td.name, &st, unix.AT_SYMLINK_NOFOLLOW) == nil { + return unix.EEXIST + } + return unix.Renameat2(ts.dir, ts.name, td.dir, td.name, 0) + } + return err +} + +// maxSize is the largest size a client may set (4 EiB): a size the file +// system could never hold is refused before anything is looked at. +const maxSize = 1 << 62 + +// setstat changes the size, the permission bits and the times, in that order, +// and nothing else. Everything a request can be refused for is judged before +// the first change, so that a refused request changes nothing; what the file +// system refuses later (the room of a growing file, a permission) can still +// leave the part before it done. +func (s *server) setstat(r *sftp.Request) (err error) { + v, err := s.changePath(r.Filepath) + if err != nil { + return err + } + fl := r.AttrFlags() + if fl.UidGid { + return errUnsupported("changing the owner") + } + a := r.Attributes() + if a == nil { + return errBadPath("malformed attributes") + } + if fl.Size && a.Size > maxSize { + return errUnsupported("a size of more than 4 EiB") + } + defer func() { s.audit(Event{Op: "setstat", Path: v.String(), Err: err}) }() + t, err := s.home.resolve(v) + if err != nil { + return err + } + defer t.close() + // The entry is pinned, judged on the descriptor and changed through it: + // a name that is made to mean another file between the look and the change + // (a rename of a hard link of a key file over it) is not followed. + p, err := t.pin("stat") + if err != nil { + return err + } + defer p.close() + st := p.st + typ := st.Mode & unix.S_IFMT + if typ == unix.S_IFLNK { + return errSymlink() + } + if typ == unix.S_IFREG && st.Nlink > 1 { + return errLink() + } + if fl.Size { + switch typ { + case unix.S_IFREG: + case unix.S_IFDIR: + return t.pathErr("truncate", unix.EISDIR) + default: + return errUnsupported("changing the size of something that is not a regular file") + } + } + // A directory the owner cannot list or search is one the quota + // cannot measure and the client cannot list: not a mode to set. + if fl.Permissions && typ == unix.S_IFDIR && a.Mode&0o500 != 0o500 { + return errUnsupported("clearing the owner's read or search permission of a directory") + } + if s.afterPin != nil { + s.afterPin() + } + if fl.Size { + if err := s.resize(p, int64(a.Size)); err != nil { + return err + } + } + if fl.Permissions { + if err := p.chmod(a.Mode & 0o777); err != nil { + return err + } + } + if fl.Acmodtime { + if err := p.utimes(a.Atime, a.Mtime); err != nil { + return err + } + } + return nil +} + +// resize sets the size of the pinned regular file: it cuts or extends it. With +// a quota the size is read, the file changed and the usage corrected as one +// step under the quota's lock, like a write or a truncating open, and a growth +// that does not fit is refused. +func (s *server) resize(p *pinned, size int64) error { + if s.quota == nil { + return p.truncate(size) + } + return s.quota.resizing(p, size) +} + +// StatVFS answers statvfs (df in sftp). With a quota the file system is +// the quota: its size and what is left of it, in 4 KiB blocks; else it is +// the file system of the home. +func (s *server) StatVFS(r *sftp.Request) (v *sftp.StatVFS, err error) { + defer s.guard(&err, r) + if _, err := s.path(r.Filepath); err != nil { + return nil, err + } + var fs unix.Statfs_t + if err := unix.Fstatfs(s.home.fd, &fs); err != nil { + return nil, &os.PathError{Op: "statvfs", Path: "/", Err: err} + } + v = &sftp.StatVFS{ + Bsize: u64(fs.Bsize), + Frsize: u64(fs.Frsize), + Blocks: u64(fs.Blocks), + Bfree: u64(fs.Bfree), + Bavail: u64(fs.Bavail), + Files: u64(fs.Files), + Ffree: u64(fs.Ffree), + Favail: u64(fs.Ffree), + Namemax: maxName, + } + if s.quota != nil { + const block = 4096 + used := s.quota.usage() + free := max(0, s.quota.limit-used) + v.Bsize, v.Frsize = block, block + v.Blocks = uint64((s.quota.limit + block - 1) / block) + v.Bfree = uint64(free / block) + v.Bavail = v.Bfree + } + return v, nil +} + +// failedOpen audits an open that failed in the kernel as the transfer it +// was meant to be, with the error. A refusal is audited as one by guard, with +// its reason, and not here. +func (s *server) failedOpen(r *sftp.Request, op string, err error) { + if reasonOf(err) == "" { + s.audit(Event{Op: op, Path: display(r.Filepath), Err: err}) + } +} + +// Fileread opens a file for download. +func (s *server) Fileread(r *sftp.Request) (ra io.ReaderAt, err error) { + defer s.guard(&err, r) + f, err := s.openFile(r, false) + if err != nil { + s.failedOpen(r, "download", err) + return nil, err + } + return f, nil +} + +// Filewrite opens a file for upload. +func (s *server) Filewrite(r *sftp.Request) (wa io.WriterAt, err error) { + defer s.guard(&err, r) + f, err := s.openFile(r, true) + if err != nil { + s.failedOpen(r, "upload", err) + return nil, err + } + return f, nil +} + +// OpenFile opens a file for reading and writing on one handle. +func (s *server) OpenFile(r *sftp.Request) (rw sftp.WriterAtReaderAt, err error) { + defer s.guard(&err, r) + f, err := s.openFile(r, true) + if err != nil { + s.failedOpen(r, "upload", err) + return nil, err + } + return f, nil +} diff --git a/internal/sftpd/handles.go b/internal/sftpd/handles.go new file mode 100644 index 00000000..4be631d4 --- /dev/null +++ b/internal/sftpd/handles.go @@ -0,0 +1,175 @@ +package sftpd + +import ( + "io" + "os" + "sync" + + "golang.org/x/sys/unix" +) + +// maxHandles is how many handles a session may have open at once, files and +// directory listings together. Each holds a descriptor, and the client picks +// how many to open: without a bound it is a way to exhaust the descriptors of +// the process that serves it. +const maxHandles = 256 + +// handleCount counts the open handles of a session against a limit. +type handleCount struct { + max int + + mu sync.Mutex + n int +} + +// acquire takes a place, or says there is none. +func (c *handleCount) acquire() error { + c.mu.Lock() + defer c.mu.Unlock() + if c.n >= c.max { + return errTooMany() + } + c.n++ + return nil +} + +// release gives a place back. +func (c *handleCount) release() { + c.mu.Lock() + defer c.mu.Unlock() + if c.n > 0 { + c.n-- + } +} + +// listBatch is how many names a directory listing reads at a time when the +// library asks for fewer (it asks for MaxFilelist, 100): the memory of a +// listing is a batch, whatever the size of the directory. +const listBatch = 100 + +// dirLister serves a directory listing to the library, one batch at a time. +// The directory is held open for as long as the handle is, and read as the +// client asks for entries. The library asks for entries at the offset of the +// ones it has been given, so a listing is a sequential read; a request for an +// earlier offset starts the directory again from its beginning, and one for a +// later offset skips ahead. Entries come in the order the file system gives +// them, not sorted (a client sorts a listing itself when it wants it so). +// +// It is an io.Closer: the library closes it with the handle. +type dirLister struct { + s *server + v vpath + root bool // the home: .ssh is left out + + mu sync.Mutex + fd int // the directory; f owns it + f *os.File // nil once closed + pos int64 // entries given out so far +} + +// list opens the directory of v for a listing and takes a place for it. +func (s *server) list(v vpath) (*dirLister, error) { + if err := s.handles.acquire(); err != nil { + return nil, err + } + t, err := s.home.resolve(v) + if err != nil { + s.handles.release() + return nil, err + } + defer t.close() + fd, err := t.openDir() + if err != nil { + s.handles.release() + return nil, err + } + return &dirLister{s: s, v: v, root: v.isRoot(), fd: fd, f: os.NewFile(uintptr(fd), v.String())}, nil +} + +// ListAt gives the entries from offset off on. +func (l *dirLister) ListAt(ls []os.FileInfo, off int64) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + if l.f == nil { + return 0, os.ErrClosed + } + if off < 0 { + return 0, io.EOF + } + if off < l.pos { + if err := l.rewind(); err != nil { + return 0, err + } + } + for l.pos < off { + if _, err := l.next(int(min(off-l.pos, listBatch))); err != nil { + return 0, err + } + } + n := 0 + for n < len(ls) { + got, err := l.next(min(len(ls)-n, listBatch)) + n += copy(ls[n:], got) + if err != nil { + return n, err // io.EOF at the end of the directory + } + } + return n, nil +} + +// rewind starts the directory again from its first entry, on a new +// description of the same directory. +func (l *dirLister) rewind() error { + fd, err := unix.Openat(l.fd, ".", dirFlags, 0) + if err != nil { + return &os.PathError{Op: "readdir", Path: l.v.String(), Err: err} + } + _ = l.f.Close() + l.fd, l.f, l.pos = fd, os.NewFile(uintptr(fd), l.v.String()), 0 + return nil +} + +// next reads up to want entries (at least one, unless the directory is at +// its end, then io.EOF), each lstat'ed through the open directory (a link is +// listed as a link). A name that is gone since it was read is left out. +func (l *dirLister) next(want int) ([]os.FileInfo, error) { + var out []os.FileInfo + for len(out) == 0 { + names, err := l.f.Readdirnames(want) + if len(names) == 0 { + if err == nil { + err = io.EOF + } + if err != io.EOF { + err = &os.PathError{Op: "readdir", Path: l.v.String(), Err: err} + } + return nil, err + } + for _, n := range names { + if l.root && n == sshDir { + continue + } + fi := &fileInfo{name: n} + if err := unix.Fstatat(l.fd, n, &fi.st, unix.AT_SYMLINK_NOFOLLOW); err != nil { + continue + } + out = append(out, fi) + } + } + l.pos += int64(len(out)) + return out, nil +} + +// Close closes the directory and gives the place back. It is safe to call +// twice. +func (l *dirLister) Close() error { + l.mu.Lock() + defer l.mu.Unlock() + if l.f == nil { + return nil + } + err := l.f.Close() + l.f = nil + l.s.handles.release() + return err +} diff --git a/internal/sftpd/handles_test.go b/internal/sftpd/handles_test.go new file mode 100644 index 00000000..674798fe --- /dev/null +++ b/internal/sftpd/handles_test.go @@ -0,0 +1,339 @@ +package sftpd + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/pkg/sftp" +) + +// wantTooMany checks the answer to an open that is over the limit. +func wantTooMany(t *testing.T, what string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s succeeded, want too many open files", what) + return + } + // Through the client the status is a code; called directly, the error + // still unwraps to it. + isFailure := code(err) == fxFailure || errors.Is(err, sftp.ErrSSHFxFailure) + if !strings.Contains(err.Error(), "too many open files") || !isFailure { + t.Errorf("%s: %v, want a failure status with too many open files", what, err) + } +} + +// listRequest is the request for the listing of a directory. +func listRequest(p string) *sftp.Request { + return &sftp.Request{Method: "List", Filepath: p} +} + +func TestHandleLimitForFiles(t *testing.T) { + e := newEnvSeams(t, nil, seams{maxHandles: 4}) + e.write("f", "x") + var open []*sftp.File + for i := 0; i < 4; i++ { + h, err := e.client.Open("f") + if err != nil { + t.Fatalf("open %d: %v", i, err) + } + open = append(open, h) + } + _, err := e.client.Open("f") + wantTooMany(t, "the fifth open", err) + _, err = e.client.OpenFile("g", os.O_WRONLY|os.O_CREATE) + wantTooMany(t, "an open for writing", err) + if e.exists("g") { + t.Error("a refused open created the file") + } + if got := refusals(e.rec.all()); len(got) != 2 || got[0] != "too many open files" { + t.Errorf("refusals = %v, want two too many open files", got) + } + // Closing gives a place back. + _ = open[0].Close() + h, err := e.client.Open("f") + if err != nil { + t.Fatalf("open after a close: %v", err) + } + _ = h.Close() + for _, h := range open[1:] { + _ = h.Close() + } + for i := 0; i < 20; i++ { // nothing leaks over many opens and closes + w, err := e.client.OpenFile("w", os.O_WRONLY|os.O_CREATE) + if err != nil { + t.Fatalf("open for writing %d: %v", i, err) + } + _ = w.Close() + } +} + +// An open that fails for another reason holds no place. +func TestHandleLimitCountsOnlyOpenHandles(t *testing.T) { + e := newEnvSeams(t, nil, seams{maxHandles: 2}) + e.write("f", "x") + e.write(".ssh/k", "x") + for i := 0; i < 10; i++ { + _, _ = e.client.Open("missing") + _, _ = e.client.Open(".ssh/k") + _, _ = e.client.Open("/") + _, _ = e.client.ReadDir("missing") + _, _ = e.client.ReadDir("f") + } + a, err := e.client.Open("f") + if err != nil { + t.Fatal(err) + } + b, err := e.client.Open("f") + if err != nil { + t.Fatalf("second handle after failed opens: %v", err) + } + _ = a.Close() + _ = b.Close() +} + +// The listers are closed by the library with their handle; here they are +// opened and closed by hand, as the library does. +func TestHandleLimitForListings(t *testing.T) { + e := newEnv(t, nil) + e.write("d/f", "x") + s := newServer(mustHome(t, e.home), Config{Home: e.home}, seams{maxHandles: 3}) + var ls []io.Closer + for i := 0; i < 3; i++ { + la, err := s.Filelist(listRequest("/d")) + if err != nil { + t.Fatalf("listing %d: %v", i, err) + } + ls = append(ls, la.(io.Closer)) + } + _, err := s.Filelist(listRequest("/d")) + wantTooMany(t, "the fourth listing", err) + if reasonOf(err) != reasonTooMany { + t.Errorf("reason = %q", reasonOf(err)) + } + // A stat is no handle. + if _, err := s.Filelist(&sftp.Request{Method: "Stat", Filepath: "/d"}); err != nil { + t.Errorf("stat at the limit: %v", err) + } + _ = ls[0].Close() + _ = ls[0].Close() // twice gives back one place only + la, err := s.Filelist(listRequest("/d")) + if err != nil { + t.Fatalf("listing after a close: %v", err) + } + ls = append(ls, la.(io.Closer)) + _, err = s.Filelist(listRequest("/d")) + wantTooMany(t, "a listing past the limit after a double close", err) + for _, c := range ls { + _ = c.Close() + } +} + +func TestHandleLimitMixedFilesAndListingsThroughTheClient(t *testing.T) { + e := newEnvSeams(t, nil, seams{maxHandles: 3}) + e.write("d/f", "x") + var open []*sftp.File + for i := 0; i < 3; i++ { + h, err := e.client.Open("d/f") + if err != nil { + t.Fatal(err) + } + open = append(open, h) + } + _, err := e.client.ReadDir("d") + wantTooMany(t, "a listing with three files open", err) + _ = open[0].Close() + if ents, err := e.client.ReadDir("d"); err != nil || len(ents) != 1 { + t.Errorf("listing after a close: %v, %v", ents, err) + } + // The client closed the listing's handle: its place is free again. + h, err := e.client.Open("d/f") + if err != nil { + t.Errorf("open after a listing: %v", err) + } else { + _ = h.Close() + } + for _, h := range open[1:] { + _ = h.Close() + } +} + +func TestSessionEndsWithHandlesOpen(t *testing.T) { + e := newEnvSeams(t, nil, seams{maxHandles: 3}) + e.write("f", "x") + for i := 0; i < 3; i++ { + if _, err := e.client.Open("f"); err != nil { + t.Fatal(err) + } + } + // The library reports a session that ends with handles open as an + // unexpected end of the stream; what matters is that it ends. + if err := e.stop(); err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { + t.Errorf("Serve with handles open: %v", err) + } +} + +// The listing is read as the client asks for it and the directory is not +// held in memory: many handles on a big directory cost a batch each. +func TestListingsDoNotSnapshotTheDirectory(t *testing.T) { + e := newEnv(t, nil) + long := strings.Repeat("n", 200) + for i := 0; i < 2000; i++ { + if err := os.WriteFile(filepath.Join(e.home, fmt.Sprintf("%s%04d", long, i)), nil, 0o644); err != nil { + t.Fatal(err) + } + } + s := newServer(mustHome(t, e.home), Config{Home: e.home}, seams{}) + heap := func() uint64 { + runtime.GC() + var m runtime.MemStats + runtime.ReadMemStats(&m) + return m.HeapAlloc + } + before := heap() + var held []io.Closer + const n = 200 + for i := 0; i < n; i++ { + la, err := s.Filelist(listRequest("/")) + if err != nil { + t.Fatal(err) + } + held = append(held, la.(io.Closer)) + ls := make([]os.FileInfo, 100) + if got, err := la.ListAt(ls, 0); got != 100 || err != nil { + t.Fatalf("first batch: %d, %v", got, err) + } + } + grown := int64(heap()) - int64(before) + // A snapshot of 2000 entries with 200-byte names, 200 times over, is + // over 100 MiB; a batch of 100 entries each is a few MiB at most. + if grown > 32<<20 { + t.Errorf("heap grew by %d MiB for %d listings of a 2000-entry directory", grown>>20, n) + } + runtime.KeepAlive(held) + for _, c := range held { + _ = c.Close() + } +} + +// listAll reads a listing in batches of size, the way the library does. +func listAll(t *testing.T, la sftp.ListerAt, size int) []string { + t.Helper() + var names []string + for { + ls := make([]os.FileInfo, size) + n, err := la.ListAt(ls, int64(len(names))) + for _, fi := range ls[:n] { + names = append(names, fi.Name()) + } + if err == io.EOF { + return names + } + if err != nil { + t.Fatal(err) + } + } +} + +func TestListerOffsets(t *testing.T) { + e := newEnv(t, nil) + for i := 0; i < 250; i++ { + e.write(fmt.Sprintf("d/f%03d", i), "x") + } + s := newServer(mustHome(t, e.home), Config{Home: e.home}, seams{}) + open := func() sftp.ListerAt { + la, err := s.Filelist(listRequest("/d")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = la.(io.Closer).Close() }) + return la + } + la := open() + all := listAll(t, la, 100) + if len(all) != 250 { + t.Fatalf("%d entries, want 250", len(all)) + } + seen := map[string]bool{} + for _, n := range all { + if seen[n] { + t.Errorf("duplicate %s", n) + } + seen[n] = true + } + // The same listing in other batch sizes gives the same entries. + if got := listAll(t, open(), 7); strings.Join(got, ",") != strings.Join(all, ",") { + t.Error("batches of 7 gave another listing") + } + // At the end: EOF, again and again. + ls := make([]os.FileInfo, 100) + if n, err := la.ListAt(ls, 250); n != 0 || err != io.EOF { + t.Errorf("at the end: %d, %v", n, err) + } + if n, err := la.ListAt(ls, 1000); n != 0 || err != io.EOF { + t.Errorf("past the end: %d, %v", n, err) + } + // A non-sequential offset: back to the start, then forward and back. + for _, off := range []int64{0, 130, 30, 249, 100, 0} { + n, err := la.ListAt(ls, off) + want := min(100, 250-int(off)) + if n != want { + t.Errorf("at %d: %d entries, want %d (%v)", off, n, want, err) + continue + } + for i := 0; i < n; i++ { + if ls[i].Name() != all[int(off)+i] { + t.Errorf("at %d entry %d is %s, want %s", off, i, ls[i].Name(), all[int(off)+i]) + break + } + } + } + // A first read at a later offset skips ahead. + small := make([]os.FileInfo, 3) + if n, _ := open().ListAt(small, 200); n != 3 || small[0].Name() != all[200] { + t.Errorf("a first read at offset 200: %d, %v", n, small[0]) + } +} + +func TestListerHidesSSHAndSurvivesRemovals(t *testing.T) { + e := sshEnv(t) + for i := 0; i < 150; i++ { + e.write(fmt.Sprintf("f%03d", i), "x") + } + s := newServer(mustHome(t, e.home), Config{Home: e.home}, seams{}) + la, err := s.Filelist(listRequest("/")) + if err != nil { + t.Fatal(err) + } + defer func() { _ = la.(io.Closer).Close() }() + names := listAll(t, la, 100) + if len(names) != 152 { // a, plain and the 150 + t.Errorf("%d entries, want 152", len(names)) + } + for _, n := range names { + if n == ".ssh" { + t.Error(".ssh is listed") + } + } + // Removed after the listing began: simply not there. + la2, err := s.Filelist(listRequest("/")) + if err != nil { + t.Fatal(err) + } + defer func() { _ = la2.(io.Closer).Close() }() + first := make([]os.FileInfo, 10) + if n, err := la2.ListAt(first, 0); n != 10 || err != nil { + t.Fatalf("first batch: %d, %v", n, err) + } + for i := 0; i < 150; i++ { + _ = os.Remove(filepath.Join(e.home, fmt.Sprintf("f%03d", i))) + } + if rest := listAll(t, la2, 100); len(rest) > 152 { + t.Errorf("%d entries after the removals", len(rest)) + } +} diff --git a/internal/sftpd/helpers_test.go b/internal/sftpd/helpers_test.go new file mode 100644 index 00000000..5e640c0a --- /dev/null +++ b/internal/sftpd/helpers_test.go @@ -0,0 +1,218 @@ +package sftpd + +import ( + "errors" + "io" + "net" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/pkg/sftp" +) + +// recorder collects the audit events of a session. +type recorder struct { + mu sync.Mutex + ev []Event +} + +func (r *recorder) add(e Event) { + r.mu.Lock() + defer r.mu.Unlock() + r.ev = append(r.ev, e) +} + +func (r *recorder) all() []Event { + r.mu.Lock() + defer r.mu.Unlock() + return append([]Event(nil), r.ev...) +} + +func (r *recorder) reset() { + r.mu.Lock() + defer r.mu.Unlock() + r.ev = nil +} + +// env is one session: a real home directory, Serve on one end of a pipe and +// a pkg/sftp client on the other. +type env struct { + t *testing.T + root string // the directory that holds the home; files in it are outside the home + home string + client *sftp.Client + rec *recorder + done chan error + sm seams +} + +// newEnv starts a session. tweak, when not nil, changes the Config before +// Serve gets it. +func newEnv(t *testing.T, tweak func(*Config)) *env { + t.Helper() + return newEnvSeams(t, tweak, seams{}) +} + +// newEnvSeams is newEnv with the clock (and whatever else a test replaces). +func newEnvSeams(t *testing.T, tweak func(*Config), sm seams) *env { + t.Helper() + e := &env{t: t, rec: &recorder{}, done: make(chan error, 1), sm: sm} + e.root = t.TempDir() + e.home = filepath.Join(e.root, "home") + if err := os.Mkdir(e.home, 0o755); err != nil { + t.Fatal(err) + } + cfg := Config{Home: e.home, Audit: e.rec.add} + if tweak != nil { + tweak(&cfg) + } + e.start(cfg) + return e +} + +// start serves cfg on a new pipe and connects the client. +func (e *env) start(cfg Config) { + e.t.Helper() + cs, ss := net.Pipe() + e.done = make(chan error, 1) + go func() { e.done <- serve(ss, cfg, e.sm) }() + c, err := sftp.NewClientPipe(cs, cs) + if err != nil { + e.t.Fatal(err) + } + e.client = c + e.t.Cleanup(func() { _ = e.stop() }) +} + +// stop ends the session and returns what Serve returned. +func (e *env) stop() error { + if e.client == nil { + return nil + } + _ = e.client.Close() + e.client = nil + return <-e.done +} + +// write makes a file in the home (or below it) directly. +func (e *env) write(rel, content string) { + e.t.Helper() + p := filepath.Join(e.home, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + e.t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + e.t.Fatal(err) + } +} + +// read returns the content of a file in the home. +func (e *env) read(rel string) string { + e.t.Helper() + b, err := os.ReadFile(filepath.Join(e.home, rel)) + if err != nil { + e.t.Fatal(err) + } + return string(b) +} + +// exists reports whether the entry (a link counts as itself) is in the home. +func (e *env) exists(rel string) bool { + _, err := os.Lstat(filepath.Join(e.home, rel)) + return err == nil +} + +// put uploads content through the client and fails the test on an error. +func (e *env) put(path, content string) { + e.t.Helper() + if err := putFile(e.client, path, content); err != nil { + e.t.Fatalf("upload %s: %v", path, err) + } +} + +func putFile(c *sftp.Client, path, content string) error { + f, err := c.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC) + if err != nil { + return err + } + if _, err := f.Write([]byte(content)); err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// get downloads a file through the client. +func (e *env) get(path string) (string, error) { + f, err := e.client.Open(path) + if err != nil { + return "", err + } + defer func() { _ = f.Close() }() + b, err := io.ReadAll(f) + return string(b), err +} + +// code is the SFTP status code of err. The client turns the codes no such +// file and permission denied into os.ErrNotExist and os.ErrPermission, and +// keeps the others as a *sftp.StatusError; -1 is anything else. +func code(err error) int { + var se *sftp.StatusError + switch { + case err == nil: + return 0 + case errors.Is(err, os.ErrNotExist): + return fxNoSuchFile + case errors.Is(err, os.ErrPermission): + return fxPermissionDenied + case errors.As(err, &se): + return int(se.Code) + } + return -1 +} + +const ( + fxNoSuchFile = 2 + fxPermissionDenied = 3 + fxFailure = 4 + fxOpUnsupported = 8 +) + +// refusals are the "refused" events, with their reasons. +func refusals(ev []Event) []string { + var out []string + for _, e := range ev { + if e.Op == "refused" { + out = append(out, e.Err.Error()) + } + } + return out +} + +// pipePair is two connected ends. +func pipePair() (net.Conn, net.Conn) { return net.Pipe() } + +// clock is a clock a test moves by hand. +type clock struct { + mu sync.Mutex + t time.Time +} + +func newClock() *clock { + return &clock{t: time.Date(2026, 10, 12, 13, 11, 0, 0, time.UTC)} +} + +func (c *clock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *clock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} diff --git a/internal/sftpd/ops_test.go b/internal/sftpd/ops_test.go new file mode 100644 index 00000000..4561e358 --- /dev/null +++ b/internal/sftpd/ops_test.go @@ -0,0 +1,552 @@ +package sftpd + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// 1. The home is "/". + +func TestRealPathIsRoot(t *testing.T) { + e := newEnv(t, nil) + for _, in := range []string{".", "", "/", "..", "../..", "/..", "a/..", "./"} { + got, err := e.client.RealPath(in) + if err != nil || got != "/" { + t.Errorf("RealPath(%q) = %q, %v; want /", in, got, err) + } + } + if got, err := e.client.Getwd(); err != nil || got != "/" { + t.Errorf("Getwd = %q, %v; want /", got, err) + } + if got, _ := e.client.RealPath("a/./b/../c"); got != "/a/c" { + t.Errorf("RealPath(a/./b/../c) = %q, want /a/c", got) + } +} + +func TestPathsStayInsideHome(t *testing.T) { + e := newEnv(t, nil) + // A secret next to the home, where "../" would lead. + if err := os.WriteFile(filepath.Join(e.root, "secret"), []byte("outside"), 0o644); err != nil { + t.Fatal(err) + } + if err := e.client.MkdirAll("/etc"); err != nil { + t.Fatal(err) + } + e.put("/etc/passwd", "inside") + if got := e.read("etc/passwd"); got != "inside" { + t.Errorf("home/etc/passwd = %q", got) + } + // Relative and absolute spellings reach the same file. + for _, p := range []string{"etc/passwd", "/etc/passwd", "./etc/passwd", "/../etc/passwd", "../../etc/passwd", "/etc/../etc/passwd", "//etc//passwd"} { + got, err := e.get(p) + if err != nil || got != "inside" { + t.Errorf("get %q = %q, %v", p, got, err) + } + } + // ".." cannot leave: the secret one level up is not there. + for _, p := range []string{"../secret", "/../secret", "../../../secret", "etc/../../secret"} { + if _, err := e.get(p); code(err) != fxNoSuchFile { + t.Errorf("get %q: err = %v, want no such file", p, err) + } + } + // Writing "outside" lands inside. + e.put("../planted", "x") + if !e.exists("planted") { + t.Error("../planted was not written in the home") + } + if _, err := os.Lstat(filepath.Join(e.root, "planted")); err == nil { + t.Error("../planted left the home") + } + // A stat of the root is the home. + fi, err := e.client.Stat("/../..") + if err != nil || !fi.IsDir() { + t.Errorf("Stat(/../..) = %v, %v", fi, err) + } +} + +func TestHomeReachedThroughALink(t *testing.T) { + e := newEnv(t, nil) + // Home may itself be a link (the caller's configuration). + link := filepath.Join(e.root, "homelink") + if err := os.Symlink(e.home, link); err != nil { + t.Fatal(err) + } + e.write("f", "hello") + if err := e.stop(); err != nil { + t.Fatal(err) + } + e.start(Config{Home: link}) + if got, err := e.get("f"); err != nil || got != "hello" { + t.Errorf("get f = %q, %v", got, err) + } +} + +func TestServeNeedsAHome(t *testing.T) { + for _, home := range []string{"", filepath.Join(t.TempDir(), "missing")} { + a, b := pipePair() + err := Serve(a, Config{Home: home}) + if err == nil { + t.Errorf("Serve(Home=%q) = nil, want an error", home) + } + _ = b.Close() + } +} + +// 3. The operations. + +func TestStatLstatFstat(t *testing.T) { + e := newEnv(t, nil) + e.write("d/f", "12345") + fi, err := e.client.Stat("d/f") + if err != nil || fi.Size() != 5 || fi.Name() != "f" || fi.IsDir() { + t.Errorf("Stat d/f = %v, %v", fi, err) + } + fi, err = e.client.Lstat("d") + if err != nil || !fi.IsDir() { + t.Errorf("Lstat d = %v, %v", fi, err) + } + f, err := e.client.Open("d/f") + if err != nil { + t.Fatal(err) + } + defer func() { _ = f.Close() }() + if fi, err := f.Stat(); err != nil || fi.Size() != 5 { + t.Errorf("Fstat = %v, %v", fi, err) + } + if _, err := e.client.Stat("nope"); code(err) != fxNoSuchFile { + t.Errorf("Stat nope: %v", err) + } + if _, err := e.client.Stat("d/f/x"); err == nil { + t.Error("Stat through a file succeeded") + } + // The mode and the time come from the file. + when := time.Date(2026, 10, 12, 13, 11, 0, 0, time.UTC) + if err := os.Chtimes(filepath.Join(e.home, "d/f"), when, when); err != nil { + t.Fatal(err) + } + fi, _ = e.client.Stat("d/f") + if !fi.ModTime().Equal(when) { + t.Errorf("ModTime = %v, want %v", fi.ModTime(), when) + } +} + +func TestListDirectory(t *testing.T) { + e := newEnv(t, nil) + for i := 0; i < 250; i++ { // more than one batch of the library + e.write(fmt.Sprintf("d/f%03d", i), "x") + } + if err := os.Mkdir(filepath.Join(e.home, "d", "sub"), 0o755); err != nil { + t.Fatal(err) + } + ents, err := e.client.ReadDir("d") + if err != nil { + t.Fatal(err) + } + if len(ents) != 251 { + t.Fatalf("ReadDir returned %d entries, want 251", len(ents)) + } + seen := map[string]bool{} + for _, fi := range ents { + if seen[fi.Name()] { + t.Errorf("duplicate entry %s", fi.Name()) + } + seen[fi.Name()] = true + if fi.Name() == "sub" && !fi.IsDir() { + t.Error("sub is not a directory") + } + } + if ents, err := e.client.ReadDir("/"); err != nil || len(ents) != 1 { + t.Errorf("ReadDir / = %d entries, %v", len(ents), err) + } + if _, err := e.client.ReadDir("d/f000"); err == nil { + t.Error("ReadDir of a file succeeded") + } + if _, err := e.client.ReadDir("nope"); code(err) != fxNoSuchFile { + t.Errorf("ReadDir nope: %v", err) + } +} + +func TestDownload(t *testing.T) { + e := newEnv(t, nil) + big := strings.Repeat("0123456789abcdef", 8192) // 128 KiB: several packets + e.write("big", big) + got, err := e.get("big") + if err != nil || got != big { + t.Errorf("download of 128 KiB: %d bytes, %v", len(got), err) + } + if _, err := e.client.Open("/"); err == nil { + t.Error("Open of a directory for reading succeeded") + } + if _, err := e.client.Open("missing"); code(err) != fxNoSuchFile { + t.Errorf("Open missing: %v", err) + } +} + +func TestUploadCreateTruncateAppendPwrite(t *testing.T) { + e := newEnv(t, nil) + big := strings.Repeat("xyz", 50000) // 150 KB over several packets + e.put("up", big) + if got := e.read("up"); got != big { + t.Errorf("upload: %d bytes stored, want %d", len(got), len(big)) + } + // Truncate through the open flags. + e.put("up", "short") + if got := e.read("up"); got != "short" { + t.Errorf("after the overwrite = %q", got) + } + // Append. + f, err := e.client.OpenFile("up", os.O_WRONLY|os.O_APPEND) + if err != nil { + t.Fatal(err) + } + if _, err := f.Write([]byte("+more")); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + if got := e.read("up"); got != "short+more" { + t.Errorf("after the append = %q", got) + } + // Writes at offsets, in any order (what a parallel scp does). + g, err := e.client.OpenFile("pw", os.O_WRONLY|os.O_CREATE|os.O_EXCL) + if err != nil { + t.Fatal(err) + } + if _, err := g.WriteAt([]byte("world"), 6); err != nil { + t.Fatal(err) + } + if _, err := g.WriteAt([]byte("hello "), 0); err != nil { + t.Fatal(err) + } + if err := g.Close(); err != nil { + t.Fatal(err) + } + if got := e.read("pw"); got != "hello world" { + t.Errorf("pwrite = %q", got) + } + // O_EXCL on an existing file fails. + if _, err := e.client.OpenFile("pw", os.O_WRONLY|os.O_CREATE|os.O_EXCL); err == nil { + t.Error("exclusive create of an existing file succeeded") + } + // Read and write on one handle. + h, err := e.client.OpenFile("pw", os.O_RDWR) + if err != nil { + t.Fatal(err) + } + if _, err := h.WriteAt([]byte("J"), 0); err != nil { + t.Fatal(err) + } + buf := make([]byte, 5) + if _, err := h.ReadAt(buf, 0); err != nil || string(buf) != "Jello" { + t.Errorf("ReadAt = %q, %v", buf, err) + } + _ = h.Close() + // Uploading to a directory fails. + if err := e.client.Mkdir("dir"); err != nil { + t.Fatal(err) + } + if err := putFile(e.client, "dir", "x"); err == nil { + t.Error("upload onto a directory succeeded") + } + // New files are not executable and not special. + fi, _ := os.Stat(filepath.Join(e.home, "up")) + if fi.Mode().Perm()&0o111 != 0 || fi.Mode()&os.ModeType != 0 { + t.Errorf("mode of a new file = %v", fi.Mode()) + } +} + +func TestMkdirRmdirRemove(t *testing.T) { + e := newEnv(t, nil) + if err := e.client.Mkdir("a"); err != nil { + t.Fatal(err) + } + if err := e.client.Mkdir("a"); err == nil { + t.Error("mkdir of an existing directory succeeded") + } + if err := e.client.Mkdir("x/y"); code(err) != fxNoSuchFile { + t.Errorf("mkdir below a missing parent: %v", err) + } + if err := e.client.MkdirAll("a/b/c"); err != nil || !e.exists("a/b/c") { + t.Errorf("MkdirAll: %v", err) + } + e.put("a/f", "x") + if err := e.client.RemoveDirectory("a"); err == nil { + t.Error("rmdir of a non-empty directory succeeded") + } + if err := e.client.Remove("a/b"); err == nil || !e.exists("a/b") { + t.Errorf("Remove of a directory: %v", err) + } + if err := e.client.Remove("a/f"); err != nil || e.exists("a/f") { + t.Errorf("Remove of a file: %v", err) + } + if err := e.client.RemoveDirectory("a/b/c"); err != nil || e.exists("a/b/c") { + t.Errorf("rmdir: %v", err) + } + if err := e.client.Remove("a/f"); code(err) != fxNoSuchFile { + t.Errorf("Remove of a missing file: %v", err) + } + // The home itself cannot be removed, renamed over or made. + for _, p := range []string{"/", ".", "..", "a/.."} { + if err := e.client.RemoveDirectory(p); code(err) != fxPermissionDenied { + t.Errorf("rmdir %q: %v", p, err) + } + if err := e.client.Mkdir(p); code(err) != fxPermissionDenied { + t.Errorf("mkdir %q: %v", p, err) + } + if err := e.client.Rename("a", p); code(err) != fxPermissionDenied { + t.Errorf("rename a %q: %v", p, err) + } + } + if _, err := os.Stat(e.home); err != nil { + t.Fatal(err) + } +} + +func TestRenameAndPosixRename(t *testing.T) { + e := newEnv(t, nil) + e.put("one", "1") + e.put("two", "2") + if err := e.client.Rename("one", "uno"); err != nil || !e.exists("uno") || e.exists("one") { + t.Errorf("rename: %v", err) + } + // Plain rename does not replace. + if err := e.client.Rename("uno", "two"); err == nil { + t.Error("rename onto an existing file succeeded") + } + if e.read("two") != "2" || e.read("uno") != "1" { + t.Error("a refused rename changed a file") + } + // posix-rename replaces. + if err := e.client.PosixRename("uno", "two"); err != nil { + t.Fatal(err) + } + if e.read("two") != "1" || e.exists("uno") { + t.Error("posix-rename did not replace") + } + // Directories move with their content. + e.write("d/x", "x") + if err := e.client.Rename("d", "e"); err != nil || e.read("e/x") != "x" { + t.Errorf("rename of a directory: %v", err) + } + if err := e.client.Rename("missing", "z"); code(err) != fxNoSuchFile { + t.Errorf("rename of a missing file: %v", err) + } +} + +func TestSetstat(t *testing.T) { + e := newEnv(t, nil) + e.write("f", "content") + if err := e.client.Chmod("f", 0o600); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(filepath.Join(e.home, "f")); fi.Mode().Perm() != 0o600 { + t.Errorf("mode = %v", fi.Mode()) + } + // Only the permission bits: a setuid bit is not taken. + if err := e.client.Chmod("f", 0o4755); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(filepath.Join(e.home, "f")); fi.Mode()&os.ModeSetuid != 0 || fi.Mode().Perm() != 0o755 { + t.Errorf("mode after chmod 4755 = %v", fi.Mode()) + } + at := time.Date(2026, 10, 12, 13, 11, 0, 0, time.UTC) + mt := at.Add(time.Hour) + if err := e.client.Chtimes("f", at, mt); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(filepath.Join(e.home, "f")); !fi.ModTime().Equal(mt) { + t.Errorf("mtime = %v, want %v", fi.ModTime(), mt) + } + // On a directory, and through an open handle (fsetstat). + if err := e.client.Mkdir("d"); err != nil { + t.Fatal(err) + } + if err := e.client.Chmod("d", 0o700); err != nil { + t.Fatal(err) + } + h, err := e.client.OpenFile("f", os.O_WRONLY) + if err != nil { + t.Fatal(err) + } + if err := h.Chmod(0o640); err != nil { + t.Errorf("fsetstat chmod: %v", err) + } + _ = h.Close() + if fi, _ := os.Stat(filepath.Join(e.home, "f")); fi.Mode().Perm() != 0o640 { + t.Errorf("mode after fsetstat = %v", fi.Mode()) + } + // An owner change is refused (the size is in size_test.go). + if err := e.client.Chown("f", 0, 0); code(err) != fxOpUnsupported { + t.Errorf("chown: %v", err) + } + if e.read("f") != "content" { + t.Error("a refused setstat changed the file") + } + if err := e.client.Chmod("missing", 0o600); code(err) != fxNoSuchFile { + t.Errorf("chmod of a missing file: %v", err) + } + if err := e.client.Chmod("/", 0o777); code(err) != fxPermissionDenied { + t.Errorf("chmod of the home: %v", err) + } +} + +// The change of the mode goes through the pinned entry, which refuses a link. +func TestChmodPinned(t *testing.T) { + dir := t.TempDir() + h, err := openHome(dir) + if err != nil { + t.Fatal(err) + } + defer h.close() + if err := os.WriteFile(filepath.Join(dir, "f"), nil, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Symlink("f", filepath.Join(dir, "l")); err != nil { + t.Fatal(err) + } + tf, _ := h.resolve(vpath{"f"}) + defer tf.close() + pf, err := tf.pin("stat") + if err != nil { + t.Fatal(err) + } + defer pf.close() + if err := pf.chmod(0o600); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(filepath.Join(dir, "f")); fi.Mode().Perm() != 0o600 { + t.Errorf("mode = %v", fi.Mode()) + } + tl, _ := h.resolve(vpath{"l"}) + defer tl.close() + pl, err := tl.pin("stat") + if err != nil { + t.Fatal(err) + } + defer pl.close() + if pl.st.Mode&unix.S_IFMT != unix.S_IFLNK { + t.Errorf("the pin of a link is of type %o, want the link itself", pl.st.Mode&unix.S_IFMT) + } + if fi, _ := os.Stat(filepath.Join(dir, "f")); fi.Mode().Perm() != 0o600 { + t.Errorf("the link's target was changed: %v", fi.Mode()) + } +} + +func TestOtherRequestsAreRefused(t *testing.T) { + e := newEnv(t, nil) + e.write("f", "x") + if err := e.client.Symlink("f", "l"); code(err) != fxPermissionDenied { + t.Errorf("symlink: %v", err) + } + if err := e.client.Link("f", "h"); err == nil { + t.Error("hard link succeeded") + } + if e.exists("l") || e.exists("h") { + t.Error("a link was created") + } + if _, err := e.client.ReadLink("f"); err == nil { + t.Error("readlink succeeded") + } +} + +// The library hands a READ request on a handle opened only for writing to the +// writer, as a write of zeros; the server refuses it. +func TestReadOnWriteOnlyHandleWritesNothing(t *testing.T) { + for _, quota := range []int64{0, 1000} { + for _, fl := range []int{os.O_WRONLY, os.O_WRONLY | os.O_APPEND, os.O_WRONLY | os.O_TRUNC | os.O_CREATE} { + e := newEnv(t, func(c *Config) { c.Quota = quota }) + e.write("f", "hello world") + h, err := e.client.OpenFile("f", fl) + if err != nil { + t.Fatal(err) + } + want := e.read("f") // an open with O_TRUNC emptied it + b := make([]byte, 5) + for _, off := range []int64{0, 3, 100} { + if _, err := h.ReadAt(b, off); code(err) != fxOpUnsupported { + t.Errorf("quota %d flags %#x: read at %d on a write-only handle: %v, want unsupported", quota, fl, off, err) + } + } + if got := e.read("f"); got != want { + t.Errorf("quota %d flags %#x: a read request changed the file from %q to %q", quota, fl, want, got) + } + // The handle still writes. + if _, err := h.Write([]byte("HE")); err != nil { + t.Errorf("quota %d flags %#x: write after the refused reads: %v", quota, fl, err) + } + if err := h.Close(); err != nil { + t.Errorf("close: %v", err) + } + if got := e.read("f"); !strings.Contains(got, "HE") { + t.Errorf("quota %d flags %#x: the write did not happen: %q", quota, fl, got) + } + if got := refusals(e.rec.all()); len(got) != 1 || got[0] != "unsupported" { + t.Errorf("refusals = %v, want one unsupported for the handle", got) + } + } + } +} + +// A handle opened to read and write is not affected. +func TestReadWriteHandleStillReadsAndWrites(t *testing.T) { + e := newEnv(t, nil) + e.write("f", "hello world") + h, err := e.client.OpenFile("f", os.O_RDWR) + if err != nil { + t.Fatal(err) + } + b := make([]byte, 5) + if n, err := h.ReadAt(b, 6); n != 5 || err != nil || string(b) != "world" { + t.Errorf("read: %d, %v, %q", n, err, b) + } + if _, err := h.WriteAt([]byte("J"), 0); err != nil { + t.Error(err) + } + _ = h.Close() + if e.read("f") != "Jello world" { + t.Errorf("file = %q", e.read("f")) + } +} + +// A FIFO in the home must neither block the session nor be opened: the open +// does not wait for a peer, and the type is refused before anything is read +// or written. +func TestFIFOIsNotOpenedAndDoesNotHang(t *testing.T) { + e := newEnvSeams(t, nil, seams{maxHandles: 2}) + if err := unix.Mkfifo(filepath.Join(e.home, "p"), 0o644); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + go func() { + defer close(done) + for i := 0; i < 5; i++ { // more than the handle limit: nothing is kept + if _, err := e.client.Open("p"); code(err) != fxOpUnsupported { + t.Errorf("open of a FIFO to read: %v, want unsupported", err) + } + for _, fl := range []int{os.O_WRONLY, os.O_RDWR, os.O_WRONLY | os.O_TRUNC, os.O_RDWR | os.O_APPEND} { + if _, err := e.client.OpenFile("p", fl); err == nil { + t.Errorf("open of a FIFO with flags %#x succeeded", fl) + } + } + } + }() + // A real 10 s deadline: it only passes if the code is wrong, and then the + // test fails instead of hanging (an open of a FIFO blocks for a peer). + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("the session wedged on a FIFO") + } + // The session works, and no handle was left behind. + e.put("f", "x") + if fi, err := e.client.Stat("p"); err != nil || fi.Mode()&os.ModeNamedPipe == 0 { + t.Errorf("stat of the FIFO: %v, %v", fi, err) + } +} diff --git a/internal/sftpd/paths.go b/internal/sftpd/paths.go new file mode 100644 index 00000000..194b946d --- /dev/null +++ b/internal/sftpd/paths.go @@ -0,0 +1,73 @@ +package sftpd + +import ( + "strings" +) + +const ( + // maxName and maxPath are the Linux limits (NAME_MAX, PATH_MAX); a + // client path over them is a bad request, answered with a status + // before the kernel is asked. + maxName = 255 + maxPath = 4096 + + // sshDir is the entry of the home the client must never reach. + sshDir = ".ssh" +) + +// vpath is a client path as the server sees it: the components of the +// cleaned absolute path under the virtual root "/", which is the home. +// The root is the empty list. +type vpath []string + +// parsePath cleans a client path lexically, as a Unix shell would after +// "cd /": empty and "." components go, ".." removes the component before it +// and, at the root, does nothing (so ".." can never leave the home), and a +// relative path is taken from the root. The cleaning is only a lexical +// step: it is sound because the resolution never follows a symbolic link +// (see resolve), so a name always means what it says. +// +// A path with a NUL, one over maxPath or a component over maxName is a bad +// request. +func parsePath(p string) (vpath, error) { + if len(p) > maxPath { + return nil, errBadPath("path too long") + } + if strings.IndexByte(p, 0) >= 0 { + return nil, errBadPath("path contains a NUL") + } + var out vpath + for _, c := range strings.Split(p, "/") { + switch c { + case "", ".": + case "..": + if len(out) > 0 { + out = out[:len(out)-1] + } + default: + if len(c) > maxName { + return nil, errBadPath("file name too long") + } + out = append(out, c) + } + } + return out, nil +} + +// String is the virtual path: "/" for the root, else "/a/b". +func (v vpath) String() string { + return "/" + strings.Join(v, "/") +} + +// isRoot reports whether v is the home itself. +func (v vpath) isRoot() bool { return len(v) == 0 } + +// inSSH reports whether v is the .ssh entry of the home or anything under +// it. The name is compared as written (case-sensitive) on the cleaned path, +// so ".ssh/../.ssh/x", "//.ssh" and "a/../.ssh" are all caught. +func (v vpath) inSSH() bool { return len(v) > 0 && v[0] == sshDir } + +// parent is the directory that holds v (v must not be the root) and name +// the last component. +func (v vpath) parent() vpath { return v[:len(v)-1] } +func (v vpath) name() string { return v[len(v)-1] } diff --git a/internal/sftpd/quota.go b/internal/sftpd/quota.go new file mode 100644 index 00000000..b674d9d6 --- /dev/null +++ b/internal/sftpd/quota.go @@ -0,0 +1,329 @@ +package sftpd + +import ( + "errors" + "math" + "os" + "sync" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// remeasureAfter is how old the last measure of the home may be when a file +// is opened for writing before the whole home is measured again, so that a +// second session, or a file tacctl itself wrote, is noticed. +const remeasureAfter = 5 * time.Second + +// maxMeasureDepth bounds the walk of the home. A path is at most maxPath +// bytes, so a tree made of paths has at most maxPath/2 levels; a tree that +// was made deeper by moving subtrees under each other is not walked below +// this depth, and the walk then says it was not complete. +const maxMeasureDepth = maxPath + +// quota keeps the usage of the home: the sum of the sizes of its regular +// files, no link followed, each inode once, .ssh counted. It is measured +// when the session starts and when a file is opened for writing and the last +// measure is older than remeasureAfter, and is kept current in between from +// what the session does itself (writes, deletes, truncations and renames). +// The overshoot between two sessions that write at once is accepted. +// +// A walk that could not see all of the home (a directory it may not list or +// search, a failed open, no descriptor left, the depth cap) is incomplete, +// and then the home counts as full: the usage is taken as at least the +// limit, so that nothing that makes the home bigger is accepted, until a later +// walk is complete. Reading, deleting and writes that do not grow the home +// go on. +// +// One lock covers the usage and, for a write, the check and the write that +// follows it, so that two writes of the same session cannot both fit in the +// room of one. +type quota struct { + limit int64 + home *home + now func() time.Time + depth int // the depth the walk goes to + + mu sync.Mutex + used int64 + incomplete bool // the last walk did not see all of the home + measuredAt time.Time + held map[inode]map[*file]struct{} // the files this session has open, by inode +} + +// inode names a file on its device. +type inode [2]uint64 + +// newQuota measures the home; depth is how far the walk goes (0 is +// maxMeasureDepth). +func newQuota(h *home, limit int64, now func() time.Time, depth int) *quota { + if depth <= 0 { + depth = maxMeasureDepth + } + q := "a{limit: limit, home: h, now: now, depth: depth, held: map[inode]map[*file]struct{}{}} + q.remeasure() + return q +} + +// remeasure walks the home. The caller holds q.mu (or is the constructor). +func (q *quota) remeasure() { + used, complete := measure(q.home, q.depth) + // A file whose last name is gone while a handle of this session is open + // still holds its data: it is not in the walk, and it counts. + for _, set := range q.held { + for f := range set { + if fi, err := f.f.Stat(); err == nil && nlinkOf(fi) == 0 { + used += fi.Size() + } + break // the files of one inode have one size + } + } + q.used, q.incomplete = used, !complete + q.measuredAt = q.now() +} + +// nlinkOf is the link count of a stat result (1 when it cannot be told). +func nlinkOf(fi os.FileInfo) uint64 { + if st, ok := fi.Sys().(*syscall.Stat_t); ok { + return u64(st.Nlink) + } + return 1 +} + +// usedLocked is the usage the checks go by: the limit at least when the +// measure was incomplete. The caller holds q.mu. +func (q *quota) usedLocked() int64 { + if q.incomplete { + return max(q.used, q.limit) + } + return q.used +} + +// refresh measures the home again when the last measure is stale. It is +// called when a file is opened for writing. +func (q *quota) refresh() { + q.mu.Lock() + defer q.mu.Unlock() + if q.now().Sub(q.measuredAt) > remeasureAfter { + q.remeasure() + } +} + +// usage is the current usage. +func (q *quota) usage() int64 { + q.mu.Lock() + defer q.mu.Unlock() + return q.usedLocked() +} + +// truncating runs cut, which empties a file and returns the size the file +// had when it did, and takes that size off the usage. The size is read by cut +// under the lock, not before it: a write of the session holds the lock from its +// check to the end of its write, so none can fill the file between the size and +// the cut. +func (q *quota) truncating(cut func() (int64, error)) error { + q.mu.Lock() + defer q.mu.Unlock() + n, err := cut() + if err != nil { + return err + } + q.used = max(0, q.used-n) + return nil +} + +// resizing sets the size of the pinned regular file and corrects the usage by +// the difference. The size the file has is read under the lock, with the +// cut: a write of the session holds the lock from its check to the end of +// its write, so none can change the file between the size and the cut. A +// growth that would take the usage over the limit is refused, whole. A file +// that lost its last name is counted only while a handle of the session holds +// it, as everywhere else: one that no handle holds has been given back, and +// what is done to it is not accounted. A file that gained a second name since +// it was pinned is refused (the link rule). +func (q *quota) resizing(p *pinned, size int64) error { + q.mu.Lock() + defer q.mu.Unlock() + st, err := p.restat() + if err != nil { + return err + } + if st.Mode&unix.S_IFMT == unix.S_IFREG && st.Nlink > 1 { + return errLink() + } + counted := st.Nlink > 0 || len(q.held[inode{u64(st.Dev), u64(st.Ino)}]) > 0 + grow := size - st.Size + if counted && grow > 0 && grow > q.limit-q.usedLocked() { + return errQuota() + } + if err := p.truncate(size); err != nil { + return err + } + if counted { + q.used = max(0, q.used+grow) + } + return nil +} + +// hold notes that f is open. A file that lost its last name between its +// open and now (a remove that did not know of the handle) took its room off +// the usage: it is put back. +func (q *quota) hold(f *file) { + q.mu.Lock() + defer q.mu.Unlock() + set := q.held[f.key] + if set == nil { + set = map[*file]struct{}{} + q.held[f.key] = set + if fi, err := f.f.Stat(); err == nil && nlinkOf(fi) == 0 { + q.used += fi.Size() + } + } + set[f] = struct{}{} +} + +// unhold notes that f is about to be closed. The last handle on a file with +// no name left gives its room back: its data goes with the handle. +func (q *quota) unhold(f *file) { + q.mu.Lock() + defer q.mu.Unlock() + set := q.held[f.key] + delete(set, f) + if len(set) > 0 { + return + } + delete(q.held, f.key) + if fi, err := f.f.Stat(); err == nil && nlinkOf(fi) == 0 { + q.used = max(0, q.used-fi.Size()) + } +} + +// unlinking runs op, which removes the entry t names or replaces it, and +// takes the size of the file off the usage when this was its last name and no +// handle of the session is open on it (else the data stays until the last +// handle closes). The look at the entry, op and the accounting are one step +// under the lock, so a handle opened meanwhile is either seen here or finds +// the name gone in hold. +func (q *quota) unlinking(t *target, op func() error) error { + q.mu.Lock() + defer q.mu.Unlock() + var freed int64 + var st unix.Stat_t + if unix.Fstatat(t.dir, t.name, &st, unix.AT_SYMLINK_NOFOLLOW) == nil && + st.Mode&unix.S_IFMT == unix.S_IFREG && st.Nlink <= 1 && + len(q.held[inode{u64(st.Dev), u64(st.Ino)}]) == 0 { + freed = st.Size + } + if err := op(); err != nil { + return err + } + q.used = max(0, q.used-freed) + return nil +} + +// write does the write w with the check that it fits: a write that would take +// the measured usage over the limit is refused whole (see doc.go for what that +// does and does not guarantee). w writes at the offset (or at the end, for a file open with +// O_APPEND) and returns the count. +func (q *quota) write(f *os.File, n int, off int64, appending bool, w func() (int, error)) (int, error) { + q.mu.Lock() + defer q.mu.Unlock() + fi, err := f.Stat() + if err != nil { + return 0, err + } + before := fi.Size() + if appending { + off = before + } + if off < 0 { + return 0, &os.PathError{Op: "write", Path: f.Name(), Err: unix.EINVAL} + } + var grow int64 + switch { + case off > math.MaxInt64-int64(n): + return 0, errQuota() // off+n does not even fit in a size + case off+int64(n) > before: + grow = off + int64(n) - before + } + if grow > 0 && grow > q.limit-q.usedLocked() { + return 0, errQuota() + } + wn, werr := w() + if grow > 0 { + if fi, err := f.Stat(); err == nil && fi.Size() > before { + q.used += fi.Size() - before + } + } + return wn, werr +} + +// measure sums the sizes of the regular files below the home and says +// whether it saw all of them: false when a directory could not be listed, +// searched or opened (a mode the client set, a descriptor limit), or lies +// deeper than depth, and then the sum is a lower bound only. It lists the +// home through a descriptor of its own: a directory read moves the offset +// of the open file, and the home's descriptor is shared. +func measure(h *home, depth int) (int64, bool) { + fd, err := unix.Openat(h.fd, ".", dirFlags, 0) + if err != nil { + return 0, false + } + w := &walk{depth: depth, seen: map[[2]uint64]bool{}, complete: true} + return w.dir(fd, 0), w.complete +} + +// walk is one measure: the inodes seen, and whether anything escaped it. +type walk struct { + depth int + seen map[[2]uint64]bool + complete bool +} + +// dir sums the directory fd and below, and closes fd. An entry that is gone +// since the listing (ENOENT) is not a failure; any other error is. +func (w *walk) dir(fd, depth int) int64 { + f := os.NewFile(uintptr(fd), "") + defer func() { _ = f.Close() }() + names, err := f.Readdirnames(-1) + if err != nil { + w.complete = false + } + var total int64 + for _, n := range names { + var st unix.Stat_t + if err := unix.Fstatat(fd, n, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil { + if !errors.Is(err, unix.ENOENT) { + w.complete = false + } + continue + } + switch st.Mode & unix.S_IFMT { + case unix.S_IFREG: + key := [2]uint64{u64(st.Dev), u64(st.Ino)} + if !w.seen[key] { + w.seen[key] = true + total += st.Size + } + case unix.S_IFDIR: + if depth >= w.depth { + w.complete = false + continue + } + sub, err := unix.Openat(fd, n, dirFlags, 0) + if err != nil { + if !errors.Is(err, unix.ENOENT) { + w.complete = false + } + continue + } + total += w.dir(sub, depth+1) + } + } + return total +} + +// u64 widens the integer types the stat structures use, which differ by +// architecture. +func u64[T ~int32 | ~int64 | ~uint32 | ~uint64](v T) uint64 { return uint64(v) } diff --git a/internal/sftpd/quota_test.go b/internal/sftpd/quota_test.go new file mode 100644 index 00000000..bb605936 --- /dev/null +++ b/internal/sftpd/quota_test.go @@ -0,0 +1,739 @@ +package sftpd + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/pkg/sftp" +) + +// 4. The quota. + +func quotaEnv(t *testing.T, limit int64) *env { + return newEnv(t, func(c *Config) { c.Quota = limit }) +} + +func bytesOf(n int) string { return strings.Repeat("q", n) } + +// diskUsage is the sum of the sizes of the regular files of the home. +func diskUsage(t *testing.T, e *env) int64 { + t.Helper() + var sum int64 + err := filepath.WalkDir(e.home, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.Type().IsRegular() { + fi, err := d.Info() + if err != nil { + return err + } + sum += fi.Size() + } + return nil + }) + if err != nil { + t.Fatal(err) + } + return sum +} + +func wantQuotaRefusal(t *testing.T, what string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s succeeded, want disk quota exceeded", what) + return + } + if !strings.Contains(err.Error(), "disk quota exceeded") { + t.Errorf("%s: %v, want a status message disk quota exceeded", what, err) + } + if code(err) != fxFailure { + t.Errorf("%s: status %d, want failure (%d)", what, code(err), fxFailure) + } +} + +func TestQuotaExactFitAndOneByteOver(t *testing.T) { + e := quotaEnv(t, 100) + e.put("a", bytesOf(100)) // exactly the quota + if got := diskUsage(t, e); got != 100 { + t.Fatalf("disk usage %d, want 100", got) + } + wantQuotaRefusal(t, "one byte more in a new file", putFile(e.client, "b", "x")) + if got := diskUsage(t, e); got != 100 { + t.Errorf("disk usage %d after the refusal, want 100", got) + } + // An empty file costs nothing. + e.put("empty", "") + // Appending one byte to the full file is over too. + f, err := e.client.OpenFile("a", os.O_WRONLY|os.O_APPEND) + if err != nil { + t.Fatal(err) + } + _, err = f.Write([]byte("x")) + wantQuotaRefusal(t, "append of one byte", err) + _ = f.Close() + if e.read("a") != bytesOf(100) { + t.Error("the file changed") + } +} + +func TestQuotaOneByteOverInOnePacketWritesNothing(t *testing.T) { + e := quotaEnv(t, 100) + wantQuotaRefusal(t, "101 bytes", putFile(e.client, "a", bytesOf(101))) + if got := e.read("a"); got != "" { + t.Errorf("%d bytes were written past the limit, want none", len(got)) + } + if got := refusals(e.rec.all()); len(got) != 1 || got[0] != "quota" { + t.Errorf("refusals = %v, want one quota", got) + } +} + +func TestQuotaLargeUploadStopsAtTheLimit(t *testing.T) { + const limit = 100 << 10 + e := quotaEnv(t, limit) + err := putFile(e.client, "big", bytesOf(500<<10)) // several packets + wantQuotaRefusal(t, "500 KiB into 100 KiB", err) + if got := diskUsage(t, e); got > limit { + t.Errorf("disk usage %d is over the quota %d", got, limit) + } + // One refusal event for the handle, not one per packet. + n := 0 + for _, r := range refusals(e.rec.all()) { + if r == "quota" { + n++ + } + } + if n != 1 { + t.Errorf("%d quota refusals, want 1 per handle", n) + } +} + +func TestQuotaOverwriteShrinking(t *testing.T) { + e := quotaEnv(t, 100) + e.put("a", bytesOf(100)) + e.put("a", bytesOf(10)) // truncated by the open, then 10 bytes + e.put("b", bytesOf(90)) + wantQuotaRefusal(t, "one byte more", putFile(e.client, "c", "x")) + // Overwriting a file with a bigger one frees its old size first. + e.put("b", bytesOf(90)) + e.put("a", bytesOf(10)) + if got := diskUsage(t, e); got != 100 { + t.Errorf("disk usage %d, want 100", got) + } + // Overwriting in place (no growth) is allowed at the limit. + h, err := e.client.OpenFile("a", os.O_WRONLY) + if err != nil { + t.Fatal(err) + } + if _, err := h.WriteAt([]byte("ZZZ"), 2); err != nil { + t.Errorf("overwrite inside the file at the limit: %v", err) + } + _, err = h.WriteAt([]byte("Z"), 10) + wantQuotaRefusal(t, "write one byte past the end at the limit", err) + _ = h.Close() + if e.read("a") != "qqZZZqqqqq" { + t.Errorf("a = %q", e.read("a")) + } +} + +func TestQuotaDeleteThenUpload(t *testing.T) { + e := quotaEnv(t, 100) + e.put("a", bytesOf(60)) + e.put("b", bytesOf(40)) + wantQuotaRefusal(t, "upload when full", putFile(e.client, "c", "x")) + if err := e.client.Remove("a"); err != nil { + t.Fatal(err) + } + e.put("c", bytesOf(60)) + wantQuotaRefusal(t, "upload when full again", putFile(e.client, "d", "x")) + // A directory with files: remove the files, then the directory. + if err := e.client.Remove("c"); err != nil { + t.Fatal(err) + } + if err := e.client.Mkdir("dir"); err != nil { + t.Fatal(err) + } + e.put("dir/f", bytesOf(60)) + if err := e.client.Remove("dir/f"); err != nil { + t.Fatal(err) + } + if err := e.client.RemoveDirectory("dir"); err != nil { + t.Fatal(err) + } + e.put("c", bytesOf(60)) +} + +func TestQuotaRenameThatReplacesFreesRoom(t *testing.T) { + e := quotaEnv(t, 100) + e.put("a", bytesOf(60)) + e.put("b", bytesOf(40)) + if err := e.client.PosixRename("b", "a"); err != nil { // a (60) is gone + t.Fatal(err) + } + e.put("c", bytesOf(60)) + wantQuotaRefusal(t, "upload when full", putFile(e.client, "d", "x")) + // A rename that only moves, and one onto itself, change nothing. + if err := e.client.Rename("c", "c2"); err != nil { + t.Fatal(err) + } + if err := e.client.PosixRename("c2", "c2"); err != nil { + t.Fatal(err) + } + wantQuotaRefusal(t, "upload when still full", putFile(e.client, "d", "x")) + // A refused plain rename onto an existing file frees nothing. + if err := e.client.Rename("c2", "a"); err == nil { + t.Fatal("rename onto an existing file succeeded") + } + wantQuotaRefusal(t, "upload after a refused rename", putFile(e.client, "d", "x")) +} + +func TestQuotaDeleteAndDownloadAreNeverLimited(t *testing.T) { + e := newEnv(t, nil) + e.write("big", bytesOf(500)) + e.write("sub/f", bytesOf(500)) + if err := e.stop(); err != nil { + t.Fatal(err) + } + e.start(Config{Home: e.home, Quota: 100, Audit: e.rec.add}) // already over + wantQuotaRefusal(t, "upload when over", putFile(e.client, "new", "x")) + if got, err := e.get("big"); err != nil || len(got) != 500 { + t.Errorf("download when over: %d bytes, %v", len(got), err) + } + if err := e.client.Chmod("big", 0o600); err != nil { + t.Errorf("chmod when over: %v", err) + } + if err := e.client.Rename("big", "big2"); err != nil { + t.Errorf("rename when over: %v", err) + } + if err := e.client.Remove("big2"); err != nil { + t.Errorf("delete when over: %v", err) + } + wantQuotaRefusal(t, "upload still over", putFile(e.client, "new", bytesOf(100))) + if err := e.client.Remove("sub/f"); err != nil { + t.Errorf("delete when over: %v", err) + } + e.put("new", bytesOf(100)) +} + +func TestQuotaMeasureAtStart(t *testing.T) { + e := newEnv(t, nil) + e.write("a", bytesOf(30)) + e.write("d/b", bytesOf(20)) + e.write(".ssh/authorized_keys", bytesOf(10)) // counts + // A hard link to a file counts once. + if err := os.Link(filepath.Join(e.home, "a"), filepath.Join(e.home, "a-link")); err != nil { + t.Fatal(err) + } + // A symbolic link to a file counts as nothing, whatever it points at. + big := filepath.Join(e.root, "big-outside") + if err := os.WriteFile(big, []byte(bytesOf(1000)), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Symlink(big, filepath.Join(e.home, "tobig")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(e.root, filepath.Join(e.home, "toroot")); err != nil { + t.Fatal(err) + } + if err := e.stop(); err != nil { + t.Fatal(err) + } + h := mustHome(t, e.home) + if got, ok := measure(h, maxMeasureDepth); got != 60 || !ok { + t.Errorf("measure = %d, %v, want 60, true (30 + 20 + 10, the hard link once, no link followed)", got, ok) + } + // And the same through a session: 60 used of 100 leaves 40. + e.start(Config{Home: e.home, Quota: 100}) + e.put("n", bytesOf(40)) + wantQuotaRefusal(t, "one byte over what was measured", putFile(e.client, "m", "x")) +} + +func TestQuotaRemeasureWhenStale(t *testing.T) { + clk := newClock() + e := newEnvSeams(t, func(c *Config) { c.Quota = 100 }, seams{now: clk.now}) + // Another session (or tacctl) fills the home after the start. + e.write("other", bytesOf(100)) + clk.advance(5 * time.Second) // 5 s is not older than 5 s + e.put("a", "x") // the stale measure says the home is empty + if e.read("a") != "x" { + t.Fatal("upload within the stale measure failed") + } + clk.advance(time.Second) // 6 s: the open for writing measures again + wantQuotaRefusal(t, "upload after the home was measured again", putFile(e.client, "b", "x")) + // The measure is now fresh: freeing room is seen at once through the + // session's own bookkeeping, and an outside change not until it is stale. + if err := os.Remove(filepath.Join(e.home, "other")); err != nil { + t.Fatal(err) + } + wantQuotaRefusal(t, "upload before the next measure", putFile(e.client, "b", "x")) + clk.advance(6 * time.Second) + e.put("b", bytesOf(99)) +} + +func TestQuotaMeasureIsOnlyAtOpenForWriting(t *testing.T) { + clk := newClock() + e := newEnvSeams(t, func(c *Config) { c.Quota = 100 }, seams{now: clk.now}) + h, err := e.client.OpenFile("a", os.O_WRONLY|os.O_CREATE) + if err != nil { + t.Fatal(err) + } + e.write("other", bytesOf(100)) + clk.advance(time.Hour) // no open for writing: no measure + if _, err := h.WriteAt([]byte("x"), 0); err != nil { + t.Errorf("write on an open handle after a long time: %v", err) + } + _ = h.Close() + // Reading and listing never measure. + if _, err := e.get("other"); err != nil { + t.Fatal(err) + } + if _, err := e.client.ReadDir("/"); err != nil { + t.Fatal(err) + } +} + +func TestQuotaZeroMeansNoCheckAndNoMeasure(t *testing.T) { + for _, limit := range []int64{0, -1} { + h := mustHome(t, t.TempDir()) + s := newServer(h, Config{Quota: limit}, seams{now: time.Now}) + if s.quota != nil { + t.Errorf("Quota %d: a quota was set up", limit) + } + } + e := newEnv(t, nil) + e.put("big", bytesOf(300<<10)) + if got := diskUsage(t, e); got != 300<<10 { + t.Errorf("disk usage %d", got) + } +} + +func TestQuotaSparseWriteIsRefused(t *testing.T) { + e := quotaEnv(t, 100) + h, err := e.client.OpenFile("sparse", os.O_WRONLY|os.O_CREATE) + if err != nil { + t.Fatal(err) + } + _, err = h.WriteAt([]byte("x"), 1<<40) + wantQuotaRefusal(t, "a write at 1 TiB", err) + _, err = h.WriteAt([]byte("x"), 1<<62) + wantQuotaRefusal(t, "a write at 4 EiB", err) + _, err = h.WriteAt([]byte("x"), 99) + if err != nil { + t.Errorf("a write that ends at the limit: %v", err) + } + _ = h.Close() +} + +func TestQuotaHardLinkedFileIsFreedWithItsLastName(t *testing.T) { + e := newEnv(t, nil) + e.write("a", bytesOf(50)) + if err := os.Link(filepath.Join(e.home, "a"), filepath.Join(e.home, "b")); err != nil { + t.Fatal(err) + } + if err := e.stop(); err != nil { + t.Fatal(err) + } + e.start(Config{Home: e.home, Quota: 100}) + if err := e.client.Remove("b"); err != nil { // a still has the inode + t.Fatal(err) + } + wantQuotaRefusal(t, "51 bytes after removing one name of 50", putFile(e.client, "c", bytesOf(51))) + if err := e.client.Remove("a"); err != nil { // the last name + t.Fatal(err) + } + e.put("c", bytesOf(100)) +} + +func TestQuotaConcurrentWritersStayUnderTheLimit(t *testing.T) { + const limit = 100 << 10 + e := quotaEnv(t, limit) + var wg sync.WaitGroup + for w := 0; w < 8; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 30; i++ { + _ = putFile(e.client, fmt.Sprintf("w%d-%d", w, i), bytesOf(1<<10)) + } + }() + } + wg.Wait() + got := diskUsage(t, e) + if got > limit { + t.Errorf("disk usage %d is over the quota %d", got, limit) + } + if got < limit-(8<<10) { + t.Errorf("disk usage %d is far under the quota %d: the quota refused what fits", got, limit) + } +} + +func TestStatVFSReportsTheQuota(t *testing.T) { + e := quotaEnv(t, 10<<20) + e.put("a", bytesOf(1<<20)) + v, err := e.client.StatVFS("/") + if err != nil { + t.Fatal(err) + } + if v.TotalSpace() != 10<<20 { + t.Errorf("total = %d, want %d", v.TotalSpace(), 10<<20) + } + if want := uint64(9 << 20); v.FreeSpace() != want { + t.Errorf("free = %d, want %d", v.FreeSpace(), want) + } + if v.Bavail != v.Bfree { + t.Errorf("available %d differs from free %d", v.Bavail, v.Bfree) + } + if _, err := e.client.StatVFS(".ssh"); code(err) != fxPermissionDenied { + t.Errorf("statvfs of .ssh: %v", err) + } + // Over the quota: nothing free, never negative. + if err := e.stop(); err != nil { + t.Fatal(err) + } + e.start(Config{Home: e.home, Quota: 1 << 19}) + v, err = e.client.StatVFS("/") + if err != nil || v.FreeSpace() != 0 || v.TotalSpace() != 1<<19 { + t.Errorf("over quota: %+v, %v", v, err) + } +} + +func TestStatVFSWithoutQuotaIsTheFileSystem(t *testing.T) { + e := newEnv(t, nil) + v, err := e.client.StatVFS("/") + if err != nil { + t.Fatal(err) + } + if v.Blocks == 0 || v.Frsize == 0 { + t.Errorf("statvfs = %+v", v) + } +} + +// A walk that could not see the whole home must not make the usage smaller: +// the quota then counts the home as full until a later walk is complete. + +// unmeasurable are the ways a directory can hide its content from the walk: +// no read (cannot be listed), no search (the entries cannot be stat'ed), and +// neither. +var unmeasurable = []os.FileMode{0o100, 0o400, 0o000} + +func TestQuotaUnmeasurableDirectoryCountsAsFull(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads every directory") + } + for _, mode := range unmeasurable { + for _, nested := range []bool{false, true} { + t.Run(fmt.Sprintf("%04o/nested=%v", mode, nested), func(t *testing.T) { + clk := newClock() + e := newEnvSeams(t, func(c *Config) { c.Quota = 100 }, seams{now: clk.now}) + dir, file := "hide", "hide/F" + if nested { + dir, file = "top/hide", "top/hide/F" + } + e.write(file, bytesOf(100)) + e.write("small", "x") + if err := os.Chmod(filepath.Join(e.home, dir), mode); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(filepath.Join(e.home, dir), 0o755) }) + clk.advance(6 * time.Second) // the open for writing measures again + wantQuotaRefusal(t, "growing upload while a directory cannot be measured", putFile(e.client, "g", "x")) + // What does not make the home bigger keeps working. + if got, err := e.get("small"); err != nil || got != "x" { + t.Errorf("download while incomplete: %q, %v", got, err) + } + e.put("empty", "") + // A write in place that stays within the file's size (an upload + // that truncates first looks like growth, and is refused). + h, err := e.client.OpenFile("small", os.O_WRONLY) + if err != nil { + t.Fatal(err) + } + if _, err := h.Write([]byte("y")); err != nil { + t.Errorf("write in place while incomplete: %v", err) + } + _ = h.Close() + if e.read("small") != "y" { + t.Error("the write in place did not happen") + } + if err := e.client.Remove("empty"); err != nil { + t.Errorf("delete while incomplete: %v", err) + } + wantQuotaRefusal(t, "growing upload after a delete", putFile(e.client, "g", "x")) + // The directory readable again and a later walk: the real usage + // (100, the limit) decides, and then the file removed gives room. + if err := os.Chmod(filepath.Join(e.home, dir), 0o755); err != nil { + t.Fatal(err) + } + clk.advance(6 * time.Second) + wantQuotaRefusal(t, "upload over the real usage", putFile(e.client, "g", "x")) + if err := os.Remove(filepath.Join(e.home, file)); err != nil { + t.Fatal(err) + } + clk.advance(6 * time.Second) + e.put("g", bytesOf(98)) // 98 + the 1 of small + }) + } + } +} + +func TestQuotaDepthCapCountsAsFull(t *testing.T) { + clk := newClock() + e := newEnvSeams(t, func(c *Config) { c.Quota = 100 }, seams{now: clk.now, measureDepth: 3}) + e.write("a/b/c/d/F", bytesOf(10)) // four levels below the home + clk.advance(6 * time.Second) + // The 10 bytes are far from the 100 of the quota, but the walk did not + // see them: the home counts as full. + wantQuotaRefusal(t, "upload with files below the walk's depth", putFile(e.client, "g", "x")) + // Within the depth the walk is complete and counts what is there. + e2 := newEnvSeams(t, func(c *Config) { c.Quota = 100 }, seams{now: clk.now, measureDepth: 3}) + e2.write("a/b/F", bytesOf(60)) + clk.advance(6 * time.Second) + e2.put("g", bytesOf(40)) + wantQuotaRefusal(t, "one byte over", putFile(e2.client, "h", "x")) +} + +func TestMeasureReportsWhetherItWasComplete(t *testing.T) { + e := newEnv(t, nil) + e.write("a/b/F", bytesOf(7)) + if err := e.stop(); err != nil { + t.Fatal(err) + } + h := mustHome(t, e.home) + if n, ok := measure(h, 8); n != 7 || !ok { + t.Errorf("measure = %d, %v, want 7, true", n, ok) + } + if _, ok := measure(h, 1); ok { + t.Error("a walk cut at depth 1 says it was complete") + } +} + +func TestQuotaStatVFSOfAnIncompleteMeasureIsFull(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads every directory") + } + e := quotaEnv(t, 8192) + e.write("hide/F", "x") + if err := os.Chmod(filepath.Join(e.home, "hide"), 0o100); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(filepath.Join(e.home, "hide"), 0o755) }) + if err := e.stop(); err != nil { + t.Fatal(err) + } + e.start(Config{Home: e.home, Quota: 8192}) + sv, err := e.client.StatVFS("/") + if err != nil { + t.Fatal(err) + } + if sv.Bfree != 0 { + t.Errorf("free blocks = %d, want 0 while the home cannot be measured", sv.Bfree) + } +} + +// A client may not make its own tree unmeasurable and unlistable. +func TestSetstatRefusesClearingTheOwnersReadOrSearchOfADirectory(t *testing.T) { + e := quotaEnv(t, 100) + if err := e.client.Mkdir("d"); err != nil { + t.Fatal(err) + } + for _, mode := range []os.FileMode{0o100, 0o400, 0o000, 0o277, 0o077} { + err := e.client.Chmod("d", mode) + if code(err) != fxOpUnsupported { + t.Errorf("chmod %04o of a directory: %v, want unsupported", mode, err) + } + if fi, _ := os.Stat(filepath.Join(e.home, "d")); fi.Mode().Perm() != 0o755 { + t.Errorf("mode after the refused chmod %04o = %v", mode, fi.Mode()) + } + } + if got := refusals(e.rec.all()); len(got) != 5 || got[0] != "unsupported" { + t.Errorf("refusals = %v, want 5 unsupported", got) + } + // What keeps the owner's r and x is fine, and so is any mode of a file. + if err := e.client.Chmod("d", 0o500); err != nil { + t.Errorf("chmod 0500 of a directory: %v", err) + } + if err := e.client.Chmod("d", 0o700); err != nil { + t.Errorf("chmod 0700 of a directory: %v", err) + } + e.write("f", "x") + if err := e.client.Chmod("f", 0o000); err != nil { + t.Errorf("chmod 0000 of a file: %v", err) + } + // Times only, on a directory. + if err := e.client.Chtimes("d", time.Unix(1e9, 0), time.Unix(1e9, 0)); err != nil { + t.Errorf("chtimes of a directory: %v", err) + } +} + +// A file that was removed (or replaced) while a handle on it is open keeps +// its data, so it keeps its room until the last handle on it closes. + +func TestQuotaRemovedFileWithAnOpenHandleKeepsItsRoom(t *testing.T) { + clk := newClock() + e := newEnvSeams(t, func(c *Config) { c.Quota = 100 }, seams{now: clk.now}) + var held []interface{ Close() error } + for i := 0; i < 5; i++ { + name := fmt.Sprintf("f%d", i) + h, err := e.client.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC) + if err != nil { + t.Fatal(err) + } + held = append(held, h) + if _, err := h.Write([]byte(bytesOf(100))); err != nil { + if i == 0 { + t.Fatalf("the first write: %v", err) + } + wantQuotaRefusal(t, fmt.Sprintf("write %d while the removed files are held", i), err) + break + } + if i > 0 { + t.Errorf("write %d of 100 bytes succeeded under a quota of 100 with %d removed files held", i, i) + } + if err := e.client.Remove(name); err != nil { + t.Fatal(err) + } + clk.advance(6 * time.Second) // and the next open for writing measures the home again + } + // The data the handles hold is on the disk, outside the home's names. + for _, h := range held { + _ = h.Close() + } + // The last close gives the room back. + e.put("fresh", bytesOf(100)) +} + +func TestQuotaRoomIsGivenBackWithTheLastHandle(t *testing.T) { + e := quotaEnv(t, 100) + h1, err := e.client.OpenFile("a", os.O_RDWR|os.O_CREATE|os.O_TRUNC) + if err != nil { + t.Fatal(err) + } + if _, err := h1.Write([]byte(bytesOf(100))); err != nil { + t.Fatal(err) + } + h2, err := e.client.OpenFile("a", os.O_RDWR) + if err != nil { + t.Fatal(err) + } + if err := e.client.Remove("a"); err != nil { + t.Fatal(err) + } + wantQuotaRefusal(t, "upload with two handles on a removed file", putFile(e.client, "b", "x")) + _ = h1.Close() + wantQuotaRefusal(t, "upload with one handle left", putFile(e.client, "b", "x")) + _ = h2.Close() + e.put("b", bytesOf(100)) +} + +func TestQuotaFileReplacedByRenameWhileOpenKeepsItsRoom(t *testing.T) { + e := quotaEnv(t, 150) + h, err := e.client.OpenFile("a", os.O_RDWR|os.O_CREATE|os.O_TRUNC) + if err != nil { + t.Fatal(err) + } + if _, err := h.Write([]byte(bytesOf(100))); err != nil { + t.Fatal(err) + } + e.put("b", bytesOf(10)) + if err := e.client.PosixRename("b", "a"); err != nil { + t.Fatal(err) + } + // 10 bytes under the name a, and the 100 the handle holds. + wantQuotaRefusal(t, "41 bytes with 110 in use", putFile(e.client, "c", bytesOf(41))) + e.put("c", bytesOf(40)) + _ = h.Close() + if err := e.client.Remove("c"); err != nil { + t.Fatal(err) + } + e.put("d", bytesOf(140)) +} + +// A held file that is written after its name is gone is counted as it grows. +func TestQuotaHeldRemovedFileStillGrowsTheUsage(t *testing.T) { + e := quotaEnv(t, 100) + h, err := e.client.OpenFile("a", os.O_RDWR|os.O_CREATE|os.O_TRUNC) + if err != nil { + t.Fatal(err) + } + if err := e.client.Remove("a"); err != nil { + t.Fatal(err) + } + if _, err := h.Write([]byte(bytesOf(60))); err != nil { + t.Fatal(err) + } + wantQuotaRefusal(t, "41 bytes beside 60 held", putFile(e.client, "b", bytesOf(41))) + _, err = h.Write([]byte(bytesOf(41))) + wantQuotaRefusal(t, "growing the removed file past the quota", err) + _ = h.Close() +} + +// A truncating open reads the size, cuts the file and lowers the usage as one +// step under the quota's lock. A write on another handle of the same file +// that is running when the cut happens must not leave the usage below the +// disk: the open is held before its cut, a write is started and is in its +// write when the cut is let go. +// +// The write waits for the file to be cut, up to a deadline on a real timer: with +// the lock held by the write the cut cannot happen until the write is over, so +// the wait ends by the deadline; without the lock the cut comes at once. +func TestQuotaTruncatingOpenDoesNotLoseAConcurrentWrite(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "f"), []byte(bytesOf(100)), 0o644); err != nil { + t.Fatal(err) + } + atCut, letCut, inWrite := make(chan struct{}), make(chan struct{}), make(chan struct{}) + s := newServer(mustHome(t, dir), Config{Quota: 1000}, seams{now: time.Now, beforeTruncate: func() { + close(atCut) + <-letCut + }}) + // The writer's handle: no truncation, so no hook. + b, err := s.openFile(&sftp.Request{Method: "Put", Filepath: "/f", Flags: 0x2}, true) // SSH_FXF_WRITE + if err != nil { + t.Fatal(err) + } + defer func() { _ = b.Close() }() + opened := make(chan error, 1) + go func() { + a, err := s.openFile(&sftp.Request{Method: "Put", Filepath: "/f", Flags: 0x2 | 0x10}, true) // WRITE | TRUNC + if err == nil { + _ = a.Close() + } + opened <- err + }() + <-atCut + wrote := make(chan error, 1) + go func() { + w := func() (int, error) { + close(inWrite) + for deadline := time.Now().Add(300 * time.Millisecond); time.Now().Before(deadline); time.Sleep(time.Millisecond) { + if fi, err := b.f.Stat(); err == nil && fi.Size() == 0 { + break + } + } + return b.f.WriteAt([]byte(bytesOf(100)), 0) + } + _, err := s.quota.write(b.f, 100, 0, false, w) + wrote <- err + }() + <-inWrite + close(letCut) + if err := <-wrote; err != nil { + t.Fatalf("write: %v", err) + } + if err := <-opened; err != nil { + t.Fatalf("truncating open: %v", err) + } + fi, err := os.Stat(filepath.Join(dir, "f")) + if err != nil { + t.Fatal(err) + } + if got := s.quota.usage(); got != fi.Size() { + t.Errorf("usage %d, the file on the disk has %d", got, fi.Size()) + } +} diff --git a/internal/sftpd/rate.go b/internal/sftpd/rate.go new file mode 100644 index 00000000..de9e1775 --- /dev/null +++ b/internal/sftpd/rate.go @@ -0,0 +1,104 @@ +package sftpd + +import ( + "io" + "sync" + "time" +) + +// bucket is a token bucket for the bytes a session moves, reads and writes +// together: it holds up to one second of bytes (the burst), refills at rate +// bytes per second, and a caller that takes more than is there goes into +// debt and sleeps for the time the debt takes to refill. Callers that +// arrive together therefore wait one behind the other, and over time the +// session moves rate bytes per second. +// +// A nil *bucket takes nothing, costs nothing and never sleeps: it is what a +// rate of 0 gives. +type bucket struct { + rate float64 // bytes per second + burst float64 + now func() time.Time + sleep func(time.Duration) + + mu sync.Mutex + tokens float64 + last time.Time +} + +// newBucket is a full bucket, or nil when rate is 0 or less. +func newBucket(rate int64, now func() time.Time, sleep func(time.Duration)) *bucket { + if rate <= 0 { + return nil + } + return &bucket{ + rate: float64(rate), + burst: float64(rate), + now: now, + sleep: sleep, + tokens: float64(rate), + last: now(), + } +} + +// take accounts for n bytes and sleeps, outside the lock, for as long as +// the bucket is in debt. +func (b *bucket) take(n int64) { + if b == nil || n <= 0 { + return + } + b.mu.Lock() + t := b.now() + if el := t.Sub(b.last).Seconds(); el > 0 { // a clock that steps back refills nothing + b.tokens = min(b.burst, b.tokens+el*b.rate) + b.last = t + } + b.tokens -= float64(n) + var wait time.Duration + if b.tokens < 0 { + wait = time.Duration(-b.tokens / b.rate * float64(time.Second)) + } + b.mu.Unlock() + if wait > 0 { + b.sleep(wait) + } +} + +// sleepUntil sleeps for d, or until done is closed. +func sleepUntil(done <-chan struct{}, d time.Duration) { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + case <-done: + } +} + +// endNotifier closes done the first time the stream ends or fails to read, +// so that a request that is sleeping for the rate limit does not hold the +// session open after the client has gone: the library waits for its workers +// before Serve returns. +type endNotifier struct { + io.ReadWriteCloser + once sync.Once + done chan struct{} +} + +func newEndNotifier(rw io.ReadWriteCloser) *endNotifier { + return &endNotifier{ReadWriteCloser: rw, done: make(chan struct{})} +} + +func (e *endNotifier) end() { e.once.Do(func() { close(e.done) }) } + +func (e *endNotifier) Read(p []byte) (int, error) { + n, err := e.ReadWriteCloser.Read(p) + if err != nil { + e.end() + } + return n, err +} + +func (e *endNotifier) Close() error { + e.end() + return e.ReadWriteCloser.Close() +} diff --git a/internal/sftpd/rate_test.go b/internal/sftpd/rate_test.go new file mode 100644 index 00000000..10d2496d --- /dev/null +++ b/internal/sftpd/rate_test.go @@ -0,0 +1,264 @@ +package sftpd + +import ( + "io" + "net" + "sync" + "testing" + "time" +) + +var _ io.ReadWriteCloser = (*endNotifier)(nil) + +// 5. The rate. No test here sleeps for the rate: the clock and the sleep +// are fakes. + +// sleeps records the sleeps asked of the bucket and does not sleep. +type sleeps struct { + mu sync.Mutex + d []time.Duration +} + +func (s *sleeps) sleep(d time.Duration) { + s.mu.Lock() + defer s.mu.Unlock() + s.d = append(s.d, d) +} + +func (s *sleeps) count() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.d) +} + +func (s *sleeps) longest() time.Duration { + s.mu.Lock() + defer s.mu.Unlock() + var m time.Duration + for _, d := range s.d { + m = max(m, d) + } + return m +} + +func TestBucketBurstThenRate(t *testing.T) { + clk, sl := newClock(), &sleeps{} + b := newBucket(1000, clk.now, sl.sleep) + b.take(1000) // the burst: one second of bytes + if sl.count() != 0 { + t.Fatalf("the burst slept: %v", sl.d) + } + b.take(500) // 500 bytes in debt: half a second + if sl.count() != 1 || sl.d[0] != 500*time.Millisecond { + t.Fatalf("sleeps = %v, want [500ms]", sl.d) + } + b.take(1000) // 1500 bytes in debt + if len(sl.d) != 2 || sl.d[1] != 1500*time.Millisecond { + t.Fatalf("sleeps = %v, want [500ms 1.5s]", sl.d) + } + // Time passes (the sleeps are not real, the clock is moved): the debt + // is paid after 1.5 s, and an idle second fills the bucket again. + clk.advance(1500 * time.Millisecond) + b.take(0) + clk.advance(10 * time.Second) // idle: the bucket holds one second at most + before := sl.count() + b.take(1000) + if sl.count() != before { + t.Errorf("a full bucket slept after an idle time: %v", sl.d) + } + b.take(1) + if sl.count() != before+1 || sl.d[before] != time.Millisecond { + t.Errorf("one byte over the burst: %v, want 1ms", sl.d[before:]) + } +} + +func TestBucketRefillsWithTime(t *testing.T) { + clk, sl := newClock(), &sleeps{} + b := newBucket(1000, clk.now, sl.sleep) + b.take(1000) + clk.advance(250 * time.Millisecond) // 250 bytes back + b.take(250) + if sl.count() != 0 { + t.Errorf("took what had refilled and slept: %v", sl.d) + } + clk.advance(250 * time.Millisecond) + b.take(300) // 250 there, 50 short: 50 ms + if sl.count() != 1 || sl.d[0] != 50*time.Millisecond { + t.Errorf("sleeps = %v, want [50ms]", sl.d) + } +} + +func TestBucketBiggerThanTheBurst(t *testing.T) { + clk, sl := newClock(), &sleeps{} + b := newBucket(1000, clk.now, sl.sleep) + b.take(5000) // 4000 over the burst: 4 s + if sl.count() != 1 || sl.d[0] != 4*time.Second { + t.Errorf("sleeps = %v, want [4s]", sl.d) + } +} + +func TestBucketClockGoingBack(t *testing.T) { + clk, sl := newClock(), &sleeps{} + b := newBucket(1000, clk.now, sl.sleep) + b.take(1000) + clk.advance(-time.Hour) + b.take(1) // no refill from a step back, no panic + if sl.count() != 1 || sl.d[0] != time.Millisecond { + t.Errorf("sleeps = %v, want [1ms]", sl.d) + } + clk.advance(time.Hour + time.Second) // forward again: one second after the last refill + b.take(999) // 1000 back, less the 1 owed + if sl.count() != 1 { + t.Errorf("sleeps = %v", sl.d) + } +} + +func TestBucketRateZeroCostsNothing(t *testing.T) { + for _, r := range []int64{0, -5} { + calls := 0 + b := newBucket(r, func() time.Time { calls++; return time.Time{} }, func(time.Duration) { calls++ }) + if b != nil { + t.Errorf("rate %d gave a bucket", r) + } + b.take(1 << 30) // on nil: a no-op + if calls != 0 { + t.Errorf("rate %d used the clock or slept", r) + } + } +} + +func TestBucketConcurrentTakers(t *testing.T) { + clk, sl := newClock(), &sleeps{} + b := newBucket(1000, clk.now, sl.sleep) + var wg sync.WaitGroup + for i := 0; i < 50; i++ { + wg.Add(1) + go func() { + defer wg.Done() + b.take(100) + }() + } + wg.Wait() + // 5000 bytes from a bucket of 1000 on a frozen clock: the last taker + // waits for the 4000 that are over. + if got := sl.longest(); got != 4*time.Second { + t.Errorf("longest sleep %v, want 4s", got) + } +} + +// Through a session. + +func rateEnv(t *testing.T, rate int64, clk *clock, sl *sleeps) *env { + return newEnvSeams(t, func(c *Config) { c.Rate = rate }, seams{now: clk.now, sleep: sl.sleep}) +} + +func TestRateLimitsUploadAndDownloadTogether(t *testing.T) { + clk, sl := newClock(), &sleeps{} + e := rateEnv(t, 10_000, clk, sl) + e.put("a", bytesOf(25_000)) // 15 000 over the burst: 1.5 s + if got := sl.longest(); got != 1500*time.Millisecond { + t.Errorf("after the upload the longest sleep is %v, want 1.5s", got) + } + got, err := e.get("a") // another 25 000: 4 s over in all + if err != nil || len(got) != 25_000 { + t.Fatalf("download: %d bytes, %v", len(got), err) + } + if want := 4 * time.Second; sl.longest() != want { + t.Errorf("after the download the longest sleep is %v, want %v", sl.longest(), want) + } + clk.advance(time.Hour) + before := sl.count() + e.put("b", bytesOf(10_000)) + if sl.count() != before { + t.Errorf("a full bucket slept: %v", sl.d[before:]) + } +} + +func TestRateLimitsOnlyTransfers(t *testing.T) { + clk, sl := newClock(), &sleeps{} + e := rateEnv(t, 100, clk, sl) + e.write("d/f", "x") + for i := 0; i < 20; i++ { + _, _ = e.client.Stat("d/f") + _, _ = e.client.ReadDir("d") + _ = e.client.Mkdir("m") + _ = e.client.Chmod("d/f", 0o600) + } + if sl.count() != 0 { + t.Errorf("requests that move no file bytes slept: %v", sl.d) + } +} + +func TestRateZeroNeverSleeps(t *testing.T) { + sl := &sleeps{} + e := newEnvSeams(t, nil, seams{sleep: sl.sleep}) + e.put("a", bytesOf(1<<20)) + if _, err := e.get("a"); err != nil { + t.Fatal(err) + } + if sl.count() != 0 { + t.Errorf("Rate 0 slept: %v", sl.d) + } +} + +func TestRateWithQuota(t *testing.T) { + clk, sl := newClock(), &sleeps{} + e := newEnvSeams(t, func(c *Config) { c.Rate = 1000; c.Quota = 2000 }, seams{now: clk.now, sleep: sl.sleep}) + e.put("a", bytesOf(2000)) + wantQuotaRefusal(t, "over the quota", putFile(e.client, "b", "x")) + if sl.longest() != time.Second { + t.Errorf("longest sleep %v, want 1s (2000 bytes at 1000 per second after the burst)", sl.longest()) + } +} + +// The real sleep ends with the session. This test waits on a real timer +// only if the code under test is wrong: the sleeps are an hour long and the +// stream ending is what must end them, so the test fails after a deadline +// instead of hanging. +func TestSleepEndsWhenTheStreamEnds(t *testing.T) { + a, b := net.Pipe() + n := newEndNotifier(a) + slept := make(chan struct{}) + go func() { + sleepUntil(n.done, time.Hour) + close(slept) + }() + _ = b.Close() // the peer goes away: Read fails + _, err := n.Read(make([]byte, 1)) + if err == nil { + t.Fatal("Read of a closed pipe succeeded") + } + select { + case <-slept: + case <-time.After(10 * time.Second): + t.Fatal("the sleep did not end with the stream") + } + _ = n.Close() + _ = n.Close() // twice is fine +} + +func TestSleepEndsOnClose(t *testing.T) { + a, b := net.Pipe() + defer func() { _ = b.Close() }() + n := newEndNotifier(a) + slept := make(chan struct{}) + go func() { + sleepUntil(n.done, time.Hour) + close(slept) + }() + _ = n.Close() + select { + case <-slept: + case <-time.After(10 * time.Second): + t.Fatal("the sleep did not end with Close") + } +} + +func TestSleepUntilTimerFires(t *testing.T) { + done := make(chan struct{}) + start := time.Now() + sleepUntil(done, 5*time.Millisecond) // a real 5 ms: the timer path + if time.Since(start) < 5*time.Millisecond { + t.Error("sleepUntil returned early") + } +} diff --git a/internal/sftpd/sftpd.go b/internal/sftpd/sftpd.go new file mode 100644 index 00000000..d8cae664 --- /dev/null +++ b/internal/sftpd/sftpd.go @@ -0,0 +1,141 @@ +package sftpd + +import ( + "cmp" + "errors" + "io" + "strings" + "time" + + "github.com/pkg/sftp" +) + +// Event is one audited thing a client did. Path and To are the virtual +// paths the client used, cleaned (the home is "/"); they hold what the +// client sent, so the caller sanitises them before it logs them. +type Event struct { + // Op is "upload" or "download" (at close, Bytes the total moved; an open + // that failed in the kernel gives the same Op at once, with Err set), + // "delete", "rename", "mkdir", "setstat", or "refused". + Op string + // Path is the file the Op is about; To is the new name of a rename. + Path, To string + // Bytes is the size of a transfer. + Bytes int64 + // Err is why an Op failed. For Op "refused" it names the reason the + // request was refused: ".ssh", "outside the home", "symlink", "link", + // "quota", "unsupported", "bad path" or "too many open files". + Err error +} + +// Config is what a session needs. +type Config struct { + // Home is the directory that is "/" for the client. + Home string + // Quota is the size in bytes the files of the home may add up to; 0 + // means no limit, and then the home is not measured. What it guarantees + // is in the package comment: a write is refused when it would take the + // usage the session measured over the limit, and no more than that. + Quota int64 + // Rate is the bytes per second the session may move, reads and writes + // together, with a burst of one second; 0 means no limit. + Rate int64 + // Audit, when set, is called once per upload, download, delete, rename, + // mkdir and setstat (with Err set when it failed), and once per refusal. + // It is called from the goroutines that serve the requests. No lock of + // this package is held, but the library may hold one of its own: the + // upload and download events fire when a handle is closed, which the + // library does under the lock of its set of open handles. The callback + // must not block, and must not call into the session. + Audit func(Event) +} + +// Serve runs the SFTP protocol on rw until the client ends it, and closes +// rw. A client that ends the session cleanly gives nil. It never writes to +// standard output or error. +func Serve(rw io.ReadWriteCloser, cfg Config) error { + return serve(rw, cfg, seams{}) +} + +// seams are what a test replaces: the clock, and the sleep of the rate +// limit (the default sleeps until the time is up or the session has ended). +type seams struct { + now func() time.Time + sleep func(time.Duration) + + measureDepth int // the depth of the quota walk, 0 for the default + maxHandles int // the open handles a session may have, 0 for the default + + // beforeTruncate, when set, runs in an open that truncates, after the + // file is open and judged and before it is cut. + beforeTruncate func() + // afterPin, when set, runs in a setstat after the entry is pinned and + // judged and before it is changed. + afterPin func() +} + +func serve(rw io.ReadWriteCloser, cfg Config, sm seams) error { + n := newEndNotifier(rw) + rw = n + defer func() { _ = rw.Close() }() + if sm.now == nil { + sm.now = time.Now + } + if sm.sleep == nil { + sm.sleep = func(d time.Duration) { sleepUntil(n.done, d) } + } + h, err := openHome(cfg.Home) + if err != nil { + return err + } + defer h.close() + s := newServer(h, cfg, sm) + rs := sftp.NewRequestServer(rw, sftp.Handlers{FileGet: s, FilePut: s, FileCmd: s, FileList: s}) + err = rs.Serve() + if errors.Is(err, io.EOF) { + return nil + } + return err +} + +// newServer builds the state of one session. The home is measured here when +// there is a quota, and not at all when there is none. +func newServer(h *home, cfg Config, sm seams) *server { + s := &server{home: h, cfg: cfg, handles: handleCount{max: cmp.Or(sm.maxHandles, maxHandles)}, beforeTruncate: sm.beforeTruncate, afterPin: sm.afterPin} + if cfg.Quota > 0 { + s.quota = newQuota(h, cfg.Quota, sm.now, sm.measureDepth) + } + s.rate = newBucket(cfg.Rate, sm.now, sm.sleep) + return s +} + +// subsystemNames are the programs sshd's Subsystem line names for sftp: +// the OpenSSH server binary and the built-in. +var subsystemNames = [...]string{"sftp-server", "internal-sftp"} + +// IsSubsystemCommand reports whether cmd is what sshd passes for the sftp +// subsystem: the base name of its first word is sftp-server or +// internal-sftp ("/usr/lib/openssh/sftp-server", "internal-sftp", +// "sftp-server -l INFO"); the arguments are ignored. A command with a shell +// metacharacter (";", "&", "|", "$", a backtick, a parenthesis, a redirection, +// a newline or a NUL) is not one, and neither is a program that only has +// spaces in its path: the first word is cut at the first blank. +func IsSubsystemCommand(cmd string) bool { + if strings.ContainsAny(cmd, ";&|`$()<>\n\r\x00") { + return false + } + w := strings.Fields(cmd) + if len(w) == 0 { + return false + } + base := w[0] + if i := strings.LastIndexByte(base, '/'); i >= 0 { + base = base[i+1:] + } + for _, n := range subsystemNames { + if base == n { + return true + } + } + return false +} diff --git a/internal/sftpd/size_test.go b/internal/sftpd/size_test.go new file mode 100644 index 00000000..331669df --- /dev/null +++ b/internal/sftpd/size_test.go @@ -0,0 +1,388 @@ +package sftpd + +import ( + "encoding/binary" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/sys/unix" +) + +// 5. The size by setstat and fsetstat. The client of OpenSSH (scp) sets the +// final size of an uploaded file with an fsetstat of the size alone. + +// The attribute flags of a request, as the protocol has them. +const ( + attrSize = 0x1 + attrUID = 0x2 + attrPerms = 0x4 +) + +// attrReq is a Setstat request with the size and, when the flags say so, +// the owner (uid, gid) and the mode, in the order of the protocol. +func attrReq(path string, flags uint32, size uint64, rest ...uint32) *sftp.Request { + b := binary.BigEndian.AppendUint64(nil, size) + for _, v := range rest { + b = binary.BigEndian.AppendUint32(b, v) + } + return &sftp.Request{Method: "Setstat", Filepath: path, Flags: flags, Attrs: b} +} + +func fileSize(t *testing.T, dir, rel string) int64 { + t.Helper() + fi, err := os.Stat(filepath.Join(dir, rel)) + if err != nil { + t.Fatal(err) + } + return fi.Size() +} + +// What scp does: upload, then an fsetstat of the final size on the open handle. +func TestFsetstatSizeAfterUpload(t *testing.T) { + for _, quota := range []int64{0, 100} { + e := newEnv(t, func(c *Config) { c.Quota = quota }) + f, err := e.client.OpenFile("up", os.O_WRONLY|os.O_CREATE|os.O_TRUNC) + if err != nil { + t.Fatal(err) + } + if _, err := f.Write([]byte("123456789")); err != nil { + t.Fatal(err) + } + if err := f.Truncate(9); err != nil { + t.Fatalf("quota %d: fsetstat of the size alone: %v", quota, err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + if got := e.read("up"); got != "123456789" { + t.Errorf("quota %d: content %q", quota, got) + } + if got := strings.Join(describe(e.rec.all()), "|"); got != "setstat /up|upload /up 9" { + t.Errorf("quota %d: events %q", quota, got) + } + } +} + +func TestSetstatSizeCutsAndExtends(t *testing.T) { + e := newEnv(t, nil) + e.write("f", "abcdef") + if err := e.client.Truncate("f", 3); err != nil { + t.Fatalf("shrink by setstat: %v", err) + } + if got := e.read("f"); got != "abc" { + t.Errorf("after shrinking: %q", got) + } + if err := e.client.Truncate("f", 5); err != nil { + t.Fatalf("extend by setstat: %v", err) + } + if got := e.read("f"); got != "abc\x00\x00" { + t.Errorf("after extending: %q", got) + } + h, err := e.client.OpenFile("f", os.O_RDWR) + if err != nil { + t.Fatal(err) + } + defer func() { _ = h.Close() }() + if err := h.Truncate(0); err != nil { + t.Fatalf("empty by fsetstat: %v", err) + } + if fileSize(t, e.home, "f") != 0 { + t.Error("the file is not empty") + } +} + +func TestSetstatSizeWithinAndBeyondTheQuota(t *testing.T) { + e := quotaEnv(t, 100) + e.put("a", bytesOf(40)) + if err := e.client.Truncate("a", 100); err != nil { + t.Fatalf("growing to the limit: %v", err) + } + if got := diskUsage(t, e); got != 100 { + t.Errorf("disk %d, want 100", got) + } + // Same size at the limit: nothing grows, so it is allowed (scp does this). + if err := e.client.Truncate("a", 100); err != nil { + t.Errorf("the size it has, at the limit: %v", err) + } + wantQuotaRefusal(t, "one byte more", e.client.Truncate("a", 101)) + wantQuotaRefusal(t, "upload with the home full", putFile(e.client, "b", "x")) + if got := fileSize(t, e.home, "a"); got != 100 { + t.Errorf("a refused extension changed the size to %d", got) + } + e.rec.reset() + wantQuotaRefusal(t, "a size far beyond", e.client.Truncate("a", 1<<40)) + if got := strings.Join(refusals(e.rec.all()), ","); got != "quota" { + t.Errorf("refusals %q, want quota", got) + } + // Through a handle, the same. + h, err := e.client.OpenFile("a", os.O_RDWR) + if err != nil { + t.Fatal(err) + } + defer func() { _ = h.Close() }() + wantQuotaRefusal(t, "fsetstat beyond", h.Truncate(150)) +} + +func TestSetstatSizeShrinkingReleasesTheQuota(t *testing.T) { + e := quotaEnv(t, 100) + e.put("a", bytesOf(100)) + wantQuotaRefusal(t, "upload into a full home", putFile(e.client, "b", "x")) + if err := e.client.Truncate("a", 30); err != nil { + t.Fatal(err) + } + e.put("b", bytesOf(70)) + wantQuotaRefusal(t, "upload over the room that was freed", putFile(e.client, "c", "x")) + // By a handle. + h, err := e.client.OpenFile("b", os.O_RDWR) + if err != nil { + t.Fatal(err) + } + if err := h.Truncate(0); err != nil { + t.Fatal(err) + } + _ = h.Close() + e.put("c", bytesOf(70)) + if got := diskUsage(t, e); got != 100 { + t.Errorf("disk %d, want 100", got) + } +} + +func TestSetstatSizeRefusedWhereTheRulesRefuse(t *testing.T) { + e := sshEnv(t) + e.write("hl", "data") + if err := os.Link(filepath.Join(e.home, "hl"), filepath.Join(e.home, "hl2")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("plain", filepath.Join(e.home, "sl")); err != nil { + t.Fatal(err) + } + if err := e.client.Mkdir("dir"); err != nil { + t.Fatal(err) + } + for _, c := range []struct{ path, reason string }{ + {"hl", "link"}, + {"hl2", "link"}, + {"sl", "symlink"}, + {".ssh/authorized_keys", ".ssh"}, + {".ssh", ".ssh"}, + {"a/../.ssh/authorized_keys", ".ssh"}, + {"/", "outside the home"}, + } { + e.rec.reset() + err := e.client.Truncate(c.path, 0) + if code(err) != fxPermissionDenied { + t.Errorf("truncate %q: %v, want permission denied", c.path, err) + } + if got := strings.Join(refusals(e.rec.all()), ","); got != c.reason { + t.Errorf("truncate %q: refusals %q, want %q", c.path, got, c.reason) + } + } + // A directory: no rule of ours, the kernel's answer. + if err := e.client.Truncate("dir", 0); err == nil { + t.Error("truncate of a directory succeeded") + } + // A fifo is not a regular file. + if err := unix.Mkfifo(filepath.Join(e.home, "fifo"), 0o644); err != nil { + t.Fatal(err) + } + if err := e.client.Truncate("fifo", 0); code(err) != fxOpUnsupported { + t.Errorf("truncate of a fifo: %v", err) + } + if e.read("hl") != "data" || e.read("hl2") != "data" || e.read("plain") != "x" || + e.read(".ssh/authorized_keys") != "ssh-ed25519 AAAA example-key alice@example.net\n" { + t.Error("a refused request changed a file") + } +} + +func TestSetstatSizeNegativeOrAbsurdIsRefused(t *testing.T) { + for _, quota := range []int64{0, 1000} { + e := newEnv(t, func(c *Config) { c.Quota = quota }) + e.write("f", "content") + for _, n := range []int64{-1, -1 << 62, 1<<62 + 1, 1<<63 - 1} { + if err := e.client.Truncate("f", n); code(err) != fxOpUnsupported { + t.Errorf("quota %d: truncate to %d: %v, want unsupported", quota, n, err) + } + } + if e.read("f") != "content" { + t.Errorf("quota %d: a refused size changed the file", quota) + } + } +} + +// A request that asks for a size and a new owner is refused whole. +func TestSetstatSizeWithOwnerIsRefusedWhole(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "f"), []byte("content"), 0o644); err != nil { + t.Fatal(err) + } + s := newServer(mustHome(t, dir), Config{Quota: 1000}, seams{now: time.Now}) + r := attrReq("/f", attrSize|attrUID|attrPerms, 0, 0, 0, 0o600) + if err := s.Filecmd(r); reasonOf(err) != reasonUnsupported { + t.Errorf("size with owner: %v, want unsupported", err) + } + fi, err := os.Stat(filepath.Join(dir, "f")) + if err != nil { + t.Fatal(err) + } + if fi.Size() != 7 || fi.Mode().Perm() != 0o644 { + t.Errorf("a refused request changed the file: size %d, mode %v", fi.Size(), fi.Mode()) + } + if got := s.quota.usage(); got != 7 { + t.Errorf("usage %d, want 7", got) + } +} + +// Size and mode in one request: the size first, then the mode; a size that is +// refused leaves the mode as it was. +func TestSetstatSizeAndModeTogether(t *testing.T) { + dir := t.TempDir() + for _, name := range []string{"a", "b"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte(bytesOf(60)), 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.Mkdir(filepath.Join(dir, "d"), 0o755); err != nil { + t.Fatal(err) + } + // The walk of the start counts 120 of the 150. + s := newServer(mustHome(t, dir), Config{Quota: 150}, seams{now: time.Now}) + if err := s.Filecmd(attrReq("/a", attrSize|attrPerms, 30, 0o600)); err != nil { + t.Fatalf("size and mode: %v", err) + } + if fi, _ := os.Stat(filepath.Join(dir, "a")); fi.Size() != 30 || fi.Mode().Perm() != 0o600 { + t.Errorf("size %d mode %v, want 30 and 0600", fi.Size(), fi.Mode().Perm()) + } + // Usage is 90 now; b may grow by 60 at most. + if err := s.Filecmd(attrReq("/b", attrSize|attrPerms, 130, 0o600)); reasonOf(err) != reasonQuota { + t.Errorf("size and mode over the quota: %v, want the quota's refusal", err) + } + if fi, _ := os.Stat(filepath.Join(dir, "b")); fi.Size() != 60 || fi.Mode().Perm() != 0o644 { + t.Errorf("refused request: size %d mode %v, want 60 and 0644", fi.Size(), fi.Mode().Perm()) + } + // A directory: the size is refused and the mode is not applied. + if err := s.Filecmd(attrReq("/d", attrSize|attrPerms, 0, 0o700)); err == nil { + t.Error("size on a directory succeeded") + } + if fi, _ := os.Stat(filepath.Join(dir, "d")); fi.Mode().Perm() != 0o755 { + t.Errorf("a directory's mode changed to %v by a refused request", fi.Mode().Perm()) + } + if got := s.quota.usage(); got != 90 { + t.Errorf("usage %d, want 90", got) + } +} + +// A file whose name is gone between the pin and the size: counted while a +// handle of the session holds it, and not once nothing does. +func TestSetstatSizeOfAnUnlinkedFile(t *testing.T) { + setup := func(t *testing.T) (*server, string) { + dir := t.TempDir() + var s *server + s = newServer(mustHome(t, dir), Config{Quota: 100}, seams{now: time.Now, afterPin: func() { + if err := s.Filecmd(&sftp.Request{Method: "Remove", Filepath: "/a"}); err != nil { + panic(err) + } + }}) + return s, dir + } + t.Run("held", func(t *testing.T) { + s, dir := setup(t) + h, err := s.openFile(&sftp.Request{Method: "Put", Filepath: "/a", Flags: 0x2 | 0x8}, true) // WRITE | CREAT + if err != nil { + t.Fatal(err) + } + if _, err := h.WriteAt([]byte(bytesOf(60)), 0); err != nil { + t.Fatal(err) + } + if err := s.Filecmd(attrReq("/a", attrSize, 80)); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "a")); err == nil { + t.Fatal("the name is still there") + } + if fi, _ := h.f.Stat(); fi.Size() != 80 { + t.Errorf("size %d, want 80", fi.Size()) + } + if got := s.quota.usage(); got != 80 { + t.Errorf("usage with the handle open %d, want 80", got) + } + _ = h.Close() + if got := s.quota.usage(); got != 0 { + t.Errorf("usage after the last handle closed %d, want 0", got) + } + }) + t.Run("not held", func(t *testing.T) { + s, dir := setup(t) + if err := os.WriteFile(filepath.Join(dir, "a"), []byte(bytesOf(60)), 0o644); err != nil { + t.Fatal(err) + } + s.quota.mu.Lock() + s.quota.remeasure() + s.quota.mu.Unlock() + if err := s.Filecmd(attrReq("/a", attrSize, 80)); err != nil { + t.Fatal(err) + } + if got := s.quota.usage(); got != 0 { + t.Errorf("usage %d, want 0: the file has no name and no handle", got) + } + }) +} + +// A size set while a write of the session is under way is counted once: the +// size is read and the file cut under the lock a write holds. +// +// The write waits for the file to be cut, up to a deadline on a real timer: +// with the lock held by the write the cut cannot happen until the write is +// over, so the wait ends by the deadline; without the lock the cut comes at +// once. +func TestSetstatSizeDoesNotLoseAConcurrentWrite(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "f"), []byte(bytesOf(100)), 0o644); err != nil { + t.Fatal(err) + } + atPin, letGo, inWrite := make(chan struct{}), make(chan struct{}), make(chan struct{}) + s := newServer(mustHome(t, dir), Config{Quota: 1000}, seams{now: time.Now, afterPin: func() { + close(atPin) + <-letGo + }}) + b, err := s.openFile(&sftp.Request{Method: "Put", Filepath: "/f", Flags: 0x2}, true) // WRITE + if err != nil { + t.Fatal(err) + } + defer func() { _ = b.Close() }() + done := make(chan error, 1) + go func() { done <- s.Filecmd(attrReq("/f", attrSize, 0)) }() + select { + case <-atPin: + case err := <-done: + t.Fatalf("setstat ended before it was changing the file: %v", err) + } + wrote := make(chan error, 1) + go func() { + w := func() (int, error) { + close(inWrite) + for deadline := time.Now().Add(300 * time.Millisecond); time.Now().Before(deadline); time.Sleep(time.Millisecond) { + if fi, err := b.f.Stat(); err == nil && fi.Size() == 0 { + break + } + } + return b.f.WriteAt([]byte(bytesOf(100)), 100) + } + _, err := s.quota.write(b.f, 100, 100, false, w) + wrote <- err + }() + <-inWrite + close(letGo) + if err := <-wrote; err != nil { + t.Fatalf("write: %v", err) + } + if err := <-done; err != nil { + t.Fatalf("setstat: %v", err) + } + if got, disk := s.quota.usage(), fileSize(t, dir, "f"); got != disk { + t.Errorf("usage %d, the file on the disk has %d", got, disk) + } +} diff --git a/internal/sftpd/ssh_test.go b/internal/sftpd/ssh_test.go new file mode 100644 index 00000000..bb6da694 --- /dev/null +++ b/internal/sftpd/ssh_test.go @@ -0,0 +1,555 @@ +package sftpd + +import ( + "os" + "path/filepath" + "sort" + "sync" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// 2. .ssh is out of reach. + +// sshSpellings are the ways to name the .ssh entry of the home, or the +// file under it, after cleaning. +var sshSpellings = []string{ + ".ssh", + "/.ssh", + "./.ssh", + "//.ssh", + ".ssh/", + ".ssh/.", + "a/../.ssh", + "/a/b/../../.ssh", + "../.ssh", + "/../../.ssh", + ".ssh/authorized_keys", + "/.ssh/authorized_keys", + ".ssh/../.ssh/authorized_keys", + "./.ssh/./authorized_keys", + "//.ssh//authorized_keys", + ".ssh/sub/new", + ".ssh/missing", +} + +func sshEnv(t *testing.T) *env { + e := newEnv(t, nil) + e.write(".ssh/authorized_keys", "ssh-ed25519 AAAA example-key alice@example.net\n") + e.write("a/placeholder", "x") + e.write("plain", "x") + return e +} + +func TestSSHRefusedForEveryOperation(t *testing.T) { + e := sshEnv(t) + for _, p := range sshSpellings { + check := func(op string, err error) { + t.Helper() + if code(err) != fxPermissionDenied { + t.Errorf("%s %q: err = %v, want permission denied", op, p, err) + } + } + _, err := e.client.Stat(p) + check("stat", err) + _, err = e.client.Lstat(p) + check("lstat", err) + _, err = e.client.ReadDir(p) + check("list", err) + _, err = e.client.Open(p) + check("open", err) + _, err = e.client.Create(p) + check("create", err) + _, err = e.client.OpenFile(p, os.O_WRONLY|os.O_APPEND) + check("append", err) + _, err = e.client.OpenFile(p, os.O_WRONLY|os.O_TRUNC) + check("truncate", err) + check("mkdir", e.client.Mkdir(p)) + check("mkdirall", e.client.MkdirAll(p)) + check("remove", e.client.Remove(p)) + check("rmdir", e.client.RemoveDirectory(p)) + check("rename from", e.client.Rename(p, "moved")) + check("rename to", e.client.Rename("plain", p)) + check("posix-rename from", e.client.PosixRename(p, "moved")) + check("posix-rename to", e.client.PosixRename("plain", p)) + check("chmod", e.client.Chmod(p, 0o777)) + check("chtimes", e.client.Chtimes(p, time.Now(), time.Now())) + check("chown", e.client.Chown(p, 1, 1)) + check("truncate by setstat", e.client.Truncate(p, 0)) + } + // Nothing changed on disk. + if got := e.read(".ssh/authorized_keys"); got != "ssh-ed25519 AAAA example-key alice@example.net\n" { + t.Errorf("authorized_keys changed: %q", got) + } + fi, _ := os.Stat(filepath.Join(e.home, ".ssh")) + if fi.Mode().Perm() != 0o755 { + t.Errorf(".ssh mode changed to %v", fi.Mode()) + } + if e.exists("moved") || e.exists(".ssh/sub") || e.exists(".ssh/missing") || !e.exists("plain") { + t.Error("a refused request changed the home") + } + for _, r := range refusals(e.rec.all()) { + if r != ".ssh" { + t.Errorf("refusal reason %q, want .ssh", r) + } + } +} + +func TestSSHHiddenFromListing(t *testing.T) { + e := sshEnv(t) + ents, err := e.client.ReadDir("/") + if err != nil { + t.Fatal(err) + } + var names []string + for _, fi := range ents { + names = append(names, fi.Name()) + } + sort.Strings(names) // a listing comes in the order of the file system + if len(names) != 2 || names[0] != "a" || names[1] != "plain" { + t.Errorf("listing of / = %v, want [a plain]", names) + } + // Other directories named .ssh are ordinary, and so is the spelling + // in another case: the rule is the entry of the home, as written. + e.write("a/.ssh/k", "x") + e.write(".SSH/k", "x") + if got, err := e.get("a/.ssh/k"); err != nil || got != "x" { + t.Errorf("a/.ssh/k = %q, %v", got, err) + } + if got, err := e.get(".SSH/k"); err != nil || got != "x" { + t.Errorf(".SSH/k = %q, %v", got, err) + } + ents, _ = e.client.ReadDir("a") + if len(ents) != 2 { + t.Errorf("listing of a = %d entries, want 2", len(ents)) + } +} + +func TestSSHRealPathIsOnlyAString(t *testing.T) { + e := sshEnv(t) + // Resolving the name gives the cleaned name; whatever is done with it + // is refused. + got, err := e.client.RealPath("a/../.ssh") + if err != nil || got != "/.ssh" { + t.Errorf("RealPath = %q, %v", got, err) + } +} + +// Symbolic links: never followed. + +func linkEnv(t *testing.T) *env { + e := sshEnv(t) + e.write("real/f", "ok") + e.write("outside-target", "x") + if err := os.WriteFile(filepath.Join(e.root, "outside"), []byte("outside"), 0o644); err != nil { + t.Fatal(err) + } + links := map[string]string{ + "tossh": ".ssh", + "tossh-file": ".ssh/authorized_keys", + "toabs": filepath.Join(e.root, "outside"), + "toparent": "../outside", + "todir": "real", + "tofile": "real/f", + "toself": "toself", + "dangling": "nothing", + "toabs-ssh": filepath.Join(e.home, ".ssh"), + "real/inlink": "../.ssh", + } + for name, target := range links { + if err := os.Symlink(target, filepath.Join(e.home, name)); err != nil { + t.Fatal(err) + } + } + return e +} + +func TestSymlinksAreListedAndLstatedAsLinks(t *testing.T) { + e := linkEnv(t) + for _, n := range []string{"tossh", "toabs", "todir", "tofile", "dangling", "toself"} { + fi, err := e.client.Lstat(n) + if err != nil { + t.Errorf("lstat %s: %v", n, err) + continue + } + if fi.Mode()&os.ModeSymlink == 0 { + t.Errorf("lstat %s: mode %v, want a symlink", n, fi.Mode()) + } + } + ents, err := e.client.ReadDir("/") + if err != nil { + t.Fatal(err) + } + links := 0 + for _, fi := range ents { + if fi.Mode()&os.ModeSymlink != 0 { + links++ + } + if fi.Name() == ".ssh" { + t.Error(".ssh is listed") + } + } + if links != 9 { + t.Errorf("%d links listed, want 9", links) + } +} + +func TestSymlinksAreNeverFollowed(t *testing.T) { + e := linkEnv(t) + through := []string{"tossh", "tossh-file", "toabs", "toparent", "todir", "tofile", "toself", "dangling", "toabs-ssh", + "tossh/authorized_keys", "todir/f", "toabs/x", "real/inlink/authorized_keys", "tossh/x/y"} + for _, p := range through { + check := func(op string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s %q succeeded through a link", op, p) + } + } + _, err := e.client.Stat(p) + check("stat", err) + _, err = e.client.ReadDir(p) + check("list", err) + _, err = e.client.Open(p) + check("open", err) + _, err = e.client.OpenFile(p, os.O_WRONLY) + check("open for write", err) + _, err = e.client.Create(p + "/new") + check("create below", err) + check("mkdir below", e.client.Mkdir(p+"/d")) + check("chmod", e.client.Chmod(p, 0o777)) + check("chtimes", e.client.Chtimes(p, time.Now(), time.Now())) + _, err = e.client.ReadLink(p) + check("readlink", err) + } + // "todir/../plain" is lexically "/plain": it is not through the link. + if _, err := e.client.Stat("todir/../plain"); err != nil { + t.Errorf("todir/../plain: %v (cleaned to /plain, not through the link)", err) + } + // The refusals through a link are of the "symlink" kind. + got := refusals(e.rec.all()) + seen := map[string]bool{} + for _, r := range got { + seen[r] = true + } + if !seen["symlink"] { + t.Errorf("no refusal with reason symlink in %v", got) + } + // Nothing was created or changed through a link. + for _, n := range []string{"new", "d"} { + for _, dir := range []string{e.home, filepath.Join(e.home, ".ssh"), e.root} { + if _, err := os.Lstat(filepath.Join(dir, n)); err == nil { + t.Errorf("%s was created in %s", n, dir) + } + } + } + if fi, _ := os.Stat(filepath.Join(e.root, "outside")); fi.Mode().Perm() != 0o644 { + t.Errorf("the file outside the home was changed: %v", fi.Mode()) + } + if got := e.read(".ssh/authorized_keys"); got != "ssh-ed25519 AAAA example-key alice@example.net\n" { + t.Errorf("authorized_keys changed: %q", got) + } +} + +func TestSymlinkAndHardlinkCreationRefused(t *testing.T) { + e := sshEnv(t) + if err := e.client.Symlink(".ssh", "l1"); code(err) != fxPermissionDenied { + t.Errorf("symlink to .ssh: %v", err) + } + if err := e.client.Symlink("/etc/passwd", "l2"); code(err) != fxPermissionDenied { + t.Errorf("symlink to /etc/passwd: %v", err) + } + if err := e.client.Symlink("plain", "l3"); code(err) != fxPermissionDenied { + t.Errorf("symlink to a file in the home: %v", err) + } + if err := e.client.Link("plain", "h1"); err == nil { + t.Error("hard link to a file in the home succeeded") + } + if err := e.client.Link(".ssh/authorized_keys", "h2"); err == nil { + t.Error("hard link of authorized_keys succeeded") + } + for _, n := range []string{"l1", "l2", "l3", "h1", "h2"} { + if e.exists(n) { + t.Errorf("%s was created", n) + } + } + got := refusals(e.rec.all()) + if len(got) < 5 { + t.Errorf("refusals = %v, want one per request", got) + } +} + +// A link can be removed or moved as the entry it is, never through. +func TestLinkItselfCanBeRemovedAndRenamed(t *testing.T) { + e := linkEnv(t) + if err := e.client.Remove("todir"); err != nil || e.exists("todir") { + t.Errorf("remove of a link: %v", err) + } + if !e.exists("real/f") { + t.Error("removing the link removed its target") + } + if err := e.client.Rename("tofile", "moved"); err != nil || !e.exists("moved") { + t.Errorf("rename of a link: %v", err) + } + if fi, err := os.Lstat(filepath.Join(e.home, "moved")); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Errorf("the moved entry is not the link: %v, %v", fi, err) + } + if !e.exists("real/f") { + t.Error("renaming the link moved its target") + } + // A link cannot be written over by an upload. + if err := putFile(e.client, "tossh-file", "x"); err == nil { + t.Error("upload over a link succeeded") + } + if got := e.read(".ssh/authorized_keys"); got[:3] != "ssh" { + t.Errorf("authorized_keys changed: %q", got) + } +} + +// A directory swapped for a link between a check and the use must not be +// followed: the resolution never looks and then follows. +func TestDirectorySwappedForLinkIsNotFollowed(t *testing.T) { + e := newEnv(t, nil) + e.write("real/f", "ok") + e.write(".ssh/f", "secret") + if err := os.Symlink(".ssh", filepath.Join(e.home, "lnk")); err != nil { + t.Fatal(err) + } + a, b := filepath.Join(e.home, "real"), filepath.Join(e.home, "lnk") + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + // Exchange the directory and the link atomically. + if err := unix.Renameat2(unix.AT_FDCWD, a, unix.AT_FDCWD, b, unix.RENAME_EXCHANGE); err != nil { + t.Error(err) + return + } + } + }() + // The reads go on until enough of them found the directory in place (the + // swap runs at the same time, so some find the link): a run in which none + // did would prove nothing about the race, and fails. + const wantOpened, maxReads = 20, 20000 + var opened, leaked, reads int + for reads = 0; reads < maxReads && opened < wantOpened; reads++ { + got, err := e.get("real/f") + if err == nil { + opened++ + if got != "ok" { + leaked++ + } + } + } + close(stop) + wg.Wait() + if leaked != 0 { + t.Fatalf("%d of %d reads returned the content of .ssh/f through a swapped link", leaked, opened) + } + if opened < wantOpened { + t.Fatalf("only %d of %d reads found the directory in place: the race was not exercised", opened, reads) + } + t.Logf("%d of %d reads found the directory in place, the others the link", opened, reads) +} + +// A regular file with more than one name is not served: a name for the +// data of .ssh/authorized_keys or of a private key, made outside SFTP, would +// otherwise be a way to it. + +func TestHardLinkedFilesAreNotServed(t *testing.T) { + e := sshEnv(t) + if err := os.Link(filepath.Join(e.home, ".ssh/authorized_keys"), filepath.Join(e.home, "keys")); err != nil { + t.Fatal(err) + } + if err := os.Link(filepath.Join(e.home, "plain"), filepath.Join(e.home, "plain2")); err != nil { + t.Fatal(err) + } + before := e.read(".ssh/authorized_keys") + e.rec.reset() + for _, name := range []string{"keys", "plain", "plain2"} { + if _, err := e.client.Open(name); code(err) != fxPermissionDenied { + t.Errorf("download of %s: %v, want permission denied", name, err) + } + for _, fl := range []int{os.O_WRONLY, os.O_WRONLY | os.O_TRUNC, os.O_RDWR, os.O_WRONLY | os.O_APPEND, os.O_WRONLY | os.O_CREATE | os.O_TRUNC} { + if _, err := e.client.OpenFile(name, fl); code(err) != fxPermissionDenied { + t.Errorf("open of %s with flags %#x: %v, want permission denied", name, fl, err) + } + } + if err := e.client.Chmod(name, 0o777); code(err) != fxPermissionDenied { + t.Errorf("chmod of %s: %v, want permission denied", name, err) + } + if err := e.client.Chtimes(name, time.Unix(1e9, 0), time.Unix(1e9, 0)); code(err) != fxPermissionDenied { + t.Errorf("chtimes of %s: %v, want permission denied", name, err) + } + } + if got := e.read(".ssh/authorized_keys"); got != before { + t.Errorf("authorized_keys changed to %q", got) + } + if fi, _ := os.Stat(filepath.Join(e.home, ".ssh/authorized_keys")); fi.Mode().Perm() != 0o644 { + t.Errorf("authorized_keys mode = %v", fi.Mode()) + } + for _, r := range refusals(e.rec.all()) { + if r != "link" { + t.Errorf("refusal reason %q, want link", r) + } + } + if n := len(refusals(e.rec.all())); n != 3*(1+5+2) { + t.Errorf("%d refusals, want %d", n, 3*(1+5+2)) + } +} + +// The name of such a file is an entry like any other: it is listed, stat'ed, +// moved and removed (none of that reaches the data), and when the other name +// is gone the file is served again. +func TestHardLinkedNamesCanBeListedMovedAndRemoved(t *testing.T) { + e := sshEnv(t) + if err := os.Link(filepath.Join(e.home, ".ssh/authorized_keys"), filepath.Join(e.home, "keys")); err != nil { + t.Fatal(err) + } + before := e.read(".ssh/authorized_keys") + if fi, err := e.client.Stat("keys"); err != nil || fi.Size() != int64(len(before)) { + t.Errorf("stat of the name: %v, %v", fi, err) + } + if err := e.client.Rename("keys", "keys2"); err != nil { + t.Errorf("rename of the name: %v", err) + } + if err := e.client.PosixRename("keys2", "keys3"); err != nil { + t.Errorf("posix rename of the name: %v", err) + } + if err := e.client.Remove("keys3"); err != nil { + t.Errorf("remove of the name: %v", err) + } + if got := e.read(".ssh/authorized_keys"); got != before { + t.Errorf("authorized_keys changed to %q", got) + } + // A file moved over a name of such a file replaces the name only. + if err := os.Link(filepath.Join(e.home, ".ssh/authorized_keys"), filepath.Join(e.home, "keys")); err != nil { + t.Fatal(err) + } + e.put("new", "n") + if err := e.client.PosixRename("new", "keys"); err != nil { + t.Errorf("posix rename over the name: %v", err) + } + if got := e.read(".ssh/authorized_keys"); got != before { + t.Errorf("authorized_keys changed to %q", got) + } + // With one name left the file is a plain one again. + if err := os.Link(filepath.Join(e.home, "plain"), filepath.Join(e.home, "plain2")); err != nil { + t.Fatal(err) + } + if _, err := e.get("plain"); code(err) != fxPermissionDenied { + t.Errorf("download with two names: %v", err) + } + if err := os.Remove(filepath.Join(e.home, "plain2")); err != nil { + t.Fatal(err) + } + if got, err := e.get("plain"); err != nil || got != "x" { + t.Errorf("download with one name: %q, %v", got, err) + } +} + +// The setstat judges the entry it changes: the name is pinned, and the mode +// and the times are set on what was pinned. A name that is made to mean a hard +// link of a key file between the check and the change (here by an exchange +// with a name that is one) must not carry the change to that file. +func TestSetstatPinsTheEntryItJudged(t *testing.T) { + ops := []struct { + name string + do func(*env, string) error + moved func(t *testing.T, e *env) bool // the key file was changed + }{ + {"chmod", func(e *env, n string) error { return e.client.Chmod(n, 0o600) }, func(t *testing.T, e *env) bool { + fi, err := os.Stat(filepath.Join(e.home, ".ssh/authorized_keys")) + if err != nil { + t.Fatal(err) + } + return fi.Mode().Perm() != 0o644 + }}, + {"chtimes", func(e *env, n string) error { return e.client.Chtimes(n, time.Unix(1e9, 0), time.Unix(1e9, 0)) }, func(t *testing.T, e *env) bool { + fi, err := os.Stat(filepath.Join(e.home, ".ssh/authorized_keys")) + if err != nil { + t.Fatal(err) + } + return fi.ModTime().Unix() == 1e9 + }}, + } + for _, op := range ops { + t.Run(op.name, func(t *testing.T) { + var e *env + var once sync.Once + e = newEnvSeams(t, nil, seams{afterPin: func() { + once.Do(func() { + a, b := filepath.Join(e.home, "n"), filepath.Join(e.home, "keys") + if err := unix.Renameat2(unix.AT_FDCWD, a, unix.AT_FDCWD, b, unix.RENAME_EXCHANGE); err != nil { + t.Error(err) + } + }) + }}) + e.write(".ssh/authorized_keys", "ssh-ed25519 AAAA example-key alice@example.net\n") + e.write("n", "x") + if err := os.Link(filepath.Join(e.home, ".ssh/authorized_keys"), filepath.Join(e.home, "keys")); err != nil { + t.Fatal(err) + } + // Before the setstat n is a plain file, and keys is a link of the key + // file. The exchange happens after the look: n is now the link. + if err := op.do(e, "n"); err != nil { + t.Fatalf("%s of the plain file: %v", op.name, err) + } + if op.moved(t, e) { + t.Errorf("%s reached the key file through the exchanged name", op.name) + } + }) + } +} + +// The same exchange, run all the time against a stream of setstats: the key +// file is never changed, and enough of the setstats got through (found the +// plain file) to show the race was exercised. +func TestSetstatNeverReachesALinkedFileUnderExchange(t *testing.T) { + e := sshEnv(t) + e.write("n", "x") + if err := os.Link(filepath.Join(e.home, ".ssh/authorized_keys"), filepath.Join(e.home, "keys")); err != nil { + t.Fatal(err) + } + a, b := filepath.Join(e.home, "n"), filepath.Join(e.home, "keys") + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + if err := unix.Renameat2(unix.AT_FDCWD, a, unix.AT_FDCWD, b, unix.RENAME_EXCHANGE); err != nil { + t.Error(err) + return + } + } + }() + const wantDone, maxTries = 20, 20000 + var done, tries int + for tries = 0; tries < maxTries && done < wantDone; tries++ { + if e.client.Chmod("n", 0o600) == nil { + done++ + } + } + close(stop) + wg.Wait() + if fi, err := os.Stat(filepath.Join(e.home, ".ssh/authorized_keys")); err != nil || fi.Mode().Perm() != 0o644 { + t.Errorf("the key file after %d setstats: %v, %v", tries, fi, err) + } + if done < wantDone { + t.Fatalf("only %d of %d setstats found the plain file: the race was not exercised", done, tries) + } +} diff --git a/internal/tier/report_limits_test.go b/internal/tier/report_limits_test.go index ed5d58ad..b6be97c8 100644 --- a/internal/tier/report_limits_test.go +++ b/internal/tier/report_limits_test.go @@ -115,3 +115,25 @@ func TestSudoersIsTheTextOf0226(t *testing.T) { t.Error("the per-tier text differs from the golden file of the 0.2.26 tag: freeze that text for the rollback to 0.2.26 (rollback0226.go leaves the drop-in alone only while they are the same)") } } + +// This release's per-tier text is the one 0.2.27 wrote, which is why the +// rollback to 0.2.27 leaves the drop-in alone. A release that changes a rule +// makes this fail: it freezes the text of the release before it and gives the +// rollback to that release a step for the drop-in. Skipped where git or the +// tag is absent. +func TestSudoersIsTheTextOf0227(t *testing.T) { + r := execx.Real{} + if _, err := r.LookPath("git"); err != nil { + t.Skip("git is not installed, so the 0.2.27 tag cannot be read") + } + if res, err := r.Run(context.Background(), execx.Cmd{Name: "git", Args: []string{"rev-parse", "-q", "--verify", "0.2.27^{commit}"}}); err != nil || res.Code != 0 { + t.Skip("the 0.2.27 tag is not in this repository (CI must fetch tags: git fetch --tags)") + } + res, err := r.Run(context.Background(), execx.Cmd{Name: "git", Args: []string{"show", "0.2.27:internal/tier/testdata/sudoers.tiers"}}) + if err != nil || res.Code != 0 { + t.Fatalf("cannot read the 0.2.27 tag's golden file: %v %s", err, res.Stderr) + } + if string(res.Stdout) != Sudoers() { + t.Error("the per-tier text differs from the golden file of the 0.2.27 tag: freeze that text for the rollback to 0.2.27 (rollback0227.go leaves the drop-in alone only while they are the same)") + } +} diff --git a/man/tacctl.1 b/man/tacctl.1 index b1a31e05..d01a7040 100644 --- a/man/tacctl.1 +++ b/man/tacctl.1 @@ -1,6 +1,6 @@ .\" Manual page for tacctl, the management CLI for pluggable network-device AAA. .\" Render locally with: groff -man -Tascii man/tacctl.1 | less -.TH TACCTL 1 "2026-11-09" "tacctl 0.2.27" "tacctl Manual" +.TH TACCTL 1 "2026-11-09" "tacctl 0.2.28" "tacctl Manual" .\" The body margin is 7n on every groff: 1.24 narrowed its default (BP) to 5n, which moves the .\" columns that `tacctl man` searches for. .nr BP 7n @@ -418,8 +418,9 @@ The tacctl repo branch to install or upgrade from (default: the current one). Prepare tacctl's state for the release before this one; run on the newer release, before the older one is installed. A dry run by default: it lists every step and every warning and changes nothing. The versions it takes are -.B 0.2.26 +.B 0.2.27 (the release before this one), +.BR 0.2.26 , .BR 0.2.25 , .BR 0.2.24 , .BR 0.2.23 , @@ -440,12 +441,12 @@ and older are refused, with the way there (one release at a time: this rollback, .BR "tacctl upgrade \-\-branch 0.2.9" , then the rollback of that release), and so is any other word (0.2.10 to -0.2.15 included: the refusal names the targets). Every target but 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20 +0.2.15 included: the refusal names the targets). Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22, 0.2.21, 0.2.20 and 0.2.19 is refused while an emergency lockdown locks a group (the refusal lists each one and .B "emergency lockdown disable" lifts it; a release before 0.2.19 would render the locked users back into the -scope; 0.2.19 has the record and keeps it), every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 is refused while an emergency lockdown stands on a scope that has enrolled hosts, or a lifted one still waits for a host to drop sshd's lockdown drop\-in (older releases cannot lift it on a host; lift it and sync the hosts first), and every target is refused while a device's record says a confirmed commit of +scope; 0.2.19 has the record and keeps it), every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 is refused while an emergency lockdown stands on a scope that has enrolled hosts, or a lifted one still waits for a host to drop sshd's lockdown drop\-in (older releases cannot lift it on a host; lift it and sync the hosts first), and every target is refused while a device's record says a confirmed commit of .B "device config apply" is .B pending @@ -460,7 +461,7 @@ settles it). The and .B users mappings of console.yaml that this release ignores stay in the file, and a -release before 0.2.20 (the targets 0.2.19 and older; 0.2.26 to 0.2.20 ignore +release before 0.2.20 (the targets 0.2.19 and older; 0.2.27 to 0.2.20 ignore them too, and their rollback says nothing of it) reads them as it always did: a user or a tier switched off there gets a plain shell again, and the password cache is on again for every user of a tier that is allowed it, so the plan lists each user who @@ -468,7 +469,7 @@ would gain a system shell or the cache, with the reason, as a warning that .B \-\-apply refuses without .BR \-\-yes . -Every target before 0.2.20 (0.2.19 and older; 0.2.26 to 0.2.20 read them and leave them) also takes out of +Every target before 0.2.20 (0.2.19 and older; 0.2.27 to 0.2.20 read them and leave them) also takes out of .I console.yaml the settings of 0.2.20 that no release before it reads: .BR settings.color , @@ -484,7 +485,7 @@ stay, for the releases that have them) are removed and a of \-1 (never ask) is written as 1000, with every other setting kept and a snapshot first. .IP -Every target but 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22 and 0.2.21, which have it themselves, keeps every user's +Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22 and 0.2.21, which have it themselves, keeps every user's login to this server: an older release answers it only for the users that have the server's scope .RB ( tacctl ) @@ -493,16 +494,16 @@ to the server and lacks it (it counts and names them; a warning, so .B \-\-apply needs .BR \-\-yes ), -after a snapshot. Every target but 0.2.26, 0.2.25, 0.2.24, 0.2.23 and 0.2.22 removes +after a snapshot. Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24, 0.2.23 and 0.2.22 removes .B server.name (the name of .BR "server name" ), -and every target but 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22 and 0.2.21 +and every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22 and 0.2.21 .B server.addresses as well, from .IR tacctl.yaml , which no older release knows; the host registry keeps the address in this -server's entry. Every target but 0.2.26, 0.2.25, 0.2.24, 0.2.23 and 0.2.22 also removes the timing scale: +server's entry. Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24, 0.2.23 and 0.2.22 also removes the timing scale: .B device.timeout_scale and .B timeout_scale_scope.\fIscope\fR @@ -517,7 +518,7 @@ key it does not know). It is a note in the plan, not a warning: the older release connects to every device with its fixed timings again, which a slow or distant device may not meet, and the values stay in the snapshot. .IP -Every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 removes the users' email addresses +Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 removes the users' email addresses .RB ( "user email" , .BR "user add \-\-email" ) from @@ -545,7 +546,7 @@ snapshot and the users. A store that cannot be read refuses every target. Until the older release is installed, the two verbs that set an address write the key again, and the command says so. .IP -Every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 writes the SNMP credential files +Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 writes the SNMP credential files .RI ( snmp.yaml , .IR snmp/ scope .yaml , .IR snmp/devices/ name .yaml ) @@ -574,7 +575,7 @@ the audit line adds and the apply names .BR "tacctl backup recover \-\-only snmp\-users" . .IP -Every target but 0.2.26, 0.2.25, 0.2.24 and 0.2.23 drops from +Every target but 0.2.27, 0.2.26, 0.2.25, 0.2.24 and 0.2.23 drops from .I state/staging the entries marked .B covered @@ -588,7 +589,7 @@ A clone that still waits for its .B "device rename \-\-replace" loses its entry, and after a re-upgrade the verb refuses it as not staged: remove the clone and clone again from the original, or restore the snapshot. Every other entry stays. .IP -Every target but 0.2.26, 0.2.25 and 0.2.24 removes the break\-glass firewall: the key +Every target but 0.2.27, 0.2.26, 0.2.25 and 0.2.24 removes the break\-glass firewall: the key .B breakglass.firewall (when set; every older release refuses it, so it is removed after the snapshot like the other keys they do not know), the nftables table @@ -634,7 +635,7 @@ and then .BR "systemctl daemon\-reload" . .IP -Every target before 0.2.26 (0.2.25 and older; 0.2.26 reads the limits and keeps them) removes the limits of the stored reports of +Every target before 0.2.26 (0.2.25 and older; 0.2.26 and 0.2.27 read the limits and keep them) removes the limits of the stored reports of .BR "device reports" : the settings .B reports.max_size @@ -684,14 +685,72 @@ again (with .B \-\-yes while a user has a limit of their own). .IP +Every target removes the file transfer settings of the console, +.B settings.file_transfer +in +.I console.yaml +.RB ( "console file\-transfer" ), +the target +.B 0.2.27 +included: no release before 0.2.28 reads the key (its reader answers +.BR "settings: unknown key" , +the console falls back to its defaults and the commands that write the file +fail). It goes after the snapshot, with the other settings of the file the +target does not know, every other setting stays, and the dry run lists the key +with what it held (the tiers, and how many user switches, quotas and rates). +It needs no +.BR \-\-yes . +When it was removed the command ends with a note: until the older release is +installed, run no +.B "console file\-transfer" +that sets something, which writes the key again (run the rollback again if one +was run), and the snapshot may be restored with this release only. +.IP +.B "rollback 0.2.27" +converts only the file transfer settings of +.IR console.yaml : +this release changed no other stored file 0.2.27 reads strictly (how +the answer of a Cisco IOS device to a long command is read, and the +documentation, are all that moved), so 0.2.27 reads every other file this release +writes. It removes no other key and no field (the limits of the stored reports, the +settings +.B reports.max_size +and +.B reports.max_count +and a user's own limits, stay: 0.2.27 has them, and so do the break\-glass firewall and its setting, the +email addresses, the SNMP credential files, the covered staging entries, the +server name, the timing scale, the server address, the users' login to this +server and an emergency lockdown, with or without enrolled hosts), leaves the +per\-tier sudoers drop\-in (0.2.27 and this release write the same text), the +pull records, every report in the users' homes, the PDF ones included (0.2.27 +has the format and reads them), and the marker +.I /var/lib/tacctl/pdf\-tools\-offered +(the packages +.B weasyprint +and +.B fonts\-dejavu\-core +stay installed), takes the snapshot of +.B \-\-apply +only when the file transfer settings are set (otherwise it takes none) and needs no +.BR \-\-yes . +It is refused only while a device's apply is not settled. +.B \-\-hosts +is accepted and does nothing. The command ends with the next step, +.BR "tacctl upgrade \-\-branch 0.2.27" , +with no note to follow but the one above when the settings were removed: the +limits and the reports are 0.2.27's own. +.IP .B "rollback 0.2.26" -converts nothing: this release changed no stored file 0.2.26 reads strictly (what +converts only the file transfer settings of +.IR console.yaml : +0.2.27 and this release changed no other stored file 0.2.26 reads strictly (what the .B "show switch" reader accepts, what the reports of a user below the operator tier hold, the audit -line of a prune of other users' reports, the wording of two notes and the -documentation are all that moved), so 0.2.26 reads every file this release -writes. It removes no key and no field (the limits of the stored reports, the +line of a prune of other users' reports, the PDF format of the reports and the offer +of its tools, how the answer of a Cisco IOS device to a long command is read, the wording of two notes and the +documentation are all that moved), so 0.2.26 reads every file 0.2.27 and this release +write. It removes no other key and no field (the limits of the stored reports, the settings .B reports.max_size and @@ -700,19 +759,19 @@ and a user's own limits, stay: 0.2.26 has them, and so do the break\-glass firew email addresses, the SNMP credential files, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown, with or without enrolled hosts), leaves the -per\-tier sudoers drop\-in (0.2.26 and this release write the same text), the -pull records and every report in the users' homes (0.2.26 reads them), takes no -snapshot and needs no +per\-tier sudoers drop\-in (0.2.26, 0.2.27 and this release write the same text), the +pull records and every report in the users' homes (0.2.26 reads them; a PDF one as text, see Rolling back in the upgrading page), takes the snapshot +only when the file transfer settings are set and needs no .BR \-\-yes . It is refused only while a device's apply is not settled. .B \-\-hosts is accepted and does nothing. The command ends with the next step, .BR "tacctl upgrade \-\-branch 0.2.26" , -with no note to follow: the limits and the reports are 0.2.26's own. +with no note to follow but the one above when the settings were removed: the limits and the reports are 0.2.26's own. .IP .B "rollback 0.2.25" -removes the limits of the stored reports of 0.2.26 and this release and converts nothing -else: 0.2.25 reads every other file 0.2.26 and this release write (the break\-glass +removes the limits of the stored reports of 0.2.26, 0.2.27 and this release and converts nothing +else but the file transfer settings of the console: 0.2.25 reads every other file 0.2.26, 0.2.27 and this release write (the break\-glass firewall and its setting, the email addresses, the SNMP credential files, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown, with or without @@ -739,7 +798,7 @@ refuses without naming each user and the values (see below). The per\-tier sudoers drop\-in is rewritten, after .BR "visudo \-cf" , -with the text 0.2.25 wrote, the text of 0.2.26 and this release without the rows of +with the text 0.2.25 wrote, the text of 0.2.26, 0.2.27 and this release without the rows of .BR "device reports" , when the file is exactly that text (no snapshot holds it; a file tacctl did not write is left). The @@ -748,7 +807,7 @@ of the pull records are left (0.2.25's decoder ignores the key), and so is every report in the users' homes: they are the users' own files, and 0.2.25 has no .B "device reports" verb to list or remove them. When the snapshot was taken, the next steps say -that it holds the 0.2.27 state and is to be restored with 0.2.27 only, and what +that it holds the 0.2.28 state and is to be restored with 0.2.28 only, and what 0.2.25's restore refuses: a tacctl.yaml with a key it does not know when a setting was removed, a store.yaml with a field it does not know when only a user's own limit was, both when both were. The command ends @@ -786,19 +845,19 @@ is accepted and does nothing. The command ends with the next step, .B "rollback 0.2.23" converts no file but the key .B breakglass.firewall -(0.2.24's) and the limits of the stored reports (0.2.26's; when either is set the snapshot is taken): 0.2.24 to 0.2.26 and this release changed no other stored file, so 0.2.23 reads every file they +(0.2.24's) and the limits of the stored reports (0.2.26's; when either is set the snapshot is taken): 0.2.24 to 0.2.27 and this release changed no other stored file, so 0.2.23 reads every file they write (the email addresses, the SNMP credential files, the covered staging entries, the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown, with or without enrolled hosts, all stay), the per\-tier sudoers drop\-in is put back as 0.2.23 wrote it (without the operator's .BR "log failures *" ; -when it is exactly the text of 0.2.24 and 0.2.25, or the one 0.2.26 and this release write, it is rewritten, after +when it is exactly the text of 0.2.24 and 0.2.25, or the one 0.2.26, 0.2.27 and this release write, it is rewritten, after .BR "visudo \-cf" , and any other file is left), no snapshot is taken for them and .B \-\-yes is never needed unless a user has an own limit of the stored reports. When the key was set the snapshot was taken, and the next steps -say that it holds the 0.2.27 state and is to be restored with 0.2.27 only +say that it holds the 0.2.28 state and is to be restored with 0.2.28 only (0.2.23's restore refuses its tacctl.yaml, which has the key). It is refused only while a device's apply is not settled. Every older target that rewrites that drop\-in recognises this release's text, 0.2.25's and 0.2.23's as tacctl's own and puts back its own. @@ -831,7 +890,7 @@ converts nothing but the email addresses, the SNMP credential files, the covered with 0.2.22's: the engineer's rule of .B "device clone" is taken out; an edited drop\-in is left): 0.2.22 -reads every other file 0.2.23 to 0.2.26 and this release write, so the server name, the timing +reads every other file 0.2.23 to 0.2.27 and this release write, so the server name, the timing scale, the server address, the users' login to this server and an emergency lockdown (of scopes with no enrolled host) stay. With no address in the store, no SNMP @@ -956,7 +1015,7 @@ An older release lints such a block as an error and plans nothing for the devices it reaches. The block files are not rewritten; take the statements out before the upgrade. .IP -Every target before 0.2.20 (0.2.19 and older; 0.2.26 to 0.2.20 read it and leave it) removes the management filter mode of the scopes +Every target before 0.2.20 (0.2.19 and older; 0.2.27 to 0.2.20 read it and leave it) removes the management filter mode of the scopes .RB ( scope_mgmt_acl.mode.\fIscope\fR , only .B strict @@ -978,7 +1037,7 @@ or would put that filter back on a device that holds the strict one, without saying so. The rollback is not refused, and no device is contacted. .IP -Every target but 0.2.26 to 0.2.20 (which read it) removes the required password change +Every target but 0.2.27 to 0.2.20 (which read it) removes the required password change .RB ( password_change_required of a user in .IR store.yaml , @@ -10518,7 +10577,7 @@ Logs in once to a registered device and collects what a developer needs to make .B "show cli authorization"\c ), the commit history and the difference to rollback 0; IOS, the version, the inventory, the switch stack, the modules, the clock, the privilege level and the lines of the running configuration that name the device; a WTI unit, the screens its pull reads, without the user directory. For all three, the SNMP system group is added when SNMP is set up. The configuration itself is not collected: the Junos difference to rollback 0 is the candidate's changes only, and the IOS lines are those that name the device. .IP -The text is scrubbed before it is written: host names, domains, users, classes, addresses, MAC addresses, serial numbers, locations, contacts and time zones become the standard example values (the same real value always the same example), the free text of a commit comment is removed (tacctl's own comments stay), and anything that looks like a secret, a hash or a key is removed. Serial numbers are replaced by their field, whatever their length, case or digits: the SN: value of the inventory, Hw Serial# (also inside a quoted DESCR:), Processor board ID, System serial number, the generic Serial number: field and the Junos Serial ID of a routing engine; the value runs to the next blank, comma or quote and ends at its last letter or digit, so the punctuation after it stays. So is the serial cell of every row of the chassis hardware and virtual chassis tables, cut at the column its header gives: any word there with a letter or digit is a serial, except the status words (Prsnt, NotPrsnt, Unprvsnd, Absent, Present, Inactive, Online, Offline, Master, Backup, Linecard, Spare, Empty, in any case). A table ends at a blank line, a line of one word and a colon, or a prompt line that begins with a brace; a row with nothing in or after the serial column stays inside it. A tab\-separated row is cut at its tabs: with as many cells as the header it has its serial at the header\(aqs column, with fewer it has it by shape (the one cell that is a word with a digit, or the one after the part number), and a cell with a hyphen (a part number, a model) is never a serial. An empty or BUILTIN cell stays, and so does the Description column. Any other token with the shape of a serial number (eight to fourteen capitals and digits, with both) is replaced too, except an example value, an image name (K9), a model name and the quoted DESCR: text. Model names stay as the device printed them: the values after PID: and VID:, the quoted DESCR: string, the model of the Model: line, of the \(lqcisco (...) processor\(rq line (the \(lqCisco (revision ...)\(rq line of IOS) and of the \(lqCisco IOS Software, Software\(rq line, and every model name the files of the bundle state, in all the files; only the model is kept, never the rest of its line. An object identifier (a dotted run that begins 1.3.6.1.) is not an address; the digits around any other address do not make it one. The host names of vendors and standards bodies stay when they are the bare domain (cisco.com, juniper.net, hpe.com, hp.com, gnu.org, fsf.org, openssl.org, ietf.org, kernel.org) or have one of the labels www, tools, ftp, cdn, software or support in front of it; a mail address, any other name under those domains and any name under a domain the files state as the owner\(aqs are replaced (only the example.* names stay). The parent domain of every host name that is replaced is the owner\(aqs too, so after acme\-corp.hpe.com is replaced, hpe.com and www.hpe.com are replaced in every file of the bundle; a public label is never replaced as a word of its own. The columns after a replacement keep their place. A Cisco session also drops the echo of a command longer than the terminal is wide, so the first file line is the device\(aqs answer. A text that still holds a value the scrubber learned to replace is not written. What was replaced is kept in a private file beside the directory, \fIname\fR\fB.map\fR (mode 0600, the real values), never in it; read the files before sharing them. +The text is scrubbed before it is written: host names, domains, users, classes, addresses, MAC addresses, serial numbers, locations, contacts and time zones become the standard example values (the same real value always the same example), the free text of a commit comment is removed (tacctl's own comments stay), and anything that looks like a secret, a hash or a key is removed. Serial numbers are replaced by their field, whatever their length, case or digits: the SN: value of the inventory, Hw Serial# (also inside a quoted DESCR:), Processor board ID, System serial number, the generic Serial number: field and the Junos Serial ID of a routing engine; the value runs to the next blank, comma or quote and ends at its last letter or digit, so the punctuation after it stays. So is the serial cell of every row of the chassis hardware and virtual chassis tables, cut at the column its header gives: any word there with a letter or digit is a serial, except the status words (Prsnt, NotPrsnt, Unprvsnd, Absent, Present, Inactive, Online, Offline, Master, Backup, Linecard, Spare, Empty, in any case). A table ends at a blank line, a line of one word and a colon, or a prompt line that begins with a brace; a row with nothing in or after the serial column stays inside it. A tab\-separated row is cut at its tabs: with as many cells as the header it has its serial at the header\(aqs column, with fewer it has it by shape (the one cell that is a word with a digit, or the one after the part number), and a cell with a hyphen (a part number, a model) is never a serial. An empty or BUILTIN cell stays, and so does the Description column. Any other token with the shape of a serial number (eight to fourteen capitals and digits, with both) is replaced too, except an example value, an image name (K9), a model name and the quoted DESCR: text. Model names stay as the device printed them: the values after PID: and VID:, the quoted DESCR: string, the model of the Model: line, of the \(lqcisco (...) processor\(rq line (the \(lqCisco (revision ...)\(rq line of IOS) and of the \(lqCisco IOS Software, Software\(rq line, and every model name the files of the bundle state, in all the files; only the model is kept, never the rest of its line. An object identifier (a dotted run that begins 1.3.6.1.) is not an address; the digits around any other address do not make it one. The host names of vendors and standards bodies stay when they are the bare domain (cisco.com, juniper.net, hpe.com, hp.com, gnu.org, fsf.org, openssl.org, ietf.org, kernel.org) or have one of the labels www, tools, ftp, cdn, software or support in front of it; a mail address, any other name under those domains and any name under a domain the files state as the owner\(aqs are replaced (only the example.* names stay). The parent domain of every host name that is replaced is the owner\(aqs too, so after acme\-corp.hpe.com is replaced, hpe.com and www.hpe.com are replaced in every file of the bundle; a public label is never replaced as a word of its own. The columns after a replacement keep their place. A Cisco session also drops the echo of a command longer than the terminal is wide, so the first file line is the device\(aqs answer; when only the tail of that echo reaches the session (a line of \fB$\fR and the rest of the command), the tail is dropped as well. A text that still holds a value the scrubber learned to replace is not written. What was replaced is kept in a private file beside the directory, \fIname\fR\fB.map\fR (mode 0600, the real values), never in it; read the files before sharing them. .IP The login is the one of .BR "device config pull" : @@ -14399,7 +14458,9 @@ List the reports of every user tacctl knows, one audit line for the whole listin Print the facts of a report: the file, the type, when it was made, by whom, the command line, the filters, the date of the oldest datum, the format, the rows, the size and the command that fetches it -.RB ( "scp user@server:reports/devices/ ." ). +.RB ( "scp user@server:reports/devices/ ." ; +the console serves it only if file transfer is enabled for the user, see +.BR "console file\-transfer" ). .B \-\-content adds the first 200 lines of the report, read from the start of the file and no further than 256 KiB (a file with more says that, and counts the lines only when it @@ -15563,7 +15624,8 @@ The settings, and for each user of the scope of the host enrolled with .B \-\-local the tier, the effective shell .RB ( console ) -and why. Then the state of the server's pieces: the +and why, the system shell and the file transfer of the user (state, quota and +rate, with the reason). Then the state of the server's pieces: the .I /usr/local/bin/tacctl\-console symlink, the .I /etc/shells @@ -15574,9 +15636,15 @@ reports for a console user .RB ( allowtcpforwarding , .BR allowagentforwarding , .BR forcecommand , -.BR pubkeyauthentication ). +.BR pubkeyauthentication ), +and whether sshd defines an sftp subsystem +.RB ( "sshd sftp subsystem: " \fIprogram\fR +or +.BR none ). A red warning appears when the drop-in is missing, sshd does not force the -console, still allows forwarding, or allows key logins. A server not enrolled +console, still allows forwarding, or allows key logins, and another when file +transfer is on for a tier other than the superuser tier, or for a user, and +sshd defines no sftp subsystem. A server not enrolled with .B \-\-local says so and lists no users. @@ -16000,6 +16068,138 @@ The system shell, default It must be an absolute path to an executable file listed in .IR /etc/shells . .TP +.BI "console file\-transfer " "[ " tier " { enable | disable } ]" +Show or set who may transfer files to and from their home through the console. +The console serves SFTP only +.RB ( sftp +and the +.B scp +of OpenSSH 9 or later; see +.BR "Console sessions" ), +for the accounts that have it. It is off for every tier but the superuser tier +by default. With no argument it lists each tier +.RB ( readonly ", " operator ", " engineer ", " superuser ) +as +.B enabled +or +.BR disabled , +then the users that have a switch of their own, with their tier, and whether +sshd defines an sftp subsystem +.RB ( "sshd sftp subsystem:" ): +sshd starts the subsystem only if its configuration has +.BR "Subsystem sftp ..." , +which a +.B Match +block cannot define, so a red warning follows when file transfer is on for a +tier other than the superuser tier, or for a user, and there is none. The superuser +tier is +.B "enabled (always)" +and cannot be disabled. Unlike the system shell, the engineer tier can be +given it: a transfer reaches the user's home only, where a shell or a +forwarded port would reach the server. A tier name alone prints that tier's +state. Setting a tier writes +.BR settings.file_transfer.tiers . +Every form of this command, the reads included, is the +superuser\(aqs and is refused for the lower tiers (logged as a tier denial); +each user\(aqs state, quota and rate are in +.BR "console show" , +which the operator tier and up can run. The change is logged as +.BR "console set key=file\-transfer item=" \fItier\fR +at +.BR auth.notice . +It applies from the next console login. +.\" BEGIN GENERATED: command console file-transfer +.RS +.PP +Requires: \fBsuperuser\fR. +.RE +.\" END GENERATED: command console file-transfer +.TP +.BI "console file\-transfer user " "name " "[ { enable | disable | clear } ]" +Show or set file transfer for one user, over the tier's setting in both +directions: enabled, it gives a user of a tier that has none file transfer; +disabled, it takes it from a user of a tier that has it. Without a value it +prints the user's effective state and why +.RB ( "user setting" ", " "tier operator" ", " always ). +.B clear +removes the user's setting, and the tier decides again. The user must exist. +An enable is for the tier the user has when it is set +.RB ( readonly , +.B operator +or +.BR engineer ): +after a move to another tier it gives nothing and is listed as +.BR "stale: set for" " \fItier\fR" ", now " \fItier\fR +until it is set again; a disable holds in any tier. A superuser always has +file transfer: disabling it is refused, and enabling it stores nothing. The +settings are kept in +.B settings.file_transfer.users +and are logged as +.BR "console set key=file\-transfer item=user:" \fIname\fR. +.B "user rename" +moves the setting, the quota and the rate of the user to the new name and +.B "user remove" +drops them (both say so and are logged as +.BR "console set" ), +so a user created later under the name does not inherit them. An entry for a +name that is no user is listed with +.BR "no such user" , +and +.B clear +removes it. +.TP +.BI "console file\-transfer quota " "[ " tier " { " size " | unlimited | default } ]" +Show or set the quota: the bytes the whole home of a user may hold. With no +argument it lists the quota of each tier and the users that have one of their +own; a tier alone prints that tier's. Nothing set is the built-in default, +256M for the readonly, operator and engineer tiers and +.B unlimited +for the superuser tier. A size is a number of bytes, or a number with +.BR K , +.BR M , +.B G +or +.B T +(powers of 1024), such as +.BR 512K , +.B 256M +or +.BR 2G ; +it is printed back in the largest unit that holds it exactly. Zero, a negative +number, a fraction, a number that overflows and more than 1T are refused; +.B unlimited +is no limit and, for a tier, +.B default +returns it to the built-in value. A tier's quota is stored in +.BR settings.file_transfer.quota . +.TP +.BI "console file\-transfer quota user " "name " "[ { " size " | unlimited | clear } ]" +Show or set the quota of one user, which wins over the tier's. Without a value +it prints the effective quota and where it comes from +.RB ( "user setting" ", " "set for the operator tier" ", " default ). +.B clear +removes the user's own quota, and the tier decides again. The user must exist +to be given one. It is stored in +.BR settings.file_transfer.quota_users . +.TP +.BI "console file\-transfer rate " "[ " tier " { " size " | off } ]" +Show or set the rate: the bytes a second a transfer may go at. It is off, no +limit, for every tier by default. Sizes are those of +.BR quota ; +.B off +removes the limit of a tier. With no argument it lists the rate of each tier +and the users that have one of their own. A tier's rate is stored in +.BR settings.file_transfer.rate . +.TP +.BI "console file\-transfer rate user " "name " "[ { " size " | off | clear } ]" +Show or set the rate of one user, which wins over the tier's: +.B off +gives the user no limit whatever their tier has, +.B clear +returns them to the tier's. It is stored in +.BR settings.file_transfer.rate_users , +and follows the user like the quota. +.TP .B console install Puts the server's pieces in place, as .B host sync @@ -16016,7 +16216,9 @@ for the members of .B "ForceCommand /usr/local/bin/tacctl\-console" (every login, remote command and subsystem, sftp included, reaches the console, which reads the client's command from -.BR SSH_ORIGINAL_COMMAND ), +.BR SSH_ORIGINAL_COMMAND ; +it serves one tacctl line, or the sftp subsystem for an account that has file +transfer), .B "DisableForwarding yes" (left out, with .BR "AllowAgentForwarding yes" , @@ -16190,15 +16392,23 @@ not while a line runs). .BI "\-c " line (the remote command sshd passes: .BR "ssh " "\fIserver\fR " "'user list'" ) -runs one tacctl line, with the connection as its standard input. A string +runs one tacctl line, with the connection as its standard input, or serves +the sftp subsystem (the command is the program of sshd's +.B Subsystem sftp +line, such as +.IR /usr/lib/openssh/sftp-server +or +.IR internal\-sftp , +which ForceCommand hands over in +.BR SSH_ORIGINAL_COMMAND ), +described below. A string that is not one line beginning with a tacctl command or .B help \(em -.BR scp , -.BR sftp , +.BR "scp \-O" , .BR rsync , any program, the shell's own words, an empty string \(em is refused with -.I "the tacctl\~console does not run programs; file transfer is not available" +.I "the tacctl\~console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)" and exit status 126, and nothing runs. Any other argument is refused the same way .RI ( "the tacctl\~console takes no options" ). @@ -16213,6 +16423,94 @@ A word that starts with an underscore at the prompt or in a batch the entry points of the scripts, the key and the console itself) is not a command there: it is answered as any word that is no command, and nothing runs. .PP +The sftp subsystem is served by the console itself, on its standard input and +output, as the logged-in user (no change of privilege), rooted in the home +directory the account database names (never +.BR $HOME ): +.B / +is the home, a relative path starts there and +.B .. +does not leave it, +.B .ssh +is not listed and every request for it is refused, no symbolic link is followed, +and neither a symbolic link nor a hard link can be created through the console. +A file that already has more than one name (a hard link made outside SFTP) +cannot be opened, downloaded or written, and its mode and times cannot be +changed (refused, reason +.BR link ): +it can still be listed, renamed and removed. Setting the mode of a directory +without the owner's read and search bits is refused. The size of a regular file +can be set (cut, or extended with zeros), which is what +.B scp +does after an upload to give the file its final size; it counts against the quota +like a write. The owner cannot be changed, and a request that asks for it is +refused whole. A new directory gets the mode the client asks for and a new file +0644, both reduced by the umask of the console, 077; the set\-user\-ID, +set\-group\-ID and sticky bits are ignored, and a client that wants another mode +sets it afterwards, which is applied as given. Changing the mode or the times of +a file goes through +.BR /proc/self/fd , +so file transfer needs +.B /proc +mounted on the server. A listing is in the order +of the file system, not sorted (the OpenSSH +.B sftp +client sorts what its +.B ls +prints). A session has at most 256 files and listings open at once (reason +.BR too\-many\-open\-files ). +The quota +.RB ( "console file\-transfer quota" ) +is the bytes the home may hold: the sizes of its regular files, each inode once +(not directories, links or inodes), reports, support bundles and +.B .ssh +included; a write over it is refused whole +.RB ( "disk quota exceeded" ), +and so is a size that would grow a file over it; a smaller size gives the room back. +An upload that is refused part way leaves what was written before the refusal in the +home (the client does not remove it), and the +.B sftp +and +.B scp +of OpenSSH show only +.B Failure +for it: the reason, +.BR reason=quota , +is in the console's audit log. +It is measured per session, so N sessions at once can reach about N times the +quota; a file deleted while a handle still holds it stays counted until the +handle is closed; and a directory in the home that the session cannot read or +search (for example one owned by root with mode 0700) makes the home count as +full, so that every upload that grows it is refused with +.B disk quota exceeded +until the directory is readable. The rate +.RB ( "console file\-transfer rate" ) +is the bytes a second the session may move, reads and writes together. The +subsystem is refused with status 126 and +.I "file transfer is not enabled for this account; an administrator can switch it on (tacctl console file\-transfer)" +when the account does not have file transfer (and with a text of its own when a +password change is required or the policy cannot be read); the OpenSSH +.B sftp +and +.B scp +show only +.B Connection closed +then, since sshd does not show the error text of a subsystem, and the reason, +.BR reason=file\-transfer , +is in the audit log. The idle timeout +does not apply: the session lasts as long as the connection and ends with +status 0 when the client closes it; a protocol error ends it with status 1 and +one line on standard error. Nothing but protocol is written to standard output; +if +.B logger +cannot write an audit line, the warning +.B The audit line was not written (logger: reason); the command continues. +can appear on standard error and the transfer goes on, unaudited. +sshd starts the subsystem only if its configuration defines +.BR "Subsystem sftp ..." ; +see +.BR "console file\-transfer" . +.PP A user who must change the password .RB ( "user require\-password\-change" ; never a superuser) gets, at the start of the console, a notice (\fBA password @@ -16288,8 +16586,8 @@ it is refused with status 126. .PP Syslog (tag .BR tacctl\-console ): -.BI "console start session=" id " user=" user " from=" address " tty=" tty " mode=" interactive|command|batch\fR, -.BI "console end session=" id " user=" user " reason=" exit|eof|idle|hangup|signal|command|failed|locked " lines=" n " status=" n\fR, +.BI "console start session=" id " user=" user " from=" address " tty=" tty " mode=" interactive|command|batch|sftp\fR, +.BI "console end session=" id " user=" user " reason=" exit|eof|idle|hangup|signal|command|failed|locked|sftp " lines=" n " status=" n\fR, .BI "console DENY session=" id " user=" user " reason=command first=" verb|\- " [len=" n ] (auth.warning; the word is the first word of the refused string when it is a verb of tacctl or one of the console's own words, else @@ -16298,6 +16596,22 @@ and .B len= is the length of the string, so a password typed at the prompt is never in the log), +.BI "console DENY session=" id " user=" user " reason=file\-transfer|password\-change|policy|home|stream subsystem=sftp" +(the sftp subsystem refused), +.BI "console sftp start session=" id " user=" user " tier=" tier " from=" address " home=" \(dqpath\(dq " quota=" size|unlimited " rate=" size|off\fR, +.BI "console sftp " "upload|download|delete|rename|mkdir|setstat" " session=" id " user=" user " tier=" tier " path=" \(dqpath\(dq " [to=" \(dqpath\(dq "] [bytes=" n "] [error=" \(dqtext\(dq ] +(one line for each upload, download and change), +.BI "console sftp DENY session=" id " user=" user " tier=" tier " path=" \(dqpath\(dq " reason=" .ssh|outside\-the\-home|symlink|link|quota|unsupported|bad\-path|too\-many\-open\-files +(auth.warning; a request the server refused, of any kind, a refused readlink or +realpath included; a successful stat, listing, readlink or realpath is not +logged) and +.BI "console sftp end session=" id " user=" user " up=" n " down=" n " ops=" n " refused=" n\fR. +A path is a file name, so unlike a refused string it is logged, but as a quoted +string in which a control character, a quote, a backslash and a byte that is not +UTF-8 are escapes, cut at 200 bytes of the escaped text (a cut name ends with +.B ... +after the closing quote); the error text is cut the same way and does not +repeat the path, so a line stays short enough for logger to keep it whole. .BI "console system\-shell start" \fR, .B end .RB ( status= ", " duration= ) @@ -16624,7 +16938,7 @@ user email, user reports\-limit, user scope .TP .B "mixed, auth.notice" config audit\-strict, config breakglass\-firewall, config sudoers, -console system\-shell, rollback, store import +console file\-transfer, console system\-shell, rollback, store import .\" END GENERATED: audit-classes .PP The fields, in the order written: @@ -18298,6 +18612,10 @@ Whether the console's lists are in colour: true (on) or false (off). Written to .B settings.system_shell_users mapping of user name to disable or enable:. Default: absent (no user has one). The users with a system-shell setting of their own, which wins over their tier's: enable: gives it to a user of a tier that has none, for as long as the user is in that tier (readonly or operator), and disable takes it from a user of a tier that has it. Written to the file only when a user has one. Set with \fBtacctl console system\-shell user\fR. +.TP +.B settings.file_transfer +mapping (tiers, users, quota, quota_users, rate, rate_users). Default: absent (nothing set). +The console's file transfer: the tiers that have it (tiers, the superuser tier always among them), the users with a switch of their own (users, a mapping of user name to disable or enable:), the quota of the home in bytes (quota per tier and quota_users per user: a size such as 256M, or unlimited) and the rate in bytes per second (rate and rate_users: a size, and off for a user). Off for every tier but the superuser tier by default; a user's own value wins over the tier's. Written only when something in it is not the built-in setting. Set with \fBtacctl console file\-transfer\fR. .\" END GENERATED: console-keys .PP A mapping diff --git a/tests/integration/console.bats b/tests/integration/console.bats index 12c37336..c0794a47 100644 --- a/tests/integration/console.bats +++ b/tests/integration/console.bats @@ -88,13 +88,13 @@ console_log() { grep '^logger -t tacctl-console ' "$CALLS_LOG" | sed 's/^logger assert_line --index 1 "sudo -n TACCTL_CONSOLE=0123456789ab ${EXE} user list" } -@test "console -c: scp, sftp, rsync, programs and the shell's own words are refused, exit 126, nothing run" { +@test "console -c: scp -O, rsync, programs and the shell's own words are refused, exit 126, nothing run" { local line while IFS= read -r line; do : > "$CALLS_LOG" run "$CONSOLE_BIN" -c "$line" assert_failure 126 - assert_output "the tacctl console does not run programs; file transfer is not available" + assert_output "the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)" run sudo_lines assert_output "" run console_log @@ -104,7 +104,7 @@ console_log() { grep '^logger -t tacctl-console ' "$CALLS_LOG" | sed 's/^logger done <<'LIST' scp -t . scp -f /etc/passwd -/usr/lib/openssh/sftp-server +scp -O -f x rsync --server -vlogDtpre.iLsfxC . /tmp bash sh -c id @@ -146,7 +146,7 @@ LIST @test "console < file: the lines run in order as a batch; system-shell is refused there" { run bash -c 'printf "user list\nsystem-shell\nuser list\n" | "$0"' "$CONSOLE_BIN" assert_failure 126 - assert_output --partial "the tacctl console does not run programs; file transfer is not available" + assert_output --partial "the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)" run sudo_lines assert_line --index 1 "sudo -n TACCTL_CONSOLE=0123456789ab ${EXE} user list" [ "${#lines[@]}" -eq 2 ] @@ -256,7 +256,7 @@ exec "$@"' assert_output --partial "session=0123456789ab" } -@test "console under sshd's ForceCommand: the client's command comes from SSH_ORIGINAL_COMMAND; sftp is refused" { +@test "console under sshd's ForceCommand: the client's command comes from SSH_ORIGINAL_COMMAND; the subsystem is refused while file transfer is off" { # sshd runs ' -c ' with the client's command aside. SSH_ORIGINAL_COMMAND="user list" run "$CONSOLE_BIN" -c "$CONSOLE_BIN" assert_success @@ -264,13 +264,19 @@ exec "$@"' run sudo_lines assert_line --index 1 "sudo -n TACCTL_CONSOLE=0123456789ab ${EXE} user list" : > "$CALLS_LOG" - for sub in internal-sftp /usr/lib/openssh/sftp-server "scp -t /tmp"; do + for sub in internal-sftp /usr/lib/openssh/sftp-server; do SSH_ORIGINAL_COMMAND="$sub" run "$CONSOLE_BIN" -c "$CONSOLE_BIN" assert_failure 126 - assert_output --partial "the tacctl console does not run programs; file transfer is not available" + assert_output "file transfer is not enabled for this account; an administrator can switch it on (tacctl console file-transfer)" done + run console_log + assert_line --partial "console DENY session=0123456789ab user=carol reason=file-transfer subsystem=sftp" + : > "$CALLS_LOG" + SSH_ORIGINAL_COMMAND="scp -t /tmp" run "$CONSOLE_BIN" -c "$CONSOLE_BIN" + assert_failure 126 + assert_output "the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)" run sudo_lines refute_output --partial " ${EXE} " run console_log - assert_line --partial "console DENY session=0123456789ab user=carol reason=command first=- len=13" + assert_line --partial "console DENY session=0123456789ab user=carol reason=command first=- len=11" } diff --git a/tests/integration/console_cli.bats b/tests/integration/console_cli.bats index 48678508..8aca86a9 100644 --- a/tests/integration/console_cli.bats +++ b/tests/integration/console_cli.bats @@ -44,6 +44,9 @@ snapshot_count() { find "${TACCTL_STATE_DIR}/backups" -mindepth 1 -maxdepth 1 -n assert_output --partial "Usage: tacctl console " assert_output --partial "system-shell [ enable|disable]" assert_output --partial "system-shell user [enable|disable|clear]" + assert_output --partial "file-transfer [ enable|disable]" + assert_output --partial "file-transfer quota user [|unlimited|clear]" + assert_output --partial "file-transfer rate user [|off|clear]" assert_output --partial "forwarding tiers [|none]" refute_output --partial " tiers [" refute_output --partial " user [enable|disable|clear]" @@ -56,6 +59,7 @@ snapshot_count() { find "${TACCTL_STATE_DIR}/backups" -mindepth 1 -maxdepth 1 -n plain assert_line --index 0 "Possible completions:" assert_line --regexp "^ system-shell +Show or set the system shell for a tier " + assert_line --regexp "^ file-transfer +Show or set file transfer through the console for a tier " assert_line --regexp "^ forwarding +Show or set the tiers that may forward X11 and TCP ports " refute_output --partial " tiers " refute_output --partial " user " @@ -447,7 +451,7 @@ LIST # A tier user: the id stub puts the caller in tac-users and its tier group. stub_cmd id 'echo "$3 tac-users"' SUDO_USER=alice run "$TACCTL_BIN_SCRIPT" _console-policy - assert_output "shell=console idle=30 system_shell=yes system_shell_path=/bin/bash ssh_escape=no agent=no forward=yes tier=superuser list_max=40 space_completion=yes color=auto" + assert_output "shell=console idle=30 system_shell=yes system_shell_path=/bin/bash ssh_escape=no agent=no forward=yes tier=superuser list_max=40 space_completion=yes color=auto file_transfer=yes ft_quota=0 ft_rate=0" SUDO_USER=bob TACCTL_CONSOLE=0123456789ab run "$TACCTL_BIN_SCRIPT" _console-policy assert_output "shell=console idle=30 system_shell=no system_shell_path=/bin/bash ssh_escape=no agent=no forward=no tier=operator list_max=40 space_completion=yes color=auto" stub_called '^logger -t tacctl -p auth.info console policy user=bob tier=operator system_shell=no session=0123456789ab sid=[a-z0-9]{8}$' diff --git a/tests/integration/console_file_transfer.bats b/tests/integration/console_file_transfer.bats new file mode 100644 index 00000000..3fcd8ec5 --- /dev/null +++ b/tests/integration/console_file_transfer.bats @@ -0,0 +1,331 @@ +#!/usr/bin/env bats +# Integration tests for `tacctl console file-transfer`: the switch of a tier +# and of a user, the quota and the rate, the refusals, clear, and the line of +# `_console-policy` that carries them to the console. + +load ../helpers/setup +load ../helpers/tmpenv +load ../helpers/mocks +load ../helpers/fixtures + +setup() { + tacctl_tmpenv_init + tacctl_mocks_init + stub_cmd chown + stub_cmd systemctl + stub_cmd logger + # sshd -T: no sftp subsystem unless a test says so (never the machine's sshd) + stub_cmd sshd 'printf "port 22\nallowtcpforwarding no\nallowagentforwarding no\n"' + load_fixture tacquito.minimal.yaml + # alice (superuser), bob (operator), carol (readonly), all in scope lab. + load_store_fixture store.multiscope.yaml + CONSOLE="${TACCTL_STATE_DIR}/console.yaml" +} + +snapshot_count() { find "${TACCTL_STATE_DIR}/backups" -mindepth 1 -maxdepth 1 -name '2*' | wc -l; } + +# ft: tacctl console file-transfer ... +ft() { "$TACCTL_BIN_SCRIPT" console file-transfer "$@"; } + +@test "console file-transfer: off by default, the superuser tier always has it; a tier is switched, snapshotted, and written as a list" { + run ft + assert_success + assert_output $'readonly: disabled\noperator: disabled\nengineer: disabled\nsuperuser: enabled (always)\n\nsshd sftp subsystem: none' + [[ ! -e "$CONSOLE" ]] + run ft operator + assert_output "disabled" + + local n + n=$(snapshot_count) + run ft operator enable + assert_success + assert_output --partial "File transfer is enabled for the operator tier. It applies from the next console login." + (( $(snapshot_count) == n + 1 )) + [[ "$(stat -c %a "$CONSOLE")" == 600 ]] + # unlike the system shell, the engineer tier is not closed to it + run ft engineer enable + assert_success + run ft + assert_output --partial $'readonly: disabled\noperator: enabled\nengineer: enabled\nsuperuser: enabled (always)\n' + run grep -c '^ tiers: \[operator, engineer, superuser\]$' "$CONSOLE" + assert_output "1" + run ft operator + assert_output "enabled" + + run ft engineer disable + assert_success + run ft operator disable + assert_success + # everything is the built-in setting again: the key is gone from the file + run grep -c file_transfer "$CONSOLE" + assert_output "0" + + # the superuser tier cannot be disabled; enabling it changes nothing + run ft superuser disable + assert_failure 1 + assert_output --partial "The superuser tier always has file transfer; it cannot be disabled. Nothing was changed." + n=$(snapshot_count) + run ft superuser enable + assert_success + assert_output --partial "The superuser tier always has file transfer. Nothing was changed." + (( $(snapshot_count) == n )) +} + +@test "console file-transfer user: a user's setting wins over the tier's, clear gives it back, a superuser cannot be disabled" { + run ft user carol enable + assert_success + assert_output --partial "File transfer is enabled for 'carol' while they are in the readonly tier" + run ft user carol + assert_output "enabled (user setting)" + run ft user bob + assert_output "disabled (tier operator)" + run ft user alice + assert_output "enabled (always)" + + run ft operator enable + run ft user bob disable + assert_success + run ft user bob + assert_output "disabled (user setting)" + run ft + assert_success + assert_output --partial $'operator: enabled\n' + assert_output --partial $'\n\nUsers with a setting of their own:\n bob: disabled (operator)\n carol: enabled (readonly)' + run grep -c "^ users: {bob: disable, carol: 'enable:readonly'}\$" "$CONSOLE" + assert_output "1" + + run ft user bob clear + assert_success + assert_output --partial "The file transfer setting of 'bob' is cleared: the tier decides." + run ft user bob + assert_output "enabled (tier operator)" + run ft user bob clear + assert_success + assert_output --partial "'bob' has no file transfer setting of their own." + run ft user carol clear + run ft operator disable + run grep -c file_transfer "$CONSOLE" + assert_output "0" + + run ft user alice disable + assert_failure 1 + assert_output --partial "'alice' is a superuser, and superusers always have file transfer; it cannot be disabled. Nothing was changed." + run ft user alice enable + assert_success + assert_output --partial "'alice' is a superuser, who always has file transfer. Nothing was changed." + run grep -c file_transfer "$CONSOLE" + assert_output "0" +} + +@test "console file-transfer quota and rate: the defaults, a tier's value, a user's over it, the words, clear" { + run ft quota + assert_success + assert_output $'readonly: 256M (default)\noperator: 256M (default)\nengineer: 256M (default)\nsuperuser: unlimited (default)' + run ft rate + assert_output $'readonly: off (default)\noperator: off (default)\nengineer: off (default)\nsuperuser: off (default)' + + # a size in any form is printed back in the largest exact unit + run ft quota operator 1024M + assert_success + assert_output --partial "The quota of the operator tier is 1G. It applies from the next console login." + run ft quota operator + assert_output "1G (set for the operator tier)" + run ft quota engineer 1500K + run ft quota engineer + assert_output "1500K (set for the engineer tier)" + run ft rate operator 512k + assert_success + assert_output --partial "The rate limit of the operator tier is 512K a second." + run ft rate operator + assert_output "512K (set for the operator tier)" + run grep -c '^ quota: {operator: 1G, engineer: 1500K}$' "$CONSOLE" + assert_output "1" + run grep -c '^ rate: {operator: 512K}$' "$CONSOLE" + assert_output "1" + + # unlimited, off and default + run ft quota operator unlimited + assert_success + assert_output --partial "The operator tier has no quota." + run ft quota operator + assert_output "unlimited (set for the operator tier)" + run ft quota operator default + assert_success + assert_output --partial "The quota of the operator tier is back to its default (256M)." + run ft quota superuser 2G + run ft quota superuser default + assert_output --partial "back to its default (unlimited)" + run ft rate operator off + assert_success + assert_output --partial "The operator tier has no rate limit." + run ft quota engineer default + run grep -cE '^ (quota|rate):' "$CONSOLE" + assert_output "0" + + # a user's own value wins over the tier's, unlimited and off included + run ft quota operator 1G + run ft rate operator 10M + run ft quota user bob 64M + assert_success + assert_output --partial "The quota of 'bob' is 64M." + run ft rate user bob off + assert_success + assert_output --partial "'bob' has no rate limit, whatever their tier has." + run ft quota user carol unlimited + run ft rate user carol 2M + run ft quota user bob + assert_output "64M (user setting)" + run ft rate user bob + assert_output "off (user setting)" + run ft quota user alice + assert_output "unlimited (default)" + run ft rate user dave + assert_failure 1 + assert_output --partial "User 'dave' does not exist." + run ft quota + assert_output --partial $'\n\nUsers with a quota of their own:\n bob: 64M (operator)\n carol: unlimited (readonly)' + run ft rate + assert_output --partial $'operator: 10M (set for the operator tier)' + assert_output --partial $'\n\nUsers with a rate limit of their own:\n bob: off (operator)\n carol: 2M (readonly)' + run grep -c "^ quota_users: {bob: 64M, carol: unlimited}\$" "$CONSOLE" + assert_output "1" + run grep -c "^ rate_users: {bob: 'off', carol: 2M}\$" "$CONSOLE" + assert_output "1" + + run ft quota user bob clear + assert_success + assert_output --partial "The quota of 'bob' is cleared: the tier decides." + run ft quota user bob + assert_output "1G (set for the operator tier)" + run ft quota user bob clear + assert_success + assert_output --partial "'bob' has no quota of their own." + run ft rate user bob clear + run ft rate user carol clear + run ft quota user carol clear + run ft quota operator default + run ft rate operator off + run grep -c file_transfer "$CONSOLE" + assert_output "0" +} + +@test "console file-transfer: console show lists the tiers' state, quota and rate and each user's next to the system shell" { + printf 'authsrv|local||lab|127.0.0.1|\n' > "${TACCTL_STATE_DIR}/linux-hosts" + ft operator enable + ft quota operator 1G + ft user carol enable + ft rate user carol 1M + run "$TACCTL_BIN_SCRIPT" console show + assert_success + output=$(sed 's/\x1b\[[0-9;]*m//g' <<< "$output") + assert_output --partial $'File transfer (off by default; a user\'s own setting wins over the tier\'s):\n readonly: disabled, quota 256M (default), rate off (default)\n operator: enabled, quota 1G, rate off (default)' + assert_output --partial "SYSTEM SHELL" + assert_output --regexp "FILE TRANSFER +QUOTA +RATE" + assert_output --regexp "alice +superuser .*enabled \(always\) +unlimited +off" + assert_output --regexp "bob +operator .*enabled \(tier operator\) +1G +off" + assert_output --regexp "carol +readonly .*enabled \(user setting\) +256M +1M" +} + +@test "console file-transfer: bad arguments exit 1 with the usage or the reason and write nothing" { + local args + while IFS= read -r args; do + run ft $args + assert_failure 1 + done <<'LIST' +mode +root enable +operator maybe +operator enable extra +user +user bob maybe +user bob enable extra +user nobody enable +quota mode 1G +quota operator 0 +quota operator 1.5G +quota operator 12X +quota operator 2T +quota operator 99999999999999999999 +quota operator off +quota operator 1G extra +quota user +quota user nobody 1G +quota user bob default +quota user bob 0 +quota user bob 1G extra +rate operator 0 +rate operator unlimited +rate operator default +rate operator 2T +rate user bob fast +rate user bob unlimited +rate user nobody 1M +LIST + [[ ! -e "$CONSOLE" ]] + (( $(snapshot_count) == 0 )) + + # the reasons + run ft quota operator 0 + assert_output --partial "Size '0' is zero: give a size above zero, or unlimited for no limit." + run ft quota operator 2T + assert_output --partial "Size '2T' is too large: at most 1T." + run ft quota operator 1.5G + assert_output --partial "Invalid size '1.5G': expected a number of bytes or a number with K, M, G or T" + run ft quota operator -- -5M + assert_failure 1 + assert_output --partial "Invalid size '-5M'" + [[ ! -e "$CONSOLE" ]] +} + +@test "_console-policy: file transfer for the caller, off unless the settings give it" { + stub_cmd id 'echo "$3 tac-users"' + # a superuser has it, with no quota; the others do not; root has none + SUDO_USER=alice run "$TACCTL_BIN_SCRIPT" _console-policy + assert_success + assert_output --partial " file_transfer=yes ft_quota=0 ft_rate=0" + SUDO_USER=bob run "$TACCTL_BIN_SCRIPT" _console-policy + refute_output --partial "file_transfer" + run "$TACCTL_BIN_SCRIPT" _console-policy + refute_output --partial "file_transfer" + + ft operator enable + SUDO_USER=bob run "$TACCTL_BIN_SCRIPT" _console-policy + assert_output --partial " file_transfer=yes ft_quota=268435456 ft_rate=0" + ft quota operator 1G + ft rate operator 512K + SUDO_USER=bob run "$TACCTL_BIN_SCRIPT" _console-policy + assert_output --partial " file_transfer=yes ft_quota=1073741824 ft_rate=524288" + ft quota user bob unlimited + ft rate user bob 2M + SUDO_USER=bob run "$TACCTL_BIN_SCRIPT" _console-policy + assert_output --partial " file_transfer=yes ft_quota=0 ft_rate=2097152" + # the user's own disable beats the tier's enable; carol's enable the tier's silence + ft user bob disable + SUDO_USER=bob run "$TACCTL_BIN_SCRIPT" _console-policy + refute_output --partial "file_transfer" + ft user carol enable + SUDO_USER=carol run "$TACCTL_BIN_SCRIPT" _console-policy + assert_output --partial " file_transfer=yes ft_quota=268435456 ft_rate=0" +} + +@test "console file-transfer: the list form and console show say whether sshd defines an sftp subsystem, and warn when it is on and there is none" { + printf 'authsrv|local||lab|127.0.0.1|\n' > "${TACCTL_STATE_DIR}/linux-hosts" + stub_cmd sshd 'printf "port 22\nallowtcpforwarding no\nallowagentforwarding no\nsubsystem sftp /usr/lib/openssh/sftp-server\n"' + run ft + assert_success + assert_output --partial $'\nsshd sftp subsystem: /usr/lib/openssh/sftp-server' + refute_output --partial "WARNING" + # none, and only the superuser tier has it: said, quiet + stub_cmd sshd 'printf "port 22\nallowtcpforwarding no\nallowagentforwarding no\n"' + run ft + assert_output --partial $'\nsshd sftp subsystem: none' + refute_output --partial "WARNING" + # none, and a tier has it: warned + ft operator enable + run ft + output=$(sed 's/\x1b\[[0-9;]*m//g' <<< "$output") + assert_output --partial $'\nsshd sftp subsystem: none\nWARNING: sshd defines no sftp subsystem: file transfer cannot start; add `Subsystem sftp ...` to sshd_config.' + run "$TACCTL_BIN_SCRIPT" console show + output=$(sed 's/\x1b\[[0-9;]*m//g' <<< "$output") + assert_output --partial "WARNING: sshd defines no sftp subsystem" +} diff --git a/tests/integration/console_sftp.bats b/tests/integration/console_sftp.bats new file mode 100644 index 00000000..de4b718c --- /dev/null +++ b/tests/integration/console_sftp.bats @@ -0,0 +1,77 @@ +#!/usr/bin/env bats +# Integration tests for the console's file transfer: the binary started as +# `tacctl-console -c ` with a canned SFTP init on standard +# input (the version request every client opens with, then the end of the +# input). The root side's policy is the stub of console.bats, with the file +# transfer fields in policy.extra. The files of the home are never touched: +# the session ends before any request (the Go tests, internal/cli/ +# console_sftp_test.go, drive the whole protocol with a real client). + +load ../helpers/setup +load ../helpers/tmpenv +load ../helpers/mocks +load ../helpers/fixtures + +setup() { + tacctl_tmpenv_init + tacctl_mocks_init + stub_cmd chown + stub_cmd systemctl + stub_cmd logger + load_fixture tacquito.minimal.yaml + stub_cmd sudo "while [[ \"\${1:-}\" == -n || \"\${1:-}\" == *=* ]]; do [[ \"\$1\" == *=* ]] && export \"\$1\"; shift; done +case \" \$* \" in *' _console-policy '*) echo 'shell=console idle=30 system_shell=no system_shell_path=/bin/bash ssh_escape=no agent=no tier=readonly list_max=40'\"\$(cat '${BATS_TEST_TMPDIR}/policy.extra' 2>/dev/null)\"; exit 0 ;; esac +exec \"\$@\"" + stub_cmd id 'echo carol tac-users tac-readonly' + export HOME="${BATS_TEST_TMPDIR}/home" + export USER=carol LOGNAME=carol + unset SSH_CLIENT SSH_CONNECTION SSH_TTY + mkdir -p "$HOME" + CONSOLE_BIN="${BATS_TEST_TMPDIR}/tacctl-console" + ln -s "$TACCTL_BIN_SCRIPT" "$CONSOLE_BIN" + export TACCTL_TEST_CONSOLE_ENV=1 + export TACCTL_TEST_RANDOM=0123456789ab +} + +console_log() { grep '^logger -t tacctl-console ' "$CALLS_LOG" | sed 's/^logger -t tacctl-console //; s/ sid=[a-z0-9]\{8\}$//' || true; } + +# init: the SSH_FXP_INIT packet of an sftp client (length 5, type 1, version 3). +init() { printf '\000\000\000\005\001\000\000\000\003'; } + +@test "console -c sftp-server: with file transfer on, the session answers the client's init with the version packet and ends with status 0" { + # the account's home comes from the account database (never $HOME): the + # session needs the running user to have one + home=$(getent passwd "$(/usr/bin/id -u)" | cut -d: -f6) + [[ -n "$home" && -d "$home" ]] || skip "the running user has no home directory in the account database" + printf ' file_transfer=yes ft_quota=0 ft_rate=0' > "${BATS_TEST_TMPDIR}/policy.extra" + # a client keeps its input open until it has the answer (the real one waits for + # the version packet); the second is the time the console has to write it + { init; sleep 1; } | "$CONSOLE_BIN" -c /usr/lib/openssh/sftp-server > "${BATS_TEST_TMPDIR}/out.bin" 2> "${BATS_TEST_TMPDIR}/err.txt" + # standard output holds SFTP packets only: the version packet (type 2) first + [[ "$(od -An -tx1 -j4 -N1 "${BATS_TEST_TMPDIR}/out.bin" | tr -d ' \n')" == "02" ]] + [[ ! -s "${BATS_TEST_TMPDIR}/err.txt" ]] + run console_log + assert_line --index 0 "-p auth.info console start session=0123456789ab user=carol from=- tty=- mode=sftp" + assert_line --index 1 --regexp "^-p auth.info console sftp start session=0123456789ab user=carol tier=readonly from=- home=\".*\" quota=unlimited rate=off\$" + assert_line --index 2 "-p auth.info console sftp end session=0123456789ab user=carol up=0 down=0 ops=0 refused=0" + assert_line --index 3 "-p auth.info console end session=0123456789ab user=carol reason=sftp lines=0 status=0" + [ "${#lines[@]}" -eq 4 ] +} + +@test "console -c internal-sftp: refused with status 126, a text on standard error only and a DENY line, while file transfer is off" { + run bash -c '"$0" -c internal-sftp > "$1/out.bin" 2> "$1/err.txt" < /dev/null' "$CONSOLE_BIN" "$BATS_TEST_TMPDIR" + assert_failure 126 + [[ ! -s "${BATS_TEST_TMPDIR}/out.bin" ]] + run cat "${BATS_TEST_TMPDIR}/err.txt" + assert_output "file transfer is not enabled for this account; an administrator can switch it on (tacctl console file-transfer)" + run console_log + assert_line --index 1 "-p auth.warning console DENY session=0123456789ab user=carol reason=file-transfer subsystem=sftp" + assert_line --index 2 "-p auth.info console end session=0123456789ab user=carol reason=sftp lines=0 status=126" +} + +@test "console -c scp -f: still refused with the program text when file transfer is on" { + printf ' file_transfer=yes ft_quota=0 ft_rate=0' > "${BATS_TEST_TMPDIR}/policy.extra" + run "$CONSOLE_BIN" -c "scp -f x" + assert_failure 126 + assert_output "the tacctl console does not run programs or shell commands; file transfer is SFTP only (sftp, scp of OpenSSH 9 or later)" +} diff --git a/tests/integration/rollback.bats b/tests/integration/rollback.bats index 143fcf7a..d509d06b 100644 --- a/tests/integration/rollback.bats +++ b/tests/integration/rollback.bats @@ -455,10 +455,10 @@ JSON assert_output --partial "Roll back to 0.2.19 (dry run)" assert_output --partial "put back the per-tier sudoers drop-in 0.2.19 writes" [[ "$(_sums)" == "$before" ]] - run "$TACCTL_BIN_SCRIPT" rollback 0.2.27 + run "$TACCTL_BIN_SCRIPT" rollback 0.2.28 assert_failure 1 - assert_output --partial "'0.2.27' is not a release to roll back to" - assert_output --partial "prepares the state for 0.2.26 (the release before this one), 0.2.25, 0.2.24, 0.2.23, 0.2.22" + assert_output --partial "'0.2.28' is not a release to roll back to" + assert_output --partial "prepares the state for 0.2.27 (the release before this one), 0.2.26, 0.2.25, 0.2.24, 0.2.23, 0.2.22" } @test "rollback 0.2.21: the release before 0.2.22; the dry run writes nothing and --apply takes out the server name and nothing else" { @@ -486,7 +486,44 @@ JSON assert_output --partial "Nothing to convert: every file is one 0.2.21 can read." } -@test "rollback 0.2.26: the release before this one; the dry run writes nothing and --apply converts nothing, the report limits stay" { +@test "rollback 0.2.27: the release before this one; the dry run writes nothing and --apply converts nothing, the report limits stay" { + _state_024 + "$TACCTL_BIN_SCRIPT" server name core-1 > /dev/null + "$TACCTL_BIN_SCRIPT" user add bob engineer --hash "$HASH" --scopes lab > /dev/null + "$TACCTL_BIN_SCRIPT" config reports max-size 20Mi > /dev/null + "$TACCTL_BIN_SCRIPT" user reports-limit bob max-count 7 > /dev/null + mkdir -p "$BATS_TEST_TMPDIR/var-lib" + echo "offered" > "$BATS_TEST_TMPDIR/var-lib/pdf-tools-offered" + before=$(_sums) + n=$(_snapshots) + run "$TACCTL_BIN_SCRIPT" rollback 0.2.27 --hosts + assert_success + assert_output --partial "Roll back to 0.2.27 (dry run)" + assert_output --partial "nothing to remove (every key of tacctl.yaml is one 0.2.27 knows)" + assert_output --partial "nothing to do for 0.2.27: this release changed nothing on the enrolled hosts" + assert_output --partial "--apply converts no file of tacctl's own and takes no snapshot" + refute_output --partial "remove reports.max_size" + refute_output --partial "--yes" + assert_output --partial "This was a dry run: nothing was changed." + [[ "$(_sums)" == "$before" ]] + [[ "$(_snapshots)" == "$n" ]] + run "$TACCTL_BIN_SCRIPT" rollback 0.2.27 --apply + assert_success + assert_output --partial "Nothing to convert: every file is one 0.2.27 can read." + assert_output --partial "tacctl upgrade --branch 0.2.27" + refute_output --partial "The reports in the users' homes stay" + [[ "$(_sums)" == "$before" ]] + [[ "$(_snapshots)" == "$n" ]] + run "$TACCTL_BIN_SCRIPT" config get reports.max_size unset-marker + refute_output "unset-marker" + run "$TACCTL_BIN_SCRIPT" user show bob + assert_output --partial "Report max-count" + run "$TACCTL_BIN_SCRIPT" config get server.name unset-marker + assert_output "core-1" + [[ "$(cat "$BATS_TEST_TMPDIR/var-lib/pdf-tools-offered")" == "offered" ]] +} + +@test "rollback 0.2.26: the release before 0.2.27; the dry run writes nothing and --apply converts nothing, the report limits stay" { _state_024 "$TACCTL_BIN_SCRIPT" server name core-1 > /dev/null "$TACCTL_BIN_SCRIPT" user add bob engineer --hash "$HASH" --scopes lab > /dev/null diff --git a/vendor/github.com/kr/fs/LICENSE b/vendor/github.com/kr/fs/LICENSE new file mode 100644 index 00000000..74487567 --- /dev/null +++ b/vendor/github.com/kr/fs/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/kr/fs/Readme b/vendor/github.com/kr/fs/Readme new file mode 100644 index 00000000..c95e13fc --- /dev/null +++ b/vendor/github.com/kr/fs/Readme @@ -0,0 +1,3 @@ +Filesystem Package + +http://godoc.org/github.com/kr/fs diff --git a/vendor/github.com/kr/fs/filesystem.go b/vendor/github.com/kr/fs/filesystem.go new file mode 100644 index 00000000..f1c4805f --- /dev/null +++ b/vendor/github.com/kr/fs/filesystem.go @@ -0,0 +1,36 @@ +package fs + +import ( + "io/ioutil" + "os" + "path/filepath" +) + +// FileSystem defines the methods of an abstract filesystem. +type FileSystem interface { + + // ReadDir reads the directory named by dirname and returns a + // list of directory entries. + ReadDir(dirname string) ([]os.FileInfo, error) + + // Lstat returns a FileInfo describing the named file. If the file is a + // symbolic link, the returned FileInfo describes the symbolic link. Lstat + // makes no attempt to follow the link. + Lstat(name string) (os.FileInfo, error) + + // Join joins any number of path elements into a single path, adding a + // separator if necessary. The result is Cleaned; in particular, all + // empty strings are ignored. + // + // The separator is FileSystem specific. + Join(elem ...string) string +} + +// fs represents a FileSystem provided by the os package. +type fs struct{} + +func (f *fs) ReadDir(dirname string) ([]os.FileInfo, error) { return ioutil.ReadDir(dirname) } + +func (f *fs) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) } + +func (f *fs) Join(elem ...string) string { return filepath.Join(elem...) } diff --git a/vendor/github.com/kr/fs/walk.go b/vendor/github.com/kr/fs/walk.go new file mode 100644 index 00000000..6ffa1e0b --- /dev/null +++ b/vendor/github.com/kr/fs/walk.go @@ -0,0 +1,95 @@ +// Package fs provides filesystem-related functions. +package fs + +import ( + "os" +) + +// Walker provides a convenient interface for iterating over the +// descendants of a filesystem path. +// Successive calls to the Step method will step through each +// file or directory in the tree, including the root. The files +// are walked in lexical order, which makes the output deterministic +// but means that for very large directories Walker can be inefficient. +// Walker does not follow symbolic links. +type Walker struct { + fs FileSystem + cur item + stack []item + descend bool +} + +type item struct { + path string + info os.FileInfo + err error +} + +// Walk returns a new Walker rooted at root. +func Walk(root string) *Walker { + return WalkFS(root, new(fs)) +} + +// WalkFS returns a new Walker rooted at root on the FileSystem fs. +func WalkFS(root string, fs FileSystem) *Walker { + info, err := fs.Lstat(root) + return &Walker{ + fs: fs, + stack: []item{{root, info, err}}, + } +} + +// Step advances the Walker to the next file or directory, +// which will then be available through the Path, Stat, +// and Err methods. +// It returns false when the walk stops at the end of the tree. +func (w *Walker) Step() bool { + if w.descend && w.cur.err == nil && w.cur.info.IsDir() { + list, err := w.fs.ReadDir(w.cur.path) + if err != nil { + w.cur.err = err + w.stack = append(w.stack, w.cur) + } else { + for i := len(list) - 1; i >= 0; i-- { + path := w.fs.Join(w.cur.path, list[i].Name()) + w.stack = append(w.stack, item{path, list[i], nil}) + } + } + } + + if len(w.stack) == 0 { + return false + } + i := len(w.stack) - 1 + w.cur = w.stack[i] + w.stack = w.stack[:i] + w.descend = true + return true +} + +// Path returns the path to the most recent file or directory +// visited by a call to Step. It contains the argument to Walk +// as a prefix; that is, if Walk is called with "dir", which is +// a directory containing the file "a", Path will return "dir/a". +func (w *Walker) Path() string { + return w.cur.path +} + +// Stat returns info for the most recent file or directory +// visited by a call to Step. +func (w *Walker) Stat() os.FileInfo { + return w.cur.info +} + +// Err returns the error, if any, for the most recent attempt +// by Step to visit a file or directory. If a directory has +// an error, w will not descend into that directory. +func (w *Walker) Err() error { + return w.cur.err +} + +// SkipDir causes the currently visited directory to be skipped. +// If w is not on a directory, SkipDir has no effect. +func (w *Walker) SkipDir() { + w.descend = false +} diff --git a/vendor/github.com/pkg/sftp/.gitignore b/vendor/github.com/pkg/sftp/.gitignore new file mode 100644 index 00000000..caf2dca2 --- /dev/null +++ b/vendor/github.com/pkg/sftp/.gitignore @@ -0,0 +1,10 @@ +.*.swo +.*.swp + +server_standalone/server_standalone + +examples/*/id_rsa +examples/*/id_rsa.pub + +memprofile.out +memprofile.svg diff --git a/vendor/github.com/pkg/sftp/CONTRIBUTORS b/vendor/github.com/pkg/sftp/CONTRIBUTORS new file mode 100644 index 00000000..5c7196ae --- /dev/null +++ b/vendor/github.com/pkg/sftp/CONTRIBUTORS @@ -0,0 +1,3 @@ +Dave Cheney +Saulius Gurklys +John Eikenberry diff --git a/vendor/github.com/pkg/sftp/LICENSE b/vendor/github.com/pkg/sftp/LICENSE new file mode 100644 index 00000000..b7b53921 --- /dev/null +++ b/vendor/github.com/pkg/sftp/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) 2013, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/sftp/Makefile b/vendor/github.com/pkg/sftp/Makefile new file mode 100644 index 00000000..4d3a0079 --- /dev/null +++ b/vendor/github.com/pkg/sftp/Makefile @@ -0,0 +1,27 @@ +.PHONY: integration integration_w_race benchmark + +integration: + go test -integration -v ./... + go test -testserver -v ./... + go test -integration -testserver -v ./... + go test -integration -allocator -v ./... + go test -testserver -allocator -v ./... + go test -integration -testserver -allocator -v ./... + +integration_w_race: + go test -race -integration -v ./... + go test -race -testserver -v ./... + go test -race -integration -testserver -v ./... + go test -race -integration -allocator -v ./... + go test -race -testserver -allocator -v ./... + go test -race -integration -allocator -testserver -v ./... + +COUNT ?= 1 +BENCHMARK_PATTERN ?= "." + +benchmark: + go test -integration -run=NONE -bench=$(BENCHMARK_PATTERN) -benchmem -count=$(COUNT) + +benchmark_w_memprofile: + go test -integration -run=NONE -bench=$(BENCHMARK_PATTERN) -benchmem -count=$(COUNT) -memprofile memprofile.out + go tool pprof -svg -output=memprofile.svg memprofile.out diff --git a/vendor/github.com/pkg/sftp/README.md b/vendor/github.com/pkg/sftp/README.md new file mode 100644 index 00000000..5e78cd39 --- /dev/null +++ b/vendor/github.com/pkg/sftp/README.md @@ -0,0 +1,44 @@ +sftp +---- + +The `sftp` package provides support for file system operations on remote ssh +servers using the SFTP subsystem. It also implements an SFTP server for serving +files from the filesystem. + +![CI Status](https://github.com/pkg/sftp/workflows/CI/badge.svg?branch=master&event=push) [![Go Reference](https://pkg.go.dev/badge/github.com/pkg/sftp.svg)](https://pkg.go.dev/github.com/pkg/sftp) + +usage and examples +------------------ + +See [https://pkg.go.dev/github.com/pkg/sftp](https://pkg.go.dev/github.com/pkg/sftp) for +examples and usage. + +The basic operation of the package mirrors the facilities of the +[os](http://golang.org/pkg/os) package. + +The Walker interface for directory traversal is heavily inspired by Keith +Rarick's [fs](https://pkg.go.dev/github.com/kr/fs) package. + +roadmap +------- + +* There is way too much duplication in the Client methods. If there was an + unmarshal(interface{}) method this would reduce a heap of the duplication. + +contributing +------------ + +We welcome pull requests, bug fixes and issue reports. + +Before proposing a large change, first please discuss your change by raising an +issue. + +For API/code bugs, please include a small, self contained code example to +reproduce the issue. For pull requests, remember test coverage. + +We try to handle issues and pull requests with a 0 open philosophy. That means +we will try to address the submission as soon as possible and will work toward +a resolution. If progress can no longer be made (eg. unreproducible bug) or +stops (eg. unresponsive submitter), we will close the bug. + +Thanks. diff --git a/vendor/github.com/pkg/sftp/SECURITY.md b/vendor/github.com/pkg/sftp/SECURITY.md new file mode 100644 index 00000000..9ebc2631 --- /dev/null +++ b/vendor/github.com/pkg/sftp/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +Security updates are provided for the latest released version of this package. +We also welcome vulnerability reports for the development version to help us ensure it is secure before the next release. + +## Reporting a Vulnerability + +If you believe you’ve found a security vulnerability in this project, we strongly encourage you to report it privately using GitHub’s [security advisory system](https://github.com/pkg/sftp/security/advisories/new). +This will allow us to review and address the issue before public disclosure. + +Thank you for helping us keep the project secure. diff --git a/vendor/github.com/pkg/sftp/allocator.go b/vendor/github.com/pkg/sftp/allocator.go new file mode 100644 index 00000000..3e67e543 --- /dev/null +++ b/vendor/github.com/pkg/sftp/allocator.go @@ -0,0 +1,96 @@ +package sftp + +import ( + "sync" +) + +type allocator struct { + sync.Mutex + available [][]byte + // map key is the request order + used map[uint32][][]byte +} + +func newAllocator() *allocator { + return &allocator{ + // micro optimization: initialize available pages with an initial capacity + available: make([][]byte, 0, SftpServerWorkerCount*2), + used: make(map[uint32][][]byte), + } +} + +// GetPage returns a previously allocated and unused []byte or create a new one. +// The slice have a fixed size = maxMsgLength, this value is suitable for both +// receiving new packets and reading the files to serve +func (a *allocator) GetPage(requestOrderID uint32) []byte { + a.Lock() + defer a.Unlock() + + var result []byte + + // get an available page and remove it from the available ones. + if len(a.available) > 0 { + truncLength := len(a.available) - 1 + result = a.available[truncLength] + + a.available[truncLength] = nil // clear out the internal pointer + a.available = a.available[:truncLength] // truncate the slice + } + + // no preallocated slice found, just allocate a new one + if result == nil { + result = make([]byte, maxMsgLength) + } + + // put result in used pages + a.used[requestOrderID] = append(a.used[requestOrderID], result) + + return result +} + +// ReleasePages marks unused all pages in use for the given requestID +func (a *allocator) ReleasePages(requestOrderID uint32) { + a.Lock() + defer a.Unlock() + + if used := a.used[requestOrderID]; len(used) > 0 { + a.available = append(a.available, used...) + } + delete(a.used, requestOrderID) +} + +// Free removes all the used and available pages. +// Call this method when the allocator is not needed anymore +func (a *allocator) Free() { + a.Lock() + defer a.Unlock() + + a.available = nil + a.used = make(map[uint32][][]byte) +} + +func (a *allocator) countUsedPages() int { + a.Lock() + defer a.Unlock() + + num := 0 + for _, p := range a.used { + num += len(p) + } + return num +} + +func (a *allocator) countAvailablePages() int { + a.Lock() + defer a.Unlock() + + return len(a.available) +} + +func (a *allocator) isRequestOrderIDUsed(requestOrderID uint32) bool { + a.Lock() + defer a.Unlock() + + _, ok := a.used[requestOrderID] + return ok +} diff --git a/vendor/github.com/pkg/sftp/attrs.go b/vendor/github.com/pkg/sftp/attrs.go new file mode 100644 index 00000000..c995534e --- /dev/null +++ b/vendor/github.com/pkg/sftp/attrs.go @@ -0,0 +1,136 @@ +package sftp + +// ssh_FXP_ATTRS support +// see https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-5 + +import ( + "os" + "time" +) + +const ( + sshFileXferAttrSize = 0x00000001 + sshFileXferAttrUIDGID = 0x00000002 + sshFileXferAttrPermissions = 0x00000004 + sshFileXferAttrACmodTime = 0x00000008 + sshFileXferAttrExtended = 0x80000000 + + sshFileXferAttrAll = sshFileXferAttrSize | sshFileXferAttrUIDGID | sshFileXferAttrPermissions | + sshFileXferAttrACmodTime | sshFileXferAttrExtended +) + +// fileInfo is an artificial type designed to satisfy os.FileInfo. +type fileInfo struct { + name string + stat *FileStat +} + +// Name returns the base name of the file. +func (fi *fileInfo) Name() string { return fi.name } + +// Size returns the length in bytes for regular files; system-dependent for others. +func (fi *fileInfo) Size() int64 { return int64(fi.stat.Size) } + +// Mode returns file mode bits. +func (fi *fileInfo) Mode() os.FileMode { return fi.stat.FileMode() } + +// ModTime returns the last modification time of the file. +func (fi *fileInfo) ModTime() time.Time { return fi.stat.ModTime() } + +// IsDir returns true if the file is a directory. +func (fi *fileInfo) IsDir() bool { return fi.Mode().IsDir() } + +func (fi *fileInfo) Sys() any { return fi.stat } + +// FileStat holds the original unmarshalled values from a call to READDIR or +// *STAT. It is exported for the purposes of accessing the raw values via +// os.FileInfo.Sys(). It is also used server side to store the unmarshalled +// values for SetStat. +type FileStat struct { + Size uint64 + Mode uint32 + Mtime uint32 + Atime uint32 + UID uint32 + GID uint32 + Extended []StatExtended +} + +// ModTime returns the Mtime SFTP file attribute converted to a time.Time +func (fs *FileStat) ModTime() time.Time { + return time.Unix(int64(fs.Mtime), 0) +} + +// AccessTime returns the Atime SFTP file attribute converted to a time.Time +func (fs *FileStat) AccessTime() time.Time { + return time.Unix(int64(fs.Atime), 0) +} + +// FileMode returns the Mode SFTP file attribute converted to an os.FileMode +func (fs *FileStat) FileMode() os.FileMode { + return toFileMode(fs.Mode) +} + +// StatExtended contains additional, extended information for a FileStat. +type StatExtended struct { + ExtType string + ExtData string +} + +func fileInfoFromStat(stat *FileStat, name string) os.FileInfo { + return &fileInfo{ + name: name, + stat: stat, + } +} + +// FileInfoUidGid extends os.FileInfo and adds callbacks for Uid and Gid retrieval, +// as an alternative to *syscall.Stat_t objects on unix systems. +type FileInfoUidGid interface { + os.FileInfo + Uid() uint32 + Gid() uint32 +} + +// FileInfoUidGid extends os.FileInfo and adds a callbacks for extended data retrieval. +type FileInfoExtendedData interface { + os.FileInfo + Extended() []StatExtended +} + +func fileStatFromInfo(fi os.FileInfo) (uint32, *FileStat) { + mtime := fi.ModTime().Unix() + atime := mtime + var flags uint32 = sshFileXferAttrSize | + sshFileXferAttrPermissions | + sshFileXferAttrACmodTime + + fileStat := &FileStat{ + Size: uint64(fi.Size()), + Mode: fromFileMode(fi.Mode()), + Mtime: uint32(mtime), + Atime: uint32(atime), + } + + // os specific file stat decoding + fileStatFromInfoOs(fi, &flags, fileStat) + + // The call above will include the sshFileXferAttrUIDGID in case + // the os.FileInfo can be casted to *syscall.Stat_t on unix. + // If fi implements FileInfoUidGid, retrieve Uid, Gid from it instead. + if fiExt, ok := fi.(FileInfoUidGid); ok { + flags |= sshFileXferAttrUIDGID + fileStat.UID = fiExt.Uid() + fileStat.GID = fiExt.Gid() + } + + // if fi implements FileInfoExtendedData, retrieve extended data from it + if fiExt, ok := fi.(FileInfoExtendedData); ok { + fileStat.Extended = fiExt.Extended() + if len(fileStat.Extended) > 0 { + flags |= sshFileXferAttrExtended + } + } + + return flags, fileStat +} diff --git a/vendor/github.com/pkg/sftp/attrs_stubs.go b/vendor/github.com/pkg/sftp/attrs_stubs.go new file mode 100644 index 00000000..d20348c1 --- /dev/null +++ b/vendor/github.com/pkg/sftp/attrs_stubs.go @@ -0,0 +1,12 @@ +//go:build plan9 || windows || android +// +build plan9 windows android + +package sftp + +import ( + "os" +) + +func fileStatFromInfoOs(fi os.FileInfo, flags *uint32, fileStat *FileStat) { + // todo +} diff --git a/vendor/github.com/pkg/sftp/attrs_unix.go b/vendor/github.com/pkg/sftp/attrs_unix.go new file mode 100644 index 00000000..96ffc03d --- /dev/null +++ b/vendor/github.com/pkg/sftp/attrs_unix.go @@ -0,0 +1,17 @@ +//go:build darwin || dragonfly || freebsd || (!android && linux) || netbsd || openbsd || solaris || aix || js || zos +// +build darwin dragonfly freebsd !android,linux netbsd openbsd solaris aix js zos + +package sftp + +import ( + "os" + "syscall" +) + +func fileStatFromInfoOs(fi os.FileInfo, flags *uint32, fileStat *FileStat) { + if statt, ok := fi.Sys().(*syscall.Stat_t); ok { + *flags |= sshFileXferAttrUIDGID + fileStat.UID = statt.Uid + fileStat.GID = statt.Gid + } +} diff --git a/vendor/github.com/pkg/sftp/client.go b/vendor/github.com/pkg/sftp/client.go new file mode 100644 index 00000000..8e027d20 --- /dev/null +++ b/vendor/github.com/pkg/sftp/client.go @@ -0,0 +1,2338 @@ +package sftp + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "os" + "path" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/kr/fs" + "golang.org/x/crypto/ssh" + + "github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh" +) + +var ( + // ErrInternalInconsistency indicates the packets sent and the data queued to be + // written to the file don't match up. It is an unusual error and usually is + // caused by bad behavior server side or connection issues. The error is + // limited in scope to the call where it happened, the client object is still + // OK to use as long as the connection is still open. + ErrInternalInconsistency = errors.New("internal inconsistency") + // InternalInconsistency alias for ErrInternalInconsistency. + // + // Deprecated: please use ErrInternalInconsistency + InternalInconsistency = ErrInternalInconsistency +) + +// A ClientOption is a function which applies configuration to a Client. +type ClientOption func(*Client) error + +// MaxPacketChecked sets the maximum size of the payload, measured in bytes. +// This option only accepts sizes servers should support, ie. <= 32768 bytes. +// +// If you get the error "failed to send packet header: EOF" when copying a +// large file, try lowering this number. +// +// The default packet size is 32768 bytes. +func MaxPacketChecked(size int) ClientOption { + return func(c *Client) error { + if size < 1 { + return errors.New("size must be greater or equal to 1") + } + if size > 32768 { + return errors.New("sizes larger than 32KB might not work with all servers") + } + c.maxPacket = size + return nil + } +} + +// MaxPacketUnchecked sets the maximum size of the payload, measured in bytes. +// It accepts sizes larger than the 32768 bytes all servers should support. +// Only use a setting higher than 32768 if your application always connects to +// the same server or after sufficiently broad testing. +// +// If you get the error "failed to send packet header: EOF" when copying a +// large file, try lowering this number. +// +// The default packet size is 32768 bytes. +func MaxPacketUnchecked(size int) ClientOption { + return func(c *Client) error { + if size < 1 { + return errors.New("size must be greater or equal to 1") + } + c.maxPacket = size + return nil + } +} + +// MaxPacket sets the maximum size of the payload, measured in bytes. +// This option only accepts sizes servers should support, ie. <= 32768 bytes. +// This is a synonym for MaxPacketChecked that provides backward compatibility. +// +// If you get the error "failed to send packet header: EOF" when copying a +// large file, try lowering this number. +// +// The default packet size is 32768 bytes. +func MaxPacket(size int) ClientOption { + return MaxPacketChecked(size) +} + +// MaxConcurrentRequestsPerFile sets the maximum concurrent requests allowed for a single file. +// +// The default maximum concurrent requests is 64. +func MaxConcurrentRequestsPerFile(n int) ClientOption { + return func(c *Client) error { + if n < 1 { + return errors.New("n must be greater or equal to 1") + } + c.maxConcurrentRequests = n + return nil + } +} + +// UseConcurrentWrites allows the Client to perform concurrent Writes. +// +// Using concurrency while doing writes, requires special consideration. +// A write to a later offset in a file after an error, +// could end up with a file length longer than what was successfully written. +// +// When using this option, if you receive an error during `io.Copy` or `io.WriteTo`, +// you may need to `Truncate` the target Writer to avoid “holes” in the data written. +func UseConcurrentWrites(value bool) ClientOption { + return func(c *Client) error { + c.useConcurrentWrites = value + return nil + } +} + +// UseConcurrentReads allows the Client to perform concurrent Reads. +// +// Concurrent reads are generally safe to use and not using them will degrade +// performance, so this option is enabled by default. +// +// When enabled, WriteTo will use Stat/Fstat to get the file size and determines +// how many concurrent workers to use. +// Some "read once" servers will delete the file if they receive a stat call on an +// open file and then the download will fail. +// Disabling concurrent reads you will be able to download files from these servers. +// If concurrent reads are disabled, the UseFstat option is ignored. +func UseConcurrentReads(value bool) ClientOption { + return func(c *Client) error { + c.disableConcurrentReads = !value + return nil + } +} + +// UseFstat sets whether to use Fstat or Stat when File.WriteTo is called +// (usually when copying files). +// Some servers limit the amount of open files and calling Stat after opening +// the file will throw an error From the server. Setting this flag will call +// Fstat instead of Stat which is suppose to be called on an open file handle. +// +// It has been found that that with IBM Sterling SFTP servers which have +// "extractability" level set to 1 which means only 1 file can be opened at +// any given time. +// +// If the server you are working with still has an issue with both Stat and +// Fstat calls you can always open a file and read it until the end. +// +// Another reason to read the file until its end and Fstat doesn't work is +// that in some servers, reading a full file will automatically delete the +// file as some of these mainframes map the file to a message in a queue. +// Once the file has been read it will get deleted. +func UseFstat(value bool) ClientOption { + return func(c *Client) error { + c.useFstat = value + return nil + } +} + +// CopyStderrTo specifies a writer to which the standard error of the remote sftp-server command should be written. +// +// The writer passed in will not be automatically closed. +// It is the responsibility of the caller to coordinate closure of any writers. +func CopyStderrTo(wr io.Writer) ClientOption { + return func(c *Client) error { + c.stderrTo = wr + return nil + } +} + +// Client represents an SFTP session on a *ssh.ClientConn SSH connection. +// Multiple Clients can be active on a single SSH connection, and a Client +// may be called concurrently from multiple Goroutines. +// +// Client implements the github.com/kr/fs.FileSystem interface. +type Client struct { + clientConn + + stderrTo io.Writer + + ext map[string]string // Extensions (name -> data). + + maxPacket int // max packet size read or written. + maxConcurrentRequests int + nextid uint32 + + // write concurrency is… error prone. + // Default behavior should be to not use it. + useConcurrentWrites bool + useFstat bool + disableConcurrentReads bool +} + +// NewClient creates a new SFTP client on conn, using zero or more option +// functions. +func NewClient(conn *ssh.Client, opts ...ClientOption) (*Client, error) { + s, err := conn.NewSession() + if err != nil { + return nil, err + } + + pw, err := s.StdinPipe() + if err != nil { + return nil, err + } + pr, err := s.StdoutPipe() + if err != nil { + return nil, err + } + perr, err := s.StderrPipe() + if err != nil { + return nil, err + } + + if err := s.RequestSubsystem("sftp"); err != nil { + return nil, err + } + + return newClientPipe(pr, perr, pw, s.Wait, opts...) +} + +// NewClientPipe creates a new SFTP client given a Reader and a WriteCloser. +// This can be used for connecting to an SFTP server over TCP/TLS or by using +// the system's ssh client program (e.g. via exec.Command). +func NewClientPipe(rd io.Reader, wr io.WriteCloser, opts ...ClientOption) (*Client, error) { + return newClientPipe(rd, nil, wr, nil, opts...) +} + +func newClientPipe(rd, stderr io.Reader, wr io.WriteCloser, wait func() error, opts ...ClientOption) (*Client, error) { + c := &Client{ + clientConn: clientConn{ + conn: conn{ + Reader: rd, + WriteCloser: wr, + }, + inflight: make(map[uint32]chan<- result), + closed: make(chan struct{}), + wait: wait, + }, + + ext: make(map[string]string), + + maxPacket: 1 << 15, + maxConcurrentRequests: 64, + } + + for _, opt := range opts { + if err := opt(c); err != nil { + wr.Close() + return nil, err + } + } + + if stderr != nil { + wr := io.Discard + if c.stderrTo != nil { + wr = c.stderrTo + } + + go func() { + // DO NOT close the writer! + // Programs may pass in `os.Stderr` to write the remote stderr to, + // and the program may continue after disconnect by reconnecting. + // But if we've closed their stderr, then we just messed everything up. + + if _, err := io.Copy(wr, stderr); err != nil { + debug("error copying stderr: %v", err) + } + }() + } + + if err := c.sendInit(); err != nil { + wr.Close() + return nil, fmt.Errorf("error sending init packet to server: %w", err) + } + + if err := c.recvVersion(); err != nil { + wr.Close() + return nil, fmt.Errorf("error receiving version packet from server: %w", err) + } + + c.clientConn.wg.Add(1) + go func() { + defer c.clientConn.wg.Done() + + if err := c.clientConn.recv(); err != nil { + c.clientConn.broadcastErr(err) + } + }() + + return c, nil +} + +// Create creates the named file mode 0666 (before umask), truncating it if it +// already exists. If successful, methods on the returned File can be used for +// I/O; the associated file descriptor has mode O_RDWR. If you need more +// control over the flags/mode used to open the file see client.OpenFile. +// +// Note that some SFTP servers (eg. AWS Transfer) do not support opening files +// read/write at the same time. For those services you will need to use +// `client.OpenFile(os.O_WRONLY|os.O_CREATE|os.O_TRUNC)`. +func (c *Client) Create(path string) (*File, error) { + return c.open(path, toPflags(os.O_RDWR|os.O_CREATE|os.O_TRUNC)) +} + +const sftpProtocolVersion = 3 // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt + +func (c *Client) sendInit() error { + return c.clientConn.conn.sendPacket(&sshFxInitPacket{ + Version: sftpProtocolVersion, // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt + }) +} + +// returns the next value of c.nextid +func (c *Client) nextID() uint32 { + return atomic.AddUint32(&c.nextid, 1) +} + +func (c *Client) recvVersion() error { + typ, data, err := c.recvPacket(0) + if err != nil { + if err == io.EOF { + return fmt.Errorf("server unexpectedly closed connection: %w", io.ErrUnexpectedEOF) + } + + return err + } + + if typ != sshFxpVersion { + return &unexpectedPacketErr{sshFxpVersion, typ} + } + + version, data, err := unmarshalUint32Safe(data) + if err != nil { + return err + } + + if version != sftpProtocolVersion { + return &unexpectedVersionErr{sftpProtocolVersion, version} + } + + for len(data) > 0 { + var ext extensionPair + ext, data, err = unmarshalExtensionPair(data) + if err != nil { + return err + } + c.ext[ext.Name] = ext.Data + } + + return nil +} + +// HasExtension checks whether the server supports a named extension. +// +// The first return value is the extension data reported by the server +// (typically a version number). +func (c *Client) HasExtension(name string) (string, bool) { + data, ok := c.ext[name] + return data, ok +} + +// Walk returns a new Walker rooted at root. +func (c *Client) Walk(root string) *fs.Walker { + return fs.WalkFS(root, c) +} + +// ReadDir reads the directory named by p +// and returns a list of directory entries. +func (c *Client) ReadDir(p string) ([]os.FileInfo, error) { + return c.ReadDirContext(context.Background(), p) +} + +// ReadDirContext reads the directory named by p +// and returns a list of directory entries. +// The passed context can be used to cancel the operation +// returning all entries listed up to the cancellation. +func (c *Client) ReadDirContext(ctx context.Context, p string) ([]os.FileInfo, error) { + handle, err := c.opendir(ctx, p) + if err != nil { + return nil, err + } + defer c.close(handle) // this has to defer earlier than the lock below + var entries []os.FileInfo + var done = false + for !done { + id := c.nextID() + typ, data, err1 := c.sendPacket(ctx, nil, &sshFxpReaddirPacket{ + ID: id, + Handle: handle, + }) + if err1 != nil { + err = err1 + done = true + break + } + switch typ { + case sshFxpName: + data, err = unmarshalSID(id, data) + if err != nil { + return nil, err + } + var count int + count, data, err = unmarshalCount(data) + if err != nil { + return nil, err + } + for range count { + var filename string + filename, data, err = unmarshalStringSafe(data) + if err != nil { + return nil, err + } + _, data, err = unmarshalStringSafe(data) // discard longname + if err != nil { + return nil, err + } + var attr *FileStat + attr, data, err = unmarshalAttrs(data) + if err != nil { + return nil, err + } + if filename == "." || filename == ".." { + continue + } + entries = append(entries, fileInfoFromStat(attr, path.Base(filename))) + } + case sshFxpStatus: + // TODO(dfc) scope warning! + err = normaliseError(unmarshalStatus(id, data)) + done = true + default: + return nil, unimplementedPacketErr(typ) + } + } + if err == io.EOF { + err = nil + } + return entries, err +} + +func (c *Client) opendir(ctx context.Context, path string) (string, error) { + id := c.nextID() + typ, data, err := c.sendPacket(ctx, nil, &sshFxpOpendirPacket{ + ID: id, + Path: path, + }) + if err != nil { + return "", err + } + switch typ { + case sshFxpHandle: + data, err := unmarshalSID(id, data) + if err != nil { + return "", err + } + handle, _, err := unmarshalStringSafe(data) + if err != nil { + return "", err + } + return handle, nil + case sshFxpStatus: + return "", normaliseError(unmarshalStatus(id, data)) + default: + return "", unimplementedPacketErr(typ) + } +} + +// Stat returns a FileInfo structure describing the file specified by path 'p'. +// If 'p' is a symbolic link, the returned FileInfo structure describes the referent file. +func (c *Client) Stat(p string) (os.FileInfo, error) { + fs, err := c.stat(p) + if err != nil { + return nil, err + } + return fileInfoFromStat(fs, path.Base(p)), nil +} + +// Lstat returns a FileInfo structure describing the file specified by path 'p'. +// If 'p' is a symbolic link, the returned FileInfo structure describes the symbolic link. +func (c *Client) Lstat(p string) (os.FileInfo, error) { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpLstatPacket{ + ID: id, + Path: p, + }) + if err != nil { + return nil, err + } + switch typ { + case sshFxpAttrs: + data, err := unmarshalSID(id, data) + if err != nil { + return nil, err + } + attr, _, err := unmarshalAttrs(data) + if err != nil { + // avoid returning a valid value from fileInfoFromStats if err != nil. + return nil, err + } + return fileInfoFromStat(attr, path.Base(p)), nil + case sshFxpStatus: + return nil, normaliseError(unmarshalStatus(id, data)) + default: + return nil, unimplementedPacketErr(typ) + } +} + +// ReadLink reads the target of a symbolic link. +func (c *Client) ReadLink(p string) (string, error) { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpReadlinkPacket{ + ID: id, + Path: p, + }) + if err != nil { + return "", err + } + switch typ { + case sshFxpName: + data, err := unmarshalSID(id, data) + if err != nil { + return "", err + } + count, data, err := unmarshalCount(data) + if err != nil { + return "", err + } + if count != 1 { + return "", unexpectedCount(1, uint32(count)) + } + filename, _, err := unmarshalStringSafe(data) // ignore dummy attributes + if err != nil { + return "", err + } + return filename, nil + case sshFxpStatus: + return "", normaliseError(unmarshalStatus(id, data)) + default: + return "", unimplementedPacketErr(typ) + } +} + +// Link creates a hard link at 'newname', pointing at the same inode as 'oldname' +func (c *Client) Link(oldname, newname string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpHardlinkPacket{ + ID: id, + Oldpath: oldname, + Newpath: newname, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +// Symlink creates a symbolic link at 'newname', pointing at target 'oldname' +func (c *Client) Symlink(oldname, newname string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpSymlinkPacket{ + ID: id, + Linkpath: newname, + Targetpath: oldname, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +func (c *Client) fsetstat(handle string, flags uint32, attrs any) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpFsetstatPacket{ + ID: id, + Handle: handle, + Flags: flags, + Attrs: attrs, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +// setstat is a convience wrapper to allow for changing of various parts of the file descriptor. +func (c *Client) setstat(path string, flags uint32, attrs any) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpSetstatPacket{ + ID: id, + Path: path, + Flags: flags, + Attrs: attrs, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +// Chtimes changes the access and modification times of the named file. +func (c *Client) Chtimes(path string, atime time.Time, mtime time.Time) error { + type times struct { + Atime uint32 + Mtime uint32 + } + attrs := times{uint32(atime.Unix()), uint32(mtime.Unix())} + return c.setstat(path, sshFileXferAttrACmodTime, attrs) +} + +// Chown changes the user and group owners of the named file. +func (c *Client) Chown(path string, uid, gid int) error { + type owner struct { + UID uint32 + GID uint32 + } + attrs := owner{uint32(uid), uint32(gid)} + return c.setstat(path, sshFileXferAttrUIDGID, attrs) +} + +// Chmod changes the permissions of the named file. +// +// Chmod does not apply a umask, because even retrieving the umask is not +// possible in a portable way without causing a race condition. Callers +// should mask off umask bits, if desired. +func (c *Client) Chmod(path string, mode os.FileMode) error { + return c.setstat(path, sshFileXferAttrPermissions, toChmodPerm(mode)) +} + +// Truncate sets the size of the named file. Although it may be safely assumed +// that if the size is less than its current size it will be truncated to fit, +// the SFTP protocol does not specify what behavior the server should do when setting +// size greater than the current size. +func (c *Client) Truncate(path string, size int64) error { + return c.setstat(path, sshFileXferAttrSize, uint64(size)) +} + +// SetExtendedData sets extended attributes of the named file. It uses the +// SSH_FILEXFER_ATTR_EXTENDED flag in the setstat request. +// +// This flag provides a general extension mechanism for vendor-specific extensions. +// Names of the attributes should be a string of the format "name@domain", where "domain" +// is a valid, registered domain name and "name" identifies the method. Server +// implementations SHOULD ignore extended data fields that they do not understand. +func (c *Client) SetExtendedData(path string, extended []StatExtended) error { + attrs := &FileStat{ + Extended: extended, + } + return c.setstat(path, sshFileXferAttrExtended, attrs) +} + +// Open opens the named file for reading. If successful, methods on the +// returned file can be used for reading; the associated file descriptor +// has mode O_RDONLY. +func (c *Client) Open(path string) (*File, error) { + return c.open(path, toPflags(os.O_RDONLY)) +} + +// OpenFile is the generalized open call; most users will use Open or +// Create instead. It opens the named file with specified flag (O_RDONLY +// etc.). If successful, methods on the returned File can be used for I/O. +func (c *Client) OpenFile(path string, f int) (*File, error) { + return c.open(path, toPflags(f)) +} + +func (c *Client) open(path string, pflags uint32) (*File, error) { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpOpenPacket{ + ID: id, + Path: path, + Pflags: pflags, + }) + if err != nil { + return nil, err + } + switch typ { + case sshFxpHandle: + data, err := unmarshalSID(id, data) + if err != nil { + return nil, err + } + handle, _, err := unmarshalStringSafe(data) + if err != nil { + return nil, err + } + return &File{c: c, path: path, handle: handle}, nil + case sshFxpStatus: + return nil, normaliseError(unmarshalStatus(id, data)) + default: + return nil, unimplementedPacketErr(typ) + } +} + +// close closes a handle handle previously returned in the response +// to SSH_FXP_OPEN or SSH_FXP_OPENDIR. The handle becomes invalid +// immediately after this request has been sent. +func (c *Client) close(handle string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpClosePacket{ + ID: id, + Handle: handle, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +func (c *Client) stat(path string) (*FileStat, error) { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpStatPacket{ + ID: id, + Path: path, + }) + if err != nil { + return nil, err + } + switch typ { + case sshFxpAttrs: + data, err := unmarshalSID(id, data) + if err != nil { + return nil, err + } + attr, _, err := unmarshalAttrs(data) + return attr, err + case sshFxpStatus: + return nil, normaliseError(unmarshalStatus(id, data)) + default: + return nil, unimplementedPacketErr(typ) + } +} + +func (c *Client) fstat(handle string) (*FileStat, error) { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpFstatPacket{ + ID: id, + Handle: handle, + }) + if err != nil { + return nil, err + } + switch typ { + case sshFxpAttrs: + data, err := unmarshalSID(id, data) + if err != nil { + return nil, err + } + attr, _, err := unmarshalAttrs(data) + return attr, err + case sshFxpStatus: + return nil, normaliseError(unmarshalStatus(id, data)) + default: + return nil, unimplementedPacketErr(typ) + } +} + +// StatVFS retrieves VFS statistics from a remote host. +// +// It implements the statvfs@openssh.com SSH_FXP_EXTENDED feature +// from http://www.opensource.apple.com/source/OpenSSH/OpenSSH-175/openssh/PROTOCOL?txt. +func (c *Client) StatVFS(path string) (*StatVFS, error) { + // send the StatVFS packet to the server + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpStatvfsPacket{ + ID: id, + Path: path, + }) + if err != nil { + return nil, err + } + + switch typ { + // server responded with valid data + case sshFxpExtendedReply: + var response StatVFS + err = binary.Read(bytes.NewReader(data), binary.BigEndian, &response) + if err != nil { + return nil, errors.New("can not parse reply") + } + + return &response, nil + + // the resquest failed + case sshFxpStatus: + return nil, normaliseError(unmarshalStatus(id, data)) + + default: + return nil, unimplementedPacketErr(typ) + } +} + +// Join joins any number of path elements into a single path, adding a +// separating slash if necessary. The result is Cleaned; in particular, all +// empty strings are ignored. +func (c *Client) Join(elem ...string) string { return path.Join(elem...) } + +// Remove removes the specified file or directory. An error will be returned if no +// file or directory with the specified path exists, or if the specified directory +// is not empty. +func (c *Client) Remove(path string) error { + errF := c.removeFile(path) + if errF == nil { + return nil + } + + errD := c.RemoveDirectory(path) + if errD == nil { + return nil + } + + // Both failed: figure out which error to return. + + if errF, ok := errF.(*os.PathError); ok { + // The only time it makes sense to compare errors, is when both are `*os.PathError`. + // We cannot test these directly with errF == errD, as that would be a pointer comparison. + + if errD, ok := errD.(*os.PathError); ok && errors.Is(errF.Err, errD.Err) { + // If they are both pointers to PathError, + // and the same underlying error, then return that. + return errF + } + } + + fi, err := c.Stat(path) + if err != nil { + return err + } + + if fi.IsDir() { + return errD + } + + return errF +} + +func (c *Client) removeFile(path string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpRemovePacket{ + ID: id, + Filename: path, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + err = normaliseError(unmarshalStatus(id, data)) + if err == nil { + return nil + } + return &os.PathError{ + Op: "remove", + Path: path, + Err: err, + } + default: + return unimplementedPacketErr(typ) + } +} + +// RemoveDirectory removes a directory path. +func (c *Client) RemoveDirectory(path string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpRmdirPacket{ + ID: id, + Path: path, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + err = normaliseError(unmarshalStatus(id, data)) + if err == nil { + return nil + } + return &os.PathError{ + Op: "remove", + Path: path, + Err: err, + } + default: + return unimplementedPacketErr(typ) + } +} + +// Rename renames a file. +func (c *Client) Rename(oldname, newname string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpRenamePacket{ + ID: id, + Oldpath: oldname, + Newpath: newname, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +// PosixRename renames a file using the posix-rename@openssh.com extension +// which will replace newname if it already exists. +func (c *Client) PosixRename(oldname, newname string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpPosixRenamePacket{ + ID: id, + Oldpath: oldname, + Newpath: newname, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +// RealPath can be used to have the server canonicalize any given path name to an absolute path. +// +// This is useful for converting path names containing ".." components, +// or relative pathnames without a leading slash into absolute paths. +func (c *Client) RealPath(path string) (string, error) { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpRealpathPacket{ + ID: id, + Path: path, + }) + if err != nil { + return "", err + } + switch typ { + case sshFxpName: + data, err := unmarshalSID(id, data) + if err != nil { + return "", err + } + count, data, err := unmarshalCount(data) + if err != nil { + return "", err + } + if count != 1 { + return "", unexpectedCount(1, uint32(count)) + } + filename, _, err := unmarshalStringSafe(data) // ignore attributes + if err != nil { + return "", err + } + return filename, nil + case sshFxpStatus: + return "", normaliseError(unmarshalStatus(id, data)) + default: + return "", unimplementedPacketErr(typ) + } +} + +// Getwd returns the current working directory of the server. Operations +// involving relative paths will be based at this location. +func (c *Client) Getwd() (string, error) { + return c.RealPath(".") +} + +// Mkdir creates the specified directory. An error will be returned if a file or +// directory with the specified path already exists, or if the directory's +// parent folder does not exist (the method cannot create complete paths). +func (c *Client) Mkdir(path string) error { + id := c.nextID() + typ, data, err := c.sendPacket(context.Background(), nil, &sshFxpMkdirPacket{ + ID: id, + Path: path, + }) + if err != nil { + return err + } + switch typ { + case sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return unimplementedPacketErr(typ) + } +} + +// MkdirAll creates a directory named path, along with any necessary parents, +// and returns nil, or else returns an error. +// If path is already a directory, MkdirAll does nothing and returns nil. +// If, while making any directory, that path is found to already be a regular file, an error is returned. +func (c *Client) MkdirAll(path string) error { + // Most of this code mimics https://golang.org/src/os/path.go?s=514:561#L13 + // Fast path: if we can tell whether path is a directory or file, stop with success or error. + dir, err := c.Stat(path) + if err == nil { + if dir.IsDir() { + return nil + } + return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} + } + + // Slow path: make sure parent exists and then call Mkdir for path. + i := len(path) + for i > 0 && path[i-1] == '/' { // Skip trailing path separator. + i-- + } + + j := i + for j > 0 && path[j-1] != '/' { // Scan backward over element. + j-- + } + + if j > 1 { + // Create parent + err = c.MkdirAll(path[0 : j-1]) + if err != nil { + return err + } + } + + // Parent now exists; invoke Mkdir and use its result. + err = c.Mkdir(path) + if err != nil { + // Handle arguments like "foo/." by + // double-checking that directory doesn't exist. + dir, err1 := c.Lstat(path) + if err1 == nil && dir.IsDir() { + return nil + } + return err + } + return nil +} + +// RemoveAll delete files recursively in the directory and Recursively delete subdirectories. +// An error will be returned if no file or directory with the specified path exists +func (c *Client) RemoveAll(path string) error { + + // Get the file/directory information, without following symlinks + fi, err := c.Lstat(path) + if err != nil { + return err + } + + if fi.IsDir() { + // Delete files recursively in the directory + files, err := c.ReadDir(path) + if err != nil { + return err + } + + for _, file := range files { + if file.IsDir() { + // Recursively delete subdirectories + err = c.RemoveAll(path + "/" + file.Name()) + if err != nil { + return err + } + } else { + // Delete individual files + err = c.Remove(path + "/" + file.Name()) + if err != nil { + return err + } + } + } + + } + + return c.Remove(path) + +} + +// File represents a remote file. +type File struct { + c *Client + path string + + mu sync.RWMutex + handle string + offset int64 // current offset within remote file +} + +// Close closes the File, rendering it unusable for I/O. It returns an +// error, if any. +func (f *File) Close() error { + f.mu.Lock() + defer f.mu.Unlock() + + if f.handle == "" { + return os.ErrClosed + } + + // The design principle here is that when `openssh-portable/sftp-server.c` is doing `handle_close`, + // it will unconditionally mark the handle as unused, + // so we need to also unconditionally mark this handle as invalid. + // By invalidating our local copy of the handle, + // we ensure that there cannot be any erroneous use-after-close requests sent after Close. + + handle := f.handle + f.handle = "" + + return f.c.close(handle) +} + +// Name returns the name of the file as presented to Open or Create. +func (f *File) Name() string { + return f.path +} + +// Read reads up to len(b) bytes from the File. It returns the number of bytes +// read and an error, if any. Read follows io.Reader semantics, so when Read +// encounters an error or EOF condition after successfully reading n > 0 bytes, +// it returns the number of bytes read. +// +// To maximise throughput for transferring the entire file (especially +// over high latency links) it is recommended to use WriteTo rather +// than calling Read multiple times. io.Copy will do this +// automatically. +func (f *File) Read(b []byte) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + + n, err := f.readAt(b, f.offset) + f.offset += int64(n) + return n, err +} + +// readChunkAt attempts to read the whole entire length of the buffer from the file starting at the offset. +// It will continue progressively reading into the buffer until it fills the whole buffer, or an error occurs. +func (f *File) readChunkAt(ch chan result, b []byte, off int64) (n int, err error) { + for err == nil && n < len(b) { + id := f.c.nextID() + typ, data, err := f.c.sendPacket(context.Background(), ch, &sshFxpReadPacket{ + ID: id, + Handle: f.handle, + Offset: uint64(off) + uint64(n), + Len: uint32(len(b) - n), + }) + if err != nil { + return n, err + } + + switch typ { + case sshFxpStatus: + return n, normaliseError(unmarshalStatus(id, data)) + + case sshFxpData: + data, err = unmarshalDataReply(id, data) + if err != nil { + return n, err + } + n += copy(b[n:], data) + + default: + return n, unimplementedPacketErr(typ) + } + } + + return +} + +func (f *File) readAtSequential(b []byte, off int64) (read int, err error) { + for read < len(b) { + rb := b[read:] + if len(rb) > f.c.maxPacket { + rb = rb[:f.c.maxPacket] + } + n, err := f.readChunkAt(nil, rb, off+int64(read)) + if n < 0 { + panic("sftp.File: returned negative count from readChunkAt") + } + if n > 0 { + read += n + } + if err != nil { + return read, err + } + } + return read, nil +} + +// ReadAt reads up to len(b) byte from the File at a given offset `off`. It returns +// the number of bytes read and an error, if any. ReadAt follows io.ReaderAt semantics, +// so the file offset is not altered during the read. +func (f *File) ReadAt(b []byte, off int64) (int, error) { + f.mu.RLock() + defer f.mu.RUnlock() + + return f.readAt(b, off) +} + +// readAt must be called while holding either the Read or Write mutex in File. +// This code is concurrent safe with itself, but not with Close. +func (f *File) readAt(b []byte, off int64) (int, error) { + if f.handle == "" { + return 0, os.ErrClosed + } + + if len(b) <= f.c.maxPacket { + // This should be able to be serviced with 1/2 requests. + // So, just do it directly. + return f.readChunkAt(nil, b, off) + } + + if f.c.disableConcurrentReads { + return f.readAtSequential(b, off) + } + + // Split the read into multiple maxPacket-sized concurrent reads bounded by maxConcurrentRequests. + // This allows writes with a suitably large buffer to transfer data at a much faster rate + // by overlapping round trip times. + + cancel := make(chan struct{}) + + concurrency := len(b)/f.c.maxPacket + 1 + if concurrency > f.c.maxConcurrentRequests || concurrency < 1 { + concurrency = f.c.maxConcurrentRequests + } + + resPool := newResChanPool(concurrency) + + type work struct { + id uint32 + res chan result + + b []byte + off int64 + } + workCh := make(chan work) + + // Slice: cut up the Read into any number of buffers of length <= f.c.maxPacket, and at appropriate offsets. + go func() { + defer close(workCh) + + b := b + offset := off + chunkSize := f.c.maxPacket + + for len(b) > 0 { + rb := b + if len(rb) > chunkSize { + rb = rb[:chunkSize] + } + + id := f.c.nextID() + res := resPool.Get() + + f.c.dispatchRequest(res, &sshFxpReadPacket{ + ID: id, + Handle: f.handle, + Offset: uint64(offset), + Len: uint32(len(rb)), + }) + + select { + case workCh <- work{id, res, rb, offset}: + case <-cancel: + return + } + + offset += int64(len(rb)) + b = b[len(rb):] + } + }() + + type rErr struct { + off int64 + err error + } + errCh := make(chan rErr) + + var wg sync.WaitGroup + wg.Add(concurrency) + for i := 0; i < concurrency; i++ { + // Map_i: each worker gets work, and then performs the Read into its buffer from its respective offset. + go func() { + defer wg.Done() + + for packet := range workCh { + var n int + + s := <-packet.res + resPool.Put(packet.res) + + err := s.err + if err == nil { + switch s.typ { + case sshFxpStatus: + err = normaliseError(unmarshalStatus(packet.id, s.data)) + + case sshFxpData: + var data []byte + data, err = unmarshalDataReply(packet.id, s.data) + if err == nil { + n = copy(packet.b, data) + + // For normal disk files, it is guaranteed that this will read + // the specified number of bytes, or up to end of file. + // This implies, if we have a short read, that means EOF. + if n < len(packet.b) { + err = io.EOF + } + } + + default: + err = unimplementedPacketErr(s.typ) + } + } + + if err != nil { + // return the offset as the start + how much we read before the error. + errCh <- rErr{packet.off + int64(n), err} + + // DO NOT return. + // We want to ensure that workCh is drained before wg.Wait returns. + } + } + }() + } + + // Wait for long tail, before closing results. + go func() { + wg.Wait() + close(errCh) + }() + + // Reduce: collect all the results into a relevant return: the earliest offset to return an error. + firstErr := rErr{math.MaxInt64, nil} + for rErr := range errCh { + if rErr.off <= firstErr.off { + firstErr = rErr + } + + select { + case <-cancel: + default: + // stop any more work from being distributed. (Just in case.) + close(cancel) + } + } + + if firstErr.err != nil { + // firstErr.err != nil if and only if firstErr.off > our starting offset. + return int(firstErr.off - off), firstErr.err + } + + // As per spec for io.ReaderAt, we return nil error if and only if we read everything. + return len(b), nil +} + +// writeToSequential implements WriteTo, but works sequentially with no parallelism. +func (f *File) writeToSequential(w io.Writer) (written int64, err error) { + b := make([]byte, f.c.maxPacket) + ch := make(chan result, 1) // reusable channel + + for { + n, err := f.readChunkAt(ch, b, f.offset) + if n < 0 { + panic("sftp.File: returned negative count from readChunkAt") + } + + if n > 0 { + f.offset += int64(n) + + m, err := w.Write(b[:n]) + written += int64(m) + + if err != nil { + return written, err + } + } + + if err != nil { + if err == io.EOF { + return written, nil // return nil explicitly. + } + + return written, err + } + } +} + +// WriteTo writes the file to the given Writer. +// The return value is the number of bytes written. +// Any error encountered during the write is also returned. +// +// This method is preferred over calling Read multiple times +// to maximise throughput for transferring the entire file, +// especially over high latency links. +func (f *File) WriteTo(w io.Writer) (written int64, err error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.handle == "" { + return 0, os.ErrClosed + } + + if f.c.disableConcurrentReads { + return f.writeToSequential(w) + } + + // For concurrency, we want to guess how many concurrent workers we should use. + var fileStat *FileStat + if f.c.useFstat { + fileStat, err = f.c.fstat(f.handle) + } else { + fileStat, err = f.c.stat(f.path) + } + if err != nil { + return 0, err + } + + fileSize := fileStat.Size + if fileSize <= uint64(f.c.maxPacket) || !isRegular(fileStat.Mode) { + // only regular files are guaranteed to return (full read) xor (partial read, next error) + return f.writeToSequential(w) + } + + concurrency64 := fileSize/uint64(f.c.maxPacket) + 1 // a bad guess, but better than no guess + if concurrency64 > uint64(f.c.maxConcurrentRequests) || concurrency64 < 1 { + concurrency64 = uint64(f.c.maxConcurrentRequests) + } + // Now that concurrency64 is saturated to an int value, we know this assignment cannot possibly overflow. + concurrency := int(concurrency64) + + chunkSize := f.c.maxPacket + pool := newBufPool(concurrency, chunkSize) + resPool := newResChanPool(concurrency) + + cancel := make(chan struct{}) + var wg sync.WaitGroup + defer func() { + // Once the writing Reduce phase has ended, all the feed work needs to unconditionally stop. + close(cancel) + + // We want to wait until all outstanding goroutines with an `f` or `f.c` reference have completed. + // Just to be sure we don’t orphan any goroutines any hanging references. + wg.Wait() + }() + + type writeWork struct { + b []byte + off int64 + err error + + next chan writeWork + } + writeCh := make(chan writeWork) + + type readWork struct { + id uint32 + res chan result + off int64 + + cur, next chan writeWork + } + readCh := make(chan readWork) + + // Slice: hand out chunks of work on demand, with a `cur` and `next` channel built-in for sequencing. + go func() { + defer close(readCh) + + off := f.offset + + cur := writeCh + for { + id := f.c.nextID() + res := resPool.Get() + + next := make(chan writeWork) + readWork := readWork{ + id: id, + res: res, + off: off, + + cur: cur, + next: next, + } + + f.c.dispatchRequest(res, &sshFxpReadPacket{ + ID: id, + Handle: f.handle, + Offset: uint64(off), + Len: uint32(chunkSize), + }) + + select { + case readCh <- readWork: + case <-cancel: + return + } + + off += int64(chunkSize) + cur = next + } + }() + + wg.Add(concurrency) + for i := 0; i < concurrency; i++ { + // Map_i: each worker gets readWork, and does the Read into a buffer at the given offset. + go func() { + defer wg.Done() + + for readWork := range readCh { + var b []byte + var n int + + s := <-readWork.res + resPool.Put(readWork.res) + + err := s.err + if err == nil { + switch s.typ { + case sshFxpStatus: + err = normaliseError(unmarshalStatus(readWork.id, s.data)) + + case sshFxpData: + var data []byte + data, err = unmarshalDataReply(readWork.id, s.data) + if err == nil { + // A malicious server may return more data than we + // requested (up to the packet limit, larger than the + // pool buffer); copy bounds it to the buffer size + // rather than slicing past the page and panicking. + b = pool.Get() + n = copy(b, data) + b = b[:n] + } + + default: + err = unimplementedPacketErr(s.typ) + } + } + + writeWork := writeWork{ + b: b, + off: readWork.off, + err: err, + + next: readWork.next, + } + + select { + case readWork.cur <- writeWork: + case <-cancel: + } + + // DO NOT return. + // We want to ensure that readCh is drained before wg.Wait returns. + } + }() + } + + // Reduce: serialize the results from the reads into sequential writes. + cur := writeCh + for { + packet, ok := <-cur + if !ok { + return written, errors.New("sftp.File.WriteTo: unexpectedly closed channel") + } + + // Because writes are serialized, this will always be the last successfully read byte. + f.offset = packet.off + int64(len(packet.b)) + + if len(packet.b) > 0 { + n, err := w.Write(packet.b) + written += int64(n) + if err != nil { + return written, err + } + } + + if packet.err != nil { + if packet.err == io.EOF { + return written, nil + } + + return written, packet.err + } + + pool.Put(packet.b) + cur = packet.next + } +} + +// Stat returns the FileInfo structure describing file. If there is an +// error. +func (f *File) Stat() (os.FileInfo, error) { + f.mu.RLock() + defer f.mu.RUnlock() + + if f.handle == "" { + return nil, os.ErrClosed + } + + return f.stat() +} + +func (f *File) stat() (os.FileInfo, error) { + fs, err := f.c.fstat(f.handle) + if err != nil { + return nil, err + } + return fileInfoFromStat(fs, path.Base(f.path)), nil +} + +// Write writes len(b) bytes to the File. It returns the number of bytes +// written and an error, if any. Write returns a non-nil error when n != +// len(b). +// +// To maximise throughput for transferring the entire file (especially +// over high latency links) it is recommended to use ReadFrom rather +// than calling Write multiple times. io.Copy will do this +// automatically. +func (f *File) Write(b []byte) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.handle == "" { + return 0, os.ErrClosed + } + + n, err := f.writeAt(b, f.offset) + f.offset += int64(n) + return n, err +} + +func (f *File) writeChunkAt(ch chan result, b []byte, off int64) (int, error) { + typ, data, err := f.c.sendPacket(context.Background(), ch, &sshFxpWritePacket{ + ID: f.c.nextID(), + Handle: f.handle, + Offset: uint64(off), + Length: uint32(len(b)), + Data: b, + }) + if err != nil { + return 0, err + } + + switch typ { + case sshFxpStatus: + id, _, err := unmarshalUint32Safe(data) + if err != nil { + return 0, err + } + err = normaliseError(unmarshalStatus(id, data)) + if err != nil { + return 0, err + } + + default: + return 0, unimplementedPacketErr(typ) + } + + return len(b), nil +} + +// writeAtConcurrent implements WriterAt, but works concurrently rather than sequentially. +func (f *File) writeAtConcurrent(b []byte, off int64) (int, error) { + // Split the write into multiple maxPacket sized concurrent writes + // bounded by maxConcurrentRequests. This allows writes with a suitably + // large buffer to transfer data at a much faster rate due to + // overlapping round trip times. + + cancel := make(chan struct{}) + + type work struct { + id uint32 + res chan result + + off int64 + } + workCh := make(chan work) + + concurrency := len(b)/f.c.maxPacket + 1 + if concurrency > f.c.maxConcurrentRequests || concurrency < 1 { + concurrency = f.c.maxConcurrentRequests + } + + pool := newResChanPool(concurrency) + + // Slice: cut up the Read into any number of buffers of length <= f.c.maxPacket, and at appropriate offsets. + go func() { + defer close(workCh) + + var read int + chunkSize := f.c.maxPacket + + for read < len(b) { + wb := b[read:] + if len(wb) > chunkSize { + wb = wb[:chunkSize] + } + + id := f.c.nextID() + res := pool.Get() + off := off + int64(read) + + f.c.dispatchRequest(res, &sshFxpWritePacket{ + ID: id, + Handle: f.handle, + Offset: uint64(off), + Length: uint32(len(wb)), + Data: wb, + }) + + select { + case workCh <- work{id, res, off}: + case <-cancel: + return + } + + read += len(wb) + } + }() + + type wErr struct { + off int64 + err error + } + errCh := make(chan wErr) + + var wg sync.WaitGroup + wg.Add(concurrency) + for i := 0; i < concurrency; i++ { + // Map_i: each worker gets work, and does the Write from each buffer to its respective offset. + go func() { + defer wg.Done() + + for work := range workCh { + s := <-work.res + pool.Put(work.res) + + err := s.err + if err == nil { + switch s.typ { + case sshFxpStatus: + err = normaliseError(unmarshalStatus(work.id, s.data)) + default: + err = unimplementedPacketErr(s.typ) + } + } + + if err != nil { + errCh <- wErr{work.off, err} + } + } + }() + } + + // Wait for long tail, before closing results. + go func() { + wg.Wait() + close(errCh) + }() + + // Reduce: collect all the results into a relevant return: the earliest offset to return an error. + firstErr := wErr{math.MaxInt64, nil} + for wErr := range errCh { + if wErr.off <= firstErr.off { + firstErr = wErr + } + + select { + case <-cancel: + default: + // stop any more work from being distributed. (Just in case.) + close(cancel) + } + } + + if firstErr.err != nil { + // firstErr.err != nil if and only if firstErr.off >= our starting offset. + return int(firstErr.off - off), firstErr.err + } + + return len(b), nil +} + +// WriteAt writes up to len(b) byte to the File at a given offset `off`. It returns +// the number of bytes written and an error, if any. WriteAt follows io.WriterAt semantics, +// so the file offset is not altered during the write. +func (f *File) WriteAt(b []byte, off int64) (written int, err error) { + f.mu.RLock() + defer f.mu.RUnlock() + + if f.handle == "" { + return 0, os.ErrClosed + } + + return f.writeAt(b, off) +} + +// writeAt must be called while holding either the Read or Write mutex in File. +// This code is concurrent safe with itself, but not with Close. +func (f *File) writeAt(b []byte, off int64) (written int, err error) { + if len(b) <= f.c.maxPacket { + // We can do this in one write. + return f.writeChunkAt(nil, b, off) + } + + if f.c.useConcurrentWrites { + return f.writeAtConcurrent(b, off) + } + + ch := make(chan result, 1) // reusable channel + + chunkSize := f.c.maxPacket + + for written < len(b) { + wb := b[written:] + if len(wb) > chunkSize { + wb = wb[:chunkSize] + } + + n, err := f.writeChunkAt(ch, wb, off+int64(written)) + if n > 0 { + written += n + } + + if err != nil { + return written, err + } + } + + return len(b), nil +} + +// ReadFromWithConcurrency implements ReaderFrom, +// but uses the given concurrency to issue multiple requests at the same time. +// +// Giving a concurrency of less than one will default to the Client’s max concurrency. +// +// Otherwise, the given concurrency will be capped by the Client's max concurrency. +// +// When one needs to guarantee concurrent reads/writes, this method is preferred +// over ReadFrom. +func (f *File) ReadFromWithConcurrency(r io.Reader, concurrency int) (read int64, err error) { + f.mu.Lock() + defer f.mu.Unlock() + + return f.readFromWithConcurrency(r, concurrency) +} + +func (f *File) readFromWithConcurrency(r io.Reader, concurrency int) (read int64, err error) { + if f.handle == "" { + return 0, os.ErrClosed + } + + // Split the write into multiple maxPacket sized concurrent writes. + // This allows writes with a suitably large reader + // to transfer data at a much faster rate due to overlapping round trip times. + + cancel := make(chan struct{}) + + type work struct { + id uint32 + res chan result + + off int64 + } + workCh := make(chan work) + + type rwErr struct { + off int64 + err error + } + errCh := make(chan rwErr) + + if concurrency > f.c.maxConcurrentRequests || concurrency < 1 { + concurrency = f.c.maxConcurrentRequests + } + + pool := newResChanPool(concurrency) + + // Slice: cut up the Read into any number of buffers of length <= f.c.maxPacket, and at appropriate offsets. + go func() { + defer close(workCh) + + b := make([]byte, f.c.maxPacket) + off := f.offset + + for { + // Fill the entire buffer. + n, err := readFull(r, b) + + if n > 0 { + read += int64(n) + + id := f.c.nextID() + res := pool.Get() + + f.c.dispatchRequest(res, &sshFxpWritePacket{ + ID: id, + Handle: f.handle, + Offset: uint64(off), + Length: uint32(n), + Data: b[:n], + }) + + select { + case workCh <- work{id, res, off}: + case <-cancel: + return + } + + off += int64(n) + } + + if err != nil { + if !errors.Is(err, io.EOF) { + errCh <- rwErr{off, err} + } + return + } + } + }() + + var wg sync.WaitGroup + wg.Add(concurrency) + for i := 0; i < concurrency; i++ { + // Map_i: each worker gets work, and does the Write from each buffer to its respective offset. + go func() { + defer wg.Done() + + for work := range workCh { + s := <-work.res + pool.Put(work.res) + + err := s.err + if err == nil { + switch s.typ { + case sshFxpStatus: + err = normaliseError(unmarshalStatus(work.id, s.data)) + default: + err = unimplementedPacketErr(s.typ) + } + } + + if err != nil { + errCh <- rwErr{work.off, err} + + // DO NOT return. + // We want to ensure that workCh is drained before wg.Wait returns. + } + } + }() + } + + // Wait for long tail, before closing results. + go func() { + wg.Wait() + close(errCh) + }() + + // Reduce: Collect all the results into a relevant return: the earliest offset to return an error. + firstErr := rwErr{math.MaxInt64, nil} + for rwErr := range errCh { + if rwErr.off <= firstErr.off { + firstErr = rwErr + } + + select { + case <-cancel: + default: + // stop any more work from being distributed. + close(cancel) + } + } + + if firstErr.err != nil { + // firstErr.err != nil if and only if firstErr.off is a valid offset. + // + // firstErr.off will then be the lesser of: + // * the offset of the first error from writing, + // * the last successfully read offset. + // + // This could be less than the last successfully written offset, + // which is the whole reason for the UseConcurrentWrites() ClientOption. + // + // Callers are responsible for truncating any SFTP files to a safe length. + f.offset = firstErr.off + + // ReadFrom is defined to return the read bytes, regardless of any writer errors. + return read, firstErr.err + } + + f.offset += read + return read, nil +} + +// ReadFrom reads data from r until EOF and writes it to the file. The return +// value is the number of bytes read. Any error except io.EOF encountered +// during the read is also returned. +// +// This method is preferred over calling Write multiple times +// to maximise throughput for transferring the entire file, +// especially over high-latency links. +// +// To ensure concurrent writes, the given r needs to implement one of +// the following receiver methods: +// +// Len() int +// Size() int64 +// Stat() (os.FileInfo, error) +// +// or be an instance of [io.LimitedReader] to determine the number of possible +// concurrent requests. Otherwise, reads/writes are performed sequentially. +// ReadFromWithConcurrency can be used explicitly to guarantee concurrent +// processing of the reader. +func (f *File) ReadFrom(r io.Reader) (int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.handle == "" { + return 0, os.ErrClosed + } + + if f.c.useConcurrentWrites { + var remain int64 + switch r := r.(type) { + case interface{ Len() int }: + remain = int64(r.Len()) + + case interface{ Size() int64 }: + remain = r.Size() + + case *io.LimitedReader: + remain = r.N + + case interface{ Stat() (os.FileInfo, error) }: + info, err := r.Stat() + if err == nil { + remain = info.Size() + } + } + + if remain < 0 { + // We can strongly assert that we want default max concurrency here. + return f.readFromWithConcurrency(r, f.c.maxConcurrentRequests) + } + + if remain > int64(f.c.maxPacket) { + // Otherwise, only use concurrency, if it would be at least two packets. + + // This is the best reasonable guess we can make. + concurrency64 := remain/int64(f.c.maxPacket) + 1 + + // We need to cap this value to an `int` size value to avoid overflow on 32-bit machines. + // So, we may as well pre-cap it to `f.c.maxConcurrentRequests`. + if concurrency64 > int64(f.c.maxConcurrentRequests) { + concurrency64 = int64(f.c.maxConcurrentRequests) + } + + return f.readFromWithConcurrency(r, int(concurrency64)) + } + } + + ch := make(chan result, 1) // reusable channel + + b := make([]byte, f.c.maxPacket) + + var read int64 + for { + // Fill the entire buffer. + n, err := readFull(r, b) + if n < 0 { + panic("sftp.File: reader returned negative count from Read") + } + + if n > 0 { + read += int64(n) + + m, err2 := f.writeChunkAt(ch, b[:n], f.offset) + f.offset += int64(m) + + if err == nil || (err2 != nil && errors.Is(err, io.EOF)) { + err = err2 + } + } + + if err != nil { + if errors.Is(err, io.EOF) { + return read, nil // return nil explicitly. + } + + return read, err + } + } +} + +// readFull reads from r into b until b is full or r returns an error. +// Unlike io.ReadFull, it returns the error from r unchanged. +// io.ReadFull turns an io.EOF after a partial read into io.ErrUnexpectedEOF, +// which can't be told apart from an io.ErrUnexpectedEOF returned by r itself. +func readFull(r io.Reader, b []byte) (n int, err error) { + for n < len(b) && err == nil { + var nn int + nn, err = r.Read(b[n:]) + n += nn + } + return n, err +} + +// Seek implements io.Seeker by setting the client offset for the next Read or +// Write. It returns the next offset read. Seeking before or after the end of +// the file is undefined. Seeking relative to the end calls Stat. +func (f *File) Seek(offset int64, whence int) (int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.handle == "" { + return 0, os.ErrClosed + } + + switch whence { + case io.SeekStart: + case io.SeekCurrent: + offset += f.offset + case io.SeekEnd: + fi, err := f.stat() + if err != nil { + return f.offset, err + } + offset += fi.Size() + default: + return f.offset, unimplementedSeekWhence(whence) + } + + if offset < 0 { + return f.offset, os.ErrInvalid + } + + f.offset = offset + return f.offset, nil +} + +// Chown changes the uid/gid of the current file. +func (f *File) Chown(uid, gid int) error { + f.mu.RLock() + defer f.mu.RUnlock() + + if f.handle == "" { + return os.ErrClosed + } + + return f.c.fsetstat(f.handle, sshFileXferAttrUIDGID, &FileStat{ + UID: uint32(uid), + GID: uint32(gid), + }) +} + +// Chmod changes the permissions of the current file. +// +// See Client.Chmod for details. +func (f *File) Chmod(mode os.FileMode) error { + f.mu.RLock() + defer f.mu.RUnlock() + + if f.handle == "" { + return os.ErrClosed + } + + return f.c.fsetstat(f.handle, sshFileXferAttrPermissions, toChmodPerm(mode)) +} + +// SetExtendedData sets extended attributes of the current file. It uses the +// SSH_FILEXFER_ATTR_EXTENDED flag in the setstat request. +// +// This flag provides a general extension mechanism for vendor-specific extensions. +// Names of the attributes should be a string of the format "name@domain", where "domain" +// is a valid, registered domain name and "name" identifies the method. Server +// implementations SHOULD ignore extended data fields that they do not understand. +func (f *File) SetExtendedData(path string, extended []StatExtended) error { + f.mu.RLock() + defer f.mu.RUnlock() + + if f.handle == "" { + return os.ErrClosed + } + + attrs := &FileStat{ + Extended: extended, + } + + return f.c.fsetstat(f.handle, sshFileXferAttrExtended, attrs) +} + +// Truncate sets the size of the current file. Although it may be safely assumed +// that if the size is less than its current size it will be truncated to fit, +// the SFTP protocol does not specify what behavior the server should do when setting +// size greater than the current size. +// We send a SSH_FXP_FSETSTAT here since we have a file handle +func (f *File) Truncate(size int64) error { + f.mu.RLock() + defer f.mu.RUnlock() + + if f.handle == "" { + return os.ErrClosed + } + + return f.c.fsetstat(f.handle, sshFileXferAttrSize, uint64(size)) +} + +// Sync requests a flush of the contents of a File to stable storage. +// +// Sync requires the server to support the fsync@openssh.com extension. +func (f *File) Sync() error { + f.mu.Lock() + defer f.mu.Unlock() + + if f.handle == "" { + return os.ErrClosed + } + + if data, ok := f.c.HasExtension(openssh.ExtensionFSync().Name); !ok || data != "1" { + return &StatusError{ + Code: sshFxOPUnsupported, + msg: "fsync not supported", + } + } + + id := f.c.nextID() + typ, data, err := f.c.sendPacket(context.Background(), nil, &sshFxpFsyncPacket{ + ID: id, + Handle: f.handle, + }) + + switch { + case err != nil: + return err + case typ == sshFxpStatus: + return normaliseError(unmarshalStatus(id, data)) + default: + return &unexpectedPacketErr{want: sshFxpStatus, got: typ} + } +} + +// normaliseError normalises an error into a more standard form that can be +// checked against stdlib errors like io.EOF or os.ErrNotExist. +func normaliseError(err error) error { + switch err := err.(type) { + case *StatusError: + switch err.Code { + case sshFxEOF: + return io.EOF + case sshFxNoSuchFile: + return os.ErrNotExist + case sshFxPermissionDenied: + return os.ErrPermission + case sshFxOk: + return nil + default: + return err + } + default: + return err + } +} + +// flags converts the flags passed to OpenFile into ssh flags. +// Unsupported flags are ignored. +func toPflags(f int) uint32 { + var out uint32 + switch f & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR) { + case os.O_RDONLY: + out |= sshFxfRead + case os.O_WRONLY: + out |= sshFxfWrite + case os.O_RDWR: + out |= sshFxfRead | sshFxfWrite + } + if f&os.O_APPEND == os.O_APPEND { + out |= sshFxfAppend + } + if f&os.O_CREATE == os.O_CREATE { + out |= sshFxfCreat + } + if f&os.O_TRUNC == os.O_TRUNC { + out |= sshFxfTrunc + } + if f&os.O_EXCL == os.O_EXCL { + out |= sshFxfExcl + } + return out +} + +// toChmodPerm converts Go permission bits to POSIX permission bits. +// +// This differs from fromFileMode in that we preserve the POSIX versions of +// setuid, setgid and sticky in m, because we've historically supported those +// bits, and we mask off any non-permission bits. +func toChmodPerm(m os.FileMode) (perm uint32) { + const mask = os.ModePerm | os.FileMode(s_ISUID|s_ISGID|s_ISVTX) + perm = uint32(m & mask) + + if m&os.ModeSetuid != 0 { + perm |= s_ISUID + } + if m&os.ModeSetgid != 0 { + perm |= s_ISGID + } + if m&os.ModeSticky != 0 { + perm |= s_ISVTX + } + + return perm +} diff --git a/vendor/github.com/pkg/sftp/conn.go b/vendor/github.com/pkg/sftp/conn.go new file mode 100644 index 00000000..e68a2bd0 --- /dev/null +++ b/vendor/github.com/pkg/sftp/conn.go @@ -0,0 +1,212 @@ +package sftp + +import ( + "context" + "encoding" + "fmt" + "io" + "sync" +) + +// conn implements a bidirectional channel on which client and server +// connections are multiplexed. +type conn struct { + io.Reader + io.WriteCloser + // this is the same allocator used in packet manager + alloc *allocator + sync.Mutex // used to serialise writes to sendPacket +} + +// the orderID is used in server mode if the allocator is enabled. +// For the client mode just pass 0. +// It returns io.EOF if the connection is closed and +// there are no more packets to read. +func (c *conn) recvPacket(orderID uint32) (fxp, []byte, error) { + return recvPacket(c, c.alloc, orderID) +} + +func (c *conn) sendPacket(m encoding.BinaryMarshaler) error { + c.Lock() + defer c.Unlock() + + return sendPacket(c, m) +} + +func (c *conn) Close() error { + c.Lock() + defer c.Unlock() + return c.WriteCloser.Close() +} + +type clientConn struct { + conn + wg sync.WaitGroup + + wait func() error // if non-nil, call this during Wait() to get a possible remote status error. + + sync.Mutex // protects inflight + inflight map[uint32]chan<- result // outstanding requests + + closed chan struct{} + err error +} + +// Wait blocks until the conn has shut down, and return the error +// causing the shutdown. It can be called concurrently from multiple +// goroutines. +func (c *clientConn) Wait() error { + <-c.closed + + if c.wait == nil { + // Only return this error if c.wait won't return something more useful. + return c.err + } + + if err := c.wait(); err != nil { + + // TODO: when https://github.com/golang/go/issues/35025 is fixed, + // we can remove this if block entirely. + // Right now, it’s always going to return this, so it is not useful. + // But we have this code here so that as soon as the ssh library is updated, + // we can return a possibly more useful error. + if err.Error() == "ssh: session not started" { + return c.err + } + + return err + } + + // c.wait returned no error; so, let's return something maybe more useful. + return c.err +} + +// Close closes the SFTP session. +func (c *clientConn) Close() error { + defer c.wg.Wait() + return c.conn.Close() +} + +// recv continuously reads from the server and forwards responses to the +// appropriate channel. +func (c *clientConn) recv() error { + defer c.conn.Close() + + for { + typ, data, err := c.recvPacket(0) + if err != nil { + return err + } + sid, _, err := unmarshalUint32Safe(data) + if err != nil { + return err + } + + ch, ok := c.getChannel(sid) + if !ok { + // This is an unexpected occurrence. Send the error + // back to all listeners so that they terminate + // gracefully. + return fmt.Errorf("sid not found: %d", sid) + } + + ch <- result{typ: typ, data: data} + } +} + +func (c *clientConn) putChannel(ch chan<- result, sid uint32) bool { + c.Lock() + defer c.Unlock() + + select { + case <-c.closed: + // already closed with broadcastErr, return error on chan. + ch <- result{err: ErrSSHFxConnectionLost} + return false + default: + } + + c.inflight[sid] = ch + return true +} + +func (c *clientConn) getChannel(sid uint32) (chan<- result, bool) { + c.Lock() + defer c.Unlock() + + ch, ok := c.inflight[sid] + delete(c.inflight, sid) + + return ch, ok +} + +// result captures the result of receiving the a packet from the server +type result struct { + typ fxp + data []byte + err error +} + +type idmarshaler interface { + id() uint32 + encoding.BinaryMarshaler +} + +func (c *clientConn) sendPacket(ctx context.Context, ch chan result, p idmarshaler) (fxp, []byte, error) { + if cap(ch) < 1 { + ch = make(chan result, 1) + } + + c.dispatchRequest(ch, p) + + select { + case <-ctx.Done(): + return 0, nil, ctx.Err() + case s := <-ch: + return s.typ, s.data, s.err + } +} + +// dispatchRequest should ideally only be called by race-detection tests outside of this file, +// where you have to ensure two packets are in flight sequentially after each other. +func (c *clientConn) dispatchRequest(ch chan<- result, p idmarshaler) { + sid := p.id() + + if !c.putChannel(ch, sid) { + // already closed. + return + } + + if err := c.conn.sendPacket(p); err != nil { + if ch, ok := c.getChannel(sid); ok { + ch <- result{err: err} + } + } +} + +// broadcastErr sends an error to all goroutines waiting for a response. +func (c *clientConn) broadcastErr(err error) { + c.Lock() + defer c.Unlock() + + bcastRes := result{err: ErrSSHFxConnectionLost} + for sid, ch := range c.inflight { + ch <- bcastRes + + // Replace the chan in inflight, + // we have hijacked this chan, + // and this guarantees always-only-once sending. + c.inflight[sid] = make(chan<- result, 1) + } + + c.err = err + close(c.closed) +} + +type serverConn struct { + conn +} + +func (s *serverConn) sendError(id uint32, err error) error { + return s.sendPacket(statusFromError(id, err)) +} diff --git a/vendor/github.com/pkg/sftp/debug.go b/vendor/github.com/pkg/sftp/debug.go new file mode 100644 index 00000000..f14febb8 --- /dev/null +++ b/vendor/github.com/pkg/sftp/debug.go @@ -0,0 +1,10 @@ +//go:build debug +// +build debug + +package sftp + +import "log" + +func debug(fmt string, args ...any) { + log.Printf(fmt, args...) +} diff --git a/vendor/github.com/pkg/sftp/errno_plan9.go b/vendor/github.com/pkg/sftp/errno_plan9.go new file mode 100644 index 00000000..cf9d3902 --- /dev/null +++ b/vendor/github.com/pkg/sftp/errno_plan9.go @@ -0,0 +1,42 @@ +package sftp + +import ( + "os" + "syscall" +) + +var EBADF = syscall.NewError("fd out of range or not open") + +func wrapPathError(filepath string, err error) error { + if errno, ok := err.(syscall.ErrorString); ok { + return &os.PathError{Path: filepath, Err: errno} + } + return err +} + +// translateErrno translates a syscall error number to a SFTP error code. +func translateErrno(errno syscall.ErrorString) uint32 { + switch errno { + case "": + return sshFxOk + case syscall.ENOENT: + return sshFxNoSuchFile + case syscall.EPERM: + return sshFxPermissionDenied + } + + return sshFxFailure +} + +func translateSyscallError(err error) (uint32, bool) { + switch e := err.(type) { + case syscall.ErrorString: + return translateErrno(e), true + case *os.PathError: + debug("statusFromError,pathError: error is %T %#v", e.Err, e.Err) + if errno, ok := e.Err.(syscall.ErrorString); ok { + return translateErrno(errno), true + } + } + return 0, false +} diff --git a/vendor/github.com/pkg/sftp/errno_posix.go b/vendor/github.com/pkg/sftp/errno_posix.go new file mode 100644 index 00000000..cd87e1b5 --- /dev/null +++ b/vendor/github.com/pkg/sftp/errno_posix.go @@ -0,0 +1,45 @@ +//go:build !plan9 +// +build !plan9 + +package sftp + +import ( + "os" + "syscall" +) + +const EBADF = syscall.EBADF + +func wrapPathError(filepath string, err error) error { + if errno, ok := err.(syscall.Errno); ok { + return &os.PathError{Path: filepath, Err: errno} + } + return err +} + +// translateErrno translates a syscall error number to a SFTP error code. +func translateErrno(errno syscall.Errno) uint32 { + switch errno { + case 0: + return sshFxOk + case syscall.ENOENT: + return sshFxNoSuchFile + case syscall.EACCES, syscall.EPERM: + return sshFxPermissionDenied + } + + return sshFxFailure +} + +func translateSyscallError(err error) (uint32, bool) { + switch e := err.(type) { + case syscall.Errno: + return translateErrno(e), true + case *os.PathError: + debug("statusFromError,pathError: error is %T %#v", e.Err, e.Err) + if errno, ok := e.Err.(syscall.Errno); ok { + return translateErrno(errno), true + } + } + return 0, false +} diff --git a/vendor/github.com/pkg/sftp/fuzz.go b/vendor/github.com/pkg/sftp/fuzz.go new file mode 100644 index 00000000..f2f1fc31 --- /dev/null +++ b/vendor/github.com/pkg/sftp/fuzz.go @@ -0,0 +1,23 @@ +//go:build gofuzz +// +build gofuzz + +package sftp + +import "bytes" + +type sinkfuzz struct{} + +func (*sinkfuzz) Close() error { return nil } +func (*sinkfuzz) Write(p []byte) (int, error) { return len(p), nil } + +var devnull = &sinkfuzz{} + +// To run: go-fuzz-build && go-fuzz +func Fuzz(data []byte) int { + c, err := NewClientPipe(bytes.NewReader(data), devnull) + if err != nil { + return 0 + } + c.Close() + return 1 +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/attrs.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/attrs.go new file mode 100644 index 00000000..3aec937f --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/attrs.go @@ -0,0 +1,296 @@ +package sshfx + +// Attributes related flags. +const ( + AttrSize = 1 << iota // SSH_FILEXFER_ATTR_SIZE + AttrUIDGID // SSH_FILEXFER_ATTR_UIDGID + AttrPermissions // SSH_FILEXFER_ATTR_PERMISSIONS + AttrACModTime // SSH_FILEXFER_ACMODTIME + + AttrExtended = 1 << 31 // SSH_FILEXFER_ATTR_EXTENDED +) + +// Attributes defines the file attributes type defined in draft-ietf-secsh-filexfer-02 +// +// Defined in: https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-5 +type Attributes struct { + Flags uint32 + + // AttrSize + Size uint64 + + // AttrUIDGID + UID uint32 + GID uint32 + + // AttrPermissions + Permissions FileMode + + // AttrACmodTime + ATime uint32 + MTime uint32 + + // AttrExtended + ExtendedAttributes []ExtendedAttribute +} + +// GetSize returns the Size field and a bool that is true if and only if the value is valid/defined. +func (a *Attributes) GetSize() (size uint64, ok bool) { + return a.Size, a.Flags&AttrSize != 0 +} + +// SetSize is a convenience function that sets the Size field, +// and marks the field as valid/defined in Flags. +func (a *Attributes) SetSize(size uint64) { + a.Flags |= AttrSize + a.Size = size +} + +// GetUIDGID returns the UID and GID fields and a bool that is true if and only if the values are valid/defined. +func (a *Attributes) GetUIDGID() (uid, gid uint32, ok bool) { + return a.UID, a.GID, a.Flags&AttrUIDGID != 0 +} + +// SetUIDGID is a convenience function that sets the UID and GID fields, +// and marks the fields as valid/defined in Flags. +func (a *Attributes) SetUIDGID(uid, gid uint32) { + a.Flags |= AttrUIDGID + a.UID = uid + a.GID = gid +} + +// GetPermissions returns the Permissions field and a bool that is true if and only if the value is valid/defined. +func (a *Attributes) GetPermissions() (perms FileMode, ok bool) { + return a.Permissions, a.Flags&AttrPermissions != 0 +} + +// SetPermissions is a convenience function that sets the Permissions field, +// and marks the field as valid/defined in Flags. +func (a *Attributes) SetPermissions(perms FileMode) { + a.Flags |= AttrPermissions + a.Permissions = perms +} + +// GetACModTime returns the ATime and MTime fields and a bool that is true if and only if the values are valid/defined. +func (a *Attributes) GetACModTime() (atime, mtime uint32, ok bool) { + return a.ATime, a.MTime, a.Flags&AttrACModTime != 0 +} + +// SetACModTime is a convenience function that sets the ATime and MTime fields, +// and marks the fields as valid/defined in Flags. +func (a *Attributes) SetACModTime(atime, mtime uint32) { + a.Flags |= AttrACModTime + a.ATime = atime + a.MTime = mtime +} + +// Len returns the number of bytes a would marshal into. +func (a *Attributes) Len() int { + length := 4 + + if a.Flags&AttrSize != 0 { + length += 8 + } + + if a.Flags&AttrUIDGID != 0 { + length += 4 + 4 + } + + if a.Flags&AttrPermissions != 0 { + length += 4 + } + + if a.Flags&AttrACModTime != 0 { + length += 4 + 4 + } + + if a.Flags&AttrExtended != 0 { + length += 4 + + for _, ext := range a.ExtendedAttributes { + length += ext.Len() + } + } + + return length +} + +// MarshalInto marshals e onto the end of the given Buffer. +func (a *Attributes) MarshalInto(buf *Buffer) { + buf.AppendUint32(a.Flags) + + if a.Flags&AttrSize != 0 { + buf.AppendUint64(a.Size) + } + + if a.Flags&AttrUIDGID != 0 { + buf.AppendUint32(a.UID) + buf.AppendUint32(a.GID) + } + + if a.Flags&AttrPermissions != 0 { + buf.AppendUint32(uint32(a.Permissions)) + } + + if a.Flags&AttrACModTime != 0 { + buf.AppendUint32(a.ATime) + buf.AppendUint32(a.MTime) + } + + if a.Flags&AttrExtended != 0 { + buf.AppendUint32(uint32(len(a.ExtendedAttributes))) + + for _, ext := range a.ExtendedAttributes { + ext.MarshalInto(buf) + } + } +} + +// MarshalBinary returns a as the binary encoding of a. +func (a *Attributes) MarshalBinary() ([]byte, error) { + buf := NewBuffer(make([]byte, 0, a.Len())) + a.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom unmarshals an Attributes from the given Buffer into e. +// +// NOTE: The values of fields not covered in the a.Flags are explicitly undefined. +func (a *Attributes) UnmarshalFrom(buf *Buffer) (err error) { + flags := buf.ConsumeUint32() + + return a.XXX_UnmarshalByFlags(flags, buf) +} + +// XXX_UnmarshalByFlags uses the pre-existing a.Flags field to determine which fields to decode. +// DO NOT USE THIS: it is an anti-corruption function to implement existing internal usage in pkg/sftp. +// This function is not a part of any compatibility promise. +func (a *Attributes) XXX_UnmarshalByFlags(flags uint32, buf *Buffer) (err error) { + a.Flags = flags + + // Short-circuit dummy attributes. + if a.Flags == 0 { + return buf.Err + } + + if a.Flags&AttrSize != 0 { + a.Size = buf.ConsumeUint64() + } + + if a.Flags&AttrUIDGID != 0 { + a.UID = buf.ConsumeUint32() + a.GID = buf.ConsumeUint32() + } + + if a.Flags&AttrPermissions != 0 { + a.Permissions = FileMode(buf.ConsumeUint32()) + } + + if a.Flags&AttrACModTime != 0 { + a.ATime = buf.ConsumeUint32() + a.MTime = buf.ConsumeUint32() + } + + if a.Flags&AttrExtended != 0 { + count := buf.ConsumeCount() + + a.ExtendedAttributes = make([]ExtendedAttribute, count) + for i := range a.ExtendedAttributes { + a.ExtendedAttributes[i].UnmarshalFrom(buf) + } + } + + return buf.Err +} + +// UnmarshalBinary decodes the binary encoding of Attributes into e. +func (a *Attributes) UnmarshalBinary(data []byte) error { + return a.UnmarshalFrom(NewBuffer(data)) +} + +// ExtendedAttribute defines the extended file attribute type defined in draft-ietf-secsh-filexfer-02 +// +// Defined in: https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-5 +type ExtendedAttribute struct { + Type string + Data string +} + +// Len returns the number of bytes e would marshal into. +func (e *ExtendedAttribute) Len() int { + return 4 + len(e.Type) + 4 + len(e.Data) +} + +// MarshalInto marshals e onto the end of the given Buffer. +func (e *ExtendedAttribute) MarshalInto(buf *Buffer) { + buf.AppendString(e.Type) + buf.AppendString(e.Data) +} + +// MarshalBinary returns e as the binary encoding of e. +func (e *ExtendedAttribute) MarshalBinary() ([]byte, error) { + buf := NewBuffer(make([]byte, 0, e.Len())) + e.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom unmarshals an ExtendedAattribute from the given Buffer into e. +func (e *ExtendedAttribute) UnmarshalFrom(buf *Buffer) (err error) { + *e = ExtendedAttribute{ + Type: buf.ConsumeString(), + Data: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the binary encoding of ExtendedAttribute into e. +func (e *ExtendedAttribute) UnmarshalBinary(data []byte) error { + return e.UnmarshalFrom(NewBuffer(data)) +} + +// NameEntry implements the SSH_FXP_NAME repeated data type from draft-ietf-secsh-filexfer-02 +// +// This type is incompatible with versions 4 or higher. +type NameEntry struct { + Filename string + Longname string + Attrs Attributes +} + +// Len returns the number of bytes e would marshal into. +func (e *NameEntry) Len() int { + return 4 + len(e.Filename) + 4 + len(e.Longname) + e.Attrs.Len() +} + +// MarshalInto marshals e onto the end of the given Buffer. +func (e *NameEntry) MarshalInto(buf *Buffer) { + buf.AppendString(e.Filename) + buf.AppendString(e.Longname) + + e.Attrs.MarshalInto(buf) +} + +// MarshalBinary returns e as the binary encoding of e. +func (e *NameEntry) MarshalBinary() ([]byte, error) { + buf := NewBuffer(make([]byte, 0, e.Len())) + e.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom unmarshals an NameEntry from the given Buffer into e. +// +// NOTE: The values of fields not covered in the a.Flags are explicitly undefined. +func (e *NameEntry) UnmarshalFrom(buf *Buffer) (err error) { + *e = NameEntry{ + Filename: buf.ConsumeString(), + Longname: buf.ConsumeString(), + } + + return e.Attrs.UnmarshalFrom(buf) +} + +// UnmarshalBinary decodes the binary encoding of NameEntry into e. +func (e *NameEntry) UnmarshalBinary(data []byte) error { + return e.UnmarshalFrom(NewBuffer(data)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/buffer.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/buffer.go new file mode 100644 index 00000000..bd4783bb --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/buffer.go @@ -0,0 +1,340 @@ +package sshfx + +import ( + "encoding/binary" + "errors" +) + +// Various encoding errors. +var ( + ErrShortPacket = errors.New("packet too short") + ErrLongPacket = errors.New("packet too long") +) + +// Buffer wraps up the various encoding details of the SSH format. +// +// Data types are encoded as per section 4 from https://tools.ietf.org/html/draft-ietf-secsh-architecture-09#page-8 +type Buffer struct { + b []byte + off int + Err error +} + +// NewBuffer creates and initializes a new buffer using buf as its initial contents. +// The new buffer takes ownership of buf, and the caller should not use buf after this call. +// +// In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer. +func NewBuffer(buf []byte) *Buffer { + return &Buffer{ + b: buf, + } +} + +// NewMarshalBuffer creates a new Buffer ready to start marshaling a Packet into. +// It preallocates enough space for uint32(length), uint8(type), uint32(request-id) and size more bytes. +func NewMarshalBuffer(size int) *Buffer { + return NewBuffer(make([]byte, 4+1+4+size)) +} + +// Bytes returns a slice of length b.Len() holding the unconsumed bytes in the Buffer. +// The slice is valid for use only until the next buffer modification +// (that is, only until the next call to an Append or Consume method). +func (b *Buffer) Bytes() []byte { + return b.b[b.off:] +} + +// Len returns the number of unconsumed bytes in the buffer. +func (b *Buffer) Len() int { return len(b.b) - b.off } + +// Cap returns the capacity of the buffer’s underlying byte slice, +// that is, the total space allocated for the buffer’s data. +func (b *Buffer) Cap() int { return cap(b.b) } + +// Reset resets the buffer to be empty, but it retains the underlying storage for use by future Appends. +func (b *Buffer) Reset() { + *b = Buffer{ + b: b.b[:0], + } +} + +// StartPacket resets and initializes the buffer to be ready to start marshaling a packet into. +// It truncates the buffer, reserves space for uint32(length), then appends the given packetType and requestID. +func (b *Buffer) StartPacket(packetType PacketType, requestID uint32) { + *b = Buffer{ + b: append(b.b[:0], make([]byte, 4)...), + } + + b.AppendUint8(uint8(packetType)) + b.AppendUint32(requestID) +} + +// Packet finalizes the packet started from StartPacket. +// It is expected that this will end the ownership of the underlying byte-slice, +// and so the returned byte-slices may be reused the same as any other byte-slice, +// the caller should not use this buffer after this call. +// +// It writes the packet body length into the first four bytes of the buffer in network byte order (big endian). +// The packet body length is the length of this buffer less the 4-byte length itself, plus the length of payload. +// +// It is assumed that no Consume methods have been called on this buffer, +// and so it returns the whole underlying slice. +func (b *Buffer) Packet(payload []byte) (header, payloadPassThru []byte, err error) { + b.PutLength(len(b.b) - 4 + len(payload)) + + return b.b, payload, nil +} + +// ConsumeUint8 consumes a single byte from the buffer. +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeUint8() uint8 { + if b.Err != nil { + return 0 + } + + if b.Len() < 1 { + b.off = len(b.b) + b.Err = ErrShortPacket + return 0 + } + + var v uint8 + v, b.off = b.b[b.off], b.off+1 + return v +} + +// AppendUint8 appends a single byte into the buffer. +func (b *Buffer) AppendUint8(v uint8) { + b.b = append(b.b, v) +} + +// ConsumeBool consumes a single byte from the buffer, and returns true if that byte is non-zero. +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeBool() bool { + return b.ConsumeUint8() != 0 +} + +// AppendBool appends a single bool into the buffer. +// It encodes it as a single byte, with false as 0, and true as 1. +func (b *Buffer) AppendBool(v bool) { + if v { + b.AppendUint8(1) + } else { + b.AppendUint8(0) + } +} + +// ConsumeUint16 consumes a single uint16 from the buffer, in network byte order (big-endian). +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeUint16() uint16 { + if b.Err != nil { + return 0 + } + + if b.Len() < 2 { + b.off = len(b.b) + b.Err = ErrShortPacket + return 0 + } + + v := binary.BigEndian.Uint16(b.b[b.off:]) + b.off += 2 + return v +} + +// AppendUint16 appends single uint16 into the buffer, in network byte order (big-endian). +func (b *Buffer) AppendUint16(v uint16) { + b.b = append(b.b, + byte(v>>8), + byte(v>>0), + ) +} + +// unmarshalUint32 is used internally to read the packet length. +// It is unsafe, and so not exported. +// Even within this package, its use should be avoided. +func unmarshalUint32(b []byte) uint32 { + return binary.BigEndian.Uint32(b[:4]) +} + +// ConsumeUint32 consumes a single uint32 from the buffer, in network byte order (big-endian). +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeUint32() uint32 { + if b.Err != nil { + return 0 + } + + if b.Len() < 4 { + b.off = len(b.b) + b.Err = ErrShortPacket + return 0 + } + + v := binary.BigEndian.Uint32(b.b[b.off:]) + b.off += 4 + return v +} + +// AppendUint32 appends a single uint32 into the buffer, in network byte order (big-endian). +func (b *Buffer) AppendUint32(v uint32) { + b.b = append(b.b, + byte(v>>24), + byte(v>>16), + byte(v>>8), + byte(v>>0), + ) +} + +// ConsumeCount consumes a single uint32 count from the buffer, in network byte order (big-endian) as an int. +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeCount() int { + return int(b.ConsumeUint32()) +} + +// AppendCount appends a single int length as a uint32 into the buffer, in network byte order (big-endian). +func (b *Buffer) AppendCount(v int) { + b.AppendUint32(uint32(v)) +} + +// ConsumeUint64 consumes a single uint64 from the buffer, in network byte order (big-endian). +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeUint64() uint64 { + if b.Err != nil { + return 0 + } + + if b.Len() < 8 { + b.off = len(b.b) + b.Err = ErrShortPacket + return 0 + } + + v := binary.BigEndian.Uint64(b.b[b.off:]) + b.off += 8 + return v +} + +// AppendUint64 appends a single uint64 into the buffer, in network byte order (big-endian). +func (b *Buffer) AppendUint64(v uint64) { + b.b = append(b.b, + byte(v>>56), + byte(v>>48), + byte(v>>40), + byte(v>>32), + byte(v>>24), + byte(v>>16), + byte(v>>8), + byte(v>>0), + ) +} + +// ConsumeInt64 consumes a single int64 from the buffer, in network byte order (big-endian) with two’s complement. +// If the buffer does not have enough data, it will set Err to ErrShortPacket. +func (b *Buffer) ConsumeInt64() int64 { + return int64(b.ConsumeUint64()) +} + +// AppendInt64 appends a single int64 into the buffer, in network byte order (big-endian) with two’s complement. +func (b *Buffer) AppendInt64(v int64) { + b.AppendUint64(uint64(v)) +} + +// ConsumeByteSlice consumes a single string of raw binary data from the buffer. +// A string is a uint32 length, followed by that number of raw bytes. +// If the buffer does not have enough data, or defines a length larger than available, it will set Err to ErrShortPacket. +// +// The returned slice aliases the buffer contents, and is valid only as long as the buffer is not reused +// (that is, only until the next call to Reset, PutLength, StartPacket, or UnmarshalBinary). +// +// In no case will any Consume calls return overlapping slice aliases, +// and Append calls are guaranteed to not disturb this slice alias. +func (b *Buffer) ConsumeByteSlice() []byte { + length := int(b.ConsumeUint32()) + if b.Err != nil { + return nil + } + + if b.Len() < length || length < 0 { + b.off = len(b.b) + b.Err = ErrShortPacket + return nil + } + + v := b.b[b.off:] + if len(v) > length || cap(v) > length { + v = v[:length:length] + } + b.off += int(length) + return v +} + +// ConsumeByteSliceCopy consumes a single string of raw binary data as a copy from the buffer. +// A string is a uint32 length, followed by that number of raw bytes. +// If the buffer does not have enough data, or defines a length larger than available, it will set Err to ErrShortPacket. +// +// The returned slice does not alias any buffer contents, +// and will therefore be valid even if the buffer is later reused. +// +// If hint has sufficient capacity to hold the data, it will be reused and overwritten, +// otherwise a new backing slice will be allocated and returned. +func (b *Buffer) ConsumeByteSliceCopy(hint []byte) []byte { + data := b.ConsumeByteSlice() + + if grow := len(data) - len(hint); grow > 0 { + hint = append(hint, make([]byte, grow)...) + } + + n := copy(hint, data) + hint = hint[:n] + return hint +} + +// AppendByteSlice appends a single string of raw binary data into the buffer. +// A string is a uint32 length, followed by that number of raw bytes. +func (b *Buffer) AppendByteSlice(v []byte) { + b.AppendUint32(uint32(len(v))) + b.b = append(b.b, v...) +} + +// ConsumeString consumes a single string of binary data from the buffer. +// A string is a uint32 length, followed by that number of raw bytes. +// If the buffer does not have enough data, or defines a length larger than available, it will set Err to ErrShortPacket. +// +// NOTE: Go implicitly assumes that strings contain UTF-8 encoded data. +// All caveats on using arbitrary binary data in Go strings applies. +func (b *Buffer) ConsumeString() string { + return string(b.ConsumeByteSlice()) +} + +// AppendString appends a single string of binary data into the buffer. +// A string is a uint32 length, followed by that number of raw bytes. +func (b *Buffer) AppendString(v string) { + b.AppendByteSlice([]byte(v)) +} + +// PutLength writes the given size into the first four bytes of the buffer in network byte order (big endian). +func (b *Buffer) PutLength(size int) { + if len(b.b) < 4 { + b.b = append(b.b, make([]byte, 4-len(b.b))...) + } + + binary.BigEndian.PutUint32(b.b, uint32(size)) +} + +// MarshalBinary returns a clone of the full internal buffer. +func (b *Buffer) MarshalBinary() ([]byte, error) { + clone := make([]byte, len(b.b)) + n := copy(clone, b.b) + return clone[:n], nil +} + +// UnmarshalBinary sets the internal buffer of b to be a clone of data, and zeros the internal offset. +func (b *Buffer) UnmarshalBinary(data []byte) error { + if grow := len(data) - len(b.b); grow > 0 { + b.b = append(b.b, make([]byte, grow)...) + } + + n := copy(b.b, data) + b.b = b.b[:n] + b.off = 0 + return nil +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/extended_packets.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/extended_packets.go new file mode 100644 index 00000000..f7174253 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/extended_packets.go @@ -0,0 +1,143 @@ +package sshfx + +import ( + "encoding" + "sync" +) + +// ExtendedData aliases the untyped interface composition of encoding.BinaryMarshaler and encoding.BinaryUnmarshaler. +type ExtendedData = interface { + encoding.BinaryMarshaler + encoding.BinaryUnmarshaler +} + +// ExtendedDataConstructor defines a function that returns a new(ArbitraryExtendedPacket). +type ExtendedDataConstructor func() ExtendedData + +var extendedPacketTypes = struct { + mu sync.RWMutex + constructors map[string]ExtendedDataConstructor +}{ + constructors: make(map[string]ExtendedDataConstructor), +} + +// RegisterExtendedPacketType defines a specific ExtendedDataConstructor for the given extension string. +func RegisterExtendedPacketType(extension string, constructor ExtendedDataConstructor) { + extendedPacketTypes.mu.Lock() + defer extendedPacketTypes.mu.Unlock() + + if _, exist := extendedPacketTypes.constructors[extension]; exist { + panic("encoding/ssh/filexfer: multiple registration of extended packet type " + extension) + } + + extendedPacketTypes.constructors[extension] = constructor +} + +func newExtendedPacket(extension string) ExtendedData { + extendedPacketTypes.mu.RLock() + defer extendedPacketTypes.mu.RUnlock() + + if f := extendedPacketTypes.constructors[extension]; f != nil { + return f() + } + + return new(Buffer) +} + +// ExtendedPacket defines the SSH_FXP_CLOSE packet. +type ExtendedPacket struct { + ExtendedRequest string + + Data ExtendedData +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *ExtendedPacket) Type() PacketType { + return PacketTypeExtended +} + +// MarshalPacket returns p as a two-part binary encoding of p. +// +// The Data is marshaled into binary, and returned as the payload. +func (p *ExtendedPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.ExtendedRequest) // string(extended-request) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeExtended, reqid) + buf.AppendString(p.ExtendedRequest) + + if p.Data != nil { + payload, err = p.Data.MarshalBinary() + if err != nil { + return nil, nil, err + } + } + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +// +// If p.Data is nil, and the extension has been registered, a new type will be made from the registration. +// If the extension has not been registered, then a new Buffer will be allocated. +// Then the request-specific-data will be unmarshaled from the rest of the buffer. +func (p *ExtendedPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + p.ExtendedRequest = buf.ConsumeString() + if buf.Err != nil { + return buf.Err + } + + if p.Data == nil { + p.Data = newExtendedPacket(p.ExtendedRequest) + } + + return p.Data.UnmarshalBinary(buf.Bytes()) +} + +// ExtendedReplyPacket defines the SSH_FXP_CLOSE packet. +type ExtendedReplyPacket struct { + Data ExtendedData +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *ExtendedReplyPacket) Type() PacketType { + return PacketTypeExtendedReply +} + +// MarshalPacket returns p as a two-part binary encoding of p. +// +// The Data is marshaled into binary, and returned as the payload. +func (p *ExtendedReplyPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + buf = NewMarshalBuffer(0) + } + + buf.StartPacket(PacketTypeExtendedReply, reqid) + + if p.Data != nil { + payload, err = p.Data.MarshalBinary() + if err != nil { + return nil, nil, err + } + } + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +// +// If p.Data is nil, and there is request-specific-data, +// then the request-specific-data will be wrapped in a Buffer and assigned to p.Data. +func (p *ExtendedReplyPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + if p.Data == nil { + p.Data = new(Buffer) + } + + return p.Data.UnmarshalBinary(buf.Bytes()) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/extensions.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/extensions.go new file mode 100644 index 00000000..c425780c --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/extensions.go @@ -0,0 +1,43 @@ +package sshfx + +// ExtensionPair defines the extension-pair type defined in draft-ietf-secsh-filexfer-13. +// This type is backwards-compatible with how draft-ietf-secsh-filexfer-02 defines extensions. +// +// Defined in: https://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-4.2 +type ExtensionPair struct { + Name string + Data string +} + +// Len returns the number of bytes e would marshal into. +func (e *ExtensionPair) Len() int { + return 4 + len(e.Name) + 4 + len(e.Data) +} + +// MarshalInto marshals e onto the end of the given Buffer. +func (e *ExtensionPair) MarshalInto(buf *Buffer) { + buf.AppendString(e.Name) + buf.AppendString(e.Data) +} + +// MarshalBinary returns e as the binary encoding of e. +func (e *ExtensionPair) MarshalBinary() ([]byte, error) { + buf := NewBuffer(make([]byte, 0, e.Len())) + e.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom unmarshals an ExtensionPair from the given Buffer into e. +func (e *ExtensionPair) UnmarshalFrom(buf *Buffer) (err error) { + *e = ExtensionPair{ + Name: buf.ConsumeString(), + Data: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the binary encoding of ExtensionPair into e. +func (e *ExtensionPair) UnmarshalBinary(data []byte) error { + return e.UnmarshalFrom(NewBuffer(data)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/filexfer.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/filexfer.go new file mode 100644 index 00000000..d3009994 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/filexfer.go @@ -0,0 +1,54 @@ +// Package sshfx implements the wire encoding for secsh-filexfer as described in https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt +package sshfx + +// PacketMarshaller narrowly defines packets that will only be transmitted. +// +// ExtendedPacket types will often only implement this interface, +// since decoding the whole packet body of an ExtendedPacket can only be done dependent on the ExtendedRequest field. +type PacketMarshaller interface { + // MarshalPacket is the primary intended way to encode a packet. + // The request-id for the packet is set from reqid. + // + // An optional buffer may be given in b. + // If the buffer has a minimum capacity, it shall be truncated and used to marshal the header into. + // The minimum capacity for the packet must be a constant expression, and should be at least 9. + // + // It shall return the main body of the encoded packet in header, + // and may optionally return an additional payload to be written immediately after the header. + // + // It shall encode in the first 4-bytes of the header the proper length of the rest of the header+payload. + MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) +} + +// Packet defines the behavior of a full generic SFTP packet. +// +// InitPacket, and VersionPacket are not generic SFTP packets, and instead implement (Un)MarshalBinary. +// +// ExtendedPacket types should not iplement this interface, +// since decoding the whole packet body of an ExtendedPacket can only be done dependent on the ExtendedRequest field. +type Packet interface { + PacketMarshaller + + // Type returns the SSH_FXP_xy value associated with the specific packet. + Type() PacketType + + // UnmarshalPacketBody decodes a packet body from the given Buffer. + // It is assumed that the common header values of the length, type and request-id have already been consumed. + // + // Implementations should not alias the given Buffer, + // instead they can consider prepopulating an internal buffer as a hint, + // and copying into that buffer if it has sufficient length. + UnmarshalPacketBody(buf *Buffer) error +} + +// ComposePacket converts returns from MarshalPacket into an equivalent call to MarshalBinary. +func ComposePacket(header, payload []byte, err error) ([]byte, error) { + return append(header, payload...), err +} + +// Default length values, +// Defined in draft-ietf-secsh-filexfer-02 section 3. +const ( + DefaultMaxPacketLength = 34000 + DefaultMaxDataLength = 32768 +) diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/fx.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/fx.go new file mode 100644 index 00000000..9abcbafc --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/fx.go @@ -0,0 +1,147 @@ +package sshfx + +import ( + "fmt" +) + +// Status defines the SFTP error codes used in SSH_FXP_STATUS response packets. +type Status uint32 + +// Defines the various SSH_FX_* values. +const ( + // see draft-ietf-secsh-filexfer-02 + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-7 + StatusOK = Status(iota) + StatusEOF + StatusNoSuchFile + StatusPermissionDenied + StatusFailure + StatusBadMessage + StatusNoConnection + StatusConnectionLost + StatusOPUnsupported + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-03.txt#section-7 + StatusV4InvalidHandle + StatusV4NoSuchPath + StatusV4FileAlreadyExists + StatusV4WriteProtect + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-04.txt#section-7 + StatusV4NoMedia + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-05.txt#section-7 + StatusV5NoSpaceOnFilesystem + StatusV5QuotaExceeded + StatusV5UnknownPrincipal + StatusV5LockConflict + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-06.txt#section-8 + StatusV6DirNotEmpty + StatusV6NotADirectory + StatusV6InvalidFilename + StatusV6LinkLoop + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-07.txt#section-8 + StatusV6CannotDelete + StatusV6InvalidParameter + StatusV6FileIsADirectory + StatusV6ByteRangeLockConflict + StatusV6ByteRangeLockRefused + StatusV6DeletePending + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-08.txt#section-8.1 + StatusV6FileCorrupt + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-10.txt#section-9.1 + StatusV6OwnerInvalid + StatusV6GroupInvalid + + // https://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.1 + StatusV6NoMatchingByteRangeLock +) + +func (s Status) Error() string { + return s.String() +} + +// Is returns true if the target is the same Status code, +// or target is a StatusPacket with the same Status code. +func (s Status) Is(target error) bool { + if target, ok := target.(*StatusPacket); ok { + return target.StatusCode == s + } + + return s == target +} + +func (s Status) String() string { + switch s { + case StatusOK: + return "SSH_FX_OK" + case StatusEOF: + return "SSH_FX_EOF" + case StatusNoSuchFile: + return "SSH_FX_NO_SUCH_FILE" + case StatusPermissionDenied: + return "SSH_FX_PERMISSION_DENIED" + case StatusFailure: + return "SSH_FX_FAILURE" + case StatusBadMessage: + return "SSH_FX_BAD_MESSAGE" + case StatusNoConnection: + return "SSH_FX_NO_CONNECTION" + case StatusConnectionLost: + return "SSH_FX_CONNECTION_LOST" + case StatusOPUnsupported: + return "SSH_FX_OP_UNSUPPORTED" + case StatusV4InvalidHandle: + return "SSH_FX_INVALID_HANDLE" + case StatusV4NoSuchPath: + return "SSH_FX_NO_SUCH_PATH" + case StatusV4FileAlreadyExists: + return "SSH_FX_FILE_ALREADY_EXISTS" + case StatusV4WriteProtect: + return "SSH_FX_WRITE_PROTECT" + case StatusV4NoMedia: + return "SSH_FX_NO_MEDIA" + case StatusV5NoSpaceOnFilesystem: + return "SSH_FX_NO_SPACE_ON_FILESYSTEM" + case StatusV5QuotaExceeded: + return "SSH_FX_QUOTA_EXCEEDED" + case StatusV5UnknownPrincipal: + return "SSH_FX_UNKNOWN_PRINCIPAL" + case StatusV5LockConflict: + return "SSH_FX_LOCK_CONFLICT" + case StatusV6DirNotEmpty: + return "SSH_FX_DIR_NOT_EMPTY" + case StatusV6NotADirectory: + return "SSH_FX_NOT_A_DIRECTORY" + case StatusV6InvalidFilename: + return "SSH_FX_INVALID_FILENAME" + case StatusV6LinkLoop: + return "SSH_FX_LINK_LOOP" + case StatusV6CannotDelete: + return "SSH_FX_CANNOT_DELETE" + case StatusV6InvalidParameter: + return "SSH_FX_INVALID_PARAMETER" + case StatusV6FileIsADirectory: + return "SSH_FX_FILE_IS_A_DIRECTORY" + case StatusV6ByteRangeLockConflict: + return "SSH_FX_BYTE_RANGE_LOCK_CONFLICT" + case StatusV6ByteRangeLockRefused: + return "SSH_FX_BYTE_RANGE_LOCK_REFUSED" + case StatusV6DeletePending: + return "SSH_FX_DELETE_PENDING" + case StatusV6FileCorrupt: + return "SSH_FX_FILE_CORRUPT" + case StatusV6OwnerInvalid: + return "SSH_FX_OWNER_INVALID" + case StatusV6GroupInvalid: + return "SSH_FX_GROUP_INVALID" + case StatusV6NoMatchingByteRangeLock: + return "SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK" + default: + return fmt.Sprintf("SSH_FX_UNKNOWN(%d)", s) + } +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/fxp.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/fxp.go new file mode 100644 index 00000000..78080021 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/fxp.go @@ -0,0 +1,169 @@ +package sshfx + +import ( + "fmt" +) + +// PacketType defines the various SFTP packet types. +type PacketType uint8 + +// Request packet types. +const ( + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-3 + PacketTypeInit = PacketType(iota + 1) + PacketTypeVersion + PacketTypeOpen + PacketTypeClose + PacketTypeRead + PacketTypeWrite + PacketTypeLStat + PacketTypeFStat + PacketTypeSetstat + PacketTypeFSetstat + PacketTypeOpenDir + PacketTypeReadDir + PacketTypeRemove + PacketTypeMkdir + PacketTypeRmdir + PacketTypeRealPath + PacketTypeStat + PacketTypeRename + PacketTypeReadLink + PacketTypeSymlink + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-07.txt#section-3.3 + PacketTypeV6Link + + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-08.txt#section-3.3 + PacketTypeV6Block + PacketTypeV6Unblock +) + +// Response packet types. +const ( + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-3 + PacketTypeStatus = PacketType(iota + 101) + PacketTypeHandle + PacketTypeData + PacketTypeName + PacketTypeAttrs +) + +// Extended packet types. +const ( + // https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-3 + PacketTypeExtended = PacketType(iota + 200) + PacketTypeExtendedReply +) + +func (f PacketType) String() string { + switch f { + case PacketTypeInit: + return "SSH_FXP_INIT" + case PacketTypeVersion: + return "SSH_FXP_VERSION" + case PacketTypeOpen: + return "SSH_FXP_OPEN" + case PacketTypeClose: + return "SSH_FXP_CLOSE" + case PacketTypeRead: + return "SSH_FXP_READ" + case PacketTypeWrite: + return "SSH_FXP_WRITE" + case PacketTypeLStat: + return "SSH_FXP_LSTAT" + case PacketTypeFStat: + return "SSH_FXP_FSTAT" + case PacketTypeSetstat: + return "SSH_FXP_SETSTAT" + case PacketTypeFSetstat: + return "SSH_FXP_FSETSTAT" + case PacketTypeOpenDir: + return "SSH_FXP_OPENDIR" + case PacketTypeReadDir: + return "SSH_FXP_READDIR" + case PacketTypeRemove: + return "SSH_FXP_REMOVE" + case PacketTypeMkdir: + return "SSH_FXP_MKDIR" + case PacketTypeRmdir: + return "SSH_FXP_RMDIR" + case PacketTypeRealPath: + return "SSH_FXP_REALPATH" + case PacketTypeStat: + return "SSH_FXP_STAT" + case PacketTypeRename: + return "SSH_FXP_RENAME" + case PacketTypeReadLink: + return "SSH_FXP_READLINK" + case PacketTypeSymlink: + return "SSH_FXP_SYMLINK" + case PacketTypeV6Link: + return "SSH_FXP_LINK" + case PacketTypeV6Block: + return "SSH_FXP_BLOCK" + case PacketTypeV6Unblock: + return "SSH_FXP_UNBLOCK" + case PacketTypeStatus: + return "SSH_FXP_STATUS" + case PacketTypeHandle: + return "SSH_FXP_HANDLE" + case PacketTypeData: + return "SSH_FXP_DATA" + case PacketTypeName: + return "SSH_FXP_NAME" + case PacketTypeAttrs: + return "SSH_FXP_ATTRS" + case PacketTypeExtended: + return "SSH_FXP_EXTENDED" + case PacketTypeExtendedReply: + return "SSH_FXP_EXTENDED_REPLY" + default: + return fmt.Sprintf("SSH_FXP_UNKNOWN(%d)", f) + } +} + +func newPacketFromType(typ PacketType) (Packet, error) { + switch typ { + case PacketTypeOpen: + return new(OpenPacket), nil + case PacketTypeClose: + return new(ClosePacket), nil + case PacketTypeRead: + return new(ReadPacket), nil + case PacketTypeWrite: + return new(WritePacket), nil + case PacketTypeLStat: + return new(LStatPacket), nil + case PacketTypeFStat: + return new(FStatPacket), nil + case PacketTypeSetstat: + return new(SetstatPacket), nil + case PacketTypeFSetstat: + return new(FSetstatPacket), nil + case PacketTypeOpenDir: + return new(OpenDirPacket), nil + case PacketTypeReadDir: + return new(ReadDirPacket), nil + case PacketTypeRemove: + return new(RemovePacket), nil + case PacketTypeMkdir: + return new(MkdirPacket), nil + case PacketTypeRmdir: + return new(RmdirPacket), nil + case PacketTypeRealPath: + return new(RealPathPacket), nil + case PacketTypeStat: + return new(StatPacket), nil + case PacketTypeRename: + return new(RenamePacket), nil + case PacketTypeReadLink: + return new(ReadLinkPacket), nil + case PacketTypeSymlink: + return new(SymlinkPacket), nil + case PacketTypeExtended: + return new(ExtendedPacket), nil + default: + return nil, fmt.Errorf("unexpected request packet type: %v", typ) + } +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/handle_packets.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/handle_packets.go new file mode 100644 index 00000000..44594acf --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/handle_packets.go @@ -0,0 +1,230 @@ +package sshfx + +// ClosePacket defines the SSH_FXP_CLOSE packet. +type ClosePacket struct { + Handle string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *ClosePacket) Type() PacketType { + return PacketTypeClose +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *ClosePacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Handle) // string(handle) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeClose, reqid) + buf.AppendString(p.Handle) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *ClosePacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = ClosePacket{ + Handle: buf.ConsumeString(), + } + + return buf.Err +} + +// ReadPacket defines the SSH_FXP_READ packet. +type ReadPacket struct { + Handle string + Offset uint64 + Length uint32 +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *ReadPacket) Type() PacketType { + return PacketTypeRead +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *ReadPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + // string(handle) + uint64(offset) + uint32(len) + size := 4 + len(p.Handle) + 8 + 4 + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeRead, reqid) + buf.AppendString(p.Handle) + buf.AppendUint64(p.Offset) + buf.AppendUint32(p.Length) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *ReadPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = ReadPacket{ + Handle: buf.ConsumeString(), + Offset: buf.ConsumeUint64(), + Length: buf.ConsumeUint32(), + } + + return buf.Err +} + +// WritePacket defines the SSH_FXP_WRITE packet. +type WritePacket struct { + Handle string + Offset uint64 + Data []byte +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *WritePacket) Type() PacketType { + return PacketTypeWrite +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *WritePacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + // string(handle) + uint64(offset) + uint32(len(data)); data content in payload + size := 4 + len(p.Handle) + 8 + 4 + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeWrite, reqid) + buf.AppendString(p.Handle) + buf.AppendUint64(p.Offset) + buf.AppendUint32(uint32(len(p.Data))) + + return buf.Packet(p.Data) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +// +// If p.Data is already populated, and of sufficient length to hold the data, +// then this will copy the data into that byte slice. +// +// If p.Data has a length insufficient to hold the data, +// then this will make a new slice of sufficient length, and copy the data into that. +// +// This means this _does not_ alias any of the data buffer that is passed in. +func (p *WritePacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = WritePacket{ + Handle: buf.ConsumeString(), + Offset: buf.ConsumeUint64(), + Data: buf.ConsumeByteSliceCopy(p.Data), + } + + return buf.Err +} + +// FStatPacket defines the SSH_FXP_FSTAT packet. +type FStatPacket struct { + Handle string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *FStatPacket) Type() PacketType { + return PacketTypeFStat +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *FStatPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Handle) // string(handle) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeFStat, reqid) + buf.AppendString(p.Handle) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *FStatPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = FStatPacket{ + Handle: buf.ConsumeString(), + } + + return buf.Err +} + +// FSetstatPacket defines the SSH_FXP_FSETSTAT packet. +type FSetstatPacket struct { + Handle string + Attrs Attributes +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *FSetstatPacket) Type() PacketType { + return PacketTypeFSetstat +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *FSetstatPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Handle) + p.Attrs.Len() // string(handle) + ATTRS(attrs) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeFSetstat, reqid) + buf.AppendString(p.Handle) + + p.Attrs.MarshalInto(buf) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *FSetstatPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = FSetstatPacket{ + Handle: buf.ConsumeString(), + } + + return p.Attrs.UnmarshalFrom(buf) +} + +// ReadDirPacket defines the SSH_FXP_READDIR packet. +type ReadDirPacket struct { + Handle string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *ReadDirPacket) Type() PacketType { + return PacketTypeReadDir +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *ReadDirPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Handle) // string(handle) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeReadDir, reqid) + buf.AppendString(p.Handle) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *ReadDirPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = ReadDirPacket{ + Handle: buf.ConsumeString(), + } + + return buf.Err +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/init_packets.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/init_packets.go new file mode 100644 index 00000000..c553ee2e --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/init_packets.go @@ -0,0 +1,99 @@ +package sshfx + +// InitPacket defines the SSH_FXP_INIT packet. +type InitPacket struct { + Version uint32 + Extensions []*ExtensionPair +} + +// MarshalBinary returns p as the binary encoding of p. +func (p *InitPacket) MarshalBinary() ([]byte, error) { + size := 1 + 4 // byte(type) + uint32(version) + + for _, ext := range p.Extensions { + size += ext.Len() + } + + b := NewBuffer(make([]byte, 4, 4+size)) + b.AppendUint8(uint8(PacketTypeInit)) + b.AppendUint32(p.Version) + + for _, ext := range p.Extensions { + ext.MarshalInto(b) + } + + b.PutLength(size) + + return b.Bytes(), nil +} + +// UnmarshalBinary unmarshals a full raw packet out of the given data. +// It is assumed that the uint32(length) has already been consumed to receive the data. +// It is also assumed that the uint8(type) has already been consumed to which packet to unmarshal into. +func (p *InitPacket) UnmarshalBinary(data []byte) (err error) { + buf := NewBuffer(data) + + *p = InitPacket{ + Version: buf.ConsumeUint32(), + } + + for buf.Len() > 0 { + var ext ExtensionPair + if err := ext.UnmarshalFrom(buf); err != nil { + return err + } + + p.Extensions = append(p.Extensions, &ext) + } + + return buf.Err +} + +// VersionPacket defines the SSH_FXP_VERSION packet. +type VersionPacket struct { + Version uint32 + Extensions []*ExtensionPair +} + +// MarshalBinary returns p as the binary encoding of p. +func (p *VersionPacket) MarshalBinary() ([]byte, error) { + size := 1 + 4 // byte(type) + uint32(version) + + for _, ext := range p.Extensions { + size += ext.Len() + } + + b := NewBuffer(make([]byte, 4, 4+size)) + b.AppendUint8(uint8(PacketTypeVersion)) + b.AppendUint32(p.Version) + + for _, ext := range p.Extensions { + ext.MarshalInto(b) + } + + b.PutLength(size) + + return b.Bytes(), nil +} + +// UnmarshalBinary unmarshals a full raw packet out of the given data. +// It is assumed that the uint32(length) has already been consumed to receive the data. +// It is also assumed that the uint8(type) has already been consumed to which packet to unmarshal into. +func (p *VersionPacket) UnmarshalBinary(data []byte) (err error) { + buf := NewBuffer(data) + + *p = VersionPacket{ + Version: buf.ConsumeUint32(), + } + + for buf.Len() > 0 { + var ext ExtensionPair + if err := ext.UnmarshalFrom(buf); err != nil { + return err + } + + p.Extensions = append(p.Extensions, &ext) + } + + return nil +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/open_packets.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/open_packets.go new file mode 100644 index 00000000..896ba16e --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/open_packets.go @@ -0,0 +1,86 @@ +package sshfx + +// SSH_FXF_* flags. +const ( + FlagRead = 1 << iota // SSH_FXF_READ + FlagWrite // SSH_FXF_WRITE + FlagAppend // SSH_FXF_APPEND + FlagCreate // SSH_FXF_CREAT + FlagTruncate // SSH_FXF_TRUNC + FlagExclusive // SSH_FXF_EXCL +) + +// OpenPacket defines the SSH_FXP_OPEN packet. +type OpenPacket struct { + Filename string + PFlags uint32 + Attrs Attributes +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *OpenPacket) Type() PacketType { + return PacketTypeOpen +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *OpenPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + // string(filename) + uint32(pflags) + ATTRS(attrs) + size := 4 + len(p.Filename) + 4 + p.Attrs.Len() + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeOpen, reqid) + buf.AppendString(p.Filename) + buf.AppendUint32(p.PFlags) + + p.Attrs.MarshalInto(buf) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *OpenPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = OpenPacket{ + Filename: buf.ConsumeString(), + PFlags: buf.ConsumeUint32(), + } + + return p.Attrs.UnmarshalFrom(buf) +} + +// OpenDirPacket defines the SSH_FXP_OPENDIR packet. +type OpenDirPacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *OpenDirPacket) Type() PacketType { + return PacketTypeOpenDir +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *OpenDirPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeOpenDir, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *OpenDirPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = OpenDirPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/fsync.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/fsync.go new file mode 100644 index 00000000..708a4ba7 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/fsync.go @@ -0,0 +1,73 @@ +package openssh + +import ( + sshfx "github.com/pkg/sftp/internal/encoding/ssh/filexfer" +) + +const extensionFSync = "fsync@openssh.com" + +// RegisterExtensionFSync registers the "fsync@openssh.com" extended packet with the encoding/ssh/filexfer package. +func RegisterExtensionFSync() { + sshfx.RegisterExtendedPacketType(extensionFSync, func() sshfx.ExtendedData { + return new(FSyncExtendedPacket) + }) +} + +// ExtensionFSync returns an ExtensionPair suitable to append into an sshfx.InitPacket or sshfx.VersionPacket. +func ExtensionFSync() *sshfx.ExtensionPair { + return &sshfx.ExtensionPair{ + Name: extensionFSync, + Data: "1", + } +} + +// FSyncExtendedPacket defines the fsync@openssh.com extend packet. +type FSyncExtendedPacket struct { + Handle string +} + +// Type returns the SSH_FXP_EXTENDED packet type. +func (ep *FSyncExtendedPacket) Type() sshfx.PacketType { + return sshfx.PacketTypeExtended +} + +// MarshalPacket returns ep as a two-part binary encoding of the full extended packet. +func (ep *FSyncExtendedPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + p := &sshfx.ExtendedPacket{ + ExtendedRequest: extensionFSync, + + Data: ep, + } + return p.MarshalPacket(reqid, b) +} + +// MarshalInto encodes ep into the binary encoding of the fsync@openssh.com extended packet-specific data. +func (ep *FSyncExtendedPacket) MarshalInto(buf *sshfx.Buffer) { + buf.AppendString(ep.Handle) +} + +// MarshalBinary encodes ep into the binary encoding of the fsync@openssh.com extended packet-specific data. +// +// NOTE: This _only_ encodes the packet-specific data, it does not encode the full extended packet. +func (ep *FSyncExtendedPacket) MarshalBinary() ([]byte, error) { + // string(handle) + size := 4 + len(ep.Handle) + + buf := sshfx.NewBuffer(make([]byte, 0, size)) + ep.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom decodes the fsync@openssh.com extended packet-specific data from buf. +func (ep *FSyncExtendedPacket) UnmarshalFrom(buf *sshfx.Buffer) (err error) { + *ep = FSyncExtendedPacket{ + Handle: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the fsync@openssh.com extended packet-specific data into ep. +func (ep *FSyncExtendedPacket) UnmarshalBinary(data []byte) (err error) { + return ep.UnmarshalFrom(sshfx.NewBuffer(data)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/hardlink.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/hardlink.go new file mode 100644 index 00000000..f48d25a2 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/hardlink.go @@ -0,0 +1,76 @@ +package openssh + +import ( + sshfx "github.com/pkg/sftp/internal/encoding/ssh/filexfer" +) + +const extensionHardlink = "hardlink@openssh.com" + +// RegisterExtensionHardlink registers the "hardlink@openssh.com" extended packet with the encoding/ssh/filexfer package. +func RegisterExtensionHardlink() { + sshfx.RegisterExtendedPacketType(extensionHardlink, func() sshfx.ExtendedData { + return new(HardlinkExtendedPacket) + }) +} + +// ExtensionHardlink returns an ExtensionPair suitable to append into an sshfx.InitPacket or sshfx.VersionPacket. +func ExtensionHardlink() *sshfx.ExtensionPair { + return &sshfx.ExtensionPair{ + Name: extensionHardlink, + Data: "1", + } +} + +// HardlinkExtendedPacket defines the hardlink@openssh.com extend packet. +type HardlinkExtendedPacket struct { + OldPath string + NewPath string +} + +// Type returns the SSH_FXP_EXTENDED packet type. +func (ep *HardlinkExtendedPacket) Type() sshfx.PacketType { + return sshfx.PacketTypeExtended +} + +// MarshalPacket returns ep as a two-part binary encoding of the full extended packet. +func (ep *HardlinkExtendedPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + p := &sshfx.ExtendedPacket{ + ExtendedRequest: extensionHardlink, + + Data: ep, + } + return p.MarshalPacket(reqid, b) +} + +// MarshalInto encodes ep into the binary encoding of the hardlink@openssh.com extended packet-specific data. +func (ep *HardlinkExtendedPacket) MarshalInto(buf *sshfx.Buffer) { + buf.AppendString(ep.OldPath) + buf.AppendString(ep.NewPath) +} + +// MarshalBinary encodes ep into the binary encoding of the hardlink@openssh.com extended packet-specific data. +// +// NOTE: This _only_ encodes the packet-specific data, it does not encode the full extended packet. +func (ep *HardlinkExtendedPacket) MarshalBinary() ([]byte, error) { + // string(oldpath) + string(newpath) + size := 4 + len(ep.OldPath) + 4 + len(ep.NewPath) + + buf := sshfx.NewBuffer(make([]byte, 0, size)) + ep.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom decodes the hardlink@openssh.com extended packet-specific data from buf. +func (ep *HardlinkExtendedPacket) UnmarshalFrom(buf *sshfx.Buffer) (err error) { + *ep = HardlinkExtendedPacket{ + OldPath: buf.ConsumeString(), + NewPath: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the hardlink@openssh.com extended packet-specific data into ep. +func (ep *HardlinkExtendedPacket) UnmarshalBinary(data []byte) (err error) { + return ep.UnmarshalFrom(sshfx.NewBuffer(data)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/openssh.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/openssh.go new file mode 100644 index 00000000..f93ff177 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/openssh.go @@ -0,0 +1,2 @@ +// Package openssh implements the openssh secsh-filexfer extensions as described in https://github.com/openssh/openssh-portable/blob/master/PROTOCOL +package openssh diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/posix-rename.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/posix-rename.go new file mode 100644 index 00000000..5166489c --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/posix-rename.go @@ -0,0 +1,76 @@ +package openssh + +import ( + sshfx "github.com/pkg/sftp/internal/encoding/ssh/filexfer" +) + +const extensionPOSIXRename = "posix-rename@openssh.com" + +// RegisterExtensionPOSIXRename registers the "posix-rename@openssh.com" extended packet with the encoding/ssh/filexfer package. +func RegisterExtensionPOSIXRename() { + sshfx.RegisterExtendedPacketType(extensionPOSIXRename, func() sshfx.ExtendedData { + return new(POSIXRenameExtendedPacket) + }) +} + +// ExtensionPOSIXRename returns an ExtensionPair suitable to append into an sshfx.InitPacket or sshfx.VersionPacket. +func ExtensionPOSIXRename() *sshfx.ExtensionPair { + return &sshfx.ExtensionPair{ + Name: extensionPOSIXRename, + Data: "1", + } +} + +// POSIXRenameExtendedPacket defines the posix-rename@openssh.com extend packet. +type POSIXRenameExtendedPacket struct { + OldPath string + NewPath string +} + +// Type returns the SSH_FXP_EXTENDED packet type. +func (ep *POSIXRenameExtendedPacket) Type() sshfx.PacketType { + return sshfx.PacketTypeExtended +} + +// MarshalPacket returns ep as a two-part binary encoding of the full extended packet. +func (ep *POSIXRenameExtendedPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + p := &sshfx.ExtendedPacket{ + ExtendedRequest: extensionPOSIXRename, + + Data: ep, + } + return p.MarshalPacket(reqid, b) +} + +// MarshalInto encodes ep into the binary encoding of the hardlink@openssh.com extended packet-specific data. +func (ep *POSIXRenameExtendedPacket) MarshalInto(buf *sshfx.Buffer) { + buf.AppendString(ep.OldPath) + buf.AppendString(ep.NewPath) +} + +// MarshalBinary encodes ep into the binary encoding of the hardlink@openssh.com extended packet-specific data. +// +// NOTE: This _only_ encodes the packet-specific data, it does not encode the full extended packet. +func (ep *POSIXRenameExtendedPacket) MarshalBinary() ([]byte, error) { + // string(oldpath) + string(newpath) + size := 4 + len(ep.OldPath) + 4 + len(ep.NewPath) + + buf := sshfx.NewBuffer(make([]byte, 0, size)) + ep.MarshalInto(buf) + return buf.Bytes(), nil +} + +// UnmarshalFrom decodes the hardlink@openssh.com extended packet-specific data from buf. +func (ep *POSIXRenameExtendedPacket) UnmarshalFrom(buf *sshfx.Buffer) (err error) { + *ep = POSIXRenameExtendedPacket{ + OldPath: buf.ConsumeString(), + NewPath: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the hardlink@openssh.com extended packet-specific data into ep. +func (ep *POSIXRenameExtendedPacket) UnmarshalBinary(data []byte) (err error) { + return ep.UnmarshalFrom(sshfx.NewBuffer(data)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/statvfs.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/statvfs.go new file mode 100644 index 00000000..51029ca0 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh/statvfs.go @@ -0,0 +1,236 @@ +package openssh + +import ( + sshfx "github.com/pkg/sftp/internal/encoding/ssh/filexfer" +) + +const extensionStatVFS = "statvfs@openssh.com" + +// RegisterExtensionStatVFS registers the "statvfs@openssh.com" extended packet with the encoding/ssh/filexfer package. +func RegisterExtensionStatVFS() { + sshfx.RegisterExtendedPacketType(extensionStatVFS, func() sshfx.ExtendedData { + return new(StatVFSExtendedPacket) + }) +} + +// ExtensionStatVFS returns an ExtensionPair suitable to append into an sshfx.InitPacket or sshfx.VersionPacket. +func ExtensionStatVFS() *sshfx.ExtensionPair { + return &sshfx.ExtensionPair{ + Name: extensionStatVFS, + Data: "2", + } +} + +// StatVFSExtendedPacket defines the statvfs@openssh.com extend packet. +type StatVFSExtendedPacket struct { + Path string +} + +// Type returns the SSH_FXP_EXTENDED packet type. +func (ep *StatVFSExtendedPacket) Type() sshfx.PacketType { + return sshfx.PacketTypeExtended +} + +// MarshalPacket returns ep as a two-part binary encoding of the full extended packet. +func (ep *StatVFSExtendedPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + p := &sshfx.ExtendedPacket{ + ExtendedRequest: extensionStatVFS, + + Data: ep, + } + return p.MarshalPacket(reqid, b) +} + +// MarshalInto encodes ep into the binary encoding of the statvfs@openssh.com extended packet-specific data. +func (ep *StatVFSExtendedPacket) MarshalInto(buf *sshfx.Buffer) { + buf.AppendString(ep.Path) +} + +// MarshalBinary encodes ep into the binary encoding of the statvfs@openssh.com extended packet-specific data. +// +// NOTE: This _only_ encodes the packet-specific data, it does not encode the full extended packet. +func (ep *StatVFSExtendedPacket) MarshalBinary() ([]byte, error) { + size := 4 + len(ep.Path) // string(path) + + buf := sshfx.NewBuffer(make([]byte, 0, size)) + + ep.MarshalInto(buf) + + return buf.Bytes(), nil +} + +// UnmarshalFrom decodes the statvfs@openssh.com extended packet-specific data into ep. +func (ep *StatVFSExtendedPacket) UnmarshalFrom(buf *sshfx.Buffer) (err error) { + *ep = StatVFSExtendedPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the statvfs@openssh.com extended packet-specific data into ep. +func (ep *StatVFSExtendedPacket) UnmarshalBinary(data []byte) (err error) { + return ep.UnmarshalFrom(sshfx.NewBuffer(data)) +} + +const extensionFStatVFS = "fstatvfs@openssh.com" + +// RegisterExtensionFStatVFS registers the "fstatvfs@openssh.com" extended packet with the encoding/ssh/filexfer package. +func RegisterExtensionFStatVFS() { + sshfx.RegisterExtendedPacketType(extensionFStatVFS, func() sshfx.ExtendedData { + return new(FStatVFSExtendedPacket) + }) +} + +// ExtensionFStatVFS returns an ExtensionPair suitable to append into an sshfx.InitPacket or sshfx.VersionPacket. +func ExtensionFStatVFS() *sshfx.ExtensionPair { + return &sshfx.ExtensionPair{ + Name: extensionFStatVFS, + Data: "2", + } +} + +// FStatVFSExtendedPacket defines the fstatvfs@openssh.com extend packet. +type FStatVFSExtendedPacket struct { + Path string +} + +// Type returns the SSH_FXP_EXTENDED packet type. +func (ep *FStatVFSExtendedPacket) Type() sshfx.PacketType { + return sshfx.PacketTypeExtended +} + +// MarshalPacket returns ep as a two-part binary encoding of the full extended packet. +func (ep *FStatVFSExtendedPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + p := &sshfx.ExtendedPacket{ + ExtendedRequest: extensionFStatVFS, + + Data: ep, + } + return p.MarshalPacket(reqid, b) +} + +// MarshalInto encodes ep into the binary encoding of the statvfs@openssh.com extended packet-specific data. +func (ep *FStatVFSExtendedPacket) MarshalInto(buf *sshfx.Buffer) { + buf.AppendString(ep.Path) +} + +// MarshalBinary encodes ep into the binary encoding of the statvfs@openssh.com extended packet-specific data. +// +// NOTE: This _only_ encodes the packet-specific data, it does not encode the full extended packet. +func (ep *FStatVFSExtendedPacket) MarshalBinary() ([]byte, error) { + size := 4 + len(ep.Path) // string(path) + + buf := sshfx.NewBuffer(make([]byte, 0, size)) + + ep.MarshalInto(buf) + + return buf.Bytes(), nil +} + +// UnmarshalFrom decodes the statvfs@openssh.com extended packet-specific data into ep. +func (ep *FStatVFSExtendedPacket) UnmarshalFrom(buf *sshfx.Buffer) (err error) { + *ep = FStatVFSExtendedPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the statvfs@openssh.com extended packet-specific data into ep. +func (ep *FStatVFSExtendedPacket) UnmarshalBinary(data []byte) (err error) { + return ep.UnmarshalFrom(sshfx.NewBuffer(data)) +} + +// The values for the MountFlags field. +// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL +const ( + MountFlagsReadOnly = 0x1 // SSH_FXE_STATVFS_ST_RDONLY + MountFlagsNoSUID = 0x2 // SSH_FXE_STATVFS_ST_NOSUID +) + +// StatVFSExtendedReplyPacket defines the extended reply packet for statvfs@openssh.com and fstatvfs@openssh.com requests. +type StatVFSExtendedReplyPacket struct { + BlockSize uint64 /* f_bsize: file system block size */ + FragmentSize uint64 /* f_frsize: fundamental fs block size / fagment size */ + Blocks uint64 /* f_blocks: number of blocks (unit f_frsize) */ + BlocksFree uint64 /* f_bfree: free blocks in filesystem */ + BlocksAvail uint64 /* f_bavail: free blocks for non-root */ + Files uint64 /* f_files: total file inodes */ + FilesFree uint64 /* f_ffree: free file inodes */ + FilesAvail uint64 /* f_favail: free file inodes for to non-root */ + FilesystemID uint64 /* f_fsid: file system id */ + MountFlags uint64 /* f_flag: bit mask of mount flag values */ + MaxNameLength uint64 /* f_namemax: maximum filename length */ +} + +// Type returns the SSH_FXP_EXTENDED_REPLY packet type. +func (ep *StatVFSExtendedReplyPacket) Type() sshfx.PacketType { + return sshfx.PacketTypeExtendedReply +} + +// MarshalPacket returns ep as a two-part binary encoding of the full extended reply packet. +func (ep *StatVFSExtendedReplyPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + p := &sshfx.ExtendedReplyPacket{ + Data: ep, + } + return p.MarshalPacket(reqid, b) +} + +// UnmarshalPacketBody returns ep as a two-part binary encoding of the full extended reply packet. +func (ep *StatVFSExtendedReplyPacket) UnmarshalPacketBody(buf *sshfx.Buffer) (err error) { + p := &sshfx.ExtendedReplyPacket{ + Data: ep, + } + return p.UnmarshalPacketBody(buf) +} + +// MarshalInto encodes ep into the binary encoding of the (f)statvfs@openssh.com extended reply packet-specific data. +func (ep *StatVFSExtendedReplyPacket) MarshalInto(buf *sshfx.Buffer) { + buf.AppendUint64(ep.BlockSize) + buf.AppendUint64(ep.FragmentSize) + buf.AppendUint64(ep.Blocks) + buf.AppendUint64(ep.BlocksFree) + buf.AppendUint64(ep.BlocksAvail) + buf.AppendUint64(ep.Files) + buf.AppendUint64(ep.FilesFree) + buf.AppendUint64(ep.FilesAvail) + buf.AppendUint64(ep.FilesystemID) + buf.AppendUint64(ep.MountFlags) + buf.AppendUint64(ep.MaxNameLength) +} + +// MarshalBinary encodes ep into the binary encoding of the (f)statvfs@openssh.com extended reply packet-specific data. +// +// NOTE: This _only_ encodes the packet-specific data, it does not encode the full extended reply packet. +func (ep *StatVFSExtendedReplyPacket) MarshalBinary() ([]byte, error) { + size := 11 * 8 // 11 × uint64(various) + + b := sshfx.NewBuffer(make([]byte, 0, size)) + ep.MarshalInto(b) + return b.Bytes(), nil +} + +// UnmarshalFrom decodes the fstatvfs@openssh.com extended reply packet-specific data into ep. +func (ep *StatVFSExtendedReplyPacket) UnmarshalFrom(buf *sshfx.Buffer) (err error) { + *ep = StatVFSExtendedReplyPacket{ + BlockSize: buf.ConsumeUint64(), + FragmentSize: buf.ConsumeUint64(), + Blocks: buf.ConsumeUint64(), + BlocksFree: buf.ConsumeUint64(), + BlocksAvail: buf.ConsumeUint64(), + Files: buf.ConsumeUint64(), + FilesFree: buf.ConsumeUint64(), + FilesAvail: buf.ConsumeUint64(), + FilesystemID: buf.ConsumeUint64(), + MountFlags: buf.ConsumeUint64(), + MaxNameLength: buf.ConsumeUint64(), + } + + return buf.Err +} + +// UnmarshalBinary decodes the fstatvfs@openssh.com extended reply packet-specific data into ep. +func (ep *StatVFSExtendedReplyPacket) UnmarshalBinary(data []byte) (err error) { + return ep.UnmarshalFrom(sshfx.NewBuffer(data)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/packets.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/packets.go new file mode 100644 index 00000000..fdf65d05 --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/packets.go @@ -0,0 +1,273 @@ +package sshfx + +import ( + "errors" + "io" +) + +// smallBufferSize is an initial allocation minimal capacity. +const smallBufferSize = 64 + +// RawPacket implements the general packet format from draft-ietf-secsh-filexfer-02 +// +// RawPacket is intended for use in clients receiving responses, +// where a response will be expected to be of a limited number of types, +// and unmarshaling unknown/unexpected response packets is unnecessary. +// +// For servers expecting to receive arbitrary request packet types, +// use RequestPacket. +// +// Defined in https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-3 +type RawPacket struct { + PacketType PacketType + RequestID uint32 + + Data Buffer +} + +// Type returns the Type field defining the SSH_FXP_xy type for this packet. +func (p *RawPacket) Type() PacketType { + return p.PacketType +} + +// Reset clears the pointers and reference-semantic variables of RawPacket, +// releasing underlying resources, and making them and the RawPacket suitable to be reused, +// so long as no other references have been kept. +func (p *RawPacket) Reset() { + p.Data = Buffer{} +} + +// MarshalPacket returns p as a two-part binary encoding of p. +// +// The internal p.RequestID is overridden by the reqid argument. +func (p *RawPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + buf = NewMarshalBuffer(0) + } + + buf.StartPacket(p.PacketType, reqid) + + return buf.Packet(p.Data.Bytes()) +} + +// MarshalBinary returns p as the binary encoding of p. +// +// This is a convenience implementation primarily intended for tests, +// because it is inefficient with allocations. +func (p *RawPacket) MarshalBinary() ([]byte, error) { + return ComposePacket(p.MarshalPacket(p.RequestID, nil)) +} + +// UnmarshalFrom decodes a RawPacket from the given Buffer into p. +// +// The Data field will alias the passed in Buffer, +// so the buffer passed in should not be reused before RawPacket.Reset(). +func (p *RawPacket) UnmarshalFrom(buf *Buffer) error { + *p = RawPacket{ + PacketType: PacketType(buf.ConsumeUint8()), + RequestID: buf.ConsumeUint32(), + } + + p.Data = *buf + + return buf.Err +} + +// UnmarshalBinary decodes a full raw packet out of the given data. +// It is assumed that the uint32(length) has already been consumed to receive the data. +// +// This is a convenience implementation primarily intended for tests, +// because this must clone the given data byte slice, +// as Data is not allowed to alias any part of the data byte slice. +func (p *RawPacket) UnmarshalBinary(data []byte) error { + clone := make([]byte, len(data)) + n := copy(clone, data) + return p.UnmarshalFrom(NewBuffer(clone[:n])) +} + +// readPacket reads a uint32 length-prefixed binary data packet from r. +// using the given byte slice as a backing array. +// +// If the packet length read from r is bigger than maxPacketLength, +// or greater than math.MaxInt32 on a 32-bit implementation, +// then a `ErrLongPacket` error will be returned. +// +// If the given byte slice is insufficient to hold the packet, +// then it will be extended to fill the packet size. +func readPacket(r io.Reader, b []byte, maxPacketLength uint32) ([]byte, error) { + if cap(b) < 4 { + // We will need allocate our own buffer just for reading the packet length. + + // However, we don’t really want to allocate an extremely narrow buffer (4-bytes), + // and cause unnecessary allocation churn from both length reads and small packet reads, + // so we use smallBufferSize from the bytes package as a reasonable guess. + + // But if callers really do want to force narrow throw-away allocation of every packet body, + // they can do so with a buffer of capacity 4. + b = make([]byte, smallBufferSize) + } + + if _, err := io.ReadFull(r, b[:4]); err != nil { + return nil, err + } + + length := unmarshalUint32(b) + if int(length) < 5 { + // Must have at least uint8(type) and uint32(request-id) + + if int(length) < 0 { + // Only possible when strconv.IntSize == 32, + // the packet length is longer than math.MaxInt32, + // and thus longer than any possible slice. + return nil, ErrLongPacket + } + + return nil, ErrShortPacket + } + if length > maxPacketLength { + return nil, ErrLongPacket + } + + if int(length) > cap(b) { + // We know int(length) must be positive, because of tests above. + b = make([]byte, length) + } + + n, err := io.ReadFull(r, b[:length]) + return b[:n], err +} + +// ReadFrom provides a simple functional packet reader, +// using the given byte slice as a backing array. +// +// To protect against potential denial of service attacks, +// if the read packet length is longer than maxPacketLength, +// then no packet data will be read, and ErrLongPacket will be returned. +// (On 32-bit int architectures, all packets >= 2^31 in length +// will return ErrLongPacket regardless of maxPacketLength.) +// +// If the read packet length is longer than cap(b), +// then a throw-away slice will allocated to meet the exact packet length. +// This can be used to limit the length of reused buffers, +// while still allowing reception of occasional large packets. +// +// The Data field may alias the passed in byte slice, +// so the byte slice passed in should not be reused before RawPacket.Reset(). +func (p *RawPacket) ReadFrom(r io.Reader, b []byte, maxPacketLength uint32) error { + b, err := readPacket(r, b, maxPacketLength) + if err != nil { + return err + } + + return p.UnmarshalFrom(NewBuffer(b)) +} + +// RequestPacket implements the general packet format from draft-ietf-secsh-filexfer-02 +// but also automatically decode/encodes valid request packets (2 < type < 100 || type == 200). +// +// RequestPacket is intended for use in servers receiving requests, +// where any arbitrary request may be received, and so decoding them automatically +// is useful. +// +// For clients expecting to receive specific response packet types, +// where automatic unmarshaling of the packet body does not make sense, +// use RawPacket. +// +// Defined in https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-3 +type RequestPacket struct { + RequestID uint32 + + Request Packet +} + +// Type returns the SSH_FXP_xy value associated with the underlying packet. +func (p *RequestPacket) Type() PacketType { + return p.Request.Type() +} + +// Reset clears the pointers and reference-semantic variables in RequestPacket, +// releasing underlying resources, and making them and the RequestPacket suitable to be reused, +// so long as no other references have been kept. +func (p *RequestPacket) Reset() { + p.Request = nil +} + +// MarshalPacket returns p as a two-part binary encoding of p. +// +// The internal p.RequestID is overridden by the reqid argument. +func (p *RequestPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + if p.Request == nil { + return nil, nil, errors.New("empty request packet") + } + + return p.Request.MarshalPacket(reqid, b) +} + +// MarshalBinary returns p as the binary encoding of p. +// +// This is a convenience implementation primarily intended for tests, +// because it is inefficient with allocations. +func (p *RequestPacket) MarshalBinary() ([]byte, error) { + return ComposePacket(p.MarshalPacket(p.RequestID, nil)) +} + +// UnmarshalFrom decodes a RequestPacket from the given Buffer into p. +// +// The Request field may alias the passed in Buffer, (e.g. SSH_FXP_WRITE), +// so the buffer passed in should not be reused before RequestPacket.Reset(). +func (p *RequestPacket) UnmarshalFrom(buf *Buffer) error { + typ := PacketType(buf.ConsumeUint8()) + if buf.Err != nil { + return buf.Err + } + + req, err := newPacketFromType(typ) + if err != nil { + return err + } + + *p = RequestPacket{ + RequestID: buf.ConsumeUint32(), + Request: req, + } + + return p.Request.UnmarshalPacketBody(buf) +} + +// UnmarshalBinary decodes a full request packet out of the given data. +// It is assumed that the uint32(length) has already been consumed to receive the data. +// +// This is a convenience implementation primarily intended for tests, +// because this must clone the given data byte slice, +// as Request is not allowed to alias any part of the data byte slice. +func (p *RequestPacket) UnmarshalBinary(data []byte) error { + clone := make([]byte, len(data)) + n := copy(clone, data) + return p.UnmarshalFrom(NewBuffer(clone[:n])) +} + +// ReadFrom provides a simple functional packet reader, +// using the given byte slice as a backing array. +// +// To protect against potential denial of service attacks, +// if the read packet length is longer than maxPacketLength, +// then no packet data will be read, and ErrLongPacket will be returned. +// (On 32-bit int architectures, all packets >= 2^31 in length +// will return ErrLongPacket regardless of maxPacketLength.) +// +// If the read packet length is longer than cap(b), +// then a throw-away slice will allocated to meet the exact packet length. +// This can be used to limit the length of reused buffers, +// while still allowing reception of occasional large packets. +// +// The Request field may alias the passed in byte slice, +// so the byte slice passed in should not be reused before RawPacket.Reset(). +func (p *RequestPacket) ReadFrom(r io.Reader, b []byte, maxPacketLength uint32) error { + b, err := readPacket(r, b, maxPacketLength) + if err != nil { + return err + } + + return p.UnmarshalFrom(NewBuffer(b)) +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/path_packets.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/path_packets.go new file mode 100644 index 00000000..0180326f --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/path_packets.go @@ -0,0 +1,362 @@ +package sshfx + +// LStatPacket defines the SSH_FXP_LSTAT packet. +type LStatPacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *LStatPacket) Type() PacketType { + return PacketTypeLStat +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *LStatPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeLStat, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *LStatPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = LStatPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// SetstatPacket defines the SSH_FXP_SETSTAT packet. +type SetstatPacket struct { + Path string + Attrs Attributes +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *SetstatPacket) Type() PacketType { + return PacketTypeSetstat +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *SetstatPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) + p.Attrs.Len() // string(path) + ATTRS(attrs) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeSetstat, reqid) + buf.AppendString(p.Path) + + p.Attrs.MarshalInto(buf) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *SetstatPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = SetstatPacket{ + Path: buf.ConsumeString(), + } + + return p.Attrs.UnmarshalFrom(buf) +} + +// RemovePacket defines the SSH_FXP_REMOVE packet. +type RemovePacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *RemovePacket) Type() PacketType { + return PacketTypeRemove +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *RemovePacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeRemove, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *RemovePacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = RemovePacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// MkdirPacket defines the SSH_FXP_MKDIR packet. +type MkdirPacket struct { + Path string + Attrs Attributes +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *MkdirPacket) Type() PacketType { + return PacketTypeMkdir +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *MkdirPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) + p.Attrs.Len() // string(path) + ATTRS(attrs) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeMkdir, reqid) + buf.AppendString(p.Path) + + p.Attrs.MarshalInto(buf) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *MkdirPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = MkdirPacket{ + Path: buf.ConsumeString(), + } + + return p.Attrs.UnmarshalFrom(buf) +} + +// RmdirPacket defines the SSH_FXP_RMDIR packet. +type RmdirPacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *RmdirPacket) Type() PacketType { + return PacketTypeRmdir +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *RmdirPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeRmdir, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *RmdirPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = RmdirPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// RealPathPacket defines the SSH_FXP_REALPATH packet. +type RealPathPacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *RealPathPacket) Type() PacketType { + return PacketTypeRealPath +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *RealPathPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeRealPath, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *RealPathPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = RealPathPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// StatPacket defines the SSH_FXP_STAT packet. +type StatPacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *StatPacket) Type() PacketType { + return PacketTypeStat +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *StatPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeStat, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *StatPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = StatPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// RenamePacket defines the SSH_FXP_RENAME packet. +type RenamePacket struct { + OldPath string + NewPath string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *RenamePacket) Type() PacketType { + return PacketTypeRename +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *RenamePacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + // string(oldpath) + string(newpath) + size := 4 + len(p.OldPath) + 4 + len(p.NewPath) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeRename, reqid) + buf.AppendString(p.OldPath) + buf.AppendString(p.NewPath) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *RenamePacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = RenamePacket{ + OldPath: buf.ConsumeString(), + NewPath: buf.ConsumeString(), + } + + return buf.Err +} + +// ReadLinkPacket defines the SSH_FXP_READLINK packet. +type ReadLinkPacket struct { + Path string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *ReadLinkPacket) Type() PacketType { + return PacketTypeReadLink +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *ReadLinkPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + size := 4 + len(p.Path) // string(path) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeReadLink, reqid) + buf.AppendString(p.Path) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *ReadLinkPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = ReadLinkPacket{ + Path: buf.ConsumeString(), + } + + return buf.Err +} + +// SymlinkPacket defines the SSH_FXP_SYMLINK packet. +// +// The order of the arguments to the SSH_FXP_SYMLINK method was inadvertently reversed. +// Unfortunately, the reversal was not noticed until the server was widely deployed. +// Covered in Section 4.1 of https://github.com/openssh/openssh-portable/blob/master/PROTOCOL +type SymlinkPacket struct { + LinkPath string + TargetPath string +} + +// Type returns the SSH_FXP_xy value associated with this packet type. +func (p *SymlinkPacket) Type() PacketType { + return PacketTypeSymlink +} + +// MarshalPacket returns p as a two-part binary encoding of p. +func (p *SymlinkPacket) MarshalPacket(reqid uint32, b []byte) (header, payload []byte, err error) { + buf := NewBuffer(b) + if buf.Cap() < 9 { + // string(targetpath) + string(linkpath) + size := 4 + len(p.TargetPath) + 4 + len(p.LinkPath) + buf = NewMarshalBuffer(size) + } + + buf.StartPacket(PacketTypeSymlink, reqid) + + // Arguments were inadvertently reversed. + buf.AppendString(p.TargetPath) + buf.AppendString(p.LinkPath) + + return buf.Packet(payload) +} + +// UnmarshalPacketBody unmarshals the packet body from the given Buffer. +// It is assumed that the uint32(request-id) has already been consumed. +func (p *SymlinkPacket) UnmarshalPacketBody(buf *Buffer) (err error) { + *p = SymlinkPacket{ + // Arguments were inadvertently reversed. + TargetPath: buf.ConsumeString(), + LinkPath: buf.ConsumeString(), + } + + return buf.Err +} diff --git a/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/permissions.go b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/permissions.go new file mode 100644 index 00000000..0143ec0c --- /dev/null +++ b/vendor/github.com/pkg/sftp/internal/encoding/ssh/filexfer/permissions.go @@ -0,0 +1,114 @@ +package sshfx + +// FileMode represents a file’s mode and permission bits. +// The bits are defined according to POSIX standards, +// and may not apply to the OS being built for. +type FileMode uint32 + +// Permission flags, defined here to avoid potential inconsistencies in individual OS implementations. +const ( + ModePerm FileMode = 0o0777 // S_IRWXU | S_IRWXG | S_IRWXO + ModeUserRead FileMode = 0o0400 // S_IRUSR + ModeUserWrite FileMode = 0o0200 // S_IWUSR + ModeUserExec FileMode = 0o0100 // S_IXUSR + ModeGroupRead FileMode = 0o0040 // S_IRGRP + ModeGroupWrite FileMode = 0o0020 // S_IWGRP + ModeGroupExec FileMode = 0o0010 // S_IXGRP + ModeOtherRead FileMode = 0o0004 // S_IROTH + ModeOtherWrite FileMode = 0o0002 // S_IWOTH + ModeOtherExec FileMode = 0o0001 // S_IXOTH + + ModeSetUID FileMode = 0o4000 // S_ISUID + ModeSetGID FileMode = 0o2000 // S_ISGID + ModeSticky FileMode = 0o1000 // S_ISVTX + + ModeType FileMode = 0xF000 // S_IFMT + ModeNamedPipe FileMode = 0x1000 // S_IFIFO + ModeCharDevice FileMode = 0x2000 // S_IFCHR + ModeDir FileMode = 0x4000 // S_IFDIR + ModeDevice FileMode = 0x6000 // S_IFBLK + ModeRegular FileMode = 0x8000 // S_IFREG + ModeSymlink FileMode = 0xA000 // S_IFLNK + ModeSocket FileMode = 0xC000 // S_IFSOCK +) + +// IsDir reports whether m describes a directory. +// That is, it tests for m.Type() == ModeDir. +func (m FileMode) IsDir() bool { + return (m & ModeType) == ModeDir +} + +// IsRegular reports whether m describes a regular file. +// That is, it tests for m.Type() == ModeRegular +func (m FileMode) IsRegular() bool { + return (m & ModeType) == ModeRegular +} + +// Perm returns the POSIX permission bits in m (m & ModePerm). +func (m FileMode) Perm() FileMode { + return (m & ModePerm) +} + +// Type returns the type bits in m (m & ModeType). +func (m FileMode) Type() FileMode { + return (m & ModeType) +} + +// String returns a `-rwxrwxrwx` style string representing the `ls -l` POSIX permissions string. +func (m FileMode) String() string { + var buf [10]byte + + switch m.Type() { + case ModeRegular: + buf[0] = '-' + case ModeDir: + buf[0] = 'd' + case ModeSymlink: + buf[0] = 'l' + case ModeDevice: + buf[0] = 'b' + case ModeCharDevice: + buf[0] = 'c' + case ModeNamedPipe: + buf[0] = 'p' + case ModeSocket: + buf[0] = 's' + default: + buf[0] = '?' + } + + const rwx = "rwxrwxrwx" + for i, c := range rwx { + if m&(1<>24), byte(v>>16), byte(v>>8), byte(v)) +} + +func marshalUint64(b []byte, v uint64) []byte { + return marshalUint32(marshalUint32(b, uint32(v>>32)), uint32(v)) +} + +func marshalString(b []byte, v string) []byte { + return append(marshalUint32(b, uint32(len(v))), v...) +} + +func marshalFileInfo(b []byte, fi os.FileInfo) []byte { + // attributes variable struct, and also variable per protocol version + // spec version 3 attributes: + // uint32 flags + // uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE + // uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID + // uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID + // uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS + // uint32 atime present only if flag SSH_FILEXFER_ACMODTIME + // uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME + // uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED + // string extended_type + // string extended_data + // ... more extended data (extended_type - extended_data pairs), + // so that number of pairs equals extended_count + + flags, fileStat := fileStatFromInfo(fi) + + b = marshalUint32(b, flags) + + return marshalFileStat(b, flags, fileStat) +} + +func marshalFileStat(b []byte, flags uint32, fileStat *FileStat) []byte { + if flags&sshFileXferAttrSize != 0 { + b = marshalUint64(b, fileStat.Size) + } + if flags&sshFileXferAttrUIDGID != 0 { + b = marshalUint32(b, fileStat.UID) + b = marshalUint32(b, fileStat.GID) + } + if flags&sshFileXferAttrPermissions != 0 { + b = marshalUint32(b, fileStat.Mode) + } + if flags&sshFileXferAttrACmodTime != 0 { + b = marshalUint32(b, fileStat.Atime) + b = marshalUint32(b, fileStat.Mtime) + } + + if flags&sshFileXferAttrExtended != 0 { + b = marshalUint32(b, uint32(len(fileStat.Extended))) + + for _, attr := range fileStat.Extended { + b = marshalString(b, attr.ExtType) + b = marshalString(b, attr.ExtData) + } + } + + return b +} + +func marshalStatus(b []byte, err StatusError) []byte { + b = marshalUint32(b, err.Code) + b = marshalString(b, err.msg) + b = marshalString(b, err.lang) + return b +} + +func marshal(b []byte, v any) []byte { + switch v := v.(type) { + case nil: + return b + case uint8: + return append(b, v) + case uint32: + return marshalUint32(b, v) + case uint64: + return marshalUint64(b, v) + case string: + return marshalString(b, v) + case []byte: + return append(b, v...) + case os.FileInfo: + return marshalFileInfo(b, v) + default: + switch d := reflect.ValueOf(v); d.Kind() { + case reflect.Struct: + for i, n := 0, d.NumField(); i < n; i++ { + b = marshal(b, d.Field(i).Interface()) + } + return b + case reflect.Slice: + for i, n := 0, d.Len(); i < n; i++ { + b = marshal(b, d.Index(i).Interface()) + } + return b + default: + panic(fmt.Sprintf("marshal(%#v): cannot handle type %T", v, v)) + } + } +} + +func unmarshalUint32(b []byte) (uint32, []byte) { + v := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 + return v, b[4:] +} + +func unmarshalUint32Safe(b []byte) (uint32, []byte, error) { + var v uint32 + if len(b) < 4 { + return 0, nil, errShortPacket + } + v, b = unmarshalUint32(b) + return v, b, nil +} + +func unmarshalUint64(b []byte) (uint64, []byte) { + h, b := unmarshalUint32(b) + l, b := unmarshalUint32(b) + return uint64(h)<<32 | uint64(l), b +} + +func unmarshalUint64Safe(b []byte) (uint64, []byte, error) { + var v uint64 + if len(b) < 8 { + return 0, nil, errShortPacket + } + v, b = unmarshalUint64(b) + return v, b, nil +} + +func unmarshalString(b []byte) (string, []byte) { + n, b := unmarshalUint32(b) + return string(b[:n]), b[n:] +} + +func unmarshalStringSafe(b []byte) (string, []byte, error) { + n, b, err := unmarshalCount(b) + if err != nil { + return "", nil, err + } + if n > len(b) { + return "", nil, errShortPacket + } + return string(b[:n]), b[n:], nil +} + +func unmarshalAttrs(b []byte) (*FileStat, []byte, error) { + flags, b, err := unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + return unmarshalFileStat(flags, b) +} + +func unmarshalFileStat(flags uint32, b []byte) (*FileStat, []byte, error) { + var fs FileStat + var err error + + if flags&sshFileXferAttrSize == sshFileXferAttrSize { + fs.Size, b, err = unmarshalUint64Safe(b) + if err != nil { + return nil, b, err + } + } + if flags&sshFileXferAttrUIDGID == sshFileXferAttrUIDGID { + fs.UID, b, err = unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + fs.GID, b, err = unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + } + if flags&sshFileXferAttrPermissions == sshFileXferAttrPermissions { + fs.Mode, b, err = unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + } + if flags&sshFileXferAttrACmodTime == sshFileXferAttrACmodTime { + fs.Atime, b, err = unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + fs.Mtime, b, err = unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + } + if flags&sshFileXferAttrExtended == sshFileXferAttrExtended { + var count uint32 + count, b, err = unmarshalUint32Safe(b) + if err != nil { + return nil, b, err + } + + // Each extended attribute occupies at least 8 bytes (two + // length-prefixed strings), so a count larger than len(b)/8 cannot + // fit and is malformed. + if count > uint32(len(b)/8) { + return nil, b, errShortPacket + } + ext := make([]StatExtended, count) + for i := uint32(0); i < count; i++ { + var typ string + var data string + typ, b, err = unmarshalStringSafe(b) + if err != nil { + return nil, b, err + } + data, b, err = unmarshalStringSafe(b) + if err != nil { + return nil, b, err + } + ext[i] = StatExtended{ + ExtType: typ, + ExtData: data, + } + } + fs.Extended = ext + } + return &fs, b, nil +} + +// unmarshalSID consumes the request-id echoed back in a reply and verifies it +// matches the id we sent, returning the remaining bytes for further decoding. +func unmarshalSID(id uint32, b []byte) ([]byte, error) { + sid, b, err := unmarshalUint32Safe(b) + if err != nil { + return nil, err + } + if sid != id { + return nil, &unexpectedIDErr{id, sid} + } + return b, nil +} + +// unmarshalCount consumes a uint32 count and returns it as an int. A value that +// does not fit in a non-negative int is rejected with errLongPacket: this is +// only possible when strconv.IntSize == 32 and the count exceeds math.MaxInt32, +// in which case it is longer than any possible slice and would otherwise drive a +// negative length into make/slice and panic. +func unmarshalCount(b []byte) (int, []byte, error) { + v, b, err := unmarshalUint32Safe(b) + if err != nil { + return 0, nil, err + } + if int(v) < 0 { + return 0, nil, errLongPacket + } + return int(v), b, nil +} + +func unmarshalStatus(id uint32, data []byte) error { + data, err := unmarshalSID(id, data) + if err != nil { + return err + } + code, data, err := unmarshalUint32Safe(data) + if err != nil { + return err + } + msg, data, _ := unmarshalStringSafe(data) + lang, _, _ := unmarshalStringSafe(data) + return &StatusError{ + Code: code, + msg: msg, + lang: lang, + } +} + +// unmarshalDataReply parses an SSH_FXP_DATA reply, validating the id and the +// declared data length against the bytes actually present. It returns the data +// payload as a sub-slice of data. +func unmarshalDataReply(id uint32, data []byte) ([]byte, error) { + data, err := unmarshalSID(id, data) + if err != nil { + return nil, err + } + l, data, err := unmarshalCount(data) + if err != nil { + return nil, err + } + if l > len(data) { + return nil, errShortPacket + } + return data[:l], nil +} + +type packetMarshaler interface { + marshalPacket() (header, payload []byte, err error) +} + +func marshalPacket(m encoding.BinaryMarshaler) (header, payload []byte, err error) { + if m, ok := m.(packetMarshaler); ok { + return m.marshalPacket() + } + + header, err = m.MarshalBinary() + return +} + +// sendPacket marshals p according to RFC 4234. +func sendPacket(w io.Writer, m encoding.BinaryMarshaler) error { + header, payload, err := marshalPacket(m) + if err != nil { + return fmt.Errorf("binary marshaller failed: %w", err) + } + + length := len(header) + len(payload) - 4 // subtract the uint32(length) from the start + if debugDumpTxPacketBytes { + debug("send packet: %s %d bytes %x%x", fxp(header[4]), length, header[5:], payload) + } else if debugDumpTxPacket { + debug("send packet: %s %d bytes", fxp(header[4]), length) + } + + binary.BigEndian.PutUint32(header[:4], uint32(length)) + + if _, err := w.Write(header); err != nil { + return fmt.Errorf("failed to send packet: %w", err) + } + + if len(payload) > 0 { + if _, err := w.Write(payload); err != nil { + return fmt.Errorf("failed to send packet payload: %w", err) + } + } + + return nil +} + +func recvPacket(r io.Reader, alloc *allocator, orderID uint32) (fxp, []byte, error) { + var b []byte + if alloc != nil { + b = alloc.GetPage(orderID) + } else { + b = make([]byte, 4) + } + + if n, err := io.ReadFull(r, b[:4]); err != nil { + if err == io.EOF { + return 0, nil, err + } + + return 0, nil, fmt.Errorf("error reading packet length: %d of 4: %w", n, err) + } + + length, _ := unmarshalUint32(b) + if length > maxMsgLength { + debug("recv packet %d bytes too long", length) + return 0, nil, errLongPacket + } + if length == 0 { + debug("recv packet of 0 bytes too short") + return 0, nil, errShortPacket + } + + if alloc == nil { + b = make([]byte, length) + } + + n, err := io.ReadFull(r, b[:length]) + b = b[:n] + + if err != nil { + debug("recv packet error: %d of %d bytes: %x", n, length, b) + + // ReadFull only returns EOF if it has read no bytes. + // In this case, that means a partial packet, and thus unexpected. + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + + if n == 0 { + return 0, nil, fmt.Errorf("error reading packet body: %d of %d: %w", n, length, err) + } + + return 0, nil, fmt.Errorf("error reading packet body: %d of %d: (%s) %w", n, length, fxp(b[0]), err) + } + + typ, payload := fxp(b[0]), b[1:n] + + if debugDumpRxPacketBytes { + debug("recv packet: %s %d bytes %x", typ, length, payload) + } else if debugDumpRxPacket { + debug("recv packet: %s %d bytes", typ, length) + } + + return typ, payload, nil +} + +type extensionPair struct { + Name string + Data string +} + +func unmarshalExtensionPair(b []byte) (extensionPair, []byte, error) { + var ep extensionPair + var err error + ep.Name, b, err = unmarshalStringSafe(b) + if err != nil { + return ep, b, err + } + ep.Data, b, err = unmarshalStringSafe(b) + return ep, b, err +} + +// Here starts the definition of packets along with their MarshalBinary +// implementations. +// Manually writing the marshalling logic wins us a lot of time and +// allocation. + +type sshFxInitPacket struct { + Version uint32 + Extensions []extensionPair +} + +func (p *sshFxInitPacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 // uint32(length) + byte(type) + uint32(version) + for _, e := range p.Extensions { + l += 4 + len(e.Name) + 4 + len(e.Data) + } + + b := make([]byte, 4, l) + b = append(b, sshFxpInit) + b = marshalUint32(b, p.Version) + + for _, e := range p.Extensions { + b = marshalString(b, e.Name) + b = marshalString(b, e.Data) + } + + return b, nil +} + +func (p *sshFxInitPacket) UnmarshalBinary(b []byte) error { + var err error + if p.Version, b, err = unmarshalUint32Safe(b); err != nil { + return err + } + for len(b) > 0 { + var ep extensionPair + ep, b, err = unmarshalExtensionPair(b) + if err != nil { + return err + } + p.Extensions = append(p.Extensions, ep) + } + return nil +} + +type sshFxVersionPacket struct { + Version uint32 + Extensions []sshExtensionPair +} + +type sshExtensionPair struct { + Name, Data string +} + +func (p *sshFxVersionPacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 // uint32(length) + byte(type) + uint32(version) + for _, e := range p.Extensions { + l += 4 + len(e.Name) + 4 + len(e.Data) + } + + b := make([]byte, 4, l) + b = append(b, sshFxpVersion) + b = marshalUint32(b, p.Version) + + for _, e := range p.Extensions { + b = marshalString(b, e.Name) + b = marshalString(b, e.Data) + } + + return b, nil +} + +func marshalIDStringPacket(packetType byte, id uint32, str string) ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(str) + + b := make([]byte, 4, l) + b = append(b, packetType) + b = marshalUint32(b, id) + b = marshalString(b, str) + + return b, nil +} + +func unmarshalIDString(b []byte, id *uint32, str *string) error { + var err error + *id, b, err = unmarshalUint32Safe(b) + if err != nil { + return err + } + *str, _, err = unmarshalStringSafe(b) + return err +} + +type sshFxpReaddirPacket struct { + ID uint32 + Handle string +} + +func (p *sshFxpReaddirPacket) id() uint32 { return p.ID } + +func (p *sshFxpReaddirPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpReaddir, p.ID, p.Handle) +} + +func (p *sshFxpReaddirPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Handle) +} + +type sshFxpOpendirPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpOpendirPacket) id() uint32 { return p.ID } + +func (p *sshFxpOpendirPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpOpendir, p.ID, p.Path) +} + +func (p *sshFxpOpendirPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Path) +} + +type sshFxpLstatPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpLstatPacket) id() uint32 { return p.ID } + +func (p *sshFxpLstatPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpLstat, p.ID, p.Path) +} + +func (p *sshFxpLstatPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Path) +} + +type sshFxpStatPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpStatPacket) id() uint32 { return p.ID } + +func (p *sshFxpStatPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpStat, p.ID, p.Path) +} + +func (p *sshFxpStatPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Path) +} + +type sshFxpFstatPacket struct { + ID uint32 + Handle string +} + +func (p *sshFxpFstatPacket) id() uint32 { return p.ID } + +func (p *sshFxpFstatPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpFstat, p.ID, p.Handle) +} + +func (p *sshFxpFstatPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Handle) +} + +type sshFxpClosePacket struct { + ID uint32 + Handle string +} + +func (p *sshFxpClosePacket) id() uint32 { return p.ID } + +func (p *sshFxpClosePacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpClose, p.ID, p.Handle) +} + +func (p *sshFxpClosePacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Handle) +} + +type sshFxpRemovePacket struct { + ID uint32 + Filename string +} + +func (p *sshFxpRemovePacket) id() uint32 { return p.ID } + +func (p *sshFxpRemovePacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpRemove, p.ID, p.Filename) +} + +func (p *sshFxpRemovePacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Filename) +} + +type sshFxpRmdirPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpRmdirPacket) id() uint32 { return p.ID } + +func (p *sshFxpRmdirPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpRmdir, p.ID, p.Path) +} + +func (p *sshFxpRmdirPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Path) +} + +type sshFxpSymlinkPacket struct { + ID uint32 + + // The order of the arguments to the SSH_FXP_SYMLINK method was inadvertently reversed. + // Unfortunately, the reversal was not noticed until the server was widely deployed. + // Covered in Section 4.1 of https://github.com/openssh/openssh-portable/blob/master/PROTOCOL + + Targetpath string + Linkpath string +} + +func (p *sshFxpSymlinkPacket) id() uint32 { return p.ID } + +func (p *sshFxpSymlinkPacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Targetpath) + + 4 + len(p.Linkpath) + + b := make([]byte, 4, l) + b = append(b, sshFxpSymlink) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Targetpath) + b = marshalString(b, p.Linkpath) + + return b, nil +} + +func (p *sshFxpSymlinkPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Targetpath, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Linkpath, _, err = unmarshalStringSafe(b); err != nil { + return err + } + return nil +} + +type sshFxpHardlinkPacket struct { + ID uint32 + Oldpath string + Newpath string +} + +func (p *sshFxpHardlinkPacket) id() uint32 { return p.ID } + +func (p *sshFxpHardlinkPacket) MarshalBinary() ([]byte, error) { + const ext = "hardlink@openssh.com" + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(ext) + + 4 + len(p.Oldpath) + + 4 + len(p.Newpath) + + b := make([]byte, 4, l) + b = append(b, sshFxpExtended) + b = marshalUint32(b, p.ID) + b = marshalString(b, ext) + b = marshalString(b, p.Oldpath) + b = marshalString(b, p.Newpath) + + return b, nil +} + +type sshFxpReadlinkPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpReadlinkPacket) id() uint32 { return p.ID } + +func (p *sshFxpReadlinkPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpReadlink, p.ID, p.Path) +} + +func (p *sshFxpReadlinkPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Path) +} + +type sshFxpRealpathPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpRealpathPacket) id() uint32 { return p.ID } + +func (p *sshFxpRealpathPacket) MarshalBinary() ([]byte, error) { + return marshalIDStringPacket(sshFxpRealpath, p.ID, p.Path) +} + +func (p *sshFxpRealpathPacket) UnmarshalBinary(b []byte) error { + return unmarshalIDString(b, &p.ID, &p.Path) +} + +type sshFxpNameAttr struct { + Name string + LongName string + Attrs []any +} + +func (p *sshFxpNameAttr) MarshalBinary() ([]byte, error) { + var b []byte + b = marshalString(b, p.Name) + b = marshalString(b, p.LongName) + for _, attr := range p.Attrs { + b = marshal(b, attr) + } + return b, nil +} + +type sshFxpNamePacket struct { + ID uint32 + NameAttrs []*sshFxpNameAttr +} + +func (p *sshFxpNamePacket) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + + b := make([]byte, 4, l) + b = append(b, sshFxpName) + b = marshalUint32(b, p.ID) + b = marshalUint32(b, uint32(len(p.NameAttrs))) + + var payload []byte + for _, na := range p.NameAttrs { + ab, err := na.MarshalBinary() + if err != nil { + return nil, nil, err + } + + payload = append(payload, ab...) + } + + return b, payload, nil +} + +func (p *sshFxpNamePacket) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +type sshFxpOpenPacket struct { + ID uint32 + Path string + Pflags uint32 + Flags uint32 + Attrs any +} + +func (p *sshFxpOpenPacket) id() uint32 { return p.ID } + +func (p *sshFxpOpenPacket) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Path) + + 4 + 4 + + b := make([]byte, 4, l) + b = append(b, sshFxpOpen) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Path) + b = marshalUint32(b, p.Pflags) + b = marshalUint32(b, p.Flags) + + switch attrs := p.Attrs.(type) { + case []byte: + return b, attrs, nil // may as well short-ciruit this case. + case os.FileInfo: + _, fs := fileStatFromInfo(attrs) // we throw away the flags, and override with those in packet. + return b, marshalFileStat(nil, p.Flags, fs), nil + case *FileStat: + return b, marshalFileStat(nil, p.Flags, attrs), nil + } + + return b, marshal(nil, p.Attrs), nil +} + +func (p *sshFxpOpenPacket) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +func (p *sshFxpOpenPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Pflags, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { + return err + } + p.Attrs = b + return nil +} + +func (p *sshFxpOpenPacket) unmarshalFileStat(flags uint32) (*FileStat, error) { + switch attrs := p.Attrs.(type) { + case *FileStat: + return attrs, nil + case []byte: + fs, _, err := unmarshalFileStat(flags, attrs) + return fs, err + default: + return nil, fmt.Errorf("invalid type in unmarshalFileStat: %T", attrs) + } +} + +type sshFxpReadPacket struct { + ID uint32 + Len uint32 + Offset uint64 + Handle string +} + +func (p *sshFxpReadPacket) id() uint32 { return p.ID } + +func (p *sshFxpReadPacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Handle) + + 8 + 4 // uint64 + uint32 + + b := make([]byte, 4, l) + b = append(b, sshFxpRead) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Handle) + b = marshalUint64(b, p.Offset) + b = marshalUint32(b, p.Len) + + return b, nil +} + +func (p *sshFxpReadPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Handle, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Offset, b, err = unmarshalUint64Safe(b); err != nil { + return err + } else if p.Len, _, err = unmarshalUint32Safe(b); err != nil { + return err + } + return nil +} + +// We need allocate bigger slices with extra capacity to avoid a re-allocation in sshFxpDataPacket.MarshalBinary +// So, we need: uint32(length) + byte(type) + uint32(id) + uint32(data_length) +const dataHeaderLen = 4 + 1 + 4 + 4 + +func (p *sshFxpReadPacket) getDataSlice(alloc *allocator, orderID uint32, maxTxPacket uint32) []byte { + dataLen := p.Len + if dataLen > maxTxPacket { + dataLen = maxTxPacket + } + + if alloc != nil { + // GetPage returns a slice with capacity = maxMsgLength this is enough to avoid new allocations in + // sshFxpDataPacket.MarshalBinary + return alloc.GetPage(orderID)[:dataLen] + } + + // allocate with extra space for the header + return make([]byte, dataLen, dataLen+dataHeaderLen) +} + +type sshFxpRenamePacket struct { + ID uint32 + Oldpath string + Newpath string +} + +func (p *sshFxpRenamePacket) id() uint32 { return p.ID } + +func (p *sshFxpRenamePacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Oldpath) + + 4 + len(p.Newpath) + + b := make([]byte, 4, l) + b = append(b, sshFxpRename) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Oldpath) + b = marshalString(b, p.Newpath) + + return b, nil +} + +func (p *sshFxpRenamePacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Oldpath, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Newpath, _, err = unmarshalStringSafe(b); err != nil { + return err + } + return nil +} + +type sshFxpPosixRenamePacket struct { + ID uint32 + Oldpath string + Newpath string +} + +func (p *sshFxpPosixRenamePacket) id() uint32 { return p.ID } + +func (p *sshFxpPosixRenamePacket) MarshalBinary() ([]byte, error) { + const ext = "posix-rename@openssh.com" + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(ext) + + 4 + len(p.Oldpath) + + 4 + len(p.Newpath) + + b := make([]byte, 4, l) + b = append(b, sshFxpExtended) + b = marshalUint32(b, p.ID) + b = marshalString(b, ext) + b = marshalString(b, p.Oldpath) + b = marshalString(b, p.Newpath) + + return b, nil +} + +type sshFxpWritePacket struct { + ID uint32 + Length uint32 + Offset uint64 + Handle string + Data []byte +} + +func (p *sshFxpWritePacket) id() uint32 { return p.ID } + +func (p *sshFxpWritePacket) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Handle) + + 8 + // uint64 + 4 + + b := make([]byte, 4, l) + b = append(b, sshFxpWrite) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Handle) + b = marshalUint64(b, p.Offset) + b = marshalUint32(b, p.Length) + + return b, p.Data, nil +} + +func (p *sshFxpWritePacket) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +func (p *sshFxpWritePacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Handle, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Offset, b, err = unmarshalUint64Safe(b); err != nil { + return err + } else if p.Length, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if uint32(len(b)) < p.Length { + return errShortPacket + } + + p.Data = b[:p.Length] + return nil +} + +type sshFxpMkdirPacket struct { + ID uint32 + Flags uint32 // ignored + Path string +} + +func (p *sshFxpMkdirPacket) id() uint32 { return p.ID } + +func (p *sshFxpMkdirPacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Path) + + 4 // uint32 + + b := make([]byte, 4, l) + b = append(b, sshFxpMkdir) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Path) + b = marshalUint32(b, p.Flags) + + return b, nil +} + +func (p *sshFxpMkdirPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Flags, _, err = unmarshalUint32Safe(b); err != nil { + return err + } + return nil +} + +type sshFxpSetstatPacket struct { + ID uint32 + Flags uint32 + Path string + Attrs any +} + +type sshFxpFsetstatPacket struct { + ID uint32 + Flags uint32 + Handle string + Attrs any +} + +func (p *sshFxpSetstatPacket) id() uint32 { return p.ID } +func (p *sshFxpFsetstatPacket) id() uint32 { return p.ID } + +func (p *sshFxpSetstatPacket) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Path) + + 4 // uint32 + + b := make([]byte, 4, l) + b = append(b, sshFxpSetstat) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Path) + b = marshalUint32(b, p.Flags) + + switch attrs := p.Attrs.(type) { + case []byte: + return b, attrs, nil // may as well short-ciruit this case. + case os.FileInfo: + _, fs := fileStatFromInfo(attrs) // we throw away the flags, and override with those in packet. + return b, marshalFileStat(nil, p.Flags, fs), nil + case *FileStat: + return b, marshalFileStat(nil, p.Flags, attrs), nil + } + + return b, marshal(nil, p.Attrs), nil +} + +func (p *sshFxpSetstatPacket) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +func (p *sshFxpFsetstatPacket) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Handle) + + 4 // uint32 + + b := make([]byte, 4, l) + b = append(b, sshFxpFsetstat) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Handle) + b = marshalUint32(b, p.Flags) + + switch attrs := p.Attrs.(type) { + case []byte: + return b, attrs, nil // may as well short-ciruit this case. + case os.FileInfo: + _, fs := fileStatFromInfo(attrs) // we throw away the flags, and override with those in packet. + return b, marshalFileStat(nil, p.Flags, fs), nil + case *FileStat: + return b, marshalFileStat(nil, p.Flags, attrs), nil + } + + return b, marshal(nil, p.Attrs), nil +} + +func (p *sshFxpFsetstatPacket) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +func (p *sshFxpSetstatPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Path, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { + return err + } + p.Attrs = b + return nil +} + +func (p *sshFxpSetstatPacket) unmarshalFileStat(flags uint32) (*FileStat, error) { + switch attrs := p.Attrs.(type) { + case *FileStat: + return attrs, nil + case []byte: + fs, _, err := unmarshalFileStat(flags, attrs) + return fs, err + default: + return nil, fmt.Errorf("invalid type in unmarshalFileStat: %T", attrs) + } +} + +func (p *sshFxpFsetstatPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Handle, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Flags, b, err = unmarshalUint32Safe(b); err != nil { + return err + } + p.Attrs = b + return nil +} + +func (p *sshFxpFsetstatPacket) unmarshalFileStat(flags uint32) (*FileStat, error) { + switch attrs := p.Attrs.(type) { + case *FileStat: + return attrs, nil + case []byte: + fs, _, err := unmarshalFileStat(flags, attrs) + return fs, err + default: + return nil, fmt.Errorf("invalid type in unmarshalFileStat: %T", attrs) + } +} + +type sshFxpHandlePacket struct { + ID uint32 + Handle string +} + +func (p *sshFxpHandlePacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(p.Handle) + + b := make([]byte, 4, l) + b = append(b, sshFxpHandle) + b = marshalUint32(b, p.ID) + b = marshalString(b, p.Handle) + + return b, nil +} + +type sshFxpStatusPacket struct { + ID uint32 + StatusError +} + +func (p *sshFxpStatusPacket) MarshalBinary() ([]byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + + 4 + len(p.StatusError.msg) + + 4 + len(p.StatusError.lang) + + b := make([]byte, 4, l) + b = append(b, sshFxpStatus) + b = marshalUint32(b, p.ID) + b = marshalStatus(b, p.StatusError) + + return b, nil +} + +type sshFxpDataPacket struct { + ID uint32 + Length uint32 + Data []byte +} + +func (p *sshFxpDataPacket) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + + b := make([]byte, 4, l) + b = append(b, sshFxpData) + b = marshalUint32(b, p.ID) + b = marshalUint32(b, p.Length) + + return b, p.Data, nil +} + +// MarshalBinary encodes the receiver into a binary form and returns the result. +// To avoid a new allocation the Data slice must have a capacity >= Length + 9 +// +// This is hand-coded rather than just append(header, payload...), +// in order to try and reuse the r.Data backing store in the packet. +func (p *sshFxpDataPacket) MarshalBinary() ([]byte, error) { + b := append(p.Data, make([]byte, dataHeaderLen)...) + copy(b[dataHeaderLen:], p.Data[:p.Length]) + // b[0:4] will be overwritten with the length in sendPacket + b[4] = sshFxpData + binary.BigEndian.PutUint32(b[5:9], p.ID) + binary.BigEndian.PutUint32(b[9:13], p.Length) + return b, nil +} + +func (p *sshFxpDataPacket) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.Length, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if uint32(len(b)) < p.Length { + return errShortPacket + } + + p.Data = b[:p.Length] + return nil +} + +type sshFxpStatvfsPacket struct { + ID uint32 + Path string +} + +func (p *sshFxpStatvfsPacket) id() uint32 { return p.ID } + +func (p *sshFxpStatvfsPacket) MarshalBinary() ([]byte, error) { + const ext = "statvfs@openssh.com" + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(ext) + + 4 + len(p.Path) + + b := make([]byte, 4, l) + b = append(b, sshFxpExtended) + b = marshalUint32(b, p.ID) + b = marshalString(b, ext) + b = marshalString(b, p.Path) + + return b, nil +} + +// A StatVFS contains statistics about a filesystem. +type StatVFS struct { + ID uint32 + Bsize uint64 /* file system block size */ + Frsize uint64 /* fundamental fs block size */ + Blocks uint64 /* number of blocks (unit f_frsize) */ + Bfree uint64 /* free blocks in file system */ + Bavail uint64 /* free blocks for non-root */ + Files uint64 /* total file inodes */ + Ffree uint64 /* free file inodes */ + Favail uint64 /* free file inodes for to non-root */ + Fsid uint64 /* file system id */ + Flag uint64 /* bit mask of f_flag values */ + Namemax uint64 /* maximum filename length */ +} + +// TotalSpace calculates the amount of total space in a filesystem. +func (p *StatVFS) TotalSpace() uint64 { + return p.Frsize * p.Blocks +} + +// FreeSpace calculates the amount of free space in a filesystem. +func (p *StatVFS) FreeSpace() uint64 { + return p.Frsize * p.Bfree +} + +// marshalPacket converts to ssh_FXP_EXTENDED_REPLY packet binary format +func (p *StatVFS) marshalPacket() ([]byte, []byte, error) { + header := []byte{0, 0, 0, 0, sshFxpExtendedReply} + + var buf bytes.Buffer + err := binary.Write(&buf, binary.BigEndian, p) + + return header, buf.Bytes(), err +} + +// MarshalBinary encodes the StatVFS as an SSH_FXP_EXTENDED_REPLY packet. +func (p *StatVFS) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +type sshFxpFsyncPacket struct { + ID uint32 + Handle string +} + +func (p *sshFxpFsyncPacket) id() uint32 { return p.ID } + +func (p *sshFxpFsyncPacket) MarshalBinary() ([]byte, error) { + const ext = "fsync@openssh.com" + l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id) + 4 + len(ext) + + 4 + len(p.Handle) + + b := make([]byte, 4, l) + b = append(b, sshFxpExtended) + b = marshalUint32(b, p.ID) + b = marshalString(b, ext) + b = marshalString(b, p.Handle) + + return b, nil +} + +type sshFxpExtendedPacket struct { + ID uint32 + ExtendedRequest string + SpecificPacket interface { + serverRespondablePacket + readonly() bool + } +} + +func (p *sshFxpExtendedPacket) id() uint32 { return p.ID } +func (p *sshFxpExtendedPacket) readonly() bool { + if p.SpecificPacket == nil { + return true + } + return p.SpecificPacket.readonly() +} + +func (p *sshFxpExtendedPacket) respond(svr *Server) responsePacket { + if p.SpecificPacket == nil { + return statusFromError(p.ID, nil) + } + return p.SpecificPacket.respond(svr) +} + +func (p *sshFxpExtendedPacket) UnmarshalBinary(b []byte) error { + var err error + bOrig := b + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.ExtendedRequest, _, err = unmarshalStringSafe(b); err != nil { + return err + } + + // specific unmarshalling + switch p.ExtendedRequest { + case "statvfs@openssh.com": + p.SpecificPacket = &sshFxpExtendedPacketStatVFS{} + case "posix-rename@openssh.com": + p.SpecificPacket = &sshFxpExtendedPacketPosixRename{} + case "hardlink@openssh.com": + p.SpecificPacket = &sshFxpExtendedPacketHardlink{} + default: + return fmt.Errorf("packet type %v: %w", p.SpecificPacket, errUnknownExtendedPacket) + } + + return p.SpecificPacket.UnmarshalBinary(bOrig) +} + +type sshFxpExtendedPacketStatVFS struct { + ID uint32 + ExtendedRequest string + Path string +} + +func (p *sshFxpExtendedPacketStatVFS) id() uint32 { return p.ID } +func (p *sshFxpExtendedPacketStatVFS) readonly() bool { return true } +func (p *sshFxpExtendedPacketStatVFS) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.ExtendedRequest, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Path, _, err = unmarshalStringSafe(b); err != nil { + return err + } + return nil +} + +type sshFxpExtendedPacketPosixRename struct { + ID uint32 + ExtendedRequest string + Oldpath string + Newpath string +} + +func (p *sshFxpExtendedPacketPosixRename) id() uint32 { return p.ID } +func (p *sshFxpExtendedPacketPosixRename) readonly() bool { return false } +func (p *sshFxpExtendedPacketPosixRename) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.ExtendedRequest, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Oldpath, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Newpath, _, err = unmarshalStringSafe(b); err != nil { + return err + } + return nil +} + +func (p *sshFxpExtendedPacketPosixRename) respond(s *Server) responsePacket { + err := os.Rename(s.toLocalPath(p.Oldpath), s.toLocalPath(p.Newpath)) + return statusFromError(p.ID, err) +} + +type sshFxpExtendedPacketHardlink struct { + ID uint32 + ExtendedRequest string + Oldpath string + Newpath string +} + +// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL +func (p *sshFxpExtendedPacketHardlink) id() uint32 { return p.ID } +func (p *sshFxpExtendedPacketHardlink) readonly() bool { return false } +func (p *sshFxpExtendedPacketHardlink) UnmarshalBinary(b []byte) error { + var err error + if p.ID, b, err = unmarshalUint32Safe(b); err != nil { + return err + } else if p.ExtendedRequest, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Oldpath, b, err = unmarshalStringSafe(b); err != nil { + return err + } else if p.Newpath, _, err = unmarshalStringSafe(b); err != nil { + return err + } + return nil +} + +func (p *sshFxpExtendedPacketHardlink) respond(s *Server) responsePacket { + err := os.Link(s.toLocalPath(p.Oldpath), s.toLocalPath(p.Newpath)) + return statusFromError(p.ID, err) +} diff --git a/vendor/github.com/pkg/sftp/pool.go b/vendor/github.com/pkg/sftp/pool.go new file mode 100644 index 00000000..36126290 --- /dev/null +++ b/vendor/github.com/pkg/sftp/pool.go @@ -0,0 +1,79 @@ +package sftp + +// bufPool provides a pool of byte-slices to be reused in various parts of the package. +// It is safe to use concurrently through a pointer. +type bufPool struct { + ch chan []byte + blen int +} + +func newBufPool(depth, bufLen int) *bufPool { + return &bufPool{ + ch: make(chan []byte, depth), + blen: bufLen, + } +} + +func (p *bufPool) Get() []byte { + if p.blen <= 0 { + panic("bufPool: new buffer creation length must be greater than zero") + } + + for { + select { + case b := <-p.ch: + if cap(b) < p.blen { + // just in case: throw away any buffer with insufficient capacity. + continue + } + + return b[:p.blen] + + default: + return make([]byte, p.blen) + } + } +} + +func (p *bufPool) Put(b []byte) { + if p == nil { + // functional default: no reuse. + return + } + + if cap(b) < p.blen || cap(b) > p.blen*2 { + // DO NOT reuse buffers with insufficient capacity. + // This could cause panics when resizing to p.blen. + + // DO NOT reuse buffers with excessive capacity. + // This could cause memory leaks. + return + } + + select { + case p.ch <- b: + default: + } +} + +type resChanPool chan chan result + +func newResChanPool(depth int) resChanPool { + return make(chan chan result, depth) +} + +func (p resChanPool) Get() chan result { + select { + case ch := <-p: + return ch + default: + return make(chan result, 1) + } +} + +func (p resChanPool) Put(ch chan result) { + select { + case p <- ch: + default: + } +} diff --git a/vendor/github.com/pkg/sftp/release.go b/vendor/github.com/pkg/sftp/release.go new file mode 100644 index 00000000..7cc8a6f6 --- /dev/null +++ b/vendor/github.com/pkg/sftp/release.go @@ -0,0 +1,6 @@ +//go:build !debug +// +build !debug + +package sftp + +func debug(fmt string, args ...any) {} diff --git a/vendor/github.com/pkg/sftp/request-attrs.go b/vendor/github.com/pkg/sftp/request-attrs.go new file mode 100644 index 00000000..476c5651 --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-attrs.go @@ -0,0 +1,57 @@ +package sftp + +// Methods on the Request object to make working with the Flags bitmasks and +// Attr(ibutes) byte blob easier. Use Pflags() when working with an Open/Write +// request and AttrFlags() and Attributes() when working with SetStat requests. + +// FileOpenFlags defines Open and Write Flags. Correlate directly with with os.OpenFile flags +// (https://golang.org/pkg/os/#pkg-constants). +type FileOpenFlags struct { + Read, Write, Append, Creat, Trunc, Excl bool +} + +func newFileOpenFlags(flags uint32) FileOpenFlags { + return FileOpenFlags{ + Read: flags&sshFxfRead != 0, + Write: flags&sshFxfWrite != 0, + Append: flags&sshFxfAppend != 0, + Creat: flags&sshFxfCreat != 0, + Trunc: flags&sshFxfTrunc != 0, + Excl: flags&sshFxfExcl != 0, + } +} + +// Pflags converts the bitmap/uint32 from SFTP Open packet pflag values, +// into a FileOpenFlags struct with booleans set for flags set in bitmap. +func (r *Request) Pflags() FileOpenFlags { + return newFileOpenFlags(r.Flags) +} + +// FileAttrFlags that indicate whether SFTP file attributes were passed. When a flag is +// true the corresponding attribute should be available from the FileStat +// object returned by Attributes method. Used with SetStat. +type FileAttrFlags struct { + Size, UidGid, Permissions, Acmodtime bool +} + +func newFileAttrFlags(flags uint32) FileAttrFlags { + return FileAttrFlags{ + Size: (flags & sshFileXferAttrSize) != 0, + UidGid: (flags & sshFileXferAttrUIDGID) != 0, + Permissions: (flags & sshFileXferAttrPermissions) != 0, + Acmodtime: (flags & sshFileXferAttrACmodTime) != 0, + } +} + +// AttrFlags returns a FileAttrFlags boolean struct based on the +// bitmap/uint32 file attribute flags from the SFTP packaet. +func (r *Request) AttrFlags() FileAttrFlags { + return newFileAttrFlags(r.Flags) +} + +// Attributes parses file attributes byte blob and return them in a +// FileStat object. +func (r *Request) Attributes() *FileStat { + fs, _, _ := unmarshalFileStat(r.Flags, r.Attrs) + return fs +} diff --git a/vendor/github.com/pkg/sftp/request-errors.go b/vendor/github.com/pkg/sftp/request-errors.go new file mode 100644 index 00000000..6505b5c7 --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-errors.go @@ -0,0 +1,54 @@ +package sftp + +type fxerr uint32 + +// Error types that match the SFTP's SSH_FXP_STATUS codes. Gives you more +// direct control of the errors being sent vs. letting the library work them +// out from the standard os/io errors. +const ( + ErrSSHFxOk = fxerr(sshFxOk) + ErrSSHFxEOF = fxerr(sshFxEOF) + ErrSSHFxNoSuchFile = fxerr(sshFxNoSuchFile) + ErrSSHFxPermissionDenied = fxerr(sshFxPermissionDenied) + ErrSSHFxFailure = fxerr(sshFxFailure) + ErrSSHFxBadMessage = fxerr(sshFxBadMessage) + ErrSSHFxNoConnection = fxerr(sshFxNoConnection) + ErrSSHFxConnectionLost = fxerr(sshFxConnectionLost) + ErrSSHFxOpUnsupported = fxerr(sshFxOPUnsupported) +) + +// Deprecated error types, these are aliases for the new ones, please use the new ones directly +const ( + ErrSshFxOk = ErrSSHFxOk + ErrSshFxEof = ErrSSHFxEOF + ErrSshFxNoSuchFile = ErrSSHFxNoSuchFile + ErrSshFxPermissionDenied = ErrSSHFxPermissionDenied + ErrSshFxFailure = ErrSSHFxFailure + ErrSshFxBadMessage = ErrSSHFxBadMessage + ErrSshFxNoConnection = ErrSSHFxNoConnection + ErrSshFxConnectionLost = ErrSSHFxConnectionLost + ErrSshFxOpUnsupported = ErrSSHFxOpUnsupported +) + +func (e fxerr) Error() string { + switch e { + case ErrSSHFxOk: + return "OK" + case ErrSSHFxEOF: + return "EOF" + case ErrSSHFxNoSuchFile: + return "no such file" + case ErrSSHFxPermissionDenied: + return "permission denied" + case ErrSSHFxBadMessage: + return "bad message" + case ErrSSHFxNoConnection: + return "no connection" + case ErrSSHFxConnectionLost: + return "connection lost" + case ErrSSHFxOpUnsupported: + return "operation unsupported" + default: + return "failure" + } +} diff --git a/vendor/github.com/pkg/sftp/request-example.go b/vendor/github.com/pkg/sftp/request-example.go new file mode 100644 index 00000000..ec0e1a98 --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-example.go @@ -0,0 +1,647 @@ +package sftp + +// This serves as an example of how to implement the request server handler as +// well as a dummy backend for testing. It implements an in-memory backend that +// works as a very simple filesystem with simple flat key-value lookup system. + +import ( + "errors" + "io" + "os" + "path" + "sort" + "strings" + "sync" + "syscall" + "time" +) + +const maxSymlinkFollows = 5 + +var errTooManySymlinks = errors.New("too many symbolic links") + +// InMemHandler returns a Handlers object with the test handlers. +func InMemHandler() Handlers { + root := &root{ + rootFile: &memFile{name: "/", modtime: time.Now(), isdir: true}, + files: make(map[string]*memFile), + } + return Handlers{root, root, root, root} +} + +// Example Handlers +func (fs *root) Fileread(r *Request) (io.ReaderAt, error) { + flags := r.Pflags() + if !flags.Read { + // sanity check + return nil, os.ErrInvalid + } + + return fs.OpenFile(r) +} + +func (fs *root) Filewrite(r *Request) (io.WriterAt, error) { + flags := r.Pflags() + if !flags.Write { + // sanity check + return nil, os.ErrInvalid + } + + return fs.OpenFile(r) +} + +func (fs *root) OpenFile(r *Request) (WriterAtReaderAt, error) { + if fs.mockErr != nil { + return nil, fs.mockErr + } + _ = r.WithContext(r.Context()) // initialize context for deadlock testing + + fs.mu.Lock() + defer fs.mu.Unlock() + + return fs.openfile(r.Filepath, r.Flags) +} + +func (fs *root) putfile(pathname string, file *memFile) error { + pathname, err := fs.canonName(pathname) + if err != nil { + return err + } + + if !strings.HasPrefix(pathname, "/") { + return os.ErrInvalid + } + + if _, err := fs.lfetch(pathname); err != os.ErrNotExist { + return os.ErrExist + } + + file.name = pathname + fs.files[pathname] = file + + return nil +} + +func (fs *root) openfile(pathname string, flags uint32) (*memFile, error) { + pflags := newFileOpenFlags(flags) + + file, err := fs.fetch(pathname) + if err == os.ErrNotExist { + if !pflags.Creat { + return nil, os.ErrNotExist + } + + var count int + // You can create files through dangling symlinks. + link, err := fs.lfetch(pathname) + for err == nil && link.symlink != "" { + if pflags.Excl { + // unless you also passed in O_EXCL + return nil, os.ErrInvalid + } + + if count++; count > maxSymlinkFollows { + return nil, errTooManySymlinks + } + + pathname = link.symlink + link, err = fs.lfetch(pathname) + } + + file := &memFile{ + modtime: time.Now(), + } + + if err := fs.putfile(pathname, file); err != nil { + return nil, err + } + + return file, nil + } + + if err != nil { + return nil, err + } + + if pflags.Creat && pflags.Excl { + return nil, os.ErrExist + } + + if file.IsDir() { + return nil, os.ErrInvalid + } + + if pflags.Trunc { + if err := file.Truncate(0); err != nil { + return nil, err + } + } + + return file, nil +} + +func (fs *root) Filecmd(r *Request) error { + if fs.mockErr != nil { + return fs.mockErr + } + _ = r.WithContext(r.Context()) // initialize context for deadlock testing + + fs.mu.Lock() + defer fs.mu.Unlock() + + switch r.Method { + case "Setstat": + file, err := fs.openfile(r.Filepath, sshFxfWrite) + if err != nil { + return err + } + + if r.AttrFlags().Size { + return file.Truncate(int64(r.Attributes().Size)) + } + + return nil + + case "Rename": + // SFTP-v2: "It is an error if there already exists a file with the name specified by newpath." + // This varies from the POSIX specification, which allows limited replacement of target files. + if fs.exists(r.Target) { + return os.ErrExist + } + + return fs.rename(r.Filepath, r.Target) + + case "Rmdir": + return fs.rmdir(r.Filepath) + + case "Remove": + // IEEE 1003.1 remove explicitly can unlink files and remove empty directories. + // We use instead here the semantics of unlink, which is allowed to be restricted against directories. + return fs.unlink(r.Filepath) + + case "Mkdir": + return fs.mkdir(r.Filepath) + + case "Link": + return fs.link(r.Filepath, r.Target) + + case "Symlink": + // NOTE: r.Filepath is the target, and r.Target is the linkpath. + return fs.symlink(r.Filepath, r.Target) + } + + return errors.New("unsupported") +} + +func (fs *root) rename(oldpath, newpath string) error { + file, err := fs.lfetch(oldpath) + if err != nil { + return err + } + + newpath, err = fs.canonName(newpath) + if err != nil { + return err + } + + if !strings.HasPrefix(newpath, "/") { + return os.ErrInvalid + } + + target, err := fs.lfetch(newpath) + if err != os.ErrNotExist { + if target == file { + // IEEE 1003.1: if oldpath and newpath are the same directory entry, + // then return no error, and perform no further action. + return nil + } + + switch { + case file.IsDir(): + // IEEE 1003.1: if oldpath is a directory, and newpath exists, + // then newpath must be a directory, and empty. + // It is to be removed prior to rename. + if err := fs.rmdir(newpath); err != nil { + return err + } + + case target.IsDir(): + // IEEE 1003.1: if oldpath is not a directory, and newpath exists, + // then newpath may not be a directory. + return syscall.EISDIR + } + } + + fs.files[newpath] = file + + if file.IsDir() { + dirprefix := file.name + "/" + + for name, file := range fs.files { + if strings.HasPrefix(name, dirprefix) { + newname := path.Join(newpath, strings.TrimPrefix(name, dirprefix)) + + fs.files[newname] = file + file.name = newname + delete(fs.files, name) + } + } + } + + file.name = newpath + delete(fs.files, oldpath) + + return nil +} + +func (fs *root) PosixRename(r *Request) error { + if fs.mockErr != nil { + return fs.mockErr + } + _ = r.WithContext(r.Context()) // initialize context for deadlock testing + + fs.mu.Lock() + defer fs.mu.Unlock() + + return fs.rename(r.Filepath, r.Target) +} + +func (fs *root) StatVFS(r *Request) (*StatVFS, error) { + if fs.mockErr != nil { + return nil, fs.mockErr + } + + return getStatVFSForPath(r.Filepath) +} + +func (fs *root) mkdir(pathname string) error { + dir := &memFile{ + modtime: time.Now(), + isdir: true, + } + + return fs.putfile(pathname, dir) +} + +func (fs *root) rmdir(pathname string) error { + // IEEE 1003.1: If pathname is a symlink, then rmdir should fail with ENOTDIR. + dir, err := fs.lfetch(pathname) + if err != nil { + return err + } + + if !dir.IsDir() { + return syscall.ENOTDIR + } + + // use the dir‘s internal name not the pathname we passed in. + // the dir.name is always the canonical name of a directory. + pathname = dir.name + + for name := range fs.files { + if path.Dir(name) == pathname { + return errors.New("directory not empty") + } + } + + delete(fs.files, pathname) + + return nil +} + +func (fs *root) link(oldpath, newpath string) error { + file, err := fs.lfetch(oldpath) + if err != nil { + return err + } + + if file.IsDir() { + return errors.New("hard link not allowed for directory") + } + + return fs.putfile(newpath, file) +} + +// symlink() creates a symbolic link named `linkpath` which contains the string `target`. +// NOTE! This would be called with `symlink(req.Filepath, req.Target)` due to different semantics. +func (fs *root) symlink(target, linkpath string) error { + link := &memFile{ + modtime: time.Now(), + symlink: target, + } + + return fs.putfile(linkpath, link) +} + +func (fs *root) unlink(pathname string) error { + // does not follow symlinks! + file, err := fs.lfetch(pathname) + if err != nil { + return err + } + + if file.IsDir() { + // IEEE 1003.1: implementations may opt out of allowing the unlinking of directories. + // SFTP-v2: SSH_FXP_REMOVE may not remove directories. + return os.ErrInvalid + } + + // DO NOT use the file’s internal name. + // because of hard-links files cannot have a single canonical name. + delete(fs.files, pathname) + + return nil +} + +type listerat []os.FileInfo + +// Modeled after strings.Reader's ReadAt() implementation +func (f listerat) ListAt(ls []os.FileInfo, offset int64) (int, error) { + var n int + if offset >= int64(len(f)) { + return 0, io.EOF + } + n = copy(ls, f[offset:]) + if n < len(ls) { + return n, io.EOF + } + return n, nil +} + +func (fs *root) Filelist(r *Request) (ListerAt, error) { + if fs.mockErr != nil { + return nil, fs.mockErr + } + _ = r.WithContext(r.Context()) // initialize context for deadlock testing + + fs.mu.Lock() + defer fs.mu.Unlock() + + switch r.Method { + case "List": + files, err := fs.readdir(r.Filepath) + if err != nil { + return nil, err + } + return listerat(files), nil + + case "Stat": + file, err := fs.fetch(r.Filepath) + if err != nil { + return nil, err + } + return listerat{file}, nil + } + + return nil, errors.New("unsupported") +} + +func (fs *root) readdir(pathname string) ([]os.FileInfo, error) { + dir, err := fs.fetch(pathname) + if err != nil { + return nil, err + } + + if !dir.IsDir() { + return nil, syscall.ENOTDIR + } + + var files []os.FileInfo + + for name, file := range fs.files { + if path.Dir(name) == dir.name { + files = append(files, file) + } + } + + sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() }) + + return files, nil +} + +func (fs *root) Readlink(pathname string) (string, error) { + file, err := fs.lfetch(pathname) + if err != nil { + return "", err + } + + if file.symlink == "" { + return "", os.ErrInvalid + } + + return file.symlink, nil +} + +// implements LstatFileLister interface +func (fs *root) Lstat(r *Request) (ListerAt, error) { + if fs.mockErr != nil { + return nil, fs.mockErr + } + _ = r.WithContext(r.Context()) // initialize context for deadlock testing + + fs.mu.Lock() + defer fs.mu.Unlock() + + file, err := fs.lfetch(r.Filepath) + if err != nil { + return nil, err + } + return listerat{file}, nil +} + +// In memory file-system-y thing that the Handlers live on +type root struct { + rootFile *memFile + mockErr error + + mu sync.Mutex + files map[string]*memFile +} + +// Set a mocked error that the next handler call will return. +// Set to nil to reset for no error. +func (fs *root) returnErr(err error) { + fs.mockErr = err +} + +func (fs *root) lfetch(path string) (*memFile, error) { + if path == "/" { + return fs.rootFile, nil + } + + file, ok := fs.files[path] + if file == nil { + if ok { + delete(fs.files, path) + } + + return nil, os.ErrNotExist + } + + return file, nil +} + +// canonName returns the “canonical” name of a file, that is: +// if the directory of the pathname is a symlink, it follows that symlink to the valid directory name. +// this is relatively easy, since `dir.name` will be the only valid canonical path for a directory. +func (fs *root) canonName(pathname string) (string, error) { + dirname, filename := path.Dir(pathname), path.Base(pathname) + + dir, err := fs.fetch(dirname) + if err != nil { + return "", err + } + + if !dir.IsDir() { + return "", syscall.ENOTDIR + } + + return path.Join(dir.name, filename), nil +} + +func (fs *root) exists(path string) bool { + path, err := fs.canonName(path) + if err != nil { + return false + } + + _, err = fs.lfetch(path) + + return err != os.ErrNotExist +} + +func (fs *root) fetch(pathname string) (*memFile, error) { + file, err := fs.lfetch(pathname) + if err != nil { + return nil, err + } + + var count int + for file.symlink != "" { + if count++; count > maxSymlinkFollows { + return nil, errTooManySymlinks + } + + linkTarget := file.symlink + if !path.IsAbs(linkTarget) { + linkTarget = path.Join(path.Dir(file.name), linkTarget) + } + + file, err = fs.lfetch(linkTarget) + if err != nil { + return nil, err + } + } + + return file, nil +} + +// Implements os.FileInfo, io.ReaderAt and io.WriterAt interfaces. +// These are the 3 interfaces necessary for the Handlers. +// Implements the optional interface TransferError. +type memFile struct { + name string + modtime time.Time + symlink string + isdir bool + + mu sync.RWMutex + content []byte + err error +} + +// These are helper functions, they must be called while holding the memFile.mu mutex +func (f *memFile) size() int64 { return int64(len(f.content)) } +func (f *memFile) grow(n int64) { f.content = append(f.content, make([]byte, n)...) } + +// Have memFile fulfill os.FileInfo interface +func (f *memFile) Name() string { return path.Base(f.name) } +func (f *memFile) Size() int64 { + f.mu.Lock() + defer f.mu.Unlock() + + return f.size() +} +func (f *memFile) Mode() os.FileMode { + if f.isdir { + return os.FileMode(0755) | os.ModeDir + } + if f.symlink != "" { + return os.FileMode(0777) | os.ModeSymlink + } + return os.FileMode(0644) +} +func (f *memFile) ModTime() time.Time { return f.modtime } +func (f *memFile) IsDir() bool { return f.isdir } +func (f *memFile) Sys() any { + return fakeFileInfoSys() +} + +func (f *memFile) ReadAt(b []byte, off int64) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.err != nil { + return 0, f.err + } + + if off < 0 { + return 0, errors.New("memFile.ReadAt: negative offset") + } + + if off >= f.size() { + return 0, io.EOF + } + + n := copy(b, f.content[off:]) + if n < len(b) { + return n, io.EOF + } + + return n, nil +} + +func (f *memFile) WriteAt(b []byte, off int64) (int, error) { + // fmt.Println(string(p), off) + // mimic write delays, should be optional + time.Sleep(time.Microsecond * time.Duration(len(b))) + + f.mu.Lock() + defer f.mu.Unlock() + + if f.err != nil { + return 0, f.err + } + + grow := int64(len(b)) + off - f.size() + if grow > 0 { + f.grow(grow) + } + + return copy(f.content[off:], b), nil +} + +func (f *memFile) Truncate(size int64) error { + f.mu.Lock() + defer f.mu.Unlock() + + if f.err != nil { + return f.err + } + + grow := size - f.size() + if grow <= 0 { + f.content = f.content[:size] + } else { + f.grow(grow) + } + + return nil +} + +func (f *memFile) TransferError(err error) { + f.mu.Lock() + defer f.mu.Unlock() + + f.err = err +} diff --git a/vendor/github.com/pkg/sftp/request-interfaces.go b/vendor/github.com/pkg/sftp/request-interfaces.go new file mode 100644 index 00000000..13e7577e --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-interfaces.go @@ -0,0 +1,159 @@ +package sftp + +import ( + "io" + "os" +) + +// WriterAtReaderAt defines the interface to return when a file is to +// be opened for reading and writing +type WriterAtReaderAt interface { + io.WriterAt + io.ReaderAt +} + +// Interfaces are differentiated based on required returned values. +// All input arguments are to be pulled from Request (the only arg). + +// The Handler interfaces all take the Request object as its only argument. +// All the data you should need to handle the call are in the Request object. +// The request.Method attribute is initially the most important one as it +// determines which Handler gets called. + +// FileReader should return an io.ReaderAt for the filepath +// Note in cases of an error, the error text will be sent to the client. +// Called for Methods: Get +type FileReader interface { + Fileread(*Request) (io.ReaderAt, error) +} + +// FileWriter should return an io.WriterAt for the filepath. +// +// The request server code will call Close() on the returned io.WriterAt +// object if an io.Closer type assertion succeeds. +// Note in cases of an error, the error text will be sent to the client. +// Note when receiving an Append flag it is important to not open files using +// O_APPEND if you plan to use WriteAt, as they conflict. +// Called for Methods: Put, Open +type FileWriter interface { + Filewrite(*Request) (io.WriterAt, error) +} + +// OpenFileWriter is a FileWriter that implements the generic OpenFile method. +// You need to implement this optional interface if you want to be able +// to read and write from/to the same handle. +// Called for Methods: Open +type OpenFileWriter interface { + FileWriter + OpenFile(*Request) (WriterAtReaderAt, error) +} + +// FileCmder should return an error +// Note in cases of an error, the error text will be sent to the client. +// Called for Methods: Setstat, Rename, Rmdir, Mkdir, Link, Symlink, Remove +type FileCmder interface { + Filecmd(*Request) error +} + +// PosixRenameFileCmder is a FileCmder that implements the PosixRename method. +// If this interface is implemented PosixRename requests will call it +// otherwise they will be handled in the same way as Rename +type PosixRenameFileCmder interface { + FileCmder + PosixRename(*Request) error +} + +// StatVFSFileCmder is a FileCmder that implements the StatVFS method. +// You need to implement this interface if you want to handle statvfs requests. +// Please also be sure that the statvfs@openssh.com extension is enabled +type StatVFSFileCmder interface { + FileCmder + StatVFS(*Request) (*StatVFS, error) +} + +// FileLister should return an object that fulfils the ListerAt interface +// Note in cases of an error, the error text will be sent to the client. +// Called for Methods: List, Stat, Readlink +// +// Since Filelist returns an os.FileInfo, this can make it non-ideal for implementing Readlink. +// This is because the Name receiver method defined by that interface defines that it should only return the base name. +// However, Readlink is required to be capable of returning essentially any arbitrary valid path relative or absolute. +// In order to implement this more expressive requirement, implement [ReadlinkFileLister] which will then be used instead. +type FileLister interface { + Filelist(*Request) (ListerAt, error) +} + +// LstatFileLister is a FileLister that implements the Lstat method. +// If this interface is implemented Lstat requests will call it +// otherwise they will be handled in the same way as Stat +type LstatFileLister interface { + FileLister + Lstat(*Request) (ListerAt, error) +} + +// RealPathFileLister is a FileLister that implements the Realpath method. +// The built-in RealPath implementation does not resolve symbolic links. +// By implementing this interface you can customize the returned path +// and, for example, resolve symbolinc links if needed for your use case. +// You have to return an absolute POSIX path. +// +// Up to v1.13.5 the signature for the RealPath method was: +// +// # RealPath(string) string +// +// we have added a legacyRealPathFileLister that implements the old method +// to ensure that your code does not break. +// You should use the new method signature to avoid future issues +type RealPathFileLister interface { + FileLister + RealPath(string) (string, error) +} + +// ReadlinkFileLister is a FileLister that implements the Readlink method. +// By implementing the Readlink method, it is possible to return any arbitrary valid path relative or absolute. +// This allows giving a better response than via the default FileLister (which is limited to os.FileInfo, whose Name method should only return the base name of a file) +type ReadlinkFileLister interface { + FileLister + Readlink(string) (string, error) +} + +// This interface is here for backward compatibility only +type legacyRealPathFileLister interface { + FileLister + RealPath(string) string +} + +// NameLookupFileLister is a FileLister that implmeents the LookupUsername and LookupGroupName methods. +// If this interface is implemented, then longname ls formatting will use these to convert usernames and groupnames. +type NameLookupFileLister interface { + FileLister + LookupUserName(string) string + LookupGroupName(string) string +} + +// ListerAt does for file lists what io.ReaderAt does for files, i.e. a []os.FileInfo buffer is passed to the ListAt function +// and the entries that are populated in the buffer will be passed to the client. +// +// ListAt should return the number of entries copied and an io.EOF error if at end of list. +// This is testable by comparing how many you copied to how many could be copied (eg. n < len(ls) below). +// The copy() builtin is best for the copying. +// +// Uid and gid information will on unix systems be retrieved from [os.FileInfo.Sys] +// if this function returns a [syscall.Stat_t] when called on a populated entry. +// Alternatively, if the entry implements [FileInfoUidGid], it will be used for uid and gid information. +// +// If a populated entry implements [FileInfoExtendedData], extended attributes will also be returned to the client. +// +// The request server code will call Close() on ListerAt if an io.Closer type assertion succeeds. +// +// Note in cases of an error, the error text will be sent to the client. +type ListerAt interface { + ListAt([]os.FileInfo, int64) (int, error) +} + +// TransferError is an optional interface that readerAt and writerAt +// can implement to be notified about the error causing Serve() to exit +// with the request still open +type TransferError interface { + TransferError(err error) +} diff --git a/vendor/github.com/pkg/sftp/request-plan9.go b/vendor/github.com/pkg/sftp/request-plan9.go new file mode 100644 index 00000000..50dc01f8 --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-plan9.go @@ -0,0 +1,16 @@ +//go:build plan9 +// +build plan9 + +package sftp + +import ( + "syscall" +) + +func fakeFileInfoSys() any { + return &syscall.Dir{} +} + +func testOsSys(sys any) error { + return nil +} diff --git a/vendor/github.com/pkg/sftp/request-readme.md b/vendor/github.com/pkg/sftp/request-readme.md new file mode 100644 index 00000000..f8b81f3a --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-readme.md @@ -0,0 +1,53 @@ +# Request Based SFTP API + +The request based API allows for custom backends in a way similar to the http +package. In order to create a backend you need to implement 4 handler +interfaces; one for reading, one for writing, one for misc commands and one for +listing files. Each has 1 required method and in each case those methods take +the Request as the only parameter and they each return something different. +These 4 interfaces are enough to handle all the SFTP traffic in a simplified +manner. + +The Request structure has 5 public fields which you will deal with. + +- Method (string) - string name of incoming call +- Filepath (string) - POSIX path of file to act on +- Flags (uint32) - 32bit bitmask value of file open/create flags +- Attrs ([]byte) - byte string of file attribute data +- Target (string) - target path for renames and sym-links + +Below are the methods and a brief description of what they need to do. + +### Fileread(*Request) (io.Reader, error) + +Handler for "Get" method and returns an io.Reader for the file which the server +then sends to the client. + +### Filewrite(*Request) (io.Writer, error) + +Handler for "Put" method and returns an io.Writer for the file which the server +then writes the uploaded file to. The file opening "pflags" are currently +preserved in the Request.Flags field as a 32bit bitmask value. See the [SFTP +spec](https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt#section-6.3) for +details. + +### Filecmd(*Request) error + +Handles "SetStat", "Rename", "Rmdir", "Mkdir" and "Symlink" methods. Makes the +appropriate changes and returns nil for success or an filesystem like error +(eg. os.ErrNotExist). The attributes are currently propagated in their raw form +([]byte) and will need to be unmarshalled to be useful. See the respond method +on sshFxpSetstatPacket for example of you might want to do this. + +### Fileinfo(*Request) ([]os.FileInfo, error) + +Handles "List", "Stat", "Readlink" methods. Gathers/creates FileInfo structs +with the data on the files and returns in a list (list of 1 for Stat and +Readlink). + + +## TODO + +- Add support for API users to see trace/debugging info of what is going on +inside SFTP server. +- Unmarshal the file attributes into a structure on the Request object. diff --git a/vendor/github.com/pkg/sftp/request-server.go b/vendor/github.com/pkg/sftp/request-server.go new file mode 100644 index 00000000..08c24d7f --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-server.go @@ -0,0 +1,355 @@ +package sftp + +import ( + "context" + "errors" + "io" + "path" + "path/filepath" + "strconv" + "sync" +) + +const defaultMaxTxPacket uint32 = 1 << 15 + +// Handlers contains the 4 SFTP server request handlers. +type Handlers struct { + FileGet FileReader + FilePut FileWriter + FileCmd FileCmder + FileList FileLister +} + +// RequestServer abstracts the sftp protocol with an http request-like protocol +type RequestServer struct { + Handlers Handlers + + *serverConn + pktMgr *packetManager + + startDirectory string + maxTxPacket uint32 + + mu sync.RWMutex + handleCount int + openRequests map[string]*Request +} + +// A RequestServerOption is a function which applies configuration to a RequestServer. +type RequestServerOption func(*RequestServer) + +// WithRSAllocator enable the allocator. +// After processing a packet we keep in memory the allocated slices +// and we reuse them for new packets. +// The allocator is experimental +func WithRSAllocator() RequestServerOption { + return func(rs *RequestServer) { + alloc := newAllocator() + rs.pktMgr.alloc = alloc + rs.conn.alloc = alloc + } +} + +// WithStartDirectory sets a start directory to use as base for relative paths. +// If unset the default is "/" +func WithStartDirectory(startDirectory string) RequestServerOption { + return func(rs *RequestServer) { + rs.startDirectory = cleanPath(startDirectory) + } +} + +// WithRSMaxTxPacket sets the maximum size of the payload returned to the client, +// measured in bytes. The default value is 32768 bytes, and this option +// can only be used to increase it. Setting this option to a larger value +// should be safe, because the client decides the size of the requested payload. +// +// The default maximum packet size is 32768 bytes. +func WithRSMaxTxPacket(size uint32) RequestServerOption { + return func(rs *RequestServer) { + if size < defaultMaxTxPacket { + return + } + + rs.maxTxPacket = size + } +} + +// NewRequestServer creates/allocates/returns new RequestServer. +// Normally there will be one server per user-session. +func NewRequestServer(rwc io.ReadWriteCloser, h Handlers, options ...RequestServerOption) *RequestServer { + svrConn := &serverConn{ + conn: conn{ + Reader: rwc, + WriteCloser: rwc, + }, + } + rs := &RequestServer{ + Handlers: h, + + serverConn: svrConn, + pktMgr: newPktMgr(svrConn), + + startDirectory: "/", + maxTxPacket: defaultMaxTxPacket, + + openRequests: make(map[string]*Request), + } + + for _, o := range options { + o(rs) + } + return rs +} + +// New Open packet/Request +func (rs *RequestServer) nextRequest(r *Request) string { + rs.mu.Lock() + defer rs.mu.Unlock() + + rs.handleCount++ + + r.handle = strconv.Itoa(rs.handleCount) + rs.openRequests[r.handle] = r + + return r.handle +} + +// Returns Request from openRequests, bool is false if it is missing. +// +// The Requests in openRequests work essentially as open file descriptors that +// you can do different things with. What you are doing with it are denoted by +// the first packet of that type (read/write/etc). +func (rs *RequestServer) getRequest(handle string) (*Request, bool) { + rs.mu.RLock() + defer rs.mu.RUnlock() + + r, ok := rs.openRequests[handle] + return r, ok +} + +// Close the Request and clear from openRequests map +func (rs *RequestServer) closeRequest(handle string) error { + rs.mu.Lock() + defer rs.mu.Unlock() + + if r, ok := rs.openRequests[handle]; ok { + delete(rs.openRequests, handle) + return r.close() + } + + return EBADF +} + +// Close the read/write/closer to trigger exiting the main server loop +func (rs *RequestServer) Close() error { return rs.conn.Close() } + +func (rs *RequestServer) serveLoop(pktChan chan<- orderedRequest) error { + defer close(pktChan) // shuts down sftpServerWorkers + + var err error + var pkt requestPacket + var pktType fxp + var pktBytes []byte + + for { + pktType, pktBytes, err = rs.serverConn.recvPacket(rs.pktMgr.getNextOrderID()) + if err != nil { + // we don't care about releasing allocated pages here, the server will quit and the allocator freed + return err + } + + pkt, err = makePacket(rxPacket{pktType, pktBytes}) + if err != nil { + switch { + case errors.Is(err, errUnknownExtendedPacket): + // do nothing + default: + debug("makePacket err: %v", err) + rs.conn.Close() // shuts down recvPacket + return err + } + } + + pktChan <- rs.pktMgr.newOrderedRequest(pkt) + } +} + +// Serve requests for user session +func (rs *RequestServer) Serve() error { + defer func() { + if rs.pktMgr.alloc != nil { + rs.pktMgr.alloc.Free() + } + }() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var wg sync.WaitGroup + runWorker := func(ch chan orderedRequest) { + wg.Add(1) + go func() { + defer wg.Done() + if err := rs.packetWorker(ctx, ch); err != nil { + rs.conn.Close() // shuts down recvPacket + } + }() + } + pktChan := rs.pktMgr.workerChan(runWorker) + + err := rs.serveLoop(pktChan) + + wg.Wait() // wait for all workers to exit + + rs.mu.Lock() + defer rs.mu.Unlock() + + // make sure all open requests are properly closed + // (eg. possible on dropped connections, client crashes, etc.) + for handle, req := range rs.openRequests { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + req.transferError(err) + + delete(rs.openRequests, handle) + req.close() + } + + return err +} + +func (rs *RequestServer) packetWorker(ctx context.Context, pktChan chan orderedRequest) error { + for pkt := range pktChan { + orderID := pkt.orderID() + if epkt, ok := pkt.requestPacket.(*sshFxpExtendedPacket); ok { + if epkt.SpecificPacket != nil { + pkt.requestPacket = epkt.SpecificPacket + } + } + + var rpkt responsePacket + switch pkt := pkt.requestPacket.(type) { + case *sshFxInitPacket: + rpkt = &sshFxVersionPacket{Version: sftpProtocolVersion, Extensions: sftpExtensions} + case *sshFxpClosePacket: + handle := pkt.getHandle() + rpkt = statusFromError(pkt.ID, rs.closeRequest(handle)) + case *sshFxpRealpathPacket: + var realPath string + var err error + + switch pather := rs.Handlers.FileList.(type) { + case RealPathFileLister: + realPath, err = pather.RealPath(pkt.getPath()) + case legacyRealPathFileLister: + realPath = pather.RealPath(pkt.getPath()) + default: + realPath = cleanPathWithBase(rs.startDirectory, pkt.getPath()) + } + if err != nil { + rpkt = statusFromError(pkt.ID, err) + } else { + rpkt = cleanPacketPath(pkt, realPath) + } + case *sshFxpOpendirPacket: + request := requestFromPacket(ctx, pkt, rs.startDirectory) + handle := rs.nextRequest(request) + rpkt = request.opendir(rs.Handlers, pkt) + if _, ok := rpkt.(*sshFxpHandlePacket); !ok { + // if we return an error we have to remove the handle from the active ones + rs.closeRequest(handle) + } + case *sshFxpOpenPacket: + request := requestFromPacket(ctx, pkt, rs.startDirectory) + handle := rs.nextRequest(request) + rpkt = request.open(rs.Handlers, pkt) + if _, ok := rpkt.(*sshFxpHandlePacket); !ok { + // if we return an error we have to remove the handle from the active ones + rs.closeRequest(handle) + } + case *sshFxpFstatPacket: + handle := pkt.getHandle() + request, ok := rs.getRequest(handle) + if !ok { + rpkt = statusFromError(pkt.ID, EBADF) + } else { + request = &Request{ + Method: "Stat", + Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath), + } + rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket) + } + case *sshFxpFsetstatPacket: + handle := pkt.getHandle() + request, ok := rs.getRequest(handle) + if !ok { + rpkt = statusFromError(pkt.ID, EBADF) + } else { + request = &Request{ + Method: "Setstat", + Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath), + } + rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket) + } + case *sshFxpExtendedPacketPosixRename: + request := &Request{ + Method: "PosixRename", + Filepath: cleanPathWithBase(rs.startDirectory, pkt.Oldpath), + Target: cleanPathWithBase(rs.startDirectory, pkt.Newpath), + } + rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket) + case *sshFxpExtendedPacketStatVFS: + request := &Request{ + Method: "StatVFS", + Filepath: cleanPathWithBase(rs.startDirectory, pkt.Path), + } + rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket) + case hasHandle: + handle := pkt.getHandle() + request, ok := rs.getRequest(handle) + if !ok { + rpkt = statusFromError(pkt.id(), EBADF) + } else { + rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket) + } + case hasPath: + request := requestFromPacket(ctx, pkt, rs.startDirectory) + rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket) + request.close() + default: + rpkt = statusFromError(pkt.id(), ErrSSHFxOpUnsupported) + } + + rs.pktMgr.readyPacket( + rs.pktMgr.newOrderedResponse(rpkt, orderID)) + } + return nil +} + +// clean and return name packet for file +func cleanPacketPath(pkt *sshFxpRealpathPacket, realPath string) responsePacket { + return &sshFxpNamePacket{ + ID: pkt.id(), + NameAttrs: []*sshFxpNameAttr{ + { + Name: realPath, + LongName: realPath, + Attrs: emptyFileStat, + }, + }, + } +} + +// Makes sure we have a clean POSIX (/) absolute path to work with +func cleanPath(p string) string { + return cleanPathWithBase("/", p) +} + +func cleanPathWithBase(base, p string) string { + p = filepath.ToSlash(filepath.Clean(p)) + if !path.IsAbs(p) { + return path.Join(base, p) + } + return p +} diff --git a/vendor/github.com/pkg/sftp/request-unix.go b/vendor/github.com/pkg/sftp/request-unix.go new file mode 100644 index 00000000..b94063dd --- /dev/null +++ b/vendor/github.com/pkg/sftp/request-unix.go @@ -0,0 +1,24 @@ +//go:build !windows && !plan9 +// +build !windows,!plan9 + +package sftp + +import ( + "errors" + "syscall" +) + +func fakeFileInfoSys() any { + return &syscall.Stat_t{Uid: 65534, Gid: 65534} +} + +func testOsSys(sys any) error { + fstat := sys.(*FileStat) + if fstat.UID != uint32(65534) { + return errors.New("Uid failed to match") + } + if fstat.GID != uint32(65534) { + return errors.New("Gid failed to match") + } + return nil +} diff --git a/vendor/github.com/pkg/sftp/request.go b/vendor/github.com/pkg/sftp/request.go new file mode 100644 index 00000000..e01cad7a --- /dev/null +++ b/vendor/github.com/pkg/sftp/request.go @@ -0,0 +1,670 @@ +package sftp + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "strings" + "sync" + "syscall" +) + +// MaxFilelist is the max number of files to return in a readdir batch. +var MaxFilelist int64 = 100 + +// state encapsulates the reader/writer/readdir from handlers. +type state struct { + mu sync.RWMutex + + writerAt io.WriterAt + readerAt io.ReaderAt + writerAtReaderAt WriterAtReaderAt + listerAt ListerAt + lsoffset int64 +} + +// copy returns a shallow copy the state. +// This is broken out to specific fields, +// because we have to copy around the mutex in state. +func (s *state) copy() state { + s.mu.RLock() + defer s.mu.RUnlock() + + return state{ + writerAt: s.writerAt, + readerAt: s.readerAt, + writerAtReaderAt: s.writerAtReaderAt, + listerAt: s.listerAt, + lsoffset: s.lsoffset, + } +} + +func (s *state) setReaderAt(rd io.ReaderAt) { + s.mu.Lock() + defer s.mu.Unlock() + + s.readerAt = rd +} + +func (s *state) getReaderAt() io.ReaderAt { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.readerAt +} + +func (s *state) setWriterAt(rd io.WriterAt) { + s.mu.Lock() + defer s.mu.Unlock() + + s.writerAt = rd +} + +func (s *state) getWriterAt() io.WriterAt { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.writerAt +} + +func (s *state) setWriterAtReaderAt(rw WriterAtReaderAt) { + s.mu.Lock() + defer s.mu.Unlock() + + s.writerAtReaderAt = rw +} + +func (s *state) getWriterAtReaderAt() WriterAtReaderAt { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.writerAtReaderAt +} + +func (s *state) getAllReaderWriters() (io.ReaderAt, io.WriterAt, WriterAtReaderAt) { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.readerAt, s.writerAt, s.writerAtReaderAt +} + +// Returns current offset for file list +func (s *state) lsNext() int64 { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.lsoffset +} + +// Increases next offset +func (s *state) lsInc(offset int64) { + s.mu.Lock() + defer s.mu.Unlock() + + s.lsoffset += offset +} + +// manage file read/write state +func (s *state) setListerAt(la ListerAt) { + s.mu.Lock() + defer s.mu.Unlock() + + s.listerAt = la +} + +func (s *state) getListerAt() ListerAt { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.listerAt +} + +func (s *state) closeListerAt() error { + s.mu.Lock() + defer s.mu.Unlock() + + var err error + + if s.listerAt != nil { + if c, ok := s.listerAt.(io.Closer); ok { + err = c.Close() + } + s.listerAt = nil + } + + return err +} + +// Request contains the data and state for the incoming service request. +type Request struct { + // Get, Put, Setstat, Stat, Rename, Remove + // Rmdir, Mkdir, List, Readlink, Link, Symlink + Method string + Filepath string + Flags uint32 + Attrs []byte // convert to sub-struct + Target string // for renames and sym-links + handle string + + // reader/writer/readdir from handlers + state + + // context lasts duration of request + ctx context.Context + cancelCtx context.CancelFunc +} + +// NewRequest creates a new Request object. +func NewRequest(method, path string) *Request { + return &Request{ + Method: method, + Filepath: cleanPath(path), + } +} + +// copy returns a shallow copy of existing request. +// This is broken out to specific fields, +// because we have to copy around the mutex in state. +func (r *Request) copy() *Request { + return &Request{ + Method: r.Method, + Filepath: r.Filepath, + Flags: r.Flags, + Attrs: r.Attrs, + Target: r.Target, + handle: r.handle, + + state: r.state.copy(), + + ctx: r.ctx, + cancelCtx: r.cancelCtx, + } +} + +// New Request initialized based on packet data +func requestFromPacket(ctx context.Context, pkt hasPath, baseDir string) *Request { + request := &Request{ + Method: requestMethod(pkt), + Filepath: cleanPathWithBase(baseDir, pkt.getPath()), + } + request.ctx, request.cancelCtx = context.WithCancel(ctx) + + switch p := pkt.(type) { + case *sshFxpOpenPacket: + request.Flags = p.Pflags + request.Attrs = p.Attrs.([]byte) + case *sshFxpSetstatPacket: + request.Flags = p.Flags + request.Attrs = p.Attrs.([]byte) + case *sshFxpRenamePacket: + request.Target = cleanPathWithBase(baseDir, p.Newpath) + case *sshFxpSymlinkPacket: + // NOTE: given a POSIX compliant signature: symlink(target, linkpath string) + // this makes Request.Target the linkpath, and Request.Filepath the target. + request.Target = cleanPathWithBase(baseDir, p.Linkpath) + request.Filepath = p.Targetpath + case *sshFxpExtendedPacketHardlink: + request.Target = cleanPathWithBase(baseDir, p.Newpath) + } + return request +} + +// Context returns the request's context. To change the context, +// use WithContext. +// +// The returned context is always non-nil; it defaults to the +// background context. +// +// For incoming server requests, the context is canceled when the +// request is complete or the client's connection closes. +func (r *Request) Context() context.Context { + if r.ctx != nil { + return r.ctx + } + return context.Background() +} + +// WithContext returns a copy of r with its context changed to ctx. +// The provided ctx must be non-nil. +func (r *Request) WithContext(ctx context.Context) *Request { + if ctx == nil { + panic("nil context") + } + r2 := r.copy() + r2.ctx = ctx + r2.cancelCtx = nil + return r2 +} + +// Close reader/writer if possible +func (r *Request) close() error { + defer func() { + if r.cancelCtx != nil { + r.cancelCtx() + } + }() + + err := r.state.closeListerAt() + + rd, wr, rw := r.getAllReaderWriters() + + // Close errors on a Writer are far more likely to be the important one. + // As they can be information that there was a loss of data. + if c, ok := wr.(io.Closer); ok { + if err2 := c.Close(); err == nil { + // update error if it is still nil + err = err2 + } + } + + if c, ok := rw.(io.Closer); ok { + if err2 := c.Close(); err == nil { + // update error if it is still nil + err = err2 + + r.setWriterAtReaderAt(nil) + } + } + + if c, ok := rd.(io.Closer); ok { + if err2 := c.Close(); err == nil { + // update error if it is still nil + err = err2 + } + } + + return err +} + +// Notify transfer error if any +func (r *Request) transferError(err error) { + if err == nil { + return + } + + rd, wr, rw := r.getAllReaderWriters() + + if t, ok := wr.(TransferError); ok { + t.TransferError(err) + } + + if t, ok := rw.(TransferError); ok { + t.TransferError(err) + } + + if t, ok := rd.(TransferError); ok { + t.TransferError(err) + } +} + +// called from worker to handle packet/request +func (r *Request) call(handlers Handlers, pkt requestPacket, alloc *allocator, orderID uint32, maxTxPacket uint32) responsePacket { + switch r.Method { + case "Get": + return fileget(handlers.FileGet, r, pkt, alloc, orderID, maxTxPacket) + case "Put": + return fileput(handlers.FilePut, r, pkt, alloc, orderID, maxTxPacket) + case "Open": + return fileputget(handlers.FilePut, r, pkt, alloc, orderID, maxTxPacket) + case "Setstat", "Rename", "Rmdir", "Mkdir", "Link", "Symlink", "Remove", "PosixRename", "StatVFS": + return filecmd(handlers.FileCmd, r, pkt) + case "List": + return filelist(handlers.FileList, r, pkt) + case "Stat", "Lstat": + return filestat(handlers.FileList, r, pkt) + case "Readlink": + if readlinkFileLister, ok := handlers.FileList.(ReadlinkFileLister); ok { + return readlink(readlinkFileLister, r, pkt) + } + return filestat(handlers.FileList, r, pkt) + default: + return statusFromError(pkt.id(), fmt.Errorf("unexpected method: %s", r.Method)) + } +} + +// Additional initialization for Open packets +func (r *Request) open(h Handlers, pkt requestPacket) responsePacket { + flags := r.Pflags() + + id := pkt.id() + + switch { + case flags.Write, flags.Append, flags.Creat, flags.Trunc: + if flags.Read { + if openFileWriter, ok := h.FilePut.(OpenFileWriter); ok { + r.Method = "Open" + rw, err := openFileWriter.OpenFile(r) + if err != nil { + return statusFromError(id, err) + } + + r.setWriterAtReaderAt(rw) + + return &sshFxpHandlePacket{ + ID: id, + Handle: r.handle, + } + } + } + + r.Method = "Put" + wr, err := h.FilePut.Filewrite(r) + if err != nil { + return statusFromError(id, err) + } + + r.setWriterAt(wr) + + case flags.Read: + r.Method = "Get" + rd, err := h.FileGet.Fileread(r) + if err != nil { + return statusFromError(id, err) + } + + r.setReaderAt(rd) + + default: + return statusFromError(id, errors.New("bad file flags")) + } + + return &sshFxpHandlePacket{ + ID: id, + Handle: r.handle, + } +} + +func (r *Request) opendir(h Handlers, pkt requestPacket) responsePacket { + r.Method = "List" + la, err := h.FileList.Filelist(r) + if err != nil { + return statusFromError(pkt.id(), wrapPathError(r.Filepath, err)) + } + + r.setListerAt(la) + + return &sshFxpHandlePacket{ + ID: pkt.id(), + Handle: r.handle, + } +} + +// wrap FileReader handler +func fileget(h FileReader, r *Request, pkt requestPacket, alloc *allocator, orderID uint32, maxTxPacket uint32) responsePacket { + rd := r.getReaderAt() + if rd == nil { + return statusFromError(pkt.id(), errors.New("unexpected read packet")) + } + + data, offset, _ := packetData(pkt, alloc, orderID, maxTxPacket) + + n, err := rd.ReadAt(data, offset) + // only return EOF error if no data left to read + if err != nil && (err != io.EOF || n == 0) { + return statusFromError(pkt.id(), err) + } + + return &sshFxpDataPacket{ + ID: pkt.id(), + Length: uint32(n), + Data: data[:n], + } +} + +// wrap FileWriter handler +func fileput(h FileWriter, r *Request, pkt requestPacket, alloc *allocator, orderID uint32, maxTxPacket uint32) responsePacket { + wr := r.getWriterAt() + if wr == nil { + return statusFromError(pkt.id(), errors.New("unexpected write packet")) + } + + data, offset, _ := packetData(pkt, alloc, orderID, maxTxPacket) + + _, err := wr.WriteAt(data, offset) + return statusFromError(pkt.id(), err) +} + +// wrap OpenFileWriter handler +func fileputget(h FileWriter, r *Request, pkt requestPacket, alloc *allocator, orderID uint32, maxTxPacket uint32) responsePacket { + rw := r.getWriterAtReaderAt() + if rw == nil { + return statusFromError(pkt.id(), errors.New("unexpected write and read packet")) + } + + switch p := pkt.(type) { + case *sshFxpReadPacket: + data, offset := p.getDataSlice(alloc, orderID, maxTxPacket), int64(p.Offset) + + n, err := rw.ReadAt(data, offset) + // only return EOF error if no data left to read + if err != nil && (err != io.EOF || n == 0) { + return statusFromError(pkt.id(), err) + } + + return &sshFxpDataPacket{ + ID: pkt.id(), + Length: uint32(n), + Data: data[:n], + } + + case *sshFxpWritePacket: + data, offset := p.Data, int64(p.Offset) + + _, err := rw.WriteAt(data, offset) + return statusFromError(pkt.id(), err) + + default: + return statusFromError(pkt.id(), errors.New("unexpected packet type for read or write")) + } +} + +// file data for additional read/write packets +func packetData(p requestPacket, alloc *allocator, orderID uint32, maxTxPacket uint32) (data []byte, offset int64, length uint32) { + switch p := p.(type) { + case *sshFxpReadPacket: + return p.getDataSlice(alloc, orderID, maxTxPacket), int64(p.Offset), p.Len + case *sshFxpWritePacket: + return p.Data, int64(p.Offset), p.Length + } + return +} + +// wrap FileCmder handler +func filecmd(h FileCmder, r *Request, pkt requestPacket) responsePacket { + switch p := pkt.(type) { + case *sshFxpFsetstatPacket: + r.Flags = p.Flags + r.Attrs = p.Attrs.([]byte) + } + + switch r.Method { + case "PosixRename": + if posixRenamer, ok := h.(PosixRenameFileCmder); ok { + err := posixRenamer.PosixRename(r) + return statusFromError(pkt.id(), err) + } + + // PosixRenameFileCmder not implemented handle this request as a Rename + r.Method = "Rename" + err := h.Filecmd(r) + return statusFromError(pkt.id(), err) + + case "StatVFS": + if statVFSCmdr, ok := h.(StatVFSFileCmder); ok { + stat, err := statVFSCmdr.StatVFS(r) + if err != nil { + return statusFromError(pkt.id(), err) + } + stat.ID = pkt.id() + return stat + } + + return statusFromError(pkt.id(), ErrSSHFxOpUnsupported) + } + + err := h.Filecmd(r) + return statusFromError(pkt.id(), err) +} + +// wrap FileLister handler +func filelist(h FileLister, r *Request, pkt requestPacket) responsePacket { + lister := r.getListerAt() + if lister == nil { + return statusFromError(pkt.id(), errors.New("unexpected dir packet")) + } + + offset := r.lsNext() + finfo := make([]os.FileInfo, MaxFilelist) + n, err := lister.ListAt(finfo, offset) + r.lsInc(int64(n)) + // ignore EOF as we only return it when there are no results + finfo = finfo[:n] // avoid need for nil tests below + + switch r.Method { + case "List": + if err != nil && (err != io.EOF || n == 0) { + return statusFromError(pkt.id(), err) + } + + nameAttrs := make([]*sshFxpNameAttr, 0, len(finfo)) + + // If the type conversion fails, we get untyped `nil`, + // which is handled by not looking up any names. + idLookup, _ := h.(NameLookupFileLister) + + for _, fi := range finfo { + nameAttrs = append(nameAttrs, &sshFxpNameAttr{ + Name: fi.Name(), + LongName: runLs(idLookup, fi), + Attrs: []any{fi}, + }) + } + + return &sshFxpNamePacket{ + ID: pkt.id(), + NameAttrs: nameAttrs, + } + + default: + err = fmt.Errorf("unexpected method: %s", r.Method) + return statusFromError(pkt.id(), err) + } +} + +func filestat(h FileLister, r *Request, pkt requestPacket) responsePacket { + var lister ListerAt + var err error + + if r.Method == "Lstat" { + if lstatFileLister, ok := h.(LstatFileLister); ok { + lister, err = lstatFileLister.Lstat(r) + } else { + // LstatFileLister not implemented handle this request as a Stat + r.Method = "Stat" + lister, err = h.Filelist(r) + } + } else { + lister, err = h.Filelist(r) + } + if err != nil { + return statusFromError(pkt.id(), err) + } + finfo := make([]os.FileInfo, 1) + n, err := lister.ListAt(finfo, 0) + finfo = finfo[:n] // avoid need for nil tests below + + switch r.Method { + case "Stat", "Lstat": + if err != nil && err != io.EOF { + return statusFromError(pkt.id(), err) + } + if n == 0 { + err = &os.PathError{ + Op: strings.ToLower(r.Method), + Path: r.Filepath, + Err: syscall.ENOENT, + } + return statusFromError(pkt.id(), err) + } + return &sshFxpStatResponse{ + ID: pkt.id(), + info: finfo[0], + } + case "Readlink": + if err != nil && err != io.EOF { + return statusFromError(pkt.id(), err) + } + if n == 0 { + err = &os.PathError{ + Op: "readlink", + Path: r.Filepath, + Err: syscall.ENOENT, + } + return statusFromError(pkt.id(), err) + } + filename := finfo[0].Name() + return &sshFxpNamePacket{ + ID: pkt.id(), + NameAttrs: []*sshFxpNameAttr{ + { + Name: filename, + LongName: filename, + Attrs: emptyFileStat, + }, + }, + } + default: + err = fmt.Errorf("unexpected method: %s", r.Method) + return statusFromError(pkt.id(), err) + } +} + +func readlink(readlinkFileLister ReadlinkFileLister, r *Request, pkt requestPacket) responsePacket { + resolved, err := readlinkFileLister.Readlink(r.Filepath) + if err != nil { + return statusFromError(pkt.id(), err) + } + return &sshFxpNamePacket{ + ID: pkt.id(), + NameAttrs: []*sshFxpNameAttr{ + { + Name: resolved, + LongName: resolved, + Attrs: emptyFileStat, + }, + }, + } +} + +// init attributes of request object from packet data +func requestMethod(p requestPacket) (method string) { + switch p.(type) { + case *sshFxpReadPacket, *sshFxpWritePacket, *sshFxpOpenPacket: + // set in open() above + case *sshFxpOpendirPacket, *sshFxpReaddirPacket: + // set in opendir() above + case *sshFxpSetstatPacket, *sshFxpFsetstatPacket: + method = "Setstat" + case *sshFxpRenamePacket: + method = "Rename" + case *sshFxpSymlinkPacket: + method = "Symlink" + case *sshFxpRemovePacket: + method = "Remove" + case *sshFxpStatPacket, *sshFxpFstatPacket: + method = "Stat" + case *sshFxpLstatPacket: + method = "Lstat" + case *sshFxpRmdirPacket: + method = "Rmdir" + case *sshFxpReadlinkPacket: + method = "Readlink" + case *sshFxpMkdirPacket: + method = "Mkdir" + case *sshFxpExtendedPacketHardlink: + method = "Link" + } + return method +} diff --git a/vendor/github.com/pkg/sftp/request_windows.go b/vendor/github.com/pkg/sftp/request_windows.go new file mode 100644 index 00000000..172a941e --- /dev/null +++ b/vendor/github.com/pkg/sftp/request_windows.go @@ -0,0 +1,13 @@ +package sftp + +import ( + "syscall" +) + +func fakeFileInfoSys() any { + return syscall.Win32FileAttributeData{} +} + +func testOsSys(sys any) error { + return nil +} diff --git a/vendor/github.com/pkg/sftp/server.go b/vendor/github.com/pkg/sftp/server.go new file mode 100644 index 00000000..c3d3364b --- /dev/null +++ b/vendor/github.com/pkg/sftp/server.go @@ -0,0 +1,659 @@ +package sftp + +// sftp server counterpart + +import ( + "encoding" + "errors" + "fmt" + "io" + "io/fs" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "sync" + "syscall" + "time" +) + +const ( + // SftpServerWorkerCount defines the number of workers for the SFTP server + SftpServerWorkerCount = 8 +) + +type file interface { + Stat() (os.FileInfo, error) + ReadAt(b []byte, off int64) (int, error) + WriteAt(b []byte, off int64) (int, error) + Readdir(int) ([]os.FileInfo, error) + Name() string + Truncate(int64) error + Chmod(mode fs.FileMode) error + Chown(uid, gid int) error + Close() error +} + +// Server is an SSH File Transfer Protocol (sftp) server. +// This is intended to provide the sftp subsystem to an ssh server daemon. +// This implementation currently supports most of sftp server protocol version 3, +// as specified at https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt +type Server struct { + *serverConn + debugStream io.Writer + readOnly bool + pktMgr *packetManager + openFiles map[string]file + openFilesLock sync.RWMutex + handleCount int + workDir string + winRoot bool + maxTxPacket uint32 +} + +func (svr *Server) nextHandle(f file) string { + svr.openFilesLock.Lock() + defer svr.openFilesLock.Unlock() + svr.handleCount++ + handle := strconv.Itoa(svr.handleCount) + svr.openFiles[handle] = f + return handle +} + +func (svr *Server) closeHandle(handle string) error { + svr.openFilesLock.Lock() + defer svr.openFilesLock.Unlock() + if f, ok := svr.openFiles[handle]; ok { + delete(svr.openFiles, handle) + return f.Close() + } + + return EBADF +} + +func (svr *Server) getHandle(handle string) (file, bool) { + svr.openFilesLock.RLock() + defer svr.openFilesLock.RUnlock() + f, ok := svr.openFiles[handle] + return f, ok +} + +type serverRespondablePacket interface { + encoding.BinaryUnmarshaler + id() uint32 + respond(svr *Server) responsePacket +} + +// NewServer creates a new Server instance around the provided streams, serving +// content from the root of the filesystem. Optionally, ServerOption +// functions may be specified to further configure the Server. +// +// A subsequent call to Serve() is required to begin serving files over SFTP. +func NewServer(rwc io.ReadWriteCloser, options ...ServerOption) (*Server, error) { + svrConn := &serverConn{ + conn: conn{ + Reader: rwc, + WriteCloser: rwc, + }, + } + s := &Server{ + serverConn: svrConn, + debugStream: ioutil.Discard, + pktMgr: newPktMgr(svrConn), + openFiles: make(map[string]file), + maxTxPacket: defaultMaxTxPacket, + } + + for _, o := range options { + if err := o(s); err != nil { + return nil, err + } + } + + return s, nil +} + +// A ServerOption is a function which applies configuration to a Server. +type ServerOption func(*Server) error + +// WithDebug enables Server debugging output to the supplied io.Writer. +func WithDebug(w io.Writer) ServerOption { + return func(s *Server) error { + s.debugStream = w + return nil + } +} + +// ReadOnly configures a Server to serve files in read-only mode. +func ReadOnly() ServerOption { + return func(s *Server) error { + s.readOnly = true + return nil + } +} + +// WindowsRootEnumeratesDrives configures a Server to serve a virtual '/' for windows that lists all drives +func WindowsRootEnumeratesDrives() ServerOption { + return func(s *Server) error { + s.winRoot = true + return nil + } +} + +// WithAllocator enable the allocator. +// After processing a packet we keep in memory the allocated slices +// and we reuse them for new packets. +// The allocator is experimental +func WithAllocator() ServerOption { + return func(s *Server) error { + alloc := newAllocator() + s.pktMgr.alloc = alloc + s.conn.alloc = alloc + return nil + } +} + +// WithServerWorkingDirectory sets a working directory to use as base +// for relative paths. +// If unset the default is current working directory (os.Getwd). +func WithServerWorkingDirectory(workDir string) ServerOption { + return func(s *Server) error { + s.workDir = cleanPath(workDir) + return nil + } +} + +// WithMaxTxPacket sets the maximum size of the payload returned to the client, +// measured in bytes. The default value is 32768 bytes, and this option +// can only be used to increase it. Setting this option to a larger value +// should be safe, because the client decides the size of the requested payload. +// +// The default maximum packet size is 32768 bytes. +func WithMaxTxPacket(size uint32) ServerOption { + return func(s *Server) error { + if size < defaultMaxTxPacket { + return errors.New("size must be greater than or equal to 32768") + } + + s.maxTxPacket = size + + return nil + } +} + +type rxPacket struct { + pktType fxp + pktBytes []byte +} + +// Up to N parallel servers +func (svr *Server) sftpServerWorker(pktChan chan orderedRequest) error { + for pkt := range pktChan { + // readonly checks + readonly := true + switch pkt := pkt.requestPacket.(type) { + case notReadOnly: + readonly = false + case *sshFxpOpenPacket: + readonly = pkt.readonly() + case *sshFxpExtendedPacket: + readonly = pkt.readonly() + } + + // If server is operating read-only and a write operation is requested, + // return permission denied + if !readonly && svr.readOnly { + svr.pktMgr.readyPacket( + svr.pktMgr.newOrderedResponse(statusFromError(pkt.id(), syscall.EPERM), pkt.orderID()), + ) + continue + } + + if err := handlePacket(svr, pkt); err != nil { + return err + } + } + return nil +} + +func handlePacket(s *Server, p orderedRequest) error { + var rpkt responsePacket + orderID := p.orderID() + switch p := p.requestPacket.(type) { + case *sshFxInitPacket: + rpkt = &sshFxVersionPacket{ + Version: sftpProtocolVersion, + Extensions: sftpExtensions, + } + case *sshFxpStatPacket: + // stat the requested file + info, err := os.Stat(s.toLocalPath(p.Path)) + rpkt = &sshFxpStatResponse{ + ID: p.ID, + info: info, + } + if err != nil { + rpkt = statusFromError(p.ID, err) + } + case *sshFxpLstatPacket: + // stat the requested file + info, err := s.lstat(s.toLocalPath(p.Path)) + rpkt = &sshFxpStatResponse{ + ID: p.ID, + info: info, + } + if err != nil { + rpkt = statusFromError(p.ID, err) + } + case *sshFxpFstatPacket: + f, ok := s.getHandle(p.Handle) + var err error = EBADF + var info os.FileInfo + if ok { + info, err = f.Stat() + rpkt = &sshFxpStatResponse{ + ID: p.ID, + info: info, + } + } + if err != nil { + rpkt = statusFromError(p.ID, err) + } + case *sshFxpMkdirPacket: + // TODO FIXME: ignore flags field + err := os.Mkdir(s.toLocalPath(p.Path), 0o755) + rpkt = statusFromError(p.ID, err) + case *sshFxpRmdirPacket: + err := os.Remove(s.toLocalPath(p.Path)) + rpkt = statusFromError(p.ID, err) + case *sshFxpRemovePacket: + err := os.Remove(s.toLocalPath(p.Filename)) + rpkt = statusFromError(p.ID, err) + case *sshFxpRenamePacket: + err := os.Rename(s.toLocalPath(p.Oldpath), s.toLocalPath(p.Newpath)) + rpkt = statusFromError(p.ID, err) + case *sshFxpSymlinkPacket: + err := os.Symlink(s.toLocalPath(p.Targetpath), s.toLocalPath(p.Linkpath)) + rpkt = statusFromError(p.ID, err) + case *sshFxpClosePacket: + rpkt = statusFromError(p.ID, s.closeHandle(p.Handle)) + case *sshFxpReadlinkPacket: + f, err := os.Readlink(s.toLocalPath(p.Path)) + rpkt = &sshFxpNamePacket{ + ID: p.ID, + NameAttrs: []*sshFxpNameAttr{ + { + Name: f, + LongName: f, + Attrs: emptyFileStat, + }, + }, + } + if err != nil { + rpkt = statusFromError(p.ID, err) + } + case *sshFxpRealpathPacket: + f, err := filepath.Abs(s.toLocalPath(p.Path)) + f = cleanPath(f) + rpkt = &sshFxpNamePacket{ + ID: p.ID, + NameAttrs: []*sshFxpNameAttr{ + { + Name: f, + LongName: f, + Attrs: emptyFileStat, + }, + }, + } + if err != nil { + rpkt = statusFromError(p.ID, err) + } + case *sshFxpOpendirPacket: + lp := s.toLocalPath(p.Path) + + if stat, err := s.stat(lp); err != nil { + rpkt = statusFromError(p.ID, err) + } else if !stat.IsDir() { + rpkt = statusFromError(p.ID, &os.PathError{ + Path: lp, Err: syscall.ENOTDIR, + }) + } else { + rpkt = (&sshFxpOpenPacket{ + ID: p.ID, + Path: p.Path, + Pflags: sshFxfRead, + }).respond(s) + } + case *sshFxpReadPacket: + var err error = EBADF + f, ok := s.getHandle(p.Handle) + if ok { + err = nil + data := p.getDataSlice(s.pktMgr.alloc, orderID, s.maxTxPacket) + n, _err := f.ReadAt(data, int64(p.Offset)) + if _err != nil && (_err != io.EOF || n == 0) { + err = _err + } + rpkt = &sshFxpDataPacket{ + ID: p.ID, + Length: uint32(n), + Data: data[:n], + // do not use data[:n:n] here to clamp the capacity, we allocated extra capacity above to avoid reallocations + } + } + if err != nil { + rpkt = statusFromError(p.ID, err) + } + + case *sshFxpWritePacket: + f, ok := s.getHandle(p.Handle) + var err error = EBADF + if ok { + _, err = f.WriteAt(p.Data, int64(p.Offset)) + } + rpkt = statusFromError(p.ID, err) + case *sshFxpExtendedPacket: + if p.SpecificPacket == nil { + rpkt = statusFromError(p.ID, ErrSSHFxOpUnsupported) + } else { + rpkt = p.respond(s) + } + case serverRespondablePacket: + rpkt = p.respond(s) + default: + return fmt.Errorf("unexpected packet type %T", p) + } + + s.pktMgr.readyPacket(s.pktMgr.newOrderedResponse(rpkt, orderID)) + return nil +} + +// Serve serves SFTP connections until the streams stop or the SFTP subsystem +// is stopped. It returns nil if the server exits cleanly. +func (svr *Server) Serve() error { + defer func() { + if svr.pktMgr.alloc != nil { + svr.pktMgr.alloc.Free() + } + }() + var wg sync.WaitGroup + runWorker := func(ch chan orderedRequest) { + wg.Add(1) + go func() { + defer wg.Done() + if err := svr.sftpServerWorker(ch); err != nil { + svr.conn.Close() // shuts down recvPacket + } + }() + } + pktChan := svr.pktMgr.workerChan(runWorker) + + var err error + var pkt requestPacket + var pktType fxp + var pktBytes []byte +recvLoop: + for { + pktType, pktBytes, err = svr.serverConn.recvPacket(svr.pktMgr.getNextOrderID()) + if err != nil { + // Check whether the connection terminated cleanly in-between packets. + if err == io.EOF { + err = nil + } + // we don't care about releasing allocated pages here, the server will quit and the allocator freed + break + } + + pkt, err = makePacket(rxPacket{pktType, pktBytes}) + if err != nil { + switch { + case errors.Is(err, errUnknownExtendedPacket): + //if err := svr.serverConn.sendError(pkt, ErrSshFxOpUnsupported); err != nil { + // debug("failed to send err packet: %v", err) + // svr.conn.Close() // shuts down recvPacket + // break + //} + default: + debug("makePacket err: %v", err) + svr.conn.Close() // shuts down recvPacket + break recvLoop + } + } + + pktChan <- svr.pktMgr.newOrderedRequest(pkt) + } + + close(pktChan) // shuts down sftpServerWorkers + wg.Wait() // wait for all workers to exit + + // close any still-open files + for handle, file := range svr.openFiles { + fmt.Fprintf(svr.debugStream, "sftp server file with handle %q left open: %v\n", handle, file.Name()) + file.Close() + } + return err // error from recvPacket +} + +type ider interface { + id() uint32 +} + +// The init packet has no ID, so we just return a zero-value ID +func (p *sshFxInitPacket) id() uint32 { return 0 } + +type sshFxpStatResponse struct { + ID uint32 + info os.FileInfo +} + +func (p *sshFxpStatResponse) marshalPacket() ([]byte, []byte, error) { + l := 4 + 1 + 4 // uint32(length) + byte(type) + uint32(id) + + b := make([]byte, 4, l) + b = append(b, sshFxpAttrs) + b = marshalUint32(b, p.ID) + + var payload []byte + payload = marshalFileInfo(payload, p.info) + + return b, payload, nil +} + +func (p *sshFxpStatResponse) MarshalBinary() ([]byte, error) { + header, payload, err := p.marshalPacket() + return append(header, payload...), err +} + +var emptyFileStat = []any{uint32(0)} + +func (p *sshFxpOpenPacket) readonly() bool { + // SSH_FXF_CREAT and SSH_FXF_TRUNC modify the filesystem even without SSH_FXF_WRITE. + return p.Pflags&(sshFxfWrite|sshFxfCreat|sshFxfTrunc) == 0 +} + +func (p *sshFxpOpenPacket) hasPflags(flags ...uint32) bool { + for _, f := range flags { + if p.Pflags&f == 0 { + return false + } + } + return true +} + +func (p *sshFxpOpenPacket) respond(svr *Server) responsePacket { + var osFlags int + if p.hasPflags(sshFxfRead, sshFxfWrite) { + osFlags |= os.O_RDWR + } else if p.hasPflags(sshFxfWrite) { + osFlags |= os.O_WRONLY + } else if p.hasPflags(sshFxfRead) { + osFlags |= os.O_RDONLY + } else { + // how are they opening? + return statusFromError(p.ID, syscall.EINVAL) + } + + // Don't use O_APPEND flag as it conflicts with WriteAt. + // The sshFxfAppend flag is a no-op here as the client sends the offsets. + + if p.hasPflags(sshFxfCreat) { + osFlags |= os.O_CREATE + } + if p.hasPflags(sshFxfTrunc) { + osFlags |= os.O_TRUNC + } + if p.hasPflags(sshFxfExcl) { + osFlags |= os.O_EXCL + } + + mode := os.FileMode(0o644) + // Like OpenSSH, we only handle permissions here, and only when the file is being created. + // Otherwise, the permissions are ignored. + if p.Flags&sshFileXferAttrPermissions != 0 { + fs, err := p.unmarshalFileStat(p.Flags) + if err != nil { + return statusFromError(p.ID, err) + } + mode = fs.FileMode() & os.ModePerm + } + + f, err := svr.openfile(svr.toLocalPath(p.Path), osFlags, mode) + if err != nil { + return statusFromError(p.ID, err) + } + + handle := svr.nextHandle(f) + return &sshFxpHandlePacket{ID: p.ID, Handle: handle} +} + +func (p *sshFxpReaddirPacket) respond(svr *Server) responsePacket { + f, ok := svr.getHandle(p.Handle) + if !ok { + return statusFromError(p.ID, EBADF) + } + + dirents, err := f.Readdir(128) + if err != nil { + return statusFromError(p.ID, err) + } + + idLookup := osIDLookup{} + + ret := &sshFxpNamePacket{ID: p.ID} + for _, dirent := range dirents { + ret.NameAttrs = append(ret.NameAttrs, &sshFxpNameAttr{ + Name: dirent.Name(), + LongName: runLs(idLookup, dirent), + Attrs: []any{dirent}, + }) + } + return ret +} + +func (p *sshFxpSetstatPacket) respond(svr *Server) responsePacket { + path := svr.toLocalPath(p.Path) + + debug("setstat name %q", path) + + fs, err := p.unmarshalFileStat(p.Flags) + + if err == nil && (p.Flags&sshFileXferAttrSize) != 0 { + err = os.Truncate(path, int64(fs.Size)) + } + if err == nil && (p.Flags&sshFileXferAttrPermissions) != 0 { + err = os.Chmod(path, fs.FileMode()) + } + if err == nil && (p.Flags&sshFileXferAttrUIDGID) != 0 { + err = os.Chown(path, int(fs.UID), int(fs.GID)) + } + if err == nil && (p.Flags&sshFileXferAttrACmodTime) != 0 { + err = os.Chtimes(path, fs.AccessTime(), fs.ModTime()) + } + + return statusFromError(p.ID, err) +} + +func (p *sshFxpFsetstatPacket) respond(svr *Server) responsePacket { + f, ok := svr.getHandle(p.Handle) + if !ok { + return statusFromError(p.ID, EBADF) + } + + path := f.Name() + + debug("fsetstat name %q", path) + + fs, err := p.unmarshalFileStat(p.Flags) + + if err == nil && (p.Flags&sshFileXferAttrSize) != 0 { + err = f.Truncate(int64(fs.Size)) + } + if err == nil && (p.Flags&sshFileXferAttrPermissions) != 0 { + err = f.Chmod(fs.FileMode()) + } + if err == nil && (p.Flags&sshFileXferAttrUIDGID) != 0 { + err = f.Chown(int(fs.UID), int(fs.GID)) + } + if err == nil && (p.Flags&sshFileXferAttrACmodTime) != 0 { + type chtimer interface { + Chtimes(atime, mtime time.Time) error + } + + switch f := any(f).(type) { + case chtimer: + // future-compatible, for when/if *os.File supports Chtimes. + err = f.Chtimes(fs.AccessTime(), fs.ModTime()) + default: + err = os.Chtimes(path, fs.AccessTime(), fs.ModTime()) + } + } + + return statusFromError(p.ID, err) +} + +func statusFromError(id uint32, err error) *sshFxpStatusPacket { + ret := &sshFxpStatusPacket{ + ID: id, + StatusError: StatusError{ + // sshFXOk = 0 + // sshFXEOF = 1 + // sshFXNoSuchFile = 2 ENOENT + // sshFXPermissionDenied = 3 + // sshFXFailure = 4 + // sshFXBadMessage = 5 + // sshFXNoConnection = 6 + // sshFXConnectionLost = 7 + // sshFXOPUnsupported = 8 + Code: sshFxOk, + }, + } + if err == nil { + return ret + } + + debug("statusFromError: error is %T %#v", err, err) + ret.StatusError.Code = sshFxFailure + ret.StatusError.msg = err.Error() + + if os.IsNotExist(err) { + ret.StatusError.Code = sshFxNoSuchFile + return ret + } + if code, ok := translateSyscallError(err); ok { + ret.StatusError.Code = code + return ret + } + + if errors.Is(err, io.EOF) { + ret.StatusError.Code = sshFxEOF + return ret + } + + var e fxerr + if errors.As(err, &e) { + ret.StatusError.Code = uint32(e) + return ret + } + + return ret +} diff --git a/vendor/github.com/pkg/sftp/server_plan9.go b/vendor/github.com/pkg/sftp/server_plan9.go new file mode 100644 index 00000000..4e8ed067 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_plan9.go @@ -0,0 +1,27 @@ +package sftp + +import ( + "path" + "path/filepath" +) + +func (s *Server) toLocalPath(p string) string { + if s.workDir != "" && !path.IsAbs(p) { + p = path.Join(s.workDir, p) + } + + lp := filepath.FromSlash(p) + + if path.IsAbs(p) { + tmp := lp[1:] + + if filepath.IsAbs(tmp) { + // If the FromSlash without any starting slashes is absolute, + // then we have a filepath encoded with a prefix '/'. + // e.g. "/#s/boot" to "#s/boot" + return tmp + } + } + + return lp +} diff --git a/vendor/github.com/pkg/sftp/server_posix.go b/vendor/github.com/pkg/sftp/server_posix.go new file mode 100644 index 00000000..c07d70a0 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_posix.go @@ -0,0 +1,21 @@ +//go:build !windows +// +build !windows + +package sftp + +import ( + "io/fs" + "os" +) + +func (s *Server) openfile(path string, flag int, mode fs.FileMode) (file, error) { + return os.OpenFile(path, flag, mode) +} + +func (s *Server) lstat(name string) (os.FileInfo, error) { + return os.Lstat(name) +} + +func (s *Server) stat(name string) (os.FileInfo, error) { + return os.Stat(name) +} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_darwin.go b/vendor/github.com/pkg/sftp/server_statvfs_darwin.go new file mode 100644 index 00000000..8c01dac5 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_statvfs_darwin.go @@ -0,0 +1,21 @@ +package sftp + +import ( + "syscall" +) + +func statvfsFromStatfst(stat *syscall.Statfs_t) (*StatVFS, error) { + return &StatVFS{ + Bsize: uint64(stat.Bsize), + Frsize: uint64(stat.Bsize), // fragment size is a linux thing; use block size here + Blocks: stat.Blocks, + Bfree: stat.Bfree, + Bavail: stat.Bavail, + Files: stat.Files, + Ffree: stat.Ffree, + Favail: stat.Ffree, // not sure how to calculate Favail + Fsid: uint64(uint64(stat.Fsid.Val[1])<<32 | uint64(stat.Fsid.Val[0])), // endianness? + Flag: uint64(stat.Flags), // assuming POSIX? + Namemax: 1024, // man 2 statfs shows: #define MAXPATHLEN 1024 + }, nil +} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_impl.go b/vendor/github.com/pkg/sftp/server_statvfs_impl.go new file mode 100644 index 00000000..a5470798 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_statvfs_impl.go @@ -0,0 +1,30 @@ +//go:build darwin || linux +// +build darwin linux + +// fill in statvfs structure with OS specific values +// Statfs_t is different per-kernel, and only exists on some unixes (not Solaris for instance) + +package sftp + +import ( + "syscall" +) + +func (p *sshFxpExtendedPacketStatVFS) respond(svr *Server) responsePacket { + retPkt, err := getStatVFSForPath(p.Path) + if err != nil { + return statusFromError(p.ID, err) + } + retPkt.ID = p.ID + + return retPkt +} + +func getStatVFSForPath(name string) (*StatVFS, error) { + var stat syscall.Statfs_t + if err := syscall.Statfs(name, &stat); err != nil { + return nil, err + } + + return statvfsFromStatfst(&stat) +} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_linux.go b/vendor/github.com/pkg/sftp/server_statvfs_linux.go new file mode 100644 index 00000000..615c4157 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_statvfs_linux.go @@ -0,0 +1,23 @@ +//go:build linux +// +build linux + +package sftp + +import ( + "syscall" +) + +func statvfsFromStatfst(stat *syscall.Statfs_t) (*StatVFS, error) { + return &StatVFS{ + Bsize: uint64(stat.Bsize), + Frsize: uint64(stat.Frsize), + Blocks: stat.Blocks, + Bfree: stat.Bfree, + Bavail: stat.Bavail, + Files: stat.Files, + Ffree: stat.Ffree, + Favail: stat.Ffree, // not sure how to calculate Favail + Flag: uint64(stat.Flags), // assuming POSIX? + Namemax: uint64(stat.Namelen), + }, nil +} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_plan9.go b/vendor/github.com/pkg/sftp/server_statvfs_plan9.go new file mode 100644 index 00000000..e71a27d3 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_statvfs_plan9.go @@ -0,0 +1,13 @@ +package sftp + +import ( + "syscall" +) + +func (p *sshFxpExtendedPacketStatVFS) respond(svr *Server) responsePacket { + return statusFromError(p.ID, syscall.EPLAN9) +} + +func getStatVFSForPath(name string) (*StatVFS, error) { + return nil, syscall.EPLAN9 +} diff --git a/vendor/github.com/pkg/sftp/server_statvfs_stubs.go b/vendor/github.com/pkg/sftp/server_statvfs_stubs.go new file mode 100644 index 00000000..dd4705bb --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_statvfs_stubs.go @@ -0,0 +1,16 @@ +//go:build !darwin && !linux && !plan9 +// +build !darwin,!linux,!plan9 + +package sftp + +import ( + "syscall" +) + +func (p *sshFxpExtendedPacketStatVFS) respond(svr *Server) responsePacket { + return statusFromError(p.ID, syscall.ENOTSUP) +} + +func getStatVFSForPath(name string) (*StatVFS, error) { + return nil, syscall.ENOTSUP +} diff --git a/vendor/github.com/pkg/sftp/server_unix.go b/vendor/github.com/pkg/sftp/server_unix.go new file mode 100644 index 00000000..495b397c --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_unix.go @@ -0,0 +1,16 @@ +//go:build !windows && !plan9 +// +build !windows,!plan9 + +package sftp + +import ( + "path" +) + +func (s *Server) toLocalPath(p string) string { + if s.workDir != "" && !path.IsAbs(p) { + p = path.Join(s.workDir, p) + } + + return p +} diff --git a/vendor/github.com/pkg/sftp/server_windows.go b/vendor/github.com/pkg/sftp/server_windows.go new file mode 100644 index 00000000..e1462039 --- /dev/null +++ b/vendor/github.com/pkg/sftp/server_windows.go @@ -0,0 +1,193 @@ +package sftp + +import ( + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "time" + + "golang.org/x/sys/windows" +) + +func (s *Server) toLocalPath(p string) string { + if s.workDir != "" && !path.IsAbs(p) { + p = path.Join(s.workDir, p) + } + + lp := filepath.FromSlash(p) + + if path.IsAbs(p) { // starts with '/' + if len(p) == 1 && s.winRoot { + return `\\.\` // for openfile + } + + tmp := lp + for len(tmp) > 0 && tmp[0] == '\\' { + tmp = tmp[1:] + } + + if filepath.IsAbs(tmp) { + // If the FromSlash without any starting slashes is absolute, + // then we have a filepath encoded with a prefix '/'. + // e.g. "/C:/Windows" to "C:\\Windows" + return tmp + } + + tmp += "\\" + + if filepath.IsAbs(tmp) { + // If the FromSlash without any starting slashes but with extra end slash is absolute, + // then we have a filepath encoded with a prefix '/' and a dropped '/' at the end. + // e.g. "/C:" to "C:\\" + return tmp + } + + if s.winRoot { + // Make it so that "/Windows" is not found, and "/c:/Windows" has to be used + return `\\.\` + tmp + } + } + + return lp +} + +func bitsToDrives(bitmap uint32) []string { + var drive rune = 'a' + var drives []string + + for bitmap != 0 && drive <= 'z' { + if bitmap&1 == 1 { + drives = append(drives, string(drive)+":") + } + drive++ + bitmap >>= 1 + } + + return drives +} + +func getDrives() ([]string, error) { + mask, err := windows.GetLogicalDrives() + if err != nil { + return nil, fmt.Errorf("GetLogicalDrives: %w", err) + } + return bitsToDrives(mask), nil +} + +type driveInfo struct { + fs.FileInfo + name string +} + +func (i *driveInfo) Name() string { + return i.name // since the Name() returned from a os.Stat("C:\\") is "\\" +} + +type winRoot struct { + drives []string +} + +func newWinRoot() (*winRoot, error) { + drives, err := getDrives() + if err != nil { + return nil, err + } + return &winRoot{ + drives: drives, + }, nil +} + +func (f *winRoot) Readdir(n int) ([]os.FileInfo, error) { + drives := f.drives + if n > 0 && len(drives) > n { + drives = drives[:n] + } + f.drives = f.drives[len(drives):] + if len(drives) == 0 { + return nil, io.EOF + } + + var infos []os.FileInfo + for _, drive := range drives { + fi, err := os.Stat(drive + `\`) + if err != nil { + return nil, err + } + + di := &driveInfo{ + FileInfo: fi, + name: drive, + } + infos = append(infos, di) + } + + return infos, nil +} + +func (f *winRoot) Stat() (os.FileInfo, error) { + return rootFileInfo, nil +} +func (f *winRoot) ReadAt(b []byte, off int64) (int, error) { + return 0, os.ErrPermission +} +func (f *winRoot) WriteAt(b []byte, off int64) (int, error) { + return 0, os.ErrPermission +} +func (f *winRoot) Name() string { + return "/" +} +func (f *winRoot) Truncate(int64) error { + return os.ErrPermission +} +func (f *winRoot) Chmod(mode fs.FileMode) error { + return os.ErrPermission +} +func (f *winRoot) Chown(uid, gid int) error { + return os.ErrPermission +} +func (f *winRoot) Close() error { + f.drives = nil + return nil +} + +func (s *Server) openfile(path string, flag int, mode fs.FileMode) (file, error) { + if path == `\\.\` && s.winRoot { + return newWinRoot() + } + return os.OpenFile(path, flag, mode) +} + +type winRootFileInfo struct { + name string + modTime time.Time +} + +func (w *winRootFileInfo) Name() string { return w.name } +func (w *winRootFileInfo) Size() int64 { return 0 } +func (w *winRootFileInfo) Mode() fs.FileMode { return fs.ModeDir | 0555 } // read+execute for all +func (w *winRootFileInfo) ModTime() time.Time { return w.modTime } +func (w *winRootFileInfo) IsDir() bool { return true } +func (w *winRootFileInfo) Sys() any { return nil } + +// Create a new root FileInfo +var rootFileInfo = &winRootFileInfo{ + name: "/", + modTime: time.Now(), +} + +func (s *Server) lstat(name string) (os.FileInfo, error) { + if name == `\\.\` && s.winRoot { + return rootFileInfo, nil + } + return os.Lstat(name) +} + +func (s *Server) stat(name string) (os.FileInfo, error) { + if name == `\\.\` && s.winRoot { + return rootFileInfo, nil + } + return os.Stat(name) +} diff --git a/vendor/github.com/pkg/sftp/sftp.go b/vendor/github.com/pkg/sftp/sftp.go new file mode 100644 index 00000000..1e698bb2 --- /dev/null +++ b/vendor/github.com/pkg/sftp/sftp.go @@ -0,0 +1,258 @@ +// Package sftp implements the SSH File Transfer Protocol as described in +// https://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt +package sftp + +import ( + "fmt" +) + +const ( + sshFxpInit = 1 + sshFxpVersion = 2 + sshFxpOpen = 3 + sshFxpClose = 4 + sshFxpRead = 5 + sshFxpWrite = 6 + sshFxpLstat = 7 + sshFxpFstat = 8 + sshFxpSetstat = 9 + sshFxpFsetstat = 10 + sshFxpOpendir = 11 + sshFxpReaddir = 12 + sshFxpRemove = 13 + sshFxpMkdir = 14 + sshFxpRmdir = 15 + sshFxpRealpath = 16 + sshFxpStat = 17 + sshFxpRename = 18 + sshFxpReadlink = 19 + sshFxpSymlink = 20 + sshFxpStatus = 101 + sshFxpHandle = 102 + sshFxpData = 103 + sshFxpName = 104 + sshFxpAttrs = 105 + sshFxpExtended = 200 + sshFxpExtendedReply = 201 +) + +const ( + sshFxOk = 0 + sshFxEOF = 1 + sshFxNoSuchFile = 2 + sshFxPermissionDenied = 3 + sshFxFailure = 4 + sshFxBadMessage = 5 + sshFxNoConnection = 6 + sshFxConnectionLost = 7 + sshFxOPUnsupported = 8 + + // see draft-ietf-secsh-filexfer-13 + // https://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.1 + sshFxInvalidHandle = 9 + sshFxNoSuchPath = 10 + sshFxFileAlreadyExists = 11 + sshFxWriteProtect = 12 + sshFxNoMedia = 13 + sshFxNoSpaceOnFilesystem = 14 + sshFxQuotaExceeded = 15 + sshFxUnknownPrincipal = 16 + sshFxLockConflict = 17 + sshFxDirNotEmpty = 18 + sshFxNotADirectory = 19 + sshFxInvalidFilename = 20 + sshFxLinkLoop = 21 + sshFxCannotDelete = 22 + sshFxInvalidParameter = 23 + sshFxFileIsADirectory = 24 + sshFxByteRangeLockConflict = 25 + sshFxByteRangeLockRefused = 26 + sshFxDeletePending = 27 + sshFxFileCorrupt = 28 + sshFxOwnerInvalid = 29 + sshFxGroupInvalid = 30 + sshFxNoMatchingByteRangeLock = 31 +) + +const ( + sshFxfRead = 0x00000001 + sshFxfWrite = 0x00000002 + sshFxfAppend = 0x00000004 + sshFxfCreat = 0x00000008 + sshFxfTrunc = 0x00000010 + sshFxfExcl = 0x00000020 +) + +var ( + // supportedSFTPExtensions defines the supported extensions + supportedSFTPExtensions = []sshExtensionPair{ + {"hardlink@openssh.com", "1"}, + {"posix-rename@openssh.com", "1"}, + {"statvfs@openssh.com", "2"}, + } + sftpExtensions = supportedSFTPExtensions +) + +type fxp uint8 + +func (f fxp) String() string { + switch f { + case sshFxpInit: + return "SSH_FXP_INIT" + case sshFxpVersion: + return "SSH_FXP_VERSION" + case sshFxpOpen: + return "SSH_FXP_OPEN" + case sshFxpClose: + return "SSH_FXP_CLOSE" + case sshFxpRead: + return "SSH_FXP_READ" + case sshFxpWrite: + return "SSH_FXP_WRITE" + case sshFxpLstat: + return "SSH_FXP_LSTAT" + case sshFxpFstat: + return "SSH_FXP_FSTAT" + case sshFxpSetstat: + return "SSH_FXP_SETSTAT" + case sshFxpFsetstat: + return "SSH_FXP_FSETSTAT" + case sshFxpOpendir: + return "SSH_FXP_OPENDIR" + case sshFxpReaddir: + return "SSH_FXP_READDIR" + case sshFxpRemove: + return "SSH_FXP_REMOVE" + case sshFxpMkdir: + return "SSH_FXP_MKDIR" + case sshFxpRmdir: + return "SSH_FXP_RMDIR" + case sshFxpRealpath: + return "SSH_FXP_REALPATH" + case sshFxpStat: + return "SSH_FXP_STAT" + case sshFxpRename: + return "SSH_FXP_RENAME" + case sshFxpReadlink: + return "SSH_FXP_READLINK" + case sshFxpSymlink: + return "SSH_FXP_SYMLINK" + case sshFxpStatus: + return "SSH_FXP_STATUS" + case sshFxpHandle: + return "SSH_FXP_HANDLE" + case sshFxpData: + return "SSH_FXP_DATA" + case sshFxpName: + return "SSH_FXP_NAME" + case sshFxpAttrs: + return "SSH_FXP_ATTRS" + case sshFxpExtended: + return "SSH_FXP_EXTENDED" + case sshFxpExtendedReply: + return "SSH_FXP_EXTENDED_REPLY" + default: + return "unknown" + } +} + +type fx uint8 + +func (f fx) String() string { + switch f { + case sshFxOk: + return "SSH_FX_OK" + case sshFxEOF: + return "SSH_FX_EOF" + case sshFxNoSuchFile: + return "SSH_FX_NO_SUCH_FILE" + case sshFxPermissionDenied: + return "SSH_FX_PERMISSION_DENIED" + case sshFxFailure: + return "SSH_FX_FAILURE" + case sshFxBadMessage: + return "SSH_FX_BAD_MESSAGE" + case sshFxNoConnection: + return "SSH_FX_NO_CONNECTION" + case sshFxConnectionLost: + return "SSH_FX_CONNECTION_LOST" + case sshFxOPUnsupported: + return "SSH_FX_OP_UNSUPPORTED" + default: + return "unknown" + } +} + +type unexpectedPacketErr struct { + want, got fxp +} + +func (u *unexpectedPacketErr) Error() string { + return fmt.Sprintf("sftp: unexpected packet: want %v, got %v", u.want, u.got) +} + +func unimplementedPacketErr(u fxp) error { + return fmt.Errorf("sftp: unimplemented packet type: got %v", u) +} + +type unexpectedIDErr struct{ want, got uint32 } + +func (u *unexpectedIDErr) Error() string { + return fmt.Sprintf("sftp: unexpected id: want %d, got %d", u.want, u.got) +} + +func unimplementedSeekWhence(whence int) error { + return fmt.Errorf("sftp: unimplemented seek whence %d", whence) +} + +func unexpectedCount(want, got uint32) error { + return fmt.Errorf("sftp: unexpected count: want %d, got %d", want, got) +} + +type unexpectedVersionErr struct{ want, got uint32 } + +func (u *unexpectedVersionErr) Error() string { + return fmt.Sprintf("sftp: unexpected server version: want %v, got %v", u.want, u.got) +} + +// A StatusError is returned when an SFTP operation fails, and provides +// additional information about the failure. +type StatusError struct { + Code uint32 + msg, lang string +} + +func (s *StatusError) Error() string { + return fmt.Sprintf("sftp: %q (%v)", s.msg, fx(s.Code)) +} + +// FxCode returns the error code typed to match against the exported codes +func (s *StatusError) FxCode() fxerr { + return fxerr(s.Code) +} + +func getSupportedExtensionByName(extensionName string) (sshExtensionPair, error) { + for _, supportedExtension := range supportedSFTPExtensions { + if supportedExtension.Name == extensionName { + return supportedExtension, nil + } + } + return sshExtensionPair{}, fmt.Errorf("unsupported extension: %s", extensionName) +} + +// SetSFTPExtensions allows to customize the supported server extensions. +// See the variable supportedSFTPExtensions for supported extensions. +// This method accepts a slice of sshExtensionPair names for example 'hardlink@openssh.com'. +// If an invalid extension is given an error will be returned and nothing will be changed +func SetSFTPExtensions(extensions ...string) error { + tempExtensions := []sshExtensionPair{} + for _, extension := range extensions { + sftpExtension, err := getSupportedExtensionByName(extension) + if err != nil { + return err + } + tempExtensions = append(tempExtensions, sftpExtension) + } + sftpExtensions = tempExtensions + return nil +} diff --git a/vendor/github.com/pkg/sftp/stat.go b/vendor/github.com/pkg/sftp/stat.go new file mode 100644 index 00000000..2bb2c137 --- /dev/null +++ b/vendor/github.com/pkg/sftp/stat.go @@ -0,0 +1,94 @@ +package sftp + +import ( + "os" + + sshfx "github.com/pkg/sftp/internal/encoding/ssh/filexfer" +) + +// isRegular returns true if the mode describes a regular file. +func isRegular(mode uint32) bool { + return sshfx.FileMode(mode)&sshfx.ModeType == sshfx.ModeRegular +} + +// toFileMode converts sftp filemode bits to the os.FileMode specification +func toFileMode(mode uint32) os.FileMode { + var fm = os.FileMode(mode & 0777) + + switch sshfx.FileMode(mode) & sshfx.ModeType { + case sshfx.ModeDevice: + fm |= os.ModeDevice + case sshfx.ModeCharDevice: + fm |= os.ModeDevice | os.ModeCharDevice + case sshfx.ModeDir: + fm |= os.ModeDir + case sshfx.ModeNamedPipe: + fm |= os.ModeNamedPipe + case sshfx.ModeSymlink: + fm |= os.ModeSymlink + case sshfx.ModeRegular: + // nothing to do + case sshfx.ModeSocket: + fm |= os.ModeSocket + } + + if sshfx.FileMode(mode)&sshfx.ModeSetUID != 0 { + fm |= os.ModeSetuid + } + if sshfx.FileMode(mode)&sshfx.ModeSetGID != 0 { + fm |= os.ModeSetgid + } + if sshfx.FileMode(mode)&sshfx.ModeSticky != 0 { + fm |= os.ModeSticky + } + + return fm +} + +// fromFileMode converts from the os.FileMode specification to sftp filemode bits +func fromFileMode(mode os.FileMode) uint32 { + ret := sshfx.FileMode(mode & os.ModePerm) + + switch mode & os.ModeType { + case os.ModeDevice | os.ModeCharDevice: + ret |= sshfx.ModeCharDevice + case os.ModeDevice: + ret |= sshfx.ModeDevice + case os.ModeDir: + ret |= sshfx.ModeDir + case os.ModeNamedPipe: + ret |= sshfx.ModeNamedPipe + case os.ModeSymlink: + ret |= sshfx.ModeSymlink + case 0: + ret |= sshfx.ModeRegular + case os.ModeSocket: + ret |= sshfx.ModeSocket + } + + if mode&os.ModeSetuid != 0 { + ret |= sshfx.ModeSetUID + } + if mode&os.ModeSetgid != 0 { + ret |= sshfx.ModeSetGID + } + if mode&os.ModeSticky != 0 { + ret |= sshfx.ModeSticky + } + + return uint32(ret) +} + +const ( + s_ISUID = uint32(sshfx.ModeSetUID) + s_ISGID = uint32(sshfx.ModeSetGID) + s_ISVTX = uint32(sshfx.ModeSticky) +) + +// S_IFMT is a legacy export, and was brought in to support GOOS environments whose sysconfig.S_IFMT may be different from the value used internally by SFTP standards. +// There should be no reason why you need to import it, or use it, but unexporting it could cause code to break in a way that cannot be readily fixed. +// As such, we continue to export this value as the value used in the SFTP standard. +// +// Deprecated: Remove use of this value, and avoid any future use as well. +// There is no alternative provided, you should never need to access this value. +const S_IFMT = uint32(sshfx.ModeType) diff --git a/vendor/modules.txt b/vendor/modules.txt index 847fb9be..94b815b0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,14 @@ # github.com/inconshreveable/mousetrap v1.1.0 ## explicit; go 1.18 github.com/inconshreveable/mousetrap +# github.com/kr/fs v0.1.0 +## explicit +github.com/kr/fs +# github.com/pkg/sftp v1.13.12 +## explicit; go 1.25.0 +github.com/pkg/sftp +github.com/pkg/sftp/internal/encoding/ssh/filexfer +github.com/pkg/sftp/internal/encoding/ssh/filexfer/openssh # github.com/spf13/cobra v1.10.2 ## explicit; go 1.15 github.com/spf13/cobra