2
0

sign.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package main
  2. import (
  3. "crypto/rand"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "os"
  10. "strings"
  11. "time"
  12. "golang.org/x/crypto/curve25519"
  13. "github.com/slackhq/nebula/cert"
  14. )
  15. type signFlags struct {
  16. set *flag.FlagSet
  17. caKeyPath *string
  18. caCertPath *string
  19. name *string
  20. ip *string
  21. duration *time.Duration
  22. inPubPath *string
  23. outKeyPath *string
  24. outCertPath *string
  25. groups *string
  26. subnets *string
  27. }
  28. func newSignFlags() *signFlags {
  29. sf := signFlags{set: flag.NewFlagSet("sign", flag.ContinueOnError)}
  30. sf.set.Usage = func() {}
  31. sf.caKeyPath = sf.set.String("ca-key", "ca.key", "Optional: path to the signing CA key")
  32. sf.caCertPath = sf.set.String("ca-crt", "ca.crt", "Optional: path to the signing CA cert")
  33. sf.name = sf.set.String("name", "", "Required: name of the cert, usually a hostname")
  34. sf.ip = sf.set.String("ip", "", "Required: ip and network in CIDR notation to assign the cert")
  35. sf.duration = sf.set.Duration("duration", 0, "Required: how long the cert should be valid for. Valid time units are seconds: \"s\", minutes: \"m\", hours: \"h\"")
  36. sf.inPubPath = sf.set.String("in-pub", "", "Optional (if out-key not set): path to read a previously generated public key")
  37. sf.outKeyPath = sf.set.String("out-key", "", "Optional (if in-pub not set): path to write the private key to")
  38. sf.outCertPath = sf.set.String("out-crt", "", "Optional: path to write the certificate to")
  39. sf.groups = sf.set.String("groups", "", "Optional: comma separated list of groups")
  40. sf.subnets = sf.set.String("subnets", "", "Optional: comma seperated list of subnet this cert can serve for")
  41. return &sf
  42. }
  43. func signCert(args []string, out io.Writer, errOut io.Writer) error {
  44. sf := newSignFlags()
  45. err := sf.set.Parse(args)
  46. if err != nil {
  47. return err
  48. }
  49. if err := mustFlagString("ca-key", sf.caKeyPath); err != nil {
  50. return err
  51. }
  52. if err := mustFlagString("ca-crt", sf.caCertPath); err != nil {
  53. return err
  54. }
  55. if err := mustFlagString("name", sf.name); err != nil {
  56. return err
  57. }
  58. if err := mustFlagString("ip", sf.ip); err != nil {
  59. return err
  60. }
  61. if *sf.inPubPath != "" && *sf.outKeyPath != "" {
  62. return newHelpErrorf("cannot set both -in-pub and -out-key")
  63. }
  64. rawCAKey, err := ioutil.ReadFile(*sf.caKeyPath)
  65. if err != nil {
  66. return fmt.Errorf("error while reading ca-key: %s", err)
  67. }
  68. caKey, _, err := cert.UnmarshalEd25519PrivateKey(rawCAKey)
  69. if err != nil {
  70. return fmt.Errorf("error while parsing ca-key: %s", err)
  71. }
  72. rawCACert, err := ioutil.ReadFile(*sf.caCertPath)
  73. if err != nil {
  74. return fmt.Errorf("error while reading ca-crt: %s", err)
  75. }
  76. caCert, _, err := cert.UnmarshalNebulaCertificateFromPEM(rawCACert)
  77. if err != nil {
  78. return fmt.Errorf("error while parsing ca-crt: %s", err)
  79. }
  80. issuer, err := caCert.Sha256Sum()
  81. if err != nil {
  82. return fmt.Errorf("error while getting -ca-crt fingerprint: %s", err)
  83. }
  84. if caCert.Expired(time.Now()) {
  85. return fmt.Errorf("ca certificate is expired")
  86. }
  87. // if no duration is given, expire one second before the root expires
  88. if *sf.duration <= 0 {
  89. *sf.duration = time.Until(caCert.Details.NotAfter) - time.Second*1
  90. }
  91. if caCert.Details.NotAfter.Before(time.Now().Add(*sf.duration)) {
  92. return fmt.Errorf("refusing to generate certificate with duration beyond root expiration: %s", caCert.Details.NotAfter)
  93. }
  94. ip, ipNet, err := net.ParseCIDR(*sf.ip)
  95. if err != nil {
  96. return newHelpErrorf("invalid ip definition: %s", err)
  97. }
  98. ipNet.IP = ip
  99. groups := []string{}
  100. if *sf.groups != "" {
  101. for _, rg := range strings.Split(*sf.groups, ",") {
  102. g := strings.TrimSpace(rg)
  103. if g != "" {
  104. groups = append(groups, g)
  105. }
  106. }
  107. }
  108. subnets := []*net.IPNet{}
  109. if *sf.subnets != "" {
  110. for _, rs := range strings.Split(*sf.subnets, ",") {
  111. rs := strings.Trim(rs, " ")
  112. if rs != "" {
  113. _, s, err := net.ParseCIDR(rs)
  114. if err != nil {
  115. return newHelpErrorf("invalid subnet definition: %s", err)
  116. }
  117. subnets = append(subnets, s)
  118. }
  119. }
  120. }
  121. var pub, rawPriv []byte
  122. if *sf.inPubPath != "" {
  123. rawPub, err := ioutil.ReadFile(*sf.inPubPath)
  124. if err != nil {
  125. return fmt.Errorf("error while reading in-pub: %s", err)
  126. }
  127. pub, _, err = cert.UnmarshalX25519PublicKey(rawPub)
  128. if err != nil {
  129. return fmt.Errorf("error while parsing in-pub: %s", err)
  130. }
  131. } else {
  132. pub, rawPriv = x25519Keypair()
  133. }
  134. nc := cert.NebulaCertificate{
  135. Details: cert.NebulaCertificateDetails{
  136. Name: *sf.name,
  137. Ips: []*net.IPNet{ipNet},
  138. Groups: groups,
  139. Subnets: subnets,
  140. NotBefore: time.Now(),
  141. NotAfter: time.Now().Add(*sf.duration),
  142. PublicKey: pub,
  143. IsCA: false,
  144. Issuer: issuer,
  145. },
  146. }
  147. if *sf.outKeyPath == "" {
  148. *sf.outKeyPath = *sf.name + ".key"
  149. }
  150. if *sf.outCertPath == "" {
  151. *sf.outCertPath = *sf.name + ".crt"
  152. }
  153. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  154. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  155. }
  156. if _, err := os.Stat(*sf.outCertPath); err == nil {
  157. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  158. }
  159. err = nc.Sign(caKey)
  160. if err != nil {
  161. return fmt.Errorf("error while signing: %s", err)
  162. }
  163. if *sf.inPubPath == "" {
  164. err = ioutil.WriteFile(*sf.outKeyPath, cert.MarshalX25519PrivateKey(rawPriv), 0600)
  165. if err != nil {
  166. return fmt.Errorf("error while writing out-key: %s", err)
  167. }
  168. }
  169. b, err := nc.MarshalToPEM()
  170. if err != nil {
  171. return fmt.Errorf("error while marshalling certificate: %s", err)
  172. }
  173. err = ioutil.WriteFile(*sf.outCertPath, b, 0600)
  174. if err != nil {
  175. return fmt.Errorf("error while writing out-crt: %s", err)
  176. }
  177. return nil
  178. }
  179. func x25519Keypair() ([]byte, []byte) {
  180. var pubkey, privkey [32]byte
  181. if _, err := io.ReadFull(rand.Reader, privkey[:]); err != nil {
  182. panic(err)
  183. }
  184. curve25519.ScalarBaseMult(&pubkey, &privkey)
  185. return pubkey[:], privkey[:]
  186. }
  187. func signSummary() string {
  188. return "sign <flags>: create and sign a certificate"
  189. }
  190. func signHelp(out io.Writer) {
  191. sf := newSignFlags()
  192. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  193. sf.set.SetOutput(out)
  194. sf.set.PrintDefaults()
  195. }