main.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path"
  10. "runtime"
  11. "time"
  12. "unicode"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/certificates/authority"
  15. "github.com/smallstep/certificates/ca"
  16. )
  17. // Version is set by an LDFLAG at build time representing the git tag or commit
  18. // for the current release
  19. var Version = "N/A"
  20. // BuildTime is set by an LDFLAG at build time representing the timestamp at
  21. // the time of build
  22. var BuildTime = "N/A"
  23. func usage() {
  24. fmt.Fprintf(os.Stderr, "Usage: %s [options] <config.json>\n\n", path.Base(os.Args[0]))
  25. flag.PrintDefaults()
  26. }
  27. func printVersion() {
  28. version, buildTime := Version, BuildTime
  29. if version == "N/A" {
  30. version = "0000000-dev"
  31. }
  32. if buildTime == "N/A" {
  33. buildTime = time.Now().UTC().Format("2006-01-02 15:04 MST")
  34. }
  35. fmt.Printf("Smallstep CA/%s (%s/%s)\n", version, runtime.GOOS, runtime.GOARCH)
  36. fmt.Printf("Release Date: %s\n", buildTime)
  37. }
  38. func main() {
  39. var version bool
  40. var configFile, passFile string
  41. flag.StringVar(&passFile, "password-file", "", "path to file containing a password")
  42. flag.BoolVar(&version, "version", false, "print version and exit")
  43. flag.Usage = usage
  44. flag.Parse()
  45. if version {
  46. printVersion()
  47. os.Exit(0)
  48. }
  49. if flag.NArg() != 1 {
  50. flag.Usage()
  51. os.Exit(1)
  52. }
  53. configFile = flag.Arg(0)
  54. config, err := authority.LoadConfiguration(configFile)
  55. if err != nil {
  56. fatal(err)
  57. }
  58. var password []byte
  59. if passFile != "" {
  60. if password, err = ioutil.ReadFile(passFile); err != nil {
  61. fatal(errors.Wrapf(err, "error reading %s", passFile))
  62. }
  63. password = bytes.TrimRightFunc(password, unicode.IsSpace)
  64. }
  65. srv, err := ca.New(config, ca.WithConfigFile(configFile), ca.WithPassword(password))
  66. if err != nil {
  67. fatal(err)
  68. }
  69. go ca.StopReloaderHandler(srv)
  70. if err = srv.Run(); err != nil && err != http.ErrServerClosed {
  71. fatal(err)
  72. }
  73. }
  74. // fatal writes the passed error on the standard error and exits with the exit
  75. // code 1. If the environment variable STEPDEBUG is set to 1 it shows the
  76. // stack trace of the error.
  77. func fatal(err error) {
  78. if os.Getenv("STEPDEBUG") == "1" {
  79. fmt.Fprintf(os.Stderr, "%+v\n", err)
  80. } else {
  81. fmt.Fprintln(os.Stderr, err)
  82. }
  83. os.Exit(2)
  84. }