cert.go 3.4 KB

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