authority.go 35 KB

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