From 2f4ecb1b6babe753b1d95d31d7c971d83136f81d Mon Sep 17 00:00:00 2001 From: Lucas Manuel Rodriguez Date: Wed, 29 Dec 2021 22:32:55 -0300 Subject: [PATCH] `fleetctl package` command to check for PEM file (#3375) #3374 --- changes/issue-3374-fleetctl-check-pem-file | 1 + cmd/fleetctl/package.go | 20 ++++++++++++++++++++ cmd/fleetctl/package_test.go | 10 ++++++++++ 3 files changed, 31 insertions(+) create mode 100644 changes/issue-3374-fleetctl-check-pem-file diff --git a/changes/issue-3374-fleetctl-check-pem-file b/changes/issue-3374-fleetctl-check-pem-file new file mode 100644 index 000000000..fe27e1c57 --- /dev/null +++ b/changes/issue-3374-fleetctl-check-pem-file @@ -0,0 +1 @@ +* Make `fleetctl package` check `--fleet-certificate` is a valid PEM file. diff --git a/cmd/fleetctl/package.go b/cmd/fleetctl/package.go index e73f7b940..706331ca2 100644 --- a/cmd/fleetctl/package.go +++ b/cmd/fleetctl/package.go @@ -1,8 +1,10 @@ package main import ( + "encoding/pem" "errors" "fmt" + "io/ioutil" "path/filepath" "runtime" @@ -128,6 +130,13 @@ func packageCommand() *cli.Command { return errors.New("Windows can only build MSI packages.") } + if opt.FleetCertificate != "" { + err := checkPEMCertificate(opt.FleetCertificate) + if err != nil { + return fmt.Errorf("failed to read certificate %q: %w", opt.FleetCertificate, err) + } + } + var buildFunc func(packaging.Options) (string, error) switch c.String("type") { case "pkg": @@ -165,3 +174,14 @@ To add other devices to Fleet, distribute this installer using Chef, Ansible, Ja }, } } + +func checkPEMCertificate(path string) error { + cert, err := ioutil.ReadFile(path) + if err != nil { + return err + } + if p, _ := pem.Decode(cert); p == nil { + return errors.New("invalid PEM file") + } + return nil +} diff --git a/cmd/fleetctl/package_test.go b/cmd/fleetctl/package_test.go index 9db9c0b4a..c6ea336d3 100644 --- a/cmd/fleetctl/package_test.go +++ b/cmd/fleetctl/package_test.go @@ -1,7 +1,10 @@ package main import ( + "fmt" + "io/ioutil" "os" + "path/filepath" "testing" "github.com/stretchr/testify/require" @@ -22,6 +25,13 @@ func TestPackage(t *testing.T) { // --insecure and --fleet-certificate are mutually exclusive runAppCheckErr(t, []string{"package", "--type=deb", "--insecure", "--fleet-certificate=test123"}, "--insecure and --fleet-certificate may not be provided together") + // Test invalid PEM file provided in --fleet-certificate. + certDir := t.TempDir() + fleetCertificate := filepath.Join(certDir, "fleet.pem") + err := ioutil.WriteFile(fleetCertificate, []byte("undefined"), os.FileMode(0644)) + require.NoError(t, err) + runAppCheckErr(t, []string{"package", "--type=deb", fmt.Sprintf("--fleet-certificate=%s", fleetCertificate)}, fmt.Sprintf("failed to read certificate %q: invalid PEM file", fleetCertificate)) + // run package tests, each should output their respective package type // fleet-osquery_0.0.3_amd64.deb runAppForTest(t, []string{"package", "--type=deb", "--insecure"})