Skip to content

Fix quadratic-time PEM scanning in load_ssh_private_key - #15461

Open
alex wants to merge 1 commit into
pyca:mainfrom
alex:ssh-private-key-quadratic-pem-scan
Open

Fix quadratic-time PEM scanning in load_ssh_private_key#15461
alex wants to merge 1 commit into
pyca:mainfrom
alex:ssh-private-key-quadratic-pem-scan

Conversation

@alex

@alex alex commented Aug 16, 2026

Copy link
Copy Markdown
Member

load_ssh_private_key located the OpenSSH PEM block with a regex whose runtime is quadratic in the length of the input: re.search restarts at every occurrence of the opening marker and rescans to the end of the input looking for a closing marker, so input with an opening marker and no closing marker drives O(n^2) work before any parsing or size check. An attacker who can supply data to the function can consume unbounded CPU (~8s for 273 KiB, extrapolating to hours for a few MiB).

Locate the markers directly with bytes.find instead. The first opening marker and the first closing marker after it delimit exactly what the lazy regex matched, and finding them is linear. memoryview inputs, which _check_byteslike permits but bytes.find does not, are converted first.

Thanks to @jaypatrickhoward for reporting this.

load_ssh_private_key located the OpenSSH PEM block with a regex whose
runtime is quadratic in the length of the input: re.search restarts at
every occurrence of the opening marker and rescans to the end of the
input looking for a closing marker, so input with an opening marker and
no closing marker drives O(n^2) work before any parsing or size check.
An attacker who can supply data to the function can consume unbounded
CPU (~8s for 273 KiB, extrapolating to hours for a few MiB).

Locate the markers directly with bytes.find instead. The first opening
marker and the first closing marker after it delimit exactly what the
lazy regex matched, and finding them is linear. memoryview inputs, which
_check_byteslike permits but bytes.find does not, are converted first.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@alex
alex force-pushed the ssh-private-key-quadratic-pem-scan branch from 55b9cc9 to 3289cb9 Compare August 16, 2026 22:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant