main.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package main
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280
  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. "go.step.sm/cli-utils/fileutil"
  20. "go.step.sm/cli-utils/ui"
  21. "go.step.sm/crypto/kms"
  22. "go.step.sm/crypto/kms/apiv1"
  23. "go.step.sm/crypto/pemutil"
  24. // Enable yubikey.
  25. _ "go.step.sm/crypto/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. ui.Println("⚠️ This command is deprecated and will be removed in future releases.")
  85. ui.Println("⚠️ Please use https://github.com/smallstep/step-kms-plugin instead.")
  86. pin, err := ui.PromptPassword("What is the YubiKey PIN?")
  87. if err != nil {
  88. fatal(err)
  89. }
  90. c.Pin = string(pin)
  91. k, err := kms.New(context.Background(), apiv1.Options{
  92. Type: apiv1.YubiKey,
  93. Pin: c.Pin,
  94. ManagementKey: c.ManagementKey,
  95. })
  96. if err != nil {
  97. fatal(err)
  98. }
  99. // Check if the slots are empty, fail if they are not
  100. if !c.Force {
  101. switch {
  102. case c.RootSlot != "":
  103. checkSlot(k, c.RootSlot)
  104. case c.CrtSlot != "":
  105. checkSlot(k, c.CrtSlot)
  106. }
  107. }
  108. if err := createPKI(k, c); err != nil {
  109. fatal(err)
  110. }
  111. defer func() {
  112. _ = k.Close()
  113. }()
  114. // Reset windows terminal
  115. ui.Reset()
  116. }
  117. func fatal(err error) {
  118. if os.Getenv("STEPDEBUG") == "1" {
  119. fmt.Fprintf(os.Stderr, "%+v\n", err)
  120. } else {
  121. fmt.Fprintln(os.Stderr, err)
  122. }
  123. ui.Reset()
  124. os.Exit(1)
  125. }
  126. func usage() {
  127. fmt.Fprintln(os.Stderr, "Usage: step-yubikey-init")
  128. fmt.Fprintln(os.Stderr, `
  129. The step-yubikey-init command initializes a public key infrastructure (PKI)
  130. to be used by step-ca.
  131. This tool is experimental and in the future it will be integrated in step cli.
  132. OPTIONS`)
  133. fmt.Fprintln(os.Stderr)
  134. flag.PrintDefaults()
  135. fmt.Fprintf(os.Stderr, `
  136. COPYRIGHT
  137. (c) 2018-%d Smallstep Labs, Inc.
  138. `, time.Now().Year())
  139. os.Exit(1)
  140. }
  141. func checkSlot(k kms.KeyManager, slot string) {
  142. if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  143. Name: slot,
  144. }); err == nil {
  145. fmt.Fprintf(os.Stderr, "⚠️ Your YubiKey already has a key in the slot %s.\n", slot)
  146. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  147. os.Exit(1)
  148. }
  149. }
  150. func createPKI(k kms.KeyManager, c Config) error {
  151. var err error
  152. ui.Println("Creating PKI ...")
  153. now := time.Now()
  154. // Root Certificate
  155. var signer crypto.Signer
  156. var root *x509.Certificate
  157. if c.RootFile != "" && c.KeyFile != "" {
  158. root, err = pemutil.ReadCertificate(c.RootFile)
  159. if err != nil {
  160. return err
  161. }
  162. key, err := pemutil.Read(c.KeyFile)
  163. if err != nil {
  164. return err
  165. }
  166. var ok bool
  167. if signer, ok = key.(crypto.Signer); !ok {
  168. return errors.Errorf("key type '%T' does not implement a signer", key)
  169. }
  170. } else {
  171. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  172. Name: c.RootSlot,
  173. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  174. })
  175. if err != nil {
  176. return err
  177. }
  178. signer, err = k.CreateSigner(&resp.CreateSignerRequest)
  179. if err != nil {
  180. return err
  181. }
  182. template := &x509.Certificate{
  183. IsCA: true,
  184. NotBefore: now,
  185. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  186. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  187. BasicConstraintsValid: true,
  188. MaxPathLen: 1,
  189. MaxPathLenZero: false,
  190. Issuer: pkix.Name{CommonName: "YubiKey Smallstep Root"},
  191. Subject: pkix.Name{CommonName: "YubiKey Smallstep Root"},
  192. SerialNumber: mustSerialNumber(),
  193. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  194. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  195. }
  196. b, err := x509.CreateCertificate(rand.Reader, template, template, resp.PublicKey, signer)
  197. if err != nil {
  198. return err
  199. }
  200. root, err = x509.ParseCertificate(b)
  201. if err != nil {
  202. return errors.Wrap(err, "error parsing root certificate")
  203. }
  204. if cm, ok := k.(kms.CertificateManager); ok {
  205. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  206. Name: c.RootSlot,
  207. Certificate: root,
  208. }); err != nil {
  209. return err
  210. }
  211. }
  212. if err := fileutil.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  213. Type: "CERTIFICATE",
  214. Bytes: b,
  215. }), 0600); err != nil {
  216. return err
  217. }
  218. ui.PrintSelected("Root Key", resp.Name)
  219. ui.PrintSelected("Root Certificate", "root_ca.crt")
  220. }
  221. // Intermediate Certificate
  222. var keyName string
  223. var publicKey crypto.PublicKey
  224. if c.RootOnly {
  225. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  226. if err != nil {
  227. return errors.Wrap(err, "error creating intermediate key")
  228. }
  229. pass, err := ui.PromptPasswordGenerate("What do you want your password to be? [leave empty and we'll generate one]",
  230. ui.WithRichPrompt())
  231. if err != nil {
  232. return err
  233. }
  234. _, err = pemutil.Serialize(priv, pemutil.WithPassword(pass), pemutil.ToFile("intermediate_ca_key", 0600))
  235. if err != nil {
  236. return err
  237. }
  238. publicKey = priv.Public()
  239. } else {
  240. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  241. Name: c.CrtSlot,
  242. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  243. })
  244. if err != nil {
  245. return err
  246. }
  247. publicKey = resp.PublicKey
  248. keyName = resp.Name
  249. }
  250. template := &x509.Certificate{
  251. IsCA: true,
  252. NotBefore: now,
  253. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  254. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  255. BasicConstraintsValid: true,
  256. MaxPathLen: 0,
  257. MaxPathLenZero: true,
  258. Issuer: root.Subject,
  259. Subject: pkix.Name{CommonName: "YubiKey Smallstep Intermediate"},
  260. SerialNumber: mustSerialNumber(),
  261. SubjectKeyId: mustSubjectKeyID(publicKey),
  262. }
  263. b, err := x509.CreateCertificate(rand.Reader, template, root, publicKey, signer)
  264. if err != nil {
  265. return err
  266. }
  267. intermediate, err := x509.ParseCertificate(b)
  268. if err != nil {
  269. return errors.Wrap(err, "error parsing intermediate certificate")
  270. }
  271. if cm, ok := k.(kms.CertificateManager); ok {
  272. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  273. Name: c.CrtSlot,
  274. Certificate: intermediate,
  275. }); err != nil {
  276. return err
  277. }
  278. }
  279. if err := fileutil.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  280. Type: "CERTIFICATE",
  281. Bytes: b,
  282. }), 0600); err != nil {
  283. return err
  284. }
  285. if c.RootOnly {
  286. ui.PrintSelected("Intermediate Key", "intermediate_ca_key")
  287. } else {
  288. ui.PrintSelected("Intermediate Key", keyName)
  289. }
  290. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  291. return nil
  292. }
  293. func mustSerialNumber() *big.Int {
  294. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  295. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  296. if err != nil {
  297. panic(err)
  298. }
  299. return sn
  300. }
  301. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  302. b, err := x509.MarshalPKIXPublicKey(key)
  303. if err != nil {
  304. panic(err)
  305. }
  306. //nolint:gosec // used to create the Subject Key Identifier by RFC 5280
  307. hash := sha1.Sum(b)
  308. return hash[:]
  309. }