Static Code Analysis (SAST)

Static Application Security Testing (SAST) analyzes source code, bytecode, or binaries to identify vulnerabilities before the application runs. SAST catches security flaws early in development by scanning code for unsafe patterns, insecure functions, logic errors, injection flaws, insecure configurations, and coding mistakes. It integrates directly into the shift-left development workflow and prevents vulnerabilities from ever entering the build pipeline.

Why SAST Is Critical

Most vulnerabilities originate in source code. SAST identifies them during coding or in CI, long before attackers or penetration testers find them. SAST reduces remediation cost, improves developer awareness, and enforces secure coding practices automatically. It also provides consistent enforcement across teams, independent of developer skill levels.

SAST prevents:

• SQL injection
• Command injection
• XSS
• Insecure deserialization
• Hardcoded secrets
• Weak crypto functions
• Path traversal
• Insecure file operations
• Unsafe subprocess calls
• Logic flaws
• Missing validation

SAST becomes a mandatory security gate in DevSecOps.

How SAST Works

Static Analysis Engine

The engine reads source code and identifies patterns based on security rules, heuristics, and data-flow analysis. It does not execute the code.

Pattern Matching

SAST tools detect known insecure functions, bad coding patterns, weak methods, and dangerous libraries.

Data Flow Tracking

Data movement from input to output is analyzed to identify injection paths or unvalidated flows.

Taint Analysis

Tools track untrusted input and detect if it reaches dangerous sinks such as SQL queries, file writes, or command execution.

Control Flow Analysis

Logic paths are checked for unsafe behavior or missing validation.

Custom Rules

Teams can define their own patterns and guidelines.


What SAST Should Detect

Input Validation Flaws

Missing validation or sanitization.

Injection Vulnerabilities

SQL, LDAP, command, template, and OS injection.

Cryptographic Issues

Weak algorithms, insecure randomness, hardcoded keys.

Access Control Flaws

Missing authorization checks.

Memory Handling Issues

Buffer overflows, unsafe memory usage (C/C++).

Code Quality Issues

Dead code, insecure defaults, error handling gaps.

Hardcoded Secrets

Tokens, passwords, API keys.

Unsafe Dependencies

Usage of risky libraries or functions.

Dangerous Functions

eval, exec, system, pickle, unescaped queries.


SAST Workflow in Secure Development

  1. Developer writes code

  2. Local scans detect issues immediately

  3. CI runs full SAST on each commit

  4. Merge request blocked if issues exceed threshold

  5. Developers fix issues

  6. SAST runs again

  7. Code merges only when secure

  8. Reports stored for auditing

  9. Policy gates enforce security rules

This creates a secure loop of continuous enforcement.


Selecting the Right SAST Tool

Common options:

• Bandit (Python)
• Semgrep (multi-language)
• ESLint security plugins (JavaScript)
• SonarQube
• CodeQL
• Brakeman (Rails)
• Flawfinder (C/C++)

Choose based on:

• Language support
• Rule coverage
• CI integration
• Custom rule capabilities


Understanding SAST Outputs

True Positives

Real vulnerabilities that must be fixed.

False Positives

Noise produced by pattern-only detection.

Severity Levels

Critical, high, medium, low.

CWE Mapping

Each finding maps to a CWE category to help understand vulnerability type.

File and Line Location

Shows exactly where to fix the issue.


Best Practices for SAST

Shift Left Hard

Run SAST in local environment and pre-commit hooks.

Fail Fast

Block merges when critical or high issues exist.

Custom Rules

Add organizational rules such as:

• No direct SQL strings
• No eval usage
• No plaintext secrets
• Only approved crypto algorithms

Integrate With CI/CD

Guarantee scanning on every commit.

Enforce Code Review

Review both SAST results and code context.

Remediate Quickly

Fix issues immediately to avoid backlog.


How SAST Fits With Other Testing

SAST complements:

• SCA (dependency scanning)
• DAST (runtime testing)
• IaC scanning
• Secret scanning

Together, they provide full coverage.


Extensive Practical Section

The following practicals provide full hands-on coverage of SAST setup, usage, automation, and rule development.


Practical 1: Install and Run Bandit on a Python Project

Install:

pip install bandit

Run scan:

bandit -r src/

Study findings:

• Hardcoded passwords
• risky functions
• insecure temp files
• unsafe file handling

Fix all issues.


Practical 2: Set Up Semgrep for Multi-Language Scanning

Install:

pip install semgrep

Scan code:

semgrep --config auto .

Review flagged patterns across languages.


Practical 3: Add SAST to Pre-Commit Hooks

Create:

.pre-commit-config.yaml

Add:

- repo: https://github.com/PyCQA/bandit
  rev: stable
  hooks:
    - id: bandit

Test by committing unsafe code.


Practical 4: Detect Insecure Python Code With Semgrep Rules

Create rule file:

rules:
- id: no-eval
  pattern: eval(...)
  message: "Avoid eval"
  severity: ERROR
  languages: [python]

Run:

semgrep --config rules.yaml src/

Add more rules as needed.


Practical 5: Scan JavaScript Code With ESLint Security Plugins

Install:

npm install eslint eslint-plugin-security --save-dev

Add to .eslintrc:

"plugins": ["security"]

Scan:

npx eslint .

Fix insecure JS patterns.


Practical 6: Use CodeQL for Deep Semantic Analysis

Initialize CodeQL:

codeql database create db --language=python --source-root=.

Run analysis:

codeql database analyze db codeql/python-security.qls --format=sarif --output=results.sarif

Review SARIF output.


Practical 7: Identify Hardcoded Secrets

Add Semgrep rule:

patterns:
  - pattern: $SECRET = "...*..."

Scan code for exposed secrets.


Practical 8: Create Custom Organizational SAST Rules

Develop rules for:

• Disallow direct SQL strings
• Enforce parameterized queries
• Enforce secure crypto
• Ban subprocess without args array
• Ban insecure HTTP clients

Integrate into SAST engine.


Practical 9: Add SAST to GitHub Actions

Workflow:

- name: Run SAST
  uses: snyk/actions/python@master

Fail pipeline on high severity issues.


Practical 10: Add SAST to GitLab CI

sast:
  stage: test
  script:
    - semgrep --config auto .

Block merge requests with critical issues.


Practical 11: Review and Fix SAST Reports

Choose three flagged issues:

• SQL injection risk
• Hardcoded token
• Insecure file open

Fix code, rerun SAST, ensure clean results.


Practical 12: Build CI SAST Gate

Add rule:

if bandit finds > 0 CRITICAL:
    fail pipeline

Allow warnings but block severe issues.


Practical 13: Integrate SAST With Developer IDEs

Install plugins:

• Semgrep VS Code extension
• SonarLint
• ESLint

Scan code while typing.


Practical 14: Write a Secure Refactoring Exercise

Take vulnerable code:

query = "SELECT * FROM users WHERE name = '" + name + "'"

Refactor:

cursor.execute("SELECT * FROM users WHERE name = %s", (name,))

Run SAST before and after.


Practical 15: Validate That No Dangerous Functions Exist

Search for:

• eval
• exec
• subprocess with shell=True
• os.system

Run SAST tools that flag these patterns.


Practical 16: SAST on Infrastructure Code

Scan IaC files:

semgrep --config p/terraform .

Find misconfigurations that lead to security issues.


Practical 17: Enforce Mandatory SAST Review in PRs

Every merge request includes:

• SAST report
• Developer fix notes
• Reviewer approval

Add rule in repository settings.


Practical 18: Build a SAST Reporting Dashboard

Aggregate results:

• Date
• File
• Severity
• CWE
• Fixed or not
• Assignee

Track metrics across releases.


Practical 19: Train Developers Using SAST Findings

Create training material using:

• Real issues
• Root causes
• How to avoid them
• Secure patterns

Store under /secure-dev/training/.


Practical 20: Build Full SAST Architecture Diagram

Include:

• Developer IDE scanning
• Pre-commit hooks
• Local scanning
• CI scanning
• Policy gates
• Reporting system
• Alerting
• Dashboard

This becomes part of DevSecOps design.


Intel Dump

• SAST analyzes code statically to detect security flaws early
• It catches injection, unsafe functions, insecure cryptography, hardcoded secrets, authorization gaps, and logic flaws
• Tools include Bandit, Semgrep, SonarQube, CodeQL, ESLint security, Brakeman, and Flawfinder
• SAST integrates into local workflows, IDEs, pre-commit hooks, and CI/CD pipelines
• Practical work includes SAST installation, custom rules, CI integration, semantic analysis, secret detection, dependency enforcement, PR gating, secure refactoring, and dashboard creation

HOME LEARN COMMUNITY DASHBOARD