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.

164 lines
4.5 KiB

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