Skip to content

Commit

Permalink
ssh: don't panic if a key is too short.
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
agl committed Sep 4, 2018
1 parent 182538f commit 0709b30
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
4 changes: 2 additions & 2 deletions ssh/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -903,8 +903,8 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
// Implemented based on the documentation at
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
magic := append([]byte("openssh-key-v1"), 0)
if !bytes.Equal(magic, key[0:len(magic)]) {
const magic = "openssh-key-v1\x00"
if len(key) < len(magic) || string(key[:len(magic)]) != magic {
return nil, errors.New("ssh: invalid openssh private key format")
}
remaining := key[len(magic):]
Expand Down
31 changes: 31 additions & 0 deletions ssh/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -498,3 +500,32 @@ func TestFingerprintSHA256(t *testing.T) {
t.Errorf("got fingerprint %q want %q", fingerprint, want)
}
}

func TestInvalidKeys(t *testing.T) {
keyTypes := []string{
"RSA PRIVATE KEY",
"PRIVATE KEY",
"EC PRIVATE KEY",
"DSA PRIVATE KEY",
"OPENSSH PRIVATE KEY",
}

for _, keyType := range keyTypes {
for _, dataLen := range []int{0, 1, 2, 5, 10, 20} {
data := make([]byte, dataLen)
if _, err := io.ReadFull(rand.Reader, data); err != nil {
t.Fatal(err)
}

var buf bytes.Buffer
pem.Encode(&buf, &pem.Block{
Type: keyType,
Bytes: data,
})

// This test is just to ensure that the function
// doesn't panic so the return value is ignored.
ParseRawPrivateKey(buf.Bytes())
}
}
}

0 comments on commit 0709b30

Please sign in to comment.