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.

186 lines
4.8 KiB

8 years ago
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Copyright 2016 The Gitea 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. cli.StringFlag{
  32. Name: "host",
  33. Value: "",
  34. Usage: "Comma-separated hostnames and IPs to generate a certificate for",
  35. },
  36. cli.StringFlag{
  37. Name: "ecdsa-curve",
  38. Value: "",
  39. Usage: "ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521",
  40. },
  41. cli.IntFlag{
  42. Name: "rsa-bits",
  43. Value: 2048,
  44. Usage: "Size of RSA key to generate. Ignored if --ecdsa-curve is set",
  45. },
  46. cli.StringFlag{
  47. Name: "start-date",
  48. Value: "",
  49. Usage: "Creation date formatted as Jan 1 15:04:05 2011",
  50. },
  51. cli.DurationFlag{
  52. Name: "duration",
  53. Value: 365 * 24 * time.Hour,
  54. Usage: "Duration that certificate is valid for",
  55. },
  56. cli.BoolFlag{
  57. Name: "ca",
  58. Usage: "whether this cert should be its own Certificate Authority",
  59. },
  60. },
  61. }
  62. func publicKey(priv interface{}) interface{} {
  63. switch k := priv.(type) {
  64. case *rsa.PrivateKey:
  65. return &k.PublicKey
  66. case *ecdsa.PrivateKey:
  67. return &k.PublicKey
  68. default:
  69. return nil
  70. }
  71. }
  72. func pemBlockForKey(priv interface{}) *pem.Block {
  73. switch k := priv.(type) {
  74. case *rsa.PrivateKey:
  75. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
  76. case *ecdsa.PrivateKey:
  77. b, err := x509.MarshalECPrivateKey(k)
  78. if err != nil {
  79. log.Fatalf("Unable to marshal ECDSA private key: %v", err)
  80. }
  81. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  82. default:
  83. return nil
  84. }
  85. }
  86. func runCert(ctx *cli.Context) error {
  87. if len(ctx.String("host")) == 0 {
  88. log.Fatal("Missing required --host parameter")
  89. }
  90. var priv interface{}
  91. var err error
  92. switch ctx.String("ecdsa-curve") {
  93. case "":
  94. priv, err = rsa.GenerateKey(rand.Reader, ctx.Int("rsa-bits"))
  95. case "P224":
  96. priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
  97. case "P256":
  98. priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  99. case "P384":
  100. priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  101. case "P521":
  102. priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  103. default:
  104. log.Fatalf("Unrecognized elliptic curve: %q", ctx.String("ecdsa-curve"))
  105. }
  106. if err != nil {
  107. log.Fatalf("Failed to generate private key: %v", err)
  108. }
  109. var notBefore time.Time
  110. if len(ctx.String("start-date")) == 0 {
  111. notBefore = time.Now()
  112. } else {
  113. notBefore, err = time.Parse("Jan 2 15:04:05 2006", ctx.String("start-date"))
  114. if err != nil {
  115. log.Fatalf("Failed to parse creation date: %v", err)
  116. }
  117. }
  118. notAfter := notBefore.Add(ctx.Duration("duration"))
  119. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  120. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  121. if err != nil {
  122. log.Fatalf("Failed to generate serial number: %v", err)
  123. }
  124. template := x509.Certificate{
  125. SerialNumber: serialNumber,
  126. Subject: pkix.Name{
  127. Organization: []string{"Acme Co"},
  128. CommonName: "Gitea",
  129. },
  130. NotBefore: notBefore,
  131. NotAfter: notAfter,
  132. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  133. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  134. BasicConstraintsValid: true,
  135. }
  136. hosts := strings.Split(ctx.String("host"), ",")
  137. for _, h := range hosts {
  138. if ip := net.ParseIP(h); ip != nil {
  139. template.IPAddresses = append(template.IPAddresses, ip)
  140. } else {
  141. template.DNSNames = append(template.DNSNames, h)
  142. }
  143. }
  144. if ctx.Bool("ca") {
  145. template.IsCA = true
  146. template.KeyUsage |= x509.KeyUsageCertSign
  147. }
  148. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  149. if err != nil {
  150. log.Fatalf("Failed to create certificate: %v", err)
  151. }
  152. certOut, err := os.Create("cert.pem")
  153. if err != nil {
  154. log.Fatalf("Failed to open cert.pem for writing: %v", err)
  155. }
  156. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  157. certOut.Close()
  158. log.Println("Written cert.pem")
  159. keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  160. if err != nil {
  161. log.Fatalf("Failed to open key.pem for writing: %v", err)
  162. }
  163. pem.Encode(keyOut, pemBlockForKey(priv))
  164. keyOut.Close()
  165. log.Println("Written key.pem")
  166. return nil
  167. }