ca.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package main
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/elliptic"
  5. "crypto/rand"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "math"
  10. "net"
  11. "os"
  12. "strings"
  13. "time"
  14. "github.com/skip2/go-qrcode"
  15. "github.com/slackhq/nebula/cert"
  16. "golang.org/x/crypto/ed25519"
  17. )
  18. type caFlags struct {
  19. set *flag.FlagSet
  20. name *string
  21. duration *time.Duration
  22. outKeyPath *string
  23. outCertPath *string
  24. outQRPath *string
  25. groups *string
  26. ips *string
  27. subnets *string
  28. argonMemory *uint
  29. argonIterations *uint
  30. argonParallelism *uint
  31. encryption *bool
  32. curve *string
  33. }
  34. func newCaFlags() *caFlags {
  35. cf := caFlags{set: flag.NewFlagSet("ca", flag.ContinueOnError)}
  36. cf.set.Usage = func() {}
  37. cf.name = cf.set.String("name", "", "Required: name of the certificate authority")
  38. 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\"")
  39. cf.outKeyPath = cf.set.String("out-key", "ca.key", "Optional: path to write the private key to")
  40. cf.outCertPath = cf.set.String("out-crt", "ca.crt", "Optional: path to write the certificate to")
  41. cf.outQRPath = cf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
  42. cf.groups = cf.set.String("groups", "", "Optional: comma separated list of groups. This will limit which groups subordinate certs can use")
  43. cf.ips = cf.set.String("ips", "", "Optional: comma separated list of ipv4 address and network in CIDR notation. This will limit which ipv4 addresses and networks subordinate certs can use for ip addresses")
  44. cf.subnets = cf.set.String("subnets", "", "Optional: comma separated list of ipv4 address and network in CIDR notation. This will limit which ipv4 addresses and networks subordinate certs can use in subnets")
  45. cf.argonMemory = cf.set.Uint("argon-memory", 2*1024*1024, "Optional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase")
  46. cf.argonParallelism = cf.set.Uint("argon-parallelism", 4, "Optional: Argon2 parallelism parameter used for encrypted private key passphrase")
  47. cf.argonIterations = cf.set.Uint("argon-iterations", 1, "Optional: Argon2 iterations parameter used for encrypted private key passphrase")
  48. cf.encryption = cf.set.Bool("encrypt", false, "Optional: prompt for passphrase and write out-key in an encrypted format")
  49. cf.curve = cf.set.String("curve", "25519", "EdDSA/ECDSA Curve (25519, P256)")
  50. return &cf
  51. }
  52. func parseArgonParameters(memory uint, parallelism uint, iterations uint) (*cert.Argon2Parameters, error) {
  53. if memory <= 0 || memory > math.MaxUint32 {
  54. return nil, newHelpErrorf("-argon-memory must be be greater than 0 and no more than %d KiB", uint32(math.MaxUint32))
  55. }
  56. if parallelism <= 0 || parallelism > math.MaxUint8 {
  57. return nil, newHelpErrorf("-argon-parallelism must be be greater than 0 and no more than %d", math.MaxUint8)
  58. }
  59. if iterations <= 0 || iterations > math.MaxUint32 {
  60. return nil, newHelpErrorf("-argon-iterations must be be greater than 0 and no more than %d", uint32(math.MaxUint32))
  61. }
  62. return cert.NewArgon2Parameters(uint32(memory), uint8(parallelism), uint32(iterations)), nil
  63. }
  64. func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error {
  65. cf := newCaFlags()
  66. err := cf.set.Parse(args)
  67. if err != nil {
  68. return err
  69. }
  70. if err := mustFlagString("name", cf.name); err != nil {
  71. return err
  72. }
  73. if err := mustFlagString("out-key", cf.outKeyPath); err != nil {
  74. return err
  75. }
  76. if err := mustFlagString("out-crt", cf.outCertPath); err != nil {
  77. return err
  78. }
  79. var kdfParams *cert.Argon2Parameters
  80. if *cf.encryption {
  81. if kdfParams, err = parseArgonParameters(*cf.argonMemory, *cf.argonParallelism, *cf.argonIterations); err != nil {
  82. return err
  83. }
  84. }
  85. if *cf.duration <= 0 {
  86. return &helpError{"-duration must be greater than 0"}
  87. }
  88. var groups []string
  89. if *cf.groups != "" {
  90. for _, rg := range strings.Split(*cf.groups, ",") {
  91. g := strings.TrimSpace(rg)
  92. if g != "" {
  93. groups = append(groups, g)
  94. }
  95. }
  96. }
  97. var ips []*net.IPNet
  98. if *cf.ips != "" {
  99. for _, rs := range strings.Split(*cf.ips, ",") {
  100. rs := strings.Trim(rs, " ")
  101. if rs != "" {
  102. ip, ipNet, err := net.ParseCIDR(rs)
  103. if err != nil {
  104. return newHelpErrorf("invalid ip definition: %s", err)
  105. }
  106. if ip.To4() == nil {
  107. return newHelpErrorf("invalid ip definition: can only be ipv4, have %s", rs)
  108. }
  109. ipNet.IP = ip
  110. ips = append(ips, ipNet)
  111. }
  112. }
  113. }
  114. var subnets []*net.IPNet
  115. if *cf.subnets != "" {
  116. for _, rs := range strings.Split(*cf.subnets, ",") {
  117. rs := strings.Trim(rs, " ")
  118. if rs != "" {
  119. _, s, err := net.ParseCIDR(rs)
  120. if err != nil {
  121. return newHelpErrorf("invalid subnet definition: %s", err)
  122. }
  123. if s.IP.To4() == nil {
  124. return newHelpErrorf("invalid subnet definition: can only be ipv4, have %s", rs)
  125. }
  126. subnets = append(subnets, s)
  127. }
  128. }
  129. }
  130. var passphrase []byte
  131. if *cf.encryption {
  132. for i := 0; i < 5; i++ {
  133. out.Write([]byte("Enter passphrase: "))
  134. passphrase, err = pr.ReadPassword()
  135. if err == ErrNoTerminal {
  136. return fmt.Errorf("out-key must be encrypted interactively")
  137. } else if err != nil {
  138. return fmt.Errorf("error reading passphrase: %s", err)
  139. }
  140. if len(passphrase) > 0 {
  141. break
  142. }
  143. }
  144. if len(passphrase) == 0 {
  145. return fmt.Errorf("no passphrase specified, remove -encrypt flag to write out-key in plaintext")
  146. }
  147. }
  148. var curve cert.Curve
  149. var pub, rawPriv []byte
  150. switch *cf.curve {
  151. case "25519", "X25519", "Curve25519", "CURVE25519":
  152. curve = cert.Curve_CURVE25519
  153. pub, rawPriv, err = ed25519.GenerateKey(rand.Reader)
  154. if err != nil {
  155. return fmt.Errorf("error while generating ed25519 keys: %s", err)
  156. }
  157. case "P256":
  158. var key *ecdsa.PrivateKey
  159. curve = cert.Curve_P256
  160. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  161. if err != nil {
  162. return fmt.Errorf("error while generating ecdsa keys: %s", err)
  163. }
  164. // ecdh.PrivateKey lets us get at the encoded bytes, even though
  165. // we aren't using ECDH here.
  166. eKey, err := key.ECDH()
  167. if err != nil {
  168. return fmt.Errorf("error while converting ecdsa key: %s", err)
  169. }
  170. rawPriv = eKey.Bytes()
  171. pub = eKey.PublicKey().Bytes()
  172. }
  173. nc := cert.NebulaCertificate{
  174. Details: cert.NebulaCertificateDetails{
  175. Name: *cf.name,
  176. Groups: groups,
  177. Ips: ips,
  178. Subnets: subnets,
  179. NotBefore: time.Now(),
  180. NotAfter: time.Now().Add(*cf.duration),
  181. PublicKey: pub,
  182. IsCA: true,
  183. Curve: curve,
  184. },
  185. }
  186. if _, err := os.Stat(*cf.outKeyPath); err == nil {
  187. return fmt.Errorf("refusing to overwrite existing CA key: %s", *cf.outKeyPath)
  188. }
  189. if _, err := os.Stat(*cf.outCertPath); err == nil {
  190. return fmt.Errorf("refusing to overwrite existing CA cert: %s", *cf.outCertPath)
  191. }
  192. err = nc.Sign(curve, rawPriv)
  193. if err != nil {
  194. return fmt.Errorf("error while signing: %s", err)
  195. }
  196. var b []byte
  197. if *cf.encryption {
  198. b, err = cert.EncryptAndMarshalSigningPrivateKey(curve, rawPriv, passphrase, kdfParams)
  199. if err != nil {
  200. return fmt.Errorf("error while encrypting out-key: %s", err)
  201. }
  202. } else {
  203. b = cert.MarshalSigningPrivateKey(curve, rawPriv)
  204. }
  205. err = os.WriteFile(*cf.outKeyPath, b, 0600)
  206. if err != nil {
  207. return fmt.Errorf("error while writing out-key: %s", err)
  208. }
  209. b, err = nc.MarshalToPEM()
  210. if err != nil {
  211. return fmt.Errorf("error while marshalling certificate: %s", err)
  212. }
  213. err = os.WriteFile(*cf.outCertPath, b, 0600)
  214. if err != nil {
  215. return fmt.Errorf("error while writing out-crt: %s", err)
  216. }
  217. if *cf.outQRPath != "" {
  218. b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
  219. if err != nil {
  220. return fmt.Errorf("error while generating qr code: %s", err)
  221. }
  222. err = os.WriteFile(*cf.outQRPath, b, 0600)
  223. if err != nil {
  224. return fmt.Errorf("error while writing out-qr: %s", err)
  225. }
  226. }
  227. return nil
  228. }
  229. func caSummary() string {
  230. return "ca <flags>: create a self signed certificate authority"
  231. }
  232. func caHelp(out io.Writer) {
  233. cf := newCaFlags()
  234. out.Write([]byte("Usage of " + os.Args[0] + " " + caSummary() + "\n"))
  235. cf.set.SetOutput(out)
  236. cf.set.PrintDefaults()
  237. }