main.go 13 KB

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