Skip to content
SQL injection Write-up Advanced

Pre-Authentication SQL Injection in FortiClient EMS 7.4.4 - CVE-2026-21643

FortiClient EMS 7.4.4 in multi-tenant mode passes the unsanitised Site HTTP header into a SQL SET search_path statement before authentication, allowing SQL injection. An unauthenticated attacker could execute arbitrary SQL against the PostgreSQL database, potentially leading to data theft, credential extraction, and remote code execution.

bishopfox.com

Published on bishopfox.com

FortiClient EMS is Fortinet's centralized management server for FortiClient endpoint agents. Organizations use it to deploy, configure, and monitor FortiClient installations across their endpoint fleet.

The author, on bishopfox.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

FortiClient EMS is Fortinet's centralised management server for FortiClient endpoint agents. Administrators use it to deploy, configure and monitor FortiClient installations across an endpoint fleet. The web GUI is a Django application served through Apache/mod_wsgi on port 443, backed by PostgreSQL through pgbouncer for connection pooling.

Since at least version 7.4.0 the product has supported a multitenancy feature called "Sites", which lets one EMS instance serve multiple virtual domains (vdoms). When the feature is enabled (SITES_ENABLED=True in the application configuration), incoming HTTP requests carry a Site header that tells the application which tenant context the request targets. Django middleware reads that header and uses it to set the PostgreSQL search_path to the matching tenant schema before any query runs, so each tenant's data stays isolated at the database level.

CVE-2026-21643 is a pre-authentication SQL injection in FortiClient EMS 7.4.4. The Site header value is interpolated into a SET search_path statement without sanitisation, and this happens before any login check. The vendor advisory is FG-IR-25-1142.

CVE ID Type Attack Vector Auth Required Impact CVSS Fixed Version
CVE-2026-21643 SQL Injection Network None Arbitrary SQL execution 9.1 7.4.5

Setup

The research was done independently after Fortinet published its advisory and patch. All testing ran against locally deployed lab instances; no production systems were targeted.

The analysis used FortiClient EMS VMware images for versions 7.4.3, 7.4.4 and 7.4.5. The workflow was:

  1. Convert the VMDK files to raw disk images with qemu-img, identify the GPT partition layout, and mount the LVM logical volumes to reach the full filesystem of each version.
  2. The web GUI is a Django application shipped as Python 3.10 bytecode (.pyc files) under /opt/forticlientems/fcm/fcm/. The researchers built pycdc to decompile the bytecode back to Python source and batch-decompiled controllers, middlewares, models and URL routing across all three versions.
  3. Run three-way diffs (7.4.3, 7.4.4, 7.4.5) to separate security-relevant changes from framework noise.
  4. Decompile the full middleware stack (SiteMiddleware, AuthMiddleware, BruteForceProtectionMiddleware, ApiLogMiddleware) to map the request chain and confirm ordering.
  5. Deploy FortiClient EMS 7.4.4 as a VMware appliance and enable multi-tenant mode through the GUI so that SITES_ENABLED=True.
  6. Test pre-authentication endpoint candidates for injectability and map operational constraints.
  7. Build a proof-of-concept script targeting init_consts for timing-based detection and error-based extraction, plus a multi-endpoint scanner.

Finding it

The differential analysis showed that 7.4.4 was a significant middleware refactoring release. The 7.4.3 middleware directory held six files:

Text
api_logging.pyc
brute_force_protection_middleware.pyc
conditional_csrf.pyc
security_headers_middleware.pyc
site.pyc
subdomain_session.pyc

The 7.4.4 directory held ten:

Text
api_log_middleware.pyc                (renamed from api_logging.pyc)
auth_middleware.pyc                   (new)
brute_force_protection_middleware.pyc
conditional_csrf.pyc
ems_common_middleware.pyc             (new)
error_handling_middleware.pyc         (new)
rate_limit_middleware.pyc             (new)
security_headers_middleware.pyc
site_middleware.pyc                   (renamed from site.pyc, +322 bytes)
subdomain_session.pyc

Five new middleware files were added, two were renamed, and the request pipeline was restructured. In the same release, postgres_conn.py grew from 11,697 bytes to 13,336 bytes (+1,639 bytes). That growth is where the vulnerable format-string interpolation of the Site header into SET search_path was introduced. Prior versions supported multitenancy but routed tenants differently at the database layer, and did not contain the interpolation.

The request processing chain in 7.4.4 is:

Text
HTTP Request -> Apache/mod_wsgi -> Django
  -> ApiLogMiddleware        (logs the request)
  -> SiteMiddleware          (reads Site header, sets vdom)
  -> PostgresConnection      (opens DB connection with search_path)
  -> AuthMiddleware          (checks session/credentials)
  -> BruteForceProtection    (rate limits login attempts)
  -> View/Controller

The critical detail is that SiteMiddleware runs before AuthMiddleware. When a request arrives at a pre-authentication endpoint such as /api/v1/auth/signin, the database connection is already established with the attacker-controlled search_path before any credentials are checked.

Exploitation

Step 1: Fingerprint the target

SITES_ENABLED is readable without authentication through GET /api/v1/init_consts, which returns it in the JSON response at data.consts.System.SITES_ENABLED. Both legitimate clients and attackers can use this to learn whether a target is in multi-tenant mode. If the flag is off, the injection path is not reachable.

Step 2: Confirm injection with a timing payload

The Site header is lowercased and then embedded in a quoted schema name. A payload that closes the quote, terminates the SET statement and comments out the remainder looks like this:

Text
Header:         Site: x'; SELECT pg_sleep(5)--
After .lower(): x'; select pg_sleep(5)--
db_name:        fcm_x'; select pg_sleep(5)--
Executed:       SET search_path TO 'fcm_x'; SELECT pg_sleep(5)--', public, addons
                                          ^                      ^
                                      breakout              commented out

The single quote closes the schema name string, the semicolon terminates the SET statement, and -- comments out the trailing ', public, addons. Everything between the semicolon and the comment marker executes as a separate statement with the privileges of the EMS database user.

Lab testing sent crafted Site headers containing pg_sleep() payloads to each endpoint and compared response times against a benign baseline. The Connection: close header was used on all requests to force fresh pgbouncer connections per request.

POST /api/v1/auth/signin (login endpoint):

Text
Baseline:   1.019s  (HTTP 401, Site: default)
Injection: 21.050s  (HTTP 401, Site: x'; SELECT pg_sleep(10)--)
Delta:     20.030s  (~2x requested sleep)

The roughly 2x delta is consistent with pgbouncer connection pooling executing the SET search_path statement on both connection acquisition and release, so the sleep runs twice. This endpoint has brute force protection: 3 attempts before lockout.

GET /api/v1/init_consts (public constants endpoint):

Text
Baseline:   0.077s  (HTTP 200, Site: default)
Injection: 10.074s  (HTTP 500, Site: x'; SELECT pg_sleep(10)--)
Delta:      9.997s  (~1x requested sleep)

Here the multiplier is a clean 1x, and the injection produces HTTP 500 with PostgreSQL error details in the body. The endpoint has no brute force protection and no authentication requirement, which makes it the more practical vector.

Step 3: Extract data through error messages

The HTTP 500 body on init_consts leaks raw PostgreSQL errors:

JSON
{"result": {"retval": -7, "message": "relation \"system_settings\" does not exist\nLINE 4: FROM system_settings\n ^"}}

Wrapping a query in CAST((<query>)::text AS int) makes PostgreSQL return the query result inside the error message, giving single-request data exfiltration without timing oracles. The injection context supports stacked queries (full SQL command execution via semicolon separation), error-based extraction confirmed on init_consts, and blind boolean extraction using conditional pg_sleep() as a fallback.

Endpoint characteristics

  • Lockout restrictions. Both /api/v1/auth/signin and /api/v1/init_consts are injectable. signin is subject to BruteForceProtectionMiddleware (default 3 attempts before lockout); init_consts has no such restriction, so an attacker who knows about it can extract data without triggering any lockout.
  • Error-based extraction. init_consts returns PostgreSQL errors in the JSON body, so CAST expressions that force type conversion errors extract arbitrary query results in one HTTP request per value, faster and stealthier than timing-based blind extraction.
  • pgbouncer connection pooling. SET search_path executes at connection acquisition time. Pooled connections cause double execution on signin (2x sleep multiplier) but single execution on init_consts (1x). Long pg_sleep() values can saturate the connection pool and temporarily make the EMS instance unresponsive.
  • Exploitation depth. Stacked queries, error-based extraction and blind boolean extraction are all available.

Root cause

In SiteMiddleware, the Site header is read and stored with no validation beyond lowercasing:

Python
# middlewares/site_middleware.py (decompiled from 7.4.4 bytecode)
def _get_header_site(self, request):
    site = request.META.get('HTTP_SITE')
    if site is not None:
        request.META['SITE'] = site.lower()
    return site is not None

def __call__(self, request):
    if not EmsConsts.SITES_ENABLED:
        request.META['SITE'] = EmsConsts.DEFAULT_VDOM
    elif not self._get_header_site(request):
        self._get_subdomain_site(request)

There is no allowlist check against known vdoms, no character filtering and no regex. The raw, lowercased header value flows into request.META['SITE'] and then into PostgresConnection.__init__():

Python
# models/utils/postgres_conn.py (decompiled from 7.4.4 bytecode)
class PostgresConnection:
    def __init__(self, vdom, ...):
        self.db_name = f"fcm_{vdom}"
        self.searchpath = f"SET search_path TO '{self._db_prefix}{self.db_name}', public, addons"

    def execute(self, query, ...):
        self._connection.execute(self.searchpath)  # Runs before every query

The format-string interpolation embeds the unsanitised vdom value directly into a SQL statement that executes on every database query. Because the schema name is wrapped in single quotes, a value containing a quote can break out, terminate the SET statement and inject arbitrary SQL. The existing defences did not stop it: the middleware ordering places the database connection setup before authentication, and the brute force protection only covers the login endpoint, not init_consts.

Impact

A successful exploit gives an unauthenticated attacker arbitrary SQL execution against the EMS PostgreSQL database with the privileges of the EMS database user. According to the report this enables:

  • Remote code execution. In the Virtual Machine image Fortinet ships, the PostgreSQL database user runs with superuser privileges, enabling OS command execution via COPY ... TO/FROM PROGRAM. Lab testing confirmed arbitrary file creation on the underlying host as the postgres system user.
  • Credential theft. Extraction of admin password hashes, API tokens and JWT secrets from authentication tables.
  • Endpoint data exfiltration. Access to the full endpoint inventory: hostnames, IP addresses, OS versions, serial numbers and installed software across all managed FortiClient deployments.
  • Configuration tampering. Modification of endpoint policies, deployment configurations and security profiles pushed to managed endpoints.
  • Certificate extraction. Access to ZTNA certificates and SAML configuration data, potentially enabling lateral movement into connected Fortinet infrastructure.
  • Persistence. Creation of new admin accounts or modification of existing credentials for persistent access to the management console.

The pre-authentication nature of the bug and its position in the database connection layer, affecting every subsequent query in the request lifecycle, make it particularly severe for exposed EMS instances. FortiClient EMS manages an organisation's entire endpoint fleet, which makes it a high-value target. The vulnerability requires direct HTTPS access to the EMS web interface, and only multi-tenant deployments are affected; single-site deployments are not.

Fix

Version 7.4.5 replaced the format-string interpolation with parameterised identifier handling:

Python
# models/utils/postgres_conn.py (decompiled from 7.4.5 bytecode)
from psycopg.sql import SQL, Identifier

schema = f'{self._db_prefix}{self.db_name}'
self.searchpath = SQL('SET search_path TO {}, public, addons').format(Identifier(schema))

psycopg.sql.Identifier() double-quotes and escapes the schema name, preventing breakout regardless of the input value. The refactored middleware architecture remained in place. No configuration changes are needed after the upgrade.

Fortinet's version matrix:

Version Affected Solution
FortiClientEMS 8.0 Not affected Not applicable
FortiClientEMS 7.4 7.4.4 only Upgrade to 7.4.5 or above
FortiClientEMS 7.2 Not affected Not applicable

The 7.2 and 8.0 lines were never part of the refactoring cycle: they use either the pre-refactored database routing code (7.2) or a separately maintained codebase (8.0), neither of which contains the format-string SET search_path construction. The vulnerable code existed in production for exactly one release cycle.

If patching is not immediately possible, the report lists three mitigations:

  1. Restrict network access. Limit HTTPS access to the EMS web GUI to authorised management networks only.
  2. Disable multitenancy. With SITES_ENABLED=False, SiteMiddleware hardcodes the default vdom and never reads the Site header. The vulnerable code remains present but unreachable.
  3. WAF/reverse proxy filtering. Strip or validate the Site header, blocking values containing single quotes, semicolons or SQL keywords.

Variants to test

  • Other pre-authentication endpoints that touch the database. The report tested seven endpoint candidates and found that init_consts was also injectable. On a similar target, send a pg_sleep() payload in the tenant header to every endpoint reachable without a session and compare response times against a benign baseline. A positive result is a consistent timing delta that scales with the requested sleep.
  • Error-leaking endpoints. Look for pre-auth endpoints that return database errors in the response body. A positive result is a 500 response containing raw PostgreSQL error text, which turns a blind injection into single-request extraction via CAST errors.
  • Header-based tenant routing in other products. Any application that maps a request header to a database schema, search path or connection parameter is a candidate. A positive result is a quote or semicolon in the header value changing the response or producing a database error.
  • Connection-pool multipliers. If a payload sleeps twice as long as requested, the statement is likely running on both acquisition and release of a pooled connection. That tells you the injection point sits in connection setup, which usually means it fires on every query in the request.

Hunting notes

This class of bug tends to hide in code that was recently refactored, especially where a feature that previously worked safely was reimplemented. The report's differential analysis is the model: compare the middleware and database connection layers across adjacent versions, and treat any file that grew in a release as worth decompiling. Renamed files and newly added middleware in a single release are a strong signal that request routing changed.

During recon, the useful signals are pre-auth endpoints that return configuration constants, and any header that selects a tenant, schema or database. A flag such as SITES_ENABLED exposed without authentication tells you both that the feature is on and that the header is likely processed early in the request chain. Endpoints that return database error text in their responses are worth prioritising because they convert blind injection into fast extraction.

To show impact, the report combined a timing proof on two endpoints with an error-based extraction proof on the unauthenticated one, and demonstrated that the database user could create files on the host. That combination, pre-auth access, arbitrary SQL and host-level file creation, is what makes the severity clear.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 28 min read.

What happened, in plain words

Fortinet makes a product called FortiClient EMS. It is a management server: a central computer that an organisation uses to look after the security software installed on all of its staff laptops and desktops. Think of it as the head office that gives instructions to hundreds of branch offices. If someone breaks into the head office, they can give instructions to every branch at once.

In version 7.4.4 of that product, a routine tidy-up of the code introduced a serious mistake. The mistake lets anyone who can reach the server's web interface over HTTPS, without any username or password at all, send a specially crafted request that makes the server run database commands of the attacker's choosing. The database is where the server keeps its most valuable information: administrator passwords, the list of every managed computer, security policies and certificates.

The flaw is called a SQL injection. SQL is the language used to talk to a database. A SQL injection happens when a program takes text supplied by a user and glues it straight into a database command, so that the user's text is treated as part of the command rather than as harmless data. A simple comparison: imagine a form that says "write your name here" and a clerk who reads the form aloud to a colleague as "file this under the name [your text]". If you write "Bob, and also throw away all the files", the clerk reads out an instruction to throw away the files. The clerk could not tell your name from a command, because nobody marked where one ended and the other began.

The bug was fixed in version 7.4.5, one release later. Only version 7.4.4 is affected, and only when a particular optional feature called multi-tenancy is switched on. The vendor's advisory is FG-IR-25-1142.

CVE ID Type Attack Vector Auth Required Impact CVSS Fixed Version
CVE-2026-21643 SQL Injection Network None Arbitrary SQL execution 9.1 7.4.5

A few words from that table. A CVE ID is a public catalogue number given to a known security flaw so that everyone can refer to the same thing. Attack Vector: Network means the attacker reaches the flaw over the network rather than needing to sit at the machine. Auth Required: None means no login is needed. CVSS 9.1 is a severity score from 0 to 10, where higher is worse; 9.1 is in the critical band.

Background: the product and the feature

FortiClient EMS runs as a Django application. Django is a popular toolkit for building websites in the Python programming language. The application is served to browsers through Apache, a web server, using a module called mod_wsgi, on port 443. Port 443 is the standard door for HTTPS, the encrypted version of the web. Behind the website sits PostgreSQL, a database, and between the two sits pgbouncer, a program whose job is to keep a pool of ready-made database connections so that the website does not have to open a new one for every request. A comparison: pgbouncer is like a taxi rank keeping a few cabs with engines running, instead of calling a new cab for each passenger.

The web GUI (graphical user interface, the pages an administrator clicks through) offers screens for deploying software to endpoints, setting policies and monitoring them. An endpoint here means a managed device such as a laptop.

Since at least version 7.4.0 the product has supported a feature called "Sites", which is a multitenancy feature. Multitenancy means one installation serves several separate customers or departments, each kept apart from the others. The report calls each separate space a vdom, short for virtual domain. A comparison: one large office building with separate locked floors, where each company on a floor can only reach its own floor.

When the feature is enabled, a setting called SITES_ENABLED is set to True in the application configuration. Incoming web requests then carry an extra piece of information called a header. Headers are small labels that travel with every web request and response, alongside the actual content; your browser sends several on every page you visit without you noticing. The header in question is called Site, and it tells the application which tenant the request is for.

Middleware is the part of a Django application that sits between the incoming request and the code that finally handles it. Each middleware is a checkpoint that inspects or modifies the request as it passes through, in a fixed order. A comparison: airport security lanes, where your bag passes through several stations in sequence, and the order of the stations matters.

The site middleware reads the Site header and uses it to set the PostgreSQL search_path to the matching tenant's schema before any query runs. Two more terms: a schema is a named section inside a database, like a folder that groups related tables; search_path is the setting that tells PostgreSQL which folder to look in first when a query names a table without saying where it lives. Setting the search path per request is how each tenant's data stays isolated at the database level.

CVE-2026-21643 is a pre-authentication SQL injection in FortiClient EMS 7.4.4. Pre-authentication means it can be triggered before the server has checked who you are, that is, before any login. The Site header value is pasted into a SET search_path statement without being cleaned, and this happens before any login check.

Setup: how the researchers got to the code

The research was done independently after Fortinet published its advisory and patch. All testing ran against locally deployed lab instances; no production systems were targeted. A lab instance is a copy of the product set up on the researchers' own machines purely for testing, so that no real customer system is touched.

The analysis used FortiClient EMS VMware images for versions 7.4.3, 7.4.4 and 7.4.5. A VMware image is a file that contains a complete pre-installed computer, which can be started inside a virtual machine on an ordinary PC. The workflow was:

  1. Convert the VMDK files to raw disk images with qemu-img, identify the GPT partition layout, and mount the LVM logical volumes to reach the full filesystem of each version. In plain words: a VMDK is the file format of a virtual machine's hard disk. qemu-img is a free tool that converts between disk image formats. A partition layout describes how a disk is divided into sections, and GPT is one common scheme for that division. LVM is a system that groups disk space into flexible volumes, and mounting means attaching a disk or volume to the operating system so its files can be read. The point of all this was to get at the actual files of the product, because the flaw is only visible in the code.
  2. The web GUI is a Django application shipped as Python 3.10 bytecode (.pyc files) under /opt/forticlientems/fcm/fcm/. Bytecode is a half-compiled form of a program: not human-readable source code, but an intermediate form the computer can run. The researchers built pycdc, a tool that turns bytecode back into readable Python source, and batch-decompiled controllers, middlewares, models and URL routing across all three versions. Decompiling is the reverse of compiling: recovering readable code from the compiled form.
  3. Run three-way diffs (7.4.3, 7.4.4, 7.4.5) to separate security-relevant changes from framework noise. A diff is a side-by-side comparison showing exactly which lines were added, removed or changed between two versions of a file. Comparing three versions at once helps tell a meaningful change from ordinary background churn.
  4. Decompile the full middleware stack (SiteMiddleware, AuthMiddleware, BruteForceProtectionMiddleware, ApiLogMiddleware) to map the request chain and confirm ordering. The reason: if the database connection is set up before the login check, then the flaw can be reached without logging in, and only reading the code in order can prove that.
  5. Deploy FortiClient EMS 7.4.4 as a VMware appliance and enable multi-tenant mode through the GUI so that SITES_ENABLED=True. This creates a realistic target on which to try the attack.
  6. Test pre-authentication endpoint candidates for injectability and map operational constraints. An endpoint in this sense is a specific web address that the application answers, such as /api/v1/auth/signin. "Injectability" means whether that address can be made to run injected SQL, and "operational constraints" means the practical limits an attacker would hit, such as lockouts.
  7. Build a proof-of-concept script targeting init_consts for timing-based detection and error-based extraction, plus a multi-endpoint scanner. A proof-of-concept is a small demonstration that proves a flaw is real without being a full attack tool.

Finding it: comparing the versions

The differential analysis showed that 7.4.4 was a significant middleware refactoring release. Refactoring means reorganising code without intending to change what it does, the programming equivalent of rearranging a kitchen. The 7.4.3 middleware directory held six files:

Text
api_logging.pyc
brute_force_protection_middleware.pyc
conditional_csrf.pyc
security_headers_middleware.pyc
site.pyc
subdomain_session.pyc

Line by line: each line is the name of one compiled file in the middleware folder of version 7.4.3. api_logging.pyc handles logging of requests. brute_force_protection_middleware.pyc is the checkpoint that slows down repeated login attempts. conditional_csrf.pyc relates to CSRF, a protection against a website being tricked into submitting forms on your behalf. security_headers_middleware.pyc adds safety-related headers to responses. site.pyc is the tenant routing checkpoint, the one that reads the Site header. subdomain_session.pyc deals with sessions tied to subdomains. The .pyc ending on every name means these are compiled bytecode files, not readable source.

The 7.4.4 directory held ten:

Text
api_log_middleware.pyc                (renamed from api_logging.pyc)
auth_middleware.pyc                   (new)
brute_force_protection_middleware.pyc
conditional_csrf.pyc
ems_common_middleware.pyc             (new)
error_handling_middleware.pyc         (new)
rate_limit_middleware.pyc             (new)
security_headers_middleware.pyc
site_middleware.pyc                   (renamed from site.pyc, +322 bytes)
subdomain_session.pyc

Line by line: api_log_middleware.pyc is the old logging file under a new name. auth_middleware.pyc is new and is the checkpoint that checks who you are. brute_force_protection_middleware.pyc, conditional_csrf.pyc, security_headers_middleware.pyc and subdomain_session.pyc are unchanged. ems_common_middleware.pyc, error_handling_middleware.pyc and rate_limit_middleware.pyc are new checkpoints for shared logic, error handling and limiting how often requests are made. site_middleware.pyc is the old site.pyc renamed, and the note says it grew by 322 bytes, meaning its compiled size increased, which hints that code was added to it.

Five new middleware files were added, two were renamed, and the request pipeline was restructured. In the same release, postgres_conn.py grew from 11,697 bytes to 13,336 bytes (+1,639 bytes). That growth is where the vulnerable format-string interpolation of the Site header into SET search_path was introduced. Format-string interpolation means building a piece of text by dropping values into a template, for example turning the template hello NAME into hello Bob. It is exactly the mechanism that lets a value be mistaken for an instruction. Prior versions supported multitenancy but routed tenants differently at the database layer, and did not contain the interpolation.

The request processing chain in 7.4.4 is:

Text
HTTP Request -> Apache/mod_wsgi -> Django
  -> ApiLogMiddleware        (logs the request)
  -> SiteMiddleware          (reads Site header, sets vdom)
  -> PostgresConnection      (opens DB connection with search_path)
  -> AuthMiddleware          (checks session/credentials)
  -> BruteForceProtection    (rate limits login attempts)
  -> View/Controller

Line by line: an HTTP request is the message your browser sends when it asks a website for something. It arrives at Apache with mod_wsgi, which hands it to Django. ApiLogMiddleware writes a log entry. SiteMiddleware reads the Site header and decides which tenant the request belongs to. PostgresConnection opens the database connection and sets the search path. Only then does AuthMiddleware check the session or credentials, that is, whether you are logged in. BruteForceProtection limits repeated login attempts. Finally the View/Controller is the code that produces the actual answer. A session is how a website remembers you between requests, usually via a small piece of data stored in your browser.

The critical detail is that SiteMiddleware runs before AuthMiddleware. When a request arrives at a pre-authentication endpoint such as /api/v1/auth/signin, the database connection is already established with the attacker-controlled search_path before any credentials are checked. In other words, the tenant is chosen and the database is contacted before anyone asks who you are.

Exploitation: trying it out

Step 1: Fingerprint the target

Fingerprinting means working out what software and version a target is running, and how it is configured, before attacking it. SITES_ENABLED is readable without authentication through GET /api/v1/init_consts, which returns it in the JSON response at data.consts.System.SITES_ENABLED. A few terms: GET is the HTTP method used when a browser simply asks for something, as opposed to submitting a form. An API is a set of web addresses a program (rather than a person clicking) uses to talk to a service; /api/v1/init_consts is one such address, and its name suggests it hands out initial constants, that is, configuration values. JSON is a common text format for structured data, made of names and values in curly braces. Both legitimate clients and attackers can use this to learn whether a target is in multi-tenant mode. If the flag is off, the injection path is not reachable, because the middleware then ignores the header entirely.

Step 2: Confirm injection with a timing payload

A payload is the malicious piece of input an attacker sends. The Site header is lowercased and then embedded in a quoted schema name. A payload that closes the quote, terminates the SET statement and comments out the remainder looks like this:

Text
Header:         Site: x'; SELECT pg_sleep(5)--
After .lower(): x'; select pg_sleep(5)--
db_name:        fcm_x'; select pg_sleep(5)--
Executed:       SET search_path TO 'fcm_x'; SELECT pg_sleep(5)--', public, addons
                                          ^                      ^
                                      breakout              commented out

Line by line: the first line shows the header as sent, with the value x'; SELECT pg_sleep(5)--. The second line shows the same value after the application has converted it to lowercase, which is why SELECT became select; SQL does not care about case. The third line shows the value after the application has glued the prefix fcm_ onto it, producing fcm_x'; select pg_sleep(5)--. The fourth line shows the final database command that results, with the attacker's text sitting inside it. The two carets point at the two key characters: the single quote, which ends the quoted schema name early, and the double dash, which starts a comment. pg_sleep(5) is a PostgreSQL function that simply waits five seconds, which is useful because a delay is easy to measure. A comment in SQL is text the database ignores, so everything after -- is thrown away, including the leftover ', public, addons that would otherwise cause a syntax error.

The single quote closes the schema name string, the semicolon terminates the SET statement, and -- comments out the trailing ', public, addons. Everything between the semicolon and the comment marker executes as a separate statement with the privileges of the EMS database user. A semicolon in SQL separates one statement from the next, which is what allows a second command to be appended. Privileges are the permissions a database account has; the injected command runs with the same permissions as the application's own database account.

Lab testing sent crafted Site headers containing pg_sleep() payloads to each endpoint and compared response times against a benign baseline. The Connection: close header was used on all requests to force fresh pgbouncer connections per request. A baseline is a normal measurement taken with harmless input, so that any difference can be attributed to the payload. Connection: close is a standard header telling the server not to keep the connection open after the response, which forces a new pooled connection next time and makes the timing more predictable.

POST /api/v1/auth/signin (login endpoint):

Text
Baseline:   1.019s  (HTTP 401, Site: default)
Injection: 21.050s  (HTTP 401, Site: x'; SELECT pg_sleep(10)--)
Delta:     20.030s  (~2x requested sleep)

Line by line: POST is the HTTP method used when a browser submits data, which is what a login form does. The baseline request, with the ordinary value default in the Site header, came back in about one second with HTTP status 401. HTTP status codes are three-digit numbers in every response: 200 means fine, 401 means not authorised, 500 means the server hit an internal error. The injection request, with a payload asking the database to sleep ten seconds, took about twenty-one seconds and still returned 401. The difference, the delta, was about twenty seconds, roughly twice the requested sleep.

The roughly 2x delta is consistent with pgbouncer connection pooling executing the SET search_path statement on both connection acquisition and release, so the sleep runs twice. This endpoint has brute force protection: 3 attempts before lockout. Brute force protection means the server refuses further attempts after too many failures in a row, to stop someone guessing passwords; here the limit is three attempts.

GET /api/v1/init_consts (public constants endpoint):

Text
Baseline:   0.077s  (HTTP 200, Site: default)
Injection: 10.074s  (HTTP 500, Site: x'; SELECT pg_sleep(10)--)
Delta:      9.997s  (~1x requested sleep)

Line by line: the baseline came back in a fraction of a second with HTTP 200, meaning success. The injection request took about ten seconds, matching the requested sleep almost exactly, and returned HTTP 500, meaning the server hit an internal error. The delta was about ten seconds, a clean 1x multiplier.

Here the multiplier is a clean 1x, and the injection produces HTTP 500 with PostgreSQL error details in the body. The endpoint has no brute force protection and no authentication requirement, which makes it the more practical vector. A vector is the particular route an attack takes.

Step 3: Extract data through error messages

The HTTP 500 body on init_consts leaks raw PostgreSQL errors:

JSON
{"result": {"retval": -7, "message": "relation \"system_settings\" does not exist\nLINE 4: FROM system_settings\n ^"}}

Line by line: this is a JSON object. result is the outer name, and inside it are two values. retval is -7, an internal return code. message is the interesting part: it is the database's own complaint, passed straight back to the caller. It says that a table called system_settings does not exist, and it even quotes the line of the query where the problem occurred. A relation is PostgreSQL's word for a table. The significance is that the server is telling the outside world about its internal database structure, which is information an attacker should never receive.

Wrapping a query in CAST((<query>)::text AS int) makes PostgreSQL return the query result inside the error message, giving single-request data exfiltration without timing oracles. Two terms: CAST converts a value from one type to another, and here the trick is to ask the database to convert a piece of text into a number, which fails and produces an error that contains the text. Exfiltration means getting data out of a system. A timing oracle is the slower alternative, where you ask yes/no questions and infer the answer from whether the server pauses; it works but takes many requests. The injection context supports stacked queries (full SQL command execution via semicolon separation), error-based extraction confirmed on init_consts, and blind boolean extraction using conditional pg_sleep() as a fallback. Blind boolean extraction means asking questions whose answer is only yes or no, and reading the answer from a delay.

Endpoint characteristics

  • Lockout restrictions. Both /api/v1/auth/signin and /api/v1/init_consts are injectable. signin is subject to BruteForceProtectionMiddleware (default 3 attempts before lockout); init_consts has no such restriction, so an attacker who knows about it can extract data without triggering any lockout.
  • Error-based extraction. init_consts returns PostgreSQL errors in the JSON body, so CAST expressions that force type conversion errors extract arbitrary query results in one HTTP request per value, faster and stealthier than timing-based blind extraction.
  • pgbouncer connection pooling. SET search_path executes at connection acquisition time. Pooled connections cause double execution on signin (2x sleep multiplier) but single execution on init_consts (1x). Long pg_sleep() values can saturate the connection pool, that is, use up all the ready connections, and temporarily make the EMS instance unresponsive.
  • Exploitation depth. Stacked queries, error-based extraction and blind boolean extraction are all available.

Root cause: the actual mistake in the code

In SiteMiddleware, the Site header is read and stored with no validation beyond lowercasing:

Python
# middlewares/site_middleware.py (decompiled from 7.4.4 bytecode)
def _get_header_site(self, request):
    site = request.META.get('HTTP_SITE')
    if site is not None:
        request.META['SITE'] = site.lower()
    return site is not None

def __call__(self, request):
    if not EmsConsts.SITES_ENABLED:
        request.META['SITE'] = EmsConsts.DEFAULT_VDOM
    elif not self._get_header_site(request):
        self._get_subdomain_site(request)

Line by line: the comment says this is the site middleware file, recovered from the compiled bytecode of 7.4.4. def _get_header_site(self, request): defines a helper function that takes the incoming request. site = request.META.get('HTTP_SITE') fetches the Site header from the request; Django stores headers in a dictionary called META, and a header named Site appears there as HTTP_SITE. if site is not None: checks whether the header was present at all. request.META['SITE'] = site.lower() stores the value back, converted to lowercase, and nothing else is done to it. return site is not None reports whether a header was found. The second function, __call__, is what runs for every request. if not EmsConsts.SITES_ENABLED: checks whether multi-tenancy is switched off; if so, request.META['SITE'] = EmsConsts.DEFAULT_VDOM forces the default tenant and the header is never used. elif not self._get_header_site(request): otherwise tries to read the header, and if there is none, self._get_subdomain_site(request) falls back to working the tenant out from the subdomain part of the address.

There is no allowlist check against known vdoms, no character filtering and no regex. An allowlist is a list of permitted values, and checking against it would have rejected anything that was not a real tenant name. A regex is a pattern used to test whether text has an expected shape. The raw, lowercased header value flows into request.META['SITE'] and then into PostgresConnection.__init__():

Python
# models/utils/postgres_conn.py (decompiled from 7.4.4 bytecode)
class PostgresConnection:
    def __init__(self, vdom, ...):
        self.db_name = f"fcm_{vdom}"
        self.searchpath = f"SET search_path TO '{self._db_prefix}{self.db_name}', public, addons"

    def execute(self, query, ...):
        self._connection.execute(self.searchpath)  # Runs before every query

Line by line: the comment says this is the database connection file from 7.4.4. class PostgresConnection: defines a blueprint for objects that hold a database connection. def __init__(self, vdom, ...): is the setup routine that runs when such an object is created, and it receives the tenant name as vdom. self.db_name = f"fcm_{vdom}" builds a database name by putting the prefix fcm_ in front of the tenant name; the f before the quote marks a Python f-string, a template where anything in curly braces is replaced by its value. self.searchpath = f"SET search_path TO '{self._db_prefix}{self.db_name}', public, addons" builds the SQL command as text, wrapping the schema name in single quotes and adding two fixed schemas, public and addons. def execute(self, query, ...): is the routine that runs a query. self._connection.execute(self.searchpath) runs the search path command first, and the comment notes it runs before every query.

The format-string interpolation embeds the unsanitised vdom value directly into a SQL statement that executes on every database query. Because the schema name is wrapped in single quotes, a value containing a quote can break out, terminate the SET statement and inject arbitrary SQL. The existing defences did not stop it: the middleware ordering places the database connection setup before authentication, and the brute force protection only covers the login endpoint, not init_consts.

Impact: what an attacker could do

A successful exploit gives an unauthenticated attacker arbitrary SQL execution against the EMS PostgreSQL database with the privileges of the EMS database user. According to the report this enables:

  • Remote code execution. In the Virtual Machine image Fortinet ships, the PostgreSQL database user runs with superuser privileges, meaning it can do anything in the database, enabling OS command execution via COPY ... TO/FROM PROGRAM. That PostgreSQL command can read or write files and run programs on the underlying operating system, which turns a database problem into control of the machine. Lab testing confirmed arbitrary file creation on the underlying host as the postgres system user.
  • Credential theft. Extraction of admin password hashes, API tokens and JWT secrets from authentication tables. A password hash is a scrambled form of a password that the server stores instead of the real thing; a token is a piece of text that acts like a temporary key, and a JWT is one common format for such tokens. Anyone who obtains these can often log in as an administrator.
  • Endpoint data exfiltration. Access to the full endpoint inventory: hostnames, IP addresses, OS versions, serial numbers and installed software across all managed FortiClient deployments. A hostname is a computer's name on a network.
  • Configuration tampering. Modification of endpoint policies, deployment configurations and security profiles pushed to managed endpoints.
  • Certificate extraction. Access to ZTNA certificates and SAML configuration data, potentially enabling lateral movement into connected Fortinet infrastructure. A certificate is a cryptographic file that proves a server's identity; ZTNA is a way of granting access to applications based on who you are rather than where you are; SAML is a standard for single sign-on between services. Lateral movement means using one compromised system as a stepping stone to reach others.
  • Persistence. Creation of new admin accounts or modification of existing credentials for persistent access to the management console. Persistence means arranging to keep access after the initial break-in.

The pre-authentication nature of the bug and its position in the database connection layer, affecting every subsequent query in the request lifecycle, make it particularly severe for exposed EMS instances. FortiClient EMS manages an organisation's entire endpoint fleet, which makes it a high-value target. The vulnerability requires direct HTTPS access to the EMS web interface, and only multi-tenant deployments are affected; single-site deployments are not.

Fix: what changed in 7.4.5

Version 7.4.5 replaced the format-string interpolation with parameterised identifier handling:

Python
# models/utils/postgres_conn.py (decompiled from 7.4.5 bytecode)
from psycopg.sql import SQL, Identifier

schema = f'{self._db_prefix}{self.db_name}'
self.searchpath = SQL('SET search_path TO {}, public, addons').format(Identifier(schema))

Line by line: the comment says this is the same file from 7.4.5. from psycopg.sql import SQL, Identifier imports two helpers from psycopg, the Python library that talks to PostgreSQL. schema = f'{self._db_prefix}{self.db_name}' still builds the schema name as before. self.searchpath = SQL('SET search_path TO {}, public, addons').format(Identifier(schema)) builds the command from a template with a placeholder, and passes the schema name through Identifier, which tells the library that this value is a name, not SQL code. psycopg.sql.Identifier() double-quotes and escapes the schema name, preventing breakout regardless of the input value. Parameterisation is the general fix for this class of bug: keep the command and the data separate, so the data can never be read as a command. The refactored middleware architecture remained in place. No configuration changes are needed after the upgrade.

Fortinet's version matrix:

Version Affected Solution
FortiClientEMS 8.0 Not affected Not applicable
FortiClientEMS 7.4 7.4.4 only Upgrade to 7.4.5 or above
FortiClientEMS 7.2 Not affected Not applicable

The 7.2 and 8.0 lines were never part of the refactoring cycle: they use either the pre-refactored database routing code (7.2) or a separately maintained codebase (8.0), neither of which contains the format-string SET search_path construction. The vulnerable code existed in production for exactly one release cycle.

If patching is not immediately possible, the report lists three mitigations:

  1. Restrict network access. Limit HTTPS access to the EMS web GUI to authorised management networks only. The vulnerability requires direct HTTPS access to the EMS web interface.
  2. Disable multitenancy. With SITES_ENABLED=False, SiteMiddleware hardcodes the default vdom and never reads the Site header. The vulnerable code remains present but unreachable.
  3. WAF/reverse proxy filtering. Strip or validate the Site header, blocking values containing single quotes, semicolons or SQL keywords. A WAF, web application firewall, is a filter placed in front of a website that inspects requests and blocks suspicious ones; a reverse proxy is a server that sits in front of the real one and forwards requests to it.

Variants to test

  • Other pre-authentication endpoints that touch the database. The report tested seven endpoint candidates and found that init_consts was also injectable. On a similar target, send a pg_sleep() payload in the tenant header to every endpoint reachable without a session and compare response times against a benign baseline. A positive result is a consistent timing delta that scales with the requested sleep.
  • Error-leaking endpoints. Look for pre-auth endpoints that return database errors in the response body. A positive result is a 500 response containing raw PostgreSQL error text, which turns a blind injection into single-request extraction via CAST errors.
  • Header-based tenant routing in other products. Any application that maps a request header to a database schema, search path or connection parameter is a candidate. A positive result is a quote or semicolon in the header value changing the response or producing a database error.
  • Connection-pool multipliers. If a payload sleeps twice as long as requested, the statement is likely running on both acquisition and release of a pooled connection. That tells you the injection point sits in connection setup, which usually means it fires on every query in the request.

Hunting notes

This class of bug tends to hide in code that was recently refactored, especially where a feature that previously worked safely was reimplemented. The report's differential analysis is the model: compare the middleware and database connection layers across adjacent versions, and treat any file that grew in a release as worth decompiling. Renamed files and newly added middleware in a single release are a strong signal that request routing changed.

During recon, short for reconnaissance, the useful signals are pre-auth endpoints that return configuration constants, and any header that selects a tenant, schema or database. A flag such as SITES_ENABLED exposed without authentication tells you both that the feature is on and that the header is likely processed early in the request chain. Endpoints that return database error text in their responses are worth prioritising because they convert blind injection into fast extraction.

To show impact, the report combined a timing proof on two endpoints with an error-based extraction proof on the unauthenticated one, and demonstrated that the database user could create files on the host. That combination, pre-auth access, arbitrary SQL and host-level file creation, is what makes the severity clear.

Glossary

  • API: a set of web addresses that programs use to talk to a service, as opposed to pages a person clicks.
  • Apache: a widely used web server program that receives requests and passes them to the application.
  • Auth Required: whether a flaw can be triggered without logging in; "None" means no login is needed.
  • Baseline: a normal measurement taken with harmless input, used for comparison against a malicious one.
  • Blind boolean extraction: extracting data by asking yes/no questions and reading the answers indirectly, for example from delays.
  • Brute force protection: a defence that blocks or slows repeated failed attempts, such as login guesses.
  • Bytecode: a half-compiled form of a program that is not directly readable by humans.
  • CAST: a database operation that converts a value from one type to another, such as text to a number.
  • Certificate: a cryptographic file that proves the identity of a server or service.
  • Comment (SQL): text in a SQL statement that the database ignores, started with --.
  • Connection pool: a set of ready-made database connections kept open for reuse.
  • Credential: a username and password, or similar proof of identity.
  • CSRF: a class of attack where a website is tricked into submitting a request on a logged-in user's behalf.
  • CVE ID: a public catalogue number assigned to a known security flaw.
  • CVSS: a 0 to 10 severity score for a security flaw, where higher is worse.
  • Decompiling: recovering readable source code from a compiled program.
  • Delta: the difference between two measurements, here between baseline and injection response times.
  • Django: a toolkit for building websites in the Python programming language.
  • Endpoint: a managed device, or (in web terms) a specific address the application answers.
  • Exfiltration: getting data out of a system without permission.
  • f-string: a Python text template where values in curly braces are replaced by their contents.
  • Format-string interpolation: building text by dropping values into a template, which can let a value be mistaken for an instruction.
  • GPT: a scheme for dividing a hard disk into partitions.
  • Header: a small label sent alongside a web request or response, carrying extra information.
  • Hostname: a computer's name on a network.
  • HTTP request: the message a browser or program sends when asking a website for something.
  • HTTP status code: a three-digit number in every response, such as 200 for success, 401 for not authorised, 500 for server error.
  • HTTPS: the encrypted version of the web, normally on port 443.
  • JSON: a common text format for structured data, made of names and values.
  • JWT: a common format for a token that proves who you are.
  • Lateral movement: using one compromised system as a stepping stone to reach others.
  • LVM: a system that groups disk space into flexible volumes.
  • Middleware: a checkpoint in a web application that inspects or modifies each request as it passes through, in a fixed order.
  • mod_wsgi: an Apache module that lets Apache run Python web applications.
  • Mounting: attaching a disk or volume to the operating system so its files can be read.
  • Multitenancy: one installation serving several separate customers or departments, each kept apart.
  • Parameterisation: keeping a database command and its data separate so the data can never be read as a command.
  • Partition layout: how a hard disk is divided into sections.
  • Payload: the malicious piece of input an attacker sends.
  • Persistence: arranging to keep access after an initial break-in.
  • pgbouncer: a program that keeps a pool of ready database connections for a website.
  • pg_sleep: a PostgreSQL function that waits a given number of seconds, used to detect injection through timing.
  • POST: the HTTP method used when submitting data, such as a login form.
  • Pre-authentication: reachable before the server has checked who you are.
  • Privileges: the permissions a database account has.
  • Proof-of-concept: a small demonstration that proves a flaw is real.
  • Recon: reconnaissance, the information-gathering stage before an attack.
  • Refactoring: reorganising code without intending to change what it does.
  • Regex: a pattern used to test whether text has an expected shape.
  • Relation: PostgreSQL's word for a table.
  • Remote code execution: running commands on someone else's machine over the network.
  • Reverse proxy: a server that sits in front of the real one and forwards requests to it.
  • SAML: a standard for single sign-on between services.
  • Schema: a named section inside a database that groups related tables, like a folder.
  • search_path: the PostgreSQL setting that says which schema to look in first.
  • Semicolon (SQL): the character that separates one SQL statement from the next.
  • Session: how a website remembers you between requests, usually via data stored in your browser.
  • SQL: the language used to talk to a database.
  • Stacked queries: sending several SQL statements in one go, separated by semicolons.
  • Superuser: a database account with permission to do anything.
  • Timing oracle: inferring answers from how long a server takes to respond.
  • Token: a piece of text that acts like a temporary key.
  • Vdom: virtual domain, one separate tenant space inside a multitenant installation.
  • Vector: the particular route an attack takes.
  • VMDK: the file format of a virtual machine's hard disk.
  • WAF: web application firewall, a filter in front of a website that blocks suspicious requests.
  • ZTNA: a way of granting access to applications based on who you are rather than where you are.

Similar reports

View all

Same bug class and techniques, clearest first.

SQL injection

The lesson behind this report.

Input reaches a database query as code, letting an attacker read or change data the application never meant to expose.