Security cheat sheet
Defensive security and secure coding on a few screens: the common flaws and their fixes, how to store passwords and sessions, secrets, headers, crypto choices, STRIDE, the logs worth collecting, alert triage and the first hour of an incident. Keep it open during code review, threat modelling and on-call.
Common flaws and the fix for each
Grouped like the OWASP Top 10 (2021 edition). The fix column is where to start; most rows need it applied everywhere, not in one place.
| Flaw | What it looks like at Mangrove | Fix | Lesson |
|---|---|---|---|
| Broken access control | GET /orders/88123 returns another customer's order; a store manager edits prices for a store that is not theirs | Check ownership on the server for every request; deny by default; scope every query by the caller's user or stores; row-level security as a second wall | Access control |
| Injection (SQL, command) | Product search builds SQL by joining strings from the search box | Parameterised queries or the ORM's bound parameters; never pass user input to a shell; least-privilege database user | Injection |
| Cross-site scripting (XSS) | A product review is rendered as raw HTML in the back office | Let the framework escape output; avoid innerHTML and dangerouslySetInnerHTML; sanitise any HTML you must keep; add a CSP | JS security, Injection |
| Cross-site request forgery (CSRF) | Cookie-authenticated back office accepts a form post from any site | SameSite=Lax or Strict cookies, plus CSRF tokens on state-changing requests | Auth and sessions |
| Cryptographic failures | Passwords stored with plain SHA-256; an internal API on plain HTTP | TLS everywhere with HSTS; a password hash such as Argon2id; encrypt sensitive data at rest; keep less data | Cryptography |
| Insecure design | One-time codes for rider login with no attempt limit | Threat model new features; write abuse cases next to user stories; limits and quotas by design | Threat modelling |
| Security misconfiguration | Debug mode on in production; a storage bucket left public; default password on a store router | A hardened baseline in code (IaC), reviewed like code; config scanning; remove defaults | Networks and cloud |
| Vulnerable components | An old npm package with a published CVE in the POS sync service | Lockfiles, npm audit, Dependabot or Renovate, an SBOM, and a patch deadline by severity | Supply chain |
| Authentication failures | No MFA on the back office; sessions that never expire; unlimited login attempts | MFA, throttling per account and per IP, session timeouts, new session id at login | Auth and sessions, Identity |
| Integrity failures | CI runs a third-party action by a moving tag; till updates are not signed | Pin actions to a commit SHA; protected branches and required reviews; signed builds and updates | Pipeline and AI, Supply chain |
| Logging and monitoring failures | Failed logins are not logged; nobody hears about 5,000 of them in an hour | Log security events centrally, alert on them, and test that the alert fires | Logs, Detections |
| Server-side request forgery (SSRF) | "Import product image from URL" can be pointed at internal addresses | Allowlist hosts; block private ranges and the cloud metadata address; do not follow redirects blindly | Injection, Networks and cloud |
| Prompt injection in AI features | A supplier document tells the shopping assistant to reveal other customers' data | Treat model output as untrusted; the model gets only the caller's permissions; human confirmation for risky tool calls | Pipeline and AI |
Passwords, sessions and tokens
Use a well-known library for each row rather than writing your own. The "Avoid" column lists what still turns up in real code reviews.
| Decision | Do | Avoid | Lesson |
|---|---|---|---|
| Storing passwords | Argon2id, scrypt or bcrypt, with the salt the library adds | MD5, SHA-1, SHA-256 alone, or reversible encryption | Cryptography |
| Password rules | Length over complexity; allow long passphrases; block known-breached passwords; no forced rotation without a reason (NIST SP 800-63B) | Short maximum lengths, composition rules, security questions | Identity |
| Login errors | One generic message ("email or password is wrong"); throttle per account and IP | Messages that reveal which accounts exist | Auth and sessions |
| Session cookie | HttpOnly; Secure; SameSite=Lax; new id after login; idle and absolute timeouts | Session ids in URLs; tokens in localStorage for sensitive apps | Auth and sessions |
| JWT access tokens | Short lifetime (minutes); verify signature with an allowlist of algorithms; check exp, aud, iss | Secrets in the payload (it is only encoded); accepting alg: none; tokens that live for weeks | Auth and sessions |
| Refresh tokens | Rotate on every use; revoke the family if an old one comes back | One long-lived token that never changes | Auth and sessions |
| MFA | Passkeys or security keys (FIDO2, WebAuthn) first, then an authenticator app | SMS codes for admins; MFA prompts users approve without thinking | Identity |
| Password reset | Single-use random token, short expiry, same answer whether or not the email exists | Reset links that never expire or can be guessed | Auth and sessions |
| Login for SPAs and mobile apps | OAuth 2 Authorization Code flow with PKCE | The implicit flow; the app holding a client secret | Identity |
| Authorization checks | On the server, per request, per object, in one shared place | Hiding buttons in the UI and calling it done | Access control |
Secrets in one breath
Never commit secrets; keep .env in .gitignore and ship a .env.example with fake values. Store real ones in a secret manager or your CI's encrypted secrets, scoped to one environment. Prefer short-lived credentials: GitHub Actions can sign in to the cloud with OIDC instead of a stored key. Turn on secret scanning and push protection. If a secret leaks, rotate it first, then clean history: deleting the commit does not un-leak it, because forks, caches and clones keep copies (Supply chain, Pipeline and AI, Supply chain in CI).
Security headers to start from
Set them once in the web server, CDN or framework middleware. Roll a new CSP out with Content-Security-Policy-Report-Only first and read the reports before enforcing it.
| Header | Starting value | What it stops | Lesson |
|---|---|---|---|
Strict-Transport-Security | max-age=31536000; includeSubDomains (add preload only when every subdomain is HTTPS) | Downgrade to plain HTTP on hostile Wi-Fi | Security |
Content-Security-Policy | default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none' | Limits what injected script can load and run; clickjacking | JS security |
X-Content-Type-Options | nosniff | Browsers guessing that an upload is a script | JS security |
Referrer-Policy | strict-origin-when-cross-origin | Full URLs, with ids or tokens, leaking to other sites | JS security |
Permissions-Policy | camera=(), microphone=(), geolocation=() for features you do not use | Embedded or injected code using device features | JS security |
X-Frame-Options | DENY (older browsers; CSP frame-ancestors replaces it) | Your page framed by another site | JS security |
CORS (Access-Control-Allow-Origin) | An exact list of your own origins | Other sites reading responses meant for your app; * never works with credentials | Access control |
Cryptography: use and avoid
Pick from a maintained library (libsodium, the platform's crypto module, your cloud's KMS). Designing your own scheme is the one mistake reviewers cannot fix with a small patch.
| Need | Use | Avoid | Lesson |
|---|---|---|---|
| Data in transit | TLS 1.2 or 1.3 (prefer 1.3) | SSL, TLS 1.0 and 1.1, turning off certificate checks | Cryptography |
| Encrypt data at rest | AES-256-GCM through a library or KMS, with envelope encryption | ECB mode, reused nonces, keys in the code | Cryptography |
| Random tokens and ids | crypto.randomBytes(32), crypto.randomUUID() | Math.random(), timestamps, counters | Cryptography |
| Integrity hash | SHA-256 or SHA-3 | MD5 and SHA-1 for anything security related | Cryptography |
| Webhook or message signature | HMAC-SHA256, compared with crypto.timingSafeEqual | A plain hash; comparing with == | Cryptography |
| Digital signatures | Ed25519 or ECDSA P-256; RSA with 2048-bit keys or longer | RSA 1024; homemade padding | Cryptography |
| Key storage | KMS, HSM or a secret manager, with rotation and access logs | Keys in the repo, in images or in shared chat | Cryptography |
Threat modelling with STRIDE
Draw the data flow first (who talks to what, across which trust boundary), then walk each arrow with the six letters. Four questions frame the session: what are we working on, what can go wrong, what are we going to do about it, and did we do a good enough job (Threat modelling).
| Letter | Ask | Mangrove example | Typical control |
|---|---|---|---|
| Spoofing | Can someone pretend to be a user, device or service? | A laptop pretends to be till 3 at store S-014 | Authentication; device certificates or mTLS |
| Tampering | Can data be changed in transit or at rest? | Sales batches edited before upload | TLS, signatures, database permissions, checksums |
| Repudiation | Can someone deny doing it? | "I never approved that price change" | Audit logs with who, what, when; logs the actor cannot edit |
| Information disclosure | Can data leak to the wrong person? | Order history visible across partner shops | Access control, encryption, keeping less data |
| Denial of service | Can it be overwhelmed or starved? | Bots hammer the festival-sale endpoint | Rate limits, quotas, timeouts, autoscaling, a CDN |
| Elevation of privilege | Can someone gain rights they should not have? | A cashier account calls an admin API | Server-side role checks, least privilege, separate admin accounts |
Secure code review: ten questions
- Does every new endpoint check who is calling and whether they may touch this object?
- Is all user input bound as a parameter, never joined into SQL, shell commands or file paths?
- Is output escaped by the framework, with no new raw-HTML sinks?
- Are secrets read from the environment or a secret manager, never written in code or logs?
- Do logs record security events without passwords, tokens, card numbers or full personal data?
- Do errors return a generic message to the client and the detail only to the logs?
- Do new dependencies come from a known publisher, with a pinned version in the lockfile?
- Are uploads limited by size and type, stored outside the web root and scanned or re-encoded?
- Are outbound calls to user-supplied URLs restricted to an allowlist?
- Is there a rate limit on anything that sends a message, costs money or checks a secret?
Logs worth collecting
Collect centrally, keep timestamps in UTC, and know how long each source is retained. Never log passwords, tokens, secrets or full card numbers (Logs).
| Source | Events to keep | Why | Lesson |
|---|---|---|---|
| Identity provider | Sign-ins, failed MFA, new MFA device, risky or impossible-travel sign-ins | Most intrusions start with a stolen account | Identity, Logs |
| App and API | Login success and failure, 403s, password resets, role changes, bulk exports, admin actions | Shows abuse that looks like normal traffic | Logs |
| Cloud control plane | New access keys, policy changes, resources made public, logging turned off | The attacker's first moves in the cloud | Networks and cloud |
| Windows Security log | 4624 logon, 4625 failed logon, 4720 user created, 4728 and 4732 added to a security group, 4688 process created, 1102 log cleared | Account misuse and tracks being covered | Logs, Detections |
| Linux auth logs | /var/log/auth.log (Debian, Ubuntu) or /var/log/secure (RHEL family); journalctl on systemd hosts | SSH logins, sudo use, new users | Logs |
| Endpoint (EDR) | Process trees, new services and scheduled tasks, PowerShell script block logs | What actually ran on the laptop or till | Detections |
| DNS, proxy, firewall | Lookups and connections, especially to new or rare domains | Command-and-control and data leaving | Threat hunting |
Alert triage in five questions
Write the answer to each question in the ticket as you go, so the next analyst can pick it up (Triage).
| Step | Ask | Look at | Lesson |
|---|---|---|---|
| 1. Real? | True positive, false positive or benign true positive? | The rule's logic and the raw event, not only the alert title | Triage |
| 2. Who and what? | Which user, host, data and how important are they? | Asset list, user role, whether this is normal for them | Triage |
| 3. What else? | What happened around it? | A timeline an hour either side for the same user, host and IP | Triage, Threat hunting |
| 4. How bad? | Data touched, privileges gained, other hosts involved? | Severity guide, scope across the estate | Triage |
| 5. What now? | Close with a reason, escalate, or contain? | Runbook for this alert; tune the rule if it was noise | Detections, Incident response |
Incident response: the phases
The classic lifecycle from NIST SP 800-61. Small incidents move through it in an hour; the order still matters.
| Phase | Do | Do not | Lesson |
|---|---|---|---|
| Prepare | Contact list, runbooks, log retention, tested backups, practice drills | Write the plan during the incident | Risk and incidents |
| Detect and analyse | Declare early, name an incident lead and a scribe, open one channel and one timeline | Investigate quietly for days before telling anyone | Incident response |
| Contain | Disable the account, revoke sessions, isolate the host through EDR, rotate exposed keys | Wipe machines before you have collected evidence | Incident response |
| Eradicate and recover | Remove the foothold, patch the hole, restore from known-good backups, watch closely | Bring systems back before the way in is closed | Incident response |
| Learn | Blameless review, actions with owners and dates, new detections | Close the ticket with "user error" | Risk and incidents |
Numbers worth remembering
Check current guidance before you put these in a policy; standards are revised every few years.
| What | Value | Use it to | Lesson |
|---|---|---|---|
| CVSS bands (v3 and v4) | Critical 9.0 to 10, High 7.0 to 8.9, Medium 4.0 to 6.9, Low 0.1 to 3.9 | Set patch deadlines; then adjust for exposure and known exploitation | Supply chain |
| GDPR breach notice | Within 72 hours of becoming aware, to the supervisory authority | Start the legal clock on day one, if you handle EU personal data | Risk and incidents |
| Argon2id minimum (OWASP) | 19 MiB memory, 2 iterations, 1 lane | Configure the password hash | Cryptography |
| bcrypt work factor (OWASP) | 10 or more | Configure legacy systems that use bcrypt | Cryptography |
| Random token size | At least 128 bits; 32 random bytes is common | Size reset tokens, API keys and session ids | Cryptography |
| HSTS max-age | 31,536,000 seconds = one year | Set the header value | Security |
| TOTP codes | 6 digits, a new one every 30 seconds | Explain why a code "expired" and why clocks must be right | Identity |
Testing your own systems
Only test what you own or have written permission to test, with a signed scope, dates and a contact for when things break. Report findings with steps to reproduce, impact and a fix, ranked by risk, not by how clever they were (Ethics and scope, Reporting).
Glossary
Plain definitions of the security terms used most across the Cybersecurity line.
- Attack surface
- Every place an attacker could interact with a system: endpoints, open ports, accounts, dependencies, people. Attacker mindset
- Authentication and authorization
- Authentication proves who you are; authorization decides what you may do. Most breaches of web apps are authorization bugs. Access control
- Break-glass account
- An emergency admin account kept offline and watched closely, used only when normal sign-in is broken. Identity
- CSP (Content Security Policy)
- A response header that tells the browser which sources of script, style and frames to allow. JS security
- CVE and CVSS
- A CVE is the public id of one known vulnerability; CVSS scores how severe it is from 0 to 10. Supply chain
- Defence in depth
- Several independent layers of protection, so one failure does not expose everything. Attacker mindset
- Detection rule
- A saved query over logs that raises an alert when it matches suspicious activity. Detections
- EDR
- Endpoint detection and response: an agent on each device that records activity and can isolate the device. SOC tour
- False positive
- An alert that fired on harmless activity; too many and analysts start ignoring alerts. Triage
- IDOR
- Insecure direct object reference: changing an id in a request gets you someone else's record. Access control
- Indicator of compromise (IOC)
- A trace of known bad activity, such as a file hash, domain or IP address. Threat hunting
- Least privilege
- Every person, service and token gets only the access its job needs, for only as long as needed. Identity
- MFA
- Multi-factor authentication: a second proof besides the password, such as a passkey or an app code. Identity
- MITRE ATT&CK
- A public catalogue of attacker techniques, used to map which ones your detections cover. Detections
- Parameterised query
- SQL sent with placeholders and the values separately, so input can never change the query's shape. Injection
- Passkey
- A phishing-resistant login based on a key pair stored on the user's device (FIDO2 and WebAuthn). Identity
- Phishing
- Tricking someone into giving up credentials or running something, usually by email or message. Breaches
- Risk
- How likely something bad is, times how much it would hurt; the basis for deciding what to fix first. Risk and incidents
- SBOM
- Software bill of materials: the list of every component and version inside a build. Supply chain
- Secret scanning
- Automatic search of code and commits for keys and passwords, ideally blocking the push. Pipeline and AI
- SIEM
- Security information and event management: the central place where logs are collected, searched and alerted on. SOC tour
- SOC
- Security operations centre: the team that watches alerts, triages them and responds to incidents. SOC tour
- Supply chain attack
- Getting into your systems through something you depend on: a package, a CI action, a vendor. Supply chain
- Threat model
- A structured look at what you are building, what can go wrong and what you will do about it. Threat modelling
- Trust boundary
- A line in a data-flow diagram where data passes between parts with different levels of trust, such as the internet and your API. Threat modelling
- Zero trust
- Checking identity and device health for every request instead of trusting anything inside the network. Networks and cloud
Courses on Kolom
- Security Foundations: how attackers think, identity, cryptography, networks and risk, without assuming you code.
- Application Security for Developers: access control, injection, sessions, threat modelling and the supply chain in your own code.
- Defensive Security: SOC, Detection and Response: logs, detection rules, triage, hunting and incident response.
- Offensive Security: Ethical Hacking and Pentesting: scoped, legal testing and reports that get fixes made.
What to read next
- OWASP Top 10 at owasp.org/Top10. The list behind the first table, with examples and prevention for each category.
- OWASP Cheat Sheet Series at cheatsheetseries.owasp.org. Short, practical pages on password storage, sessions, CSP, input validation and much more.
- OWASP ASVS at owasp.org. A checklist of security requirements to test an application against, in three levels.
- NIST SP 800-63B at pages.nist.gov. The source of modern password and MFA guidance.
- MITRE ATT&CK at attack.mitre.org. Attacker techniques with detection ideas; pairs with Detections.
- Threat Modeling: Designing for Security by Adam Shostack. The book behind STRIDE practice and the four questions.