authority.go 30 KB

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