cert.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package control
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. "flag"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/v2fly/v2ray-core/v4/common"
  11. "github.com/v2fly/v2ray-core/v4/common/protocol/tls/cert"
  12. "github.com/v2fly/v2ray-core/v4/common/task"
  13. )
  14. type stringList []string
  15. func (l *stringList) String() string {
  16. return "String list"
  17. }
  18. func (l *stringList) Set(v string) error {
  19. if v == "" {
  20. return newError("empty value")
  21. }
  22. *l = append(*l, v)
  23. return nil
  24. }
  25. type jsonCert struct {
  26. Certificate []string `json:"certificate"`
  27. Key []string `json:"key"`
  28. }
  29. type CertificateCommand struct{}
  30. func (c *CertificateCommand) Name() string {
  31. return "cert"
  32. }
  33. func (c *CertificateCommand) Description() Description {
  34. return Description{
  35. Short: "Generate TLS certificates.",
  36. Usage: []string{
  37. "v2ctl cert [--ca] [--domain=v2fly.org] [--expire=240h]",
  38. "Generate new TLS certificate",
  39. "--ca The new certificate is a CA certificate",
  40. "--domain Common name for the certificate",
  41. "--expire Time until certificate expires. 240h = 10 days.",
  42. },
  43. }
  44. }
  45. func (c *CertificateCommand) printJSON(certificate *cert.Certificate) {
  46. certPEM, keyPEM := certificate.ToPEM()
  47. jCert := &jsonCert{
  48. Certificate: strings.Split(strings.TrimSpace(string(certPEM)), "\n"),
  49. Key: strings.Split(strings.TrimSpace(string(keyPEM)), "\n"),
  50. }
  51. content, err := json.MarshalIndent(jCert, "", " ")
  52. common.Must(err)
  53. os.Stdout.Write(content)
  54. os.Stdout.WriteString("\n")
  55. }
  56. func (c *CertificateCommand) writeFile(content []byte, name string) error {
  57. f, err := os.Create(name)
  58. if err != nil {
  59. return err
  60. }
  61. defer f.Close()
  62. return common.Error2(f.Write(content))
  63. }
  64. func (c *CertificateCommand) printFile(certificate *cert.Certificate, name string) error {
  65. certPEM, keyPEM := certificate.ToPEM()
  66. return task.Run(context.Background(), func() error {
  67. return c.writeFile(certPEM, name+"_cert.pem")
  68. }, func() error {
  69. return c.writeFile(keyPEM, name+"_key.pem")
  70. })
  71. }
  72. func (c *CertificateCommand) Execute(args []string) error {
  73. fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
  74. var domainNames stringList
  75. fs.Var(&domainNames, "domain", "Domain name for the certificate")
  76. commonName := fs.String("name", "V2Ray Inc", "The common name of this certificate")
  77. organization := fs.String("org", "V2Ray Inc", "Organization of the certificate")
  78. isCA := fs.Bool("ca", false, "Whether this certificate is a CA")
  79. jsonOutput := fs.Bool("json", true, "Print certificate in JSON format")
  80. fileOutput := fs.String("file", "", "Save certificate in file.")
  81. expire := fs.Duration("expire", time.Hour*24*90 /* 90 days */, "Time until the certificate expires. Default value 3 months.")
  82. if err := fs.Parse(args); err != nil {
  83. return err
  84. }
  85. var opts []cert.Option
  86. if *isCA {
  87. opts = append(opts, cert.Authority(*isCA))
  88. opts = append(opts, cert.KeyUsage(x509.KeyUsageCertSign|x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature))
  89. }
  90. opts = append(opts, cert.NotAfter(time.Now().Add(*expire)))
  91. opts = append(opts, cert.CommonName(*commonName))
  92. if len(domainNames) > 0 {
  93. opts = append(opts, cert.DNSNames(domainNames...))
  94. }
  95. opts = append(opts, cert.Organization(*organization))
  96. cert, err := cert.Generate(nil, opts...)
  97. if err != nil {
  98. return newError("failed to generate TLS certificate").Base(err)
  99. }
  100. if *jsonOutput {
  101. c.printJSON(cert)
  102. }
  103. if len(*fileOutput) > 0 {
  104. if err := c.printFile(cert, *fileOutput); err != nil {
  105. return err
  106. }
  107. }
  108. return nil
  109. }
  110. func init() {
  111. common.Must(RegisterCommand(&CertificateCommand{}))
  112. }