Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

**`reuse_connection` per-server option (default `true`).** Setting `reuse_connection = false` on a `[servers.*]` block makes every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server open a brand-new SSH connection and close it, waiting for the close, right after the operation — on success or error — without ever storing it in the connection pool. It governs only operations run on that host itself: a jump host used as a tunnel is still reached through the shared pool and stays cached (tunnels use direct-tcpip channels, not exec channels). This is needed for Windows OpenSSH hosts that run a `ForceCommand` wrapper: Windows OpenSSH hands every exec channel after the first on one connection the first channel's `SSH_ORIGINAL_COMMAND`, so with a cached connection every command after the first returned the first command's output. The key must be a TOML boolean; a non-boolean value is rejected at load. With the default `true`, behaviour is unchanged.

**`redact_output` setting (default `false`).** With `redact_output = true` in `[settings]`, `execute` and `execute_on_group` mask secrets in their final result string — stdout, stderr, the echoed command and error text, plus the text of any error the tool raises — before returning it, in a worker thread so a large output does not stall the event loop. Masked: PEM private keys (`[REDACTED PRIVATE KEY]`; an unterminated block from truncated output is masked up to the `[... output truncated at N bytes]` marker, the next blank line or an `Exit code:` line, so stderr, the exit line and later servers of a group result survive); `key=value` / `key: value` pairs for `password`, `passphrase`, `pwd`, `secret` (also `secret_key`, `secret_access_key`), `token`, `api_key`, `access_key` and `client_secret`, plus `pass` / `passwd` with `=` only (key names also match as the tail of a longer name such as `PGPASSWORD` or `dbPassword`; the key and separator are kept, and quoted values are masked through their closing quote, escape-aware); `Authorization:` headers and `Bearer` tokens; and the password of `scheme://user:pass@host` URLs (`scheme://user:[REDACTED]@host`; only the authority is parsed, so a port followed by a query-string e-mail is left alone). Logins, e-mail addresses, IP addresses and host names are left readable on purpose. The rules are heuristic and run in time linear in the output length (`src/ssh_mcp/redact.py`; deliberately not `ssh._redact_secrets`, which is superlinear). The key must be a TOML boolean; a non-boolean value is rejected at load. With the default `false`, behaviour is unchanged.

`redact_output` edge behaviour: a `pwd` / `PWD` value starting with `/` (`PWD=/home/x`, `OLDPWD=/tmp`) stays visible, so a password beginning with `/` after `pwd=` is not masked; `secret_key_base` is masked; an unquoted `Authorization:` value stops at a quote that closes nothing, so `curl -H "Authorization: Bearer x" https://host/` keeps its closing quote and the URL; a URL's authority ends at a quote or angle bracket; a URL whose login is a key word (`https://token:pw@host/x`) keeps its login and host; and a quoted value cut off right after a backslash is masked in full.

## [0.9.3] - 2026-12-01

> **Why 0.9.3 and not 0.10.0:** nothing here makes a configuration that started on 0.9.2 refuse to start. The runtime dependency changes are lockfile-only patches (`opentelemetry-api`, `pydantic`); the only new declared floor is a uv constraint, and the container image's interpreter move adds no configuration surface.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ max_command_bytes = 65536 # reject longer command strings at the tool bounda
connection_idle_timeout = 300 # seconds; eviction scan runs every 60s
known_hosts = true # false removes MITM protection
max_parallel_hosts = 10 # process-wide concurrency cap for group execution (1..100)
redact_output = false # true masks secrets in execute / execute_on_group results (default false)

[groups]
production = { description = "Production servers" }
Expand Down Expand Up @@ -351,6 +352,10 @@ Note two things about the timeouts, because the names invite confusion:

`max_parallel_hosts` bounds the whole process, not a single call: the semaphore is built once at startup, so concurrent `execute_on_group` calls share the same budget rather than each getting their own.

`redact_output` (boolean, default `false`) is opt-in output masking. With `redact_output = true`, `execute` and `execute_on_group` pass their final result — stdout, stderr, the echoed command and error text, plus the text of any error the tool raises — through a redactor before returning it: PEM private keys become `[REDACTED PRIVATE KEY]` (an unterminated block, from truncated output, is masked up to the truncation marker, the next blank line or an `Exit code:` line); `key=value` / `key: value` pairs whose key is `password`, `passphrase`, `pwd`, `secret` (also `secret_key`, `secret_access_key`), `token`, `api_key`, `access_key` or `client_secret` keep the key and separator and have the value replaced by `[REDACTED]`, and `pass` / `passwd` do the same with `=` only (so `/etc/passwd:` lines are left alone); keys match as the tail of a longer name too (`PGPASSWORD`, `dbPassword`, `"accessToken"`), so a harmless name ending in one (`bypass=1`) is masked as well; quoted values are masked through the closing quote (escape-aware), which covers connection strings like `Password=x;`; `Authorization:` headers and `Bearer` tokens are masked; and the password of `scheme://user:pass@host` URLs is replaced (`scheme://user:[REDACTED]@host`, the user stays). Logins, e-mail addresses, IP addresses and host names are deliberately left readable so output stays diagnosable. The rules are heuristic — a secret printed with no key name is not recognised — and run in linear time, off the event loop. `upload_file` and `download_file` return only a confirmation message, so they are unaffected.

Edge behaviour of `redact_output`: a `pwd` / `PWD` value that starts with `/` (`PWD=/home/x`, `OLDPWD=/tmp` in `env` output) is the working directory and stays visible, so a password beginning with `/` after `pwd=` is not masked; `secret_key_base` is masked; an unquoted `Authorization:` value stops at a quote that closes nothing (`curl -H "Authorization: Bearer x" https://host/` keeps its closing quote and the URL); and a URL's authority ends at a quote or angle bracket, so `["http://host:8080","[email protected]"]` is not read as credentials.

Per-server overrides (`hostname`, `port`, `user`, `identity_file`, `jump_host`, `default_dir`, `timeout`) take precedence over `~/.ssh/config`. See [config/servers.example.toml](https://github.com/blackaxgit/ssh-mcp/blob/main/config/servers.example.toml) for the annotated reference.

`reuse_connection` (boolean, default `true`) controls connection caching for one server. With `reuse_connection = false`, every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server opens a brand-new SSH connection and closes it as soon as the operation finishes (success or error); nothing is cached, so each call pays a full connect and handshake. The setting governs only operations run on that host itself: a jump host used as a tunnel is always reached through the shared connection pool and stays cached whatever its own `reuse_connection` says (tunnels use direct-tcpip channels, not exec channels, so the Windows issue below does not apply to them). Set it to `false` on **Windows hosts whose `sshd` uses a `ForceCommand` wrapper**: Windows OpenSSH gives every exec channel after the first on one SSH connection the *first* channel's `SSH_ORIGINAL_COMMAND`, so over a cached connection every command after the first would silently return the first command's output. Linux and MikroTik hosts are unaffected and should keep the default.
Expand Down
6 changes: 6 additions & 0 deletions config/servers.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ known_hosts = true
# exhaust file descriptors or trigger fleet-wide load spikes.
max_parallel_hosts = 10

# Opt-in: mask secrets (PEM private keys, password/token/api_key-style
# key=value pairs, Authorization/Bearer values, URL passwords) in everything
# execute / execute_on_group return. Logins, e-mails, IPs and host names stay
# readable. Heuristic, so it is not a substitute for keeping secrets off hosts.
# redact_output = true

# =============================================================================
# GROUP DEFINITIONS
# =============================================================================
Expand Down
13 changes: 13 additions & 0 deletions src/ssh_mcp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,18 @@ class Settings:
reaper closes them, so open descriptors can still exceed this
number. Bounded to 1..100 to keep fleet-wide load spikes and
descriptor growth in check.
redact_output: Mask secrets in everything the execute tools return
from remote hosts (default False, so output is returned verbatim).
When true, ``execute`` and ``execute_on_group`` run their final
result string — stdout, stderr, the echoed command and any error
text, including the text of a converted exception — through
``ssh_mcp.redact.redact_output`` (in a worker thread): PEM private
keys, ``key=value`` / ``key: value`` secrets (password, token,
api_key, ...), ``Authorization`` / ``Bearer`` credentials and the
password part of ``scheme://user:pass@host`` URLs. Logins, e-mail
addresses, IPs and host names are left alone. Heuristic: it
cannot recognise a secret that carries no key name. Must be a
TOML boolean.
"""

# ``validate_default=True`` is load-bearing on the path fields: pydantic
Expand All @@ -117,6 +129,7 @@ class Settings:
connection_idle_timeout: int = Field(default=300, ge=10)
known_hosts: bool = True
max_parallel_hosts: int = Field(default=10, ge=1, le=100)
redact_output: bool = Field(default=False, strict=True)

@field_validator("ssh_config_path", "transfer_root")
@classmethod
Expand Down
168 changes: 168 additions & 0 deletions src/ssh_mcp/redact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"""Opt-in masking of secrets in text returned from remote hosts.

Applied by the MCP tools to their final result string when
``Settings.redact_output`` is true (default false). This is deliberately
separate from ``ssh._redact_secrets``, which scrubs *commands* for logging and
is superlinear on large input; remote output can be up to
``max_output_bytes`` (10 MiB at most) per stream, so every pattern here must
run in time linear in the text length.

How linearity is kept (Python's ``re`` has no timeout, so this is by
construction, not by measurement alone):

* no nested quantifiers and no alternation whose branches can match the same
characters at the same position;
* every unbounded repetition is a negated character class that stops at a
delimiter the *next* part of the pattern needs, so a failed attempt re-scans
at most up to that delimiter, and attempts at later start positions begin
past it;
* the key names are plain literals, not preceded by a ``\\w*`` that every start
position would rescan.

Deliberately NOT masked, because they are needed to diagnose problems:
logins, e-mail addresses, IP addresses and host names. Only the secret part
of a URL's userinfo is masked, never the user.

Known limits: the rules are heuristic. A secret that carries no key name
(a bare token printed on its own line), or one split across the output
truncation marker, is not recognised. Key names match as the tail of a longer
name on purpose (``PGPASSWORD``, ``dbPassword``, ``REDISPASS``), so a
harmless name that merely ends in one of them (``bypass=1``) is masked too.
The exception is ``pwd``: ``PWD=/home/x`` and ``OLDPWD=/tmp`` (a value
starting with ``/``) stay visible, so a password that begins with ``/`` after
``pwd=`` is not masked.
"""

from __future__ import annotations

import re

_FLAGS = re.IGNORECASE

# The ``[... output truncated at N bytes]`` marker ssh.py appends after a cut
# stream. Secrets are masked up to it, never across it, so the reader can still
# see why the output stopped.
_TRUNCATION = r"\n\[\.\.\. output truncated at \d+ bytes\]"

# Rule 1: PEM private key, BEGIN line through the matching END line.
# An unterminated block (output truncated mid-key) is masked up to the first
# of: the truncation marker, a blank line, a line starting ``Exit code:`` or
# the end of the text — so stderr, the exit line and later servers of a group
# result survive. The legacy encrypted layout (``Proc-Type:`` / ``DEK-Info:``
# headers, then a blank line, then the body) is skipped over explicitly so
# that blank line does not end a complete block early.
_PEM_STOP = r"\n[ \t\r]*\n|\nExit code:|" + _TRUNCATION
_PEM = re.compile(
r"-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----"
r"(?:(?:\n(?:Proc-Type|DEK-Info):[^\n]*)+(?:\n[ \t\r]*\n)?)?"
r"[\s\S]*?"
r"(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY-----"
r"|(?=" + _PEM_STOP + r")"
r"|\Z)",
_FLAGS,
)

# A quoted string, escape-aware (``\"`` does not close it) and single-line.
# Masked through the closing quote; when the closing quote never comes because
# the stream was truncated, through to the truncation marker / end of text —
# including a lone trailing backslash cut off right before it. Any other
# unclosed quote does not match here and falls back to an unquoted run, so a
# stray quote cannot swallow the rest of the output.
_END_OF_STREAM = r"(?=" + _TRUNCATION + r"|\Z)"
_DQ = r'"[^"\\\n]*(?:\\.[^"\\\n]*)*(?:"|\\?' + _END_OF_STREAM + r")"
_SQ = r"'[^'\\\n]*(?:\\.[^'\\\n]*)*(?:'|\\?" + _END_OF_STREAM + r")"

# Rule 3a: ``Authorization: <scheme> <value>`` — the header name and separator
# stay, everything after them (a quoted string, else the rest of the line, so
# multi-field schemes such as Digest are covered) is masked. An unquoted value
# stops at a quote that closes nothing, so ``curl -H "Authorization: Bearer x"
# https://host/`` keeps its closing ``"`` and the URL; balanced double-quoted
# segments inside it (Digest's ``username="bob", response="ff"``) are part of
# the value.
_AUTHORIZATION = re.compile(
r"""(authorization["']?[ \t]*[:=][ \t]*)(?:"""
+ _DQ
+ "|"
+ _SQ
+ r"""|["']?[^\r\n"']+(?:"[^"\r\n]*"[^\r\n"']*)*)""",
_FLAGS,
)

# Rule 3b: a bare ``Bearer <token>`` outside any Authorization header.
_BEARER = re.compile(
r"(?<![A-Za-z0-9])(bearer[ \t]+)[A-Za-z0-9._~+/=-]+",
_FLAGS,
)

# Rule 4: the password in a URL's userinfo, ``scheme://user:pass@host``; the
# user stays. Only the authority is parsed — it ends at ``/``, ``?``, ``#`` or
# whitespace — so ``host:[email protected]`` (port, then a query-string
# e-mail) is never read as credentials. The password runs to the LAST ``@`` of
# the authority, so one containing a raw ``@`` is masked whole. A userinfo
# without a password (``ssh://git@host``) and a plain ``host:port`` authority
# do not match. Anchored on ``://`` rather than the scheme, so no start
# position has to scan a scheme-shaped run.
_URL_CREDENTIALS = re.compile(r"(://[^\s/?#@:\"'<>]*:)[^\s/?#\"'<>]*@")

# Rule 2: ``key=value`` / ``key: value`` (also JSON/YAML ``"key": "value"``).
# Key names match anywhere, including as the tail of a longer name, so
# ``PGPASSWORD``, ``dbPassword``, ``"accessToken"`` and ``SECRET_KEY`` are
# covered. ``pass`` and ``passwd`` are too common in ordinary logs and
# ``/etc/passwd`` lines to take a ``:`` separator, so they take only ``=``.
# There is no bare ``auth`` key (``auth: user=<bob>`` is a log line, not a
# secret); ``Authorization`` is rule 3. The value is a quoted string or a run
# of characters up to whitespace or one of ``,;&`` — which covers connection
# strings (``Password=x;``) and query strings (``?token=x&``).
_KEYS_ANY_SEPARATOR = (
r"password|passphrase|secret(?:[_-]?access)?(?:[_-]?key(?:[_-]?base)?)?"
r"|token|api[_-]?key|access[_-]?key|client[_-]?secret"
)
# ``pwd`` is the shell's working directory as often as it is a password
# (``PWD=/home/x``, ``OLDPWD=/tmp`` in ``env`` output), so a value that starts
# with ``/`` (optionally quoted) is left alone for it alone.
_SEPARATOR = r"[\"']?[ \t]*[=:]"
_KEY_VALUE = re.compile(
r"((?:(?:"
+ _KEYS_ANY_SEPARATOR
+ r")"
+ _SEPARATOR
+ r"|pwd"
+ _SEPARATOR
+ r"(?![ \t]*[\"']?/)"
+ r"|(?:passwd|pass)[\"']?[ \t]*=)[ \t]*)"
# A value that is already a masked URL password (``[REDACTED]@host``, from
# rule 4 running first) is skipped: ``https://token:pw@host/x`` must keep
# its host, not be erased by the ``token:`` key.
+ r"(?!\[REDACTED\]@)"
+ r"(?:"
+ _DQ
+ "|"
+ _SQ
+ r"|[^\s,;&]+)",
_FLAGS,
)


def redact_output(text: str) -> str:
"""Mask secrets in ``text`` and return the result.

Rules, applied in this order:

1. PEM private keys -> ``[REDACTED PRIVATE KEY]``.
2. ``Authorization: ...`` -> ``Authorization: [REDACTED]`` and
``Bearer <token>`` -> ``Bearer [REDACTED]``.
3. URL credentials ``scheme://user:pass@host`` ->
``scheme://user:[REDACTED]@host``.
4. ``key=value`` / ``key: value`` for password, passphrase, pwd, secret
(also ``secret_key`` / ``secret_access_key``), token, api_key,
access_key and client_secret, plus ``pass`` / ``passwd`` with ``=``
only (case-insensitive, also as the tail of a longer name) -> the key
and separator are kept, the value becomes ``[REDACTED]``.

Runs in time linear in ``len(text)`` and is idempotent.
"""
text = _PEM.sub("[REDACTED PRIVATE KEY]", text)
text = _AUTHORIZATION.sub(r"\1[REDACTED]", text)
text = _BEARER.sub(r"\1[REDACTED]", text)
text = _URL_CREDENTIALS.sub(r"\1[REDACTED]@", text)
return _KEY_VALUE.sub(r"\1[REDACTED]", text)
Loading