Secure Coding and Application Security Questions
Writing and reviewing code that resists attack. Covers the OWASP Top Ten and common web vulnerabilities (XSS, SQL injection, CSRF), input validation, secure coding practices and security code review, static application security testing (SAST), API and HTTP security, database and frontend security, and mobile app security. The application-layer defense discipline for engineers building software.
Walk through a code-level security review for a REST endpoint that accepts file uploads, pushes the file to a worker for processing (thumbnailing, parsing), and stores metadata in a database. Identify the high-risk code paths (parsers, deserializers, temporary-file handling) and propose mitigations at the code level for input validation, safe deserialization, resource-exhaustion limits, sandboxing the processing step, and access control on the stored results.
Sample Answer
Direct answer
A file-upload-to-worker-to-database pipeline has four genuinely high-risk code paths, and they need four different kinds of mitigation, not one generic "validate the input" pass: the upload handler itself (input validation on the file and its metadata), the parser/deserializer the worker invokes to process the file (safe parsing and safe deserialization, since thumbnailing and parsing libraries are exactly the kind of code that resolves untrusted structure into live objects), the temporary-file handling in between (resource-exhaustion limits and safe file-system behavior), and the stored-result access path (access control on who can retrieve the processed output). Reviewing this endpoint means walking the data physically through all four stages and asking, at each one, "what happens if this specific piece of attacker-controlled data is actually hostile," because a fix at only one stage (validating the upload, say) leaves the worker's parser and the storage access control exactly as exposed as before.
Structured elaboration
Stage 1: the upload handler (input validation). The first code path attacker-controlled bytes touch, and the review should check specifically for validation of type, size, and content, not filename alone:
- Content-type and magic-byte validation, not just trusting the client-supplied
Content-Typeheader or file extension, both of which are entirely attacker-controlled. Validate the file's actual structure (magic bytes/file signature) matches the declared type before anything downstream treats it as that type. - Size limits enforced before the full file is read into memory or written to disk, not after, since an unbounded upload is itself a resource-exhaustion vector regardless of what the file contains.
- Filename handling: never use the client-supplied filename directly as a filesystem path component; generate an internal identifier (a UUID (Universally Unique Identifier) or content hash) and store the original filename only as metadata, which closes the path-traversal risk (
../../etc/cron.d/malicious) at the point of storage rather than relying on sanitization logic that has to anticipate every encoding trick. - Reject, do not attempt to "clean," structurally invalid input. A file that fails magic-byte validation for its declared type should be rejected outright; attempting to salvage or partially process a file that does not match its declared format is how a parser ends up being handed data it was never designed to defend against.
Stage 2: the worker's parser/deserializer (the highest-risk stage, and the one most reviews under-scrutinize). This is where "thumbnailing" and "parsing" actually happen, and it deserves the most attention precisely because it is furthest from the request boundary and easiest to assume is "just processing," when it is actually parsing untrusted, attacker-shaped structure:
- Image/document parsing libraries have their own, well-documented history of memory-safety and resource-exhaustion vulnerabilities (decompression bombs, malformed-header crashes, embedded-script execution in formats that support it like SVG (Scalable Vector Graphics) or certain PDF (Portable Document Format) constructs). The review question is not "does this library work," it is "is this library kept current, and does it run with any sandboxing given that its own attack surface is effectively the whole file format's specification."
- Any deserialization inside the parsing step (a document format that embeds structured metadata, or a parser that reconstructs objects rather than just extracting bytes) needs the same type-allowlisting and safe-format discipline that applies to insecure deserialization generally (allow-list the expected types, prefer a non-executable format over native serialization); a file-upload pipeline is a very common, easily-overlooked place for this exact vulnerability class to hide, because the entry point looks like "file processing," not "deserialization."
- The worker should never construct a shell command or a second parser invocation by string-interpolating attacker-controlled filename or metadata (a classic command-injection path when thumbnailing is implemented by shelling out to an external tool like ImageMagick with a filename or option value the attacker influenced).
Stage 3: temporary-file handling (resource exhaustion and filesystem safety). The stage most reviews skip entirely, treating "we use a temp file" as inherently safe:
- Bound total temp-storage consumption, both per-request and system-wide, since an attacker who can upload many large files concurrently (or a single file that expands dramatically during processing, a decompression-bomb variant) can exhaust disk space and take down unrelated functionality sharing the same filesystem.
- Use a dedicated, non-web-accessible temp directory with a defined, enforced lifecycle (deleted immediately after processing completes, and cleaned up on any failure path, not just the success path), since a temp file that outlives its processing step, or that is accidentally created inside a web-servable directory, converts a processing bug into a direct file-disclosure or, worse, a remote-code-execution path if the temp directory happens to be inside the web root and the content can be interpreted as executable.
- Explicit timeouts and resource caps on the processing step itself (CPU time, memory, wall-clock deadline for the worker job), so a single pathological file cannot monopolize worker capacity indefinitely, which is the resource-exhaustion mitigation the question calls out explicitly.
Stage 4: access control on the stored results. The last stage, and the one where a purely technical fix (encryption at rest, for instance) is often mistaken for the actual control that matters here:
- Authorization check on retrieval, scoped to the uploading user/tenant, verified on every access, not just at upload time; this is the same class of control as an Insecure Direct Object Reference (IDOR) fix: checking a resource's owner against the requesting caller's identity, applied here to processed-upload metadata and content.
- Storage location should not be predictable or guessable (sequential IDs, or a path derivable from the original filename) as the only control, since an unauthorized-access bug elsewhere in the authorization check becomes trivially exploitable if the storage path itself leaks the resource's location; unpredictable storage identifiers are defense in depth alongside the authorization check, not a substitute for it.
- Metadata stored in the database should itself be validated before storage, not treated as inherently safe because it came from "our own worker": if the worker extracts metadata (image dimensions, embedded EXIF (Exchangeable Image File Format) fields, document author) from the parsed file and writes it to the database unvalidated, that metadata is still attacker-influenced data and needs the same injection-safe handling (parameterized writes, output encoding wherever it is later displayed) as any other user input, just arriving one processing hop removed from the original request.
Applying this to a concrete stack (Java/Spring), since the review needs to land as specific, actionable findings, not abstract principles. A Spring-based implementation of this pipeline has a fairly predictable checklist:
MultipartFilehandling: verifyspring.servlet.multipart.max-file-sizeandmax-request-sizeare set explicitly (the framework defaults are permissive), and that the code validates content beyond what Spring's own multipart parsing provides, since Spring validates that the upload is well-formed multipart data, not that its payload is a legitimate, safe file of the declared type.- Path construction: verify no code path builds a
java.io.Fileorjava.nio.file.Pathby concatenating the client-supplied original filename, and specifically check forPath.resolve()calls fed attacker-controlled segments, sinceresolve()will happily walk outside the intended base directory given a../-laden input unless the result is explicitly verified to remain within the intended root afterward. - Thumbnailing/parsing library currency: check the dependency manifest for the specific image/document library version in use against known Common Vulnerabilities and Exposures (CVEs) for that library, since this class of library has a persistent history of parser-level memory-safety bugs.
- Any
ObjectInputStream, XML parsing (DocumentBuilderFactory), or YAML loading (Yaml.loadversusSafeConstructor) reachable from the parsing step gets the same hardening each of those vulnerability classes requires (type-allowlisting for deserialization, disabling DOCTYPE/external-entity resolution for XML, a safe constructor for YAML); a file-upload pipeline is one of the more common places these show up embedded inside "just processing the file." - Result access: verify the controller method serving processed results checks
@PreAuthorize(or equivalent explicit authorization logic) against the authenticated principal and the resource's recorded owner, not merely that the caller is authenticated at all.
Worked example
Walking a specific attacker-controlled input through all four stages makes the review concrete: an uploaded file named ../../../../var/www/html/shell.jpg;.php (a classic double-extension/traversal attempt) with a payload disguised as a valid JPEG. Stage 1 should reject the filename characters and validate the magic bytes; if it passes only because the magic-byte check was skipped (a common gap when a review only checks the extension), Stage 2's thumbnailing library now processes a file that is not actually a valid JPEG, which is exactly the kind of malformed input parser-level vulnerabilities are triggered by, potentially crashing the worker or worse, depending on the specific library and version. If Stage 2 also fails to isolate the failure (no timeout, no sandboxing, the worker process itself compromised), Stage 3's temp-file handling determines whether the resulting artifact is written somewhere web-accessible (severe) or confined to a locked-down, non-served temp path (contained). Even if all three stages hold, Stage 4 still needs to verify that whatever metadata or thumbnail was ultimately produced is served back only to the uploading user, since a validation gap anywhere upstream should not also mean any authenticated user can retrieve any other user's processed output. The point of walking all four stages together is that a single passing check at any one stage does not tell you the endpoint is safe; each stage is an independent line of defense against a slightly different failure of the ones before it.
Trade-offs and pitfalls
- Reviewing only the upload handler and declaring the endpoint safe. This is the most common shallow review outcome for exactly this shape of endpoint: Stage 1 is the most visible, closest-to-the-request-boundary code, and it is easy to stop there without following the file into the worker's parsing logic, which is usually where the actual highest-severity risk lives.
- Trusting library currency as a complete answer for Stage 2. Keeping the thumbnailing/parsing library patched closes known vulnerabilities but not unknown ones; sandboxing the processing step (a restricted container, a separate low-privilege process) is the control that limits blast radius from a vulnerability that has not been disclosed yet, and a review that only checks "is the version current" without also checking isolation has covered a smaller slice of the actual risk than it appears to.
- Treating temp-file cleanup as a happy-path-only concern. A cleanup step that only runs on successful processing (and not in a
finallyblock or equivalent, covering exceptions and timeouts) leaks temp files specifically on the failure paths an attacker is most likely to be deliberately triggering, which is the opposite of where cleanup discipline matters most. - Confusing "the file is stored with an unguessable name" with "the file is access-controlled." These are complementary, not equivalent; an unpredictable storage path raises the bar against blind guessing but does nothing against a real authorization bug (a broken IDOR check, a missing ownership verification) that an authenticated attacker can exploit directly, and reviews sometimes accept unguessable naming as sufficient evidence of access control when it is only ever a supporting layer.
Describe device attestation services available for mobile platforms: Android SafetyNet and Play Integrity, and Apple DeviceCheck and App Attest. Explain what an attestation actually asserts about the device and app, how the server should validate an attestation response, and known limitations or attacks against attestation.
Sample Answer
Direct answer: Device attestation lets a server ask "is this request genuinely coming from an unmodified copy of my app, running on a genuine, uncompromised device" - Android SafetyNet/Play Integrity and Apple DeviceCheck/App Attest are the platform-provided mechanisms for answering that, each producing a cryptographically-signed statement the server can verify without trusting the client's own claims about itself.
Structured elaboration.
What attestation asserts. Play Integrity (Android's current mechanism, succeeding the deprecated SafetyNet) reports on device integrity (is this a genuine, unmodified Android device, or an emulator/rooted device/one running a modified OS), app integrity (was this APK signed with the expected key and installed through a recognized channel like Play Store, or has it been repackaged/sideloaded), and account/licensing details. Apple's App Attest generates a hardware-backed key pair on first launch and has the Secure Enclave produce a signed attestation proving the app is a genuine, unmodified build running on genuine Apple hardware; DeviceCheck offers similar but lighter-weight device-level signals (primarily useful for abuse prevention like limiting free-trial abuse per physical device).
How the server validates. In both cases, the client obtains an attestation object/token from the platform API and sends it to the server, which verifies the signature chain against Google's/Apple's public root of trust (never trusting a client-reported "I'm legitimate" claim directly), checks the payload's freshness (a nonce the server issued, to prevent replaying an old attestation), and checks the reported package/bundle identifier matches the expected app. I ran this validation shape directly rather than just asserting it works:
import time
ISSUED_NONCES = {"session1": ("abc123", time.time())}
def validate_attestation(device_session, attestation):
session_entry = ISSUED_NONCES.get(device_session)
if session_entry is None:
return False # no outstanding nonce: unknown session, or already consumed by a prior call
expected_nonce, issued_at = session_entry
if time.time() - issued_at > 120:
return False # freshness window
if attestation["nonce"] != expected_nonce:
return False # blocks replay with a mismatched nonce
if attestation["bundle_id"] != "com.example.app":
return False
if attestation["integrity_verdict"] not in ("MEETS_DEVICE_INTEGRITY", "MEETS_BASIC_INTEGRITY"):
return False
del ISSUED_NONCES[device_session] # one-shot: consume the nonce
return True
valid_attestation = {"nonce": "abc123", "bundle_id": "com.example.app", "integrity_verdict": "MEETS_DEVICE_INTEGRITY"}
wrong_bundle = {"nonce": "abc123", "bundle_id": "com.evil.app", "integrity_verdict": "MEETS_DEVICE_INTEGRITY"}
print("valid attestation, first use:", validate_attestation("session1", valid_attestation))
print("SAME attestation replayed: ", validate_attestation("session1", valid_attestation))
ISSUED_NONCES["session2"] = ("xyz789", time.time())
print("wrong bundle id: ", validate_attestation("session2", wrong_bundle))
Running it against a valid attestation, then replaying that exact same attestation a second time, then submitting a wrong bundle ID produced:
valid attestation, first use: True
SAME attestation replayed: False
wrong bundle id: False
The second call fails specifically because the nonce entry was deleted after the first successful validation, so a lookup for that session now finds nothing; the ISSUED_NONCES.get(device_session) guard turns that into a clean False rather than a KeyError, which matters because a raw dictionary-index lookup (ISSUED_NONCES[device_session]) on an already-consumed or never-issued session crashes the request handler instead of rejecting it, turning a replay attempt into an accidental denial-of-service vector on the endpoint rather than a handled security rejection. An attacker capturing and replaying a genuine attestation gets cleanly rejected the same way a forged one would, without taking the server down in the process.
Known limitations and attacks against attestation. Attestation raises the bar significantly but isn't unconditionally unbreakable: emulator/root-detection bypass tooling exists and is actively maintained by the reverse-engineering community, specifically targeting these exact APIs; a sufficiently resourced attacker with a genuine device can sometimes extract or relay a legitimate attestation to a different, compromised context (a "relay attack" pattern). Attestation should be one signal feeding a broader risk decision (combined with behavioral signals, rate limiting, and business-logic-level abuse detection), not a single binary gate that, once passed, grants unlimited trust.
Trade-offs and pitfalls: attestation APIs require network calls to Google/Apple's servers and can fail transiently (no connectivity, a platform-side outage) or report degraded confidence on legitimate but unusual devices (certain enterprise-managed or older devices); a strict "reject anything below full integrity" policy will false-positive-block some real users, so design a graceful degradation path (reduced functionality rather than a hard block) for borderline verdicts, reserving hard blocks for clearly failed attestations.
Your web application serves user-generated HTML and relies on third-party analytics and widgets. Design a Content Security Policy that reduces XSS risk while preserving the required third-party functionality. Discuss nonces versus hashes, strict-dynamic, report-only mode, subresource integrity, and practical bypass techniques an attacker might try against your policy.
Sample Answer
Direct answer: For a page that must render user-generated HTML alongside third-party analytics and widgets, the right CSP design is a strict, allowlist-based policy built around nonces (not unsafe-inline), strict-dynamic to let trusted first-party scripts load their own dependencies without re-listing every third-party domain, and Subresource Integrity (SRI) on any third-party script you can pin to a specific version.
Structured elaboration.
A minimal-viable strict policy looks like:
Content-Security-Policy:
default-src 'self';
script-src 'nonce-{RANDOM_PER_REQUEST}' 'strict-dynamic';
style-src 'self' 'nonce-{RANDOM_PER_REQUEST}';
object-src 'none';
base-uri 'self';
frame-ancestors 'self';
- Nonces over
unsafe-inlineor domain allowlists: a fresh, unpredictable nonce is generated server-side per response and both embedded in the<script nonce="...">tag and sent in the header. An attacker who injects a<script>tag via a missed-encoding bug cannot guess the nonce, so their script simply doesn't execute even though the injection technically succeeded - this is the core value of CSP as defense in depth. strict-dynamic: once a nonce-carrying script is allowed to run, it can dynamically load further scripts (e.g. an analytics snippet that injects its own sub-scripts) without those sub-scripts needing their own nonce or domain listed. Withoutstrict-dynamic, every third-party analytics vendor's dynamically-loaded dependency chain has to be individually allowlisted by domain, which breaks constantly as vendors change their infrastructure.- SRI (
integrity="sha384-..."on<script>/<link>tags): for third-party scripts loaded from a CDN by URL rather than dynamically, SRI ensures that if the CDN is compromised or the script is tampered with in transit, the browser refuses to execute the mismatched content. This doesn't help for scripts loaded viastrict-dynamic's dynamic-injection path, since SRI requires a static<script src>tag; the two techniques cover different loading patterns. - Hashes as the alternative to nonces: instead of (or alongside) a nonce,
script-srccan allowlist a script by the SHA-256/384/512 hash of its exact content ('sha256-abc123...'). A hash source fits a script whose content is static and known ahead of time, since you compute the hash once and ship it in the policy; it needs no per-request coordination between the response header and the HTML, unlike a nonce, which must be freshly generated and matched on every single response. The trade-off runs the opposite way from a nonce's: a hash must be recomputed and redeployed on every single-byte change to the script's content, which makes it a poor fit for anything server-rendered with per-request variation, and a strong fit for a fixed, versioned, cacheable script file - the two mechanisms are chosen based on whether the script content is dynamic (nonce) or static (hash), not as competing options for the same script. - Report-only mode first: deploy as
Content-Security-Policy-Report-Onlywith areport-uri/report-toendpoint before enforcing, so you can see what the policy would have blocked (often a surprising number of legitimate but sloppy inline handlers or forgotten trackers) without breaking the page for real users while you fix them.
Worked example. A blog page that renders user comments (sanitized HTML, so no arbitrary <script> tags survive sanitization) plus a Google Analytics snippet and a chat widget. The analytics snippet is loaded via a nonce'd <script> tag; strict-dynamic lets it pull in its own further scripts. The chat widget is loaded from a fixed CDN URL with SRI pinning a specific build hash. If an attacker manages to sneak an unsanitized <img src=x onerror=...> past the comment sanitizer (a defense-in-depth failure at the sanitization layer), the CSP still blocks the onerror handler from executing, because inline event-handler attributes are blocked by default under a nonce-based script-src with no unsafe-inline.
Trade-offs and pitfalls: nonces require the CSP header and the HTML to be generated together per-request (not a static file, not cached HTML with a shared nonce, which would let an attacker capture and replay a previously-leaked nonce). Common attacker bypass attempts against a policy like this: JSONP-style endpoints (JSONP is an older cross-origin data-fetching technique that works by injecting a <script> tag whose src points at an endpoint accepting a callback= parameter, which the browser then executes as JavaScript) on your own 'self' origin that reflect a callback parameter (effectively becoming an attacker-controlled script source under your own domain), and abusing base-uri if you forget to restrict it, letting an attacker's injected <base href> tag redirect all relative script/resource loads to their own server. A widget vendor that insists on eval() or inline onclick= handlers will force a policy weakening (unsafe-eval/unsafe-inline) that undermines much of this design, so vet third-party scripts for CSP-compatibility before adopting them, not after.
Implement a safe Go-based CLI helper that accepts a filename and a single template command pattern but prevents command injection: the tool must execute a trusted command with the user-supplied filename as an argument, without any shell interpolation of that filename. Provide the code and explain specifically how it avoids shell injection.
Sample Answer
Direct answer
The tool avoids shell injection by never invoking a shell at all: os/exec.Command calls the target binary directly through the operating system's process-creation call, passing each argument as a separate, literal element of the argument list. There is no /bin/sh -c "..." step anywhere in the path, so there is nothing to interpret shell metacharacters like ;, |, &&, or $() in the user-supplied filename in the first place.
Structured elaboration
The vulnerable version of this pattern that the question is asking to avoid looks like building a shell command string, "wc -l " + filename, and handing it to something like exec.Command("sh", "-c", cmdString). That pattern is dangerous specifically because /bin/sh -c re-parses its string argument as a full shell command line, so any shell metacharacter embedded in filename (attacker-controlled) is interpreted as shell syntax rather than as literal text: a filename like x; rm -rf / becomes two commands to the shell, wc -l x followed by rm -rf /.
The fix is structural, not a matter of escaping characters more carefully: exec.Command(name, arg1, arg2, ...) in Go's standard library takes the program name and each argument as separate string values and passes them to the operating system as a pre-split argument vector (argv), calling execve directly. No shell is invoked at any point in this call path, so there is no shell syntax for an attacker-controlled string to exploit, regardless of what characters it contains. This is a fundamentally different guarantee than "we validated the filename doesn't contain dangerous characters," because it does not depend on the validation being complete: a shell-based approach is only as safe as its escaping logic, while an exec.Command-based approach has no escaping logic to get wrong in the first place.
Worked example
// s104 - safe CLI helper: runs a trusted, fixed command against a
// user-supplied filename without ever letting a shell interpret that
// filename.
//
// Build/run: go run . <filename>
package main
import (
"fmt"
"os"
"os/exec"
)
// runLineCount executes `wc -l <filename>` and returns its stdout.
// The command name ("wc") and flag ("-l") are fixed, trusted literals.
// filename is the ONLY user-controlled value, and it is passed as a
// separate argv element to exec.Command, never concatenated into a shell
// string. exec.Command calls the target binary directly via execve(2); it
// does not spawn /bin/sh and does not perform any word-splitting,
// globbing, `;`/`|`/`&&` interpretation, or `$()` substitution on its
// arguments. A filename like `x; rm -rf /` is therefore passed to wc as
// one literal (and almost certainly nonexistent) filename argument, not
// parsed as two shell commands.
func runLineCount(filename string) (string, error) {
cmd := exec.Command("wc", "-l", filename)
out, err := cmd.CombinedOutput()
return string(out), err
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: s104 <filename>")
os.Exit(2)
}
out, err := runLineCount(os.Args[1])
if err != nil {
fmt.Fprintf(os.Stderr, "command failed: %v\noutput: %s", err, out)
os.Exit(1)
}
fmt.Print(out)
}
And the tests that exercise it:
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestRunLineCount_LegitimateFile(t *testing.T) {
dir := t.TempDir()
f := filepath.Join(dir, "sample.txt")
if err := os.WriteFile(f, []byte("a\nb\nc\n"), 0o644); err != nil {
t.Fatal(err)
}
out, err := runLineCount(f)
if err != nil {
t.Fatalf("expected success, got error: %v (output: %s)", err, out)
}
// Parse the count out of `wc`'s output rather than substring-matching
// the whole line. wc echoes the full path back, and t.TempDir() paths
// contain a random numeric suffix, so a strings.Contains(out, "3")
// check would pass on the path digits no matter what the real count is.
fields := strings.Fields(out)
if len(fields) == 0 {
t.Fatalf("expected a count in wc output, got: %q", out)
}
if fields[0] != "3" {
t.Fatalf("expected line count 3, got %q (full output: %q)", fields[0], out)
}
}
func TestRunLineCount_ShellMetacharactersAreNotInterpreted(t *testing.T) {
dir := t.TempDir()
canary := filepath.Join(dir, "pwned")
// A classic command-injection payload: if this string were ever handed
// to /bin/sh -c, it would run `touch <canary>` as a second command.
maliciousFilename := filepath.Join(dir, "x; touch "+canary)
_, err := runLineCount(maliciousFilename)
if err == nil {
t.Fatalf("expected an error (no file literally named %q exists)", maliciousFilename)
}
if _, statErr := os.Stat(canary); statErr == nil {
t.Fatalf("SECURITY FAILURE: injected `touch` command executed and created %s", canary)
}
}
func TestRunLineCount_CommandSubstitutionNotInterpreted(t *testing.T) {
dir := t.TempDir()
// If this were shell-interpreted, $(id) would run the `id` command and
// splice its output into the argument list.
maliciousFilename := filepath.Join(dir, "$(id)")
out, err := runLineCount(maliciousFilename)
if err == nil {
t.Fatalf("expected an error, since no file literally named %q exists", maliciousFilename)
}
if strings.Contains(out, "uid=") {
t.Fatalf("SECURITY FAILURE: $(id) was shell-expanded, output leaked: %s", out)
}
}
Running go build ., go vet ., and go test -v ./... in the module all succeeded: build and vet reported no issues, and all three tests passed (TestRunLineCount_LegitimateFile, TestRunLineCount_ShellMetacharactersAreNotInterpreted, TestRunLineCount_CommandSubstitutionNotInterpreted), confirming both that a legitimate file is counted correctly and that neither a ;-separated injection payload nor a $() command-substitution payload gets shell-interpreted. The way to check a security test is actually load-bearing is to break the thing it guards and confirm it goes red: swapping the call for exec.Command("sh", "-c", "wc -l "+filename) makes the two injection tests fail immediately, the second one printing the expanded uid= output it was watching for. As a direct demonstration beyond the test suite: running go run . "sample.txt; touch pwned_demo" against a real 3-line sample.txt in the same directory does not create a file named pwned_demo. Instead it fails with wc: sample.txt; touch pwned_demo: open: No such file or directory, which is wc reporting that no file literally named sample.txt; touch pwned_demo (including the semicolon and space as literal filename characters) exists, exactly the outcome the code and tests both predict. (That exact wording is BSD/macOS wc; GNU coreutils phrases the same failure as wc: 'sample.txt; touch pwned_demo': No such file or directory. The literal-filename point is identical either way.)
Trade-offs and pitfalls
The single most common way to reintroduce this vulnerability later is a well-meaning refactor that swaps exec.Command("wc", "-l", filename) for exec.Command("sh", "-c", fmt.Sprintf("wc -l %s", filename)), often to support shell features like globbing or pipes that seem convenient. Any code review touching this function should treat the appearance of "sh", "-c", "bash", or manual string formatting into a command anywhere near this call as an immediate red flag, not a style preference.
This mitigation is specific to avoiding shell interpretation; it does not by itself validate that filename is a sensible or safe path in other respects (path traversal into an unintended directory via ../, for example, is a separate concern from command injection and needs its own check, typically resolving the path and confirming it stays within an expected base directory before use).
cmd.CombinedOutput() merges stdout and stderr for simplicity in this example; a production tool would likely keep them separate so a caller can distinguish the command's actual output from its diagnostic error text, and would also consider whether wc's own exit code and stderr content should be surfaced to the caller in more structured form than a merged string.
Passing the trusted command name ("wc") as a literal is itself a small design decision worth being deliberate about: if the command name itself were ever built from user input (a different, related mistake from the filename-injection case this question asks about), the same exec.Command safety property would not apply, since an attacker could then point the process at an arbitrary binary on the system's PATH rather than merely supplying an unusual filename argument.
Write server-side pseudocode (or an algorithm description) to validate an App Attest or Play Integrity attestation. Include validating the signing certificate or attestation chain, verifying the nonce and freshness, checking the package name or bundle identifier, interpreting the integrity flags, and preventing replay attacks. Discuss caching strategies and how to handle offline validation failures gracefully.
Sample Answer
Approach
Validating an App Attest (iOS) or Play Integrity (Android) attestation server-side is a fixed sequence of checks, and the order matters: verify the signature/chain FIRST (nothing else about an unsigned or forged token is trustworthy), then check freshness and identity, then apply an integrity-flag policy, then guard against replay, all before caching the result so a later request from the same device does not have to repeat the whole check. Caching also has to degrade gracefully: if the attestation provider itself is temporarily unreachable, the service should serve a recent, still-fresh cached verdict rather than either blocking every user outright or silently granting trust with no verification at all.
Language-tagged code block
The listing below implements and exercises this full flow, using HMAC-SHA256 (Python's standard-library hmac/hashlib) as an explicit stand-in for the real signature verification (Elliptic Curve Digital Signature Algorithm, ECDSA, over the platform's attestation certificate chain) that App Attest and Play Integrity actually use in production. The control flow this exercises, chain/signature check, nonce and freshness, package identity, integrity-flag policy, replay guard, caching with graceful offline fallback, is the reusable part; the actual cryptographic primitive is swapped out here specifically so the file runs with no external dependencies, and that substitution is disclosed rather than presented as a real attestation-chain verifier.
import hashlib
import hmac
import time
TRUSTED_KEY = b"stand-in-secret-for-the-platform-attestation-key"
MAX_CLOCK_SKEW_SECONDS = 120
FRESHNESS_WINDOW_SECONDS = 300
NONCE_RETENTION_SECONDS = 3600
_seen_nonces: dict[str, float] = {}
_attestation_cache: dict[str, dict] = {}
def sign(payload: str, key: bytes) -> str:
return hmac.new(key, payload.encode(), hashlib.sha256).hexdigest()
def make_token(nonce: str, timestamp: float, package_name: str, integrity: str,
apk_digest: str, key: bytes) -> dict:
payload = f"{nonce}|{timestamp}|{package_name}|{integrity}|{apk_digest}"
return {
"nonce": nonce, "timestamp": timestamp, "package_name": package_name,
"integrity": integrity, "apk_digest": apk_digest,
"signature": sign(payload, key),
}
def validate_attestation(token: dict, expected_nonce: str, allowed_package: str,
expected_digest: str, now: float) -> tuple[bool, str]:
payload = f"{token['nonce']}|{token['timestamp']}|{token['package_name']}|{token['integrity']}|{token['apk_digest']}"
expected_sig = sign(payload, TRUSTED_KEY)
if not hmac.compare_digest(expected_sig, token["signature"]):
return False, "reject: bad_signature"
if token["nonce"] != expected_nonce:
return False, "reject: nonce_mismatch"
if abs(now - token["timestamp"]) > MAX_CLOCK_SKEW_SECONDS + FRESHNESS_WINDOW_SECONDS:
return False, "reject: stale"
if token["package_name"] != allowed_package:
return False, "reject: package_mismatch"
if token["apk_digest"] != expected_digest:
return False, "reject: digest_mismatch"
if _seen_nonces.get(token["nonce"]) is not None:
return False, "reject: replay"
_seen_nonces[token["nonce"]] = now
if token["integrity"] != "MEETS_DEVICE_INTEGRITY":
_attestation_cache[token["nonce"]] = {"accepted_at": now, "trust": "reduced"}
return True, "accept: reduced_trust (integrity=" + token["integrity"] + ")"
_attestation_cache[token["nonce"]] = {"accepted_at": now, "trust": "full"}
return True, "accept: full_trust"
def cached_or_validate(token: dict, expected_nonce: str, allowed_package: str,
expected_digest: str, now: float, provider_reachable: bool) -> tuple[bool, str]:
"""Caching + graceful offline handling: if the attestation provider is
unreachable, fall back to a cached, still-fresh accepted result for this
nonce instead of either blocking the user outright or silently granting
full trust with no verification at all."""
if not provider_reachable:
cached = _attestation_cache.get(token["nonce"])
if cached and (now - cached["accepted_at"]) <= FRESHNESS_WINDOW_SECONDS:
return True, f"accept: served_from_cache (trust={cached['trust']})"
return False, "reject: provider_unreachable_no_fresh_cache"
return validate_attestation(token, expected_nonce, allowed_package, expected_digest, now)
if __name__ == "__main__":
now = time.time()
ALLOWED_PACKAGE = "com.example.securebank"
EXPECTED_DIGEST = "sha256:abc123def456"
valid = make_token("nonce-001", now, ALLOWED_PACKAGE, "MEETS_DEVICE_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
print("1) Valid token: ", validate_attestation(
valid, "nonce-001", ALLOWED_PACKAGE, EXPECTED_DIGEST, now))
wrong_package = make_token("nonce-002", now, "com.attacker.clone", "MEETS_DEVICE_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
print("2) Wrong package name: ", validate_attestation(
wrong_package, "nonce-002", ALLOWED_PACKAGE, EXPECTED_DIGEST, now))
replay = make_token("nonce-001", now, ALLOWED_PACKAGE, "MEETS_DEVICE_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
print("3) Replayed nonce-001: ", validate_attestation(
replay, "nonce-001", ALLOWED_PACKAGE, EXPECTED_DIGEST, now))
stale = make_token("nonce-003", now - 1000, ALLOWED_PACKAGE, "MEETS_DEVICE_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
print("4) Stale timestamp: ", validate_attestation(
stale, "nonce-003", ALLOWED_PACKAGE, EXPECTED_DIGEST, now))
reduced = make_token("nonce-004", now, ALLOWED_PACKAGE, "MEETS_BASIC_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
ok, reason = validate_attestation(reduced, "nonce-004", ALLOWED_PACKAGE, EXPECTED_DIGEST, now)
print("5) Reduced device integrity:", (ok, reason))
tampered = make_token("nonce-005", now, ALLOWED_PACKAGE, "MEETS_DEVICE_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
tampered["integrity"] = "MEETS_DEVICE_INTEGRITY_TAMPERED"
print("6) Tampered signature: ", validate_attestation(
tampered, "nonce-005", ALLOWED_PACKAGE, EXPECTED_DIGEST, now))
print()
offline_valid = make_token("nonce-006", now, ALLOWED_PACKAGE, "MEETS_DEVICE_INTEGRITY",
EXPECTED_DIGEST, TRUSTED_KEY)
ok1, r1 = cached_or_validate(offline_valid, "nonce-006", ALLOWED_PACKAGE, EXPECTED_DIGEST, now, provider_reachable=True)
print("7a) First check (provider reachable): ", (ok1, r1))
ok2, r2 = cached_or_validate(offline_valid, "nonce-006", ALLOWED_PACKAGE, EXPECTED_DIGEST, now + 30, provider_reachable=False)
print("7b) Re-check 30s later (provider unreachable):", (ok2, r2))
Running this produces:
1) Valid token: (True, 'accept: full_trust')
2) Wrong package name: (False, 'reject: package_mismatch')
3) Replayed nonce-001: (False, 'reject: replay')
4) Stale timestamp: (False, 'reject: stale')
5) Reduced device integrity: (True, 'accept: reduced_trust (integrity=MEETS_BASIC_INTEGRITY)')
6) Tampered signature: (False, 'reject: bad_signature')
7a) First check (provider reachable): (True, 'accept: full_trust')
7b) Re-check 30s later (provider unreachable): (True, 'accept: served_from_cache (trust=full)')
Key points
- Signature/chain check comes first, unconditionally. Scenario 6 shows why: even though every OTHER field in the tampered token is well-formed, altering the
integrityfield after signing invalidates the signature, and the function rejects on that basis alone, never reaching (and never needing to reach) any of the later checks. - Nonce and freshness together defeat replay AND staleness. The nonce (scenario 3) stops a captured, otherwise-valid token from being resubmitted; the timestamp/freshness window (scenario 4) independently stops an old token from being accepted just because its nonce happens not to have been seen yet (a nonce store that has since been cleared or expired, for example).
- Package/bundle identity check stops a cloned or repackaged app from attesting on a legitimate app's behalf. Scenario 2: a token that is otherwise perfectly valid, correctly signed, fresh, unused nonce, is still rejected because it claims to come from a different package than the one this backend serves.
- Interpreting integrity flags is a policy decision, not a binary accept/reject. Scenario 5 shows a device that meets only BASIC (not full hardware-backed) integrity still gets accepted, but tagged
reduced_trust; the calling application decides what reduced trust means (perhaps allow read-only actions, block a funds transfer) rather than the attestation layer making that business decision itself. - Caching serves the LAST VERIFIED result, not a bypass of verification. Scenario 7 shows the sequence explicitly: the token is fully verified once while the provider is reachable, and only a SUBSEQUENT check, within the freshness window, for the SAME already-verified nonce, is served from cache when the provider becomes unreachable; a token that has never been successfully verified has no cache entry to fall back to.
Complexity
Each individual validation call is constant-time relative to the number of stored nonces: the signature check is a fixed-cost hash comparison, and the nonce lookup and cache lookup are both dictionary (hash-map) operations, average O(1). The one place this is not free is nonce-store growth: _seen_nonces grows without bound as written above, which is why a real implementation needs the NONCE_RETENTION_SECONDS constant actually enforced (evicting entries older than the retention window, an O(1) amortized cost per insertion using a time-ordered structure) rather than left to grow forever, since an unbounded in-memory replay-guard store is itself an operational and memory-exhaustion risk at scale.
Edge cases
- Clock skew between device and server.
MAX_CLOCK_SKEW_SECONDSgives explicit tolerance so a device with a slightly incorrect clock is not rejected outright, without making the freshness window so wide that a captured token stays replayable for a meaningful period. - Attestation provider unreachable with no prior successful verification for this device/nonce. Scenario 7's logic explicitly falls through to rejection in this case (
reject: provider_unreachable_no_fresh_cache) rather than silently granting trust; failing closed here is the correct default for a security control, even though it costs availability for that specific user until the provider is reachable again. - A device that meets basic but not full integrity. Handled as a policy tier (scenario 5), not a hard reject, since legitimately many real devices (older hardware, certain custom ROMs, some emulators used for legitimate testing) cannot achieve full attestation but are not necessarily malicious.
- Nonce store growth over time. Called out explicitly in Complexity above; an attacker deliberately generating many distinct nonces to grow the store is itself a resource-exhaustion vector worth rate-limiting upstream of this validation logic, not something this function alone can defend against.
Unlock Full Question Bank
Get access to all Secure Coding and Application Security interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.