sign.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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: ipv4 address 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 ipv4 address and network in CIDR notation. Subnets 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. if err := caCert.VerifyPrivateKey(caKey); err != nil {
  84. return fmt.Errorf("refusing to sign, root certificate does not match private key")
  85. }
  86. issuer, err := caCert.Sha256Sum()
  87. if err != nil {
  88. return fmt.Errorf("error while getting -ca-crt fingerprint: %s", err)
  89. }
  90. if caCert.Expired(time.Now()) {
  91. return fmt.Errorf("ca certificate is expired")
  92. }
  93. // if no duration is given, expire one second before the root expires
  94. if *sf.duration <= 0 {
  95. *sf.duration = time.Until(caCert.Details.NotAfter) - time.Second*1
  96. }
  97. ip, ipNet, err := net.ParseCIDR(*sf.ip)
  98. if err != nil {
  99. return newHelpErrorf("invalid ip definition: %s", err)
  100. }
  101. if ip.To4() == nil {
  102. return newHelpErrorf("invalid ip definition: can only be ipv4, have %s", *sf.ip)
  103. }
  104. ipNet.IP = ip
  105. groups := []string{}
  106. if *sf.groups != "" {
  107. for _, rg := range strings.Split(*sf.groups, ",") {
  108. g := strings.TrimSpace(rg)
  109. if g != "" {
  110. groups = append(groups, g)
  111. }
  112. }
  113. }
  114. subnets := []*net.IPNet{}
  115. if *sf.subnets != "" {
  116. for _, rs := range strings.Split(*sf.subnets, ",") {
  117. rs := strings.Trim(rs, " ")
  118. if rs != "" {
  119. _, s, err := net.ParseCIDR(rs)
  120. if err != nil {
  121. return newHelpErrorf("invalid subnet definition: %s", err)
  122. }
  123. if s.IP.To4() == nil {
  124. return newHelpErrorf("invalid subnet definition: can only be ipv4, have %s", rs)
  125. }
  126. subnets = append(subnets, s)
  127. }
  128. }
  129. }
  130. var pub, rawPriv []byte
  131. if *sf.inPubPath != "" {
  132. rawPub, err := ioutil.ReadFile(*sf.inPubPath)
  133. if err != nil {
  134. return fmt.Errorf("error while reading in-pub: %s", err)
  135. }
  136. pub, _, err = cert.UnmarshalX25519PublicKey(rawPub)
  137. if err != nil {
  138. return fmt.Errorf("error while parsing in-pub: %s", err)
  139. }
  140. } else {
  141. pub, rawPriv = x25519Keypair()
  142. }
  143. nc := cert.NebulaCertificate{
  144. Details: cert.NebulaCertificateDetails{
  145. Name: *sf.name,
  146. Ips: []*net.IPNet{ipNet},
  147. Groups: groups,
  148. Subnets: subnets,
  149. NotBefore: time.Now(),
  150. NotAfter: time.Now().Add(*sf.duration),
  151. PublicKey: pub,
  152. IsCA: false,
  153. Issuer: issuer,
  154. },
  155. }
  156. if err := nc.CheckRootConstrains(caCert); err != nil {
  157. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  158. }
  159. if *sf.outKeyPath == "" {
  160. *sf.outKeyPath = *sf.name + ".key"
  161. }
  162. if *sf.outCertPath == "" {
  163. *sf.outCertPath = *sf.name + ".crt"
  164. }
  165. if _, err := os.Stat(*sf.outCertPath); err == nil {
  166. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  167. }
  168. err = nc.Sign(caKey)
  169. if err != nil {
  170. return fmt.Errorf("error while signing: %s", err)
  171. }
  172. if *sf.inPubPath == "" {
  173. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  174. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  175. }
  176. err = ioutil.WriteFile(*sf.outKeyPath, cert.MarshalX25519PrivateKey(rawPriv), 0600)
  177. if err != nil {
  178. return fmt.Errorf("error while writing out-key: %s", err)
  179. }
  180. }
  181. b, err := nc.MarshalToPEM()
  182. if err != nil {
  183. return fmt.Errorf("error while marshalling certificate: %s", err)
  184. }
  185. err = ioutil.WriteFile(*sf.outCertPath, b, 0600)
  186. if err != nil {
  187. return fmt.Errorf("error while writing out-crt: %s", err)
  188. }
  189. if *sf.outQRPath != "" {
  190. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  191. if err != nil {
  192. return fmt.Errorf("error while generating qr code: %s", err)
  193. }
  194. err = ioutil.WriteFile(*sf.outQRPath, b, 0600)
  195. if err != nil {
  196. return fmt.Errorf("error while writing out-qr: %s", err)
  197. }
  198. }
  199. return nil
  200. }
  201. func x25519Keypair() ([]byte, []byte) {
  202. privkey := make([]byte, 32)
  203. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  204. panic(err)
  205. }
  206. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  207. if err != nil {
  208. panic(err)
  209. }
  210. return pubkey, privkey
  211. }
  212. func signSummary() string {
  213. return "sign <flags>: create and sign a certificate"
  214. }
  215. func signHelp(out io.Writer) {
  216. sf := newSignFlags()
  217. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  218. sf.set.SetOutput(out)
  219. sf.set.PrintDefaults()
  220. }