4
0

main.go 7.1 KB

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