cert.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. 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. stringFlag("host", "", "Comma-separated hostnames and IPs to generate a certificate for"),
  31. stringFlag("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521"),
  32. intFlag("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set"),
  33. stringFlag("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011"),
  34. durationFlag("duration", 365*24*time.Hour, "Duration that certificate is valid for"),
  35. 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.Fatalf("Unable to marshal ECDSA private key: %v\n", 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) error {
  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. CommonName: "Gogs",
  105. },
  106. NotBefore: notBefore,
  107. NotAfter: notAfter,
  108. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  109. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  110. BasicConstraintsValid: true,
  111. }
  112. hosts := strings.Split(ctx.String("host"), ",")
  113. for _, h := range hosts {
  114. if ip := net.ParseIP(h); ip != nil {
  115. template.IPAddresses = append(template.IPAddresses, ip)
  116. } else {
  117. template.DNSNames = append(template.DNSNames, h)
  118. }
  119. }
  120. if ctx.Bool("ca") {
  121. template.IsCA = true
  122. template.KeyUsage |= x509.KeyUsageCertSign
  123. }
  124. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  125. if err != nil {
  126. log.Fatalf("Failed to create certificate: %s", err)
  127. }
  128. certOut, err := os.Create("cert.pem")
  129. if err != nil {
  130. log.Fatalf("Failed to open cert.pem for writing: %s", err)
  131. }
  132. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  133. certOut.Close()
  134. log.Println("Written cert.pem")
  135. keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  136. if err != nil {
  137. log.Fatalf("Failed to open key.pem for writing: %v\n", err)
  138. }
  139. pem.Encode(keyOut, pemBlockForKey(priv))
  140. keyOut.Close()
  141. log.Println("Written key.pem")
  142. return nil
  143. }