main.go 8.7 KB

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