cert.go 4.2 KB

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