Skip to main content

Shift Left Security


1 - The Shift Left concept

1.1 Definition

Shift Left = Move security activities toward the start of the development lifecycle.

1.2 Benefits

BenefitImpact
Reduced cost100x cheaper than in production
Shorter timeNo feedback at the end of the cycle
Improved qualityLess technical debt
CultureSecurity-aware developers

2 - Threat Modeling

2.1 STRIDE methodology

2.2 Threat Modeling process

threat_modeling_steps:
1_decompose:
- Identify the components
- Define the trust boundaries
- Map the data flows

2_identify_threats:
- Apply STRIDE to each component
- Document the attack scenarios
- Assess the likelihood

3_mitigate:
- Define the controls
- Prioritize by risk
- Assign to teams

4_validate:
- Verify the implementation
- Security tests
- Periodic review

2.3 Example Threat Model

# threat-model.yaml
application: E-Commerce API
version: 1.0
date: 2024-01-15

components:
- name: API Gateway
type: entry_point
threats:
- type: Spoofing
description: "Attacker spoofs a user's identity"
mitigation: "OAuth2 + MFA"
status: mitigated
- type: DoS
description: "Request flood"
mitigation: "Rate limiting + WAF"
status: mitigated

- name: Database
type: data_store
threats:
- type: Information Disclosure
description: "Unauthorized access to data"
mitigation: "Encryption at rest + RBAC"
status: mitigated
- type: Tampering
description: "Data modification"
mitigation: "Audit logs + Integrity checks"
status: in_progress

trust_boundaries:
- name: Internet to DMZ
controls: [WAF, IDS, TLS]
- name: DMZ to Internal
controls: [Firewall, mTLS]

3 - Security Requirements

3.1 Secure User Stories

# User Story Template with Security

**As a** [role]
**I want** [action]
**So that** [benefit]

## Acceptance criteria
- [ ] Functional criterion 1
- [ ] Functional criterion 2

## Security criteria
- [ ] Authentication required
- [ ] Authorization verified (RBAC)
- [ ] Input validated and sanitized
- [ ] Sensitive data encrypted
- [ ] Audit log generated

3.2 Security Requirements Checklist

# Based on OWASP ASVS
authentication:
- Multi-factor authentication support
- Secure password storage (bcrypt/argon2)
- Session management secure
- Account lockout after failures

authorization:
- Role-based access control
- Principle of least privilege
- API authorization on all endpoints
- Resource-level permissions

data_protection:
- Encryption at rest (AES-256)
- Encryption in transit (TLS 1.3)
- PII handling compliant
- Secure key management

input_validation:
- Input validation on all inputs
- Output encoding
- SQL injection prevention
- XSS prevention

logging:
- Security events logged
- No sensitive data in logs
- Log integrity protected
- Centralized logging

4 - Secure Coding Guidelines

4.1 Top 10 rules

RuleDescription
1. Input ValidationValidate all inputs
2. Output EncodingEncode outputs (XSS)
3. Parameterized QueriesPrevent SQL injection
4. AuthenticationRobust authentication
5. Access ControlStrict access control
6. CryptographyModern and correct crypto
7. Error HandlingNo sensitive info in errors
8. LoggingLog security events
9. Data ProtectionProtect sensitive data
10. HTTP SecurityHTTP security headers

4.2 Secure code examples

# ❌ BAD - SQL Injection
query = f"SELECT * FROM users WHERE id = {user_id}"

# ✅ GOOD - Parameterized Query
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
// ❌ BAD - XSS
element.innerHTML = userInput;

// ✅ GOOD - Encoding
element.textContent = userInput;
# ❌ BAD - Hardcoded secret
api_key = "sk-12345secret"

# ✅ GOOD - Environment variable
api_key = os.environ.get("API_KEY")

5 - Security Code Review

5.1 Review checklist

## Security Code Review Checklist

### Authentication & Authorization
- [ ] Authentication required for sensitive endpoints
- [ ] Authorization verified server-side
- [ ] Secure session management

### Input/Output
- [ ] All inputs validated
- [ ] Outputs encoded correctly
- [ ] Secure file uploads

### Data
- [ ] Sensitive data encrypted
- [ ] No hardcoded secrets
- [ ] PII handled correctly

### Error Handling
- [ ] Errors do not reveal sensitive info
- [ ] Exceptions handled cleanly

### Logging
- [ ] Security events logged
- [ ] No sensitive data in the logs

5.2 Automation with Semgrep

# .semgrep.yml
rules:
- id: hardcoded-password
patterns:
- pattern: password = "..."
message: "Hardcoded password detected"
severity: ERROR

- id: sql-injection
patterns:
- pattern: |
$QUERY = f"... {$VAR} ..."
$CURSOR.execute($QUERY)
message: "Potential SQL injection"
severity: ERROR

- id: insecure-hash
patterns:
- pattern: hashlib.md5(...)
- pattern: hashlib.sha1(...)
message: "Use SHA-256 or better"
severity: WARNING

6 - Pre-commit Hooks

6.1 Configuration

# .pre-commit-config.yaml
repos:
# Secrets detection
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks

# Security linting
- repo: https://github.com/PyCQA/bandit
rev: 1.7.5
hooks:
- id: bandit
args: ['-r', 'src/', '-ll']

# Semgrep
- repo: https://github.com/returntocorp/semgrep
rev: v1.50.0
hooks:
- id: semgrep
args: ['--config', 'auto', '--error']

6.2 Installation

# Install pre-commit
pip install pre-commit

# Install the hooks
pre-commit install

# Run manually
pre-commit run --all-files

7 - IDE Security Plugins

IDEExtensionFunction
VS CodeSnykSCA + SAST
VS CodeGitLens + GitLeaksSecrets
VS CodeSonarLintSAST
IntelliJSnykSCA + SAST
IntelliJSonarLintSAST

7.2 VS Code configuration

// settings.json
{
"sonarlint.rules": {
"typescript:S2068": {
"level": "on" // Hardcoded credentials
},
"typescript:S5542": {
"level": "on" // Encryption mode
}
},
"snyk.features.openSourceSecurity": true,
"snyk.features.codeSecurity": true
}

Summary

In this chapter, we learned:

  • The Shift Left concept
  • Threat Modeling with STRIDE
  • Security Requirements
  • Secure Coding Guidelines
  • Security Code Review
  • Pre-commit Hooks
  • IDE Security Plugins

Next step

In the next chapter, we will look at SAST and DAST.

→ Next chapter: SAST and DAST


← Back to table of contents