sign.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. 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. ipNet.IP = ip
  102. groups := []string{}
  103. if *sf.groups != "" {
  104. for _, rg := range strings.Split(*sf.groups, ",") {
  105. g := strings.TrimSpace(rg)
  106. if g != "" {
  107. groups = append(groups, g)
  108. }
  109. }
  110. }
  111. subnets := []*net.IPNet{}
  112. if *sf.subnets != "" {
  113. for _, rs := range strings.Split(*sf.subnets, ",") {
  114. rs := strings.Trim(rs, " ")
  115. if rs != "" {
  116. _, s, err := net.ParseCIDR(rs)
  117. if err != nil {
  118. return newHelpErrorf("invalid subnet definition: %s", err)
  119. }
  120. subnets = append(subnets, s)
  121. }
  122. }
  123. }
  124. var pub, rawPriv []byte
  125. if *sf.inPubPath != "" {
  126. rawPub, err := ioutil.ReadFile(*sf.inPubPath)
  127. if err != nil {
  128. return fmt.Errorf("error while reading in-pub: %s", err)
  129. }
  130. pub, _, err = cert.UnmarshalX25519PublicKey(rawPub)
  131. if err != nil {
  132. return fmt.Errorf("error while parsing in-pub: %s", err)
  133. }
  134. } else {
  135. pub, rawPriv = x25519Keypair()
  136. }
  137. nc := cert.NebulaCertificate{
  138. Details: cert.NebulaCertificateDetails{
  139. Name: *sf.name,
  140. Ips: []*net.IPNet{ipNet},
  141. Groups: groups,
  142. Subnets: subnets,
  143. NotBefore: time.Now(),
  144. NotAfter: time.Now().Add(*sf.duration),
  145. PublicKey: pub,
  146. IsCA: false,
  147. Issuer: issuer,
  148. },
  149. }
  150. if err := nc.CheckRootConstrains(caCert); err != nil {
  151. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  152. }
  153. if *sf.outKeyPath == "" {
  154. *sf.outKeyPath = *sf.name + ".key"
  155. }
  156. if *sf.outCertPath == "" {
  157. *sf.outCertPath = *sf.name + ".crt"
  158. }
  159. if _, err := os.Stat(*sf.outCertPath); err == nil {
  160. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  161. }
  162. err = nc.Sign(caKey)
  163. if err != nil {
  164. return fmt.Errorf("error while signing: %s", err)
  165. }
  166. if *sf.inPubPath == "" {
  167. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  168. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  169. }
  170. err = ioutil.WriteFile(*sf.outKeyPath, cert.MarshalX25519PrivateKey(rawPriv), 0600)
  171. if err != nil {
  172. return fmt.Errorf("error while writing out-key: %s", err)
  173. }
  174. }
  175. b, err := nc.MarshalToPEM()
  176. if err != nil {
  177. return fmt.Errorf("error while marshalling certificate: %s", err)
  178. }
  179. err = ioutil.WriteFile(*sf.outCertPath, b, 0600)
  180. if err != nil {
  181. return fmt.Errorf("error while writing out-crt: %s", err)
  182. }
  183. if *sf.outQRPath != "" {
  184. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  185. if err != nil {
  186. return fmt.Errorf("error while generating qr code: %s", err)
  187. }
  188. err = ioutil.WriteFile(*sf.outQRPath, b, 0600)
  189. if err != nil {
  190. return fmt.Errorf("error while writing out-qr: %s", err)
  191. }
  192. }
  193. return nil
  194. }
  195. func x25519Keypair() ([]byte, []byte) {
  196. var pubkey, privkey [32]byte
  197. if _, err := io.ReadFull(rand.Reader, privkey[:]); err != nil {
  198. panic(err)
  199. }
  200. curve25519.ScalarBaseMult(&pubkey, &privkey)
  201. return pubkey[:], privkey[:]
  202. }
  203. func signSummary() string {
  204. return "sign <flags>: create and sign a certificate"
  205. }
  206. func signHelp(out io.Writer) {
  207. sf := newSignFlags()
  208. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  209. sf.set.SetOutput(out)
  210. sf.set.PrintDefaults()
  211. }