You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
4.5 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cmd
  6. import (
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "crypto/rsa"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "encoding/pem"
  14. "log"
  15. "math/big"
  16. "net"
  17. "os"
  18. "strings"
  19. "time"
  20. "github.com/codegangsta/cli"
  21. )
  22. var CmdCert = cli.Command{
  23. Name: "cert",
  24. Usage: "Generate self-signed certificate",
  25. Description: `Generate a self-signed X.509 certificate for a TLS server.
  26. Outputs to 'cert.pem' and 'key.pem' and will overwrite existing files.`,
  27. Action: runCert,
  28. Flags: []cli.Flag{
  29. cli.StringFlag{"host", "", "Comma-separated hostnames and IPs to generate a certificate for", ""},
  30. cli.StringFlag{"ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521", ""},
  31. cli.IntFlag{"rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set", ""},
  32. cli.StringFlag{"start-date", "", "Creation date formatted as Jan 1 15:04:05 2011", ""},
  33. cli.DurationFlag{"duration", 365 * 24 * time.Hour, "Duration that certificate is valid for", ""},
  34. cli.BoolFlag{"ca", "whether this cert should be its own Certificate Authority", ""},
  35. },
  36. }
  37. func publicKey(priv interface{}) interface{} {
  38. switch k := priv.(type) {
  39. case *rsa.PrivateKey:
  40. return &k.PublicKey
  41. case *ecdsa.PrivateKey:
  42. return &k.PublicKey
  43. default:
  44. return nil
  45. }
  46. }
  47. func pemBlockForKey(priv interface{}) *pem.Block {
  48. switch k := priv.(type) {
  49. case *rsa.PrivateKey:
  50. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
  51. case *ecdsa.PrivateKey:
  52. b, err := x509.MarshalECPrivateKey(k)
  53. if err != nil {
  54. log.Fatal("unable to marshal ECDSA private key: %v", err)
  55. }
  56. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  57. default:
  58. return nil
  59. }
  60. }
  61. func runCert(ctx *cli.Context) {
  62. if len(ctx.String("host")) == 0 {
  63. log.Fatal("Missing required --host parameter")
  64. }
  65. var priv interface{}
  66. var err error
  67. switch ctx.String("ecdsa-curve") {
  68. case "":
  69. priv, err = rsa.GenerateKey(rand.Reader, ctx.Int("rsa-bits"))
  70. case "P224":
  71. priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
  72. case "P256":
  73. priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  74. case "P384":
  75. priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  76. case "P521":
  77. priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  78. default:
  79. log.Fatalf("Unrecognized elliptic curve: %q", ctx.String("ecdsa-curve"))
  80. }
  81. if err != nil {
  82. log.Fatalf("Failed to generate private key: %s", err)
  83. }
  84. var notBefore time.Time
  85. if len(ctx.String("start-date")) == 0 {
  86. notBefore = time.Now()
  87. } else {
  88. notBefore, err = time.Parse("Jan 2 15:04:05 2006", ctx.String("start-date"))
  89. if err != nil {
  90. log.Fatalf("Failed to parse creation date: %s", err)
  91. }
  92. }
  93. notAfter := notBefore.Add(ctx.Duration("duration"))
  94. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  95. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  96. if err != nil {
  97. log.Fatalf("Failed to generate serial number: %s", err)
  98. }
  99. template := x509.Certificate{
  100. SerialNumber: serialNumber,
  101. Subject: pkix.Name{
  102. Organization: []string{"Acme Co"},
  103. },
  104. NotBefore: notBefore,
  105. NotAfter: notAfter,
  106. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  107. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  108. BasicConstraintsValid: true,
  109. }
  110. hosts := strings.Split(ctx.String("host"), ",")
  111. for _, h := range hosts {
  112. if ip := net.ParseIP(h); ip != nil {
  113. template.IPAddresses = append(template.IPAddresses, ip)
  114. } else {
  115. template.DNSNames = append(template.DNSNames, h)
  116. }
  117. }
  118. if ctx.Bool("ca") {
  119. template.IsCA = true
  120. template.KeyUsage |= x509.KeyUsageCertSign
  121. }
  122. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  123. if err != nil {
  124. log.Fatalf("Failed to create certificate: %s", err)
  125. }
  126. certOut, err := os.Create("cert.pem")
  127. if err != nil {
  128. log.Fatalf("Failed to open cert.pem for writing: %s", err)
  129. }
  130. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  131. certOut.Close()
  132. log.Println("Written cert.pem")
  133. keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  134. if err != nil {
  135. log.Fatal("failed to open key.pem for writing: %v", err)
  136. }
  137. pem.Encode(keyOut, pemBlockForKey(priv))
  138. keyOut.Close()
  139. log.Println("Written key.pem")
  140. }