ca.go 8.0 KB

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