Engineer working on a laptop connected to a device test rig, surrounded by wiring harnesses and test hardware

Firmware vulnerabilities & fixes

How to fix SQL injection, XSS, resource exhaustion and deserialization flaws in embedded firmware

Last updated:

Device web UIs and local management APIs are small web applications, so they inherit classic web weaknesses: SQL injection (CWE-89), cross-site scripting (CWE-79), resource exhaustion (CWE-400) and insecure deserialization (CWE-502). All four MITRE pages read 2026-10-29. Each is a distinct root cause with its own fix, covered in its own section below — detect, fix, verify, ship and disclose steps follow after.

Key takeaways

  • They sit near the top of the weaknesses behind published CVEs, and device standards now ask for input validation by name.
  • A device's local database — often SQLite, backing configuration, logs or a captive-portal user list — is queried with a string built from request input.
  • A status page, log viewer, or any page that echoes a device name, SSID or other user-supplied string back into HTML without encoding is vulnerable.
  • An embedded device has a fixed, usually small, memory and CPU budget, which makes it more vulnerable than a server to a flood of connections, an uncapped log or upload size, or a request that triggers unbounded work.

Why do these four weaknesses matter for device makers?

They sit near the top of the weaknesses behind published CVEs, and device standards now ask for input validation by name. MITRE's 2025 CWE Top 25 ranks cross-site scripting first and SQL injection second:

Weakness 2025 Top 25 rank Score CVEs in CISA KEV
CWE-79 Cross-site scripting 1 60.38 7
CWE-89 SQL injection 2 28.72 4
CWE-502 Deserialization of untrusted data 15 5.23 11
CWE-770 Allocation of resources without limits or throttling (a child of CWE-400) 25 2.54 0

Source: MITRE 2025 CWE Top 25, read 2026-11-10. Deserialization ranks lower but has the most known-exploited entries of the four. See our CWE Top 25 guide for how the ranking is computed.

On the standards side, ETSI EN 303 645 V3.1.3 provision 5.13-1A requires that data input via user interfaces "shall be validated by the device regarding unexpected data input to prevent system manipulations and failures". Provision 5.13-1B applies the same rule to network interfaces, including network-accessible APIs reached without prior authentication. Both are mandatory, and the standard's own example is SQL injection. The EU Cyber Resilience Act, Annex I Part I (2)(h), asks products to protect essential functions "including through resilience and mitigation measures against denial-of-service attacks", and point (2)(j) asks them to limit attack surfaces, including external interfaces. See ETSI EN 303 645 explained and CRA Annex I explained.

What is SQL injection (CWE-89), and how do you fix it?

A device's local database — often SQLite, backing configuration, logs or a captive-portal user list — is queried with a string built from request input. MITRE's CWE-89: the product "constructs all or part of an SQL command using externally-influenced input... but does not neutralize" special characters in it. Fix: switch every query touching request input to prepared statements / parameterized queries, where, per OWASP, "bound values [are treated] as data rather than SQL syntax" — never build SQL by string concatenation, and don't rely on manual escaping as a substitute. For structural elements a parameter can't bind (table or column names, sort order), map the request's choice to a small, fixed, application-owned set of allowed tokens and reject anything else.

The SQLite C API makes the difference concrete. sqlite3_exec() is a convenience wrapper that runs every semicolon-separated statement in the string it receives, so an injected ; DELETE FROM log runs as a second statement. sqlite3_prepare_v2() compiles only the first statement, and request values go in through the sqlite3_bind_*() routines with ?, ?NNN or :name placeholders, so they never reach the SQL parser. For pages that only read, open a second connection with the SQLITE_OPEN_READONLY flag: OWASP lists least privilege as an extra layer, and a read-only handle cannot delete rows even if a query slips through.

What is cross-site scripting (CWE-79), and how do you fix it?

A status page, log viewer, or any page that echoes a device name, SSID or other user-supplied string back into HTML without encoding is vulnerable. MITRE's CWE-79: the product "does not neutralize... user-controllable input before it is placed in output that is used as a web page." Fix: encode every variable for the specific context it's rendered into — HTML entity encoding for text content, attribute encoding for HTML attributes, JavaScript-string encoding plus the surrounding HTML encoding for script contexts, URL encoding for URL parameters — using your web framework's auto-escaping templates rather than hand-written string concatenation. Prefer safe DOM methods (textContent, setAttribute()) over innerHTML in any client-side JavaScript. Set the HttpOnly flag on session cookies as defense in depth, and treat a Content-Security-Policy as an additional layer, not the primary fix.

For HTML text, the OWASP cheat sheet lists five characters to encode: &, <, >, " and '. On a device, remember the values nobody typed into the UI: Wi-Fi scan results, DHCP client host names, Bluetooth device names and syslog lines are all chosen by whoever is nearby on the network, and they end up in admin pages.

What is resource exhaustion (CWE-400), and how do you fix it?

An embedded device has a fixed, usually small, memory and CPU budget, which makes it more vulnerable than a server to a flood of connections, an uncapped log or upload size, or a request that triggers unbounded work. MITRE's CWE-400: the product "does not properly control the allocation and maintenance of a limited resource," typically leading to denial of service, and in some designs to an insecure "fail open" state once a resource limit is hit. Fix: design explicit limits into the architecture — a maximum number of concurrent connections or sessions, a maximum request/upload size, a maximum log or queue size — and rate-limit requests per source rather than leaving any resource uncapped. Just as important: make every resource-allocation failure path fail into a safe state (reject the request, keep existing sessions intact) rather than an undefined one that could itself be a security hole.

The more specific CWE-770 names the usual cause: the product "allocates a reusable resource or group of resources on behalf of an actor without imposing any intended restrictions on the size or number". OWASP's Denial of Service Cheat Sheet adds limits on upload and total request size, a ban on input-based resource allocation, and request-read timeouts against slow HTTP attacks. Regular expressions count too: CWE-1333 covers patterns whose worst-case cost is "inefficient and possibly exponential". A checklist of limits to define:

Limit Where it lives What it prevents
Maximum header and body size HTTP server or request parser One upload filling RAM or a flash partition
Maximum concurrent connections and sessions Server, session table Fixed-size tables overflowing; reject new entries when full
Request-read timeout and minimum data rate Server Slow-HTTP clients holding every worker
Requests per source per minute Handler or packet filter Floods and password guessing
Rows per query (LIMIT) and page size SQL layer One request scanning the whole log
JSON nesting depth and element count Parser configuration Deep recursion and allocation storms
Log and queue size with rotation Logger A full partition stopping configuration writes

What is insecure deserialization (CWE-502), and how do you fix it?

A management API or companion-app protocol that deserializes a structured object (a session token, a configuration blob, an IPC message) from untrusted input is vulnerable if the deserializer will instantiate arbitrary types from that input. MITRE's CWE-502: the product "deserializes untrusted data without sufficiently ensuring that the resulting data will be valid," which can corrupt application state or, through chained method calls, lead to code execution. Fix: per OWASP's top recommendation, avoid native/binary deserialization of untrusted data entirely — use a plain data format (JSON, protobuf with a fixed schema) instead of a language's native object-serialization format. Where a native format can't be avoided, enforce a strict allowlist of the specific types allowed to deserialize, and verify an integrity signature on the serialized blob before deserializing it at all.

Gateways that run Python services meet this directly: the pickle documentation warns "Only unpickle data you trust", because malicious pickle data can run arbitrary code during unpickling. A plain format lowers the risk without removing it; the Deserialization Cheat Sheet notes the application can still make security mistakes after parsing. In C, a custom binary or TLV parser needs the same discipline: check every declared length against the bytes left, cap nesting depth, and reject unknown type tags, or the bug becomes memory corruption.

Worked example: how do you fix a device log-viewer endpoint?

Synthetic example. The device, endpoint and code are invented for this guide and are not taken from any product.

A hypothetical environmental data logger serves /logs?sensor=<name>&sort=<column> on its local web UI and returns an HTML table. The original handler:

/* SYNTHETIC - vulnerable */
char sql[512];
snprintf(sql, sizeof sql,
  "SELECT ts, sensor, msg FROM log WHERE sensor = '%s' ORDER BY %s", sensor, sort);
sqlite3_exec(db, sql, print_row_raw, out, NULL);

Three of the four weaknesses meet here. x' OR '1'='1 returns every row. x'; DELETE FROM log; -- runs a second statement, because sqlite3_exec() runs them all. sort accepts any SQL expression. There is no LIMIT, so one request walks the whole table. And msg stores text the logger received from the network, which print_row_raw writes into HTML unencoded: stored cross-site scripting. The fixed handler:

/* SYNTHETIC - fixed */
static const char *const Q[] = {   /* fixed, application-owned queries */
  "SELECT ts, sensor, msg FROM log WHERE sensor = ?1 ORDER BY ts DESC LIMIT ?2",
  "SELECT ts, sensor, msg FROM log WHERE sensor = ?1 ORDER BY sensor LIMIT ?2",
};

int list_logs(sqlite3 *ro_db, const char *sensor, const char *sort, struct out *o) {
  if (strlen(sensor) > 32) return 400;
  int q = (strcmp(sort, "sensor") == 0) ? 1 : 0;   /* anything else: default order */
  sqlite3_stmt *st;
  if (sqlite3_prepare_v2(ro_db, Q[q], -1, &st, NULL) != SQLITE_OK) return 500;
  sqlite3_bind_text(st, 1, sensor, -1, SQLITE_TRANSIENT);
  sqlite3_bind_int(st, 2, 200);                      /* page size cap */
  while (sqlite3_step(st) == SQLITE_ROW) {
    out_puts(o, "<tr>");
    for (int c = 0; c < 3; c++) {
      out_puts(o, "<td>");
      out_html(o, (const char *)sqlite3_column_text(st, c));  /* & < > " ' encoded, NULL-safe */
      out_puts(o, "</td>");
    }
    out_puts(o, "</tr>");
  }
  sqlite3_finalize(st);
  return 200;
}

What changed, and why:

  • Bound values. ?1 takes the sensor name as data, so quotes and semicolons are just characters in a name that matches nothing.
  • Fixed queries for structure. The sort choice selects one of two complete statements; the request never contributes SQL text.
  • A read-only connection. ro_db was opened with SQLITE_OPEN_READONLY, so even a future mistake cannot delete logs.
  • Bounded work. A 32-character name limit and LIMIT 200 cap the cost of one request; pagination handles the rest.
  • Output encoding at the point of output. The message is stored as received and encoded only when written into HTML.

Test list for this endpoint: x' OR '1'='1 (no rows), x'; DELETE FROM log; -- (no rows, table intact), sort=(SELECT 1) (default order), a 33-character name (400), a logged message containing <img src=x onerror=alert(1)> (shown as text), and 50 parallel requests (each capped, device stays responsive). For the shell side of the same web UI, see how to fix command injection.

How do you detect all four?

  • Map every endpoint in the device's web UI and management API that touches a local database, renders user-supplied text into HTML, accepts a request with no size/rate limit, or deserializes a structured object from the network.
  • Fuzz each one with the matching payload class: SQL metacharacters and boolean/time-based injection probes for database-backed endpoints; HTML/JS injection strings for anything echoed into a page; oversized/burst requests for anything unbounded; crafted serialized blobs for deserialization endpoints.
  • Run static analysis with rule coverage for CWE-89, CWE-79, CWE-400 and CWE-502 across the web UI and API codebase.

How do you verify the fix?

  • Re-test the original proof-of-concept payload against the patched endpoint, plus at least one variant per class (a different injection encoding, a different resource-exhaustion vector, a different deserialization gadget) to confirm the fix isn't narrowly scoped to the exact reported case.
  • For resource-exhaustion fixes specifically, load-test the patched limit under a sustained flood and confirm the device degrades into the intended safe state rather than crashing or exposing an unintended bypass.

What are the common pitfalls?

  • Escaping quotes by hand instead of binding. OWASP's SQL Injection Prevention Cheat Sheet calls manual escaping error-prone and strongly discourages it.
  • Binding values but still string-building ORDER BY or column names. Map those to fixed tokens.
  • Calling sqlite3_exec() with anything derived from a request.
  • Encoding on input instead of on output. Stored data gets double-encoded in one place and missed in a JSON or JavaScript context somewhere else.
  • Trusting network-learned strings (SSIDs, host names, log lines) because no user typed them.
  • Limits enforced only in the browser. The device must enforce every limit itself.
  • A limit that reboots the device when reached instead of rejecting the request.
  • Validation regexes with nested quantifiers, which turn one long input into a CPU lock (CWE-1333).
  • Assuming JSON removes CWE-502. It narrows the problem; type allowlists and parser limits still apply.
  • Fixing the reported page only. The same pattern usually exists in every handler written by the same team.

How do you ship the update and disclose it?

Distribute the fix through your normal signed-firmware update channel, and use your firmware SBOM to confirm which product lines share the affected web UI or API component. Publish the advisory through your coordinated disclosure process (CVD process explained; PSIRT setup for a hardware company if you don't have one yet), and check the Cyber Resilience Act's 24-/72-hour reporting duty for EU-market products if there is evidence of active exploitation (CRA 24h/72h reporting). CISA's Secure by Design Pledge names SQL injection and cross-site scripting explicitly as example classes signatories commit to reducing; see our CISA Secure by Design guide. Use KEV and EPSS signals to decide how fast a published CVE in a shipped component needs a release.

What can SoftWSP check, and what needs code review?

Flaws in your own handlers are found by the review, fuzzing and tests above. SoftWSP covers the third-party components in the image. It extracts a software bill of materials from the firmware as CycloneDX JSON and matches components against NVD, CISA KEV, FIRST EPSS and CISA ICS advisories, so a published SQL injection or XSS CVE in a web server, SQLite build or management library you ship appears with its exploitation signals. An AI-drafted report cites each source, and an engineer reviews it before you receive it. SoftWSP does not trace request input through your code and does not judge reachability. See device & firmware security.

This guide summarises public MITRE CWE and OWASP guidance; it is not a substitute for a full code review and does not constitute legal advice.

Put this guide to work

Frequently asked questions

Why are these four different weaknesses covered in one guide?

SQL injection (CWE-89), cross-site scripting (CWE-79), resource exhaustion (CWE-400) and insecure deserialization (CWE-502) are distinct weaknesses with different root causes, but in embedded device firmware they share the same attack surface — the device's local web management UI and management API — and the same underlying discipline: untrusted input must be handled through a safe, structured mechanism (a parameterized query, a context-aware encoder, a resource limit, a type allowlist) rather than concatenated, rendered or deserialized directly. Each has its own section below with its own MITRE/OWASP citations.

What is SQL injection, and what is the actual fix?

MITRE's CWE-89 defines it as a product that "constructs all or part of an SQL command using externally-influenced input... but does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command." OWASP's SQL Injection Prevention Cheat Sheet is direct about the fix: "define the SQL structure separately from its data values, then bind those values through the database API" — i.e. prepared statements / parameterized queries, where "bound values [are treated] as data rather than SQL syntax." OWASP explicitly warns not to "use manual escaping as a substitute for parameter binding," since escaping rules vary by database configuration and are routinely bypassed.

What is cross-site scripting, and what is the actual fix?

MITRE's CWE-79 defines it as a product that "does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page." A device's web UI (status pages, log viewers, device-name fields echoed back into HTML) is a classic target. OWASP's Cross-Site Scripting Prevention Cheat Sheet's core rule is to encode every variable for the specific output context it lands in — HTML entity encoding, HTML-attribute encoding, JavaScript string encoding, URL encoding — rather than one generic filter, and to prefer safe DOM APIs (`textContent`, `setAttribute()`) over `innerHTML` in any JavaScript-rendered UI.

What is resource exhaustion, and what is the actual fix?

MITRE's CWE-400 (Uncontrolled Resource Consumption) is simply: "the product does not properly control the allocation and maintenance of a limited resource," most often resulting in denial of service, and in some cases a security-relevant "fail open" state when a resource limit is hit. MITRE's architecture-level mitigation is to "design throttling mechanisms into the system architecture... limit the amount of resources that an unauthorized user can cause to be expended," track and rate-limit requests per source, and — critically for embedded devices with fixed memory/CPU budgets — "ensure that all failures in resource allocation place the system into a safe posture" rather than an undefined or insecure one.

What is insecure deserialization, and what is the actual fix?

MITRE's CWE-502 defines it as a product that "deserializes untrusted data without sufficiently ensuring that the resulting data will be valid," which can let an attacker construct an object graph that corrupts application data or, via chained method calls ("gadget chains"), triggers unintended code execution. OWASP's Deserialization Cheat Sheet's top recommendation is to avoid native/binary deserialization formats for untrusted data entirely — "switching to a pure data format like JSON or XML... lessen[s] the chance of custom deserialization logic being repurposed" — and, where a native format can't be avoided, apply a strict type allowlist and verify an integrity signature before deserializing.

Sources

  1. MITRE CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
  2. MITRE CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
  3. MITRE CWE-400: Uncontrolled Resource Consumption
  4. MITRE CWE-502: Deserialization of Untrusted Data
  5. OWASP Cheat Sheet Series: SQL Injection Prevention Cheat Sheet
  6. OWASP Cheat Sheet Series: Cross Site Scripting Prevention Cheat Sheet
  7. OWASP Cheat Sheet Series: Deserialization Cheat Sheet
  8. MITRE: 2025 CWE Top 25 Most Dangerous Software Weaknesses
  9. MITRE CWE-770: Allocation of Resources Without Limits or Throttling
  10. MITRE CWE-1333: Inefficient Regular Expression Complexity
  11. OWASP Cheat Sheet Series: Denial of Service Cheat Sheet
  12. SQLite C API: One-Step Query Execution Interface (sqlite3_exec)
  13. SQLite C API: Compiling An SQL Statement (sqlite3_prepare_v2)
  14. SQLite C API: Binding Values To Prepared Statements
  15. SQLite C API: Opening A New Database Connection (SQLITE_OPEN_READONLY)
  16. Python documentation: pickle — Python object serialization (security warning)
  17. ETSI EN 303 645 V3.1.3 (2024-09): Cyber Security for Consumer Internet of Things: Baseline Requirements
  18. Regulation (EU) 2024/2847 (Cyber Resilience Act), Annex I
Was this guide helpful?

In this cluster

How to fix SQL injection, XSS, resource exhaustion and deserialization flaws in embedded firmware