Skip to content

Commit

Permalink
crypto/rsa: check for primes ≤ 1 in Validate
Browse files Browse the repository at this point in the history
Change 7c7126c removed the primality
checking in Validate to save CPU time. That check happened to be
filtering out private keys with primes that were zero or one. Without
that filtering, such primes cause a panic when trying to use such a
private key.

This change specifically checks for and rejects primes ≤ 1 in Validate.

Fixes golang#11233.

Change-Id: Ie6537edb8250c07a45aaf50dab43227002ee7386
Reviewed-on: https://go-review.googlesource.com/11611
Reviewed-by: Brad Fitzpatrick <[email protected]>
Reviewed-by: Russ Cox <[email protected]>
  • Loading branch information
agl authored and rsc committed Jun 29, 2015
1 parent 9b2d84e commit 2814906
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/crypto/rsa/rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ func (priv *PrivateKey) Validate() error {
// Check that Πprimes == n.
modulus := new(big.Int).Set(bigOne)
for _, prime := range priv.Primes {
// Any primes ≤ 1 will cause divide-by-zero panics later.
if prime.Cmp(bigOne) <= 0 {
return errors.New("crypto/rsa: invalid prime value")
}
modulus.Mul(modulus, prime)
}
if modulus.Cmp(priv.N) != 0 {
Expand Down
7 changes: 7 additions & 0 deletions src/crypto/x509/x509_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ func TestParsePKCS1PrivateKey(t *testing.T) {
priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 {
t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey)
}

// This private key includes an invalid prime that
// rsa.PrivateKey.Validate should reject.
data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00")
if _, err := ParsePKCS1PrivateKey(data); err == nil {
t.Errorf("parsing invalid private key did not result in an error")
}
}

func TestParsePKIXPublicKey(t *testing.T) {
Expand Down

0 comments on commit 2814906

Please sign in to comment.