Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trim whitespace around public keys before parsing #1175

Merged
merged 2 commits into from
Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pkg/pki/x509/x509.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,17 @@ func NewPublicKey(r io.Reader) (*PublicKey, error) {
if err != nil {
return nil, err
}
trimmedRawPub := bytes.TrimSpace(rawPub)

block, rest := pem.Decode(rawPub)
block, rest := pem.Decode(trimmedRawPub)
if block == nil {
return nil, errors.New("invalid public key: failure decoding PEM")
}

// Handle certificate chain, concatenated PEM-encoded certificates
if len(rest) > 0 {
// Support up to 10 certificates in a chain, to avoid parsing extremely long chains
certs, err := cryptoutils.UnmarshalCertificatesFromPEMLimited(rawPub, 10)
certs, err := cryptoutils.UnmarshalCertificatesFromPEMLimited(trimmedRawPub, 10)
if err != nil {
return nil, err
}
Expand Down
12 changes: 12 additions & 0 deletions pkg/pki/x509/x509_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ const ed25519Pub = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAizWek2gKgMM+bad4rVJ5nc9NsbNOba0A0BNfzOgklRs=
-----END PUBLIC KEY-----`

const pubWithTrailingNewLine = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEx+ikqUxXurlxZltajRBV2ju31j32
baT2ax2dXBcpInWaFESqGF35KISflP1EmMvEnfG+AzHecQ0WQp5QzNId+w==
-----END PUBLIC KEY-----

`

func signData(t *testing.T, b []byte, pkey string) []byte {

priv, err := cryptoutils.UnmarshalPEMToPrivateKey([]byte(pkey), cryptoutils.SkipPassword)
Expand Down Expand Up @@ -303,4 +310,9 @@ func TestPublicKeyWithCertChain(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "too many certificates specified in PEM block") {
t.Fatalf("expected error with long certificate chain, got %v", err)
}

// Verify public key with trailing newline is parsed OK
if _, err = NewPublicKey(strings.NewReader(pubWithTrailingNewLine)); err != nil {
asraa marked this conversation as resolved.
Show resolved Hide resolved
t.Fatalf("unexpected error parsing public key with trailing newline: %v", err)
}
}