ca.go 10 KB

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