main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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.Fprintf(os.Stderr, `
  95. COPYRIGHT
  96. (c) 2018-%d Smallstep Labs, Inc.
  97. `, time.Now().Year())
  98. os.Exit(1)
  99. }
  100. func createPKI(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  101. ui.Println("Creating PKI ...")
  102. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  103. // Root Certificate
  104. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  105. Name: parent + "/root",
  106. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  107. ProtectionLevel: protectionLevel,
  108. })
  109. if err != nil {
  110. return err
  111. }
  112. signer, err := c.CreateSigner(&resp.CreateSignerRequest)
  113. if err != nil {
  114. return err
  115. }
  116. now := time.Now()
  117. root := &x509.Certificate{
  118. IsCA: true,
  119. NotBefore: now,
  120. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  121. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  122. BasicConstraintsValid: true,
  123. MaxPathLen: 1,
  124. MaxPathLenZero: false,
  125. Issuer: pkix.Name{CommonName: "Smallstep Root"},
  126. Subject: pkix.Name{CommonName: "Smallstep Root"},
  127. SerialNumber: mustSerialNumber(),
  128. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  129. AuthorityKeyId: mustSubjectKeyID(resp.PublicKey),
  130. }
  131. b, err := x509.CreateCertificate(rand.Reader, root, root, resp.PublicKey, signer)
  132. if err != nil {
  133. return err
  134. }
  135. if err := fileutil.WriteFile("root_ca.crt", pem.EncodeToMemory(&pem.Block{
  136. Type: "CERTIFICATE",
  137. Bytes: b,
  138. }), 0600); err != nil {
  139. return err
  140. }
  141. ui.PrintSelected("Root Key", resp.Name)
  142. ui.PrintSelected("Root Certificate", "root_ca.crt")
  143. root, err = pemutil.ReadCertificate("root_ca.crt")
  144. if err != nil {
  145. return err
  146. }
  147. // Intermediate Certificate
  148. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  149. Name: parent + "/intermediate",
  150. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  151. ProtectionLevel: protectionLevel,
  152. })
  153. if err != nil {
  154. return err
  155. }
  156. intermediate := &x509.Certificate{
  157. IsCA: true,
  158. NotBefore: now,
  159. NotAfter: now.Add(time.Hour * 24 * 365 * 10),
  160. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  161. BasicConstraintsValid: true,
  162. MaxPathLen: 0,
  163. MaxPathLenZero: true,
  164. Issuer: root.Subject,
  165. Subject: pkix.Name{CommonName: "Smallstep Intermediate"},
  166. SerialNumber: mustSerialNumber(),
  167. SubjectKeyId: mustSubjectKeyID(resp.PublicKey),
  168. }
  169. b, err = x509.CreateCertificate(rand.Reader, intermediate, root, resp.PublicKey, signer)
  170. if err != nil {
  171. return err
  172. }
  173. if err := fileutil.WriteFile("intermediate_ca.crt", pem.EncodeToMemory(&pem.Block{
  174. Type: "CERTIFICATE",
  175. Bytes: b,
  176. }), 0600); err != nil {
  177. return err
  178. }
  179. ui.PrintSelected("Intermediate Key", resp.Name)
  180. ui.PrintSelected("Intermediate Certificate", "intermediate_ca.crt")
  181. return nil
  182. }
  183. func createSSH(c *cloudkms.CloudKMS, project, location, keyRing string, protectionLevel apiv1.ProtectionLevel) error {
  184. ui.Println("Creating SSH Keys ...")
  185. parent := "projects/" + project + "/locations/" + location + "/keyRings/" + keyRing + "/cryptoKeys"
  186. // User Key
  187. resp, err := c.CreateKey(&apiv1.CreateKeyRequest{
  188. Name: parent + "/ssh-user-key",
  189. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  190. ProtectionLevel: protectionLevel,
  191. })
  192. if err != nil {
  193. return err
  194. }
  195. key, err := ssh.NewPublicKey(resp.PublicKey)
  196. if err != nil {
  197. return err
  198. }
  199. if err := fileutil.WriteFile("ssh_user_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  200. return err
  201. }
  202. ui.PrintSelected("SSH User Public Key", "ssh_user_ca_key.pub")
  203. ui.PrintSelected("SSH User Private Key", resp.Name)
  204. // Host Key
  205. resp, err = c.CreateKey(&apiv1.CreateKeyRequest{
  206. Name: parent + "/ssh-host-key",
  207. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  208. ProtectionLevel: protectionLevel,
  209. })
  210. if err != nil {
  211. return err
  212. }
  213. key, err = ssh.NewPublicKey(resp.PublicKey)
  214. if err != nil {
  215. return err
  216. }
  217. if err := fileutil.WriteFile("ssh_host_ca_key.pub", ssh.MarshalAuthorizedKey(key), 0600); err != nil {
  218. return err
  219. }
  220. ui.PrintSelected("SSH Host Public Key", "ssh_host_ca_key.pub")
  221. ui.PrintSelected("SSH Host Private Key", resp.Name)
  222. return nil
  223. }
  224. func mustSerialNumber() *big.Int {
  225. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  226. sn, err := rand.Int(rand.Reader, serialNumberLimit)
  227. if err != nil {
  228. panic(err)
  229. }
  230. return sn
  231. }
  232. func mustSubjectKeyID(key crypto.PublicKey) []byte {
  233. b, err := x509.MarshalPKIXPublicKey(key)
  234. if err != nil {
  235. panic(err)
  236. }
  237. hash := sha1.Sum(b)
  238. return hash[:]
  239. }