Skip to content

fix(git): GitHub clones trust GitHub's published host keys through OpenSSH, so junk known_hosts lines and a failed key scan no longer skip pinning #1114

Closed

Description

@dan-petty

Problem

Lines cited at dcafadf.
At 132ecc5, config/constants.py lines :2168-2355 moved down 1 and lines from :2356 on moved down 34 (:2296-2299 is :2297-2300, :2505 is :2539, :2512-2518 is :2546-2552, and the host-key block :2799-2830 is :2833-2864); every other cited file is unchanged.

Before devops repos clone (commands/repos.py:283) clones a GitHub SSH URL, clone_repo (git/operations.py:195-199) calls _prepare_clone_url (:187-192), which calls _ensure_known_host (:126-167). That function decides whether to pin GitHub's host key in ~/.ssh/known_hosts. To decide, it reimplements OpenSSH's known_hosts file format in Python. To get the key, it runs ssh-keyscan and fingerprints the output by hand. #364 (for #322) replaced ssh-keygen -F with this parser to save a process spawn. OpenSSH already checks known_hosts when it connects. The parser only decides whether the pinned key is written first.

Hand-rolled code:

  • crypto/known_hosts.py (272 lines) reimplements the format sshd(8) describes:
    • hashed |1| entries, by recomputing HMAC-SHA1 (:83-101);
    • */? patterns compiled to regexes (:116-128);
    • ! negation (:75-81);
    • [host]:port spellings (:104-113);
    • markers (:49-57, :149-151);
    • a line parser (:141-182).
  • crypto/host_keys.py (163 lines) parses ssh-keyscan output and computes SHA256 fingerprints by hand. It compares them with three pinned fingerprints (config/constants.py:2823-2829).
  • git/operations.py:90-105 runs ssh-keyscan -t ed25519 and accepts the output after a substring test (hostname not in result.stdout, :100).
  • git/operations.py:190 decides whether to pin at all with a case-sensitive startswith on two prefixes (git@github.com: and ssh://git@github.com/, constants.py:500-501).

Confirmed defects. The parser was compared offline with ssh-keygen -F on 30 cases (OpenSSH 10.5p1), and the parser rows below were re-run at dcafadf:

  • Fail-open on junk lines. For each of these lines, the parser reports github.com as already trusted. OpenSSH never uses any of them to trust GitHub's plain host key:
    • @cert-authority github.com … or @cert-authority * …. CA lines vouch only for certificates, and GitHub serves plain keys.
    • An unknown marker, such as @foo github.com ….
    • A truncated key (github.com ssh-ed25519 AAAA) or a key that does not decode as base64.
    • An unknown key type, or ssh-dss (OpenSSH 10 removed DSA).
  • What that does end to end. The flow was run through _ensure_known_host with the subprocess mocked. In each of those cases, ssh-keyscan is never called and GitHub's verified key is never written. git clone then falls back to the user's StrictHostKeyChecking setting. Under the default ask, that means a trust-on-first-use prompt. Under accept-new, an unverified key is accepted silently. This is feat(cli): cryptography pure-python asymmetric key management & hardware token authentication research #322's defect again, through another path. The control case, an @revoked line, does write the key.
  • Silent scan failure. If ssh-keyscan fails, _ensure_known_host returns and the clone goes ahead (operations.py:145-147). test_a_failed_scan_writes_nothing (tests/test_ssh_host_keys.py:520) pins this behaviour.
  • Spellings that skip pinning (the prefix test at :190): git@GitHub.com:, ssh://git@github.com:22/, ssh://GIT@GITHUB.COM/, ssh://github.com/, git+ssh://git@github.com/…, scp-like github.com:org/repo, org-123@github.com:, and ssh-config aliases such as gh-work:org/repo.
  • Dead code.
    • The allow_unverified branch (:127, :149-162) has no production caller. The only call is at :191, with defaults.
    • CONST_GITHUB_META_URL (constants.py:2830) is unused.
    • The comment at constants.py:2822 points to a devops git host-keys command that does not exist.
  • Raw clone errors. commands/repos.py:283 does not catch the GitCommandError that Repo.clone_from raises (operations.py:199), so a failed clone, a host-key failure included, surfaces as a raw GitPython exception.
  • Stale docs. docs/KNOWN_ISSUES.md:29-31 and :52 still describe trust on first use through ssh-keyscan, which fix(git): verify SSH host keys before trusting them (#322) #364 removed.

Acceptance criteria

  • Pinned lines. config/constants.py holds CONST_GITHUB_KNOWN_HOSTS_LINES: Final[tuple[str, ...]], GitHub's three published known_hosts lines, in place of the block at :2799-2830: github.com ssh-ed25519 …, github.com ecdsa-sha2-nistp256 … and github.com ssh-rsa ….

    • A comment cites the source: https://api.github.com/meta (.ssh_keys) and GitHub's docs page "GitHub's SSH key fingerprints", which publishes these lines for known_hosts.
    • Measured: the three keys that gh api meta --jq .ssh_keys serves today have the fingerprints pinned at :2825-2827.
    • Structure test. Each line is split once on the first space (str.partition(" ")). The host field must be github.com. The rest, <type> <base64>, is loaded with cryptography's load_ssh_public_key, and public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH) must equal it byte for byte. The host field is split off first because load_ssh_public_key rejects a full known_hosts line (Unsupported key type: b'github.com'). cryptography 50.0.1 is already a direct dependency.
    • The structure test catches structural damage only. Measured with cryptography 50.0.1: truncated and non-base64 key data raise ValueError; an unknown key type raises UnsupportedAlgorithm, which subclasses Exception, not ValueError; a well-formed ssh-dss key still loads, with a CryptographyDeprecationWarning. One changed base64 character inside the key material of the ed25519 or RSA key still loads and round-trips byte for byte, because the test re-encodes whatever bytes it is given.
    • Fingerprint test. For each pinned key, the test computes its SHA256 fingerprint with serialization.ssh_key_fingerprint(key, hashes.SHA256()) (present in cryptography 50.0.1), encodes it with base64.b64encode without the = padding, and compares it with GitHub's published fingerprints. Those three fingerprints are test-only data, copied from the "GitHub's SSH key fingerprints" docs page (also served as .ssh_key_fingerprints by https://api.github.com/meta). That source is independent of the key lines, so a copy error in a pinned key fails the gate. Measured: ssh_key_fingerprint reproduces all three published fingerprints from the keys served today.
  • Write. clone_repo makes sure each pinned line is in ~/.ssh/known_hosts and appends any that are missing.

    • Lines are compared whole and verbatim, with pathlib/os only.
    • The directory is created with mode 0700 and the file is 0600.
    • The comparison only stops devops-cli from writing its own lines twice. devops-cli itself does no host, pattern, hash or marker matching.
    • The write runs once per process (functools.cache on the helper; tests call its cache_clear()), so clone-org reads the file once and logs at most one warning.
    • Tests check that:
      • the lines are written with modes 0600 and 0700;
      • a second run adds nothing;
      • a file without a trailing newline is not corrupted;
      • an unwritable directory logs one warning, and the clone continues;
      • no subprocess is spawned.
  • Regression test for the fail-open. Start from a known_hosts file holding any one of these lines:

    • @cert-authority github.com … or @cert-authority * …;
    • @foo github.com …;
    • a truncated key, or a key that does not decode;
    • an ssh-dss line;
    • @revoked github.com <other key>;
    • a hashed |1|… github.com entry.

    The test checks that the existing line is kept byte for byte and that the pinned lines are still appended.

  • Every spelling. The write runs for every URL passed to clone_repo, with no URL test. A parametrised test covers each spelling listed under Problem. devops repos clone-org (commands/repos.py:134) passes HTTPS URLs and also gets the write (see "Write unconditionally" below for the cost).

  • Errors. clone_repo wraps every GitCommandError from Repo.clone_from in a GitOperationError whose message carries git's stderr (GitCommandError.stderr) passed through mask_secrets (security/sanitizer.py:269). commands/repos.py:283 reports it with the existing exit_on_error(GitOperationError) (core/cli.py:187-200), which prints the message without a traceback.

    • No string matching: ssh writes its own host-key message to that stderr, and git passes it through. For a changed key, which is how an interceptor's key for github.com appears once the pinned lines are present, that message names the host and the offending known_hosts file and line. A host-key-specific hint would need a substring test on stderr, because neither tool exposes a structured host-key status: ssh exits 255 for every failure, and git reports 128 for all of them.
    • clone-org's existing except Exception (commands/repos.py:136-137) still prints fail <repo>: … for each repository.
    • Tests, with a stubbed GitCommandError, check that:
      • stderr holding ssh's "Host key for github.com has changed and you have requested strict checking." and "Host key verification failed." reaches the GitOperationError message;
      • a credential in a URL in that stderr (for example https://user:<token>@example.com/o/r.git) is masked;
      • devops repos clone exits non-zero with the message and no traceback.
  • No construct left.

  • Out of scope. _normalize_clone_url (operations.py:53-62) and CONST_GITHUB_SSH_PREFIX / CONST_GITHUB_SSH_URL_PREFIX stay as they are. They belong to a later git-remote-URL item that is not yet filed.

  • Tests.

    • tests/test_ssh_host_keys.py: delete :61-456 (parsing, membership, append, fingerprint, keyscan and verification). Rewrite the integration block at :458-614 as the tests above.
    • tests/test_git_operations.py: update :74-99, :102-110, :279-282 and :285-312, plus parts 1, 2, 3 and 5 of :315-381. Part 4 (_validate_clone_dest) stays.
    • Unaffected: tests/test_review_page_line_numbers.py and tests/golden/review_findings.json. They use "known_hosts.py" only as a label.
  • Docs.

    • docs/KNOWN_ISSUES.md:29-31 and :52 describe the pinned lines and OpenSSH's own check.
    • A changelog.d fragment: Security (junk known_hosts lines no longer skip pinning, and a failed scan no longer skips it silently), Changed (a failed clone reports git's and ssh's message instead of a raw exception, and HTTPS clones also write the pinned lines) and Removed (the in-process parser and the ssh-keyscan call).
  • Gate. Tests run offline with no ssh binary and no network. The suite shrinks by the deleted parser tests. uv run devops ci passes.

  • Pending a person: with an empty ~/.ssh and OpenSSH's default StrictHostKeyChecking ask, devops repos clone git@github.com:<org>/<repo>.git clones with no host-key prompt. It does the same with an @cert-authority github.com … line already in ~/.ssh/known_hosts.

Key questions

  • What replaces the parser and ssh-keyscan? Proposed: GitHub's documented method. Add its published known_hosts lines to ~/.ssh/known_hosts and let OpenSSH handle hashing, patterns, negation, ports, @revoked and @cert-authority.
    • No new dependency is needed. OpenSSH is already required, because git's SSH transport uses it, and the full key lines remove the need to fingerprint anything at run time.
    • Rejected: asyncssh 2.24.0. Its licence is EPL-2.0 OR GPL-2.0-or-later, against this MIT project, and it would keep a trust decision inside the devops-cli process.
    • Rejected: paramiko 5.0.0's HostKeyEntry.from_line. It has no marker handling and reads @revoked as a host name.
  • Write to ~/.ssh/known_hosts, or to a file devops-cli manages? Decided (owner, 2026-10-03): the standard ~/.ssh/known_hosts, the file today's code already writes. It works with core.sshCommand, ssh-config aliases, fetch_all and pull_tracking (operations.py:202-221), and manual git commands.
    • Rejected: a managed file. Checked offline with a stub ssh, the variant that sets GIT_SSH_COMMAND with UserKnownHostsFile=<managed> and StrictHostKeyChecking=yes regresses in four ways:
      • The environment variable overrides the user's core.sshCommand; the user's -i key was never used.
      • UserKnownHostsFile=<managed> on its own stops ssh from reading ~/.ssh/known_hosts and known_hosts2, so the user's @revoked lines stop applying.
      • With StrictHostKeyChecking=yes, every non-GitHub SSH clone fails.
      • Applied to the clone alone, fetch_all and pull_tracking lose GitHub's key. fetch_all swallows GitCommandError (:208-209), so its fetches fail silently. Persisting core.sshCommand at clone time needs GitPython's allow_unsafe_options=True.
  • Why not go back to ssh-keygen -F? Proposed: keep no lookup at all. ssh-keygen -F exits 0 when the file holds only an @revoked, @cert-authority or truncated line. Using its exit status would be looser than today's @revoked handling.
  • Write unconditionally, or parse the URL first? Proposed: unconditionally, in clone_repo. It is three lines that are never written twice, and it needs no URL parsing. The deferred git-remote-URL work (giturlparse needs owner approval) therefore does not block this item.
    • Cost: HTTPS-only clones, every repository in clone-org included, now create ~/.ssh (0700) and add the three lines to known_hosts. In the devcontainer, ~/.ssh is the host's own directory, bind-mounted at .devcontainer/devcontainer.json:40 (docs/KNOWN_ISSUES.md item 5), so the lines land in the host's file, as today's SSH clones already do.
    • Cost: when ~/.ssh is not writable (for example a host directory bind-mounted read-only), every run that clones logs the new warning. The once-per-process write keeps that to one warning per clone-org run.
    • Accepted: the lines are GitHub's own, are what GitHub's docs tell users to add, and never change a decision for another host.
  • Is the new behaviour ever looser than today's? Proposed: in one case, accepted. It follows from the decided standard file: only the rejected managed-file variant forces StrictHostKeyChecking=yes for GitHub.
    • Stricter: junk lines, a failed scan, and no network.
    • Equal: @revoked lines, hashed files, and a key the user accepted earlier for github.com. ssh trusts any matching line, so that key stays trusted, as it does today. Removing it would need host matching again.
    • Looser: the first clone under interception, for a user whose ssh does not enforce ~/.ssh/known_hosts. Today the scan's fingerprint check fails, _verified_host_key raises GitOperationError (operations.py:120-123, called at :164), and the clone aborts before git runs. After this change:
      • With StrictHostKeyChecking=no, the pinned lines make the interceptor's key a changed key. ssh_config(5) lets such a connection go ahead "subject to some restrictions", and those restrictions leave public-key authentication working, so the clone proceeds.
      • With UserKnownHostsFile pointed elsewhere (in ssh_config or core.sshCommand), ssh never reads the pinned lines and treats the key as new: accept-new takes it silently and ask prompts.
    • Accepted, because in both cases the user turned off or redirected ssh's host-key checking, and every other path is stricter or equal. Keeping today's abort would mean keeping ssh-keyscan and the fingerprinting that this item deletes.
  • What about ssh.github.com on port 443? Proposed: out of scope. Today's code never pins it either. OpenSSH looks it up as [ssh.github.com]:443, and the pinned lines name github.com only, so the user's ssh decides, as today.
  • Strings or key objects for the constant? Proposed: strings, because they are written verbatim. The structure test checks their shape, and the fingerprint test against GitHub's published fingerprints checks their content.
  • Key rotation? Proposed: as today, edit one constant and the fingerprints in its test; the last rotation was RSA, in March 2023. Lines written earlier stay in the file. A key GitHub withdraws can be added as an @revoked github.com <key> line, which OpenSSH enforces.

Strategic alignment

Update 2026-10-08: refinement

#1332 plans tests for crypto/known_hosts.py and tests/test_ssh_host_keys.py, and #1333 fakes ssh-keyscan (git/operations.py:91-93). This item deletes both; whichever lands second drops those targets.

Activity

  1. added
    type/security
    scope/security
    scope/cli
    priority/p2-medium
    on Oct 3, 2026
  2. added this to the v0.2.32 milestone on Oct 8, 2026
  3. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Placed in v0.2.32 on 2026-10-08 at the owner's request ("Populate 10 security and ci issues into each v0.2.30, v0.2.31, and v0.2.32 milestone"). This is a person's placement. Release theme: URLs and host keys read by the library that dials, ollama hardening, and pull-request test-quality tooling. Position 3 of 10 in the release's planned merge order. Its board Status is set to Ready, so the release-start fill keeps it.

  4. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Linked: #1399 and #900. Each wraps a GitCommandError from git/operations.py in a GitOperationError with git's stderr through mask_secrets; whichever lands later reuses the shape. Found by the 2026-10-08 backlog review.

  5. dan-petty-bot commented on Oct 9, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1510, merged into release/v0.2.32 as 0efe7c8.

    Resolves #1114

    10 file(s) changed.

    How it was verified

    Check runs at 0a878b3:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • Static Analysis: pass
    • Analyze (actions): pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-1114-github-ssh-host-keys.md:

    No Acceptance Criteria section.

  6. added a commit that references this issue on Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/cliscope/securitytype/security

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions