Secure Coding Practices
Secure coding practices are techniques that stop untrusted input, memory errors, and third-party code from changing what a program does.
Also known as secure programming, secure coding guidelines
Secure coding practices, also called secure programming, are techniques developers use to stop untrusted input, memory errors, and third-party code from changing what a program does. Most reduce to one mechanism: never letting data be interpreted as code. Injection and memory-corruption bugs fill seven of the top ten slots in MITRE's 2025 CWE Top 25.
We think most published lists of secure coding practices get the emphasis wrong. They hand developers a checklist and ask them to remember it on every line. The practices that measurably work do the opposite: they remove a bug class by construction, so the unsafe version is hard to write at all. Parameterized queries, auto-escaping templates, and memory-safe languages are in that group. After Android shifted new code to memory-safe languages, memory-safety bugs fell from 76% of its vulnerabilities in 2019 to 24% in 2024.
The second gap is scope. Secure coding practices are usually written as if the developer authored every line that runs. They did not. On March 30, 2026, the axios compromise shipped a dependency whose install hook dropped a remote access trojan during npm install, before any of the victim's own code executed. Input validation in your application cannot stop that. Dependency intake belongs on the list of secure coding practices.
What are secure coding practices?
#Secure coding practices are a short list of rules, and each one closes a boundary where data can turn into behavior. The table maps each practice to the weakness it prevents and that weakness's rank in MITRE's 2025 CWE Top 25. The ranking is built from 39,080 CVE records published between June 1, 2024 and June 1, 2025. The last column matters most: every practice leaves something open.
| Practice | Prevents | 2025 CWE Top 25 rank | What it does not cover |
|---|---|---|---|
| Bind query parameters; never build SQL from strings | SQL injection (CWE-89) | #2 | Table and column names, which cannot be bound and need an allowlist |
| Encode output for its context; use auto-escaping templates | Cross-site scripting (CWE-79) | #1 | Escape hatches such as dangerouslySetInnerHTML or |safe, and javascript: URLs in attributes |
| Check authorization on every request; deny by default | Missing authorization (CWE-862) | #4 | Checks that exist but ask the wrong question |
| Require anti-forgery tokens and SameSite cookies | Cross-site request forgery (CWE-352) | #3 | State changes made through GET requests |
| Use memory-safe languages; bounds-check in C and C++ | Out-of-bounds write (CWE-787), use after free (CWE-416), out-of-bounds read (CWE-125) | #5, #7, #8 | unsafe blocks and calls into C libraries through FFI |
| Resolve file paths, then verify they stay under a root | Path traversal (CWE-22) | #6 | Symlinks swapped in between the check and the open |
| Pass argument arrays to processes; never invoke a shell | OS command injection (CWE-78) | #9 | Arguments that begin with - and are parsed as flags |
| Never eval or deserialize untrusted data | Code injection (CWE-94), unsafe deserialization (CWE-502) | #10, #15 | Formats that execute on load, such as Python pickle |
| Keep secrets out of source; scan every push | Hard-coded credentials (CWE-798) | Not ranked in 2025 | Secrets already copied into forks, caches, and CI logs |
| Gate dependencies before install | Malicious packages | None: malware has no CWE | Payloads that run later, at import time or in the browser |
Seven of the top ten weaknesses are one of two failures. Data reaches an interpreter as code (CWE-79, CWE-89, CWE-78, CWE-94), or data overwrites memory it should never reach (CWE-787, CWE-416, CWE-125). Malicious packages do not appear anywhere on the list. The Common Weakness Enumeration (CWE) ranks mistakes in code you wrote, and a malicious package is not a mistake. It does exactly what its author intended, so it never gets a CWE and rarely gets a CVE. A program built only from the first nine rows can still be compromised by the tenth. OWASP reached the same conclusion from the other side: its 2025 Top 10 added Software Supply Chain Failures at #3, a category that maps to only 11 CVEs but that half of surveyed practitioners ranked as their top concern.
Why must data never become code?
#Data becomes code whenever a program builds a string in one language and hands it to an interpreter for another. SQL engines, HTML parsers, shells, and JavaScript's eval are all interpreters. An interpreter cannot tell which bytes the developer typed and which arrived from a user. It parses the whole string. This is the mechanism behind SQL injection, and it takes fourteen lines to reproduce:
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users(name TEXT, role TEXT);
INSERT INTO users VALUES ('alice','admin'),('bob','user');
""")
name = "nobody' OR '1'='1"
# String building: the input is spliced into the program text
q = f"SELECT name, role FROM users WHERE name = '{name}'"
print(db.execute(q).fetchall())
# Parameter binding: the program text is fixed, the input travels separately
print(db.execute("SELECT name, role FROM users WHERE name = ?", (name,)).fetchall())$ python3 sqli.py
[('alice', 'admin'), ('bob', 'user')]
[]In the first query, the quote character in the input closes the string literal the developer opened. The remaining OR '1'='1' becomes part of the WHERE clause, which is now always true, so the query returns every user. The input changed the shape of the program. In the second query, the statement text is fixed before the value exists, and the value can only ever be compared as a string.
PostgreSQL makes the two channels explicit on the wire. Its extended query protocol has a parse step, which creates a prepared statement from the query text with $1 placeholders, and a separate bind step, which supplies the parameter values. The server finishes parsing before it ever sees the input. No byte sequence in a bound value can add an OR clause, because the parse tree already exists.
The figure compares the two paths for the input nobody' OR '1'='1. With string building, the template WHERE name = '{name}' and the input are concatenated into one string, WHERE name = 'nobody' OR '1'='1'. The parser turns that into two conditions joined by OR, the second of which is always true, so the query returns both rows (alice/admin and bob/user). With parameter binding, a Parse message carries WHERE name = $1 and a separate Bind message carries the whole input as the value of $1. The parse tree was built before the value existed, so the input stays one literal string and the query returns no rows.
Memory corruption is the same failure one layer down. In C, a stack buffer sits next to control data such as the saved return address. A copy with no bounds check, like strcpy(buf, input), lets input bytes run past the end of the buffer and overwrite that address. The input now decides where the CPU jumps next. A buffer overflow is data rewriting control data, exactly as injection is data rewriting a query.
Is input validation enough?
#Input validation is not enough on its own, because whether a string is dangerous depends on where it is used, not where it entered. Validation runs once at the edge. The danger appears later, in whichever interpreter the data reaches. O'Brien is a valid surname, harmless in an HTML paragraph, and an injection inside a hand-built SQL string. The same text needs a different encoding in every context:
>>> import html, json, shlex
>>> s = "O'Brien</script>"
>>> html.escape(s) # safe in HTML text and quoted attributes
'O'Brien</script>'
>>> json.dumps(s) # valid JSON, but </script> still ends an inline <script> block
'"O\'Brien</script>"'
>>> shlex.quote(s) # safe as one POSIX shell argument
'\'O\'"\'"\'Brien</script>\''No single "sanitize" function can produce all three outputs, which is why input sanitization fails as a general defense. Sanitization rewrites input to strip the dangerous parts, so it has to predict every downstream context in advance, and it fails silently when it guesses wrong. Cross-site scripting (XSS) is the usual result. MITRE still ranks improper input validation (CWE-20) at #18, but most of the injection entries above it are fixed by encoding or binding at the point of use, not by better filters at the door.
Validation still earns its place for structure. Reject an order ID that is not an integer, a country code not in your list, or a JSON body that fails its schema. Use allowlists, never denylists of "bad characters", because every interpreter has its own metacharacters and encodings. Our rule is short: validate shape at the boundary, encode for context at the point of use, and bind parameters instead of escaping by hand. Where you must accept rich HTML, use a maintained HTML sanitizer that parses the markup, never a regular expression.
Language security: make the bug impossible to write
#The most effective secure coding practice is choosing a language or API in which the vulnerable version does not compile or does not run. Memory-safe languages such as Rust, Go, Java, C#, Python, and JavaScript make out-of-bounds writes and use-after-free bugs impossible in ordinary code. Google's Android data shows why this beats training: memory-safety issues were 76% of Android vulnerabilities in 2019 and 24% in 2024, against an industry norm of about 70%.
Google did not get there by rewriting old C++. Its analysis found that vulnerabilities concentrate in new code: by its estimates, five-year-old code has 3.4x to 7.4x lower vulnerability density than new code. Writing new code in memory-safe languages therefore cut the vulnerability rate even while the existing C++ stayed in place. Google's engineers describe the approach as "Safe Coding, which enforces security invariants directly into the development platform."
The same principle works above the language. React escapes text in JSX by default. Django templates auto-escape by default, and Flask turns on Jinja2 auto-escaping for .html templates. Python's subprocess.run(["convert", path, "out.png"]) never starts a shell unless you pass shell=True. Each default turns a secure coding practice from something a developer must remember into something a developer must deliberately switch off.
Construction has costs and gaps. Every safe default ships with an escape hatch, and bugs concentrate there: dangerouslySetInnerHTML, |safe, mark_safe, shell=True, eval, pickle.loads, and Rust's unsafe. Rust code that calls a C library through FFI is only as safe as that library. Rewrites are expensive, which is why Google aimed at new code first. And no language feature says anything about what a third-party package does when it is installed.
Enforce a secure coding baseline in tooling
#A secure coding baseline is the subset of secure coding practices that a machine checks on every change. A document cannot enforce anything. The checklist most pages cite, the OWASP Secure Coding Practices Quick Reference Guide, was archived in June 2025 and its content moved into the OWASP Developer Guide. It remains a good reference. It was never a control. A 2024 OpenSSF study found that 28% of developers, and 75% of those with under a year of experience, are unfamiliar with secure software development.
The baseline turns the escape hatches from the previous section into build failures. This ESLint 9 configuration rejects eval and the shell-spawning exec from Node's child_process:
export default [
{
rules: {
"no-eval": "error",
"no-implied-eval": "error",
"no-new-func": "error",
"no-restricted-imports": ["error", {
paths: ["child_process", "node:child_process"].map((name) => ({
name,
importNames: ["exec", "execSync"],
message: "Use execFile with an argument array. exec runs a shell.",
})),
}],
},
},
];$ npx eslint app.js
1:10 error 'exec' import from 'node:child_process' is restricted. Use execFile with an argument array. exec runs a shell no-restricted-imports
3:1 error eval can be harmful no-eval
✖ 2 problems (2 errors, 0 warnings)Add static application security testing (SAST) for data-flow bugs a lint rule cannot see, compiler hardening such as -D_FORTIFY_SOURCE=3 and stack protectors for C and C++, and secret scanning on every push. Make each check fail the build. The trade-offs are real. Lint rules flag every eval, including the rare legitimate one, so each exception needs a narrow, reviewed suppression. SAST tools report false positives that teams learn to ignore. And all of these tools analyze the code in your repository, not the code your package manager downloads.
How do secure coding practices apply to dependencies?
#Secure coding practices apply to dependencies as intake rules: decide which third-party code may run, when, and with what privileges, before it reaches a machine. Most dependency code was not written by anyone on your team, yet it runs with your team's credentials. Package managers historically ran that code at install time, through postinstall scripts and similar hooks, before any review or test.
The axios compromise shows the sequence. On March 30, 2026 at 23:59:12 UTC, plain-crypto-js@4.2.1 was published with a postinstall hook that ran a 4,209-byte dropper, setup.js. Poisoned releases axios@1.14.1 and axios@0.30.4 added it as a dependency, and axios has about 100 million weekly downloads. Any fresh resolution of ^1.14.0 pulled it in. The dropper fetched a platform-specific remote access trojan, then deleted itself and swapped its package.json for a clean copy to hide the evidence. Socket's scanner flagged the package about six minutes after it was published, but any fresh install in that window had already run the dropper.
npm's own team agrees on where the risk sits. Announcing the change, npm product manager Leo Balter wrote: "Install-time lifecycle scripts are the single largest code-execution surface in the npm ecosystem." pnpm 10 stopped running dependency lifecycle scripts by default in January 2025. npm v12, released in July 2026 and the current major version as of November 2026, did the same. We ran an identical install of a local package whose postinstall writes /tmp/pwned, first with npm 10.9 and then with npm 12.2.2:
# npm 10.9.9: the script runs during install
$ npm install ../dep/evil-dep-1.0.0.tgz; cat /tmp/pwned
added 1 package, and audited 2 packages in 364ms
found 0 vulnerabilities
ran
# npm 12.2.2: the script is skipped, the install still succeeds
$ npm install ../dep/evil-dep-1.0.0.tgz; cat /tmp/pwned
added 1 package, and audited 2 packages in 386ms
found 0 vulnerabilities
npm warn install-scripts 1 package had install scripts blocked because they are not covered by allowScripts:
npm warn install-scripts evil-dep@1.0.0 (postinstall: node -e "require('fs').writeFileSync('/tmp/pwned','ran')")
npm warn install-scripts
npm warn install-scripts Run `npm install-scripts ls` to review, or `npm install-scripts approve <pkg>` to allow.
cat: /tmp/pwned: No such file or directoryPackages that need a build step are approved explicitly. Running npm approve-scripts esbuild against a real install wrote a version-pinned entry, "allowScripts": {"esbuild@0.28.2": true}, into package.json. A pinned approval does not carry over to the next version, so a hijacked esbuild@0.28.3 would be blocked again until someone reviews it. Approving by name with --no-allow-scripts-pin avoids that churn and gives up exactly that protection. The cost of the new default lands on native modules: when the build step for a package like sharp or better-sqlite3 is skipped, it fails at runtime, not at install.
Script defaults close one door, not the building. The compromise of npm author Qix in September 2025 put its payload in the package code itself, in versions such as chalk@5.6.1 and debug@4.4.2. That payload ran in the browser when bundled code loaded, rewriting cryptocurrency wallet transactions. No install script was involved, so allowScripts would not have stopped it. The other intake practices each cover part of the gap and cost something:
- Commit a lockfile and install with npm ci. A lockfile makes existing installs reproducible. It does not make new resolution safe: adding or updating a dependency, running a tool with
npx, or installing globally all resolve against the live registry. As our analysis of the axios blast radius puts it, "Lockfiles make existing installs deterministic. They do not make new installs safe." Usenpx --no --offlinesonpxruns only what is already installed. - Set a minimum release age. pnpm 11 refuses versions younger than 1,440 minutes (one day) by default, and npm's minimumReleaseAge setting, added in early 2026, does the same when configured. The delay gives scanners and maintainers time to catch a compromise. The cost is that urgent security fixes wait out the same delay. A one-day window would not have caught a compromise that is first noticed on day two.
- Treat provenance as necessary, not sufficient. Signatures and build provenance prove where a package was built. A maintainer whose account is taken over publishes through the legitimate pipeline, so the malicious version arrives with valid credentials.
- Analyze what the package does before it installs. Socket Firewall Free,
sfw npm install <pkg>, proxies the package manager's downloads and blocks versions that human review has confirmed as malware, including transitive ones. It does not block packages that are only flagged by automated analysis, and it does not check packages already in the local cache.
Secure coding practices when an agent writes the code
#Secure coding practices were written for human authors who could be trained, and that assumption is breaking. Our data shows npm publishing rising from about 40,000 packages a month between June 2025 and January 2026 to about 100,000 a month by May 2026, a jump we tie largely to AI-generated packages. Coding agents increasingly write application code and choose dependencies. An agent tends to copy the patterns already in the repository, so a codebase full of f-string SQL produces more f-string SQL. An agent will not read your secure coding wiki. It can also install a package name it hallucinated, which attackers register in advance, a technique called slopsquatting.
That shifts the weight onto the practices that never depended on memory: APIs where the safe path is the default, a baseline that fails the build, and dependency intake that is checked by a machine. The open problem is the last one. Rust's compiler proves your code cannot use memory after freeing it. It says nothing about what a dependency's build script does. In the arrayref, internment, and append-only-vec crate compromise of August 2026, the poisoned releases added a typosquat named proc-macro1, and Cargo ran its build.rs during compilation. That loader fetched a backdoor without the application ever importing it. The only way to know what a dependency does is to analyze the package that is actually published, before it runs, on every install.
