main.go 16 KB

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