Home / Learn Chip Programming / Secure Coding for Embedded: Input Validation, Memory Safety, Rust
Secure Coding for Embedded: Input Validation, Memory Safety, Rust
Write firmware that does not crash or give access when it receives bad data.
Theory in plain words
What it is
Most firmware vulnerabilities are memory safety bugs: buffer overflows, integer overflows, format strings, use-after-free. Validate all external input, check lengths, avoid unsafe functions, and consider memory-safe languages like Rust for new modules.
Why we use it
A single unchecked length field in a protocol parser can give an attacker remote code execution on a million devices.
How it works
Treat all input as hostile (UART, BLE, Wi-Fi, USB, files). Use bounded functions, enable stack protection and MPU, fuzz parsers, run static analysis and sanitizers.
Where it is used
- Network and USB stacks
- Over-the-air updates
- Interview and code review topics
Spot the vulnerability
These six patterns cause most real firmware CVEs.
| Practice | Benefit |
|---|---|
| Validate every length and index | stops overflows |
| Use snprintf / strlcpy / memcpy_s | bounded copies |
| Compile with -fstack-protector, -D_FORTIFY_SOURCE, enable MPU | harder exploitation |
| Fuzz parsers (AFL++, libFuzzer) on the PC | finds crashes automatically |
| Rust for new modules (Embassy, RTIC) | memory safety by the compiler |
| Least privilege: MPU regions, TrustZone | limits damage of a bug |
| Update path and SBOM | fix issues in the field and know your dependencies |
Quick quiz
1. Safe alternative to strcpy?
Bounded copy prevents overflow.
2. Fuzzing is...
Automatic bug finding.