main.go 12 KB

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