pki.go 30 KB

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