Skip to content

Commit 0709b30

Browse files
committed
ssh: don't panic if a key is too short.
Change-Id: I810eb1c5d4cacc710a427e2ce031db1e9c292454 Reviewed-on: https://go-review.googlesource.com/132656 Run-TryBot: Adam Langley <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Filippo Valsorda <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 182538f commit 0709b30

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

ssh/keys.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -903,8 +903,8 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
903903
// Implemented based on the documentation at
904904
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
905905
func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
906-
magic := append([]byte("openssh-key-v1"), 0)
907-
if !bytes.Equal(magic, key[0:len(magic)]) {
906+
const magic = "openssh-key-v1\x00"
907+
if len(key) < len(magic) || string(key[:len(magic)]) != magic {
908908
return nil, errors.New("ssh: invalid openssh private key format")
909909
}
910910
remaining := key[len(magic):]

ssh/keys_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ import (
1313
"crypto/rsa"
1414
"crypto/x509"
1515
"encoding/base64"
16+
"encoding/pem"
1617
"fmt"
18+
"io"
1719
"reflect"
1820
"strings"
1921
"testing"
@@ -498,3 +500,32 @@ func TestFingerprintSHA256(t *testing.T) {
498500
t.Errorf("got fingerprint %q want %q", fingerprint, want)
499501
}
500502
}
503+
504+
func TestInvalidKeys(t *testing.T) {
505+
keyTypes := []string{
506+
"RSA PRIVATE KEY",
507+
"PRIVATE KEY",
508+
"EC PRIVATE KEY",
509+
"DSA PRIVATE KEY",
510+
"OPENSSH PRIVATE KEY",
511+
}
512+
513+
for _, keyType := range keyTypes {
514+
for _, dataLen := range []int{0, 1, 2, 5, 10, 20} {
515+
data := make([]byte, dataLen)
516+
if _, err := io.ReadFull(rand.Reader, data); err != nil {
517+
t.Fatal(err)
518+
}
519+
520+
var buf bytes.Buffer
521+
pem.Encode(&buf, &pem.Block{
522+
Type: keyType,
523+
Bytes: data,
524+
})
525+
526+
// This test is just to ensure that the function
527+
// doesn't panic so the return value is ignored.
528+
ParseRawPrivateKey(buf.Bytes())
529+
}
530+
}
531+
}

0 commit comments

Comments
 (0)