pki.go 25 KB

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