parse CA certificate to catch more specific errors

This commit is contained in:
Chelsea Holland Komlo 2018-05-25 14:47:19 -04:00
parent 6ee62a0973
commit 521f8d3fb4
2 changed files with 58 additions and 5 deletions

View file

@ -3,6 +3,7 @@ package tlsutil
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"net"
@ -146,8 +147,18 @@ func (c *Config) AppendCA(pool *x509.CertPool) error {
return fmt.Errorf("Failed to read CA file: %v", err)
}
block, _ := pem.Decode([]byte(data))
if block == nil {
return fmt.Errorf("Failed to decode CA file from pem format")
}
// Parse the certificate to ensure that it is properly formatted
if _, err := x509.ParseCertificates(block.Bytes); err != nil {
return fmt.Errorf("Failed to parse CA file: %v", err)
}
if !pool.AppendCertsFromPEM(data) {
return fmt.Errorf("Failed to parse any CA certificates")
return fmt.Errorf("Failed to add any CA certificates")
}
return nil

View file

@ -7,6 +7,7 @@ import (
"io"
"io/ioutil"
"net"
"os"
"strings"
"testing"
@ -26,14 +27,55 @@ const (
)
func TestConfig_AppendCA_None(t *testing.T) {
require := require.New(t)
conf := &Config{}
pool := x509.NewCertPool()
err := conf.AppendCA(pool)
if err != nil {
t.Fatalf("err: %v", err)
require.Nil(err)
}
func TestConfig_AppendCA_Valid(t *testing.T) {
require := require.New(t)
conf := &Config{
CAFile: cacert,
}
if len(pool.Subjects()) != 0 {
t.Fatalf("bad: %v", pool.Subjects())
pool := x509.NewCertPool()
err := conf.AppendCA(pool)
require.Nil(err)
}
func TestConfig_AppendCA_Invalid(t *testing.T) {
require := require.New(t)
{
conf := &Config{
CAFile: "invalidFile",
}
pool := x509.NewCertPool()
err := conf.AppendCA(pool)
require.NotNil(err)
require.Contains(err.Error(), "Failed to read CA file")
require.Equal(len(pool.Subjects()), 0)
}
{
tmpFile, err := ioutil.TempFile("/tmp", "test_ca_file")
require.Nil(err)
defer os.Remove(tmpFile.Name())
_, err = tmpFile.Write([]byte("Invalid CA Content!"))
require.Nil(err)
conf := &Config{
CAFile: tmpFile.Name(),
}
pool := x509.NewCertPool()
err = conf.AppendCA(pool)
require.NotNil(err)
require.Contains(err.Error(), "Failed to decode CA file from pem format")
require.Equal(len(pool.Subjects()), 0)
}
}