pki.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. package pki
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "crypto/x509/pkix"
  8. "encoding/hex"
  9. "encoding/json"
  10. "encoding/pem"
  11. "fmt"
  12. "net"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "time"
  17. "github.com/pkg/errors"
  18. "github.com/smallstep/certificates/authority"
  19. "github.com/smallstep/certificates/authority/admin"
  20. admindb "github.com/smallstep/certificates/authority/admin/db/nosql"
  21. authconfig "github.com/smallstep/certificates/authority/config"
  22. "github.com/smallstep/certificates/authority/provisioner"
  23. "github.com/smallstep/certificates/ca"
  24. "github.com/smallstep/certificates/cas"
  25. "github.com/smallstep/certificates/cas/apiv1"
  26. "github.com/smallstep/certificates/db"
  27. "github.com/smallstep/nosql"
  28. "go.step.sm/cli-utils/errs"
  29. "go.step.sm/cli-utils/fileutil"
  30. "go.step.sm/cli-utils/step"
  31. "go.step.sm/cli-utils/ui"
  32. "go.step.sm/crypto/jose"
  33. "go.step.sm/crypto/kms"
  34. kmsapi "go.step.sm/crypto/kms/apiv1"
  35. "go.step.sm/crypto/pemutil"
  36. "go.step.sm/linkedca"
  37. "golang.org/x/crypto/ssh"
  38. )
  39. // DeploymentType defines witch type of deployment a user is initializing
  40. type DeploymentType int
  41. const (
  42. // StandaloneDeployment is a deployment where all the components like keys,
  43. // provisioners, admins, certificates and others are managed by the user.
  44. StandaloneDeployment DeploymentType = iota
  45. // LinkedDeployment is a deployment where the keys are managed by the user,
  46. // but provisioners, admins and the record of certificates are managed in
  47. // the cloud.
  48. LinkedDeployment
  49. // HostedDeployment is a deployment where all the components are managed in
  50. // the cloud by smallstep.com/certificate-manager.
  51. HostedDeployment
  52. )
  53. // String returns the string version of the deployment type.
  54. func (d DeploymentType) String() string {
  55. switch d {
  56. case StandaloneDeployment:
  57. return "standalone"
  58. case LinkedDeployment:
  59. return "linked"
  60. case HostedDeployment:
  61. return "hosted"
  62. default:
  63. return "unknown"
  64. }
  65. }
  66. const (
  67. // ConfigPath is the directory name under the step path where the configuration
  68. // files will be stored.
  69. configPath = "config"
  70. // PublicPath is the directory name under the step path where the public keys
  71. // will be stored.
  72. publicPath = "certs"
  73. // PublicPath is the directory name under the step path where the private keys
  74. // will be stored.
  75. privatePath = "secrets"
  76. // DBPath is the directory name under the step path where the private keys
  77. // will be stored.
  78. dbPath = "db"
  79. // templatesPath is the directory to store templates
  80. templatesPath = "templates"
  81. )
  82. // GetDBPath returns the path where the file-system persistence is stored
  83. // based on the $(step path).
  84. func GetDBPath() string {
  85. return filepath.Join(step.Path(), dbPath)
  86. }
  87. // GetConfigPath returns the directory where the configuration files are stored
  88. // based on the $(step path).
  89. func GetConfigPath() string {
  90. return filepath.Join(step.Path(), configPath)
  91. }
  92. // GetProfileConfigPath returns the directory where the profile configuration
  93. // files are stored based on the $(step path).
  94. func GetProfileConfigPath() string {
  95. return filepath.Join(step.ProfilePath(), configPath)
  96. }
  97. // GetPublicPath returns the directory where the public keys are stored based on
  98. // the $(step path).
  99. func GetPublicPath() string {
  100. return filepath.Join(step.Path(), publicPath)
  101. }
  102. // GetSecretsPath returns the directory where the private keys are stored based
  103. // on the $(step path).
  104. func GetSecretsPath() string {
  105. return filepath.Join(step.Path(), privatePath)
  106. }
  107. // GetRootCAPath returns the path where the root CA is stored based on the
  108. // $(step path).
  109. func GetRootCAPath() string {
  110. return filepath.Join(step.Path(), publicPath, "root_ca.crt")
  111. }
  112. // GetOTTKeyPath returns the path where the one-time token key is stored based
  113. // on the $(step path).
  114. func GetOTTKeyPath() string {
  115. return filepath.Join(step.Path(), privatePath, "ott_key")
  116. }
  117. // GetTemplatesPath returns the path where the templates are stored.
  118. func GetTemplatesPath() string {
  119. return filepath.Join(step.Path(), templatesPath)
  120. }
  121. // GetProvisioners returns the map of provisioners on the given CA.
  122. func GetProvisioners(caURL, rootFile string) (provisioner.List, error) {
  123. if rootFile == "" {
  124. rootFile = GetRootCAPath()
  125. }
  126. client, err := ca.NewClient(caURL, ca.WithRootFile(rootFile))
  127. if err != nil {
  128. return nil, err
  129. }
  130. cursor := ""
  131. provisioners := provisioner.List{}
  132. for {
  133. resp, err := client.Provisioners(ca.WithProvisionerCursor(cursor), ca.WithProvisionerLimit(100))
  134. if err != nil {
  135. return nil, err
  136. }
  137. provisioners = append(provisioners, resp.Provisioners...)
  138. if resp.NextCursor == "" {
  139. return provisioners, nil
  140. }
  141. cursor = resp.NextCursor
  142. }
  143. }
  144. // GetProvisionerKey returns the encrypted provisioner key with the for the
  145. // given kid.
  146. func GetProvisionerKey(caURL, rootFile, kid string) (string, error) {
  147. if rootFile == "" {
  148. rootFile = GetRootCAPath()
  149. }
  150. client, err := ca.NewClient(caURL, ca.WithRootFile(rootFile))
  151. if err != nil {
  152. return "", err
  153. }
  154. resp, err := client.ProvisionerKey(kid)
  155. if err != nil {
  156. return "", err
  157. }
  158. return resp.Key, nil
  159. }
  160. type options struct {
  161. provisioner string
  162. pkiOnly bool
  163. enableACME bool
  164. enableSSH bool
  165. enableAdmin bool
  166. noDB bool
  167. isHelm bool
  168. deploymentType DeploymentType
  169. rootKeyURI string
  170. intermediateKeyURI string
  171. hostKeyURI string
  172. userKeyURI string
  173. }
  174. // Option is the type of a configuration option on the pki constructor.
  175. type Option func(p *PKI)
  176. // WithAddress sets the listen address of step-ca.
  177. func WithAddress(s string) Option {
  178. return func(p *PKI) {
  179. p.Address = s
  180. }
  181. }
  182. // WithCaURL sets the default ca-url of step-ca.
  183. func WithCaURL(s string) Option {
  184. return func(p *PKI) {
  185. p.Defaults.CaUrl = s
  186. }
  187. }
  188. // WithDNSNames sets the SANs of step-ca.
  189. func WithDNSNames(s []string) Option {
  190. return func(p *PKI) {
  191. p.DnsNames = s
  192. }
  193. }
  194. // WithProvisioner defines the name of the default provisioner.
  195. func WithProvisioner(s string) Option {
  196. return func(p *PKI) {
  197. p.options.provisioner = s
  198. }
  199. }
  200. // WithPKIOnly will only generate the PKI without the step-ca config files.
  201. func WithPKIOnly() Option {
  202. return func(p *PKI) {
  203. p.options.pkiOnly = true
  204. }
  205. }
  206. // WithACME enables acme provisioner in step-ca.
  207. func WithACME() Option {
  208. return func(p *PKI) {
  209. p.options.enableACME = true
  210. }
  211. }
  212. // WithSSH enables ssh in step-ca.
  213. func WithSSH() Option {
  214. return func(p *PKI) {
  215. p.options.enableSSH = true
  216. }
  217. }
  218. // WithAdmin enables the admin api in step-ca.
  219. func WithAdmin() Option {
  220. return func(p *PKI) {
  221. p.options.enableAdmin = true
  222. }
  223. }
  224. // WithNoDB disables the db in step-ca.
  225. func WithNoDB() Option {
  226. return func(p *PKI) {
  227. p.options.noDB = true
  228. }
  229. }
  230. // WithHelm configures the pki to create a helm values.yaml.
  231. func WithHelm() Option {
  232. return func(p *PKI) {
  233. p.options.isHelm = true
  234. }
  235. }
  236. // WithDeploymentType defines the deployment type of step-ca.
  237. func WithDeploymentType(dt DeploymentType) Option {
  238. return func(p *PKI) {
  239. p.options.deploymentType = dt
  240. }
  241. }
  242. // WithKMS enables the kms with the given name.
  243. func WithKMS(name string) Option {
  244. return func(p *PKI) {
  245. typ := linkedca.KMS_Type_value[strings.ToUpper(name)]
  246. p.Configuration.Kms = &linkedca.KMS{
  247. Type: linkedca.KMS_Type(typ),
  248. }
  249. }
  250. }
  251. // WithKeyURIs defines the key uris for X.509 and SSH keys.
  252. func WithKeyURIs(rootKey, intermediateKey, hostKey, userKey string) Option {
  253. return func(p *PKI) {
  254. p.options.rootKeyURI = rootKey
  255. p.options.intermediateKeyURI = intermediateKey
  256. p.options.hostKeyURI = hostKey
  257. p.options.userKeyURI = userKey
  258. }
  259. }
  260. // PKI represents the Public Key Infrastructure used by a certificate authority.
  261. type PKI struct {
  262. linkedca.Configuration
  263. Defaults linkedca.Defaults
  264. casOptions apiv1.Options
  265. caService apiv1.CertificateAuthorityService
  266. caCreator apiv1.CertificateAuthorityCreator
  267. keyManager kmsapi.KeyManager
  268. config string
  269. defaults string
  270. profileDefaults string
  271. ottPublicKey *jose.JSONWebKey
  272. ottPrivateKey *jose.JSONWebEncryption
  273. options *options
  274. }
  275. // New creates a new PKI configuration.
  276. func New(o apiv1.Options, opts ...Option) (*PKI, error) {
  277. currentCtx := step.Contexts().GetCurrent()
  278. caService, err := cas.New(context.Background(), o)
  279. if err != nil {
  280. return nil, err
  281. }
  282. var caCreator apiv1.CertificateAuthorityCreator
  283. if o.IsCreator {
  284. creator, ok := caService.(apiv1.CertificateAuthorityCreator)
  285. if !ok {
  286. return nil, errors.Errorf("cas type '%s' does not implements CertificateAuthorityCreator", o.Type)
  287. }
  288. caCreator = creator
  289. }
  290. // get absolute path for dir/name
  291. getPath := func(dir string, name string) (string, error) {
  292. s, err := filepath.Abs(filepath.Join(dir, name))
  293. return s, errors.Wrapf(err, "error getting absolute path for %s", name)
  294. }
  295. p := &PKI{
  296. Configuration: linkedca.Configuration{
  297. Address: "127.0.0.1:9000",
  298. DnsNames: []string{"127.0.0.1"},
  299. Ssh: &linkedca.SSH{},
  300. Authority: &linkedca.Authority{},
  301. Files: make(map[string][]byte),
  302. },
  303. casOptions: o,
  304. caService: caService,
  305. caCreator: caCreator,
  306. keyManager: o.KeyManager,
  307. options: &options{
  308. provisioner: "step-cli",
  309. },
  310. }
  311. for _, fn := range opts {
  312. fn(p)
  313. }
  314. // Use default key manager
  315. if p.keyManager == nil {
  316. p.keyManager = kms.Default
  317. }
  318. // Use /home/step as the step path in helm configurations.
  319. // Use the current step path when creating pki in files.
  320. var public, private, cfg string
  321. if p.options.isHelm {
  322. public = "/home/step/certs"
  323. private = "/home/step/secrets"
  324. cfg = "/home/step/config"
  325. } else {
  326. public = GetPublicPath()
  327. private = GetSecretsPath()
  328. cfg = GetConfigPath()
  329. // Create directories
  330. dirs := []string{public, private, cfg, GetTemplatesPath()}
  331. if currentCtx != nil {
  332. dirs = append(dirs, GetProfileConfigPath())
  333. }
  334. for _, name := range dirs {
  335. if _, err := os.Stat(name); os.IsNotExist(err) {
  336. if err = os.MkdirAll(name, 0700); err != nil {
  337. return nil, errs.FileError(err, name)
  338. }
  339. }
  340. }
  341. }
  342. if p.Defaults.CaUrl == "" {
  343. p.Defaults.CaUrl = p.DnsNames[0]
  344. _, port, err := net.SplitHostPort(p.Address)
  345. if err != nil {
  346. return nil, errors.Wrapf(err, "error parsing %s", p.Address)
  347. }
  348. // On k8s we usually access through a service, and this is configured on
  349. // port 443 by default.
  350. if port == "443" || p.options.isHelm {
  351. p.Defaults.CaUrl = fmt.Sprintf("https://%s", p.Defaults.CaUrl)
  352. } else {
  353. p.Defaults.CaUrl = fmt.Sprintf("https://%s", net.JoinHostPort(p.Defaults.CaUrl, port))
  354. }
  355. }
  356. root, err := getPath(public, "root_ca.crt")
  357. if err != nil {
  358. return nil, err
  359. }
  360. rootKey, err := getPath(private, "root_ca_key")
  361. if err != nil {
  362. return nil, err
  363. }
  364. p.Root = []string{root}
  365. p.RootKey = []string{rootKey}
  366. p.Defaults.Root = root
  367. if p.Intermediate, err = getPath(public, "intermediate_ca.crt"); err != nil {
  368. return nil, err
  369. }
  370. if p.IntermediateKey, err = getPath(private, "intermediate_ca_key"); err != nil {
  371. return nil, err
  372. }
  373. if p.Ssh.HostPublicKey, err = getPath(public, "ssh_host_ca_key.pub"); err != nil {
  374. return nil, err
  375. }
  376. if p.Ssh.UserPublicKey, err = getPath(public, "ssh_user_ca_key.pub"); err != nil {
  377. return nil, err
  378. }
  379. if p.Ssh.HostKey, err = getPath(private, "ssh_host_ca_key"); err != nil {
  380. return nil, err
  381. }
  382. if p.Ssh.UserKey, err = getPath(private, "ssh_user_ca_key"); err != nil {
  383. return nil, err
  384. }
  385. if p.defaults, err = getPath(cfg, "defaults.json"); err != nil {
  386. return nil, err
  387. }
  388. if currentCtx != nil {
  389. p.profileDefaults = currentCtx.ProfileDefaultsFile()
  390. }
  391. if p.config, err = getPath(cfg, "ca.json"); err != nil {
  392. return nil, err
  393. }
  394. p.Defaults.CaConfig = p.config
  395. return p, nil
  396. }
  397. // GetCAConfigPath returns the path of the CA configuration file.
  398. func (p *PKI) GetCAConfigPath() string {
  399. return p.config
  400. }
  401. // GetRootFingerprint returns the root fingerprint.
  402. func (p *PKI) GetRootFingerprint() string {
  403. return p.Defaults.Fingerprint
  404. }
  405. // GenerateKeyPairs generates the key pairs used by the certificate authority.
  406. func (p *PKI) GenerateKeyPairs(pass []byte) error {
  407. var err error
  408. // Create OTT key pair, the user doesn't need to know about this.
  409. p.ottPublicKey, p.ottPrivateKey, err = jose.GenerateDefaultKeyPair(pass)
  410. if err != nil {
  411. return err
  412. }
  413. var claims *linkedca.Claims
  414. if p.options.enableSSH {
  415. claims = &linkedca.Claims{
  416. Ssh: &linkedca.SSHClaims{
  417. Enabled: true,
  418. },
  419. }
  420. }
  421. // Add JWK provisioner to the configuration.
  422. publicKey, err := json.Marshal(p.ottPublicKey)
  423. if err != nil {
  424. return errors.Wrap(err, "error marshaling public key")
  425. }
  426. encryptedKey, err := p.ottPrivateKey.CompactSerialize()
  427. if err != nil {
  428. return errors.Wrap(err, "error serializing private key")
  429. }
  430. p.Authority.Provisioners = append(p.Authority.Provisioners, &linkedca.Provisioner{
  431. Type: linkedca.Provisioner_JWK,
  432. Name: p.options.provisioner,
  433. Claims: claims,
  434. Details: &linkedca.ProvisionerDetails{
  435. Data: &linkedca.ProvisionerDetails_JWK{
  436. JWK: &linkedca.JWKProvisioner{
  437. PublicKey: publicKey,
  438. EncryptedPrivateKey: []byte(encryptedKey),
  439. },
  440. },
  441. },
  442. })
  443. return nil
  444. }
  445. // GenerateRootCertificate generates a root certificate with the given name
  446. // and using the default key type.
  447. func (p *PKI) GenerateRootCertificate(name, org, resource string, pass []byte) (*apiv1.CreateCertificateAuthorityResponse, error) {
  448. if uri := p.options.rootKeyURI; uri != "" {
  449. p.RootKey[0] = uri
  450. }
  451. resp, err := p.caCreator.CreateCertificateAuthority(&apiv1.CreateCertificateAuthorityRequest{
  452. Name: resource + "-Root-CA",
  453. Type: apiv1.RootCA,
  454. Lifetime: 10 * 365 * 24 * time.Hour,
  455. CreateKey: &apiv1.CreateKeyRequest{
  456. Name: p.RootKey[0],
  457. SignatureAlgorithm: kmsapi.UnspecifiedSignAlgorithm,
  458. },
  459. Template: &x509.Certificate{
  460. Subject: pkix.Name{
  461. CommonName: name + " Root CA",
  462. Organization: []string{org},
  463. },
  464. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  465. BasicConstraintsValid: true,
  466. IsCA: true,
  467. MaxPathLen: 1,
  468. MaxPathLenZero: false,
  469. },
  470. })
  471. if err != nil {
  472. return nil, err
  473. }
  474. // Replace key name with the one from the key manager if available. On
  475. // softcas this will be the original filename, on any other kms will be the
  476. // uri to the key.
  477. if resp.KeyName != "" {
  478. p.RootKey[0] = resp.KeyName
  479. }
  480. // PrivateKey will only be set if we have access to it (SoftCAS).
  481. if err := p.WriteRootCertificate(resp.Certificate, resp.PrivateKey, pass); err != nil {
  482. return nil, err
  483. }
  484. return resp, nil
  485. }
  486. // WriteRootCertificate writes to the buffer the given certificate and key if given.
  487. func (p *PKI) WriteRootCertificate(rootCrt *x509.Certificate, rootKey interface{}, pass []byte) error {
  488. p.Files[p.Root[0]] = encodeCertificate(rootCrt)
  489. if rootKey != nil {
  490. var err error
  491. p.Files[p.RootKey[0]], err = encodePrivateKey(rootKey, pass)
  492. if err != nil {
  493. return err
  494. }
  495. }
  496. sum := sha256.Sum256(rootCrt.Raw)
  497. p.Defaults.Fingerprint = strings.ToLower(hex.EncodeToString(sum[:]))
  498. return nil
  499. }
  500. // GenerateIntermediateCertificate generates an intermediate certificate with
  501. // the given name and using the default key type.
  502. func (p *PKI) GenerateIntermediateCertificate(name, org, resource string, parent *apiv1.CreateCertificateAuthorityResponse, pass []byte) error {
  503. if uri := p.options.intermediateKeyURI; uri != "" {
  504. p.IntermediateKey = uri
  505. }
  506. resp, err := p.caCreator.CreateCertificateAuthority(&apiv1.CreateCertificateAuthorityRequest{
  507. Name: resource + "-Intermediate-CA",
  508. Type: apiv1.IntermediateCA,
  509. Lifetime: 10 * 365 * 24 * time.Hour,
  510. CreateKey: &apiv1.CreateKeyRequest{
  511. Name: p.IntermediateKey,
  512. SignatureAlgorithm: kmsapi.UnspecifiedSignAlgorithm,
  513. },
  514. Template: &x509.Certificate{
  515. Subject: pkix.Name{
  516. CommonName: name + " Intermediate CA",
  517. Organization: []string{org},
  518. },
  519. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  520. BasicConstraintsValid: true,
  521. IsCA: true,
  522. MaxPathLen: 0,
  523. MaxPathLenZero: true,
  524. },
  525. Parent: parent,
  526. })
  527. if err != nil {
  528. return err
  529. }
  530. p.casOptions.CertificateAuthority = resp.Name
  531. p.Files[p.Intermediate] = encodeCertificate(resp.Certificate)
  532. // Replace the key name with the one from the key manager. On softcas this
  533. // will be the original filename, on any other kms will be the uri to the
  534. // key.
  535. if resp.KeyName != "" {
  536. p.IntermediateKey = resp.KeyName
  537. }
  538. // If a kms is used it will not have the private key
  539. if resp.PrivateKey != nil {
  540. p.Files[p.IntermediateKey], err = encodePrivateKey(resp.PrivateKey, pass)
  541. }
  542. return err
  543. }
  544. // CreateCertificateAuthorityResponse returns a
  545. // CreateCertificateAuthorityResponse that can be used as a parent of a
  546. // CreateCertificateAuthority request.
  547. func (p *PKI) CreateCertificateAuthorityResponse(cert *x509.Certificate, key crypto.PrivateKey) *apiv1.CreateCertificateAuthorityResponse {
  548. signer, _ := key.(crypto.Signer)
  549. return &apiv1.CreateCertificateAuthorityResponse{
  550. Certificate: cert,
  551. PrivateKey: key,
  552. Signer: signer,
  553. }
  554. }
  555. // GetCertificateAuthority attempts to load the certificate authority from the
  556. // RA.
  557. func (p *PKI) GetCertificateAuthority() error {
  558. srv, ok := p.caService.(apiv1.CertificateAuthorityGetter)
  559. if !ok {
  560. return nil
  561. }
  562. resp, err := srv.GetCertificateAuthority(&apiv1.GetCertificateAuthorityRequest{
  563. Name: p.casOptions.CertificateAuthority,
  564. })
  565. if err != nil {
  566. return err
  567. }
  568. if err := p.WriteRootCertificate(resp.RootCertificate, nil, nil); err != nil {
  569. return err
  570. }
  571. // Issuer is in the RA
  572. p.Intermediate = ""
  573. p.IntermediateKey = ""
  574. return nil
  575. }
  576. // GenerateSSHSigningKeys generates and encrypts a private key used for signing
  577. // SSH user certificates and a private key used for signing host certificates.
  578. func (p *PKI) GenerateSSHSigningKeys(password []byte) error {
  579. // Enable SSH
  580. p.options.enableSSH = true
  581. // Create SSH key used to sign host certificates. Using
  582. // kmsapi.UnspecifiedSignAlgorithm will default to the default algorithm.
  583. name := p.Ssh.HostKey
  584. if uri := p.options.hostKeyURI; uri != "" {
  585. name = uri
  586. }
  587. resp, err := p.keyManager.CreateKey(&kmsapi.CreateKeyRequest{
  588. Name: name,
  589. SignatureAlgorithm: kmsapi.UnspecifiedSignAlgorithm,
  590. })
  591. if err != nil {
  592. return err
  593. }
  594. sshKey, err := ssh.NewPublicKey(resp.PublicKey)
  595. if err != nil {
  596. return errors.Wrapf(err, "error converting public key")
  597. }
  598. p.Files[p.Ssh.HostPublicKey] = ssh.MarshalAuthorizedKey(sshKey)
  599. // On softkms we will have the private key
  600. if resp.PrivateKey != nil {
  601. p.Files[p.Ssh.HostKey], err = encodePrivateKey(resp.PrivateKey, password)
  602. if err != nil {
  603. return err
  604. }
  605. } else {
  606. p.Ssh.HostKey = resp.Name
  607. }
  608. // Create SSH key used to sign user certificates. Using
  609. // kmsapi.UnspecifiedSignAlgorithm will default to the default algorithm.
  610. name = p.Ssh.UserKey
  611. if uri := p.options.userKeyURI; uri != "" {
  612. name = uri
  613. }
  614. resp, err = p.keyManager.CreateKey(&kmsapi.CreateKeyRequest{
  615. Name: name,
  616. SignatureAlgorithm: kmsapi.UnspecifiedSignAlgorithm,
  617. })
  618. if err != nil {
  619. return err
  620. }
  621. sshKey, err = ssh.NewPublicKey(resp.PublicKey)
  622. if err != nil {
  623. return errors.Wrapf(err, "error converting public key")
  624. }
  625. p.Files[p.Ssh.UserPublicKey] = ssh.MarshalAuthorizedKey(sshKey)
  626. // On softkms we will have the private key
  627. if resp.PrivateKey != nil {
  628. p.Files[p.Ssh.UserKey], err = encodePrivateKey(resp.PrivateKey, password)
  629. if err != nil {
  630. return err
  631. }
  632. } else {
  633. p.Ssh.UserKey = resp.Name
  634. }
  635. return nil
  636. }
  637. // WriteFiles writes on disk the previously generated files.
  638. func (p *PKI) WriteFiles() error {
  639. for fn, b := range p.Files {
  640. if err := fileutil.WriteFile(fn, b, 0600); err != nil {
  641. return err
  642. }
  643. }
  644. return nil
  645. }
  646. func (p *PKI) askFeedback() {
  647. ui.Println()
  648. ui.Println("\033[1mFEEDBACK\033[0m 😍 🍻")
  649. ui.Println(" The \033[1mstep\033[0m utility is not instrumented for usage statistics. It does not phone")
  650. ui.Println(" home. But your feedback is extremely valuable. Any information you can provide")
  651. ui.Println(" regarding how you’re using `step` helps. Please send us a sentence or two,")
  652. ui.Println(" good or bad at \033[1mfeedback@smallstep.com\033[0m or join GitHub Discussions")
  653. ui.Println(" \033[1mhttps://github.com/smallstep/certificates/discussions\033[0m and our Discord ")
  654. ui.Println(" \033[1mhttps://u.step.sm/discord\033[0m.")
  655. if p.options.deploymentType == LinkedDeployment {
  656. ui.Println()
  657. ui.Println("\033[1mNEXT STEPS\033[0m")
  658. ui.Println(" 1. Log in or create a Certificate Manager account at \033[1mhttps://u.step.sm/linked\033[0m")
  659. ui.Println(" 2. Add a new authority and select \"Link a step-ca instance\"")
  660. ui.Println(" 3. Follow instructions in browser to start `step-ca` using the `--token` flag")
  661. ui.Println()
  662. }
  663. }
  664. func (p *PKI) tellPKI() {
  665. ui.Println()
  666. switch {
  667. case p.casOptions.Is(apiv1.SoftCAS):
  668. ui.PrintSelected("Root certificate", p.Root[0])
  669. ui.PrintSelected("Root private key", p.RootKey[0])
  670. ui.PrintSelected("Root fingerprint", p.Defaults.Fingerprint)
  671. ui.PrintSelected("Intermediate certificate", p.Intermediate)
  672. ui.PrintSelected("Intermediate private key", p.IntermediateKey)
  673. case p.Defaults.Fingerprint != "":
  674. ui.PrintSelected("Root certificate", p.Root[0])
  675. ui.PrintSelected("Root fingerprint", p.Defaults.Fingerprint)
  676. default:
  677. ui.Printf(`{{ "%s" | red }} {{ "Root certificate:" | bold }} failed to retrieve it from RA`+"\n", ui.IconBad)
  678. }
  679. if p.options.enableSSH {
  680. ui.PrintSelected("SSH user public key", p.Ssh.UserPublicKey)
  681. ui.PrintSelected("SSH user private key", p.Ssh.UserKey)
  682. ui.PrintSelected("SSH host public key", p.Ssh.HostPublicKey)
  683. ui.PrintSelected("SSH host private key", p.Ssh.HostKey)
  684. }
  685. }
  686. type caDefaults struct {
  687. CAUrl string `json:"ca-url"`
  688. CAConfig string `json:"ca-config"`
  689. Fingerprint string `json:"fingerprint"`
  690. Root string `json:"root"`
  691. }
  692. // ConfigOption is the type for modifiers over the auth config object.
  693. type ConfigOption func(c *authconfig.Config) error
  694. // GenerateConfig returns the step certificates configuration.
  695. func (p *PKI) GenerateConfig(opt ...ConfigOption) (*authconfig.Config, error) {
  696. var authorityOptions *apiv1.Options
  697. if !p.casOptions.Is(apiv1.SoftCAS) {
  698. authorityOptions = &p.casOptions
  699. }
  700. cfg := &authconfig.Config{
  701. Root: p.Root,
  702. FederatedRoots: p.FederatedRoots,
  703. IntermediateCert: p.Intermediate,
  704. IntermediateKey: p.IntermediateKey,
  705. Address: p.Address,
  706. DNSNames: p.DnsNames,
  707. Logger: []byte(`{"format": "text"}`),
  708. DB: &db.Config{
  709. Type: "badgerv2",
  710. DataSource: GetDBPath(),
  711. },
  712. AuthorityConfig: &authconfig.AuthConfig{
  713. Options: authorityOptions,
  714. DisableIssuedAtCheck: false,
  715. EnableAdmin: false,
  716. },
  717. TLS: &authconfig.DefaultTLSOptions,
  718. Templates: p.getTemplates(),
  719. }
  720. // Add linked as a deployment type to detect it on start and provide a
  721. // message if the token is not given.
  722. if p.options.deploymentType == LinkedDeployment {
  723. cfg.AuthorityConfig.DeploymentType = LinkedDeployment.String()
  724. }
  725. // Enable KMS if necessary
  726. if p.Kms != nil {
  727. typ := strings.ToLower(p.Kms.Type.String())
  728. cfg.KMS = &kmsapi.Options{
  729. Type: kmsapi.Type(typ),
  730. }
  731. }
  732. // On standalone deployments add the provisioners to either the ca.json or
  733. // the database.
  734. var provisioners []provisioner.Interface
  735. if p.options.deploymentType == StandaloneDeployment {
  736. key, err := p.ottPrivateKey.CompactSerialize()
  737. if err != nil {
  738. return nil, errors.Wrap(err, "error serializing private key")
  739. }
  740. prov := &provisioner.JWK{
  741. Name: p.options.provisioner,
  742. Type: "JWK",
  743. Key: p.ottPublicKey,
  744. EncryptedKey: key,
  745. }
  746. provisioners = append(provisioners, prov)
  747. // Add default ACME provisioner if enabled
  748. if p.options.enableACME {
  749. provisioners = append(provisioners, &provisioner.ACME{
  750. Type: "ACME",
  751. Name: "acme",
  752. })
  753. }
  754. if p.options.enableSSH {
  755. enableSSHCA := true
  756. cfg.SSH = &authconfig.SSHConfig{
  757. HostKey: p.Ssh.HostKey,
  758. UserKey: p.Ssh.UserKey,
  759. }
  760. // Enable SSH authorization for default JWK provisioner
  761. prov.Claims = &provisioner.Claims{
  762. EnableSSHCA: &enableSSHCA,
  763. }
  764. // Add default SSHPOP provisioner
  765. provisioners = append(provisioners, &provisioner.SSHPOP{
  766. Type: "SSHPOP",
  767. Name: "sshpop",
  768. Claims: &provisioner.Claims{
  769. EnableSSHCA: &enableSSHCA,
  770. },
  771. })
  772. }
  773. }
  774. // Apply configuration modifiers
  775. for _, o := range opt {
  776. if err := o(cfg); err != nil {
  777. return nil, err
  778. }
  779. }
  780. // Set authority.enableAdmin to true
  781. if p.options.enableAdmin {
  782. cfg.AuthorityConfig.EnableAdmin = true
  783. }
  784. if p.options.deploymentType == StandaloneDeployment {
  785. if !cfg.AuthorityConfig.EnableAdmin {
  786. cfg.AuthorityConfig.Provisioners = provisioners
  787. } else {
  788. // At this moment this code path is never used because `step ca
  789. // init` will always set enableAdmin to false for a standalone
  790. // deployment. Once we move `step beta` commands out of the beta we
  791. // should probably default to this route.
  792. //
  793. // Note that we might want to be able to define the database as a
  794. // flag in `step ca init` so we can write to the proper place.
  795. _db, err := db.New(cfg.DB)
  796. if err != nil {
  797. return nil, err
  798. }
  799. adminDB, err := admindb.New(_db.(nosql.DB), admin.DefaultAuthorityID)
  800. if err != nil {
  801. return nil, err
  802. }
  803. // Add all the provisioners to the db.
  804. var adminID string
  805. for i, p := range provisioners {
  806. prov, err := authority.ProvisionerToLinkedca(p)
  807. if err != nil {
  808. return nil, err
  809. }
  810. if err := adminDB.CreateProvisioner(context.Background(), prov); err != nil {
  811. return nil, err
  812. }
  813. if i == 0 {
  814. adminID = prov.Id
  815. }
  816. }
  817. // Add the first provisioner as an admin.
  818. if err := adminDB.CreateAdmin(context.Background(), &linkedca.Admin{
  819. AuthorityId: admin.DefaultAuthorityID,
  820. Subject: "step",
  821. Type: linkedca.Admin_SUPER_ADMIN,
  822. ProvisionerId: adminID,
  823. }); err != nil {
  824. return nil, err
  825. }
  826. }
  827. }
  828. return cfg, nil
  829. }
  830. // Save stores the pki on a json file that will be used as the certificate
  831. // authority configuration.
  832. func (p *PKI) Save(opt ...ConfigOption) error {
  833. // Write generated files
  834. if err := p.WriteFiles(); err != nil {
  835. return err
  836. }
  837. // Display the files written
  838. p.tellPKI()
  839. // Generate and write ca.json
  840. if !p.options.pkiOnly {
  841. cfg, err := p.GenerateConfig(opt...)
  842. if err != nil {
  843. return err
  844. }
  845. b, err := json.MarshalIndent(cfg, "", "\t")
  846. if err != nil {
  847. return errors.Wrapf(err, "error marshaling %s", p.config)
  848. }
  849. if err = fileutil.WriteFile(p.config, b, 0644); err != nil {
  850. return errs.FileError(err, p.config)
  851. }
  852. // Generate and write defaults.json
  853. defaults := &caDefaults{
  854. Root: p.Defaults.Root,
  855. CAConfig: p.Defaults.CaConfig,
  856. CAUrl: p.Defaults.CaUrl,
  857. Fingerprint: p.Defaults.Fingerprint,
  858. }
  859. b, err = json.MarshalIndent(defaults, "", "\t")
  860. if err != nil {
  861. return errors.Wrapf(err, "error marshaling %s", p.defaults)
  862. }
  863. if err = fileutil.WriteFile(p.defaults, b, 0644); err != nil {
  864. return errs.FileError(err, p.defaults)
  865. }
  866. // If we're using contexts then write a blank object to the default profile
  867. // configuration location.
  868. if p.profileDefaults != "" {
  869. if _, err := os.Stat(p.profileDefaults); os.IsNotExist(err) {
  870. // Write with 0600 to be consistent with directories structure.
  871. if err = fileutil.WriteFile(p.profileDefaults, []byte("{}"), 0600); err != nil {
  872. return errs.FileError(err, p.profileDefaults)
  873. }
  874. } else if err != nil {
  875. return errs.FileError(err, p.profileDefaults)
  876. }
  877. }
  878. // Generate and write templates
  879. if err := generateTemplates(cfg.Templates); err != nil {
  880. return err
  881. }
  882. if cfg.DB != nil {
  883. os.MkdirAll(cfg.DB.DataSource, 0700)
  884. ui.PrintSelected("Database folder", cfg.DB.DataSource)
  885. }
  886. if cfg.Templates != nil {
  887. ui.PrintSelected("Templates folder", GetTemplatesPath())
  888. }
  889. ui.PrintSelected("Default configuration", p.defaults)
  890. if p.profileDefaults != "" {
  891. ui.PrintSelected("Default profile configuration", p.profileDefaults)
  892. }
  893. ui.PrintSelected("Certificate Authority configuration", p.config)
  894. if p.options.deploymentType != LinkedDeployment {
  895. ui.Println()
  896. if p.casOptions.Is(apiv1.SoftCAS) {
  897. ui.Println("Your PKI is ready to go. To generate certificates for individual services see 'step help ca'.")
  898. } else {
  899. ui.Println("Your registration authority is ready to go. To generate certificates for individual services see 'step help ca'.")
  900. }
  901. }
  902. }
  903. p.askFeedback()
  904. return nil
  905. }
  906. func encodeCertificate(c *x509.Certificate) []byte {
  907. return pem.EncodeToMemory(&pem.Block{
  908. Type: "CERTIFICATE",
  909. Bytes: c.Raw,
  910. })
  911. }
  912. func encodePrivateKey(key crypto.PrivateKey, pass []byte) ([]byte, error) {
  913. block, err := pemutil.Serialize(key, pemutil.WithPassword(pass))
  914. if err != nil {
  915. return nil, err
  916. }
  917. return pem.EncodeToMemory(block), nil
  918. }