Skip to content

Fix PEM private key loading when preamble lines precede BEGIN - #2698

Open
bhavyup wants to merge 2 commits into
paramiko:mainfrom
bhavyup:fix-pem-preamble-parsing
Open

bhavyup wants to merge 2 commits into
paramiko:mainfrom
bhavyup:fix-pem-preamble-parsing

Conversation

@bhavyup

@bhavyup bhavyup commented Oct 4, 2026

Copy link
Copy Markdown

Closes #1641.

PKey._read_private_key() correctly skips preamble lines to locate the -----BEGIN tag, but then passed the entire file (preamble included) to _read_private_key_pem(), which assumes line 0 is BEGIN. The preamble lines were fed into the base64 decoder, failing with "base64 decoding error".

This passes only the lines from BEGIN onward to _read_private_key_pem(), so preamble lines are excluded before header parsing and base64 decoding.

Changes:

  • paramiko/pkey.py: slice lines[begin:end] in _read_private_key for the PEM path
  • tests/pkey.py: test loading a PEM key with preamble lines (including a Key: value style line to cover header parsing)

All 58 tests in tests/pkey.py pass.

@bhavyup
bhavyup force-pushed the fix-pem-preamble-parsing branch from 4450532 to d0b996a Compare October 4, 2026 13:13
@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

Uh-huh It was a 2-file commit ... I mean even using AI for that is a joke.
Still not gonna argue with a maintainer, but respectfully it was not an AI commit.
But still if something is wrong and/or i went/missed something in the fix, point me there so that i could help.
Thanks @bskinn ! do i need to comment same on my other PR as well?

@bskinn

bskinn commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Thanks for following up, @bhavyup. Apologies for evaluating your PRs as AI; it is a judgment call a lot of the time, and I know I'm going to get it wrong periodically. And yes, I've seen some really small commits that were even still pretty clearly AI-written.

A single-commit, multi-file PR isn't something I usually see from human authors, especially with subsequent changes applied by force-push instead of just adding additional commits.

The fix does make sense, only passing the correct portion to _read_private_key_pem(). bitprophet will be the final arbiter, though.

Are there any constraints on the validity of the contents of the preamble, or can it be any arbitrary text? (If the former, then should we consider validating?)

Separately, more generally - how did you come across paramiko? Were you trying to use it and encountered this?

@bhavyup

bhavyup commented Nov 2, 2026

Copy link
Copy Markdown
Author

Thanks @bskinn for reopening this and I get the AI part. You did it with right mindset!

For the follow-up question. Answering it directly: no, the preamble does not need validation, and adding validation would be the wrong fix here. Let's tackle why? (sorry if it's too long):

  • You already know what a PEM file is, by definition: its BEGIN and END lines, the encapsulation boundaries. Everything between them is the key, and for an old-style encrypted PEM key, the headers after BEGIN such as Proc-Type and DEK-Info.
  • Everything before that is not key material. Does not affect decryption or key-type choosing. It's just useful to human reading the file, i.e. a comment, bag attribute, etc. Does not contribute to anything, loading-key wise.
  • The problem old code had, was that it tried to parse preamble as if they are headers which never worked reliably. For old-style encrypted PEM keys (which needed this header-parsing most, for backward-compat), headers exist inside the BEGIN and END tag not in the preamble, which the new fix still parses because it gets the actual begin boundaries. That is legacy PEM, from before RFC 7468. RFC 7468 itself says its modern textual encoding does not define headers alongside the data, and that empty space after BEGIN is just a throwback to old PEM which did define an encapsulated header portion. Paramiko still supports the old format for backwards compatibility, because old tools still produce it.
  • How I validate the philosophy behind the fix? I checked RFC 7468, Section 2, General Considerations, and Section 5.2, Explanatory Text, rather than relying on a summary.
  • Section 2 says data before the encapsulation boundaries is permitted, and parsers must not malfunction when processing such data. It also says parsers should ignore whitespace and other non-base64 characters.
  • Section 5.2 says many tools are known to emit explanatory text before BEGIN and after END. For generators, that text should be related to the object, for example a textual representation of it. That is a generator-side SHOULD, not a parser-side MUST, and it is not a format, charset, or allowlist.

That distinction matters for your question. There is no preamble format in the RFC that paramiko could validate against. If I invented one, for example only plain sentences, or only Key: value lines, I would reject legitimate files. Plain sentences would break bag attributes, Key: value only would break plain comments and blank lines, and either rule would recreate the original bug for a different group of users.

Validation would also add no security here. The preamble is ignored, it is not executed, it is not used as key material, and it does not decide the key type. The BEGIN label and the decoded data inside BEGIN/END decide that. A strict preamble check would therefore be a new, breaking feature, not part of this bugfix.

THE FIX:

The outer loader, _read_private_key, already scanned for BEGIN correctly.
This fix makes the PEM path consistent with the OpenSSH path, which was already sliced correctly. It passes only the lines from BEGIN to END to _read_private_key_pem. The inner parser then sees exactly what it expects: BEGIN skipped, real headers if any, then only real base64, with END excluded.

Because of that slice, preamble content cannot affect parsing, except for one unavoidable rule, which I cover below.

CURRENT TEST COVERAGE:

The PR adds one test, loads_pem_with_preamble_lines in tests/pkey.py, with the comment that preamble lines before BEGIN must not corrupt loading, referencing #1641, covering the two failure modes: a non-header line breaking the parse, and a header-like line being mistaken for a header.

It prepends two lines to the test RSA key:

This is a preamble, a plain line with no colon & Another: preamble line, a line that looks like a header.

That test alone is not exhaustive, and it is not foolproof. It does not separately cover blank lines, a multi-line bag-attributes block, an EC PEM key, an encrypted traditional PEM key with preamble, or a fake BEGIN line.
The argument for generality is not the test count, it is structural: after the fix, preamble content never reaches the parser, so its exact wording cannot change the result, except through BEGIN detection itself.

[IMPORTANT] The fake BEGIN case

This is the one edge where "arbitrary text" needs qualification.

Paramiko's BEGIN pattern is strict: five dashes, BEGIN, a label of RSA, EC, or OPENSSH, PRIVATE KEY, five dashes, and only trailing whitespace. A near-miss line does not match, so it stays preamble and is ignored.

But an exact fake BEGIN is different, because then it is not preamble anymore as far as any parser can tell, it is a boundary. The scanner stops at the first exact BEGIN line, and that has three outcomes depending on what follows:

  • Fake BEGIN, then junk, then the real BEGIN, then real base64, then real END: paramiko tries to decode junk plus the real BEGIN line plus the real base64 together, and fails. It fails closed, it does not load a wrong key, but it also does not recover the real key behind the fake.
  • Fake BEGIN that is itself a complete valid key, followed by a second key: paramiko loads the first key and ignores the second, because this loader loads one key per call. That is a file containing two keys, not a preamble problem.
  • Fake BEGIN with a different type, for example EC while loading RSA: it fails with the existing "encountered EC key, expected RSA key" error.
  • Multiple fake blocks do not change this, the parser stops at the first BEGIN/END pair and never searches further.

I do not think preamble validation solves this. Validation cannot tell whether a BEGIN line was intended or not, and anyone who can prepend a fake BEGIN to a private key file can already replace the whole file. RFC 7468 also warns that very lax parsing can accept text that was not intended to be accepted, like a snippet or sample. That ambiguity is inherent to PEM, not introduced by this fix.

TEST PROPOSAL

To make the generality concrete instead of just arguing it, I can add the following as a separate follow-up commit, if you would like them:

  • Blank lines before BEGIN on an RSA key
  • A multi-line bag-attributes block before BEGIN on an RSA key
  • An EC PEM key with preamble, since the current test is RSA only but the PEM path is shared
  • A near-miss BEGIN line in the preamble, for example a CERTIFICATE label or a line with extra trailing words, expecting the real key to load
  • An END line before BEGIN, expecting it to be ignored
  • An encrypted traditional PEM key with preamble and its password, to prove the post-BEGIN Proc-Type and DEK-Info headers are still preserved

I would deliberately not add an exact fake BEGIN as a success test, because it fails by design for the reasons above. If you want that behaviour locked in, I can add it as an error-expectation test instead, expecting an SSHException, but I wanted to flag that choice rather than assume it.

Please let me know if you want the additional tests added, or if you would prefer a different shape for the fake BEGIN edge or anything else.

@bhavyup

bhavyup commented Nov 2, 2026

Copy link
Copy Markdown
Author

As for the general part, I did use paramiko to get the SSH tooling I use to reach my PC over Tailscale for myself and my AI Agents. Though my main work was based on Ed25519 OpenSSH key, not an RSA PEM key with a preamble, and the OpenSSH path was already sliced correctly anyway, so I did not encounter the bug this way.
I'll be blunt here: I found #1641 while hunting for clean, unclaimed issues in repos/stack I use for some OSCs, and reproduced it locally with generated RSA keys.

Since then, I've had eyes on many other issues too apart from the two I worked on. Did some work on them too but I did not push or open PRs since multiple PRs in a short time with no maintainer's permission/guidance would just flag me more into BOT Category.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Errors when parsing the preamble lines before the private key

2 participants