sign.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package main
  2. import (
  3. "crypto/ecdh"
  4. "crypto/rand"
  5. "flag"
  6. "fmt"
  7. "io"
  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, pr PasswordReader) 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 := os.ReadFile(*sf.caKeyPath)
  68. if err != nil {
  69. return fmt.Errorf("error while reading ca-key: %s", err)
  70. }
  71. var curve cert.Curve
  72. var caKey []byte
  73. // naively attempt to decode the private key as though it is not encrypted
  74. caKey, _, curve, err = cert.UnmarshalSigningPrivateKey(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. curve, caKey, _, err = cert.DecryptAndUnmarshalSigningPrivateKey(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 := os.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(curve, 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 := os.ReadFile(*sf.inPubPath)
  158. if err != nil {
  159. return fmt.Errorf("error while reading in-pub: %s", err)
  160. }
  161. var pubCurve cert.Curve
  162. pub, _, pubCurve, err = cert.UnmarshalPublicKey(rawPub)
  163. if err != nil {
  164. return fmt.Errorf("error while parsing in-pub: %s", err)
  165. }
  166. if pubCurve != curve {
  167. return fmt.Errorf("curve of in-pub does not match ca")
  168. }
  169. } else {
  170. pub, rawPriv = newKeypair(curve)
  171. }
  172. nc := cert.NebulaCertificate{
  173. Details: cert.NebulaCertificateDetails{
  174. Name: *sf.name,
  175. Ips: []*net.IPNet{ipNet},
  176. Groups: groups,
  177. Subnets: subnets,
  178. NotBefore: time.Now(),
  179. NotAfter: time.Now().Add(*sf.duration),
  180. PublicKey: pub,
  181. IsCA: false,
  182. Issuer: issuer,
  183. Curve: curve,
  184. },
  185. }
  186. if err := nc.CheckRootConstrains(caCert); err != nil {
  187. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  188. }
  189. if *sf.outKeyPath == "" {
  190. *sf.outKeyPath = *sf.name + ".key"
  191. }
  192. if *sf.outCertPath == "" {
  193. *sf.outCertPath = *sf.name + ".crt"
  194. }
  195. if _, err := os.Stat(*sf.outCertPath); err == nil {
  196. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  197. }
  198. err = nc.Sign(curve, caKey)
  199. if err != nil {
  200. return fmt.Errorf("error while signing: %s", err)
  201. }
  202. if *sf.inPubPath == "" {
  203. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  204. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  205. }
  206. err = os.WriteFile(*sf.outKeyPath, cert.MarshalPrivateKey(curve, rawPriv), 0600)
  207. if err != nil {
  208. return fmt.Errorf("error while writing out-key: %s", err)
  209. }
  210. }
  211. b, err := nc.MarshalToPEM()
  212. if err != nil {
  213. return fmt.Errorf("error while marshalling certificate: %s", err)
  214. }
  215. err = os.WriteFile(*sf.outCertPath, b, 0600)
  216. if err != nil {
  217. return fmt.Errorf("error while writing out-crt: %s", err)
  218. }
  219. if *sf.outQRPath != "" {
  220. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  221. if err != nil {
  222. return fmt.Errorf("error while generating qr code: %s", err)
  223. }
  224. err = os.WriteFile(*sf.outQRPath, b, 0600)
  225. if err != nil {
  226. return fmt.Errorf("error while writing out-qr: %s", err)
  227. }
  228. }
  229. return nil
  230. }
  231. func newKeypair(curve cert.Curve) ([]byte, []byte) {
  232. switch curve {
  233. case cert.Curve_CURVE25519:
  234. return x25519Keypair()
  235. case cert.Curve_P256:
  236. return p256Keypair()
  237. default:
  238. return nil, nil
  239. }
  240. }
  241. func x25519Keypair() ([]byte, []byte) {
  242. privkey := make([]byte, 32)
  243. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  244. panic(err)
  245. }
  246. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  247. if err != nil {
  248. panic(err)
  249. }
  250. return pubkey, privkey
  251. }
  252. func p256Keypair() ([]byte, []byte) {
  253. privkey, err := ecdh.P256().GenerateKey(rand.Reader)
  254. if err != nil {
  255. panic(err)
  256. }
  257. pubkey := privkey.PublicKey()
  258. return pubkey.Bytes(), privkey.Bytes()
  259. }
  260. func signSummary() string {
  261. return "sign <flags>: create and sign a certificate"
  262. }
  263. func signHelp(out io.Writer) {
  264. sf := newSignFlags()
  265. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  266. sf.set.SetOutput(out)
  267. sf.set.PrintDefaults()
  268. }