main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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/pem"
  12. "flag"
  13. "fmt"
  14. "math/big"
  15. "os"
  16. "runtime"
  17. "time"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/kms"
  20. "github.com/smallstep/certificates/kms/apiv1"
  21. "github.com/smallstep/certificates/kms/uri"
  22. "go.step.sm/cli-utils/fileutil"
  23. "go.step.sm/cli-utils/ui"
  24. "go.step.sm/crypto/pemutil"
  25. // Enable pkcs11.
  26. _ "github.com/smallstep/certificates/kms/pkcs11"
  27. )
  28. // Config is a mapping of the cli flags.
  29. type Config struct {
  30. KMS string
  31. GenerateRoot bool
  32. RootObject string
  33. RootKeyObject string
  34. RootSubject string
  35. RootPath string
  36. CrtObject string
  37. CrtPath string
  38. CrtKeyObject string
  39. CrtSubject string
  40. CrtKeyPath string
  41. SSHHostKeyObject string
  42. SSHUserKeyObject string
  43. RootFile string
  44. KeyFile string
  45. Pin string
  46. NoCerts bool
  47. EnableSSH bool
  48. Force bool
  49. Extractable bool
  50. }
  51. // Validate checks the flags in the config.
  52. func (c *Config) Validate() error {
  53. switch {
  54. case c.KMS == "":
  55. return errors.New("flag `--kms` is required")
  56. case c.CrtPath == "":
  57. return errors.New("flag `--crt-cert-path` is required")
  58. case c.RootFile != "" && c.KeyFile == "":
  59. return errors.New("flag `--root-cert-file` requires flag `--root-key-file`")
  60. case c.KeyFile != "" && c.RootFile == "":
  61. return errors.New("flag `--root-key-file` requires flag `--root-cert-file`")
  62. case c.RootFile == "" && c.RootObject == "":
  63. return errors.New("one of flag `--root-cert-file` or `--root-cert-obj` is required")
  64. case c.KeyFile == "" && c.RootKeyObject == "":
  65. return errors.New("one of flag `--root-key-file` or `--root-key-obj` is required")
  66. case c.CrtKeyPath == "" && c.CrtKeyObject == "":
  67. return errors.New("one of flag `--crt-key-path` or `--crt-key-obj` is required")
  68. case c.RootFile == "" && c.GenerateRoot && c.RootKeyObject == "":
  69. return errors.New("flag `--root-gen` requires flag `--root-key-obj`")
  70. case c.RootFile == "" && c.GenerateRoot && c.RootPath == "":
  71. return errors.New("flag `--root-gen` requires `--root-cert-path`")
  72. default:
  73. if c.RootFile != "" {
  74. c.GenerateRoot = false
  75. c.RootObject = ""
  76. c.RootKeyObject = ""
  77. }
  78. if c.CrtKeyPath != "" {
  79. c.CrtObject = ""
  80. c.CrtKeyObject = ""
  81. }
  82. if !c.EnableSSH {
  83. c.SSHHostKeyObject = ""
  84. c.SSHUserKeyObject = ""
  85. }
  86. return nil
  87. }
  88. }
  89. func main() {
  90. var kmsuri string
  91. switch runtime.GOOS {
  92. case "darwin":
  93. kmsuri = "pkcs11:module-path=/usr/local/lib/pkcs11/yubihsm_pkcs11.dylib;token=YubiHSM"
  94. case "linux":
  95. kmsuri = "pkcs11:module-path=/usr/lib/x86_64-linux-gnu/pkcs11/yubihsm_pkcs11.so;token=YubiHSM"
  96. case "windows":
  97. if home, err := os.UserHomeDir(); err == nil {
  98. kmsuri = "pkcs11:module-path=" + home + "\\yubihsm2-sdk\\bin\\yubihsm_pkcs11.dll" + ";token=YubiHSM"
  99. }
  100. }
  101. var c Config
  102. flag.StringVar(&c.KMS, "kms", kmsuri, "PKCS #11 URI with the module-path and token to connect to the module.")
  103. flag.StringVar(&c.Pin, "pin", "", "PKCS #11 PIN")
  104. // Option 1: Generate new root
  105. flag.BoolVar(&c.GenerateRoot, "root-gen", true, "Enable the generation of a root key.")
  106. flag.StringVar(&c.RootSubject, "root-name", "PKCS #11 Smallstep Root", "Subject and Issuer of the root certificate.")
  107. flag.StringVar(&c.RootObject, "root-cert-obj", "pkcs11:id=7330;object=root-cert", "PKCS #11 URI with object id and label to store the root certificate.")
  108. flag.StringVar(&c.RootKeyObject, "root-key-obj", "pkcs11:id=7330;object=root-key", "PKCS #11 URI with object id and label to store the root key.")
  109. // Option 2: Read root from disk and sign intermediate
  110. flag.StringVar(&c.RootFile, "root-cert-file", "", "Path to the root certificate to use.")
  111. flag.StringVar(&c.KeyFile, "root-key-file", "", "Path to the root key to use.")
  112. // Option 3: Generate certificate signing request
  113. flag.StringVar(&c.CrtSubject, "crt-name", "PKCS #11 Smallstep Intermediate", "Subject of the intermediate certificate.")
  114. flag.StringVar(&c.CrtObject, "crt-cert-obj", "pkcs11:id=7331;object=intermediate-cert", "PKCS #11 URI with object id and label to store the intermediate certificate.")
  115. flag.StringVar(&c.CrtKeyObject, "crt-key-obj", "pkcs11:id=7331;object=intermediate-key", "PKCS #11 URI with object id and label to store the intermediate certificate.")
  116. // SSH certificates
  117. flag.BoolVar(&c.EnableSSH, "ssh", false, "Enable the creation of ssh keys.")
  118. flag.StringVar(&c.SSHHostKeyObject, "ssh-host-key", "pkcs11:id=7332;object=ssh-host-key", "PKCS #11 URI with object id and label to store the key used to sign SSH host certificates.")
  119. flag.StringVar(&c.SSHUserKeyObject, "ssh-user-key", "pkcs11:id=7333;object=ssh-user-key", "PKCS #11 URI with object id and label to store the key used to sign SSH user certificates.")
  120. // Output files
  121. flag.StringVar(&c.RootPath, "root-cert-path", "root_ca.crt", "Location to write the root certificate.")
  122. flag.StringVar(&c.CrtPath, "crt-cert-path", "intermediate_ca.crt", "Location to write the intermediate certificate.")
  123. flag.StringVar(&c.CrtKeyPath, "crt-key-path", "", "Location to write the intermediate private key.")
  124. // Others
  125. flag.BoolVar(&c.NoCerts, "no-certs", false, "Do not store certificates in the module.")
  126. flag.BoolVar(&c.Force, "force", false, "Force the delete of previous keys.")
  127. flag.BoolVar(&c.Extractable, "extractable", false, "Allow export of private keys under wrap.")
  128. flag.Usage = usage
  129. flag.Parse()
  130. if err := c.Validate(); err != nil {
  131. fatal(err)
  132. }
  133. u, err := uri.ParseWithScheme("pkcs11", c.KMS)
  134. if err != nil {
  135. fatal(err)
  136. }
  137. // Initialize windows terminal
  138. ui.Init()
  139. if u.Get("pin-value") == "" && u.Get("pin-source") == "" && c.Pin == "" {
  140. pin, err := ui.PromptPassword("What is the PKCS#11 PIN?")
  141. if err != nil {
  142. fatal(err)
  143. }
  144. c.Pin = string(pin)
  145. }
  146. k, err := kms.New(context.Background(), apiv1.Options{
  147. Type: string(apiv1.PKCS11),
  148. URI: c.KMS,
  149. Pin: c.Pin,
  150. })
  151. if err != nil {
  152. fatal(err)
  153. }
  154. defer func() {
  155. _ = k.Close()
  156. }()
  157. // Check if the slots are empty, fail if they are not
  158. certUris := []string{
  159. c.RootObject, c.CrtObject,
  160. }
  161. keyUris := []string{
  162. c.RootKeyObject, c.CrtKeyObject,
  163. c.SSHHostKeyObject, c.SSHUserKeyObject,
  164. }
  165. if !c.Force {
  166. for _, u := range certUris {
  167. if u != "" && !c.NoCerts {
  168. checkObject(k, u)
  169. checkCertificate(k, u)
  170. }
  171. }
  172. for _, u := range keyUris {
  173. if u != "" {
  174. checkObject(k, u)
  175. }
  176. }
  177. } else {
  178. deleter, ok := k.(interface {
  179. DeleteKey(uri string) error
  180. DeleteCertificate(uri string) error
  181. })
  182. if ok {
  183. for _, u := range certUris {
  184. if u != "" && !c.NoCerts {
  185. // Some HSMs like Nitrokey will overwrite the key with the
  186. // certificate label.
  187. if err := deleter.DeleteKey(u); err != nil {
  188. fatalClose(err, k)
  189. }
  190. if err := deleter.DeleteCertificate(u); err != nil {
  191. fatalClose(err, k)
  192. }
  193. }
  194. }
  195. for _, u := range keyUris {
  196. if u != "" {
  197. if err := deleter.DeleteKey(u); err != nil {
  198. fatalClose(err, k)
  199. }
  200. }
  201. }
  202. }
  203. }
  204. if err := createPKI(k, c); err != nil {
  205. fatalClose(err, k)
  206. }
  207. // Reset windows terminal
  208. ui.Reset()
  209. }
  210. func fatal(err error) {
  211. if os.Getenv("STEPDEBUG") == "1" {
  212. fmt.Fprintf(os.Stderr, "%+v\n", err)
  213. } else {
  214. fmt.Fprintln(os.Stderr, err)
  215. }
  216. ui.Reset()
  217. os.Exit(1)
  218. }
  219. func fatalClose(err error, k kms.KeyManager) {
  220. _ = k.Close()
  221. fatal(err)
  222. }
  223. func usage() {
  224. fmt.Fprintln(os.Stderr, "Usage: step-pkcs11-init")
  225. fmt.Fprintln(os.Stderr, `
  226. The step-pkcs11-init command initializes a public key infrastructure (PKI)
  227. to be used by step-ca.
  228. This tool is experimental and in the future it will be integrated in step cli.
  229. OPTIONS`)
  230. fmt.Fprintln(os.Stderr)
  231. flag.PrintDefaults()
  232. fmt.Fprintf(os.Stderr, `
  233. COPYRIGHT
  234. (c) 2018-%d Smallstep Labs, Inc.
  235. `, time.Now().Year())
  236. os.Exit(1)
  237. }
  238. func checkCertificate(k kms.KeyManager, rawuri string) {
  239. if cm, ok := k.(kms.CertificateManager); ok {
  240. if _, err := cm.LoadCertificate(&apiv1.LoadCertificateRequest{
  241. Name: rawuri,
  242. }); err == nil {
  243. fmt.Fprintf(os.Stderr, "⚠️ Your PKCS #11 module already has a certificate on %s.\n", rawuri)
  244. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  245. _ = k.Close()
  246. os.Exit(1)
  247. }
  248. }
  249. }
  250. func checkObject(k kms.KeyManager, rawuri string) {
  251. if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  252. Name: rawuri,
  253. }); err == nil {
  254. fmt.Fprintf(os.Stderr, "⚠️ Your PKCS #11 module already has a key on %s.\n", rawuri)
  255. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  256. _ = k.Close()
  257. os.Exit(1)
  258. }
  259. }
  260. func createPKI(k kms.KeyManager, c Config) error {
  261. var err error
  262. ui.Println("Creating PKI ...")
  263. now := time.Now()
  264. // Root Certificate
  265. var signer crypto.Signer
  266. var root *x509.Certificate
  267. switch {
  268. case c.GenerateRoot:
  269. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  270. Name: c.RootKeyObject,
  271. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  272. Extractable: c.Extractable,
  273. })
  274. if err != nil {
  275. return err
  276. }
  277. signer, err = k.CreateSigner(&resp.CreateSignerRequest)
  278. if err != nil {
  279. return err
  280. }
  281. template := &x509.Certificate{
  282. IsCA: true,
  283. NotBefore: now,
  284. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  285. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  286. BasicConstraintsValid: true,
  287. MaxPathLen: 1,
  288. MaxPathLenZero: false,
  289. Issuer: pkix.Name{CommonName: c.RootSubject},
  290. Subject: pkix.Name{CommonName: c.RootSubject},
  291. SerialNumber: mustSerialNumber(),
  292. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  293. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  294. }
  295. b, err := x509.CreateCertificate(rand.Reader, template, template, resp.PublicKey, signer)
  296. if err != nil {
  297. return err
  298. }
  299. root, err = x509.ParseCertificate(b)
  300. if err != nil {
  301. return errors.Wrap(err, "error parsing root certificate")
  302. }
  303. if cm, ok := k.(kms.CertificateManager); ok && c.RootObject != "" && !c.NoCerts {
  304. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  305. Name: c.RootObject,
  306. Certificate: root,
  307. Extractable: c.Extractable,
  308. }); err != nil {
  309. return err
  310. }
  311. } else {
  312. c.RootObject = ""
  313. }
  314. if err := fileutil.WriteFile(c.RootPath, pem.EncodeToMemory(&pem.Block{
  315. Type: "CERTIFICATE",
  316. Bytes: b,
  317. }), 0600); err != nil {
  318. return err
  319. }
  320. ui.PrintSelected("Root Key", resp.Name)
  321. ui.PrintSelected("Root Certificate", c.RootPath)
  322. if c.RootObject != "" {
  323. ui.PrintSelected("Root Certificate Object", c.RootObject)
  324. }
  325. case c.RootFile != "" && c.KeyFile != "": // Read Root From File
  326. root, err = pemutil.ReadCertificate(c.RootFile)
  327. if err != nil {
  328. return err
  329. }
  330. key, err := pemutil.Read(c.KeyFile)
  331. if err != nil {
  332. return err
  333. }
  334. var ok bool
  335. if signer, ok = key.(crypto.Signer); !ok {
  336. return errors.Errorf("key type '%T' does not implement a signer", key)
  337. }
  338. }
  339. // Intermediate Certificate
  340. var keyName string
  341. var publicKey crypto.PublicKey
  342. var intSigner crypto.Signer
  343. if c.CrtKeyPath != "" {
  344. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  345. if err != nil {
  346. return errors.Wrap(err, "error creating intermediate key")
  347. }
  348. pass, err := ui.PromptPasswordGenerate("What do you want your password to be? [leave empty and we'll generate one]",
  349. ui.WithRichPrompt())
  350. if err != nil {
  351. return err
  352. }
  353. _, err = pemutil.Serialize(priv, pemutil.WithPassword(pass), pemutil.ToFile(c.CrtKeyPath, 0600))
  354. if err != nil {
  355. return err
  356. }
  357. publicKey = priv.Public()
  358. intSigner = priv
  359. } else {
  360. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  361. Name: c.CrtKeyObject,
  362. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  363. Extractable: c.Extractable,
  364. })
  365. if err != nil {
  366. return err
  367. }
  368. publicKey = resp.PublicKey
  369. keyName = resp.Name
  370. intSigner, err = k.CreateSigner(&resp.CreateSignerRequest)
  371. if err != nil {
  372. return err
  373. }
  374. }
  375. if root != nil {
  376. template := &x509.Certificate{
  377. IsCA: true,
  378. NotBefore: now,
  379. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  380. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  381. BasicConstraintsValid: true,
  382. MaxPathLen: 0,
  383. MaxPathLenZero: true,
  384. Issuer: root.Subject,
  385. Subject: pkix.Name{CommonName: c.CrtSubject},
  386. SerialNumber: mustSerialNumber(),
  387. SubjectKeyId: mustSubjectKeyID(publicKey),
  388. }
  389. b, err := x509.CreateCertificate(rand.Reader, template, root, publicKey, signer)
  390. if err != nil {
  391. return err
  392. }
  393. intermediate, err := x509.ParseCertificate(b)
  394. if err != nil {
  395. return errors.Wrap(err, "error parsing intermediate certificate")
  396. }
  397. if cm, ok := k.(kms.CertificateManager); ok && c.CrtObject != "" && !c.NoCerts {
  398. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  399. Name: c.CrtObject,
  400. Certificate: intermediate,
  401. Extractable: c.Extractable,
  402. }); err != nil {
  403. return err
  404. }
  405. } else {
  406. c.CrtObject = ""
  407. }
  408. if err := fileutil.WriteFile(c.CrtPath, pem.EncodeToMemory(&pem.Block{
  409. Type: "CERTIFICATE",
  410. Bytes: b,
  411. }), 0600); err != nil {
  412. return err
  413. }
  414. } else {
  415. // No root available, generate CSR for external root.
  416. csrTemplate := x509.CertificateRequest{
  417. Subject: pkix.Name{CommonName: c.CrtSubject},
  418. SignatureAlgorithm: x509.ECDSAWithSHA256,
  419. }
  420. // step: generate the csr request
  421. csrCertificate, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, intSigner)
  422. if err != nil {
  423. return err
  424. }
  425. if err := fileutil.WriteFile(c.CrtPath, pem.EncodeToMemory(&pem.Block{
  426. Type: "CERTIFICATE REQUEST",
  427. Bytes: csrCertificate,
  428. }), 0600); err != nil {
  429. return err
  430. }
  431. }
  432. if c.CrtKeyPath != "" {
  433. ui.PrintSelected("Intermediate Key", c.CrtKeyPath)
  434. } else {
  435. ui.PrintSelected("Intermediate Key", keyName)
  436. }
  437. if root != nil {
  438. ui.PrintSelected("Intermediate Certificate", c.CrtPath)
  439. if c.CrtObject != "" {
  440. ui.PrintSelected("Intermediate Certificate Object", c.CrtObject)
  441. }
  442. } else {
  443. ui.PrintSelected("Intermediate Certificate Request", c.CrtPath)
  444. }
  445. if c.SSHHostKeyObject != "" {
  446. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  447. Name: c.SSHHostKeyObject,
  448. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  449. })
  450. if err != nil {
  451. return err
  452. }
  453. ui.PrintSelected("SSH Host Key", resp.Name)
  454. }
  455. if c.SSHUserKeyObject != "" {
  456. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  457. Name: c.SSHUserKeyObject,
  458. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  459. })
  460. if err != nil {
  461. return err
  462. }
  463. ui.PrintSelected("SSH User Key", resp.Name)
  464. }
  465. return nil
  466. }
  467. func mustSerialNumber() *big.Int {
  468. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  469. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  470. if err != nil {
  471. panic(err)
  472. }
  473. return sn
  474. }
  475. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  476. b, err := x509.MarshalPKIXPublicKey(key)
  477. if err != nil {
  478. panic(err)
  479. }
  480. hash := sha1.Sum(b)
  481. return hash[:]
  482. }