
Recall first from Threat modelling and least privilege
- A threat model states what needs protection, who can reach it, and which components enforce its protections.
- A dedicated service account limits access through Linux file permissions. Capabilities grant specific privileged operations.
- Seccomp filters system calls. Filesystem restrictions and application authorisation enforce different rules.
Find invalid accesses and fix their causes
4 min readLeast privilege limits what a compromised service can touch; this lesson moves to the bugs that let attackers in, memory safety and input validation.
The printf(3) manual documents a real memory-safety problem in ordinary logging code. A format string directs the function to read arguments, and the %n conversion directs it to write through a pointer argument. A log message received from outside the program can therefore change what the logging function attempts to access if the program passes it as the format. That same distinction between data and instructions matters when code starts a helper or opens a requested file.
A buffer overflow is a write beyond the bounds of a buffer. An out-of-bounds read can also fail or expose data. In a device service that copies a message, check the declared byte count against both the bytes actually received and the available destination space. A successful allocation is evidence about the destination size only. If the destination holds a C string, reserve room for the terminating zero byte. If the input is binary, carry its length explicitly and use operations that accept that length.
A use-after-free occurs when code accesses an object after its allocation has been freed. For example, a service might enqueue a callback with a pointer to a request, then destroy the request on cancellation. Clearing the pointer in the cancelling function leaves the callback’s copy intact. Repair the lifetime relationship. A queued job can own a copy of the data it needs, take ownership of the request, or complete cancellation before the request is destroyed. Check the normal completion and shutdown paths as well as explicit cancellation.
In C++, use an owning container such as std::vector for a byte buffer and use .at() when you want range-checked element access. A std::span carries a length but does not own the storage, and its C++20 operator[] requires a valid index. A vector reallocation can invalidate a span into that vector. Use std::unique_ptr to express a single owner and move it into a job when the job should control the lifetime. In safe Rust, borrowing enforces lifetimes and slice .get(index) returns None for an invalid index. Use that result to reject malformed input without a panic. When Rust calls C, review the pointer, length, and lifetime assumptions at the interface. Safe Rust code relies on those assumptions being upheld.
AddressSanitizer (ASan) can detect invalid accesses such as heap or stack buffer overflows and heap use-after-free. UndefinedBehaviorSanitizer (UBSan) checks selected operations such as signed integer overflow and misaligned accesses. Build the app and its tests with both. For a single-file C app on Ubuntu, this command compiles and links an instrumented executable. Use the existing project build for an app with multiple source files or libraries. Apply the sanitizer flags to the source compilation and the final compiler-driver link, and retain the app’s normal library flags.
gcc -Wall -Wextra -std=c17 -g -O1 -fno-omit-frame-pointer \
-fsanitize=address,undefined -fno-sanitize-recover=undefined \
app.c -o app-sanitized
Run the existing tests through the instrumented build, including parsing, repeated requests, cancellation, cleanup, and failed initialization where the app supports them. Use the native host build with mock I/O if the app normally runs on a board. A host run exercises the code compiled for that host. Keep track of hardware-only paths, target-specific layouts, and code inside libraries built without instrumentation when you interpret the results.
Start with the first report. For an invalid access, find the application frame and identify the buffer or object being accessed. If ASan includes allocation and free traces, compare them with the access trace to see which function owned the storage when it was released. For a UBSan arithmetic report, inspect the operand types and where their values were accepted. Repair the condition that allowed the operation, add a test that checks the intended result, and run the full suite again. A clean run gives evidence for the operations those tests executed. Review the inputs and lifecycle cases the suite still misses.
Validate input before using it
2 min readA device service may accept bytes from a network message, an IPC request, or a configuration file. For each field, define which bytes are valid, which values the application supports, and how much work a request may cause. A decimal count, for example, can have a maximum text length, a digits-only grammar, and an application maximum well below the largest value its C type can represent. Apply the message size limit during intake so that reading and buffering a request also have a bound.
Validate the representation the program will use. If a framework decodes a field, apply the field rules to the decoded bytes and avoid decoding that field again later. Reject embedded zero bytes before converting a length-delimited text field to a C string. Otherwise the validator and a later C string API can see different lengths. For a decimal field, check the ASCII digit grammar, then convert. With strtol and base 10, set errno to zero first, check for ERANGE, verify that the end pointer advanced and reaches the string terminator, and check the application range before converting to a narrower type. The grammar matters because strtol also accepts leading whitespace and an optional sign. strtol(3)
Check arithmetic before evaluating it. Signed integer overflow is undefined in C. Unsigned arithmetic wraps, which can produce an allocation smaller than the caller expects. Suppose a validated size_t record count is multiplied by a positive record size. Reject the count if it exceeds SIZE_MAX / record_size before multiplying. When adding a header size to a computed body size, reject the addition if the body size exceeds SIZE_MAX - header_size. Then enforce the application’s memory budget and check the allocator’s result before use. For a read at an offset, first establish offset <= available and then check length <= available - offset. Each comparison protects the arithmetic that follows it.
Keep a literal format. In fprintf(stderr, "%s\n", message), only the literal controls formatting. Here message must point to a valid, terminated C string for the duration of the call. Treat a negative return as an output error when the caller needs to know whether logging succeeded. -Wformat=2 adds compiler diagnostics for suspicious formatting calls. Use the compiler warnings during review and check the caller’s string and lifetime contract separately. printf(3)
Avoid shell parsing for request data. On Linux, system() passes a command string to a shell. If only one operation is needed, call the library function that performs it. If a child process is needed, choose a fixed executable path and supply an explicit argument vector, for example with execve in the child. Validate the permitted operation and each argument according to the helper’s rules. An argument beginning with - can still be interpreted as an option by the helper. Use an end-of-options marker only when the helper documents it, and check launch failure and the child’s exit status. system(3), execve(2)
Constrain path resolution. If a request names an export, prefer a validated identifier that maps to a filename known to the service. For a feature that really accepts relative paths, open the trusted base directory and keep its descriptor. On Linux 6.8, openat2 can resolve a requested path relative to that descriptor with RESOLVE_BENEATH. glibc 2.39 has no openat2() wrapper, so call it as syscall(SYS_openat2, dirfd, path, &how, sizeof how) with a struct open_how from <linux/openat2.h>. It rejects resolutions that would escape the base. Add RESOLVE_NO_SYMLINKS if the application forbids symlinks throughout the path. Use the returned descriptor and handle a failed open as a failed request. A string prefix check cannot enforce this rule because the filesystem resolves components and links when opening the file. If your service promises to read regular files only, verify the opened object’s type before reading. openat2(2)
Make rejection observable in tests. Check the largest supported count and the first value above it, truncated input, unexpected trailing bytes, and any forbidden filename syntax. For requests that should fail, also check that they leave state unchanged. A handler that returns an error after opening a file, launching a helper, or committing a setting has already performed an operation the validation was supposed to prevent.
Check the dependencies in the delivered build
3 min readSanitizers answer questions about code exercised in a test run. To ask whether an included library has a published vulnerability, first establish what version the device will actually receive. A an inventory of software components and their identifying information, commonly called an SBOM gives you a record to compare with vulnerability data. A native audit build can use different libraries from the device release. Choose the staged release filesystem or unpacked image that corresponds to the artifact you intend to deliver, and record its build ID alongside the SBOM.
With Syft and Grype installed, run the following from a directory containing release-root, the staged or unpacked release tree. Give Grype access to a current vulnerability database. Keep your output files outside release-root so the files produced by the audit stay outside the tree being inventoried.
syft dir:./release-root -o cyclonedx-json > app-sbom.cdx.json
grype sbom:app-sbom.cdx.json -o json > dependency-findings.json
Confirm each command succeeded before using its output. Inspect the SBOM for a component you know the release includes. Look for its version and record the evidence that ties it to the staged artifact. Package metadata can identify libraries installed by the distribution. A staged directory with stripped binaries, statically linked libraries, or vendored source may contain components the directory scan cannot identify. Compare the SBOM with build inputs and resolved dependency records. Record missing components with their available version evidence and check them separately if they cannot be represented reliably in the scan.
A CVE identifies a publicly catalogued vulnerability. When a scanner reports a match, confirm the component identity, the installed release, and the affected versions against the relevant vendor advisory. A distribution can backport a security fix while retaining the upstream base version, so compare the full package revision and the advisory status for that distribution release. For an applicable finding, record the affected dependency and its proposed fix or mitigation. For a disputed match, record the evidence and the reason it needs no change or needs more investigation. When the scan reports zero matches, keep the artifact ID, scan date, database status, and any inventory gaps with the report. Those details define what the zero covers.
Authentication, secrets, and TLS is the next lesson. It asks how the same service can verify who is connecting and protect what it exchanges.
Key takeaways
- ASan detects many invalid memory accesses during execution, while UBSan detects selected forms of undefined behavior.
- Bounds and resource limits must be checked before arithmetic, allocation, or copying.
- Fixed format strings, explicit child arguments, and constrained path resolution enforce different input rules.
- An SBOM scan depends on component coverage, version identification, and vulnerability database freshness.
Reflect
- Explain to a colleague, in two sentences: distinguish out-of-bounds access from use-after-free in sanitizer reports.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageprintf(3): formatted output
- Man pagesystem(3): execute a shell command
- Man pageexecve(2): execute a program
- Man pageopenat2(2): open a file with resolution constraints
- Man pagestrtol(3): convert a string to a long integer
Official documentation first. Links checked when the lesson was published.