authority.go 30 KB

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