main.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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.Fprintln(os.Stderr, `
  134. COPYRIGHT
  135. (c) 2018-2020 Smallstep Labs, Inc.`)
  136. os.Exit(1)
  137. }
  138. func checkSlot(k kms.KeyManager, slot string) {
  139. if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  140. Name: slot,
  141. }); err == nil {
  142. fmt.Fprintf(os.Stderr, "⚠️ Your YubiKey already has a key in the slot %s.\n", slot)
  143. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  144. os.Exit(1)
  145. }
  146. }
  147. func createPKI(k kms.KeyManager, c Config) error {
  148. var err error
  149. ui.Println("Creating PKI ...")
  150. now := time.Now()
  151. // Root Certificate
  152. var signer crypto.Signer
  153. var root *x509.Certificate
  154. if c.RootFile != "" && c.KeyFile != "" {
  155. root, err = pemutil.ReadCertificate(c.RootFile)
  156. if err != nil {
  157. return err
  158. }
  159. key, err := pemutil.Read(c.KeyFile)
  160. if err != nil {
  161. return err
  162. }
  163. var ok bool
  164. if signer, ok = key.(crypto.Signer); !ok {
  165. return errors.Errorf("key type '%T' does not implement a signer", key)
  166. }
  167. } else {
  168. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  169. Name: c.RootSlot,
  170. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  171. })
  172. if err != nil {
  173. return err
  174. }
  175. signer, err = k.CreateSigner(&resp.CreateSignerRequest)
  176. if err != nil {
  177. return err
  178. }
  179. template := &x509.Certificate{
  180. IsCA: true,
  181. NotBefore: now,
  182. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  183. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  184. BasicConstraintsValid: true,
  185. MaxPathLen: 1,
  186. MaxPathLenZero: false,
  187. Issuer: pkix.Name{CommonName: "YubiKey Smallstep Root"},
  188. Subject: pkix.Name{CommonName: "YubiKey Smallstep Root"},
  189. SerialNumber: mustSerialNumber(),
  190. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  191. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  192. }
  193. b, err := x509.CreateCertificate(rand.Reader, template, template, resp.PublicKey, signer)
  194. if err != nil {
  195. return err
  196. }
  197. root, err = x509.ParseCertificate(b)
  198. if err != nil {
  199. return errors.Wrap(err, "error parsing root certificate")
  200. }
  201. if cm, ok := k.(kms.CertificateManager); ok {
  202. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  203. Name: c.RootSlot,
  204. Certificate: root,
  205. }); err != nil {
  206. return err
  207. }
  208. }
  209. if err := fileutil.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  210. Type: "CERTIFICATE",
  211. Bytes: b,
  212. }), 0600); err != nil {
  213. return err
  214. }
  215. ui.PrintSelected("Root Key", resp.Name)
  216. ui.PrintSelected("Root Certificate", "root_ca.crt")
  217. }
  218. // Intermediate Certificate
  219. var keyName string
  220. var publicKey crypto.PublicKey
  221. if c.RootOnly {
  222. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  223. if err != nil {
  224. return errors.Wrap(err, "error creating intermediate key")
  225. }
  226. pass, err := ui.PromptPasswordGenerate("What do you want your password to be? [leave empty and we'll generate one]",
  227. ui.WithRichPrompt())
  228. if err != nil {
  229. return err
  230. }
  231. _, err = pemutil.Serialize(priv, pemutil.WithPassword(pass), pemutil.ToFile("intermediate_ca_key", 0600))
  232. if err != nil {
  233. return err
  234. }
  235. publicKey = priv.Public()
  236. } else {
  237. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  238. Name: c.CrtSlot,
  239. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  240. })
  241. if err != nil {
  242. return err
  243. }
  244. publicKey = resp.PublicKey
  245. keyName = resp.Name
  246. }
  247. template := &x509.Certificate{
  248. IsCA: true,
  249. NotBefore: now,
  250. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  251. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  252. BasicConstraintsValid: true,
  253. MaxPathLen: 0,
  254. MaxPathLenZero: true,
  255. Issuer: root.Subject,
  256. Subject: pkix.Name{CommonName: "YubiKey Smallstep Intermediate"},
  257. SerialNumber: mustSerialNumber(),
  258. SubjectKeyId: mustSubjectKeyID(publicKey),
  259. }
  260. b, err := x509.CreateCertificate(rand.Reader, template, root, publicKey, signer)
  261. if err != nil {
  262. return err
  263. }
  264. intermediate, err := x509.ParseCertificate(b)
  265. if err != nil {
  266. return errors.Wrap(err, "error parsing intermediate certificate")
  267. }
  268. if cm, ok := k.(kms.CertificateManager); ok {
  269. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  270. Name: c.CrtSlot,
  271. Certificate: intermediate,
  272. }); err != nil {
  273. return err
  274. }
  275. }
  276. if err := fileutil.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  277. Type: "CERTIFICATE",
  278. Bytes: b,
  279. }), 0600); err != nil {
  280. return err
  281. }
  282. if c.RootOnly {
  283. ui.PrintSelected("Intermediate Key", "intermediate_ca_key")
  284. } else {
  285. ui.PrintSelected("Intermediate Key", keyName)
  286. }
  287. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  288. return nil
  289. }
  290. func mustSerialNumber() *big.Int {
  291. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  292. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  293. if err != nil {
  294. panic(err)
  295. }
  296. return sn
  297. }
  298. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  299. b, err := x509.MarshalPKIXPublicKey(key)
  300. if err != nil {
  301. panic(err)
  302. }
  303. hash := sha1.Sum(b)
  304. return hash[:]
  305. }