20  Software & Web Vulnerabilities

20.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Classify Software Vulnerabilities: Categorize OWASP Top IoT vulnerabilities including authentication, access control, and injection flaws
  • Differentiate Attack Mechanisms: Distinguish between local exploits (physical access) and remote exploits (network-based)
  • Mitigate XSS Attacks: Implement input validation, output encoding, and Content Security Policy defenses
  • Eliminate SQL Injection: Construct parameterized queries and input validation to protect IoT databases
  • Architect Defense in Depth: Layer multiple security controls to protect against diverse attack vectors
In 60 Seconds

Software vulnerabilities in IoT firmware and applications — buffer overflows, injection flaws, use-after-free errors, and insecure cryptographic implementations — provide attackers with the foothold needed to compromise devices, exfiltrate data, and pivot to other systems. Unlike hardware vulnerabilities, software vulnerabilities can be fixed through firmware updates, but only if the device has a functioning secure update mechanism.

What are Software Vulnerabilities? Software vulnerabilities are weaknesses in code that attackers can exploit to compromise systems. In IoT, these vulnerabilities exist in device firmware, web interfaces, mobile apps, and backend servers. Common vulnerabilities include SQL injection (manipulating database queries), cross-site scripting (injecting malicious JavaScript), and hardcoded credentials (passwords stored directly in code).

Why does it matter? The 2016 Mirai botnet compromised 600,000+ IoT devices using default passwords and outdated firmware—causing billions in damage by attacking Twitter, Netflix, and other major sites. Insecure software creates entry points for attackers to steal data, take control of devices, or use them for larger attacks.

Key terms: | Term | Definition | |——|————| | SQL Injection | Exploiting database queries by injecting malicious SQL commands allowing unauthorized data access | | Cross-Site Scripting (XSS) | Injecting malicious JavaScript into web pages that executes in victims’ browsers stealing credentials | | Input Validation | Checking and sanitizing user input to ensure it conforms to expected format and content | | OWASP | Open Web Application Security Project—organization publishing security standards and guidelines |

“Guess what?” Sammy the Sensor said with wide eyes. “In 2016, the Mirai botnet took over 600,000 IoT devices just by trying default passwords like ‘admin’ and ‘12345’. That is like leaving your house key under the doormat – everyone knows to look there!”

Max the Microcontroller frowned. “Software vulnerabilities are like hidden holes in a fence. SQL injection is when an attacker types sneaky database commands into a login box instead of a real username. Imagine if you asked someone their name and they said ‘DELETE ALL RECORDS’ – and your system actually did it! That is why we ALWAYS check and clean user input before using it.”

“Cross-site scripting is another tricky one,” Lila the LED added. “That is when someone hides malicious code inside a web page. When another person visits the page, the hidden code runs in their browser and steals their cookies – not chocolate chip cookies, but the little data files that keep you logged in! The attacker can then pretend to be you.”

“The OWASP Top 10 is like a most-wanted list for software bugs,” Bella the Battery explained. “It tells developers the ten most common and dangerous mistakes. The number one lesson? Never trust user input! Always check it, clean it, and limit what it can do. And for goodness sake, change those default passwords the moment you set up a new device!”

20.2 Prerequisites

Before diving into this chapter, you should be familiar with:

  • Security and Privacy Overview: Understanding of the CIA triad, basic security principles, and common attack vectors
  • Networking Basics: Understanding of network protocols and communication layers
  • Basic HTML and JavaScript concepts for understanding XSS attacks
  • Basic SQL knowledge for understanding injection attacks

20.3 Application Vulnerabilities

⏱️ ~20 min | ⭐⭐⭐ Advanced | 📋 P11.C14.U01

Key Concepts

  • Buffer overflow: A vulnerability where a program writes more data to a fixed-size buffer than it can hold, overwriting adjacent memory — potentially allowing an attacker to overwrite the return address and execute arbitrary code.
  • Command injection: A vulnerability where an attacker can include operating system commands in input that is passed to a system shell without sanitisation — particularly dangerous in IoT devices with web management interfaces.
  • Use-after-free: A memory safety vulnerability where a program dereferences a pointer to memory that has already been freed, potentially allowing an attacker to control the contents of the freed memory region.
  • CVE (Common Vulnerabilities and Exposures): A public database of known security vulnerabilities with standardised identifiers, used to track which vulnerabilities affect which IoT firmware versions and coordinate patching.
  • CVSS score: A numerical severity score (0–10) for a CVE, calculated from exploitability, impact, and scope factors — used to prioritise which vulnerabilities require immediate patching.
  • Static analysis: Automated scanning of source code or firmware binaries without execution to identify patterns associated with known vulnerability classes — a cost-effective technique for finding obvious security flaws before deployment.

Application Vulnerability: Any weakness an attacker could exploit to compromise security—design flaws or implementation bugs.

20.3.1 OWASP Top IoT Vulnerabilities

OWASP IoT Top 10 vulnerability categories ranked by risk: weak passwords, insecure network, ecosystem interfaces, updates, components, privacy, transfers, management, defaults, physical
Figure 20.1: OWASP IoT Top 10: Critical Vulnerability Categories and Risk Levels

This view maps vulnerabilities by exploitability (ease of attack) vs. impact severity, helping prioritize remediation efforts:

OWASP IoT vulnerability impact matrix mapping exploitability against severity to prioritize remediation

Remediation Priority Guide:

  • Fix Immediately (Red Zone): I1 Weak Passwords, I9 Insecure Defaults - trivial attacks, critical impact
  • High Priority (Orange Zone): I2 Network, I7 Transfer, I4 Updates - moderate effort, high impact
  • Medium Priority (Yellow Zone): I3 Interfaces, I5 Components - require more skill to exploit
  • Monitor (Gray Zone): I8 Management, I10 Physical - require physical access or specialized attacks

This view shows how attackers chain multiple OWASP vulnerabilities together in real attacks:

Attack chain showing how attackers combine multiple OWASP vulnerabilities from reconnaissance to exploitation

Key insight: Attackers don’t exploit single vulnerabilities in isolation - they chain multiple weaknesses. Mitigating ANY vulnerability in the chain breaks the attack path. Defense-in-depth means blocking at multiple points.

Critical Vulnerabilities:

  1. Username Enumeration: Attackers discover valid usernames through authentication mechanisms
  2. Weak Passwords: Default or easily guessed credentials (admin/admin, root/12345)
  3. Account Lockout: Multiple failed attempts lock accounts (DoS potential)
  4. Lack of Multi-Factor Authentication: Single authentication factor increases risk
  5. Insecure 3rd Party Components: Vulnerable dependencies require constant patching

20.4 Local vs Remote Exploits

20.4.1 Local Application Exploits

Local exploit methods requiring physical device access: JTAG debugging, UART console, and flash memory extraction
Figure 20.2: Local Exploits: Physical Access Attack Methods via JTAG, UART, and Flash Memory

20.4.2 Remote Protocol Exploits

Remote exploit methods via network: man-in-the-middle, eavesdropping, SQL injection, and protocol attacks
Figure 20.3: Remote Exploits: Network-Based Attack Methods Including MITM and SQL Injection

20.5 Web Application Vulnerabilities

20.5.1 Cross-Site Scripting (XSS)

Cross-site scripting attack flow diagram showing attacker injecting malicious JavaScript into a vulnerable web application web form, which is then stored in the database and executed in victim browsers when they view the page, stealing session cookies and credentials
Figure 20.4: Cross-site scripting attack

Attack Mechanism: Inject malicious JavaScript into web applications to execute in victim’s browser.

XSS attack chain: malicious script injection into web form, storage in database, execution in victim browser, session hijacking
Figure 20.5: Cross-Site Scripting Attack Chain: Script Injection to Session Hijacking

This view shows the multiple defense layers needed to prevent XSS attacks at each stage:

Multi-layer XSS defense: input validation, output encoding, Content Security Policy, and HttpOnly cookies

Defense Implementation Checklist:

  • Layer 1: Use validation libraries (OWASP Java Encoder, DOMPurify)
  • Layer 2: Always use parameterized queries, never concatenate user input
  • Layer 3: Add CSP headers: Content-Security-Policy: default-src 'self'
  • Layer 4: Set cookies: Set-Cookie: session=xyz; HttpOnly; Secure; SameSite=Strict

20.5.2 Implementation: XSS Detection and Prevention

XSS protection requires input validation, output encoding, and Content Security Policy implementation. Production systems should use established security libraries and frameworks with built-in XSS protection mechanisms.

20.5.3 SQL Injection (SQLi)

SQL injection attack demonstrating how attacker inputs malicious SQL code like 'admin' OR '1'='1' into login form, which manipulates database query to bypass authentication and return all user records instead of validating credentials
Figure 20.6: SQL injection attack diagram

Attack Mechanism: Inject malicious SQL commands to manipulate database queries.

Side-by-side comparison of vulnerable SQL string concatenation vs secure parameterized query approach
Figure 20.7: SQL Injection: Vulnerable Query vs Secure Parameterized Query Comparison

20.5.4 Implementation: SQL Injection Prevention

SQL injection prevention requires parameterized queries, input validation, and least-privilege database access. Production systems should use ORM frameworks and prepared statements to separate SQL code from user data.

20.5.5 Why SQL Injection Is Especially Dangerous in IoT

IoT systems present a unique SQL injection risk because web dashboards often expose device management endpoints that directly control physical systems. In a traditional web application, SQL injection might leak user data (bad enough). In an IoT building management system, the same vulnerability could allow an attacker to:

  • Modify HVAC setpoints: Inject UPDATE devices SET setpoint=45 WHERE type='HVAC' to overheat an entire building
  • Disable fire alarms: Inject UPDATE sensors SET status='disabled' WHERE type='smoke_detector' to create a life-safety hazard
  • Extract device credentials: Inject SELECT * FROM device_credentials to obtain keys that enable direct device control

Real-world example: In 2021, researchers at Claroty demonstrated SQL injection against a popular building automation system (BAS) web interface, gaining access to the underlying database that stored BACnet device credentials. With those credentials, they controlled HVAC systems, lighting, and door locks across the building – all from a single SQL injection in a web form intended for adjusting temperature schedules. The vendor patched the vulnerability within 90 days, but the disclosure highlighted that IoT web interfaces frequently have weaker security review than enterprise web applications because they are considered “internal tools” rather than public-facing systems.

20.6 Defense in Depth: Seven Security Layers

Common Misconception: “Encryption Alone Makes My IoT System Secure”

The Myth: Many developers believe that adding TLS/HTTPS encryption to their IoT communications automatically solves all security problems.

The Reality: Encryption protects confidentiality (data in transit) but doesn’t address authentication (who is connecting?) or authorization (what can they access?).

Real-World Impact:

  • 2019 Ring Camera Breach: Encrypted communications, but weak passwords allowed attackers to hijack 3,600+ cameras. Encryption didn’t prevent credential stuffing attacks.
  • MQTT Broker Misconfiguration: 47% of publicly exposed MQTT brokers use TLS encryption but have no authentication enabled (Shodan 2022 analysis). Anyone can connect and publish/subscribe to any topic.

The Complete Picture: Defense-in-depth requires 7 layers: 1. Network Security: TLS/DTLS encryption (confidentiality) 2. Authentication: Username/password or certificates (identity) 3. Authorization: Topic/resource-level access control (permissions) 4. Input Validation: Whitelist approach (prevent injection) 5. Secure Coding: Parameterized queries, output encoding (prevent exploitation) 6. Updates: Regular patching (remediate discovered vulnerabilities) 7. Monitoring: Audit logs and anomaly detection (detect breaches)

Seven concentric defense layers: network encryption, authentication, authorization, input validation, secure coding, updates, and monitoring
Figure 20.8: Seven-Layer Defense-in-Depth: From Physical Security to Monitoring

20.7 Worked Example: Vulnerability Assessment of a Smart Building Management System

Scenario: A commercial building management system (BMS) controls HVAC, lighting, and access for a 15-story office tower housing 2,000 workers and 45 tenants. The system includes a web dashboard (port 443), an MQTT broker (port 1883), 850 sensors/actuators, and a REST API for tenant mobile apps. You are conducting a security assessment.

Step 1: Attack Surface Enumeration

Component Interfaces Users Risk Level
Web dashboard HTTPS (port 443) 12 facility managers High (internet-facing)
MQTT broker TCP (port 1883, 8883) 850 devices + 3 integrations Critical (no TLS on 1883)
REST API HTTPS (port 8443) 2,000 tenant app users High (user input)
Device firmware OTA update server 850 devices Medium (internal)
Database PostgreSQL (port 5432) Dashboard + API backends Critical (stores credentials)

Step 2: Vulnerability Testing (OWASP IoT Top 10)

Testing the web dashboard login form with input: admin' OR '1'='1' --

Original query: SELECT * FROM users WHERE username='admin' AND password='...'
Injected query: SELECT * FROM users WHERE username='admin' OR '1'='1' --' AND password='...'
Result: Returns ALL 12 manager accounts (SQL injection confirmed)

Testing the tenant feedback form with: <img src=x onerror=alert(document.cookie)>

Result: JavaScript executes in browser (Stored XSS confirmed)
Impact: Any tenant viewing feedback page leaks session cookies

Step 3: Quantified Risk Assessment

Vulnerability CVSS Score Exploitability Estimated Impact
SQL injection on dashboard 9.8 (Critical) Trivial (automated tools) Full database access: 2,000 tenant records, HVAC override
Stored XSS on feedback 8.1 (High) Easy (single form submission) Session hijack for 12 managers, credential theft
MQTT no authentication on 1883 9.1 (Critical) Trivial (any MQTT client) Subscribe to all topics, publish HVAC commands
Default credentials on 23 sensors 7.5 (High) Easy (Mirai-style scan) Sensor data manipulation, pivot to internal network

Step 4: Attack Chain Demonstration

An attacker chains three vulnerabilities for full building control:

  1. XSS on feedback form steals facility manager session cookie (5 minutes)
  2. Hijacked session accesses dashboard with manager privileges (1 minute)
  3. SQL injection extracts MQTT broker credentials from database (2 minutes)
  4. MQTT access publishes building/hvac/setpoint with value 40C to all floors (1 minute)

Total time from initial access to building-wide HVAC disruption: under 10 minutes. At peak summer occupancy, disabling cooling for a 15-story building affects 2,000 workers and violates OSHA workplace temperature standards within 2-4 hours.

20.7.1 Interactive Attack Timeline Visualization

Step 5: Remediation with Cost Estimates

Fix Implementation Cost Time
Parameterized queries (SQL injection) Replace string concatenation with prepared statements $2,000 (8 dev hours) 1 week
Input sanitization + CSP (XSS) DOMPurify library + Content-Security-Policy header $1,500 (6 dev hours) 1 week
MQTT authentication + TLS Enable username/password + TLS on port 8883, close 1883 $3,000 (12 dev hours) 2 weeks
Credential rotation Unique per-device credentials via provisioning server $8,000 (32 dev hours) 4 weeks
WAF deployment Cloud WAF in front of dashboard and API $500/month 1 day

Total remediation: $15,500 one-time + $6,000/year. Compare to potential cost of a building-wide HVAC attack: $50,000-$200,000 in business disruption, regulatory fines, and tenant lawsuits (based on 2022 Johnson Controls ransomware incident, which cost an estimated $27 million).

20.8 Knowledge Check

Common Vulnerability Scoring System quantifies severity

\[\text{CVSS Base} = \begin{cases} 0 & \text{if } \text{Impact} = 0 \\ \text{Impact} + 1.08 \times \text{Exploitability} & \text{otherwise} \end{cases}\]

Where: \(\text{Exploitability} = 8.22 \times \text{AV} \times \text{AC} \times \text{PR} \times \text{UI}\)

Working through an example:

Given: SQL injection in smart building management web dashboard (unauthenticated, low complexity)

Step 1: Attack Vector (AV) = Network (0.85) Step 2: Attack Complexity (AC) = Low (0.77) Step 3: Privileges Required (PR) = None (0.85) Step 4: User Interaction (UI) = None (0.85)

Step 5: Calculate Exploitability \(\text{Exploitability} = 8.22 \times 0.85 \times 0.77 \times 0.85 \times 0.85 = 3.89\)

Step 6: Impact Sub-Scores Confidentiality: High (0.56), Integrity: High (0.56), Availability: None (0) \(\text{Impact} = 1 - [(1-0.56)(1-0.56)(1-1.0)] = 1 - 0.1936 = 0.8064\)

Step 7: Calculate CVSS Base Score \(\text{CVSS Base} = 0.8064 + 1.08 \times 3.89 = 0.8064 + 4.2012 = 5.01\) Rounded to 5.0, scaled: \(\min(10, 5.0 \times 1.08) = 5.4\)CVSS 5.4 (Medium)

Temporal Adjustment (exploit code available publicly) \(\text{Temporal} = 5.4 \times 1.0 \text{ (exploit maturity)} = 5.4\)

Result: CVSS 5.4 (Medium severity). However, for IoT controlling HVAC/access in 15-story building, contextual risk is CRITICAL due to potential for physical harm and building-wide impact affecting 2,000 occupants.

In practice: CVSS provides standardized vulnerability scoring but doesn’t account for IoT-specific context (physical safety, operational impact). A “Medium” web vulnerability becomes “Critical” when it controls building infrastructure. Always adjust CVSS with environmental metrics.

20.8.1 Interactive CVSS Calculator

20.9 Concept Relationships

How Software Security Concepts Connect
Vulnerability Class Attack Vector Prevention Layer OWASP Category
SQL Injection Unvalidated input → DB query Parameterized queries, input validation A03:2021 Injection
XSS Unvalidated input → browser execution Output encoding, CSP headers A03:2021 Injection
Default Credentials Hardcoded passwords → remote login Unique per-device credentials OWASP IoT I1
Insecure Network Unencrypted protocol → eavesdropping TLS/DTLS, certificate validation OWASP IoT I2
Weak Authentication Single factor → credential stuffing MFA, rate limiting, account lockout A07:2021 Auth Failures

Integration Pattern: Defense-in-depth combines input validation (first line), secure coding (second line), and monitoring (detection). No single layer is sufficient.

20.10 See Also

Related Security Topics:

Vulnerability Databases:

  • OWASP Top 10 Web Application Security Risks
  • OWASP IoT Top 10 (2018)
  • MITRE CWE (Common Weakness Enumeration)

Security Testing Tools:

  • OWASP ZAP (web vulnerability scanner)
  • SQLMap (SQL injection testing)
  • Burp Suite (comprehensive web testing)

Common Pitfalls

IoT firmware frequently includes open-source libraries (OpenSSL, FreeRTOS, lwIP) that have their own CVE histories. Use a software composition analysis (SCA) tool to identify vulnerable library versions and update them before deployment.

Switching to Rust eliminates memory safety vulnerabilities but does not eliminate logic errors, authentication weaknesses, or cryptographic implementation mistakes. Apply multiple layers of vulnerability mitigation regardless of programming language.

A CVSS score of 9.8 on a vulnerability that requires physical access to a device locked in a secure cabinet is less urgent than a CVSS 7.0 vulnerability remotely exploitable over MQTT. Factor in the actual threat model and device deployment context when prioritising patches.

Zero-day vulnerabilities in active exploitation require immediate patching even without complete regression test coverage. Define a fast-track security patch process that accepts controlled risk to eliminate known exploitation.

20.11 Summary

This chapter covered software vulnerabilities and web security fundamentals:

Application Vulnerabilities:

  • OWASP Top 10 IoT vulnerabilities prioritized by risk
  • Local exploits requiring physical access (JTAG, UART, flash extraction)
  • Remote exploits via network (MITM, eavesdropping, injection)

Web Security:

  • XSS (Cross-Site Scripting): JavaScript injection attacking browsers
  • SQL Injection: Database query manipulation through unvalidated input
  • Prevention: Input validation (whitelist), parameterized queries, output encoding

Defense in Depth:

  • Seven security layers from encryption to monitoring
  • No single control is sufficient—combine multiple defenses
  • Encryption protects transit but not authentication or authorization

20.12 What’s Next

If you want to… Read this
Learn about secure OTA updates for delivering patches Secure OTA Updates
Explore protocol-level security to complement software hardening Secure Data IoT Protocols
Study OWASP Top 10 for IoT vulnerabilities OWASP IoT Top 10
Apply STRIDE to identify software threat vectors STRIDE Framework
Return to the security module overview IoT Security Fundamentals