verify.go 1.9 KB

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