Skip to content

Commit

Permalink
add nil-check for decoded private key pem bytes (#360)
Browse files Browse the repository at this point in the history
  • Loading branch information
rockspore authored Nov 29, 2021
1 parent 1e7bb20 commit ffc1eb1
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
3 changes: 3 additions & 0 deletions server/authmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ func LoadPrivateKey(privateKeyBytes []byte) (*rsa.PrivateKey, error) {

var err error
privPem, _ := pem.Decode(privateKeyBytes)
if privPem == nil {
return nil, fmt.Errorf("bytes in bad format")
}
if PEMKeyType != privPem.Type {
return nil, fmt.Errorf("%s required, found: %s", PEMKeyType, privPem.Type)
}
Expand Down
60 changes: 60 additions & 0 deletions server/authmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
package server

import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -147,3 +152,58 @@ func TestNoAuthPUTRoundTripper(t *testing.T) {
t.Fatal(err)
}
}

func TestLoadPrivateKey(t *testing.T) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
t.Fatal(err)
}
goodKeyBuf := &bytes.Buffer{}
if err := pem.Encode(goodKeyBuf, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: privateKeyBytes}); err != nil {
t.Fatal(err)
}
badKeyBuf1 := &bytes.Buffer{}
if err := pem.Encode(badKeyBuf1, &pem.Block{Type: "UNKNOWN PRIVATE KEY", Bytes: privateKeyBytes}); err != nil {
t.Fatal(err)
}
badKeyBuf2 := &bytes.Buffer{}
if err := pem.Encode(badKeyBuf2, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: []byte("not a private key")}); err != nil {
t.Fatal(err)
}

tests := []struct {
desc string
pkBytes []byte
wantErr bool
}{
{
desc: "good private key bytes",
pkBytes: goodKeyBuf.Bytes(),
},
{
desc: "private key bytes with bad pem type",
pkBytes: badKeyBuf1.Bytes(),
wantErr: true,
},
{
desc: "bad private key bytes",
pkBytes: badKeyBuf2.Bytes(),
wantErr: true,
},
{
desc: "bad bytes",
pkBytes: []byte("not a private key"),
wantErr: true,
},
}

for _, test := range tests {
if _, err := LoadPrivateKey(test.pkBytes); (err != nil) != test.wantErr {
t.Errorf("LoadPrivateKey() error = %v, wantErr? %t", err, test.wantErr)
}
}
}

0 comments on commit ffc1eb1

Please sign in to comment.