pki.go 31 KB

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