Plan Penetration Testing: Design security test plans for IoT devices
Perform Vulnerability Scanning: Use automated tools to find common vulnerabilities
Test Wireless Security: Validate BLE, Wi-Fi, and LoRa security implementations
Evaluate Security Certifications: Navigate PSA Certified, FIPS, and regulatory requirements
In 60 Seconds
Security testing for IoT devices validates that devices resist unauthorized access, protect data in transit and at rest, and cannot be exploited to attack other systems. IoT security testing spans: firmware binary analysis (extracting hardcoded credentials, identifying crypto implementation), protocol fuzzing (sending malformed packets to find crash bugs), authentication bypass testing (attempting default credentials, null authentication), and physical attack testing (JTAG extraction, side-channel analysis). Regulatory requirements (IEC 62443, ETSI EN 303 645) increasingly mandate security testing.
6.2 For Beginners: Security Testing for IoT Devices
Security testing for IoT verifies that your device is resistant to attacks. Think of hiring a professional lockpicker to test your building’s security – better to find the weaknesses yourself than have a real burglar find them. Security testers try to hack your device the same way an attacker would, revealing vulnerabilities before deployment.
6.3 Prerequisites
Before diving into this chapter, you should be familiar with:
In one sentence: Security testing validates that your device resists real-world attacks, not just theoretical threats.
Remember this rule: If you haven’t tested for it, hackers will. Security bugs are the most expensive to fix after deployment.
MVU: The Security Testing Cost Multiplier
Core Concept: Security vulnerabilities discovered in production cost 30-100x more to fix than those caught during development. A buffer overflow found during code review takes 1 hour to patch; the same bug discovered after a breach requires firmware recall, customer notification, regulatory reporting, and reputation repair.
Why It Matters: IoT devices face unique challenges: 10-20 year deployment lifecycles, physical accessibility enabling hardware attacks, resource constraints limiting security controls, and massive fleet sizes multiplying attack surfaces. The Mirai botnet compromised 600,000 devices through default credentials - a vulnerability that costs $0 to prevent but billions to remediate at scale.
Key Takeaway: Security testing is not optional or “nice to have” - it’s the cheapest insurance against catastrophic failure. Budget 15-20% of development time for security testing. Every dollar spent on penetration testing saves $30-100 in breach response costs.
For Kids: Meet the Sensor Squad!
Security Testing is like having a friendly spy team check if your secret clubhouse is REALLY secret!
6.3.1 The Sensor Squad Adventure: The Great Clubhouse Security Check
The Sensor Squad had built the most amazing high-tech clubhouse ever! It had a password-protected door, a secret handshake scanner, and even a laser grid (okay, it was just red yarn, but it looked cool). They were SO proud of their security.
But then Sammy the Temperature Sensor had a thought: “How do we KNOW our security actually works? We built it ourselves, so of course WE can get in. But could a sneaky spy get in too?”
Max the Microcontroller suggested something brilliant: “What if we ask our friend Riley to TRY to break in? Riley doesn’t know any of our secrets, so they’ll try things we never thought of!”
They invited Riley over for “The Great Security Challenge.” Riley discovered some surprising things:
The “Secret” Password: Riley noticed that when Sammy typed the password, everyone could see it on the screen. “That’s like shouting your secret out loud!” Riley said.
The Back Window: The Squad had focused so much on the front door that they forgot about the window! Riley just climbed right in.
The Emergency Override: There was a big red button that opened the door “for emergencies” - but anyone could press it!
“Wow!” said Lux the Light Sensor. “We thought we were safe, but we never tested it like a real intruder would!”
Riley helped them fix everything:
The password screen now shows asterisks (****) instead of letters
The window got a sensor alarm
The emergency button now needs a special key
“This is called penetration testing,” explained Max. “You pretend to be a bad guy to find problems BEFORE real bad guys do!”
6.3.2 Key Words for Kids:
Penetration Testing: Having someone try to break in (nicely!) to find weak spots
Vulnerability: A weak spot that could let bad guys in
Security Audit: Checking all your defenses to make sure they work
Attack Surface: All the different ways someone might try to get in
Remember: The best security experts think like sneaky spies - they imagine all the tricky ways someone might try to break in, then fix those problems before anyone actually tries!
6.4 Introduction
Security testing is the practice of systematically evaluating IoT devices for vulnerabilities before attackers find them. Unlike functional testing that verifies features work correctly, security testing asks: “How could this device be compromised?”
Real-world IoT security failures demonstrate the critical importance of security testing:
Incident
Impact
Root Cause
Mirai botnet
600,000 compromised devices, major DDoS attacks
Default credentials, no authentication
Ring camera hacks
Strangers talking to children through cameras
Credential stuffing, weak passwords
Jeep Cherokee hack
Remote control of vehicle steering/brakes
Unprotected CAN bus access
St. Jude pacemakers
FDA recall for security vulnerabilities
Hardcoded credentials, no encryption
The stakes are high because IoT devices present unique security challenges:
Long deployment cycles: Devices operate for 10-20 years, outliving the companies that made them
Physical accessibility: Unlike servers in locked data centers, IoT devices can be physically accessed
Resource constraints: Limited CPU, memory, and power restrict security controls
Scale: A vulnerability in one device design affects millions of deployed units
This chapter covers practical security testing techniques: penetration testing methodology, vulnerability scanning, wireless protocol security, and navigating the certification landscape. You will learn to think like an attacker while building defenses like an engineer.
6.5 Security Testing Cost Calculator
Interactive Calculator: Estimate the cost impact of finding security vulnerabilities at different development phases.
Show code
viewof baseCost = Inputs.range([1000,50000], {value:5000,step:1000,label:"Base Engineering Cost ($)",description:"Cost to fix the vulnerability in the design phase"})viewof phase = Inputs.select(["Design","Prototyping","Pre-production","Post-launch"], {value:"Design",label:"Discovery Phase",description:"When is the vulnerability discovered?"})viewof deployedUnits = Inputs.range([0,50000], {value:10000,step:1000,label:"Deployed Units",description:"Number of devices already deployed (post-launch only)"})// Phase multipliers and scale impactsphaseMultiplier = ({"Design":1,"Prototyping":4,"Pre-production":15,"Post-launch":80})scaleImpact = ({"Design":0,"Prototyping":0,"Pre-production":80000,"Post-launch": deployedUnits *200})totalCost = baseCost * phaseMultiplier[phase] + scaleImpact[phase]costMultiplier = totalCost / baseCosthtml`<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #2C3E50;"> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;"> <div style="background: white; padding: 15px; border-radius: 6px; border: 1px solid #e0e0e0;"> <div style="font-size: 0.9em; color: #7F8C8D; margin-bottom: 5px;">Base Engineering Cost</div> <div style="font-size: 1.8em; font-weight: bold; color: #2C3E50;">$${baseCost.toLocaleString()}</div> </div> <div style="background: white; padding: 15px; border-radius: 6px; border: 1px solid #e0e0e0;"> <div style="font-size: 0.9em; color: #7F8C8D; margin-bottom: 5px;">Phase Multiplier</div> <div style="font-size: 1.8em; font-weight: bold; color: #E67E22;">${phaseMultiplier[phase]}×</div> </div> </div> <div style="background: white; padding: 20px; border-radius: 6px; border: 1px solid #e0e0e0;"> <div style="font-size: 0.9em; color: #7F8C8D; margin-bottom: 5px;">Total Fix Cost in ${phase} Phase</div> <div style="font-size: 2.2em; font-weight: bold; color: ${phase ==="Design"?"#16A085": phase ==="Prototyping"?"#3498DB": phase ==="Pre-production"?"#E67E22":"#E74C3C"};">$${totalCost.toLocaleString()}</div> <div style="margin-top: 10px; font-size: 0.95em; color: #7F8C8D;">${costMultiplier >1?`That's ${costMultiplier.toFixed(0)}× more expensive than fixing during design`:"Most cost-effective time to fix"} </div> </div>${phase ==="Post-launch"?html`<div style="margin-top: 15px; padding: 15px; background: #fff3cd; border-radius: 6px; border-left: 4px solid #E67E22;"> <strong>Additional Post-Launch Costs:</strong> <ul style="margin: 10px 0 0 0; padding-left: 20px;"> <li>Recall logistics and customer notification</li> <li>Regulatory fines and legal fees</li> <li>Reputation damage and lost future sales</li> <li>PR and crisis management</li> </ul> </div>`:""}</div>`
Key Insight: Security vulnerabilities discovered in production cost 30-100× more to fix than those caught during development. This calculator demonstrates why “shift-left security testing” is one of the highest-ROI practices in IoT development.
6.6 Penetration Testing
6.6.1 IoT Attack Surface
IoT devices present multiple attack surfaces that security testers must evaluate systematically. Unlike traditional IT systems, IoT devices are physically accessible, use wireless protocols, and connect to cloud services - creating a complex threat landscape.
IoT device attack surface: Four primary attack vectors that security testers must evaluate
Figure 6.1: IoT device attack surface: Four primary attack vectors that security testers must evaluate
6.6.2 Penetration Test Methodology
Follow a structured approach to security testing:
IoT Penetration Testing Methodology: Six-phase systematic approach to security assessment
# BLE security test scriptfrom bluepy.btle import Scanner, Peripheraldef test_ble_security(device_mac):"""Test BLE device security posture."""# 1. Check if device is discoverable scanner = Scanner() devices = scanner.scan(10.0) discoverable =any(d.addr == device_mac for d in devices)print(f"Device discoverable: {discoverable}")# 2. Check for pairing requirementstry: p = Peripheral(device_mac)# If we get here without pairing, device accepts unauthenticated connectionsprint("WARNING: Device accepts unauthenticated connections!")# 3. Enumerate services without auth services = p.getServices()for svc in services:print(f"Service: {svc.uuid}")for char in svc.getCharacteristics():print(f" Characteristic: {char.uuid}, Properties: {char.propertiesToString()}")# Check if sensitive chars are readable without authif char.supportsRead():try: value = char.read()print(f" Value (unauth): {value.hex()}")except:print(f" Read protected (good)")exceptExceptionas e:if"authentication"instr(e).lower():print("Device requires authentication (good)")else:print(f"Connection error: {e}")
Wi-Fi Security Testing:
Test
Tool
Pass Criteria
Encryption strength
aircrack-ng
WPA2/WPA3 only, no WEP/WPA
Default SSID
Manual
No identifiable device info in SSID
Hidden SSID
airodump-ng
SSID hidden (if security requirement)
AP mode security
Manual
Provisioning AP uses WPA2 minimum
Credential storage
Firmware analysis
Wi-Fi creds encrypted in flash
6.7 Vulnerability Scanning
6.7.1 Automated Scanning Tools
Tool
Purpose
Target
Binwalk
Extract firmware contents
Firmware binaries
Firmwalker
Scan for hardcoded secrets
Extracted filesystems
OWASP ZAP
Web API vulnerability scanning
Cloud APIs
Nmap
Network service discovery
Open ports on device
6.7.2 Firmware Analysis
# Extract firmware from binary$ binwalk -e device_firmware.bin# Scan extracted filesystem for secrets$ firmwalker firmware/_device_firmware.bin.extracted/[!] Hardcoded Wi-Fi password found: config/wifi.conf[!] Hardcoded API key found: app/cloud_client.py[!] Private RSA key found: etc/ssl/device.key# Scan for known CVEs in included libraries$ grep -r"OpenSSL" firmware/_device_firmware.bin.extracted/OpenSSL 1.0.1e 11 Feb 2013# Check CVE databaseCVE-2014-0160(Heartbleed)affects OpenSSL 1.0.1e→ Device vulnerable to Heartbleed attack!
6.7.3 Common IoT Vulnerabilities
Vulnerability
Detection Method
Fix
Default credentials
Firmware analysis
Force password change on first boot
Hardcoded secrets
String analysis
Use secure key storage, provisioning
Unencrypted protocols
Network capture
Enforce TLS 1.2+ everywhere
Insecure update
OTA interception
Sign firmware, verify chain of trust
Debug interfaces
Physical inspection
Disable UART/JTAG in production
Weak crypto
Crypto audit
Use modern algorithms (AES-256, ECDSA)
6.7.4 Vulnerability Risk Score Calculator
Interactive Calculator: Calculate the CVSS-style risk score for discovered vulnerabilities to prioritize remediation efforts.
Show code
viewof attackVector = Inputs.select(["Network","Adjacent","Local","Physical"], {value:"Network",label:"Attack Vector",description:"How can the vulnerability be exploited?"})viewof attackComplexity = Inputs.select(["Low","High"], {value:"Low",label:"Attack Complexity",description:"How difficult is it to exploit?"})viewof privilegesRequired = Inputs.select(["None","Low","High"], {value:"None",label:"Privileges Required",description:"What access level is needed?"})viewof userInteraction = Inputs.select(["None","Required"], {value:"None",label:"User Interaction",description:"Does exploitation require user action?"})viewof impactScope = Inputs.select(["Critical","High","Medium","Low"], {value:"High",label:"Impact Scope",description:"What is affected if exploited?"})// Scoring logic (simplified CVSS-like)attackVectorScore = ({"Network":3.0,"Adjacent":2.0,"Local":1.5,"Physical":1.0})complexityScore = ({"Low":2.0,"High":1.0})privilegesScore = ({"None":2.0,"Low":1.5,"High":1.0})interactionScore = ({"None":2.0,"Required":1.0})impactScore = ({"Critical":4.0,"High":3.0,"Medium":2.0,"Low":1.0})baseScore =Math.min(10, (attackVectorScore[attackVector] + complexityScore[attackComplexity] + privilegesScore[privilegesRequired] + interactionScore[userInteraction] + impactScore[impactScope]) /1.4)severity = baseScore >=9.0?"Critical": baseScore >=7.0?"High": baseScore >=4.0?"Medium":"Low"severityColor = baseScore >=9.0?"#E74C3C": baseScore >=7.0?"#E67E22": baseScore >=4.0?"#3498DB":"#16A085"html`<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid ${severityColor};"> <div style="background: white; padding: 20px; border-radius: 6px; border: 1px solid #e0e0e0; margin-bottom: 20px;"> <div style="display: flex; justify-content: space-between; align-items: center;"> <div> <div style="font-size: 0.9em; color: #7F8C8D; margin-bottom: 5px;">Risk Score</div> <div style="font-size: 3em; font-weight: bold; color: ${severityColor};">${baseScore.toFixed(1)}</div> </div> <div style="text-align: right;"> <div style="font-size: 0.9em; color: #7F8C8D; margin-bottom: 5px;">Severity</div> <div style="font-size: 1.8em; font-weight: bold; color: ${severityColor};">${severity}</div> </div> </div> </div> <div style="background: white; padding: 15px; border-radius: 6px; border: 1px solid #e0e0e0;"> <div style="font-weight: bold; color: #2C3E50; margin-bottom: 10px;">Recommended Action:</div> <div style="color: #34495e; line-height: 1.6;">${baseScore >=9.0?"⚠️ <strong>Critical:</strong> Fix immediately. Do not ship product until resolved. Requires emergency patch if already deployed.": baseScore >=7.0?"🔴 <strong>High:</strong> Fix before release. Schedule hotfix if in production. Allocate dedicated resources.": baseScore >=4.0?"🟡 <strong>Medium:</strong> Fix in next release cycle. Monitor for exploitation attempts. Include in regular security updates.":"🟢 <strong>Low:</strong> Fix when convenient. Document in known issues. Consider including in next major version."} </div> </div> <div style="margin-top: 15px; padding: 15px; background: #e8f4f8; border-radius: 6px;"> <div style="font-size: 0.85em; color: #2C3E50;"> <strong>Score Breakdown:</strong><br> Attack Vector (${attackVector}): ${attackVectorScore[attackVector].toFixed(1)} • Complexity (${attackComplexity}): ${complexityScore[attackComplexity].toFixed(1)} • Privileges (${privilegesRequired}): ${privilegesScore[privilegesRequired].toFixed(1)} • Interaction (${userInteraction}): ${interactionScore[userInteraction].toFixed(1)} • Impact (${impactScope}): ${impactScore[impactScope].toFixed(1)} </div> </div></div>`
Example Scenarios:
UART debug port (Physical, Low complexity, None privileges, None interaction, High impact) ≈ 6.4 (High)
Hardcoded API key (Local, Low complexity, High privileges, None interaction, Medium impact) ≈ 4.6 (Medium)
6.8 Automated Security Testing in CI/CD
Security testing must be integrated into the development lifecycle, not performed as a one-time event before release. The following diagram shows how security testing activities map to development phases:
Security Testing Throughout the Development Lifecycle: Continuous security validation from design to production
Figure 6.3: Security Testing Throughout the Development Lifecycle: Continuous security validation from design to production
6.8.1 Security Test Pipeline
# .github/workflows/security-tests.ymlname: Security Test Suiteon:pull_request:branches:[main, release/*]jobs:static-analysis:runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Static security scan run: ./scripts/security-scan.sh - name: SAST with Semgrep uses: returntocorp/semgrep-action@v1 with: config: >- p/security-audit p/secrets p/owasp-top-ten dynamic-ble-tests: runs-on: [self-hosted, device-farm]needs: static-analysissteps:-uses: actions/checkout@v3-name: Flash test firmwarerun: esptool.py write_flash 0x10000 build/firmware.bin-name: Run BLE security testsrun: pytest tests/security/test_ble_security.py -v --timeout=300dynamic-tls-tests:runs-on:[self-hosted, device-farm]needs: static-analysissteps:-name: Run TLS security testsrun: pytest tests/security/test_tls_security.py -v --timeout=300security-gate:runs-on: ubuntu-latestneeds:[static-analysis, dynamic-ble-tests, dynamic-tls-tests]steps:-name: Security gate decision run: | echo "All security tests passed - PR approved for merge"
6.8.2 Security Test Examples
# tests/security/test_tls_security.pyimport pytestimport sslimport socketDEVICE_IP ="192.168.1.100"def test_tls_version():"""Device must reject TLS 1.1 and below.""" context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1)try:with socket.create_connection((DEVICE_IP, 443)) as sock:with context.wrap_socket(sock, server_hostname=DEVICE_IP) as ssock: pytest.fail("SECURITY FAILURE: Device accepted TLS 1.1")except ssl.SSLError:pass# Expected - TLS 1.1 should be rejecteddef test_firmware_update_requires_signature():"""Verify device rejects unsigned firmware."""# Create unsigned firmware image unsigned_fw = create_test_firmware(signed=False)# Attempt OTA update result = attempt_ota_update(DEVICE_IP, unsigned_fw)assert result['status'] =='rejected', \"SECURITY FAILURE: Device accepted unsigned firmware"assert'signature'in result['reason'].lower(), \"Device rejected for wrong reason"
6.9 Security Certifications
6.9.1 Common IoT Security Certifications
Certification
Level
Scope
Cost/Time
PSA Certified
Level 1-3
ARM-based IoT devices
$5K-$50K, 3-6 months
SESIP
Level 1-3
Secure elements, TEE
$10K-$100K, 6-12 months
FIPS 140-2
Level 1-4
Cryptographic modules
$50K-$500K, 12-24 months
Common Criteria (EAL)
EAL1-EAL7
High-security gov/mil
$100K-$1M+, 12-36 months
6.9.2 Certification Selection Decision Tree
Security Certification Selection: Choose the right certification based on device type and regulatory requirements
Figure 6.4: Security Certification Selection: Choose the right certification based on device type and regulatory requirements
6.9.3 When to Certify
Device Type
Recommended Certification
Consumer IoT
PSA Certified Level 1 (baseline security)
Healthcare/Finance
FIPS 140-2 Level 2 (regulated industries)
Government/Military
Common Criteria EAL4+ (high assurance)
6.9.4 PSA Certified Level 1 Requirements
Secure boot: Device only runs signed firmware
Secure storage: Encryption keys stored in secure element
Secure communication: TLS 1.2+ with certificate validation
Secure update: Firmware updates must be signed and authenticated
Vulnerability disclosure: Process for handling reported vulnerabilities
6.10 Multi-Region Regulatory Compliance
Worked Example: Multi-Region Regulatory Compliance Planning
Scenario: A medical device startup has developed a continuous glucose monitor (CGM) with BLE connectivity. After FDA 510(k) clearance in the US, they want to expand to Europe (CE/MDR), Canada (Health Canada), and Japan (PMDA) within 18 months.
Requirements by Region:
Requirement
USA (baseline)
EU (CE/MDR)
Canada
Japan
Device classification
Class II (510k)
Class IIb (MDR)
Class III
Class II
Clinical data
Predicate + bench
Clinical study likely
Accept FDA data
Clinical in Japan
Quality system
FDA 21 CFR 820
ISO 13485 + MDR
ISO 13485 (MDSAP)
ISO 13485 + JPAL
Typical timeline
(complete)
12-18 months
6-10 months
12-18 months
Typical cost
(complete)
$150K-$250K
$40K-$80K
$100K-$180K
Optimal Strategy: EU first (hardest, most stringent), then Canada (accepts EU data), then Japan (requires local clinical but can use EU data as basis).
Key Insight: The EU MDR has the most stringent clinical evidence requirements. Satisfying MDR creates documentation that simplifies submissions to other regions.
Worked Example: Security Penetration Test Uncovers Critical Firmware Extraction Vulnerability
Scenario: Your team built a smart door lock for residential use. Before production, you hire a third-party security firm for penetration testing. The pentest report reveals a critical vulnerability: attackers with 30 seconds of physical access can extract firmware containing the master encryption key, enabling them to clone the lock.
Given:
Product: Wi-Fi smart lock with PIN code + mobile app control
Encryption: AES-256 for cloud communication
Authentication: TLS with device certificates
Cost: $120 retail, $45 manufacturing cost
Timeline: 6 weeks until production (10,000 units)
Pentest finding: JTAG debug port active, firmware unencrypted
Penetration Test Report (Summary):
CRITICAL: CVE-2024-XXXXX - Unrestricted Firmware Extraction
Severity: 9.8/10 (Critical)
Attack Vector: Physical (requires brief device access)
Complexity: Low (standard tools)
Vulnerability Details:
1. JTAG debug interface left active in production firmware
2. Firmware stored unencrypted in external SPI flash
3. Master AES encryption key hardcoded in firmware binary
4. Device certificate private key extractable from flash dump
Proof of Concept:
$ openocd -f interface/ftdi/um232h.cfg -f target/esp32.cfg
> halt
> dump_image firmware_dump.bin 0x0 0x400000
$ binwalk -e firmware_dump.bin
$ strings _firmware_dump.bin.extracted/10000 | grep -i "aes_key"
AES_MASTER_KEY=F3A7B9C1D2E4F6... # Found hardcoded key
Impact:
- Attacker with 30 seconds of physical access extracts firmware
- Master key enables decryption of ALL cloud traffic
- Device certificate extraction enables impersonation
- Single compromised device compromises entire fleet
- Attack is undetectable (no logs, device appears normal)
Affected Component: ESP32 firmware v1.2.4
Likelihood: High (physical access common for door locks)
Business Impact: Full compromise of product security model
Immediate Response (Week 1):
Emergency Security Review:
├─ Halt production (10,000 unit order on hold)
├─ Convene security incident team
├─ Assess fix complexity and timeline
└─ Calculate impact of delayed launch
100% of test units pass extraction protection tests
Third-party retest
✅ Pass
Pentest firm confirms vulnerability patched
Production units (10,000)
✅ Ready
All units provisioned with unique credentials
Cost Impact:
Item
Cost
Firmware redesign
$40K (2 senior engineers × 3 weeks)
Manufacturing process
$15K (tooling + process validation)
Security retesting
$10K (third-party pentest firm)
Production delay
$120K (6 weeks of lost revenue)
Total
$185K
Cost Avoidance (if launched vulnerable): - Recall of 10,000 units: $1.2M ($120 retail × 10K units) - Reputation damage: $2-5M (brand value loss, future sales impact) - Regulatory fines (FTC, GDPR): $100K-$1M - Total avoided cost: $3.5-$7.2M
ROI: $185K investment avoided $3.5-7.2M in losses (19-39× return)
Key Insight: The penetration test discovered four compounding vulnerabilities: JTAG enabled (physical access) + unencrypted firmware (no confidentiality) + hardcoded master key (compromises entire fleet) + extractable certificates (enables impersonation). Fixing the vulnerability required both firmware changes (disabling JTAG, enabling encryption) and manufacturing process changes (per-device unique keys). The $185K fix cost was 5-40× cheaper than launching a vulnerable product.
Decision Framework: Prioritizing Security Testing Investment Based on Product Risk
Use this framework to determine which security testing activities are critical vs. optional for your IoT product.
Full security audit ($50K+), certification, red team engagement
Security Testing Decision Matrix:
START: What is your product's risk profile?
Does the device control physical access (locks, doors)?
├─ YES: MANDATORY penetration test + hardware security audit
└─ NO: Continue
Does the device capture sensitive data (video, audio, health)?
├─ YES: MANDATORY penetration test + privacy impact assessment
└─ NO: Continue
Is the device safety-critical (medical, automotive, industrial)?
├─ YES: MANDATORY comprehensive security assessment + certification
└─ NO: Continue
Does the device cost >$200 or is it business/commercial use?
├─ YES: RECOMMENDED penetration test ($10-20K)
└─ NO: MINIMUM automated vulnerability scanning + firmware analysis
Is it a consumer device <$50 with no sensitive data?
├─ YES: MINIMUM automated scanning, consider basic pentest if budget allows
└─ NO: Re-evaluate the above criteria
API security testing, authentication/authorization bypass
Burp Suite, OWASP ZAP, custom scripts
$5-10K
Mobile apps
App security audit, reverse engineering, API abuse
MobSF, Frida, jadx, Burp
$5-10K
Firmware
Static analysis, hardcoded secrets, crypto review
Binwalk, Ghidra, Firmwalker
$8-15K
Web interfaces
OWASP Top 10 testing, XSS, CSRF, injection
Burp Suite, OWASP ZAP
$3-8K
Security Certification Decision:
Certification
When Required
Cost
Duration
PSA Certified Level 1
Consumer IoT seeking security differentiation
$5-15K
2-4 months
PSA Certified Level 2
Consumer IoT with sensitive data or control functions
$15-50K
4-6 months
IEC 62443
Industrial IoT, critical infrastructure
$50-200K
6-12 months
FIPS 140-2
Government, healthcare, financial services
$50-500K
12-24 months
Common Criteria EAL
High-assurance government/military
$100K-$1M+
12-36 months
Key Insight: Security testing investment should match product risk, not product budget. A $40 smart lock (physical access control) requires more security testing than a $200 weather station (non-critical monitoring). Prioritize penetration testing for devices with physical access control, sensitive data capture, or safety criticality.
Common Mistake: Performing Security Testing Too Late in Development Cycle
The Mistake: Building the entire product (hardware designed, firmware 90% complete, 5,000 units ordered from factory), then scheduling a security pentest “before launch.” The pentest discovers a critical flaw requiring a hardware redesign. The team faces a choice: launch vulnerable or delay 6 months and write off $200K in inventory.
Why It Happens:
“Security testing is expensive, we’ll do it at the end” mindset
Treating security as a checkbox before launch, not a design constraint
Underestimating the impact of late-stage security findings
No security expertise in-house during design phase
Real-World Impact:
Timeline of Late Security Testing:
Month 0-9: Product Development
├─ Hardware design (PCBs, enclosures)
├─ Firmware development (no security review)
├─ Mobile app development
├─ Place manufacturing order: 5,000 units
└─ Total investment: $350K
Month 10: "Let's do security testing before launch"
└─ Hire penetration testing firm ($15K)
Month 11: Penetration Test Report
├─ CRITICAL: Hardware has no secure element
├─ CRITICAL: Firmware encryption keys extractable
├─ HIGH: Mobile app uses unencrypted API keys
└─ Impact: Requires hardware redesign (secure element)
Month 11: Crisis Decision
├─ Option A: Launch with vulnerabilities
│ └─ Risk: Recall, regulatory fines, reputation damage
├─ Option B: Redesign hardware + firmware
│ └─ Cost: $200K (inventory write-off) + $100K (redesign) + 6 months delay
└─ Chosen: Option B (delayed launch)
Total Cost: $350K (sunk) + $300K (fix) = $650K + 6-month delay
Security fix costs grow exponentially through the development lifecycle. The cost multiplier captures design freeze, inventory commitment, and deployment scale.
The pre-production multiplier includes PCB redesign ($30K), factory retooling ($40K), and scrapped inventory. Post-launch adds recall logistics for all deployed units — a 480× cost increase from design-phase integration.
Example: Secure Element Integration Cost:
Phase
Cost
Notes
Design phase
$5K
Add $0.50 secure element chip, update PCB design
Prototyping
$25K
Redesign PCB ($10K), new prototypes ($5K), firmware integration ($10K)
Pre-production
$150K
New PCB layout ($30K), factory retooling ($40K), write off 5,000 existing units ($80K)
Post-launch
$2-5M
Recall existing units, replace with secure version, legal/regulatory, reputation
❌ “We’ll add security at the end” ❌ “Security is just encryption, right?” ❌ “Let’s finish the MVP, then do security” ❌ “Security testing is scheduled for the week before launch” ❌ “We’ll hire a pentester after manufacturing orders are placed”
Early Security Integration Checklist:
✅ Security requirements defined in month 0 (alongside functional requirements) ✅ Threat model created before design phase ✅ Security architect reviews design (not just functional architect) ✅ Secure coding training for all developers ✅ Automated security scanning in CI/CD from day 1 ✅ Security code reviews before merging to main ✅ Penetration testing at prototype phase (when changes are cheap) ✅ Security certification planned 6+ months before launch
Key Insight: Security testing at the prototype phase costs $5-25K and can identify issues when fixes are cheap (software changes, minor PCB revisions). Security testing after manufacturing orders ($5-40K for testing) can reveal issues requiring $200-500K fixes (hardware redesign, inventory write-off, 6-month delay). The 10-50× cost multiplier makes “shift-left security” one of the highest-ROI practices in IoT development.
Matching Exercise: Key Concepts
Order the Steps
Label the Diagram
💻 Code Challenge
6.12 Summary
Security testing validates real-world attack resistance through systematic evaluation of all attack vectors:
IoT Security Testing Summary: Key areas and their relationship to overall device security
Figure 6.5: IoT Security Testing Summary: Key areas and their relationship to overall device security
UART/JTAG/flash extraction must be tested; disable debug in production
Wireless Security
Test BLE pairing, Wi-Fi encryption, protocol authentication
Vulnerability Scanning
Use Binwalk, Firmwalker for firmware; scan for hardcoded secrets and outdated libraries
CI/CD Integration
Automate security gates; reject builds with critical vulnerabilities
Certifications
Match certification to market (PSA for consumer, FIPS for regulated, CC for government)
6.12.2 Security Testing Checklist
Before shipping any IoT device, verify:
6.13 Knowledge Check
Quiz: Security Testing for IoT
Try It Yourself: Security Testing Exercise
Objective: Perform a basic security assessment of an ESP32-based IoT device using open-source tools.
What You’ll Need:
ESP32 development board with sample firmware
Laptop with Wireshark, Binwalk, and strings command installed
Local MQTT broker (Mosquitto)
Step-by-Step Exercise:
Physical Interface Inspection (15 min)
Identify UART/JTAG pins on your ESP32 board
Connect USB-to-serial adapter to UART pins
Open serial terminal (115200 baud) and observe boot messages
What to observe: Are debug messages exposed? Can you access a shell prompt?
Firmware Extraction (20 min)
# Extract firmware from ESP32esptool.py-p /dev/ttyUSB0 read_flash 0x0 0x400000 firmware.bin# Analyze with binwalkbinwalk-e firmware.bin# Search for hardcoded credentialsstrings firmware.bin |grep-i"password\|api_key\|secret"
What to observe: Are credentials hardcoded? Are private keys embedded?
Network Traffic Analysis (25 min)
Start Wireshark capture on port 1883 (MQTT)
Power on ESP32 and let it connect to broker
Filter for mqtt protocol
What to observe: Is MQTT using TLS (port 8883) or plaintext (1883)? Are credentials visible?
Vulnerability Assessment (20 min)
Check if debug interfaces are disabled in production firmware
Verify firmware uses encrypted storage for credentials
Test if device rejects unsigned OTA updates
Document findings in security report template
Expected Outcome: You should identify 3-5 common IoT security issues (debug ports enabled, hardcoded secrets, unencrypted protocols) and understand how to fix them.
Challenge Extension: Write a script that automates the firmware analysis steps and generates a security score (0-100) based on findings.
Common Pitfalls
1. Not Including Security Testing in the Regular CI Pipeline
Security testing performed once per year (or only before major releases) misses regressions introduced during daily development. Integrate lightweight security checks into CI: static analysis for crypto misuse (semgrep-crypto rules), hardcoded credential detection (trufflehog, gitleaks), and dependency vulnerability scanning (safety check for Python, cargo audit for Rust, npm audit). Reserve expensive penetration testing for major releases; run automated security scanning on every commit.
2. Testing Security on Development Firmware Instead of Production Firmware
Development firmware often has: JTAG debug enabled, verbose serial logging, test credentials (admin/admin, 1234), relaxed authentication (any device can connect), and disabled TLS certificate validation. Security testing on development firmware produces results that are meaningless for production security. Always test security on production firmware builds with all debug features disabled, production certificates, and production security configuration. Maintain explicit “production security checklist” verified before each release.
3. Treating Security Testing as a One-Time Activity
Security testing before initial product launch catches vulnerabilities at that point in time. New vulnerabilities are discovered continuously: a chip’s ROM bootloader CVE discovered 18 months after launch, a new Bluetooth stack vulnerability, or a server library CVE. Establish ongoing security processes: subscribe to CVE feeds for all components (chipset, RTOS, TLS library, cloud SDK), run automated dependency scanning, and define a vulnerability response process with SLA (critical CVE → patch within 30 days + OTA release).
4. Not Testing for Physical Access Attacks
IoT devices in uncontrolled physical environments (outdoor smart meters, public transit scanners, retail kiosks) are subject to physical attacks: extracting firmware via JTAG/UART debug ports, cloning SIM cards, reading NVS flash with external programmer, and fault injection via voltage glitching. Test physical security: attempt firmware extraction with JTAG debugger attached (should require authentication or JTAG fuse blown), verify debug port protection, and test that device cannot be trivially cloned by copying flash contents.
6.14 What’s Next?
Continue your testing journey with these chapters: