sign.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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/skip2/go-qrcode"
  13. "github.com/slackhq/nebula/cert"
  14. "golang.org/x/crypto/curve25519"
  15. )
  16. type signFlags struct {
  17. set *flag.FlagSet
  18. caKeyPath *string
  19. caCertPath *string
  20. name *string
  21. ip *string
  22. duration *time.Duration
  23. inPubPath *string
  24. outKeyPath *string
  25. outCertPath *string
  26. outQRPath *string
  27. groups *string
  28. subnets *string
  29. }
  30. func newSignFlags() *signFlags {
  31. sf := signFlags{set: flag.NewFlagSet("sign", flag.ContinueOnError)}
  32. sf.set.Usage = func() {}
  33. sf.caKeyPath = sf.set.String("ca-key", "ca.key", "Optional: path to the signing CA key")
  34. sf.caCertPath = sf.set.String("ca-crt", "ca.crt", "Optional: path to the signing CA cert")
  35. sf.name = sf.set.String("name", "", "Required: name of the cert, usually a hostname")
  36. sf.ip = sf.set.String("ip", "", "Required: ip and network in CIDR notation to assign the cert")
  37. 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\"")
  38. sf.inPubPath = sf.set.String("in-pub", "", "Optional (if out-key not set): path to read a previously generated public key")
  39. sf.outKeyPath = sf.set.String("out-key", "", "Optional (if in-pub not set): path to write the private key to")
  40. sf.outCertPath = sf.set.String("out-crt", "", "Optional: path to write the certificate to")
  41. sf.outQRPath = sf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
  42. sf.groups = sf.set.String("groups", "", "Optional: comma separated list of groups")
  43. sf.subnets = sf.set.String("subnets", "", "Optional: comma separated list of subnet this cert can serve for")
  44. return &sf
  45. }
  46. func signCert(args []string, out io.Writer, errOut io.Writer) error {
  47. sf := newSignFlags()
  48. err := sf.set.Parse(args)
  49. if err != nil {
  50. return err
  51. }
  52. if err := mustFlagString("ca-key", sf.caKeyPath); err != nil {
  53. return err
  54. }
  55. if err := mustFlagString("ca-crt", sf.caCertPath); err != nil {
  56. return err
  57. }
  58. if err := mustFlagString("name", sf.name); err != nil {
  59. return err
  60. }
  61. if err := mustFlagString("ip", sf.ip); err != nil {
  62. return err
  63. }
  64. if *sf.inPubPath != "" && *sf.outKeyPath != "" {
  65. return newHelpErrorf("cannot set both -in-pub and -out-key")
  66. }
  67. rawCAKey, err := ioutil.ReadFile(*sf.caKeyPath)
  68. if err != nil {
  69. return fmt.Errorf("error while reading ca-key: %s", err)
  70. }
  71. caKey, _, err := cert.UnmarshalEd25519PrivateKey(rawCAKey)
  72. if err != nil {
  73. return fmt.Errorf("error while parsing ca-key: %s", err)
  74. }
  75. rawCACert, err := ioutil.ReadFile(*sf.caCertPath)
  76. if err != nil {
  77. return fmt.Errorf("error while reading ca-crt: %s", err)
  78. }
  79. caCert, _, err := cert.UnmarshalNebulaCertificateFromPEM(rawCACert)
  80. if err != nil {
  81. return fmt.Errorf("error while parsing ca-crt: %s", err)
  82. }
  83. issuer, err := caCert.Sha256Sum()
  84. if err != nil {
  85. return fmt.Errorf("error while getting -ca-crt fingerprint: %s", err)
  86. }
  87. if caCert.Expired(time.Now()) {
  88. return fmt.Errorf("ca certificate is expired")
  89. }
  90. // if no duration is given, expire one second before the root expires
  91. if *sf.duration <= 0 {
  92. *sf.duration = time.Until(caCert.Details.NotAfter) - time.Second*1
  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 err := nc.CheckRootConstrains(caCert); err != nil {
  148. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  149. }
  150. if *sf.outKeyPath == "" {
  151. *sf.outKeyPath = *sf.name + ".key"
  152. }
  153. if *sf.outCertPath == "" {
  154. *sf.outCertPath = *sf.name + ".crt"
  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. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  165. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  166. }
  167. err = ioutil.WriteFile(*sf.outKeyPath, cert.MarshalX25519PrivateKey(rawPriv), 0600)
  168. if err != nil {
  169. return fmt.Errorf("error while writing out-key: %s", err)
  170. }
  171. }
  172. b, err := nc.MarshalToPEM()
  173. if err != nil {
  174. return fmt.Errorf("error while marshalling certificate: %s", err)
  175. }
  176. err = ioutil.WriteFile(*sf.outCertPath, b, 0600)
  177. if err != nil {
  178. return fmt.Errorf("error while writing out-crt: %s", err)
  179. }
  180. if *sf.outQRPath != "" {
  181. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  182. if err != nil {
  183. return fmt.Errorf("error while generating qr code: %s", err)
  184. }
  185. err = ioutil.WriteFile(*sf.outQRPath, b, 0600)
  186. if err != nil {
  187. return fmt.Errorf("error while writing out-qr: %s", err)
  188. }
  189. }
  190. return nil
  191. }
  192. func x25519Keypair() ([]byte, []byte) {
  193. var pubkey, privkey [32]byte
  194. if _, err := io.ReadFull(rand.Reader, privkey[:]); err != nil {
  195. panic(err)
  196. }
  197. curve25519.ScalarBaseMult(&pubkey, &privkey)
  198. return pubkey[:], privkey[:]
  199. }
  200. func signSummary() string {
  201. return "sign <flags>: create and sign a certificate"
  202. }
  203. func signHelp(out io.Writer) {
  204. sf := newSignFlags()
  205. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  206. sf.set.SetOutput(out)
  207. sf.set.PrintDefaults()
  208. }