github.com/slackhq/nebula@v1.9.0/cmd/nebula-cert/verify.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/slackhq/nebula/cert"
    12  )
    13  
    14  type verifyFlags struct {
    15  	set      *flag.FlagSet
    16  	caPath   *string
    17  	certPath *string
    18  }
    19  
    20  func newVerifyFlags() *verifyFlags {
    21  	vf := verifyFlags{set: flag.NewFlagSet("verify", flag.ContinueOnError)}
    22  	vf.set.Usage = func() {}
    23  	vf.caPath = vf.set.String("ca", "", "Required: path to a file containing one or more ca certificates")
    24  	vf.certPath = vf.set.String("crt", "", "Required: path to a file containing a single certificate")
    25  	return &vf
    26  }
    27  
    28  func verify(args []string, out io.Writer, errOut io.Writer) error {
    29  	vf := newVerifyFlags()
    30  	err := vf.set.Parse(args)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	if err := mustFlagString("ca", vf.caPath); err != nil {
    36  		return err
    37  	}
    38  	if err := mustFlagString("crt", vf.certPath); err != nil {
    39  		return err
    40  	}
    41  
    42  	rawCACert, err := os.ReadFile(*vf.caPath)
    43  	if err != nil {
    44  		return fmt.Errorf("error while reading ca: %s", err)
    45  	}
    46  
    47  	caPool := cert.NewCAPool()
    48  	for {
    49  		rawCACert, err = caPool.AddCACertificate(rawCACert)
    50  		if err != nil {
    51  			return fmt.Errorf("error while adding ca cert to pool: %s", err)
    52  		}
    53  
    54  		if rawCACert == nil || len(rawCACert) == 0 || strings.TrimSpace(string(rawCACert)) == "" {
    55  			break
    56  		}
    57  	}
    58  
    59  	rawCert, err := os.ReadFile(*vf.certPath)
    60  	if err != nil {
    61  		return fmt.Errorf("unable to read crt; %s", err)
    62  	}
    63  
    64  	c, _, err := cert.UnmarshalNebulaCertificateFromPEM(rawCert)
    65  	if err != nil {
    66  		return fmt.Errorf("error while parsing crt: %s", err)
    67  	}
    68  
    69  	good, err := c.Verify(time.Now(), caPool)
    70  	if !good {
    71  		return err
    72  	}
    73  
    74  	return nil
    75  }
    76  
    77  func verifySummary() string {
    78  	return "verify <flags>: verifies a certificate isn't expired and was signed by a trusted authority."
    79  }
    80  
    81  func verifyHelp(out io.Writer) {
    82  	vf := newVerifyFlags()
    83  	out.Write([]byte("Usage of " + os.Args[0] + " " + verifySummary() + "\n"))
    84  	vf.set.SetOutput(out)
    85  	vf.set.PrintDefaults()
    86  }