authority.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. package authority
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/rsa"
  7. "crypto/sha256"
  8. "crypto/x509"
  9. "encoding/hex"
  10. "fmt"
  11. "log"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/pkg/errors"
  16. "golang.org/x/crypto/ssh"
  17. "github.com/smallstep/linkedca"
  18. "go.step.sm/crypto/kms"
  19. kmsapi "go.step.sm/crypto/kms/apiv1"
  20. "go.step.sm/crypto/kms/sshagentkms"
  21. "go.step.sm/crypto/pemutil"
  22. "github.com/smallstep/certificates/authority/admin"
  23. adminDBNosql "github.com/smallstep/certificates/authority/admin/db/nosql"
  24. "github.com/smallstep/certificates/authority/administrator"
  25. "github.com/smallstep/certificates/authority/config"
  26. "github.com/smallstep/certificates/authority/internal/constraints"
  27. "github.com/smallstep/certificates/authority/policy"
  28. "github.com/smallstep/certificates/authority/provisioner"
  29. "github.com/smallstep/certificates/cas"
  30. casapi "github.com/smallstep/certificates/cas/apiv1"
  31. "github.com/smallstep/certificates/db"
  32. "github.com/smallstep/certificates/internal/httptransport"
  33. "github.com/smallstep/certificates/scep"
  34. "github.com/smallstep/certificates/templates"
  35. "github.com/smallstep/nosql"
  36. )
  37. // Authority implements the Certificate Authority internal interface.
  38. type Authority struct {
  39. config *config.Config
  40. keyManager kms.KeyManager
  41. provisioners *provisioner.Collection
  42. admins *administrator.Collection
  43. db db.AuthDB
  44. adminDB admin.DB
  45. templates *templates.Templates
  46. linkedCAToken string
  47. wrapTransport httptransport.Wrapper
  48. webhookClient provisioner.HTTPClient
  49. httpClient provisioner.HTTPClient
  50. // X509 CA
  51. password []byte
  52. issuerPassword []byte
  53. x509CAService cas.CertificateAuthorityService
  54. rootX509Certs []*x509.Certificate
  55. rootX509CertPool *x509.CertPool
  56. federatedX509Certs []*x509.Certificate
  57. intermediateX509Certs []*x509.Certificate
  58. certificates *sync.Map
  59. x509Enforcers []provisioner.CertificateEnforcer
  60. // SCEP CA
  61. scepOptions *scep.Options
  62. validateSCEP bool
  63. scepAuthority *scep.Authority
  64. scepKeyManager provisioner.SCEPKeyManager
  65. // SSH CA
  66. sshHostPassword []byte
  67. sshUserPassword []byte
  68. sshCAUserCertSignKey ssh.Signer
  69. sshCAHostCertSignKey ssh.Signer
  70. sshCAUserCerts []ssh.PublicKey
  71. sshCAHostCerts []ssh.PublicKey
  72. sshCAUserFederatedCerts []ssh.PublicKey
  73. sshCAHostFederatedCerts []ssh.PublicKey
  74. // CRL vars
  75. crlTicker *time.Ticker
  76. crlStopper chan struct{}
  77. crlMutex sync.Mutex
  78. // If true, do not re-initialize
  79. initOnce bool
  80. startTime time.Time
  81. // Custom functions
  82. sshBastionFunc func(ctx context.Context, user, hostname string) (*config.Bastion, error)
  83. sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  84. sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]config.Host, error)
  85. getIdentityFunc provisioner.GetIdentityFunc
  86. authorizeRenewFunc provisioner.AuthorizeRenewFunc
  87. authorizeSSHRenewFunc provisioner.AuthorizeSSHRenewFunc
  88. // Constraints and Policy engines
  89. constraintsEngine *constraints.Engine
  90. policyEngine *policy.Engine
  91. adminMutex sync.RWMutex
  92. // If true, do not initialize the authority
  93. skipInit bool
  94. // If true, do not output initialization logs
  95. quietInit bool
  96. // Called whenever applicable, in order to instrument the authority.
  97. meter Meter
  98. }
  99. // Info contains information about the authority.
  100. type Info struct {
  101. StartTime time.Time
  102. RootX509Certs []*x509.Certificate
  103. SSHCAUserPublicKey []byte
  104. SSHCAHostPublicKey []byte
  105. DNSNames []string
  106. }
  107. // New creates and initiates a new Authority type.
  108. func New(cfg *config.Config, opts ...Option) (*Authority, error) {
  109. err := cfg.Validate()
  110. if err != nil {
  111. return nil, err
  112. }
  113. var a = &Authority{
  114. config: cfg,
  115. certificates: new(sync.Map),
  116. validateSCEP: true,
  117. meter: noopMeter{},
  118. wrapTransport: httptransport.NoopWrapper(),
  119. }
  120. // Apply options.
  121. for _, fn := range opts {
  122. if err := fn(a); err != nil {
  123. return nil, err
  124. }
  125. }
  126. if a.keyManager != nil {
  127. a.keyManager = newInstrumentedKeyManager(a.keyManager, a.meter)
  128. }
  129. // Initialize system cert pool
  130. if err := initializeSystemCertPool(); err != nil {
  131. return nil, fmt.Errorf("failed to initialize the system cert pool: %w", err)
  132. }
  133. if !a.skipInit {
  134. // Initialize authority from options or configuration.
  135. if err := a.init(); err != nil {
  136. return nil, err
  137. }
  138. }
  139. return a, nil
  140. }
  141. // NewEmbedded initializes an authority that can be embedded in a different
  142. // project without the limitations of the config.
  143. func NewEmbedded(opts ...Option) (*Authority, error) {
  144. a := &Authority{
  145. config: &config.Config{},
  146. certificates: new(sync.Map),
  147. meter: noopMeter{},
  148. wrapTransport: httptransport.NoopWrapper(),
  149. }
  150. // Apply options.
  151. for _, fn := range opts {
  152. if err := fn(a); err != nil {
  153. return nil, err
  154. }
  155. }
  156. if a.keyManager != nil {
  157. a.keyManager = newInstrumentedKeyManager(a.keyManager, a.meter)
  158. }
  159. // Initialize system cert pool
  160. if err := initializeSystemCertPool(); err != nil {
  161. return nil, fmt.Errorf("failed to initialize the system cert pool: %w", err)
  162. }
  163. // Validate required options
  164. switch {
  165. case a.config == nil:
  166. return nil, errors.New("cannot create an authority without a configuration")
  167. case len(a.rootX509Certs) == 0 && a.config.Root.HasEmpties():
  168. return nil, errors.New("cannot create an authority without a root certificate")
  169. case a.x509CAService == nil && a.config.IntermediateCert == "":
  170. return nil, errors.New("cannot create an authority without an issuer certificate")
  171. case a.x509CAService == nil && a.config.IntermediateKey == "":
  172. return nil, errors.New("cannot create an authority without an issuer signer")
  173. }
  174. // Initialize config required fields.
  175. a.config.Init()
  176. if !a.skipInit {
  177. // Initialize authority from options or configuration.
  178. if err := a.init(); err != nil {
  179. return nil, err
  180. }
  181. }
  182. return a, nil
  183. }
  184. type authorityKey struct{}
  185. // NewContext adds the given authority to the context.
  186. func NewContext(ctx context.Context, a *Authority) context.Context {
  187. return context.WithValue(ctx, authorityKey{}, a)
  188. }
  189. // FromContext returns the current authority from the given context.
  190. func FromContext(ctx context.Context) (a *Authority, ok bool) {
  191. a, ok = ctx.Value(authorityKey{}).(*Authority)
  192. return
  193. }
  194. // MustFromContext returns the current authority from the given context. It will
  195. // panic if the authority is not in the context.
  196. func MustFromContext(ctx context.Context) *Authority {
  197. var (
  198. a *Authority
  199. ok bool
  200. )
  201. if a, ok = FromContext(ctx); !ok {
  202. panic("authority is not in the context")
  203. }
  204. return a
  205. }
  206. // ReloadAdminResources reloads admins and provisioners from the DB.
  207. func (a *Authority) ReloadAdminResources(ctx context.Context) error {
  208. var (
  209. provList provisioner.List
  210. adminList []*linkedca.Admin
  211. )
  212. if a.config.AuthorityConfig.EnableAdmin {
  213. provs, err := a.adminDB.GetProvisioners(ctx)
  214. if err != nil {
  215. return admin.WrapErrorISE(err, "error getting provisioners to initialize authority")
  216. }
  217. provList, err = provisionerListToCertificates(provs)
  218. if err != nil {
  219. return admin.WrapErrorISE(err, "error converting provisioner list to certificates")
  220. }
  221. adminList, err = a.adminDB.GetAdmins(ctx)
  222. if err != nil {
  223. return admin.WrapErrorISE(err, "error getting admins to initialize authority")
  224. }
  225. } else {
  226. provList = a.config.AuthorityConfig.Provisioners
  227. adminList = a.config.AuthorityConfig.Admins
  228. }
  229. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  230. if err != nil {
  231. return admin.WrapErrorISE(err, "error generating provisioner config")
  232. }
  233. // Create provisioner collection.
  234. provClxn := provisioner.NewCollection(provisionerConfig.Audiences)
  235. for _, p := range provList {
  236. if err := p.Init(provisionerConfig); err != nil {
  237. log.Printf("failed to initialize %s provisioner %q: %v\n", p.GetType(), p.GetName(), err)
  238. p = provisioner.Uninitialized{
  239. Interface: p, Reason: err,
  240. }
  241. }
  242. if err := provClxn.Store(p); err != nil {
  243. return err
  244. }
  245. }
  246. // Create admin collection.
  247. adminClxn := administrator.NewCollection(provClxn)
  248. for _, adm := range adminList {
  249. p, ok := provClxn.Load(adm.ProvisionerId)
  250. if !ok {
  251. return admin.NewErrorISE("provisioner %s not found when loading admin %s",
  252. adm.ProvisionerId, adm.Id)
  253. }
  254. if err := adminClxn.Store(adm, p); err != nil {
  255. return err
  256. }
  257. }
  258. a.config.AuthorityConfig.Provisioners = provList
  259. a.provisioners = provClxn
  260. a.config.AuthorityConfig.Admins = adminList
  261. a.admins = adminClxn
  262. switch {
  263. case a.requiresSCEP() && a.GetSCEP() == nil:
  264. // TODO(hs): try to initialize SCEP here too? It's a bit
  265. // problematic if this method is called as part of an update
  266. // via Admin API and a password needs to be provided.
  267. case a.requiresSCEP() && a.GetSCEP() != nil:
  268. // update the SCEP Authority with the currently active SCEP
  269. // provisioner names and revalidate the configuration.
  270. a.scepAuthority.UpdateProvisioners(a.getSCEPProvisionerNames())
  271. if err := a.scepAuthority.Validate(); err != nil {
  272. log.Printf("failed validating SCEP authority: %v\n", err)
  273. }
  274. case !a.requiresSCEP() && a.GetSCEP() != nil:
  275. // TODO(hs): don't remove the authority if we can't also
  276. // reload it.
  277. //a.scepAuthority = nil
  278. }
  279. return nil
  280. }
  281. // init performs validation and initializes the fields of an Authority struct.
  282. func (a *Authority) init() error {
  283. // Check if handler has already been validated/initialized.
  284. if a.initOnce {
  285. return nil
  286. }
  287. var err error
  288. ctx := NewContext(context.Background(), a)
  289. // Set password if they are not set.
  290. var configPassword []byte
  291. if a.config.Password != "" {
  292. configPassword = []byte(a.config.Password)
  293. }
  294. if configPassword != nil && a.password == nil {
  295. a.password = configPassword
  296. }
  297. if a.sshHostPassword == nil {
  298. a.sshHostPassword = a.password
  299. }
  300. if a.sshUserPassword == nil {
  301. a.sshUserPassword = a.password
  302. }
  303. // Automatically enable admin for all linked cas.
  304. if a.linkedCAToken != "" {
  305. a.config.AuthorityConfig.EnableAdmin = true
  306. }
  307. // Initialize step-ca Database if it's not already initialized with WithDB.
  308. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  309. if a.db == nil {
  310. if a.db, err = db.New(a.config.DB); err != nil {
  311. return err
  312. }
  313. }
  314. // Initialize key manager if it has not been set in the options.
  315. if a.keyManager == nil {
  316. var options kmsapi.Options
  317. if a.config.KMS != nil {
  318. options = *a.config.KMS
  319. }
  320. a.keyManager, err = kms.New(ctx, options)
  321. if err != nil {
  322. return err
  323. }
  324. a.keyManager = newInstrumentedKeyManager(a.keyManager, a.meter)
  325. }
  326. // Initialize linkedca client if necessary. On a linked RA, the issuer
  327. // configuration might come from majordomo.
  328. var linkedcaClient *linkedCaClient
  329. if a.config.AuthorityConfig.EnableAdmin && a.linkedCAToken != "" && a.adminDB == nil {
  330. linkedcaClient, err = newLinkedCAClient(a.linkedCAToken)
  331. if err != nil {
  332. return err
  333. }
  334. // If authorityId is configured make sure it matches the one in the token
  335. if id := a.config.AuthorityConfig.AuthorityID; id != "" && !strings.EqualFold(id, linkedcaClient.authorityID) {
  336. return errors.New("error initializing linkedca: token authority and configured authority do not match")
  337. }
  338. a.config.AuthorityConfig.AuthorityID = linkedcaClient.authorityID
  339. linkedcaClient.Run()
  340. }
  341. // Initialize the X.509 CA Service if it has not been set in the options.
  342. if a.x509CAService == nil {
  343. var options casapi.Options
  344. if a.config.AuthorityConfig.Options != nil {
  345. options = *a.config.AuthorityConfig.Options
  346. }
  347. // AuthorityID might be empty. It's always available linked CAs/RAs.
  348. options.AuthorityID = a.config.AuthorityConfig.AuthorityID
  349. // Configure linked RA
  350. if linkedcaClient != nil && options.CertificateAuthority == "" {
  351. conf, err := linkedcaClient.GetConfiguration(ctx)
  352. if err != nil {
  353. return err
  354. }
  355. if conf.RaConfig != nil {
  356. options.CertificateAuthority = conf.RaConfig.CaUrl
  357. options.CertificateAuthorityFingerprint = conf.RaConfig.Fingerprint
  358. options.CertificateIssuer = &casapi.CertificateIssuer{
  359. Type: conf.RaConfig.Provisioner.Type.String(),
  360. Provisioner: conf.RaConfig.Provisioner.Name,
  361. }
  362. // Configure the RA authority type if needed
  363. if options.Type == "" {
  364. options.Type = casapi.StepCAS
  365. }
  366. }
  367. // Remote configuration is currently only supported on a linked RA
  368. if sc := conf.ServerConfig; sc != nil {
  369. if a.config.Address == "" {
  370. a.config.Address = sc.Address
  371. }
  372. if len(a.config.DNSNames) == 0 {
  373. a.config.DNSNames = sc.DnsNames
  374. }
  375. }
  376. }
  377. // Set the issuer password if passed in the flags.
  378. if options.CertificateIssuer != nil && a.issuerPassword != nil {
  379. options.CertificateIssuer.Password = string(a.issuerPassword)
  380. }
  381. // Read intermediate and create X509 signer for default CAS.
  382. if options.Is(casapi.SoftCAS) {
  383. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  384. if err != nil {
  385. return err
  386. }
  387. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  388. SigningKey: a.config.IntermediateKey,
  389. Password: a.password,
  390. })
  391. if err != nil {
  392. return err
  393. }
  394. // If not defined with an option, add intermediates to the list of
  395. // certificates used for name constraints validation at issuance
  396. // time.
  397. if len(a.intermediateX509Certs) == 0 {
  398. a.intermediateX509Certs = append(a.intermediateX509Certs, options.CertificateChain...)
  399. }
  400. }
  401. a.x509CAService, err = cas.New(ctx, options)
  402. if err != nil {
  403. return err
  404. }
  405. // Get root certificate from CAS.
  406. if srv, ok := a.x509CAService.(casapi.CertificateAuthorityGetter); ok {
  407. resp, err := srv.GetCertificateAuthority(&casapi.GetCertificateAuthorityRequest{
  408. Name: options.CertificateAuthority,
  409. })
  410. if err != nil {
  411. return err
  412. }
  413. a.rootX509Certs = append(a.rootX509Certs, resp.RootCertificate)
  414. a.intermediateX509Certs = append(a.intermediateX509Certs, resp.IntermediateCertificates...)
  415. }
  416. }
  417. // Read root certificates and store them in the certificates map.
  418. if len(a.rootX509Certs) == 0 {
  419. a.rootX509Certs = make([]*x509.Certificate, 0, len(a.config.Root))
  420. for _, path := range a.config.Root {
  421. crts, err := pemutil.ReadCertificateBundle(path)
  422. if err != nil {
  423. return err
  424. }
  425. a.rootX509Certs = append(a.rootX509Certs, crts...)
  426. }
  427. }
  428. for _, crt := range a.rootX509Certs {
  429. sum := sha256.Sum256(crt.Raw)
  430. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  431. }
  432. a.rootX509CertPool = x509.NewCertPool()
  433. for _, cert := range a.rootX509Certs {
  434. a.rootX509CertPool.AddCert(cert)
  435. }
  436. // Read federated certificates and store them in the certificates map.
  437. if len(a.federatedX509Certs) == 0 {
  438. a.federatedX509Certs = make([]*x509.Certificate, 0, len(a.config.FederatedRoots))
  439. for _, path := range a.config.FederatedRoots {
  440. crts, err := pemutil.ReadCertificateBundle(path)
  441. if err != nil {
  442. return err
  443. }
  444. a.federatedX509Certs = append(a.federatedX509Certs, crts...)
  445. }
  446. }
  447. for _, crt := range a.federatedX509Certs {
  448. sum := sha256.Sum256(crt.Raw)
  449. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  450. }
  451. // Initialize HTTPClient with all root certs
  452. clientRoots := make([]*x509.Certificate, 0, len(a.rootX509Certs)+len(a.federatedX509Certs))
  453. clientRoots = append(clientRoots, a.rootX509Certs...)
  454. clientRoots = append(clientRoots, a.federatedX509Certs...)
  455. a.httpClient = newHTTPClient(a.wrapTransport, clientRoots...)
  456. if err != nil {
  457. return err
  458. }
  459. // Decrypt and load SSH keys
  460. var tmplVars templates.Step
  461. if a.config.SSH != nil {
  462. if a.config.SSH.HostKey != "" {
  463. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  464. SigningKey: a.config.SSH.HostKey,
  465. Password: a.sshHostPassword,
  466. })
  467. if err != nil {
  468. return err
  469. }
  470. // If our signer is from sshagentkms, just unwrap it instead of
  471. // wrapping it in another layer, and this prevents crypto from
  472. // erroring out with: ssh: unsupported key type *agent.Key
  473. switch s := signer.(type) {
  474. case *sshagentkms.WrappedSSHSigner:
  475. a.sshCAHostCertSignKey = s.Signer
  476. case crypto.Signer:
  477. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(s)
  478. default:
  479. return errors.Errorf("unsupported signer type %T", signer)
  480. }
  481. if err != nil {
  482. return errors.Wrap(err, "error creating ssh signer")
  483. }
  484. // Append public key to list of host certs
  485. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  486. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  487. }
  488. if a.config.SSH.UserKey != "" {
  489. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  490. SigningKey: a.config.SSH.UserKey,
  491. Password: a.sshUserPassword,
  492. })
  493. if err != nil {
  494. return err
  495. }
  496. // If our signer is from sshagentkms, just unwrap it instead of
  497. // wrapping it in another layer, and this prevents crypto from
  498. // erroring out with: ssh: unsupported key type *agent.Key
  499. switch s := signer.(type) {
  500. case *sshagentkms.WrappedSSHSigner:
  501. a.sshCAUserCertSignKey = s.Signer
  502. case crypto.Signer:
  503. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(s)
  504. default:
  505. return errors.Errorf("unsupported signer type %T", signer)
  506. }
  507. if err != nil {
  508. return errors.Wrap(err, "error creating ssh signer")
  509. }
  510. // Append public key to list of user certs
  511. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  512. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  513. }
  514. // Append other public keys and add them to the template variables.
  515. for _, key := range a.config.SSH.Keys {
  516. publicKey := key.PublicKey()
  517. switch key.Type {
  518. case provisioner.SSHHostCert:
  519. if key.Federated {
  520. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, publicKey)
  521. } else {
  522. a.sshCAHostCerts = append(a.sshCAHostCerts, publicKey)
  523. }
  524. case provisioner.SSHUserCert:
  525. if key.Federated {
  526. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, publicKey)
  527. } else {
  528. a.sshCAUserCerts = append(a.sshCAUserCerts, publicKey)
  529. }
  530. default:
  531. return errors.Errorf("unsupported type %s", key.Type)
  532. }
  533. }
  534. }
  535. // Configure template variables. On the template variables HostFederatedKeys
  536. // and UserFederatedKeys we will skip the actual CA that will be available
  537. // in HostKey and UserKey.
  538. //
  539. // We cannot do it in the previous blocks because this configuration can be
  540. // injected using options.
  541. if a.sshCAHostCertSignKey != nil {
  542. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  543. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  544. } else {
  545. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts...)
  546. }
  547. if a.sshCAUserCertSignKey != nil {
  548. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  549. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  550. } else {
  551. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts...)
  552. }
  553. if a.config.AuthorityConfig.EnableAdmin {
  554. // Initialize step-ca Admin Database if it's not already initialized using
  555. // WithAdminDB.
  556. if a.adminDB == nil {
  557. if linkedcaClient != nil {
  558. a.adminDB = linkedcaClient
  559. } else {
  560. a.adminDB, err = adminDBNosql.New(a.db.(nosql.DB), admin.DefaultAuthorityID)
  561. if err != nil {
  562. return err
  563. }
  564. }
  565. }
  566. provs, err := a.adminDB.GetProvisioners(ctx)
  567. if err != nil {
  568. return admin.WrapErrorISE(err, "error loading provisioners to initialize authority")
  569. }
  570. if len(provs) == 0 && !strings.EqualFold(a.config.AuthorityConfig.DeploymentType, "linked") {
  571. // Migration will currently only be kicked off once, because either one or more provisioners
  572. // are migrated or a default JWK provisioner will be created in the DB. It won't run for
  573. // linked or hosted deployments. Not for linked, because that case is explicitly checked
  574. // for above. Not for hosted, because there'll be at least an existing OIDC provisioner.
  575. var firstJWKProvisioner *linkedca.Provisioner
  576. if len(a.config.AuthorityConfig.Provisioners) > 0 {
  577. // Existing provisioners detected; try migrating them to DB storage.
  578. a.initLogf("Starting migration of provisioners")
  579. for _, p := range a.config.AuthorityConfig.Provisioners {
  580. lp, err := ProvisionerToLinkedca(p)
  581. if err != nil {
  582. return admin.WrapErrorISE(err, "error transforming provisioner %q while migrating", p.GetName())
  583. }
  584. // Store the provisioner to be migrated
  585. if err := a.adminDB.CreateProvisioner(ctx, lp); err != nil {
  586. return admin.WrapErrorISE(err, "error creating provisioner %q while migrating", p.GetName())
  587. }
  588. // Mark the first JWK provisioner, so that it can be used for administration purposes
  589. if firstJWKProvisioner == nil && lp.Type == linkedca.Provisioner_JWK {
  590. firstJWKProvisioner = lp
  591. a.initLogf("Migrated JWK provisioner %q with admin permissions", p.GetName())
  592. } else {
  593. a.initLogf("Migrated %s provisioner %q", p.GetType(), p.GetName())
  594. }
  595. }
  596. c := a.config
  597. if c.WasLoadedFromFile() {
  598. // The provisioners in the configuration file can be deleted from
  599. // the file by editing it. Automatic rewriting of the file was considered
  600. // to be too surprising for users and not the right solution for all
  601. // use cases, so we leave it up to users to this themselves.
  602. a.initLogf("Provisioners that were migrated can now be removed from `ca.json` by editing it")
  603. }
  604. a.initLogf("Finished migrating provisioners")
  605. }
  606. // Create first JWK provisioner for remote administration purposes if none exists yet
  607. if firstJWKProvisioner == nil {
  608. firstJWKProvisioner, err = CreateFirstProvisioner(ctx, a.adminDB, string(a.password))
  609. if err != nil {
  610. return admin.WrapErrorISE(err, "error creating first provisioner")
  611. }
  612. a.initLogf("Created JWK provisioner %q with admin permissions", firstJWKProvisioner.GetName())
  613. }
  614. // Create first super admin, belonging to the first JWK provisioner
  615. // TODO(hs): pass a user-provided first super admin subject to here. With `ca init` it's
  616. // added to the DB immediately if using remote management. But when migrating from
  617. // ca.json to the DB, this option doesn't exist. Adding a flag just to do it during
  618. // migration isn't nice. We could opt for a user to change it afterwards. There exist
  619. // cases in which creation of `step` could lock out a user from API access. This is the
  620. // case if `step` isn't allowed to be signed by Name Constraints or the X.509 policy.
  621. // We have protection for that when creating and updating a policy, but if a policy or
  622. // Name Constraints are in use at the time of migration, that could lock the user out.
  623. superAdminSubject := "step"
  624. if err := a.adminDB.CreateAdmin(ctx, &linkedca.Admin{
  625. ProvisionerId: firstJWKProvisioner.Id,
  626. Subject: superAdminSubject,
  627. Type: linkedca.Admin_SUPER_ADMIN,
  628. }); err != nil {
  629. return admin.WrapErrorISE(err, "error creating first admin")
  630. }
  631. a.initLogf("Created super admin %q for JWK provisioner %q", superAdminSubject, firstJWKProvisioner.GetName())
  632. }
  633. }
  634. // Load Provisioners and Admins
  635. if err := a.ReloadAdminResources(ctx); err != nil {
  636. return err
  637. }
  638. // The SCEP functionality is provided through an instance of
  639. // scep.Authority. It is initialized when the CA is started and
  640. // if it doesn't exist yet. It gets refreshed if it already
  641. // exists. If the SCEP authority is no longer required on reload,
  642. // it gets removed.
  643. // TODO(hs): reloading through SIGHUP doesn't hit these cases. This
  644. // is because an entirely new authority.Authority is created, including
  645. // a new scep.Authority. Look into this to see if we want this to
  646. // keep working like that, or want to reuse a single instance and
  647. // update that.
  648. switch {
  649. case a.requiresSCEP() && a.GetSCEP() == nil:
  650. if a.scepOptions == nil {
  651. options := &scep.Options{
  652. Roots: a.rootX509Certs,
  653. Intermediates: a.intermediateX509Certs,
  654. }
  655. // intermediate certificates can be empty in RA mode
  656. if len(a.intermediateX509Certs) > 0 {
  657. options.SignerCert = a.intermediateX509Certs[0]
  658. }
  659. // attempt to create the (default) SCEP signer if the intermediate
  660. // key is configured.
  661. if a.config.IntermediateKey != "" {
  662. if options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  663. SigningKey: a.config.IntermediateKey,
  664. Password: a.password,
  665. }); err != nil {
  666. return err
  667. }
  668. // TODO(hs): instead of creating the decrypter here, pass the
  669. // intermediate key + chain down to the SCEP authority,
  670. // and only instantiate it when required there. Is that possible?
  671. // Also with entering passwords?
  672. // TODO(hs): if moving the logic, try improving the logic for the
  673. // decrypter password too? Right now it needs to be entered multiple
  674. // times; I've observed it to be three times maximum, every time
  675. // the intermediate key is read.
  676. _, isRSAKey := options.Signer.Public().(*rsa.PublicKey)
  677. if km, ok := a.keyManager.(kmsapi.Decrypter); ok && isRSAKey {
  678. if decrypter, err := km.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  679. DecryptionKey: a.config.IntermediateKey,
  680. Password: a.password,
  681. }); err == nil {
  682. // only pass the decrypter down when it was successfully created,
  683. // meaning it's an RSA key, and `CreateDecrypter` did not fail.
  684. options.Decrypter = decrypter
  685. options.DecrypterCert = options.Intermediates[0]
  686. }
  687. }
  688. }
  689. a.scepOptions = options
  690. }
  691. // provide the current SCEP provisioner names, so that the provisioners
  692. // can be validated when the CA is started.
  693. a.scepOptions.SCEPProvisionerNames = a.getSCEPProvisionerNames()
  694. // create a new SCEP authority
  695. scepAuthority, err := scep.New(a, *a.scepOptions)
  696. if err != nil {
  697. return err
  698. }
  699. if a.validateSCEP {
  700. // validate the SCEP authority
  701. if err := scepAuthority.Validate(); err != nil {
  702. a.initLogf("failed validating SCEP authority: %v", err)
  703. }
  704. }
  705. // set the SCEP authority
  706. a.scepAuthority = scepAuthority
  707. case !a.requiresSCEP() && a.GetSCEP() != nil:
  708. // clear the SCEP authority if it's no longer required
  709. a.scepAuthority = nil
  710. case a.requiresSCEP() && a.GetSCEP() != nil:
  711. // update the SCEP Authority with the currently active SCEP
  712. // provisioner names and revalidate the configuration.
  713. a.scepAuthority.UpdateProvisioners(a.getSCEPProvisionerNames())
  714. if err := a.scepAuthority.Validate(); err != nil {
  715. log.Printf("failed validating SCEP authority: %v\n", err)
  716. }
  717. }
  718. // Load X509 constraints engine.
  719. //
  720. // This is currently only available in CA mode.
  721. if size := len(a.intermediateX509Certs); size > 0 {
  722. last := a.intermediateX509Certs[size-1]
  723. constraintCerts := make([]*x509.Certificate, 0, size+1)
  724. constraintCerts = append(constraintCerts, a.intermediateX509Certs...)
  725. for _, root := range a.rootX509Certs {
  726. if bytes.Equal(last.RawIssuer, root.RawSubject) && bytes.Equal(last.AuthorityKeyId, root.SubjectKeyId) {
  727. constraintCerts = append(constraintCerts, root)
  728. }
  729. }
  730. a.constraintsEngine = constraints.New(constraintCerts...)
  731. }
  732. // Load x509 and SSH Policy Engines
  733. if err := a.reloadPolicyEngines(ctx); err != nil {
  734. return err
  735. }
  736. // Configure templates, currently only ssh templates are supported.
  737. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  738. a.templates = a.config.Templates
  739. if a.templates == nil {
  740. a.templates = templates.DefaultTemplates()
  741. }
  742. if a.templates.Data == nil {
  743. a.templates.Data = make(map[string]interface{})
  744. }
  745. a.templates.Data["Step"] = tmplVars
  746. }
  747. // Start the CRL generator, we can assume the configuration is validated.
  748. if a.config.CRL.IsEnabled() {
  749. // Default cache duration to the default one
  750. if v := a.config.CRL.CacheDuration; v == nil || v.Duration <= 0 {
  751. a.config.CRL.CacheDuration = config.DefaultCRLCacheDuration
  752. }
  753. // Start CRL generator
  754. if err := a.startCRLGenerator(); err != nil {
  755. return err
  756. }
  757. }
  758. // JWT numeric dates are seconds.
  759. a.startTime = time.Now().Truncate(time.Second)
  760. // Set flag indicating that initialization has been completed, and should
  761. // not be repeated.
  762. a.initOnce = true
  763. return nil
  764. }
  765. // initLogf is used to log initialization information. The output
  766. // can be disabled by starting the CA with the `--quiet` flag.
  767. func (a *Authority) initLogf(format string, v ...any) {
  768. if !a.quietInit {
  769. log.Printf(format, v...)
  770. }
  771. }
  772. // GetID returns the define authority id or a zero uuid.
  773. func (a *Authority) GetID() string {
  774. const zeroUUID = "00000000-0000-0000-0000-000000000000"
  775. if id := a.config.AuthorityConfig.AuthorityID; id != "" {
  776. return id
  777. }
  778. return zeroUUID
  779. }
  780. // GetDatabase returns the authority database. If the configuration does not
  781. // define a database, GetDatabase will return a db.SimpleDB instance.
  782. func (a *Authority) GetDatabase() db.AuthDB {
  783. return a.db
  784. }
  785. // GetAdminDatabase returns the admin database, if one exists.
  786. func (a *Authority) GetAdminDatabase() admin.DB {
  787. return a.adminDB
  788. }
  789. // GetConfig returns the config.
  790. func (a *Authority) GetConfig() *config.Config {
  791. return a.config
  792. }
  793. // GetBackdate returns the [time.Duration] representing the
  794. // amount of time that is to be subtracted from the current
  795. // time when issuing a new certificate.
  796. func (a *Authority) GetBackdate() *time.Duration {
  797. if a.config == nil || a.config.AuthorityConfig == nil || a.config.AuthorityConfig.Backdate == nil {
  798. return nil
  799. }
  800. return &a.config.AuthorityConfig.Backdate.Duration
  801. }
  802. // GetInfo returns information about the authority.
  803. func (a *Authority) GetInfo() Info {
  804. ai := Info{
  805. StartTime: a.startTime,
  806. RootX509Certs: a.rootX509Certs,
  807. DNSNames: a.config.DNSNames,
  808. }
  809. if a.sshCAUserCertSignKey != nil {
  810. ai.SSHCAUserPublicKey = ssh.MarshalAuthorizedKey(a.sshCAUserCertSignKey.PublicKey())
  811. }
  812. if a.sshCAHostCertSignKey != nil {
  813. ai.SSHCAHostPublicKey = ssh.MarshalAuthorizedKey(a.sshCAHostCertSignKey.PublicKey())
  814. }
  815. return ai
  816. }
  817. // IsAdminAPIEnabled returns a boolean indicating whether the Admin API has
  818. // been enabled.
  819. func (a *Authority) IsAdminAPIEnabled() bool {
  820. return a.config.AuthorityConfig.EnableAdmin
  821. }
  822. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  823. func (a *Authority) Shutdown() error {
  824. if a.crlTicker != nil {
  825. a.crlTicker.Stop()
  826. close(a.crlStopper)
  827. }
  828. if err := a.keyManager.Close(); err != nil {
  829. log.Printf("error closing the key manager: %v", err)
  830. }
  831. return a.db.Shutdown()
  832. }
  833. // CloseForReload closes internal services, to allow a safe reload.
  834. func (a *Authority) CloseForReload() {
  835. if a.crlTicker != nil {
  836. a.crlTicker.Stop()
  837. close(a.crlStopper)
  838. }
  839. if err := a.keyManager.Close(); err != nil {
  840. log.Printf("error closing the key manager: %v", err)
  841. }
  842. if client, ok := a.adminDB.(*linkedCaClient); ok {
  843. client.Stop()
  844. }
  845. }
  846. // IsRevoked returns whether or not a certificate has been
  847. // revoked before.
  848. func (a *Authority) IsRevoked(sn string) (bool, error) {
  849. // Check the passive revocation table.
  850. if lca, ok := a.adminDB.(interface {
  851. IsRevoked(string) (bool, error)
  852. }); ok {
  853. return lca.IsRevoked(sn)
  854. }
  855. return a.db.IsRevoked(sn)
  856. }
  857. // requiresSCEP iterates over the configured provisioners
  858. // and determines if at least one of them is a SCEP provisioner.
  859. func (a *Authority) requiresSCEP() bool {
  860. for _, p := range a.config.AuthorityConfig.Provisioners {
  861. if p.GetType() == provisioner.TypeSCEP {
  862. return true
  863. }
  864. }
  865. return false
  866. }
  867. // getSCEPProvisionerNames returns the names of the SCEP provisioners
  868. // that are currently available in the CA.
  869. func (a *Authority) getSCEPProvisionerNames() (names []string) {
  870. for _, p := range a.config.AuthorityConfig.Provisioners {
  871. if p.GetType() == provisioner.TypeSCEP {
  872. names = append(names, p.GetName())
  873. }
  874. }
  875. return
  876. }
  877. // GetSCEP returns the configured SCEP Authority
  878. func (a *Authority) GetSCEP() *scep.Authority {
  879. return a.scepAuthority
  880. }
  881. func (a *Authority) startCRLGenerator() error {
  882. if !a.config.CRL.IsEnabled() {
  883. return nil
  884. }
  885. // Check that there is a valid CRL in the DB right now. If it doesn't exist
  886. // or is expired, generate one now
  887. _, ok := a.db.(db.CertificateRevocationListDB)
  888. if !ok {
  889. return errors.Errorf("CRL Generation requested, but database does not support CRL generation")
  890. }
  891. // Always create a new CRL on startup in case the CA has been down and the
  892. // time to next expected CRL update is less than the cache duration.
  893. if err := a.GenerateCertificateRevocationList(); err != nil {
  894. return errors.Wrap(err, "could not generate a CRL")
  895. }
  896. a.crlStopper = make(chan struct{}, 1)
  897. a.crlTicker = time.NewTicker(a.config.CRL.TickerDuration())
  898. go func() {
  899. for {
  900. select {
  901. case <-a.crlTicker.C:
  902. log.Println("Regenerating CRL")
  903. if err := a.GenerateCertificateRevocationList(); err != nil {
  904. log.Printf("error regenerating the CRL: %v", err)
  905. }
  906. case <-a.crlStopper:
  907. return
  908. }
  909. }
  910. }()
  911. return nil
  912. }