sign.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "flag"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "os"
  11. "strings"
  12. "time"
  13. "github.com/skip2/go-qrcode"
  14. "github.com/slackhq/nebula/cert"
  15. "golang.org/x/crypto/curve25519"
  16. )
  17. type signFlags struct {
  18. set *flag.FlagSet
  19. caKeyPath *string
  20. caCertPath *string
  21. name *string
  22. ip *string
  23. duration *time.Duration
  24. inPubPath *string
  25. outKeyPath *string
  26. outCertPath *string
  27. outQRPath *string
  28. groups *string
  29. subnets *string
  30. }
  31. func newSignFlags() *signFlags {
  32. sf := signFlags{set: flag.NewFlagSet("sign", flag.ContinueOnError)}
  33. sf.set.Usage = func() {}
  34. sf.caKeyPath = sf.set.String("ca-key", "ca.key", "Optional: path to the signing CA key")
  35. sf.caCertPath = sf.set.String("ca-crt", "ca.crt", "Optional: path to the signing CA cert")
  36. sf.name = sf.set.String("name", "", "Required: name of the cert, usually a hostname")
  37. sf.ip = sf.set.String("ip", "", "Required: ipv4 address and network in CIDR notation to assign the cert")
  38. 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\"")
  39. sf.inPubPath = sf.set.String("in-pub", "", "Optional (if out-key not set): path to read a previously generated public key")
  40. sf.outKeyPath = sf.set.String("out-key", "", "Optional (if in-pub not set): path to write the private key to")
  41. sf.outCertPath = sf.set.String("out-crt", "", "Optional: path to write the certificate to")
  42. sf.outQRPath = sf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
  43. sf.groups = sf.set.String("groups", "", "Optional: comma separated list of groups")
  44. sf.subnets = sf.set.String("subnets", "", "Optional: comma separated list of ipv4 address and network in CIDR notation. Subnets this cert can serve for")
  45. return &sf
  46. }
  47. func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error {
  48. sf := newSignFlags()
  49. err := sf.set.Parse(args)
  50. if err != nil {
  51. return err
  52. }
  53. if err := mustFlagString("ca-key", sf.caKeyPath); err != nil {
  54. return err
  55. }
  56. if err := mustFlagString("ca-crt", sf.caCertPath); err != nil {
  57. return err
  58. }
  59. if err := mustFlagString("name", sf.name); err != nil {
  60. return err
  61. }
  62. if err := mustFlagString("ip", sf.ip); err != nil {
  63. return err
  64. }
  65. if *sf.inPubPath != "" && *sf.outKeyPath != "" {
  66. return newHelpErrorf("cannot set both -in-pub and -out-key")
  67. }
  68. rawCAKey, err := ioutil.ReadFile(*sf.caKeyPath)
  69. if err != nil {
  70. return fmt.Errorf("error while reading ca-key: %s", err)
  71. }
  72. var caKey ed25519.PrivateKey
  73. // naively attempt to decode the private key as though it is not encrypted
  74. caKey, _, err = cert.UnmarshalEd25519PrivateKey(rawCAKey)
  75. if err == cert.ErrPrivateKeyEncrypted {
  76. // ask for a passphrase until we get one
  77. var passphrase []byte
  78. for i := 0; i < 5; i++ {
  79. out.Write([]byte("Enter passphrase: "))
  80. passphrase, err = pr.ReadPassword()
  81. if err == ErrNoTerminal {
  82. return fmt.Errorf("ca-key is encrypted and must be decrypted interactively")
  83. } else if err != nil {
  84. return fmt.Errorf("error reading password: %s", err)
  85. }
  86. if len(passphrase) > 0 {
  87. break
  88. }
  89. }
  90. if len(passphrase) == 0 {
  91. return fmt.Errorf("cannot open encrypted ca-key without passphrase")
  92. }
  93. caKey, _, err = cert.DecryptAndUnmarshalEd25519PrivateKey(passphrase, rawCAKey)
  94. if err != nil {
  95. return fmt.Errorf("error while parsing encrypted ca-key: %s", err)
  96. }
  97. } else if err != nil {
  98. return fmt.Errorf("error while parsing ca-key: %s", err)
  99. }
  100. rawCACert, err := ioutil.ReadFile(*sf.caCertPath)
  101. if err != nil {
  102. return fmt.Errorf("error while reading ca-crt: %s", err)
  103. }
  104. caCert, _, err := cert.UnmarshalNebulaCertificateFromPEM(rawCACert)
  105. if err != nil {
  106. return fmt.Errorf("error while parsing ca-crt: %s", err)
  107. }
  108. if err := caCert.VerifyPrivateKey(caKey); err != nil {
  109. return fmt.Errorf("refusing to sign, root certificate does not match private key")
  110. }
  111. issuer, err := caCert.Sha256Sum()
  112. if err != nil {
  113. return fmt.Errorf("error while getting -ca-crt fingerprint: %s", err)
  114. }
  115. if caCert.Expired(time.Now()) {
  116. return fmt.Errorf("ca certificate is expired")
  117. }
  118. // if no duration is given, expire one second before the root expires
  119. if *sf.duration <= 0 {
  120. *sf.duration = time.Until(caCert.Details.NotAfter) - time.Second*1
  121. }
  122. ip, ipNet, err := net.ParseCIDR(*sf.ip)
  123. if err != nil {
  124. return newHelpErrorf("invalid ip definition: %s", err)
  125. }
  126. if ip.To4() == nil {
  127. return newHelpErrorf("invalid ip definition: can only be ipv4, have %s", *sf.ip)
  128. }
  129. ipNet.IP = ip
  130. groups := []string{}
  131. if *sf.groups != "" {
  132. for _, rg := range strings.Split(*sf.groups, ",") {
  133. g := strings.TrimSpace(rg)
  134. if g != "" {
  135. groups = append(groups, g)
  136. }
  137. }
  138. }
  139. subnets := []*net.IPNet{}
  140. if *sf.subnets != "" {
  141. for _, rs := range strings.Split(*sf.subnets, ",") {
  142. rs := strings.Trim(rs, " ")
  143. if rs != "" {
  144. _, s, err := net.ParseCIDR(rs)
  145. if err != nil {
  146. return newHelpErrorf("invalid subnet definition: %s", err)
  147. }
  148. if s.IP.To4() == nil {
  149. return newHelpErrorf("invalid subnet definition: can only be ipv4, have %s", rs)
  150. }
  151. subnets = append(subnets, s)
  152. }
  153. }
  154. }
  155. var pub, rawPriv []byte
  156. if *sf.inPubPath != "" {
  157. rawPub, err := ioutil.ReadFile(*sf.inPubPath)
  158. if err != nil {
  159. return fmt.Errorf("error while reading in-pub: %s", err)
  160. }
  161. pub, _, err = cert.UnmarshalX25519PublicKey(rawPub)
  162. if err != nil {
  163. return fmt.Errorf("error while parsing in-pub: %s", err)
  164. }
  165. } else {
  166. pub, rawPriv = x25519Keypair()
  167. }
  168. nc := cert.NebulaCertificate{
  169. Details: cert.NebulaCertificateDetails{
  170. Name: *sf.name,
  171. Ips: []*net.IPNet{ipNet},
  172. Groups: groups,
  173. Subnets: subnets,
  174. NotBefore: time.Now(),
  175. NotAfter: time.Now().Add(*sf.duration),
  176. PublicKey: pub,
  177. IsCA: false,
  178. Issuer: issuer,
  179. },
  180. }
  181. if err := nc.CheckRootConstrains(caCert); err != nil {
  182. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  183. }
  184. if *sf.outKeyPath == "" {
  185. *sf.outKeyPath = *sf.name + ".key"
  186. }
  187. if *sf.outCertPath == "" {
  188. *sf.outCertPath = *sf.name + ".crt"
  189. }
  190. if _, err := os.Stat(*sf.outCertPath); err == nil {
  191. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  192. }
  193. err = nc.Sign(caKey)
  194. if err != nil {
  195. return fmt.Errorf("error while signing: %s", err)
  196. }
  197. if *sf.inPubPath == "" {
  198. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  199. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  200. }
  201. err = ioutil.WriteFile(*sf.outKeyPath, cert.MarshalX25519PrivateKey(rawPriv), 0600)
  202. if err != nil {
  203. return fmt.Errorf("error while writing out-key: %s", err)
  204. }
  205. }
  206. b, err := nc.MarshalToPEM()
  207. if err != nil {
  208. return fmt.Errorf("error while marshalling certificate: %s", err)
  209. }
  210. err = ioutil.WriteFile(*sf.outCertPath, b, 0600)
  211. if err != nil {
  212. return fmt.Errorf("error while writing out-crt: %s", err)
  213. }
  214. if *sf.outQRPath != "" {
  215. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  216. if err != nil {
  217. return fmt.Errorf("error while generating qr code: %s", err)
  218. }
  219. err = ioutil.WriteFile(*sf.outQRPath, b, 0600)
  220. if err != nil {
  221. return fmt.Errorf("error while writing out-qr: %s", err)
  222. }
  223. }
  224. return nil
  225. }
  226. func x25519Keypair() ([]byte, []byte) {
  227. privkey := make([]byte, 32)
  228. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  229. panic(err)
  230. }
  231. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  232. if err != nil {
  233. panic(err)
  234. }
  235. return pubkey, privkey
  236. }
  237. func signSummary() string {
  238. return "sign <flags>: create and sign a certificate"
  239. }
  240. func signHelp(out io.Writer) {
  241. sf := newSignFlags()
  242. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  243. sf.set.SetOutput(out)
  244. sf.set.PrintDefaults()
  245. }