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.

160 lines
4.5 KiB

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