ca.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package main
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/elliptic"
  5. "crypto/fips140"
  6. "crypto/rand"
  7. "errors"
  8. "flag"
  9. "fmt"
  10. "io"
  11. "math"
  12. "math/bits"
  13. "net/netip"
  14. "os"
  15. "strings"
  16. "time"
  17. "github.com/skip2/go-qrcode"
  18. "github.com/slackhq/nebula/cert"
  19. "github.com/slackhq/nebula/pkclient"
  20. "golang.org/x/crypto/ed25519"
  21. )
  22. type caFlags struct {
  23. set *flag.FlagSet
  24. name *string
  25. duration *time.Duration
  26. outKeyPath *string
  27. outCertPath *string
  28. outQRPath *string
  29. groups *string
  30. networks *string
  31. unsafeNetworks *string
  32. argonMemory *uint
  33. argonIterations *uint
  34. argonParallelism *uint
  35. encryption *bool
  36. version *uint
  37. curve *string
  38. p11url *string
  39. // Deprecated options
  40. ips *string
  41. subnets *string
  42. }
  43. func defaultCurve() string {
  44. if fips140.Enforced() {
  45. return "P256"
  46. }
  47. return "25519"
  48. }
  49. func newCaFlags() *caFlags {
  50. // prevent running out of memory on 32-bit systems by defaulting to
  51. // RFC9106's recommendation for memory-constrained environments
  52. var (
  53. defaultArgonMemory uint
  54. defaultArgonIterations uint
  55. )
  56. if bits.UintSize == 32 {
  57. defaultArgonMemory = 64 * 1024
  58. defaultArgonIterations = 3
  59. } else {
  60. defaultArgonMemory = 2 * 1024 * 1024
  61. defaultArgonIterations = 1
  62. }
  63. cf := caFlags{set: flag.NewFlagSet("ca", flag.ContinueOnError)}
  64. cf.set.Usage = func() {}
  65. cf.name = cf.set.String("name", "", "Required: name of the certificate authority")
  66. cf.version = cf.set.Uint("version", uint(cert.Version2), "Optional: version of the certificate format to use")
  67. cf.duration = cf.set.Duration("duration", time.Duration(time.Hour*8760), "Optional: amount of time the certificate should be valid for. Valid time units are seconds: \"s\", minutes: \"m\", hours: \"h\"")
  68. cf.outKeyPath = cf.set.String("out-key", "ca.key", "Optional: path to write the private key to")
  69. cf.outCertPath = cf.set.String("out-crt", "ca.crt", "Optional: path to write the certificate to")
  70. cf.outQRPath = cf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
  71. cf.groups = cf.set.String("groups", "", "Optional: comma separated list of groups. This will limit which groups subordinate certs can use")
  72. cf.networks = cf.set.String("networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in networks")
  73. cf.unsafeNetworks = cf.set.String("unsafe-networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in unsafe networks")
  74. cf.argonMemory = cf.set.Uint("argon-memory", defaultArgonMemory, "Optional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase")
  75. cf.argonParallelism = cf.set.Uint("argon-parallelism", 4, "Optional: Argon2 parallelism parameter used for encrypted private key passphrase")
  76. cf.argonIterations = cf.set.Uint("argon-iterations", defaultArgonIterations, "Optional: Argon2 iterations parameter used for encrypted private key passphrase")
  77. cf.encryption = cf.set.Bool("encrypt", false, "Optional: prompt for passphrase and write out-key in an encrypted format")
  78. cf.curve = cf.set.String("curve", defaultCurve(), "EdDSA/ECDSA Curve (25519, P256)")
  79. cf.p11url = p11Flag(cf.set)
  80. cf.ips = cf.set.String("ips", "", "Deprecated, see -networks")
  81. cf.subnets = cf.set.String("subnets", "", "Deprecated, see -unsafe-networks")
  82. return &cf
  83. }
  84. func parseArgonParameters(memory uint, parallelism uint, iterations uint) (*cert.Argon2Parameters, error) {
  85. if memory <= 0 || memory > math.MaxUint32 {
  86. return nil, newHelpErrorf("-argon-memory must be be greater than 0 and no more than %d KiB", uint32(math.MaxUint32))
  87. }
  88. if parallelism <= 0 || parallelism > math.MaxUint8 {
  89. return nil, newHelpErrorf("-argon-parallelism must be be greater than 0 and no more than %d", math.MaxUint8)
  90. }
  91. if iterations <= 0 || iterations > math.MaxUint32 {
  92. return nil, newHelpErrorf("-argon-iterations must be be greater than 0 and no more than %d", uint32(math.MaxUint32))
  93. }
  94. return cert.NewArgon2Parameters(uint32(memory), uint8(parallelism), uint32(iterations)), nil
  95. }
  96. func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error {
  97. cf := newCaFlags()
  98. err := cf.set.Parse(args)
  99. if err != nil {
  100. return err
  101. }
  102. isP11 := len(*cf.p11url) > 0
  103. if err := mustFlagString("name", cf.name); err != nil {
  104. return err
  105. }
  106. if !isP11 {
  107. if err = mustFlagString("out-key", cf.outKeyPath); err != nil {
  108. return err
  109. }
  110. } else {
  111. // out-key is meaningless under PKCS#11 because the private key never
  112. // leaves the HSM; reject it so we never silently accept or claim a
  113. // stdout slot for it.
  114. outKeySet := false
  115. cf.set.Visit(func(f *flag.Flag) {
  116. if f.Name == "out-key" {
  117. outKeySet = true
  118. }
  119. })
  120. if outKeySet {
  121. return newHelpErrorf("cannot set -out-key with -pkcs11")
  122. }
  123. }
  124. if err := mustFlagString("out-crt", cf.outCertPath); err != nil {
  125. return err
  126. }
  127. var kdfParams *cert.Argon2Parameters
  128. if !isP11 && *cf.encryption {
  129. if kdfParams, err = parseArgonParameters(*cf.argonMemory, *cf.argonParallelism, *cf.argonIterations); err != nil {
  130. return err
  131. }
  132. }
  133. if *cf.duration <= 0 {
  134. return &helpError{"-duration must be greater than 0"}
  135. }
  136. var groups []string
  137. if *cf.groups != "" {
  138. for rg := range strings.SplitSeq(*cf.groups, ",") {
  139. g := strings.TrimSpace(rg)
  140. if g != "" {
  141. groups = append(groups, g)
  142. }
  143. }
  144. }
  145. version := cert.Version(*cf.version)
  146. if version != cert.Version1 && version != cert.Version2 {
  147. return newHelpErrorf("-version must be either %v or %v", cert.Version1, cert.Version2)
  148. }
  149. var networks []netip.Prefix
  150. if *cf.networks == "" && *cf.ips != "" {
  151. // Pull up deprecated -ips flag if needed
  152. *cf.networks = *cf.ips
  153. }
  154. if *cf.networks != "" {
  155. for rs := range strings.SplitSeq(*cf.networks, ",") {
  156. rs := strings.Trim(rs, " ")
  157. if rs != "" {
  158. n, err := netip.ParsePrefix(rs)
  159. if err != nil {
  160. return newHelpErrorf("invalid -networks definition: %s", rs)
  161. }
  162. if version == cert.Version1 && !n.Addr().Is4() {
  163. return newHelpErrorf("invalid -networks definition: v1 certificates can only be ipv4, have %s", rs)
  164. }
  165. networks = append(networks, n)
  166. }
  167. }
  168. }
  169. var unsafeNetworks []netip.Prefix
  170. if *cf.unsafeNetworks == "" && *cf.subnets != "" {
  171. // Pull up deprecated -subnets flag if needed
  172. *cf.unsafeNetworks = *cf.subnets
  173. }
  174. if *cf.unsafeNetworks != "" {
  175. for rs := range strings.SplitSeq(*cf.unsafeNetworks, ",") {
  176. rs := strings.Trim(rs, " ")
  177. if rs != "" {
  178. n, err := netip.ParsePrefix(rs)
  179. if err != nil {
  180. return newHelpErrorf("invalid -unsafe-networks definition: %s", rs)
  181. }
  182. if version == cert.Version1 && !n.Addr().Is4() {
  183. return newHelpErrorf("invalid -unsafe-networks definition: v1 certificates can only be ipv4, have %s", rs)
  184. }
  185. unsafeNetworks = append(unsafeNetworks, n)
  186. }
  187. }
  188. }
  189. var claims ioClaims
  190. if err := reserveOutputs(&claims,
  191. "out-key", *cf.outKeyPath,
  192. "out-crt", *cf.outCertPath,
  193. "out-qr", *cf.outQRPath,
  194. ); err != nil {
  195. return err
  196. }
  197. var passphrase []byte
  198. if !isP11 && *cf.encryption {
  199. passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
  200. if len(passphrase) == 0 {
  201. for range 5 {
  202. errOut.Write([]byte("Enter passphrase: "))
  203. passphrase, err = pr.ReadPassword()
  204. if err == ErrNoTerminal {
  205. return fmt.Errorf("out-key must be encrypted interactively")
  206. } else if err != nil {
  207. return fmt.Errorf("error reading passphrase: %s", err)
  208. }
  209. if len(passphrase) > 0 {
  210. break
  211. }
  212. }
  213. if len(passphrase) == 0 {
  214. return fmt.Errorf("no passphrase specified, remove -encrypt flag to write out-key in plaintext")
  215. }
  216. }
  217. }
  218. var curve cert.Curve
  219. var pub, rawPriv []byte
  220. var p11Client *pkclient.PKClient
  221. if isP11 {
  222. switch *cf.curve {
  223. case "P256":
  224. curve = cert.Curve_P256
  225. default:
  226. return fmt.Errorf("invalid curve for PKCS#11: %s", *cf.curve)
  227. }
  228. p11Client, err = pkclient.FromUrl(*cf.p11url)
  229. if err != nil {
  230. return fmt.Errorf("error while creating PKCS#11 client: %w", err)
  231. }
  232. defer func(client *pkclient.PKClient) {
  233. _ = client.Close()
  234. }(p11Client)
  235. pub, err = p11Client.GetPubKey()
  236. if err != nil {
  237. return fmt.Errorf("error while getting public key with PKCS#11: %w", err)
  238. }
  239. } else {
  240. switch *cf.curve {
  241. case "25519", "X25519", "Curve25519", "CURVE25519":
  242. if fips140.Enforced() {
  243. return errors.New("use of Curve25519 is not allowed in FIPS 140-only mode")
  244. }
  245. curve = cert.Curve_CURVE25519
  246. pub, rawPriv, err = ed25519.GenerateKey(rand.Reader)
  247. if err != nil {
  248. return fmt.Errorf("error while generating ed25519 keys: %s", err)
  249. }
  250. case "P256":
  251. var key *ecdsa.PrivateKey
  252. curve = cert.Curve_P256
  253. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  254. if err != nil {
  255. return fmt.Errorf("error while generating ecdsa keys: %s", err)
  256. }
  257. // ecdh.PrivateKey lets us get at the encoded bytes, even though
  258. // we aren't using ECDH here.
  259. eKey, err := key.ECDH()
  260. if err != nil {
  261. return fmt.Errorf("error while converting ecdsa key: %s", err)
  262. }
  263. rawPriv = eKey.Bytes()
  264. pub = eKey.PublicKey().Bytes()
  265. default:
  266. return fmt.Errorf("invalid curve: %s", *cf.curve)
  267. }
  268. }
  269. t := &cert.TBSCertificate{
  270. Version: version,
  271. Name: *cf.name,
  272. Groups: groups,
  273. Networks: networks,
  274. UnsafeNetworks: unsafeNetworks,
  275. NotBefore: time.Now(),
  276. NotAfter: time.Now().Add(*cf.duration),
  277. PublicKey: pub,
  278. IsCA: true,
  279. Curve: curve,
  280. }
  281. if !isP11 && !isStdio(*cf.outKeyPath) {
  282. if _, err := os.Stat(*cf.outKeyPath); err == nil {
  283. return fmt.Errorf("refusing to overwrite existing CA key: %s", *cf.outKeyPath)
  284. }
  285. }
  286. if !isStdio(*cf.outCertPath) {
  287. if _, err := os.Stat(*cf.outCertPath); err == nil {
  288. return fmt.Errorf("refusing to overwrite existing CA cert: %s", *cf.outCertPath)
  289. }
  290. }
  291. var c cert.Certificate
  292. var b []byte
  293. if isP11 {
  294. c, err = t.SignWith(nil, curve, p11Client.SignASN1)
  295. if err != nil {
  296. return fmt.Errorf("error while signing with PKCS#11: %w", err)
  297. }
  298. } else {
  299. c, err = t.Sign(nil, curve, rawPriv)
  300. if err != nil {
  301. return fmt.Errorf("error while signing: %s", err)
  302. }
  303. if *cf.encryption {
  304. b, err = cert.EncryptAndMarshalSigningPrivateKey(curve, rawPriv, passphrase, kdfParams)
  305. if err != nil {
  306. return fmt.Errorf("error while encrypting out-key: %s", err)
  307. }
  308. } else {
  309. b = cert.MarshalSigningPrivateKeyToPEM(curve, rawPriv)
  310. }
  311. err = writeOutput(*cf.outKeyPath, b, 0600, out)
  312. if err != nil {
  313. return fmt.Errorf("error while writing out-key: %s", err)
  314. }
  315. }
  316. b, err = c.MarshalPEM()
  317. if err != nil {
  318. return fmt.Errorf("error while marshalling certificate: %s", err)
  319. }
  320. err = writeOutput(*cf.outCertPath, b, 0600, out)
  321. if err != nil {
  322. return fmt.Errorf("error while writing out-crt: %s", err)
  323. }
  324. if *cf.outQRPath != "" {
  325. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  326. if err != nil {
  327. return fmt.Errorf("error while generating qr code: %s", err)
  328. }
  329. err = writeOutput(*cf.outQRPath, b, 0600, out)
  330. if err != nil {
  331. return fmt.Errorf("error while writing out-qr: %s", err)
  332. }
  333. }
  334. return nil
  335. }
  336. func caSummary() string {
  337. return "ca <flags>: create a self signed certificate authority"
  338. }
  339. func caHelp(out io.Writer) {
  340. cf := newCaFlags()
  341. out.Write([]byte("Usage of " + os.Args[0] + " " + caSummary() + "\n"))
  342. out.Write([]byte(stdioHelpText))
  343. cf.set.SetOutput(out)
  344. cf.set.PrintDefaults()
  345. }