Cyber crime prevention and application security
Practical notes on preventing cyber crime and securing applications: principles, common vulnerabilities, secure development practices, formulas for risk and password entropy, worked examples and exam tips.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use these ideas when they design, build and operate software so that attackers cannot steal data, break services or bypass controls. Application security and cybercrime prevention reduce financial loss, legal risk and damage to reputation by stopping common attack paths early in the software lifecycle.
Key ideas
Start from definitions (each bold term is defined first time it appears):
- Vulnerability — a weakness in software, hardware, process or configuration that can be exploited to violate security. Example: a missing input check that allows SQL injection.
- Threat — a potential cause of an unwanted incident that may result in harm. Example: an attacker using stolen credentials.
- Risk — the expected harm from threats exploiting vulnerabilities. (Formal formula in Formulas.)
- Authentication — proving identity (something you know, have, or are). Examples: passwords, tokens, biometrics.
- Authorization — deciding whether an authenticated identity can perform an action or access a resource (often called access control).
- Confidentiality, Integrity, Availability (CIA triad) — foundational security goals: keep data private, correct and available when needed.
- Secure Development Lifecycle (SDLC) — the process steps (requirements, design, implementation, testing, deployment, maintenance) enhanced with security activities (threat modelling, secure coding, security testing, patching).
- Defense-in-depth — using several independent security controls at different layers so a single failure does not lead to compromise. Draw a layered diagram: client browser -> network firewall -> web application firewall (WAF) -> application logic -> database access control; label arrows showing data flow and annotate each layer with its primary control (filtering, authentication, authorization, encryption, logging).
- Least privilege — give users or processes the minimum rights necessary to perform their function. Exact statement to remember: “An entity should have only those privileges necessary to complete its tasks, and no more.” Assumption: privileges can be partitioned.
- Input validation — check that incoming data matches allowed formats before using it. Must be performed server-side (client-side checks are for usability only). Define a whitelist (allow-list) as preferred over blacklist (deny-list).
- Output encoding (contextual encoding) — transform data before placing it in a context (HTML, URL, JavaScript, CSS) so it cannot be interpreted as active code. Example: encode characters before inserting user content in HTML to prevent XSS. For SQL, do not rely on encoding; use parameterized queries/prepared statements.
- Cryptographic hashing — a function mapping data to fixed-length output; a secure hash is preimage-resistant, second-preimage-resistant, and collision-resistant for practical sizes. For passwords use a slow hash (e.g., bcrypt or Argon2id) plus a salt (a per-password random value) and a work factor.
Common web vulnerabilities (explain simply):
- Injection (SQL injection) — untrusted data used to build code/queries. Prevent with parameterized queries / prepared statements.
- Cross-Site Scripting (XSS) — untrusted data included in web pages without proper encoding so browsers execute it. Prevent with output encoding and Content Security Policy (CSP).
- Cross-Site Request Forgery (CSRF) — a site causes a user’s browser to perform actions on another site where the user is authenticated. Prevent with anti-CSRF tokens, SameSite cookies, and double-submit tokens.
- Broken Authentication and Session Management — flaws that let attackers impersonate users. Countermeasures: secure cookies (HttpOnly, Secure, SameSite), session timeouts, multi-factor authentication (MFA).
- Insecure Dependencies — using libraries with known vulnerabilities. Prevent by dependency scanning and timely patching.
Secure coding and operational practices (what to do):
- Threat modelling during design: enumerate assets, threats, and mitigations.
- Use parameterized queries or ORM for database access.
- Validate and canonicalize inputs; perform output encoding by context.
- Enforce authentication, then enforce authorization checks for every action (do not rely on client-side checks or hidden fields).
- Use TLS for transport, verify certificates, disable weak ciphers.
- Store passwords with per-user salts and strong slow hash functions; never store plaintext passwords or use reversible encryption.
- Log security-relevant events and keep logs protected (integrity). Monitor logs for unusual activity.
- Use automated scanning (SAST for source code, DAST for running apps) and regular penetration testing.
- Apply security patches quickly and have an incident response plan.
Diagrams students may be asked to draw and label:
- Defense-in-depth layered stack (label each layer and its controls).
- Sequence diagram of login flow (client -> server: credentials, server -> auth service: validate, server -> client: session token; annotate where TLS applies and where session cookies are set with flags).
Assumptions behind common claims: many security calculations assume independence and uniform distribution (for example, calculating password entropy assumes each character is chosen uniformly and independently from an allowed set). Call out such assumptions when answering exam questions.
Formulas
Risk = Likelihood × Impact — Likelihood can be expressed as a per-year probability (unitless) or as an annualized rate of occurrence (units: 1/year); be explicit which is used. Impact is expected loss (currency, e.g., INR). Applies when modelling expected annual loss.
H = - Σ (p_i · log2 p_i) — Shannon entropy of a discrete source. H in bits. p_i are symbol probabilities. Assumes known probability distribution.
Password entropy (bits) ≈ L · log2(N) — L = password length (symbols), N = size of symbol set (e.g., 62 for [A–Z,a–z,0–9]). Units: bits. Assumes characters independent and uniformly chosen.
Number of guesses to brute force ≈ 2^(entropy) — expected guesses around 2^(entropy-1) for uniform distribution. Units: guesses. Applies for offline attacks when attacker can try candidate guesses quickly (depends on hashing cost and available compute).
No other SI-unit formulas are required here. For code remember parameterized query syntax:
- Java JDBC:
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?"); ps.setString(1, id); - Python DB-API:
cursor.execute("SELECT * FROM users WHERE id = %s", (id,))(placeholder style depends on driver).
Worked examples
- Password entropy (numerical, step-by-step)
Problem: Estimate entropy for an 8-character password chosen from [A–Z,a–z,0–9] (62 symbols) and for a 12-character password from same set.
Steps:
- Use formula
Entropy = L × log2(N). - Compute log2(62). ln(62)=4.127134, ln(2)=0.693147 → log2(62)=4.127134/0.693147 = 5.9542 bits per character.
- For L=8: Entropy = 8 × 5.9542 = 47.6336 bits → 47.63 bits.
- For L=12: Entropy = 12 × 5.9542 = 71.4504 bits → 71.45 bits.
Interpretation: 47.6 bits is moderate strength for online-limited attempts but weak for offline attacks if hashes are fast; 71.5 bits is strong for many scenarios but using a slow hash and salt is still required.
- Risk and residual risk (numerical)
Problem: A vulnerability has yearly likelihood 0.02 (2% chance) of being exploited, and if exploited the organization loses INR 200,000. A control reduces likelihood by 75% but costs INR 10,000 per year to operate. Compute annual expected loss before and after control and net benefit.
Steps:
- Base expected loss = Likelihood × Impact = 0.02 × 200,000 = 4,000 INR per year.
- New likelihood after control = 0.02 × (1 - 0.75) = 0.005.
- New expected loss = 0.005 × 200,000 = 1,000 INR per year.
- Total annual cost after control = expected loss + control cost = 1,000 + 10,000 = 11,000 INR.
- Compare: without control cost = 4,000 INR; with control = 11,000 INR. Net benefit = 4,000 - 11,000 = -7,000 → control is not cost-effective at these numbers.
Answer: The control reduces risk but increases total cost; decision depends on non-financial factors too (compliance, reputation).
- SQL injection prevention (algorithmic trace)
Vulnerable query (pseudocode):
sql = "SELECT * FROM users WHERE username = '" + userInput + "' AND password = '" + passInput + "'"
If attacker input userInput = admin' -- and passInput = anything, result becomes:
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything'
SQL treats -- as comment; password condition removed; attacker may login as admin.
Safe version (parameterized):
- Java:
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?"); ps.setString(1, userInput); ps.setString(2, passInput);Trace: driver sends statement with placeholders and binds values; the DB treats values only as data, not code, preventing injection.
Common mistakes
- Using predictable salts (not per-user random salts) or fast hashes (MD5, SHA-1) for passwords.
- Omitting authorization checks on server APIs and assuming the client enforces them.
- Improper use of TLS: leaving certificate validation off (e.g., ignoring hostname mismatch or trusting all certificates in development builds) or allowing weak ciphers.
- Performing input sanitization by blacklists only (attackers find bypasses); prefer allow-lists.
- Not rotating keys or credentials, and not logging authentication failures properly.
For your exam
Types of questions you will see: definitions (state and explain terms like vulnerability, threat, risk), short notes (describe secure SDLC, defense-in-depth), derivations (derive password entropy formula from Shannon entropy), numerical problems (compute expected loss or password entropy), code/algorithm tracing (show how SQL injection works and how prepared statements prevent it), and diagram questions (draw a layered defense diagram or login sequence).
What full-marks answers include:
- Clear definitions of bolded terms.
- Explicit assumptions (e.g., uniform choice when computing entropy).
- Step-by-step derivations or calculations with units and final labelled result.
- For code/diagram questions: labelled diagrams or code snippets that show the vulnerable and fixed versions and a short explanation of why the fix works.
Quick check
- Define "salt" for password storage in one line.
- Write the formula for expected annual loss from a threat.
- Give two server-side controls that prevent XSS.
Answers: 1) A salt is a per-password random value stored with the hash so identical passwords produce different hashes. 2) Risk = Likelihood × Impact. 3) Output encoding by context (HTML-escape) and Content Security Policy (CSP).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?