Don't corrupt RSA private keys during loading. #1055
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fifteen years ago, Twisted landed a change which enforced that the RSA primes were ordered p ⩽ q, but then serialised them backwards, so that actually p ⩾ q, and it always recreated the CRT values. This was because of this bug, which is something to do with testing key serialisation round-tripping. 2003-era PyCrypto did something very similar, so they were probably copying that in order to avoid PyCrypto changing their keys and triggering round-trip failures.
As time has gone by, much of the Twisted code has changed, but the initial condition to swap p & q if p > q has remained. However, the CRT values are no longer recomputed, so this just corrupts the key. (For example,
dmp1
stands for “d mod p-1” so clearly if p & q are swapped, that value has to be updated in order to be correct. The valuesdmq1
andiqmp
(inverse of q mod p) are likewise.)OpenSSL has anti-glitch checking in its RSA implementation that is designed to stop power-glitching attacks. (An arithmetic error during CRT computation has a high chance of leaking the private key.) That anti-glitch code detects the error caused by swapping p and q and triggers a slow-path re-computation of signatures without the CRT. Thus OpenSSL is silently correcting this, but spending much more CPU to do so.
https://twistedmatrix.com/trac/ticket/9518
Contributor Checklist: