4
0

main.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package main
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/rand"
  6. "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280
  7. "crypto/x509"
  8. "crypto/x509/pkix"
  9. "encoding/pem"
  10. "flag"
  11. "fmt"
  12. "math/big"
  13. "os"
  14. "strings"
  15. "time"
  16. "go.step.sm/cli-utils/fileutil"
  17. "go.step.sm/cli-utils/ui"
  18. "go.step.sm/crypto/kms/apiv1"
  19. "go.step.sm/crypto/kms/cloudkms"
  20. "go.step.sm/crypto/pemutil"
  21. "golang.org/x/crypto/ssh"
  22. )
  23. func main() {
  24. var credentialsFile string
  25. var project, location, ring string
  26. var protectionLevelName string
  27. var enableSSH bool
  28. flag.StringVar(&credentialsFile, "credentials-file", "", "Path to the `file` containing the Google's Cloud KMS credentials.")
  29. flag.StringVar(&project, "project", "", "Google Cloud Project ID.")
  30. flag.StringVar(&location, "location", "global", "Cloud KMS location name.")
  31. flag.StringVar(&ring, "ring", "pki", "Cloud KMS ring name.")
  32. flag.StringVar(&protectionLevelName, "protection-level", "SOFTWARE", "Protection level to use, SOFTWARE or HSM.")
  33. flag.BoolVar(&enableSSH, "ssh", false, "Create SSH keys.")
  34. flag.Usage = usage
  35. flag.Parse()
  36. switch {
  37. case project == "":
  38. usage()
  39. case location == "":
  40. fmt.Fprintln(os.Stderr, "flag `--location` is required")
  41. os.Exit(1)
  42. case ring == "":
  43. fmt.Fprintln(os.Stderr, "flag `--ring` is required")
  44. os.Exit(1)
  45. case protectionLevelName == "":
  46. fmt.Fprintln(os.Stderr, "flag `--protection-level` is required")
  47. os.Exit(1)
  48. }
  49. var protectionLevel apiv1.ProtectionLevel
  50. switch strings.ToUpper(protectionLevelName) {
  51. case "SOFTWARE":
  52. protectionLevel = apiv1.Software
  53. case "HSM":
  54. protectionLevel = apiv1.HSM
  55. default:
  56. fmt.Fprintf(os.Stderr, "invalid value `%s` for flag `--protection-level`; options are `SOFTWARE` or `HSM`\n", protectionLevelName)
  57. os.Exit(1)
  58. }
  59. // Initialize windows terminal
  60. ui.Init()
  61. ui.Println("⚠️ This command is deprecated and will be removed in future releases.")
  62. ui.Println("⚠️ Please use https://github.com/smallstep/step-kms-plugin instead.")
  63. c, err := cloudkms.New(context.Background(), apiv1.Options{
  64. Type: apiv1.CloudKMS,
  65. CredentialsFile: credentialsFile,
  66. })
  67. if err != nil {
  68. fatal(err)
  69. }
  70. if err := createPKI(c, project, location, ring, protectionLevel); err != nil {
  71. fatal(err)
  72. }
  73. if enableSSH {
  74. ui.Println()
  75. if err := createSSH(c, project, location, ring, protectionLevel); err != nil {
  76. fatal(err)
  77. }
  78. }
  79. // Reset windows terminal
  80. ui.Reset()
  81. }
  82. func fatal(err error) {
  83. fmt.Fprintln(os.Stderr, err)
  84. ui.Reset()
  85. os.Exit(1)
  86. }
  87. func usage() {
  88. fmt.Fprintln(os.Stderr, "Usage: step-cloudkms-init --project <name>")
  89. fmt.Fprintln(os.Stderr, `
  90. The step-cloudkms-init command initializes a public key infrastructure (PKI)
  91. to be used by step-ca.
  92. This tool is experimental and in the future it will be integrated in step cli.
  93. OPTIONS`)
  94. fmt.Fprintln(os.Stderr)
  95. flag.PrintDefaults()
  96. fmt.Fprintf(os.Stderr, `
  97. COPYRIGHT
  98. (c) 2018-%d Smallstep Labs, Inc.
  99. `, time.Now().Year())
  100. os.Exit(1)
  101. }
  102. func createPKI(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  103. ui.Println("Creating PKI ...")
  104. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  105. // Root Certificate
  106. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  107. Name: parent + "/root",
  108. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  109. ProtectionLevel: protectionLevel,
  110. })
  111. if err != nil {
  112. return err
  113. }
  114. signer, err := c.CreateSigner(&resp.CreateSignerRequest)
  115. if err != nil {
  116. return err
  117. }
  118. now := time.Now()
  119. root := &x509.Certificate{
  120. IsCA: true,
  121. NotBefore: now,
  122. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  123. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  124. BasicConstraintsValid: true,
  125. MaxPathLen: 1,
  126. MaxPathLenZero: false,
  127. Issuer: pkix.Name{CommonName: "Smallstep Root"},
  128. Subject: pkix.Name{CommonName: "Smallstep Root"},
  129. SerialNumber: mustSerialNumber(),
  130. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  131. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  132. }
  133. b, err := x509.CreateCertificate(rand.Reader, root, root, resp.PublicKey, signer)
  134. if err != nil {
  135. return err
  136. }
  137. if err := fileutil.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  138. Type: "CERTIFICATE",
  139. Bytes: b,
  140. }), 0600); err != nil {
  141. return err
  142. }
  143. ui.PrintSelected("Root Key", resp.Name)
  144. ui.PrintSelected("Root Certificate", "root_ca.crt")
  145. root, err = pemutil.ReadCertificate("root_ca.crt")
  146. if err != nil {
  147. return err
  148. }
  149. // Intermediate Certificate
  150. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  151. Name: parent + "/intermediate",
  152. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  153. ProtectionLevel: protectionLevel,
  154. })
  155. if err != nil {
  156. return err
  157. }
  158. intermediate := &x509.Certificate{
  159. IsCA: true,
  160. NotBefore: now,
  161. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  162. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  163. BasicConstraintsValid: true,
  164. MaxPathLen: 0,
  165. MaxPathLenZero: true,
  166. Issuer: root.Subject,
  167. Subject: pkix.Name{CommonName: "Smallstep Intermediate"},
  168. SerialNumber: mustSerialNumber(),
  169. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  170. }
  171. b, err = x509.CreateCertificate(rand.Reader, intermediate, root, resp.PublicKey, signer)
  172. if err != nil {
  173. return err
  174. }
  175. if err := fileutil.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  176. Type: "CERTIFICATE",
  177. Bytes: b,
  178. }), 0600); err != nil {
  179. return err
  180. }
  181. ui.PrintSelected("Intermediate Key", resp.Name)
  182. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  183. return nil
  184. }
  185. func createSSH(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  186. ui.Println("Creating SSH Keys ...")
  187. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  188. // User Key
  189. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  190. Name: parent + "/ssh-user-key",
  191. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  192. ProtectionLevel: protectionLevel,
  193. })
  194. if err != nil {
  195. return err
  196. }
  197. key, err := ssh.NewPublicKey(resp.PublicKey)
  198. if err != nil {
  199. return err
  200. }
  201. if err := fileutil.WriteFile("ssh_user_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  202. return err
  203. }
  204. ui.PrintSelected("SSH User Public Key", "ssh_user_ca_key.pub")
  205. ui.PrintSelected("SSH User Private Key", resp.Name)
  206. // Host Key
  207. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  208. Name: parent + "/ssh-host-key",
  209. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  210. ProtectionLevel: protectionLevel,
  211. })
  212. if err != nil {
  213. return err
  214. }
  215. key, err = ssh.NewPublicKey(resp.PublicKey)
  216. if err != nil {
  217. return err
  218. }
  219. if err := fileutil.WriteFile("ssh_host_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  220. return err
  221. }
  222. ui.PrintSelected("SSH Host Public Key", "ssh_host_ca_key.pub")
  223. ui.PrintSelected("SSH Host Private Key", resp.Name)
  224. return nil
  225. }
  226. func mustSerialNumber() *big.Int {
  227. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  228. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  229. if err != nil {
  230. panic(err)
  231. }
  232. return sn
  233. }
  234. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  235. b, err := x509.MarshalPKIXPublicKey(key)
  236. if err != nil {
  237. panic(err)
  238. }
  239. //nolint:gosec // used to create the Subject Key Identifier by RFC 5280
  240. hash := sha1.Sum(b)
  241. return hash[:]
  242. }