main.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "github.com/smallstep/cli/crypto/pemutil"
  19. "github.com/smallstep/cli/ui"
  20. "github.com/smallstep/cli/utils"
  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. }
  124. b, err := x509.CreateCertificate(rand.Reader, root, root, resp.PublicKey, signer)
  125. if err != nil {
  126. return err
  127. }
  128. if err = utils.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  129. Type: "CERTIFICATE",
  130. Bytes: b,
  131. }), 0600); err != nil {
  132. return err
  133. }
  134. ui.PrintSelected("Root Key", resp.Name)
  135. ui.PrintSelected("Root Certificate", "root_ca.crt")
  136. root, err = pemutil.ReadCertificate("root_ca.crt")
  137. if err != nil {
  138. return err
  139. }
  140. // Intermediate Certificate
  141. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  142. Name: parent + "/intermediate",
  143. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  144. ProtectionLevel: protectionLevel,
  145. })
  146. if err != nil {
  147. return err
  148. }
  149. intermediate := &x509.Certificate{
  150. IsCA: true,
  151. NotBefore: now,
  152. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  153. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  154. BasicConstraintsValid: true,
  155. MaxPathLen: 0,
  156. MaxPathLenZero: true,
  157. Issuer: root.Subject,
  158. Subject: pkix.Name{CommonName: "Smallstep Intermediate"},
  159. SerialNumber: mustSerialNumber(),
  160. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  161. }
  162. b, err = x509.CreateCertificate(rand.Reader, intermediate, root, resp.PublicKey, signer)
  163. if err != nil {
  164. return err
  165. }
  166. if err = utils.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  167. Type: "CERTIFICATE",
  168. Bytes: b,
  169. }), 0600); err != nil {
  170. return err
  171. }
  172. ui.PrintSelected("Intermediate Key", resp.Name)
  173. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  174. return nil
  175. }
  176. func createSSH(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  177. ui.Println("Creating SSH Keys ...")
  178. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  179. // User Key
  180. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  181. Name: parent + "/ssh-user-key",
  182. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  183. ProtectionLevel: protectionLevel,
  184. })
  185. if err != nil {
  186. return err
  187. }
  188. key, err := ssh.NewPublicKey(resp.PublicKey)
  189. if err != nil {
  190. return err
  191. }
  192. if err = utils.WriteFile("ssh_user_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  193. return err
  194. }
  195. ui.PrintSelected("SSH User Public Key", "ssh_user_ca_key.pub")
  196. ui.PrintSelected("SSH User Private Key", resp.Name)
  197. // Host Key
  198. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  199. Name: parent + "/ssh-host-key",
  200. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  201. ProtectionLevel: apiv1.Software,
  202. })
  203. if err != nil {
  204. return err
  205. }
  206. key, err = ssh.NewPublicKey(resp.PublicKey)
  207. if err != nil {
  208. return err
  209. }
  210. if err = utils.WriteFile("ssh_host_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  211. return err
  212. }
  213. ui.PrintSelected("SSH Host Public Key", "ssh_host_ca_key.pub")
  214. ui.PrintSelected("SSH Host Private Key", resp.Name)
  215. return nil
  216. }
  217. func mustSerialNumber() *big.Int {
  218. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  219. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  220. if err != nil {
  221. panic(err)
  222. }
  223. return sn
  224. }
  225. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  226. b, err := x509.MarshalPKIXPublicKey(key)
  227. if err != nil {
  228. panic(err)
  229. }
  230. hash := sha1.Sum(b)
  231. return hash[:]
  232. }