BlogSecurity

Code Security Vulnerabilities: Complete Guide

Understand common security vulnerabilities in code, how to detect them, and proven strategies for prevention. Essential knowledge for every developer.

20 min readUpdated December 2025

Why Code Security Matters

Security vulnerabilities in code can lead to data breaches, financial loss, regulatory penalties, and reputation damage. The average cost of a data breach is $4.45 million (IBM, 2023).

70%

of applications have security flaws (Veracode)

6 months

Average time to detect a breach

85%

of breaches involve human error

Common Code Vulnerabilities

SQL Injection (SQLi)

CWE-89Critical

Occurs when untrusted data is sent to an interpreter as part of a command or query. Attackers can read, modify, or delete database data.

Example:

// Vulnerable
const query = "SELECT * FROM users WHERE id = " + userId;

// Secure (parameterized)
const query = "SELECT * FROM users WHERE id = ?";
db.query(query, [userId]);

Prevention:

  • Use parameterized queries or prepared statements
  • Use ORM frameworks that handle escaping
  • Validate and sanitize all input
  • Apply principle of least privilege to DB accounts

Cross-Site Scripting (XSS)

CWE-79High

Allows attackers to inject malicious scripts into web pages viewed by other users. Can steal cookies, session tokens, or deface websites.

Example:

// Vulnerable
element.innerHTML = userInput;

// Secure (text only)
element.textContent = userInput;

// Secure (with sanitization)
element.innerHTML = DOMPurify.sanitize(userInput);

Prevention:

  • Encode output based on context (HTML, JS, URL, CSS)
  • Use Content Security Policy (CSP) headers
  • Sanitize HTML input with libraries like DOMPurify
  • Use frameworks that auto-escape by default

Cross-Site Request Forgery (CSRF)

CWE-352Medium

Tricks authenticated users into performing unintended actions. Can change passwords, transfer funds, or modify settings.

Example:

// Protection with CSRF token
<form method="POST">
  <input type="hidden" name="csrf_token" value="{{csrf_token}}">
  <!-- form fields -->
</form>

// Verify on server
if (request.csrf_token !== session.csrf_token) {
  throw new Error('Invalid CSRF token');
}

Prevention:

  • Use anti-CSRF tokens on all state-changing requests
  • Verify Origin and Referer headers
  • Use SameSite cookie attribute
  • Require re-authentication for sensitive actions

Insecure Deserialization

CWE-502Critical

Occurs when untrusted data is used to abuse application logic or achieve remote code execution. Common in Java, PHP, and Python applications.

Example:

// Vulnerable (Python)
data = pickle.loads(user_input)  # Never do this!

// Secure
data = json.loads(user_input)  # Use safe formats
# Validate schema after parsing

Prevention:

  • Never deserialize untrusted data
  • Use simple data formats like JSON
  • Implement integrity checks (signatures)
  • Isolate deserialization in sandboxed environments

Broken Authentication

CWE-287Critical

Weak authentication mechanisms that allow attackers to compromise passwords, session tokens, or exploit implementation flaws.

Example:

// Weak
if (password === storedPassword) { /* OK */ }

// Secure
const match = await bcrypt.compare(password, hashedPassword);

// Session security
app.use(session({
  secret: process.env.SESSION_SECRET,
  cookie: { secure: true, httpOnly: true, sameSite: 'strict' }
}));

Prevention:

  • Use strong password hashing (bcrypt, Argon2)
  • Implement multi-factor authentication
  • Use secure session management
  • Rate limit authentication attempts

Sensitive Data Exposure

CWE-200High

Improper protection of sensitive data like passwords, credit cards, health records. Can occur in transit or at rest.

Example:

// Bad: Sensitive data in logs
console.log(`User ${user.email} with card ${card.number}`);

// Good: Mask sensitive data
console.log(`User ${maskEmail(user.email)}`);

// Good: Encrypt at rest
const encrypted = crypto.encrypt(sensitiveData, key);

Prevention:

  • Encrypt all sensitive data at rest and in transit
  • Don't store sensitive data unnecessarily
  • Use strong encryption algorithms (AES-256)
  • Disable caching for sensitive responses

How to Detect Vulnerabilities

Static Application Security Testing (SAST)

Analyzes source code for vulnerabilities without executing the program.

Tools: Semgrep, SonarQube, Checkmarx, TigerGate
+ Early detection
+ Finds root cause
- False positives
- Can't find runtime issues

Software Composition Analysis (SCA)

Scans dependencies for known vulnerabilities in third-party libraries.

Tools: Snyk, Dependabot, OSV-Scanner, TigerGate
+ Finds dependency vulns
+ CVE database matching
- Only finds known issues
- Doesn't scan your code

Dynamic Application Security Testing (DAST)

Tests running applications by simulating attacks from the outside.

Tools: OWASP ZAP, Burp Suite, Nuclei, TigerGate
+ Finds runtime issues
+ Tests like attacker
- Needs running app
- Can miss code paths

Secrets Detection

Scans code for hardcoded API keys, passwords, and credentials.

Tools: Gitleaks, TruffleHog, detect-secrets, TigerGate
+ Prevents credential leaks
+ Easy to implement
- Limited to known patterns
- Possible false positives

Scan Your Code for Vulnerabilities

TigerGate combines SAST, SCA, secrets detection, and DAST in one platform. Find vulnerabilities before attackers do.

Start Free Security Scan