sign.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package main
  2. import (
  3. "crypto/ecdh"
  4. "crypto/rand"
  5. "flag"
  6. "fmt"
  7. "io"
  8. "net/netip"
  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.UnmarshalSigningPrivateKeyFromPEM(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.UnmarshalCertificateFromPEM(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. if caCert.Expired(time.Now()) {
  123. return fmt.Errorf("ca certificate is expired")
  124. }
  125. // if no duration is given, expire one second before the root expires
  126. if *sf.duration <= 0 {
  127. *sf.duration = time.Until(caCert.NotAfter()) - time.Second*1
  128. }
  129. network, err := netip.ParsePrefix(*sf.ip)
  130. if err != nil {
  131. return newHelpErrorf("invalid ip definition: %s", *sf.ip)
  132. }
  133. if !network.Addr().Is4() {
  134. return newHelpErrorf("invalid ip definition: can only be ipv4, have %s", *sf.ip)
  135. }
  136. var groups []string
  137. if *sf.groups != "" {
  138. for _, rg := range strings.Split(*sf.groups, ",") {
  139. g := strings.TrimSpace(rg)
  140. if g != "" {
  141. groups = append(groups, g)
  142. }
  143. }
  144. }
  145. var subnets []netip.Prefix
  146. if *sf.subnets != "" {
  147. for _, rs := range strings.Split(*sf.subnets, ",") {
  148. rs := strings.Trim(rs, " ")
  149. if rs != "" {
  150. s, err := netip.ParsePrefix(rs)
  151. if err != nil {
  152. return newHelpErrorf("invalid subnet definition: %s", rs)
  153. }
  154. if !s.Addr().Is4() {
  155. return newHelpErrorf("invalid subnet definition: can only be ipv4, have %s", rs)
  156. }
  157. subnets = append(subnets, s)
  158. }
  159. }
  160. }
  161. var pub, rawPriv []byte
  162. var p11Client *pkclient.PKClient
  163. if isP11 {
  164. curve = cert.Curve_P256
  165. p11Client, err = pkclient.FromUrl(*sf.p11url)
  166. if err != nil {
  167. return fmt.Errorf("error while creating PKCS#11 client: %w", err)
  168. }
  169. defer func(client *pkclient.PKClient) {
  170. _ = client.Close()
  171. }(p11Client)
  172. }
  173. if *sf.inPubPath != "" {
  174. var pubCurve cert.Curve
  175. rawPub, err := os.ReadFile(*sf.inPubPath)
  176. if err != nil {
  177. return fmt.Errorf("error while reading in-pub: %s", err)
  178. }
  179. pub, _, pubCurve, err = cert.UnmarshalPublicKeyFromPEM(rawPub)
  180. if err != nil {
  181. return fmt.Errorf("error while parsing in-pub: %s", err)
  182. }
  183. if pubCurve != curve {
  184. return fmt.Errorf("curve of in-pub does not match ca")
  185. }
  186. } else if isP11 {
  187. pub, err = p11Client.GetPubKey()
  188. if err != nil {
  189. return fmt.Errorf("error while getting public key with PKCS#11: %w", err)
  190. }
  191. } else {
  192. pub, rawPriv = newKeypair(curve)
  193. }
  194. t := &cert.TBSCertificate{
  195. Version: cert.Version1,
  196. Name: *sf.name,
  197. Networks: []netip.Prefix{network},
  198. Groups: groups,
  199. UnsafeNetworks: subnets,
  200. NotBefore: time.Now(),
  201. NotAfter: time.Now().Add(*sf.duration),
  202. PublicKey: pub,
  203. IsCA: false,
  204. Curve: curve,
  205. }
  206. if *sf.outKeyPath == "" {
  207. *sf.outKeyPath = *sf.name + ".key"
  208. }
  209. if *sf.outCertPath == "" {
  210. *sf.outCertPath = *sf.name + ".crt"
  211. }
  212. if _, err := os.Stat(*sf.outCertPath); err == nil {
  213. return fmt.Errorf("refusing to overwrite existing cert: %s", *sf.outCertPath)
  214. }
  215. var c cert.Certificate
  216. if p11Client == nil {
  217. c, err = t.Sign(caCert, curve, caKey)
  218. if err != nil {
  219. return fmt.Errorf("error while signing: %w", err)
  220. }
  221. } else {
  222. c, err = t.SignPkcs11(caCert, curve, p11Client)
  223. if err != nil {
  224. return fmt.Errorf("error while signing with PKCS#11: %w", err)
  225. }
  226. }
  227. if !isP11 && *sf.inPubPath == "" {
  228. if _, err := os.Stat(*sf.outKeyPath); err == nil {
  229. return fmt.Errorf("refusing to overwrite existing key: %s", *sf.outKeyPath)
  230. }
  231. err = os.WriteFile(*sf.outKeyPath, cert.MarshalPrivateKeyToPEM(curve, rawPriv), 0600)
  232. if err != nil {
  233. return fmt.Errorf("error while writing out-key: %s", err)
  234. }
  235. }
  236. b, err := c.MarshalPEM()
  237. if err != nil {
  238. return fmt.Errorf("error while marshalling certificate: %s", err)
  239. }
  240. err = os.WriteFile(*sf.outCertPath, b, 0600)
  241. if err != nil {
  242. return fmt.Errorf("error while writing out-crt: %s", err)
  243. }
  244. if *sf.outQRPath != "" {
  245. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  246. if err != nil {
  247. return fmt.Errorf("error while generating qr code: %s", err)
  248. }
  249. err = os.WriteFile(*sf.outQRPath, b, 0600)
  250. if err != nil {
  251. return fmt.Errorf("error while writing out-qr: %s", err)
  252. }
  253. }
  254. return nil
  255. }
  256. func newKeypair(curve cert.Curve) ([]byte, []byte) {
  257. switch curve {
  258. case cert.Curve_CURVE25519:
  259. return x25519Keypair()
  260. case cert.Curve_P256:
  261. return p256Keypair()
  262. default:
  263. return nil, nil
  264. }
  265. }
  266. func x25519Keypair() ([]byte, []byte) {
  267. privkey := make([]byte, 32)
  268. if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
  269. panic(err)
  270. }
  271. pubkey, err := curve25519.X25519(privkey, curve25519.Basepoint)
  272. if err != nil {
  273. panic(err)
  274. }
  275. return pubkey, privkey
  276. }
  277. func p256Keypair() ([]byte, []byte) {
  278. privkey, err := ecdh.P256().GenerateKey(rand.Reader)
  279. if err != nil {
  280. panic(err)
  281. }
  282. pubkey := privkey.PublicKey()
  283. return pubkey.Bytes(), privkey.Bytes()
  284. }
  285. func signSummary() string {
  286. return "sign <flags>: create and sign a certificate"
  287. }
  288. func signHelp(out io.Writer) {
  289. sf := newSignFlags()
  290. out.Write([]byte("Usage of " + os.Args[0] + " " + signSummary() + "\n"))
  291. sf.set.SetOutput(out)
  292. sf.set.PrintDefaults()
  293. }