1. Cheat sheets
  2. Cybersecurity

9 minReference

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.

FlawWhat it looks like at MangroveFixLesson
Broken access controlGET /orders/88123 returns another customer's order; a store manager edits prices for a store that is not theirsCheck 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 wallAccess control
Injection (SQL, command)Product search builds SQL by joining strings from the search boxParameterised queries or the ORM's bound parameters; never pass user input to a shell; least-privilege database userInjection
Cross-site scripting (XSS)A product review is rendered as raw HTML in the back officeLet the framework escape output; avoid innerHTML and dangerouslySetInnerHTML; sanitise any HTML you must keep; add a CSPJS security, Injection
Cross-site request forgery (CSRF)Cookie-authenticated back office accepts a form post from any siteSameSite=Lax or Strict cookies, plus CSRF tokens on state-changing requestsAuth and sessions
Cryptographic failuresPasswords stored with plain SHA-256; an internal API on plain HTTPTLS everywhere with HSTS; a password hash such as Argon2id; encrypt sensitive data at rest; keep less dataCryptography
Insecure designOne-time codes for rider login with no attempt limitThreat model new features; write abuse cases next to user stories; limits and quotas by designThreat modelling
Security misconfigurationDebug mode on in production; a storage bucket left public; default password on a store routerA hardened baseline in code (IaC), reviewed like code; config scanning; remove defaultsNetworks and cloud
Vulnerable componentsAn old npm package with a published CVE in the POS sync serviceLockfiles, npm audit, Dependabot or Renovate, an SBOM, and a patch deadline by severitySupply chain
Authentication failuresNo MFA on the back office; sessions that never expire; unlimited login attemptsMFA, throttling per account and per IP, session timeouts, new session id at loginAuth and sessions, Identity
Integrity failuresCI runs a third-party action by a moving tag; till updates are not signedPin actions to a commit SHA; protected branches and required reviews; signed builds and updatesPipeline and AI, Supply chain
Logging and monitoring failuresFailed logins are not logged; nobody hears about 5,000 of them in an hourLog security events centrally, alert on them, and test that the alert firesLogs, Detections
Server-side request forgery (SSRF)"Import product image from URL" can be pointed at internal addressesAllowlist hosts; block private ranges and the cloud metadata address; do not follow redirects blindlyInjection, Networks and cloud
Prompt injection in AI featuresA supplier document tells the shopping assistant to reveal other customers' dataTreat model output as untrusted; the model gets only the caller's permissions; human confirmation for risky tool callsPipeline 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.

DecisionDoAvoidLesson
Storing passwordsArgon2id, scrypt or bcrypt, with the salt the library addsMD5, SHA-1, SHA-256 alone, or reversible encryptionCryptography
Password rulesLength 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 questionsIdentity
Login errorsOne generic message ("email or password is wrong"); throttle per account and IPMessages that reveal which accounts existAuth and sessions
Session cookieHttpOnly; Secure; SameSite=Lax; new id after login; idle and absolute timeoutsSession ids in URLs; tokens in localStorage for sensitive appsAuth and sessions
JWT access tokensShort lifetime (minutes); verify signature with an allowlist of algorithms; check exp, aud, issSecrets in the payload (it is only encoded); accepting alg: none; tokens that live for weeksAuth and sessions
Refresh tokensRotate on every use; revoke the family if an old one comes backOne long-lived token that never changesAuth and sessions
MFAPasskeys or security keys (FIDO2, WebAuthn) first, then an authenticator appSMS codes for admins; MFA prompts users approve without thinkingIdentity
Password resetSingle-use random token, short expiry, same answer whether or not the email existsReset links that never expire or can be guessedAuth and sessions
Login for SPAs and mobile appsOAuth 2 Authorization Code flow with PKCEThe implicit flow; the app holding a client secretIdentity
Authorization checksOn the server, per request, per object, in one shared placeHiding buttons in the UI and calling it doneAccess 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.

HeaderStarting valueWhat it stopsLesson
Strict-Transport-Securitymax-age=31536000; includeSubDomains (add preload only when every subdomain is HTTPS)Downgrade to plain HTTP on hostile Wi-FiSecurity
Content-Security-Policydefault-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'Limits what injected script can load and run; clickjackingJS security
X-Content-Type-OptionsnosniffBrowsers guessing that an upload is a scriptJS security
Referrer-Policystrict-origin-when-cross-originFull URLs, with ids or tokens, leaking to other sitesJS security
Permissions-Policycamera=(), microphone=(), geolocation=() for features you do not useEmbedded or injected code using device featuresJS security
X-Frame-OptionsDENY (older browsers; CSP frame-ancestors replaces it)Your page framed by another siteJS security
CORS (Access-Control-Allow-Origin)An exact list of your own originsOther sites reading responses meant for your app; * never works with credentialsAccess 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.

NeedUseAvoidLesson
Data in transitTLS 1.2 or 1.3 (prefer 1.3)SSL, TLS 1.0 and 1.1, turning off certificate checksCryptography
Encrypt data at restAES-256-GCM through a library or KMS, with envelope encryptionECB mode, reused nonces, keys in the codeCryptography
Random tokens and idscrypto.randomBytes(32), crypto.randomUUID()Math.random(), timestamps, countersCryptography
Integrity hashSHA-256 or SHA-3MD5 and SHA-1 for anything security relatedCryptography
Webhook or message signatureHMAC-SHA256, compared with crypto.timingSafeEqualA plain hash; comparing with ==Cryptography
Digital signaturesEd25519 or ECDSA P-256; RSA with 2048-bit keys or longerRSA 1024; homemade paddingCryptography
Key storageKMS, HSM or a secret manager, with rotation and access logsKeys in the repo, in images or in shared chatCryptography

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).

LetterAskMangrove exampleTypical control
SpoofingCan someone pretend to be a user, device or service?A laptop pretends to be till 3 at store S-014Authentication; device certificates or mTLS
TamperingCan data be changed in transit or at rest?Sales batches edited before uploadTLS, signatures, database permissions, checksums
RepudiationCan someone deny doing it?"I never approved that price change"Audit logs with who, what, when; logs the actor cannot edit
Information disclosureCan data leak to the wrong person?Order history visible across partner shopsAccess control, encryption, keeping less data
Denial of serviceCan it be overwhelmed or starved?Bots hammer the festival-sale endpointRate limits, quotas, timeouts, autoscaling, a CDN
Elevation of privilegeCan someone gain rights they should not have?A cashier account calls an admin APIServer-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).

SourceEvents to keepWhyLesson
Identity providerSign-ins, failed MFA, new MFA device, risky or impossible-travel sign-insMost intrusions start with a stolen accountIdentity, Logs
App and APILogin success and failure, 403s, password resets, role changes, bulk exports, admin actionsShows abuse that looks like normal trafficLogs
Cloud control planeNew access keys, policy changes, resources made public, logging turned offThe attacker's first moves in the cloudNetworks and cloud
Windows Security log4624 logon, 4625 failed logon, 4720 user created, 4728 and 4732 added to a security group, 4688 process created, 1102 log clearedAccount misuse and tracks being coveredLogs, Detections
Linux auth logs/var/log/auth.log (Debian, Ubuntu) or /var/log/secure (RHEL family); journalctl on systemd hostsSSH logins, sudo use, new usersLogs
Endpoint (EDR)Process trees, new services and scheduled tasks, PowerShell script block logsWhat actually ran on the laptop or tillDetections
DNS, proxy, firewallLookups and connections, especially to new or rare domainsCommand-and-control and data leavingThreat 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).

StepAskLook atLesson
1. Real?True positive, false positive or benign true positive?The rule's logic and the raw event, not only the alert titleTriage
2. Who and what?Which user, host, data and how important are they?Asset list, user role, whether this is normal for themTriage
3. What else?What happened around it?A timeline an hour either side for the same user, host and IPTriage, Threat hunting
4. How bad?Data touched, privileges gained, other hosts involved?Severity guide, scope across the estateTriage
5. What now?Close with a reason, escalate, or contain?Runbook for this alert; tune the rule if it was noiseDetections, 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.

PhaseDoDo notLesson
PrepareContact list, runbooks, log retention, tested backups, practice drillsWrite the plan during the incidentRisk and incidents
Detect and analyseDeclare early, name an incident lead and a scribe, open one channel and one timelineInvestigate quietly for days before telling anyoneIncident response
ContainDisable the account, revoke sessions, isolate the host through EDR, rotate exposed keysWipe machines before you have collected evidenceIncident response
Eradicate and recoverRemove the foothold, patch the hole, restore from known-good backups, watch closelyBring systems back before the way in is closedIncident response
LearnBlameless review, actions with owners and dates, new detectionsClose 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.

WhatValueUse it toLesson
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.9Set patch deadlines; then adjust for exposure and known exploitationSupply chain
GDPR breach noticeWithin 72 hours of becoming aware, to the supervisory authorityStart the legal clock on day one, if you handle EU personal dataRisk and incidents
Argon2id minimum (OWASP)19 MiB memory, 2 iterations, 1 laneConfigure the password hashCryptography
bcrypt work factor (OWASP)10 or moreConfigure legacy systems that use bcryptCryptography
Random token sizeAt least 128 bits; 32 random bytes is commonSize reset tokens, API keys and session idsCryptography
HSTS max-age31,536,000 seconds = one yearSet the header valueSecurity
TOTP codes6 digits, a new one every 30 secondsExplain why a code "expired" and why clocks must be rightIdentity

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

  • 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.