4
0

main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package main
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/rand"
  6. "crypto/sha1"
  7. "crypto/x509"
  8. "crypto/x509/pkix"
  9. "encoding/pem"
  10. "flag"
  11. "fmt"
  12. "math/big"
  13. "os"
  14. "strings"
  15. "time"
  16. "github.com/smallstep/certificates/kms/apiv1"
  17. "github.com/smallstep/certificates/kms/cloudkms"
  18. "go.step.sm/cli-utils/fileutil"
  19. "go.step.sm/cli-utils/ui"
  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. c, err := cloudkms.New(context.Background(), apiv1.Options{
  62. Type: string(apiv1.CloudKMS),
  63. CredentialsFile: credentialsFile,
  64. })
  65. if err != nil {
  66. fatal(err)
  67. }
  68. if err := createPKI(c, project, location, ring, protectionLevel); err != nil {
  69. fatal(err)
  70. }
  71. if enableSSH {
  72. ui.Println()
  73. if err := createSSH(c, project, location, ring, protectionLevel); err != nil {
  74. fatal(err)
  75. }
  76. }
  77. // Reset windows terminal
  78. ui.Reset()
  79. }
  80. func fatal(err error) {
  81. fmt.Fprintln(os.Stderr, err)
  82. ui.Reset()
  83. os.Exit(1)
  84. }
  85. func usage() {
  86. fmt.Fprintln(os.Stderr, "Usage: step-cloudkms-init --project <name>")
  87. fmt.Fprintln(os.Stderr, `
  88. The step-cloudkms-init command initializes a public key infrastructure (PKI)
  89. to be used by step-ca.
  90. This tool is experimental and in the future it will be integrated in step cli.
  91. OPTIONS`)
  92. fmt.Fprintln(os.Stderr)
  93. flag.PrintDefaults()
  94. fmt.Fprintln(os.Stderr, `
  95. COPYRIGHT
  96. (c) 2018-2020 Smallstep Labs, Inc.`)
  97. os.Exit(1)
  98. }
  99. func createPKI(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  100. ui.Println("Creating PKI ...")
  101. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  102. // Root Certificate
  103. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  104. Name: parent + "/root",
  105. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  106. ProtectionLevel: protectionLevel,
  107. })
  108. if err != nil {
  109. return err
  110. }
  111. signer, err := c.CreateSigner(&resp.CreateSignerRequest)
  112. if err != nil {
  113. return err
  114. }
  115. now := time.Now()
  116. root := &x509.Certificate{
  117. IsCA: true,
  118. NotBefore: now,
  119. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  120. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  121. BasicConstraintsValid: true,
  122. MaxPathLen: 1,
  123. MaxPathLenZero: false,
  124. Issuer: pkix.Name{CommonName: "Smallstep Root"},
  125. Subject: pkix.Name{CommonName: "Smallstep Root"},
  126. SerialNumber: mustSerialNumber(),
  127. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  128. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  129. }
  130. b, err := x509.CreateCertificate(rand.Reader, root, root, resp.PublicKey, signer)
  131. if err != nil {
  132. return err
  133. }
  134. if err := fileutil.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  135. Type: "CERTIFICATE",
  136. Bytes: b,
  137. }), 0600); err != nil {
  138. return err
  139. }
  140. ui.PrintSelected("Root Key", resp.Name)
  141. ui.PrintSelected("Root Certificate", "root_ca.crt")
  142. root, err = pemutil.ReadCertificate("root_ca.crt")
  143. if err != nil {
  144. return err
  145. }
  146. // Intermediate Certificate
  147. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  148. Name: parent + "/intermediate",
  149. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  150. ProtectionLevel: protectionLevel,
  151. })
  152. if err != nil {
  153. return err
  154. }
  155. intermediate := &x509.Certificate{
  156. IsCA: true,
  157. NotBefore: now,
  158. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  159. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  160. BasicConstraintsValid: true,
  161. MaxPathLen: 0,
  162. MaxPathLenZero: true,
  163. Issuer: root.Subject,
  164. Subject: pkix.Name{CommonName: "Smallstep Intermediate"},
  165. SerialNumber: mustSerialNumber(),
  166. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  167. }
  168. b, err = x509.CreateCertificate(rand.Reader, intermediate, root, resp.PublicKey, signer)
  169. if err != nil {
  170. return err
  171. }
  172. if err := fileutil.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  173. Type: "CERTIFICATE",
  174. Bytes: b,
  175. }), 0600); err != nil {
  176. return err
  177. }
  178. ui.PrintSelected("Intermediate Key", resp.Name)
  179. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  180. return nil
  181. }
  182. func createSSH(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  183. ui.Println("Creating SSH Keys ...")
  184. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  185. // User Key
  186. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  187. Name: parent + "/ssh-user-key",
  188. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  189. ProtectionLevel: protectionLevel,
  190. })
  191. if err != nil {
  192. return err
  193. }
  194. key, err := ssh.NewPublicKey(resp.PublicKey)
  195. if err != nil {
  196. return err
  197. }
  198. if err := fileutil.WriteFile("ssh_user_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  199. return err
  200. }
  201. ui.PrintSelected("SSH User Public Key", "ssh_user_ca_key.pub")
  202. ui.PrintSelected("SSH User Private Key", resp.Name)
  203. // Host Key
  204. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  205. Name: parent + "/ssh-host-key",
  206. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  207. ProtectionLevel: protectionLevel,
  208. })
  209. if err != nil {
  210. return err
  211. }
  212. key, err = ssh.NewPublicKey(resp.PublicKey)
  213. if err != nil {
  214. return err
  215. }
  216. if err := fileutil.WriteFile("ssh_host_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  217. return err
  218. }
  219. ui.PrintSelected("SSH Host Public Key", "ssh_host_ca_key.pub")
  220. ui.PrintSelected("SSH Host Private Key", resp.Name)
  221. return nil
  222. }
  223. func mustSerialNumber() *big.Int {
  224. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  225. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  226. if err != nil {
  227. panic(err)
  228. }
  229. return sn
  230. }
  231. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  232. b, err := x509.MarshalPKIXPublicKey(key)
  233. if err != nil {
  234. panic(err)
  235. }
  236. hash := sha1.Sum(b)
  237. return hash[:]
  238. }