Skip to content

Validate embedded key type when loading OpenSSH private keys - #2697

Open
bhavyup wants to merge 2 commits into
paramiko:mainfrom
bhavyup:fix-openssh-keytype-validation
Open

bhavyup wants to merge 2 commits into
paramiko:mainfrom
bhavyup:fix-openssh-keytype-validation

Conversation

@bhavyup

@bhavyup bhavyup commented Oct 4, 2026

Copy link
Copy Markdown

Closes #2467.

When loading an OpenSSH-format private key (BEGIN OPENSSH PRIVATE KEY), PKey._read_private_key_openssh() extracted the key type embedded in the file but never validated it against the key class being loaded. A wrong-type key file would then mis-parse into garbage and fail later with a cryptic error (e.g. "unpack requires a buffer of 4 bytes") instead of failing fast with a clear message.

This adds the missing check: each key class declares its expected OpenSSH key type name(s) via _expected_openssh_keytypes, and the loader raises SSHException("encountered X key, expected Y key") on mismatch, thus mirroring the check _read_private_key already performs for PEM files.

Changes:

  • paramiko/pkey.py: new _expected_openssh_keytypes attribute (empty tuple disables the check) + validation in _read_private_key_openssh
  • paramiko/rsakey.py: declares ("ssh-rsa",)
  • paramiko/ecdsakey.py: declares the three ecdsa-sha2-nistp* types
  • tests/pkey.py: tests proving wrong-type files fail with the clear error, and right-type files still load fine

All 57 tests in tests/pkey.py pass.

@bskinn

bskinn commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Thank you for your interest in paramiko.

Per discussion with bitprophet, the paramiko project is operating under a blanket policy rejecting AI-generated contributions of all kinds. The text of all issue and PR descriptions, and all code in PRs, comment-suggestions, etc. must be human-written.

Direct attributions of AI authorship fall under the policy straightforwardly. In the absence of direct attribution, evaluation of AI authorship is ultimately a judgment call.

Closing this PR due to inferred AI authorship.

@bskinn bskinn closed this Nov 1, 2026
@bhavyup

bhavyup commented Nov 1, 2026

Copy link
Copy Markdown
Author

Sir ... already commented on the other one. I have only one thing to say, It was not an AI-written or commited PR. THANK YOU!

@bskinn

bskinn commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Reopening, cf. the first part of #2698 (comment).

This fix makes sense to me for what it directly solves; I'm not sure if it's a sufficiently general solution, though. Are you confident that it entirely fixes #2467/#2048, and doesn't break something broader in the machinery? (I'm not deeply familiar with how exhaustive the test suite is in terms of checking that keys pass or fail when they should.)

@bskinn bskinn reopened this Nov 1, 2026
@bhavyup

bhavyup commented Nov 2, 2026

Copy link
Copy Markdown
Author

Thanks for reopening this and for the follow-up question.

Direct answer: yes, this fixes the mechanism behind #2467, and that same mechanism is the core of #2048 as well (with one exception in #2048 that I will name below).

In #2467, the root cause was in _read_private_key_openssh. A wrong-type try that leaks a ValueError or produces a garbage key that fails later when signing, breaks that trial design.

This PR adds an expected-types list per class, checked after decryption and after the checkints match, but before returning the unpadded data. That turns a wrong guess into exactly the exception the trial loop is designed to catch.

I am not expecting this PR to close #2048 on its own for two reasons. First, this PR only references #2467 structurally. Second, #2048 contains a separate request: Schwaneberg's proposal for an enabled_algorithms whitelist for server algorithm negotiation. That is a feature request, not a client key-loading bug, and this PR does not address it. Additionally, since DSSKey was removed in main, the literal RSA-as-DSA path is already resolved; this PR locks down the remaining RSA and ECDSA pairs.

On broader breakage, the risk is narrow. PEM keys, public key parsing, cipher and KDF handling, checkints, and padding are untouched. Ed25519 is also unchanged. What changes is simply that wrong-type OpenSSH loads that previously leaked a ValueError or produced garbage now cleanly raise an SSHException.

Tests does not enumerate every single pair or test corrupt types except RSA rejected as ECDSA, ECDSA 384 rejected as RSA. Not that wrong, since the check happens before any numbers are decoded and only compares the string label.

There are two real edge cases I want to flag:

  1. Cert labels like [email protected] are not in any tuple, but in standard OpenSSH those are for public cert objects, not the embedded type in a private key file, making this theoretical for standard files.
  2. A corrupt, non-UTF-8 embedded type would raise UnicodeDecodeError, not SSHException, because the decode in the added code has no guard around it.

I can wrap that decode and add tests for the missing pairs as a follow-up commit if you would like.

@bhavyup

bhavyup commented Nov 2, 2026

Copy link
Copy Markdown
Author

Keeping this PR minimal on purpose, but thinking longer term about the trial loading design itself, here are some redesign options if you think any of them are worth a separate issue.

First, I should note what is not new here. The reporter in #2467 already asked why paramiko tries classes by trial instead of detecting the type, and jun66j5 in #2048 already proposed verifying the embedded type in pkey.py (which is what this PR does) or validating by signing after loading. The ideas below go beyond those two.

1. Detect from the public blob first, not from the private blob
This is my top pick for a follow up. OpenSSH private files include a plaintext public key section even when encrypted, which starts with the same type string. Right now, _read_private_key_openssh unpacks but ignores it, waiting until after decryption to check the type in the private section.
Checking the public blob first tells us the type without a password. This avoids running the heavy bcrypt KDF on wrong guesses and throws a clean type error instead of a password error. It also lets us compare public and private types to catch tampered files. I left it out here because parsing the public blob for all types is a larger feature, not a scoped bugfix.

2. Stop trial loading entirely and dispatch once from the detected type
PKey.from_path already detects types properly by parsing once via the cryptography library. If _auth used this instead of guessing, this entire bug class vanishes. I skipped this because it is a major behavioral change. Fixing it properly requires rewriting key subclasses to accept cryptography objects directly, which risks breaking custom subclasses and legacy formats.

3. Make the parser return a neutral, typed structure once
Right now each key class re parses the same binary blob in its own _decode_key with its own unpacking logic, which is how a mismatch can slip through. A neutral OpenSSH parser that returns type, public numbers, private numbers, comment, and padding once, with each class constructing from that structure, would put the type check in one central place. The downside is that it touches every key class and changes an internal API.

4. Wrap any parsing error in the trial loop into SSHException, chained from the original
This would fix the symptom for all future mis parses because trial loading would always move on. I would not propose it as the main fix because it masks real bugs: a corrupt key, a bug in paramiko's own parser, and a wrong type would all look the same. It is useful as defence in depth after a type check, not instead of it.

5. Validate by signing after loading
Load the key, then sign a dummy message with its own public key and verify it. That would catch cases a type check alone cannot catch (like a file where the label matches but the numbers themselves are corrupt). Again, I would keep this as defence in depth. Signing is extra work on every load and could in theory give false negatives for unusual but valid keys.

My recommendation is to keep this PR as is. If any follow up is worth it, I'd start with public-blob-first detection as a separate issue, since it gives a real performance win for encrypted keys without changing the trial API. Happy to open that issue if you think it is worth tracking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] - OpenSSH RSA key file successfully parses as a DSA key and is used to authenticate with client

2 participants