cert.go 3.6 KB

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