sign.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package main
  2. import (
  3. "crypto/ecdh"
  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 curve cert.Curve
  73. var caKey []byte
  74. // naively attempt to decode the private key as though it is not encrypted
  75. caKey, _, curve, err = cert.UnmarshalSigningPrivateKey(rawCAKey)
  76. if err == cert.ErrPrivateKeyEncrypted {
  77. // ask for a passphrase until we get one
  78. var passphrase []byte
  79. for i := 0; i < 5; i++ {
  80. out.Write([]byte("Enter passphrase: "))
  81. passphrase, err = pr.ReadPassword()
  82. if err == ErrNoTerminal {
  83. return fmt.Errorf("ca-key is encrypted and must be decrypted interactively")
  84. } else if err != nil {
  85. return fmt.Errorf("error reading password: %s", err)
  86. }
  87. if len(passphrase) > 0 {
  88. break
  89. }
  90. }
  91. if len(passphrase) == 0 {
  92. return fmt.Errorf("cannot open encrypted ca-key without passphrase")
  93. }
  94. curve, caKey, _, err = cert.DecryptAndUnmarshalSigningPrivateKey(passphrase, rawCAKey)
  95. if err != nil {
  96. return fmt.Errorf("error while parsing encrypted ca-key: %s", err)
  97. }
  98. } else if err != nil {
  99. return fmt.Errorf("error while parsing ca-key: %s", err)
  100. }
  101. rawCACert, err := ioutil.ReadFile(*sf.caCertPath)
  102. if err != nil {
  103. return fmt.Errorf("error while reading ca-crt: %s", err)
  104. }
  105. caCert, _, err := cert.UnmarshalNebulaCertificateFromPEM(rawCACert)
  106. if err != nil {
  107. return fmt.Errorf("error while parsing ca-crt: %s", err)
  108. }
  109. if err := caCert.VerifyPrivateKey(curve, caKey); err != nil {
  110. return fmt.Errorf("refusing to sign, root certificate does not match private key")
  111. }
  112. issuer, err := caCert.Sha256Sum()
  113. if err != nil {
  114. return fmt.Errorf("error while getting -ca-crt fingerprint: %s", err)
  115. }
  116. if caCert.Expired(time.Now()) {
  117. return fmt.Errorf("ca certificate is expired")
  118. }
  119. // if no duration is given, expire one second before the root expires
  120. if *sf.duration <= 0 {
  121. *sf.duration = time.Until(caCert.Details.NotAfter) - time.Second*1
  122. }
  123. ip, ipNet, err := net.ParseCIDR(*sf.ip)
  124. if err != nil {
  125. return newHelpErrorf("invalid ip definition: %s", err)
  126. }
  127. if ip.To4() == nil {
  128. return newHelpErrorf("invalid ip definition: can only be ipv4, have %s", *sf.ip)
  129. }
  130. ipNet.IP = ip
  131. groups := []string{}
  132. if *sf.groups != "" {
  133. for _, rg := range strings.Split(*sf.groups, ",") {
  134. g := strings.TrimSpace(rg)
  135. if g != "" {
  136. groups = append(groups, g)
  137. }
  138. }
  139. }
  140. subnets := []*net.IPNet{}
  141. if *sf.subnets != "" {
  142. for _, rs := range strings.Split(*sf.subnets, ",") {
  143. rs := strings.Trim(rs, " ")
  144. if rs != "" {
  145. _, s, err := net.ParseCIDR(rs)
  146. if err != nil {
  147. return newHelpErrorf("invalid subnet definition: %s", err)
  148. }
  149. if s.IP.To4() == nil {
  150. return newHelpErrorf("invalid subnet definition: can only be ipv4, have %s", rs)
  151. }
  152. subnets = append(subnets, s)
  153. }
  154. }
  155. }
  156. var pub, rawPriv []byte
  157. if *sf.inPubPath != "" {
  158. rawPub, err := ioutil.ReadFile(*sf.inPubPath)
  159. if err != nil {
  160. return fmt.Errorf("error while reading in-pub: %s", err)
  161. }
  162. var pubCurve cert.Curve
  163. pub, _, pubCurve, err = cert.UnmarshalPublicKey(rawPub)
  164. if err != nil {
  165. return fmt.Errorf("error while parsing in-pub: %s", err)
  166. }
  167. if pubCurve != curve {
  168. return fmt.Errorf("curve of in-pub does not match ca")
  169. }
  170. } else {
  171. pub, rawPriv = newKeypair(curve)
  172. }
  173. nc := cert.NebulaCertificate{
  174. Details: cert.NebulaCertificateDetails{
  175. Name: *sf.name,
  176. Ips: []*net.IPNet{ipNet},
  177. Groups: groups,
  178. Subnets: subnets,
  179. NotBefore: time.Now(),
  180. NotAfter: time.Now().Add(*sf.duration),
  181. PublicKey: pub,
  182. IsCA: false,
  183. Issuer: issuer,
  184. Curve: curve,
  185. },
  186. }
  187. if err := nc.CheckRootConstrains(caCert); err != nil {
  188. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  189. }
  190. if *sf.outKeyPath == "" {
  191. *sf.outKeyPath = *sf.name + ".key"
  192. }
  193. if *sf.outCertPath == "" {
  194. *sf.outCertPath = *sf.name + ".crt"
  195. }
  196. if _, err := os.Stat(*sf.outCertPath); err == nil {
  197. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  198. }
  199. err = nc.Sign(curve, caKey)
  200. if err != nil {
  201. return fmt.Errorf("error while signing: %s", err)
  202. }
  203. if *sf.inPubPath == "" {
  204. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  205. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  206. }
  207. err = ioutil.WriteFile(*sf.outKeyPath, cert.MarshalPrivateKey(curve, rawPriv), 0600)
  208. if err != nil {
  209. return fmt.Errorf("error while writing out-key: %s", err)
  210. }
  211. }
  212. b, err := nc.MarshalToPEM()
  213. if err != nil {
  214. return fmt.Errorf("error while marshalling certificate: %s", err)
  215. }
  216. err = ioutil.WriteFile(*sf.outCertPath, b, 0600)
  217. if err != nil {
  218. return fmt.Errorf("error while writing out-crt: %s", err)
  219. }
  220. if *sf.outQRPath != "" {
  221. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  222. if err != nil {
  223. return fmt.Errorf("error while generating qr code: %s", err)
  224. }
  225. err = ioutil.WriteFile(*sf.outQRPath, b, 0600)
  226. if err != nil {
  227. return fmt.Errorf("error while writing out-qr: %s", err)
  228. }
  229. }
  230. return nil
  231. }
  232. func newKeypair(curve cert.Curve) ([]byte, []byte) {
  233. switch curve {
  234. case cert.Curve_CURVE25519:
  235. return x25519Keypair()
  236. case cert.Curve_P256:
  237. return p256Keypair()
  238. default:
  239. return nil, nil
  240. }
  241. }
  242. func x25519Keypair() ([]byte, []byte) {
  243. privkey := make([]byte, 32)
  244. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  245. panic(err)
  246. }
  247. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  248. if err != nil {
  249. panic(err)
  250. }
  251. return pubkey, privkey
  252. }
  253. func p256Keypair() ([]byte, []byte) {
  254. privkey, err := ecdh.P256().GenerateKey(rand.Reader)
  255. if err != nil {
  256. panic(err)
  257. }
  258. pubkey := privkey.PublicKey()
  259. return pubkey.Bytes(), privkey.Bytes()
  260. }
  261. func signSummary() string {
  262. return "sign <flags>: create and sign a certificate"
  263. }
  264. func signHelp(out io.Writer) {
  265. sf := newSignFlags()
  266. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  267. sf.set.SetOutput(out)
  268. sf.set.PrintDefaults()
  269. }