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. "github.com/slackhq/nebula/cert"
  13. "golang.org/x/crypto/curve25519"
  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, "Optional: how long the cert should be valid for. The default is 1 second before the signing cert expires. 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. ip, ipNet, err := net.ParseCIDR(*sf.ip)
  92. if err != nil {
  93. return newHelpErrorf("invalid ip definition: %s", err)
  94. }
  95. ipNet.IP = ip
  96. groups := []string{}
  97. if *sf.groups != "" {
  98. for _, rg := range strings.Split(*sf.groups, ",") {
  99. g := strings.TrimSpace(rg)
  100. if g != "" {
  101. groups = append(groups, g)
  102. }
  103. }
  104. }
  105. subnets := []*net.IPNet{}
  106. if *sf.subnets != "" {
  107. for _, rs := range strings.Split(*sf.subnets, ",") {
  108. rs := strings.Trim(rs, " ")
  109. if rs != "" {
  110. _, s, err := net.ParseCIDR(rs)
  111. if err != nil {
  112. return newHelpErrorf("invalid subnet definition: %s", err)
  113. }
  114. subnets = append(subnets, s)
  115. }
  116. }
  117. }
  118. var pub, rawPriv []byte
  119. if *sf.inPubPath != "" {
  120. rawPub, err := ioutil.ReadFile(*sf.inPubPath)
  121. if err != nil {
  122. return fmt.Errorf("error while reading in-pub: %s", err)
  123. }
  124. pub, _, err = cert.UnmarshalX25519PublicKey(rawPub)
  125. if err != nil {
  126. return fmt.Errorf("error while parsing in-pub: %s", err)
  127. }
  128. } else {
  129. pub, rawPriv = x25519Keypair()
  130. }
  131. nc := cert.NebulaCertificate{
  132. Details: cert.NebulaCertificateDetails{
  133. Name: *sf.name,
  134. Ips: []*net.IPNet{ipNet},
  135. Groups: groups,
  136. Subnets: subnets,
  137. NotBefore: time.Now(),
  138. NotAfter: time.Now().Add(*sf.duration),
  139. PublicKey: pub,
  140. IsCA: false,
  141. Issuer: issuer,
  142. },
  143. }
  144. if err := nc.CheckRootConstrains(caCert); err != nil {
  145. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  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.outCertPath); err == nil {
  154. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  155. }
  156. err = nc.Sign(caKey)
  157. if err != nil {
  158. return fmt.Errorf("error while signing: %s", err)
  159. }
  160. if *sf.inPubPath == "" {
  161. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  162. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  163. }
  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. }