verify.go 1.9 KB

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