main.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package main
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "crypto/x509"
  10. "crypto/x509/pkix"
  11. "encoding/hex"
  12. "encoding/pem"
  13. "flag"
  14. "fmt"
  15. "math/big"
  16. "os"
  17. "time"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/kms"
  20. "github.com/smallstep/certificates/kms/apiv1"
  21. "go.step.sm/cli-utils/fileutil"
  22. "go.step.sm/cli-utils/ui"
  23. "go.step.sm/crypto/pemutil"
  24. // Enable yubikey.
  25. _ "github.com/smallstep/certificates/kms/yubikey"
  26. )
  27. // Config is a mapping of the cli flags.
  28. type Config struct {
  29. RootOnly bool
  30. RootSlot string
  31. CrtSlot string
  32. RootFile string
  33. KeyFile string
  34. Pin string
  35. ManagementKey string
  36. Force bool
  37. }
  38. // Validate checks the flags in the config.
  39. func (c *Config) Validate() error {
  40. switch {
  41. case c.ManagementKey != "" && len(c.ManagementKey) != 48:
  42. return errors.New("flag `--management-key` must be 48 hexadecimal characters (24 bytes)")
  43. case c.RootFile != "" && c.KeyFile == "":
  44. return errors.New("flag `--root` requires flag `--key`")
  45. case c.KeyFile != "" && c.RootFile == "":
  46. return errors.New("flag `--key` requires flag `--root`")
  47. case c.RootOnly && c.RootFile != "":
  48. return errors.New("flag `--root-only` is incompatible with flag `--root`")
  49. case c.RootSlot == c.CrtSlot:
  50. return errors.New("flag `--root-slot` and flag `--crt-slot` cannot be the same")
  51. case c.RootFile == "" && c.RootSlot == "":
  52. return errors.New("one of flag `--root` or `--root-slot` is required")
  53. default:
  54. if c.RootFile != "" {
  55. c.RootSlot = ""
  56. }
  57. if c.RootOnly {
  58. c.CrtSlot = ""
  59. }
  60. if c.ManagementKey != "" {
  61. if _, err := hex.DecodeString(c.ManagementKey); err != nil {
  62. return errors.Wrap(err, "flag `--management-key` is not valid")
  63. }
  64. }
  65. return nil
  66. }
  67. }
  68. func main() {
  69. var c Config
  70. flag.StringVar(&c.ManagementKey, "management-key", "", `Management key to use in hexadecimal format. (default "010203040506070801020304050607080102030405060708")`)
  71. flag.BoolVar(&c.RootOnly, "root-only", false, "Slot only the root certificate and sign and intermediate.")
  72. flag.StringVar(&c.RootSlot, "root-slot", "9a", "Slot to store the root certificate.")
  73. flag.StringVar(&c.CrtSlot, "crt-slot", "9c", "Slot to store the intermediate certificate.")
  74. flag.StringVar(&c.RootFile, "root", "", "Path to the root certificate to use.")
  75. flag.StringVar(&c.KeyFile, "key", "", "Path to the root key to use.")
  76. flag.BoolVar(&c.Force, "force", false, "Force the delete of previous keys.")
  77. flag.Usage = usage
  78. flag.Parse()
  79. if err := c.Validate(); err != nil {
  80. fatal(err)
  81. }
  82. // Initialize windows terminal
  83. ui.Init()
  84. pin, err := ui.PromptPassword("What is the YubiKey PIN?")
  85. if err != nil {
  86. fatal(err)
  87. }
  88. c.Pin = string(pin)
  89. k, err := kms.New(context.Background(), apiv1.Options{
  90. Type: string(apiv1.YubiKey),
  91. Pin: c.Pin,
  92. ManagementKey: c.ManagementKey,
  93. })
  94. if err != nil {
  95. fatal(err)
  96. }
  97. // Check if the slots are empty, fail if they are not
  98. if !c.Force {
  99. switch {
  100. case c.RootSlot != "":
  101. checkSlot(k, c.RootSlot)
  102. case c.CrtSlot != "":
  103. checkSlot(k, c.CrtSlot)
  104. }
  105. }
  106. if err := createPKI(k, c); err != nil {
  107. fatal(err)
  108. }
  109. defer func() {
  110. _ = k.Close()
  111. }()
  112. // Reset windows terminal
  113. ui.Reset()
  114. }
  115. func fatal(err error) {
  116. if os.Getenv("STEPDEBUG") == "1" {
  117. fmt.Fprintf(os.Stderr, "%+v\n", err)
  118. } else {
  119. fmt.Fprintln(os.Stderr, err)
  120. }
  121. ui.Reset()
  122. os.Exit(1)
  123. }
  124. func usage() {
  125. fmt.Fprintln(os.Stderr, "Usage: step-yubikey-init")
  126. fmt.Fprintln(os.Stderr, `
  127. The step-yubikey-init command initializes a public key infrastructure (PKI)
  128. to be used by step-ca.
  129. This tool is experimental and in the future it will be integrated in step cli.
  130. OPTIONS`)
  131. fmt.Fprintln(os.Stderr)
  132. flag.PrintDefaults()
  133. fmt.Fprintf(os.Stderr, `
  134. COPYRIGHT
  135. (c) 2018-%d Smallstep Labs, Inc.
  136. `, time.Now().Year())
  137. os.Exit(1)
  138. }
  139. func checkSlot(k kms.KeyManager, slot string) {
  140. if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  141. Name: slot,
  142. }); err == nil {
  143. fmt.Fprintf(os.Stderr, "⚠️ Your YubiKey already has a key in the slot %s.\n", slot)
  144. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  145. os.Exit(1)
  146. }
  147. }
  148. func createPKI(k kms.KeyManager, c Config) error {
  149. var err error
  150. ui.Println("Creating PKI ...")
  151. now := time.Now()
  152. // Root Certificate
  153. var signer crypto.Signer
  154. var root *x509.Certificate
  155. if c.RootFile != "" && c.KeyFile != "" {
  156. root, err = pemutil.ReadCertificate(c.RootFile)
  157. if err != nil {
  158. return err
  159. }
  160. key, err := pemutil.Read(c.KeyFile)
  161. if err != nil {
  162. return err
  163. }
  164. var ok bool
  165. if signer, ok = key.(crypto.Signer); !ok {
  166. return errors.Errorf("key type '%T' does not implement a signer", key)
  167. }
  168. } else {
  169. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  170. Name: c.RootSlot,
  171. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  172. })
  173. if err != nil {
  174. return err
  175. }
  176. signer, err = k.CreateSigner(&resp.CreateSignerRequest)
  177. if err != nil {
  178. return err
  179. }
  180. template := &x509.Certificate{
  181. IsCA: true,
  182. NotBefore: now,
  183. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  184. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  185. BasicConstraintsValid: true,
  186. MaxPathLen: 1,
  187. MaxPathLenZero: false,
  188. Issuer: pkix.Name{CommonName: "YubiKey Smallstep Root"},
  189. Subject: pkix.Name{CommonName: "YubiKey Smallstep Root"},
  190. SerialNumber: mustSerialNumber(),
  191. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  192. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  193. }
  194. b, err := x509.CreateCertificate(rand.Reader, template, template, resp.PublicKey, signer)
  195. if err != nil {
  196. return err
  197. }
  198. root, err = x509.ParseCertificate(b)
  199. if err != nil {
  200. return errors.Wrap(err, "error parsing root certificate")
  201. }
  202. if cm, ok := k.(kms.CertificateManager); ok {
  203. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  204. Name: c.RootSlot,
  205. Certificate: root,
  206. }); err != nil {
  207. return err
  208. }
  209. }
  210. if err := fileutil.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  211. Type: "CERTIFICATE",
  212. Bytes: b,
  213. }), 0600); err != nil {
  214. return err
  215. }
  216. ui.PrintSelected("Root Key", resp.Name)
  217. ui.PrintSelected("Root Certificate", "root_ca.crt")
  218. }
  219. // Intermediate Certificate
  220. var keyName string
  221. var publicKey crypto.PublicKey
  222. if c.RootOnly {
  223. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  224. if err != nil {
  225. return errors.Wrap(err, "error creating intermediate key")
  226. }
  227. pass, err := ui.PromptPasswordGenerate("What do you want your password to be? [leave empty and we'll generate one]",
  228. ui.WithRichPrompt())
  229. if err != nil {
  230. return err
  231. }
  232. _, err = pemutil.Serialize(priv, pemutil.WithPassword(pass), pemutil.ToFile("intermediate_ca_key", 0600))
  233. if err != nil {
  234. return err
  235. }
  236. publicKey = priv.Public()
  237. } else {
  238. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  239. Name: c.CrtSlot,
  240. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  241. })
  242. if err != nil {
  243. return err
  244. }
  245. publicKey = resp.PublicKey
  246. keyName = resp.Name
  247. }
  248. template := &x509.Certificate{
  249. IsCA: true,
  250. NotBefore: now,
  251. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  252. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  253. BasicConstraintsValid: true,
  254. MaxPathLen: 0,
  255. MaxPathLenZero: true,
  256. Issuer: root.Subject,
  257. Subject: pkix.Name{CommonName: "YubiKey Smallstep Intermediate"},
  258. SerialNumber: mustSerialNumber(),
  259. SubjectKeyId: mustSubjectKeyID(publicKey),
  260. }
  261. b, err := x509.CreateCertificate(rand.Reader, template, root, publicKey, signer)
  262. if err != nil {
  263. return err
  264. }
  265. intermediate, err := x509.ParseCertificate(b)
  266. if err != nil {
  267. return errors.Wrap(err, "error parsing intermediate certificate")
  268. }
  269. if cm, ok := k.(kms.CertificateManager); ok {
  270. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  271. Name: c.CrtSlot,
  272. Certificate: intermediate,
  273. }); err != nil {
  274. return err
  275. }
  276. }
  277. if err := fileutil.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  278. Type: "CERTIFICATE",
  279. Bytes: b,
  280. }), 0600); err != nil {
  281. return err
  282. }
  283. if c.RootOnly {
  284. ui.PrintSelected("Intermediate Key", "intermediate_ca_key")
  285. } else {
  286. ui.PrintSelected("Intermediate Key", keyName)
  287. }
  288. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  289. return nil
  290. }
  291. func mustSerialNumber() *big.Int {
  292. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  293. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  294. if err != nil {
  295. panic(err)
  296. }
  297. return sn
  298. }
  299. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  300. b, err := x509.MarshalPKIXPublicKey(key)
  301. if err != nil {
  302. panic(err)
  303. }
  304. hash := sha1.Sum(b)
  305. return hash[:]
  306. }