4
0

main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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.Fprintln(os.Stderr, `
  233. COPYRIGHT
  234. (c) 2018-2021 Smallstep Labs, Inc.`)
  235. os.Exit(1)
  236. }
  237. func checkCertificate(k kms.KeyManager, rawuri string) {
  238. if cm, ok := k.(kms.CertificateManager); ok {
  239. if _, err := cm.LoadCertificate(&apiv1.LoadCertificateRequest{
  240. Name: rawuri,
  241. }); err == nil {
  242. fmt.Fprintf(os.Stderr, "⚠️ Your PKCS #11 module already has a certificate on %s.\n", rawuri)
  243. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  244. _ = k.Close()
  245. os.Exit(1)
  246. }
  247. }
  248. }
  249. func checkObject(k kms.KeyManager, rawuri string) {
  250. if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  251. Name: rawuri,
  252. }); err == nil {
  253. fmt.Fprintf(os.Stderr, "⚠️ Your PKCS #11 module already has a key on %s.\n", rawuri)
  254. fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.")
  255. _ = k.Close()
  256. os.Exit(1)
  257. }
  258. }
  259. func createPKI(k kms.KeyManager, c Config) error {
  260. var err error
  261. ui.Println("Creating PKI ...")
  262. now := time.Now()
  263. // Root Certificate
  264. var signer crypto.Signer
  265. var root *x509.Certificate
  266. switch {
  267. case c.GenerateRoot:
  268. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  269. Name: c.RootKeyObject,
  270. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  271. Extractable: c.Extractable,
  272. })
  273. if err != nil {
  274. return err
  275. }
  276. signer, err = k.CreateSigner(&resp.CreateSignerRequest)
  277. if err != nil {
  278. return err
  279. }
  280. template := &x509.Certificate{
  281. IsCA: true,
  282. NotBefore: now,
  283. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  284. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  285. BasicConstraintsValid: true,
  286. MaxPathLen: 1,
  287. MaxPathLenZero: false,
  288. Issuer: pkix.Name{CommonName: c.RootSubject},
  289. Subject: pkix.Name{CommonName: c.RootSubject},
  290. SerialNumber: mustSerialNumber(),
  291. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  292. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  293. }
  294. b, err := x509.CreateCertificate(rand.Reader, template, template, resp.PublicKey, signer)
  295. if err != nil {
  296. return err
  297. }
  298. root, err = x509.ParseCertificate(b)
  299. if err != nil {
  300. return errors.Wrap(err, "error parsing root certificate")
  301. }
  302. if cm, ok := k.(kms.CertificateManager); ok && c.RootObject != "" && !c.NoCerts {
  303. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  304. Name: c.RootObject,
  305. Certificate: root,
  306. Extractable: c.Extractable,
  307. }); err != nil {
  308. return err
  309. }
  310. } else {
  311. c.RootObject = ""
  312. }
  313. if err := fileutil.WriteFile(c.RootPath, pem.EncodeToMemory(&pem.Block{
  314. Type: "CERTIFICATE",
  315. Bytes: b,
  316. }), 0600); err != nil {
  317. return err
  318. }
  319. ui.PrintSelected("Root Key", resp.Name)
  320. ui.PrintSelected("Root Certificate", c.RootPath)
  321. if c.RootObject != "" {
  322. ui.PrintSelected("Root Certificate Object", c.RootObject)
  323. }
  324. case c.RootFile != "" && c.KeyFile != "": // Read Root From File
  325. root, err = pemutil.ReadCertificate(c.RootFile)
  326. if err != nil {
  327. return err
  328. }
  329. key, err := pemutil.Read(c.KeyFile)
  330. if err != nil {
  331. return err
  332. }
  333. var ok bool
  334. if signer, ok = key.(crypto.Signer); !ok {
  335. return errors.Errorf("key type '%T' does not implement a signer", key)
  336. }
  337. }
  338. // Intermediate Certificate
  339. var keyName string
  340. var publicKey crypto.PublicKey
  341. var intSigner crypto.Signer
  342. if c.CrtKeyPath != "" {
  343. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  344. if err != nil {
  345. return errors.Wrap(err, "error creating intermediate key")
  346. }
  347. pass, err := ui.PromptPasswordGenerate("What do you want your password to be? [leave empty and we'll generate one]",
  348. ui.WithRichPrompt())
  349. if err != nil {
  350. return err
  351. }
  352. _, err = pemutil.Serialize(priv, pemutil.WithPassword(pass), pemutil.ToFile(c.CrtKeyPath, 0600))
  353. if err != nil {
  354. return err
  355. }
  356. publicKey = priv.Public()
  357. intSigner = priv
  358. } else {
  359. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  360. Name: c.CrtKeyObject,
  361. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  362. Extractable: c.Extractable,
  363. })
  364. if err != nil {
  365. return err
  366. }
  367. publicKey = resp.PublicKey
  368. keyName = resp.Name
  369. intSigner, err = k.CreateSigner(&resp.CreateSignerRequest)
  370. if err != nil {
  371. return err
  372. }
  373. }
  374. if root != nil {
  375. template := &x509.Certificate{
  376. IsCA: true,
  377. NotBefore: now,
  378. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  379. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  380. BasicConstraintsValid: true,
  381. MaxPathLen: 0,
  382. MaxPathLenZero: true,
  383. Issuer: root.Subject,
  384. Subject: pkix.Name{CommonName: c.CrtSubject},
  385. SerialNumber: mustSerialNumber(),
  386. SubjectKeyId: mustSubjectKeyID(publicKey),
  387. }
  388. b, err := x509.CreateCertificate(rand.Reader, template, root, publicKey, signer)
  389. if err != nil {
  390. return err
  391. }
  392. intermediate, err := x509.ParseCertificate(b)
  393. if err != nil {
  394. return errors.Wrap(err, "error parsing intermediate certificate")
  395. }
  396. if cm, ok := k.(kms.CertificateManager); ok && c.CrtObject != "" && !c.NoCerts {
  397. if err := cm.StoreCertificate(&apiv1.StoreCertificateRequest{
  398. Name: c.CrtObject,
  399. Certificate: intermediate,
  400. Extractable: c.Extractable,
  401. }); err != nil {
  402. return err
  403. }
  404. } else {
  405. c.CrtObject = ""
  406. }
  407. if err := fileutil.WriteFile(c.CrtPath, pem.EncodeToMemory(&pem.Block{
  408. Type: "CERTIFICATE",
  409. Bytes: b,
  410. }), 0600); err != nil {
  411. return err
  412. }
  413. } else {
  414. // No root available, generate CSR for external root.
  415. csrTemplate := x509.CertificateRequest{
  416. Subject: pkix.Name{CommonName: c.CrtSubject},
  417. SignatureAlgorithm: x509.ECDSAWithSHA256,
  418. }
  419. // step: generate the csr request
  420. csrCertificate, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, intSigner)
  421. if err != nil {
  422. return err
  423. }
  424. if err := fileutil.WriteFile(c.CrtPath, pem.EncodeToMemory(&pem.Block{
  425. Type: "CERTIFICATE REQUEST",
  426. Bytes: csrCertificate,
  427. }), 0600); err != nil {
  428. return err
  429. }
  430. }
  431. if c.CrtKeyPath != "" {
  432. ui.PrintSelected("Intermediate Key", c.CrtKeyPath)
  433. } else {
  434. ui.PrintSelected("Intermediate Key", keyName)
  435. }
  436. if root != nil {
  437. ui.PrintSelected("Intermediate Certificate", c.CrtPath)
  438. if c.CrtObject != "" {
  439. ui.PrintSelected("Intermediate Certificate Object", c.CrtObject)
  440. }
  441. } else {
  442. ui.PrintSelected("Intermediate Certificate Request", c.CrtPath)
  443. }
  444. if c.SSHHostKeyObject != "" {
  445. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  446. Name: c.SSHHostKeyObject,
  447. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  448. })
  449. if err != nil {
  450. return err
  451. }
  452. ui.PrintSelected("SSH Host Key", resp.Name)
  453. }
  454. if c.SSHUserKeyObject != "" {
  455. resp, err := k.CreateKey(&apiv1.CreateKeyRequest{
  456. Name: c.SSHUserKeyObject,
  457. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  458. })
  459. if err != nil {
  460. return err
  461. }
  462. ui.PrintSelected("SSH User Key", resp.Name)
  463. }
  464. return nil
  465. }
  466. func mustSerialNumber() *big.Int {
  467. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  468. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  469. if err != nil {
  470. panic(err)
  471. }
  472. return sn
  473. }
  474. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  475. b, err := x509.MarshalPKIXPublicKey(key)
  476. if err != nil {
  477. panic(err)
  478. }
  479. hash := sha1.Sum(b)
  480. return hash[:]
  481. }