sign.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. "github.com/slackhq/nebula/pkclient"
  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. p11url *string
  31. }
  32. func newSignFlags() *signFlags {
  33. sf := signFlags{set: flag.NewFlagSet("sign", flag.ContinueOnError)}
  34. sf.set.Usage = func() {}
  35. sf.caKeyPath = sf.set.String("ca-key", "ca.key", "Optional: path to the signing CA key")
  36. sf.caCertPath = sf.set.String("ca-crt", "ca.crt", "Optional: path to the signing CA cert")
  37. sf.name = sf.set.String("name", "", "Required: name of the cert, usually a hostname")
  38. sf.ip = sf.set.String("ip", "", "Required: ipv4 address and network in CIDR notation to assign the cert")
  39. 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\"")
  40. sf.inPubPath = sf.set.String("in-pub", "", "Optional (if out-key not set): path to read a previously generated public key")
  41. sf.outKeyPath = sf.set.String("out-key", "", "Optional (if in-pub not set): path to write the private key to")
  42. sf.outCertPath = sf.set.String("out-crt", "", "Optional: path to write the certificate to")
  43. sf.outQRPath = sf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
  44. sf.groups = sf.set.String("groups", "", "Optional: comma separated list of groups")
  45. sf.subnets = sf.set.String("subnets", "", "Optional: comma separated list of ipv4 address and network in CIDR notation. Subnets this cert can serve for")
  46. sf.p11url = p11Flag(sf.set)
  47. return &sf
  48. }
  49. func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error {
  50. sf := newSignFlags()
  51. err := sf.set.Parse(args)
  52. if err != nil {
  53. return err
  54. }
  55. isP11 := len(*sf.p11url) > 0
  56. if !isP11 {
  57. if err := mustFlagString("ca-key", sf.caKeyPath); err != nil {
  58. return err
  59. }
  60. }
  61. if err := mustFlagString("ca-crt", sf.caCertPath); err != nil {
  62. return err
  63. }
  64. if err := mustFlagString("name", sf.name); err != nil {
  65. return err
  66. }
  67. if err := mustFlagString("ip", sf.ip); err != nil {
  68. return err
  69. }
  70. if !isP11 && *sf.inPubPath != "" && *sf.outKeyPath != "" {
  71. return newHelpErrorf("cannot set both -in-pub and -out-key")
  72. }
  73. var curve cert.Curve
  74. var caKey []byte
  75. if !isP11 {
  76. var rawCAKey []byte
  77. rawCAKey, err := os.ReadFile(*sf.caKeyPath)
  78. if err != nil {
  79. return fmt.Errorf("error while reading ca-key: %s", err)
  80. }
  81. // naively attempt to decode the private key as though it is not encrypted
  82. caKey, _, curve, err = cert.UnmarshalSigningPrivateKey(rawCAKey)
  83. if err == cert.ErrPrivateKeyEncrypted {
  84. // ask for a passphrase until we get one
  85. var passphrase []byte
  86. for i := 0; i < 5; i++ {
  87. out.Write([]byte("Enter passphrase: "))
  88. passphrase, err = pr.ReadPassword()
  89. if err == ErrNoTerminal {
  90. return fmt.Errorf("ca-key is encrypted and must be decrypted interactively")
  91. } else if err != nil {
  92. return fmt.Errorf("error reading password: %s", err)
  93. }
  94. if len(passphrase) > 0 {
  95. break
  96. }
  97. }
  98. if len(passphrase) == 0 {
  99. return fmt.Errorf("cannot open encrypted ca-key without passphrase")
  100. }
  101. curve, caKey, _, err = cert.DecryptAndUnmarshalSigningPrivateKey(passphrase, rawCAKey)
  102. if err != nil {
  103. return fmt.Errorf("error while parsing encrypted ca-key: %s", err)
  104. }
  105. } else if err != nil {
  106. return fmt.Errorf("error while parsing ca-key: %s", err)
  107. }
  108. }
  109. rawCACert, err := os.ReadFile(*sf.caCertPath)
  110. if err != nil {
  111. return fmt.Errorf("error while reading ca-crt: %s", err)
  112. }
  113. caCert, _, err := cert.UnmarshalNebulaCertificateFromPEM(rawCACert)
  114. if err != nil {
  115. return fmt.Errorf("error while parsing ca-crt: %s", err)
  116. }
  117. if !isP11 {
  118. if err := caCert.VerifyPrivateKey(curve, caKey); err != nil {
  119. return fmt.Errorf("refusing to sign, root certificate does not match private key")
  120. }
  121. }
  122. issuer, err := caCert.Sha256Sum()
  123. if err != nil {
  124. return fmt.Errorf("error while getting -ca-crt fingerprint: %s", err)
  125. }
  126. if caCert.Expired(time.Now()) {
  127. return fmt.Errorf("ca certificate is expired")
  128. }
  129. // if no duration is given, expire one second before the root expires
  130. if *sf.duration <= 0 {
  131. *sf.duration = time.Until(caCert.Details.NotAfter) - time.Second*1
  132. }
  133. ip, ipNet, err := net.ParseCIDR(*sf.ip)
  134. if err != nil {
  135. return newHelpErrorf("invalid ip definition: %s", err)
  136. }
  137. if ip.To4() == nil {
  138. return newHelpErrorf("invalid ip definition: can only be ipv4, have %s", *sf.ip)
  139. }
  140. ipNet.IP = ip
  141. groups := []string{}
  142. if *sf.groups != "" {
  143. for _, rg := range strings.Split(*sf.groups, ",") {
  144. g := strings.TrimSpace(rg)
  145. if g != "" {
  146. groups = append(groups, g)
  147. }
  148. }
  149. }
  150. subnets := []*net.IPNet{}
  151. if *sf.subnets != "" {
  152. for _, rs := range strings.Split(*sf.subnets, ",") {
  153. rs := strings.Trim(rs, " ")
  154. if rs != "" {
  155. _, s, err := net.ParseCIDR(rs)
  156. if err != nil {
  157. return newHelpErrorf("invalid subnet definition: %s", err)
  158. }
  159. if s.IP.To4() == nil {
  160. return newHelpErrorf("invalid subnet definition: can only be ipv4, have %s", rs)
  161. }
  162. subnets = append(subnets, s)
  163. }
  164. }
  165. }
  166. var pub, rawPriv []byte
  167. var p11Client *pkclient.PKClient
  168. if isP11 {
  169. curve = cert.Curve_P256
  170. p11Client, err = pkclient.FromUrl(*sf.p11url)
  171. if err != nil {
  172. return fmt.Errorf("error while creating PKCS#11 client: %w", err)
  173. }
  174. defer func(client *pkclient.PKClient) {
  175. _ = client.Close()
  176. }(p11Client)
  177. }
  178. if *sf.inPubPath != "" {
  179. var pubCurve cert.Curve
  180. rawPub, err := os.ReadFile(*sf.inPubPath)
  181. if err != nil {
  182. return fmt.Errorf("error while reading in-pub: %s", err)
  183. }
  184. pub, _, pubCurve, err = cert.UnmarshalPublicKey(rawPub)
  185. if err != nil {
  186. return fmt.Errorf("error while parsing in-pub: %s", err)
  187. }
  188. if pubCurve != curve {
  189. return fmt.Errorf("curve of in-pub does not match ca")
  190. }
  191. } else if isP11 {
  192. pub, err = p11Client.GetPubKey()
  193. if err != nil {
  194. return fmt.Errorf("error while getting public key with PKCS#11: %w", err)
  195. }
  196. } else {
  197. pub, rawPriv = newKeypair(curve)
  198. }
  199. nc := cert.NebulaCertificate{
  200. Details: cert.NebulaCertificateDetails{
  201. Name: *sf.name,
  202. Ips: []*net.IPNet{ipNet},
  203. Groups: groups,
  204. Subnets: subnets,
  205. NotBefore: time.Now(),
  206. NotAfter: time.Now().Add(*sf.duration),
  207. PublicKey: pub,
  208. IsCA: false,
  209. Issuer: issuer,
  210. Curve: curve,
  211. },
  212. Pkcs11Backed: isP11,
  213. }
  214. if p11Client == nil {
  215. err = nc.Sign(curve, caKey)
  216. if err != nil {
  217. return fmt.Errorf("error while signing: %w", err)
  218. }
  219. } else {
  220. err = nc.SignPkcs11(curve, p11Client)
  221. if err != nil {
  222. return fmt.Errorf("error while signing with PKCS#11: %w", err)
  223. }
  224. }
  225. if err := nc.CheckRootConstrains(caCert); err != nil {
  226. return fmt.Errorf("refusing to sign, root certificate constraints violated: %s", err)
  227. }
  228. if *sf.outKeyPath == "" {
  229. *sf.outKeyPath = *sf.name + ".key"
  230. }
  231. if *sf.outCertPath == "" {
  232. *sf.outCertPath = *sf.name + ".crt"
  233. }
  234. if _, err := os.Stat(*sf.outCertPath); err == nil {
  235. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  236. }
  237. if !isP11 && *sf.inPubPath == "" {
  238. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  239. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  240. }
  241. err = os.WriteFile(*sf.outKeyPath, cert.MarshalPrivateKey(curve, rawPriv), 0600)
  242. if err != nil {
  243. return fmt.Errorf("error while writing out-key: %s", err)
  244. }
  245. }
  246. b, err := nc.MarshalToPEM()
  247. if err != nil {
  248. return fmt.Errorf("error while marshalling certificate: %s", err)
  249. }
  250. err = os.WriteFile(*sf.outCertPath, b, 0600)
  251. if err != nil {
  252. return fmt.Errorf("error while writing out-crt: %s", err)
  253. }
  254. if *sf.outQRPath != "" {
  255. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  256. if err != nil {
  257. return fmt.Errorf("error while generating qr code: %s", err)
  258. }
  259. err = os.WriteFile(*sf.outQRPath, b, 0600)
  260. if err != nil {
  261. return fmt.Errorf("error while writing out-qr: %s", err)
  262. }
  263. }
  264. return nil
  265. }
  266. func newKeypair(curve cert.Curve) ([]byte, []byte) {
  267. switch curve {
  268. case cert.Curve_CURVE25519:
  269. return x25519Keypair()
  270. case cert.Curve_P256:
  271. return p256Keypair()
  272. default:
  273. return nil, nil
  274. }
  275. }
  276. func x25519Keypair() ([]byte, []byte) {
  277. privkey := make([]byte, 32)
  278. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  279. panic(err)
  280. }
  281. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  282. if err != nil {
  283. panic(err)
  284. }
  285. return pubkey, privkey
  286. }
  287. func p256Keypair() ([]byte, []byte) {
  288. privkey, err := ecdh.P256().GenerateKey(rand.Reader)
  289. if err != nil {
  290. panic(err)
  291. }
  292. pubkey := privkey.PublicKey()
  293. return pubkey.Bytes(), privkey.Bytes()
  294. }
  295. func signSummary() string {
  296. return "sign <flags>: create and sign a certificate"
  297. }
  298. func signHelp(out io.Writer) {
  299. sf := newSignFlags()
  300. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  301. sf.set.SetOutput(out)
  302. sf.set.PrintDefaults()
  303. }