Skip to content
Singahi

Compliance · guide

ISO 27001 A.8.28: Secure Coding

53 min read

Share
On this page

Quick Reference (60 Seconds)

Control: A.8.28, Secure Coding
Purpose: Ensure software is written securely, preventing common vulnerabilities from being introduced into applications through insecure coding practices.
ISO 27002 attributes: Control type: Preventive · Properties: Confidentiality, Integrity, Availability · Concepts: Protect · Capabilities: Application security, System and network security · Domains: Protection
Who it applies to: All organizations that develop software in-house, customize third-party software, or manage outsourced development.
Minimum viable actions:

  • Adopt a secure coding standard (e.g., OWASP, CERT, MISRA)
  • Train all developers on secure coding practices
  • Implement automated SAST in CI/CD pipeline
  • Conduct manual code review for security-critical code
  • Maintain a secure coding policy with language-specific guidelines

Key deliverables: Secure Coding Policy, Secure Coding Standard (per language), SAST Configuration, Code Review Checklist, Developer Training Records.

Audit questions you should be able to answer:

  • What secure coding standard does your organization follow?
  • How are developers trained on secure coding?
  • What automated tools check code for security vulnerabilities?
  • How do you handle code review for security?

What the Control Asks For

Do you need this control?

A.8.28 is not mandatory in itself: under clause 6.1.3 you include it if your risk assessment calls for it, and record the decision in your Statement of Applicability. Include it if you write code, including scripts, infrastructure as code and low-code workflows. If you develop nothing, you can exclude it with that reason.

Annex A 8.28 asks organizations to apply secure coding principles to software development.

What ISO 27002:2022 Adds

ISO/IEC 27002:2022 (8.28), paraphrased:

General. Set organisation-wide governance for secure coding and a minimum secure baseline, extended to third-party and open-source components. Watch real-world threats and current vulnerability advice and use them to keep improving your coding principles.

Planning and before coding. Apply the principles to new code and reused code, in-house and for products you supply to others. Prepare:

  • expectations and approved principles for in-house and outsourced code;
  • knowledge of common and historical coding defects that lead to vulnerabilities;
  • development tools, such as IDEs, configured to help enforce secure code;
  • guidance from tool and platform providers, and up-to-date tools (for example compilers);
  • developers qualified to write secure code;
  • secure design and architecture, including threat modelling;
  • secure coding standards, mandated where relevant;
  • controlled development environments.

During coding. Use language-specific secure practices; secure techniques such as pair programming, refactoring, peer review, security iterations and test-driven development; structured programming; documented code with defects removed; and prohibit insecure techniques such as hard-coded passwords, unapproved code samples and unauthenticated web services. Test during and after development (8.29); SAST helps. Before go-live, evaluate the attack surface and least privilege, and check that the most common programming errors have been mitigated.

Review and maintenance. Package and deploy updates securely; handle reported vulnerabilities (8.8); log errors and suspected attacks and review the logs to improve the code; protect source code from unauthorised access and tampering (version control, 8.4).

External tools and libraries. Keep an inventory of libraries and versions and update them; choose well-vetted components, especially for authentication and cryptography; check licence, security and history; use maintainable software from reputable sources; and make sure development resources stay available long enough.

Modifying a vendor package. Consider the risk to built-in controls, vendor consent, getting the change as a standard vendor update, who maintains it afterwards, and compatibility.

What the Standard Does NOT Require

  • The standard does not mandate specific programming languages or frameworks
  • It does not require 100% vulnerability-free code (impossible), but rather systematic prevention and detection
  • It does not specify particular tools, but requires that code security analysis be performed
  • It does not require manual review of every line of code, but rather risk-based review

Why Secure Coding Matters

The Vulnerability Epidemic

The OWASP Top 10 and the CWE Top 25 show how many serious vulnerabilities start in code. The current OWASP Top 10:2025 (final release January 2026) is:

  • A01 Broken Access Control (now including server-side request forgery)
  • A02 Security Misconfiguration
  • A03 Software Supply Chain Failures
  • A04 Cryptographic Failures
  • A05 Injection (including cross-site scripting)
  • A06 Insecure Design
  • A07 Authentication Failures
  • A08 Software or Data Integrity Failures
  • A09 Security Logging and Alerting Failures
  • A10 Mishandling of Exceptional Conditions

Many tools and contracts still reference the 2021 edition (A01 Broken Access Control, A02 Cryptographic Failures, A03 Injection, A04 Insecure Design, A05 Security Misconfiguration, A06 Vulnerable and Outdated Components, A07 Identification and Authentication Failures, A08 Software and Data Integrity Failures, A09 Security Logging and Monitoring Failures, A10 SSRF). Say which edition your standard uses. Most of these are prevented or caught by secure coding, review and testing. Some (insecure design, misconfiguration) also need A.8.27 and A.8.9.

The Indian Context

Indian organizations face unique secure coding challenges:

  • Startup ecosystem: many startups build applications with limited security expertise
  • Outsourcing hub: Indian developers write code for global clients; secure coding is a competitive advantage
  • Digital India: Government applications processing citizen data (Aadhaar, UPI) require bulletproof code
  • Fintech growth: payment applications in card scope must meet PCI DSS v4.0.1 Requirement 6; the RBI Master Direction on Digital Payment Security Controls (2021) sets application security requirements (it applies to banks, small finance banks, payments banks and credit-card-issuing NBFCs; fintechs working with them usually inherit it through contracts)
  • AI/ML adoption: Indian enterprises building AI/ML applications need secure coding for model serving, data pipelines, and inference
  • Skill gap: Computer science curricula in India often lack sufficient secure coding training
  • DPDP Act 2023: code must implement notice, consent and erasure (s.5, s.6, s.8(7)) and the reasonable security safeguards in s.8(5)
  • AI coding assistants: now common in Indian engineering teams; see the AI-assisted coding rules below

Scope and Applicability

In Scope

This control applies to:

  • All in-house developed code: Web applications, mobile apps, APIs, microservices, batch jobs, scripts
  • Customized third-party code: Modifications to COTS, plugin development, theme customization
  • Infrastructure code: Terraform, CloudFormation, Ansible, Kubernetes manifests
  • Database code: Stored procedures, triggers, functions, queries
  • Client-side code: JavaScript, TypeScript, mobile client code, desktop applications
  • AI/ML code: Model training scripts, inference code, data preprocessing, pipeline code
  • Embedded/IoT code: Firmware, device drivers, edge computing code
  • Outsourced code: Code written by vendors, contractors, or offshore teams

Out of Scope (with caveats)

  • Unmodified third-party code: COTS software, SaaS (but configuration is in scope)
  • Generated code: Code generated by frameworks or tools (but the generation process and templates are in scope)
  • Configuration-only changes: Settings, permissions, feature flags (covered by A.8.9)
  • Documentation-only changes: No code impact

Caveat: If you customize third-party code, the customizations are in scope. If you generate code from templates, the templates and generation logic are in scope.

Applicability by Organization Type

Organization TypeApplicabilityTypical Coding Focus
Software product companiesCriticalSaaS code, API code, mobile apps, client code
Financial servicesCriticalBanking applications, payment processing, trading systems
HealthcareCriticalPHI handling code, clinical systems, telemedicine apps
E-commerceCriticalPayment code, customer data handling, inventory systems
GovernmentCriticalCitizen portals, Aadhaar integration, UPI code
ManufacturingHighOT/IT integration code, IoT firmware, supply chain apps
StartupsHighCloud-native code, rapid development, API-first
NGOsModerateDonor management, grant processing, web applications

Key Definitions and Terminology

TermDefinition
Secure CodingThe practice of writing software code in a way that guards against the introduction of security vulnerabilities
Static Application Security Testing (SAST)Analysis of source code or compiled code to find security vulnerabilities without executing the code
Dynamic Application Security Testing (DAST)Testing of running applications to find security vulnerabilities by simulating attacks
Software Composition Analysis (SCA)Analysis of third-party and open-source components for known vulnerabilities
Code ReviewThe systematic examination of source code by humans to find bugs, security flaws, and violations of coding standards
Security Code ReviewA specialized code review focused on identifying security vulnerabilities
Input ValidationThe process of ensuring that user input conforms to expected format, type, and range before processing
Output EncodingThe process of converting data into a safe format before displaying it to prevent injection attacks
Parameterized QueryA database query where user input is passed as parameters rather than concatenated into the query string
Secure Session ManagementPractices for creating, managing, and destroying user sessions securely
CWE (Common Weakness Enumeration)A community-developed list of common software and hardware weakness types
OWASP Top 10The ten most critical web application security risks
Defensive CodingWriting code that continues to function correctly even in unexpected circumstances
Fail-Safe DefaultsDefaulting to the most secure option when configuration is ambiguous or missing
Code LintingAutomated checking of source code for programmatic and stylistic errors
CI/CD PipelineContinuous Integration/Continuous Deployment pipeline that automates building, testing, and deploying code

Relationship to Other Controls

ControlRelationship
A.5.21, ICT supply chainThird-party and open-source components
A.5.32, Intellectual property rightsLicences of libraries and code samples
A.6.3, Awareness, education and trainingSecure-coding training for developers
A.8.4, Access to source codeProtect code from unauthorised access and tampering
A.8.8, Management of technical vulnerabilitiesHandling reported vulnerabilities in your code
A.8.9, Configuration managementSecure defaults and configuration in code
A.8.15 / A.8.16, Logging; monitoringLogging errors and suspected attacks
A.8.24, Use of cryptographyCorrect use of cryptographic libraries
A.8.25, Secure development life cycleSecure coding is a core SDLC phase
A.8.26, Application security requirementsCode implements the requirements
A.8.27, Secure system architectureCode implements the design
A.8.29, Security testingSAST, DAST and review verify the code
A.8.30, Outsourced developmentSame rules for supplier code
A.8.32, Change managementSecure packaging and deployment of updates

Framework Mapping

FrameworkRelevant Control / Reference
NIST CSF 2.0PR.PS-06 (secure software development), ID.RA-01 (vulnerabilities identified)
NIST SP 800-218 (SSDF)PW.5 (create source code by following secure coding practices), PW.4 (reuse well-secured software), PW.7 (review code)
NIST SP 800-53 Rev 5SA-15 (development process, standards and tools), SA-11 (developer testing), SI-10 (input validation), SI-11 (error handling)
PCI DSS v4.0.16.2.1–6.2.4 (bespoke software developed securely, code review, attack prevention), 6.3.2 (component inventory)
COBIT 2019BAI03.03 (develop solution components)
CIS Controls v816.1, 16.4 (third-party components), 16.9 (developer training), 16.12 (code-level security checks)
OWASPASVS, SAMM (Implementation: Secure Build), Cheat Sheet Series
GDPRArt 25 (data protection by design), Art 32 (security of processing)
DPDP Act 2023Section 8(4), 8(5)

Implementation Roadmap (Week-by-Week)

Figure · Tiers

Maturity levels for secure coding

Maturity levels for ISO 27001 A.8.28, secure coding, from most to least mature: Optimizing, ai-assisted code review; Quantitatively Managed, metrics tracked, automated enforcement; Defined, standardized across all teams; Managed, basic standard exists; Ad-hoc, no secure coding standard, no tools.
Where most organisations sit, and what the next level asks for. Full characteristics per level are in the table below.

Phase 1: Foundation (Weeks 1–3)

Week 1: Policy and Standard Selection

  • Draft the Secure Coding Policy
  • Select secure coding standards (OWASP, CERT, MISRA, language-specific)
  • Define scope (languages, frameworks, platforms in scope)
  • Identify security champions

Week 2: Tool Selection and Setup

  • Select SAST tools for primary languages
  • Select SCA tools for dependency management
  • Select code review tools (if not already using)
  • Set up tools in CI/CD pipeline

Week 3: Baseline Assessment

  • Run SAST on existing codebase to establish vulnerability baseline
  • Run SCA to identify vulnerable dependencies
  • Identify "hot spots", files/modules with highest vulnerability density
  • Document baseline metrics

Deliverables: Secure Coding Policy, Tool selection, Baseline report, Vulnerability inventory

Phase 2: Pilot (Weeks 4–6)

Week 4-5: Developer Training

  • Conduct secure coding training for all developers
  • Focus on top 10 vulnerability types for your technology stack
  • Hands-on secure coding workshop (code review exercise, CTF-style challenges)
  • Train security champions on advanced topics

Week 6: Pilot with One Team

  • Apply secure coding practices to one development team
  • Enforce SAST in CI/CD for the pilot team
  • Conduct peer code review for security
  • Measure vulnerability reduction

Deliverables: Training completion records, Pilot team results, Training feedback, Improved practices

Phase 3: Rollout (Weeks 7–10)

Week 7-8: Organization-Wide Rollout

  • Deploy secure coding practices to all development teams
  • Enforce SAST/SCA in all CI/CD pipelines
  • Establish security code review process
  • Create secure coding reference materials (wiki, cheat sheets)

Week 9-10: Process Integration

  • Integrate secure coding into SDLC gates
  • Define vulnerability severity thresholds (block build on critical/high)
  • Establish vulnerability remediation SLA
  • Create developer security dashboard

Deliverables: Organization-wide deployment, Integrated gates, SLA definitions, Dashboard

Phase 4: Optimization (Weeks 11–14)

Week 11-12: Metrics and Monitoring

  • Collect and analyze KPIs (see Section 13)
  • Conduct first internal audit of secure coding process
  • Identify improvement opportunities
  • Update training with lessons learned

Week 13-14: Continuous Improvement

  • Update secure coding standards with new vulnerability types
  • Integrate DAST for runtime validation
  • Automate more security checks (secrets detection, license compliance)
  • Gamify secure coding (leaderboards, rewards)

Deliverables: KPI dashboard, Internal audit report, Updated standards, Gamification program

Maturity Model

LevelDescriptionTypical Timeline
1, Ad-hocNo secure coding standard, no tools, no training, security found in testingPre-implementation
2, ManagedBasic standard exists, SAST for some projects, initial trainingWeeks 1–3
3, DefinedStandardized across all teams, SAST/SCA in all pipelines, regular training, code review processWeeks 4–8
4, Quantitatively ManagedMetrics tracked, automated enforcement, vulnerability SLAs, advanced trainingWeeks 9–12
5, OptimizingAI-assisted code review, predictive vulnerability prevention, zero-vulnerability culture, continuous improvementOngoing

Detailed Implementation Guidance

Secure Coding Standards by Vulnerability Type

Injection Prevention (SQL, NoSQL, OS Command, LDAP)

The Problem: User input is concatenated into queries or commands, allowing attackers to execute arbitrary code.

Secure Coding Rules:

  • Rule 1: Never concatenate user input into SQL queries. Use parameterized queries or prepared statements.
  • Rule 2: Use ORM frameworks that automatically parameterize queries (but be aware of ORM injection).
  • Rule 3: Validate input before using it in any command context.
  • Rule 4: Use stored procedures with parameterized inputs (but don't build dynamic SQL inside procedures).
  • Rule 5: Escape/encode output when parameterized queries are not possible (legacy code only).

Language Examples:

## Python (SQL Injection Prevention)
## BAD: Concatenation
query = f"SELECT * FROM users WHERE username = '{username}'"

## GOOD: Parameterized query
cursor.execute("SELECT * FROM users WHERE username = %s", (username))

## Java (SQL Injection Prevention)
// BAD: Concatenation
String query = "SELECT * FROM users WHERE username = '" + username + "'";

// GOOD: PreparedStatement
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?");
stmt.setString(1, username);

NoSQL Injection Prevention:

// Node.js (MongoDB) — BAD
const user = await db.collection('users').findOne({ username: req.body.username });

// Node.js (MongoDB) — GOOD

Broken Authentication Prevention

The Problem: Authentication mechanisms are implemented incorrectly, allowing attackers to compromise credentials or session tokens.

Secure Coding Rules:

  • Rule 1: Use standard, well-tested authentication libraries (don't roll your own crypto or auth).
  • Rule 2: Implement multi-factor authentication (MFA) for all sensitive accounts.
  • Rule 3: Use strong password policies (minimum 12 characters, complexity requirements, breach detection).
  • Rule 4: Implement secure session management (secure cookies, HttpOnly, SameSite, short timeouts, rotation).
  • Rule 5: Protect against brute force (rate limiting, account lockout, CAPTCHA after failures).
  • Rule 6: Implement secure password recovery (non-guessable tokens, time-limited, single-use).
  • Rule 7: Use password hashing with slow algorithms (bcrypt, Argon2, PBKDF2), never MD5 or SHA-1.

Password Hashing Example:

## Python (bcrypt)
import bcrypt

## Hashing
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12))

## Verification
if bcrypt.checkpw(password.encode('utf-8'), hashed):
    # Authentication successful
// Java (Spring Security)
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12); // strength factor 12
}

Sensitive Data Exposure Prevention

The Problem: Sensitive data (PII, PHI, financial data, credentials) is exposed in plaintext, weakly encrypted, or logged.

Secure Coding Rules:

  • Rule 1: Classify data by sensitivity and apply appropriate protection.
  • Rule 2: Encrypt sensitive data at rest using AES-256 or equivalent.
  • Rule 3: Encrypt all data in transit using TLS 1.3 (disable TLS 1.0, 1.1, and weak cipher suites).
  • Rule 4: Never store plaintext passwords, credit card numbers, or encryption keys in code.
  • Rule 5: Use environment variables or secure vaults (HashiCorp Vault, AWS KMS, Azure Key Vault) for secrets.
  • Rule 6: Mask or truncate sensitive data in logs (e.g., show only last 4 digits of credit card).
  • Rule 7: Implement data retention and deletion policies in code.
  • Rule 8: Use tokenization for payment card data (PCI DSS requirement).

Secret Management Example:

## Python — BAD: Hardcoded secret
API_KEY = "sk-1234567890abcdef"

## Python — GOOD: Environment variable
import os
API_KEY = os.environ.get('API_KEY')

## Python — BETTER: AWS Secrets Manager
import boto3
client = boto3.client('secretsmanager')
secret = client.get_secret_value(SecretId='api-key')
API_KEY = secret['SecretString']

Cross-Site Scripting (XSS) Prevention

The Problem: User input is rendered in HTML without proper encoding, allowing attackers to inject malicious scripts.

Secure Coding Rules:

  • Rule 1: Validate and sanitize all user input on the server side.
  • Rule 2: Encode output based on context (HTML, JavaScript, CSS, URL, XML).
  • Rule 3: Use modern frameworks that auto-encode by default (React, Vue, Angular with proper usage).
  • Rule 4: Implement Content Security Policy (CSP) to mitigate XSS impact.
  • Rule 5: Never use innerHTML, document.write, or eval() with user input.
  • Rule 6: Use textContent or innerText instead of innerHTML when inserting text.

Output Encoding Example:

// JavaScript (React) — GOOD (auto-escapes by default)
function UserProfile({ user }) {
  return <div>{user.name}</div>; // Auto-escaped
}

// JavaScript (React) — DANGEROUS (dangerouslySetInnerHTML)
function UserProfile({ user }) {
  return <div dangerouslySetInnerHTML={{ __html: user.bio }} />; // Only if bio is trusted
}

// Java (JSP) — GOOD

// Java (JSP) — BAD
<%= user.getName() %> <%-- Does NOT escape --%>

Insecure Deserialization Prevention

The Problem: Untrusted data is deserialized without validation, allowing attackers to execute arbitrary code.

Secure Coding Rules:

  • Rule 1: Never deserialize untrusted data.
  • Rule 2: If deserialization is necessary, use safe formats (JSON with schema validation) instead of native serialization.
  • Rule 3: Implement integrity checks (HMAC or digital signatures) on serialized data.
  • Rule 4: Isolate deserialization in a low-privilege environment.
  • Rule 5: Log deserialization exceptions and monitor for attacks.
  • Rule 6: Use allowlists for deserialized classes (reject all except known safe classes).

Safe Serialization Example:

## Python — BAD (pickle with untrusted data)
data = pickle.loads(untrusted_data)  # Can execute arbitrary code

## Python — GOOD (JSON with schema validation)
import jsonschema
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string", "maxLength": 100},
        "age": {"type": "integer", "minimum": 0, "maximum": 150}
    }
}
data = json.loads(untrusted_data)
jsonschema.validate(data, schema)

Broken Access Control Prevention

The Problem: Users can access resources or perform actions outside their authorized permissions.

Secure Coding Rules:

  • Rule 1: Deny by default, reject all requests except explicitly allowed ones.
  • Rule 2: Implement access control on the server side (never trust client-side checks).
  • Rule 3: Use a single, well-tested access control mechanism (don't mix multiple approaches).
  • Rule 4: Implement least privilege, users get minimum permissions needed.
  • Rule 5: Validate access control on every request (don't rely on cached permissions).
  • Rule 6: Use indirect object references (e.g., mappings) rather than exposing internal IDs.
  • Rule 7: Log all access control failures and alert on anomalies.
  • Rule 8: Implement rate limiting for sensitive operations.

Access Control Example:

## Python (Flask) — BAD
@app.route('/api/users/<id>')
def get_user(id):
    user = User.query.get(id)
    return jsonify(user.to_dict())  # No authorization check!

## Python (Flask) — GOOD
@app.route('/api/users/<id>')
@login_required
def get_user(id):
    user = User.query.get(id)
    if not user:
        abort(404)
    if not current_user.can_access(user):  # Server-side authorization
        abort(403)
    return jsonify(user.to_dict())

Security Misconfiguration Prevention

The Problem: Default configurations, incomplete setups, or verbose error messages expose security weaknesses.

Secure Coding Rules:

  • Rule 1: Change all default passwords and credentials.
  • Rule 2: Disable unnecessary features, services, and ports.
  • Rule 3: Remove default accounts, sample applications, and unnecessary documentation.
  • Rule 4: Implement secure headers (HSTS, X-Frame-Options, X-Content-Type-Options, CSP).
  • Rule 5: Disable verbose error messages in production (no stack traces, no internal paths).
  • Rule 6: Keep all frameworks, libraries, and platforms updated.
  • Rule 7: Use automated configuration scanning (CIS benchmarks, security baselines).
  • Rule 8: Separate environments (dev, test, prod) with different configurations.

Secure Headers Example:

## Python (Flask)
from flask import Flask
app = Flask(__name__)

@app.after_request
def set_security_headers(response):
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['Content-Security-Policy'] = "default-src 'self'"
    response.headers['X-Permitted-Cross-Domain-Policies'] = 'none'
    return response

Using Components with Known Vulnerabilities Prevention

The Problem: Applications use outdated libraries and frameworks with known CVEs.

Secure Coding Rules:

  • Rule 1: Maintain an inventory of all dependencies (Software Bill of Materials, SBoM).
  • Rule 2: Use SCA tools to scan for known vulnerabilities in dependencies.
  • Rule 3: Subscribe to security advisories for all frameworks and libraries used.
  • Rule 4: Establish a vulnerability management process for dependencies (CVE monitoring, patch cycle).
  • Rule 5: Use dependency pinning (lock files) to ensure reproducible builds.
  • Rule 6: Regularly update dependencies (automated with tools like Dependabot, Renovate).
  • Rule 7: Evaluate new dependencies for security posture before adoption.
  • Rule 8: Remove unused dependencies (they still create attack surface).

Insufficient Logging and Monitoring Prevention

The Problem: Security events are not logged, or logs are not monitored, allowing attackers to operate undetected.

Secure Coding Rules:

  • Rule 1: Log all security-relevant events (authentication, authorization, data access, changes, errors).
  • Rule 2: Include sufficient context in logs (timestamp, user, IP, action, result, object).
  • Rule 3: Protect logs from tampering (immutable storage, append-only).
  • Rule 4: Never log sensitive data (passwords, tokens, credit card numbers, PII).
  • Rule 5: Use structured logging (JSON) for easier parsing and analysis.
  • Rule 6: Implement log integrity verification (hashing, digital signatures).
  • Rule 7: Set up real-time alerting for critical security events.
  • Rule 8: Centralize logs in a SIEM or log management platform.

Secure Logging Example:

## Python — GOOD: Structured logging without sensitive data
import logging
import json

logger = logging.getLogger('security')

## Log authentication event (no password!)
logger.info(json.dumps({
    "event": "authentication_attempt",
    "timestamp": "2026-01-15T10:30:00Z",
    "user_id": user.id,
    "ip_address": request.remote_addr,
    "result": "success" if authenticated else "failure",
    "mfa_used": True
}))

## BAD: Logging sensitive data
logger.info(f"User {username} logged in with password {password}")  # NEVER DO THIS

Server-Side Request Forgery (SSRF) Prevention

The Problem: The server makes requests to attacker-controlled URLs, potentially accessing internal services or exfiltrating data.

Secure Coding Rules:

  • Rule 1: Validate and sanitize all URLs before making server-side requests.
  • Rule 2: Use allowlists for allowed URL schemes, hosts, and ports.
  • Rule 3: Disable URL schemas that enable unwanted protocols (file://, ftp://, gopher://).
  • Rule 4: Implement network segmentation to prevent SSRF from accessing internal services.
  • Rule 5: Use DNS resolution validation to prevent DNS rebinding attacks.
  • Rule 6: Log all server-side requests for monitoring and forensics.
  • Rule 7: Implement response timeouts and size limits to prevent DoS.

Cryptographic Failures Prevention

The Problem: Weak cryptography, improper implementation, or hardcoded keys expose sensitive data.

Secure Coding Rules:

  • Rule 1: Use well-tested cryptographic libraries (never roll your own crypto).
  • Rule 2: Use strong, industry-standard algorithms (AES-256-GCM, RSA-4096, ECDSA P-256, ChaCha20-Poly1305).
  • Rule 3: Use authenticated encryption (GCM, CCM, ChaCha20-Poly1305) rather than unauthenticated modes (CBC, ECB).
  • Rule 4: Generate random values using cryptographically secure random number generators (CSPRNG).
  • Rule 5: Never hardcode cryptographic keys, IVs, or salts in code.
  • Rule 6: Implement key rotation and management via a key management service.
  • Rule 7: Use proper key derivation functions (PBKDF2, Argon2, scrypt) for password-based keys.
  • Rule 8: Validate certificates properly (hostname verification, certificate pinning for mobile).
  • Rule 9: Disable weak protocols (SSL, TLS 1.0, TLS 1.1) and weak cipher suites.
  • Rule 10: Protect against timing attacks (use constant-time comparison functions).

Secure Cryptography Example:

## Python (cryptography library)
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
import os

## Generate key from password using PBKDF2
salt = os.urandom(16)
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000)
key = base64.urlsafe_b64encode(kdf.derive(password))

## Encrypt
f = Fernet(key)
token = f.encrypt(b"sensitive data")

## Decrypt
data = f.decrypt(token)

Language-Specific Secure Coding Guidelines

Python Secure Coding

  • Use parameterized queries with sqlite3, psycopg2, MySQLdb
  • Use cryptography library for crypto, not pycrypto (unmaintained)
  • Use secrets module for random tokens, not random module
  • Use html.escape() for HTML encoding, urllib.parse.quote() for URL encoding
  • Use defusedxml for XML parsing (prevents XXE)
  • Use ast.literal_eval() instead of eval() for safe evaluation
  • Use subprocess.run() with argument lists, not os.system() or subprocess.call() with strings
  • Use mypy for type checking, bandit for security linting

Java Secure Coding

  • Use PreparedStatement for all database queries
  • Use OWASP Java Encoder for output encoding
  • Use Spring Security or Apache Shiro for authentication/authorization
  • Use Jackson with enableDefaultTyping() disabled (prevents deserialization attacks)
  • Use java.security.SecureRandom for randomness
  • Use java.nio.file for file operations (prevents path traversal)
  • Use @PreAuthorize and @PostAuthorize for access control
  • Use ESAPI for validation and encoding

JavaScript/Node.js Secure Coding

  • Use helmet middleware for security headers
  • Use express-rate-limit for rate limiting
  • Use validator library for input validation
  • Use bcrypt or argon2 for password hashing
  • Use jsonwebtoken with secure configuration for JWT
  • Use sequelize or knex with parameterized queries
  • Use dompurify for sanitizing HTML on the client side
  • Use npm audit and snyk for dependency scanning
  • Use eslint-plugin-security for security linting

C/C++ Secure Coding

  • Use CERT C Secure Coding Standard or MISRA C
  • Use strncpy, strncat instead of strcpy, strcat (or better, use snprintf)
  • Use malloc/free carefully (prevent use-after-free, double-free)
  • Use static analysis tools (Coverity, Clang Static Analyzer, PVS-Studio)
  • Use AddressSanitizer and MemorySanitizer for runtime detection
  • Use integer overflow checks (check before arithmetic)
  • Use format string protection (always specify format string in printf)
  • Use bounded loops to prevent infinite loops and DoS
  • Use const correctness to prevent accidental modification

Go Secure Coding

  • Use database/sql with parameterized queries
  • Use crypto/rand for randomness, not math/rand
  • Use html/template for auto-escaping HTML templates
  • Use gosec for security linting
  • Use dep or go mod with vulnerability scanning
  • Use context package for request cancellation and timeouts
  • Use validator package for input validation
  • Use securecookie for secure session management

Java/Kotlin (Android) Secure Coding

  • Use Room or SQLiteDatabase with parameterized queries
  • Use EncryptedSharedPreferences for sensitive data storage
  • Use Certificate pinning for API communication
  • Use Root detection and Tamper detection
  • Use ProGuard/R8 for code obfuscation (not security, but raises the bar)
  • Use BiometricPrompt for biometric authentication
  • Use SafetyNet API or Play Integrity API for device integrity
  • Use NetworkSecurityConfig for certificate pinning and cleartext traffic disabling

Swift (iOS) Secure Coding

  • Use Keychain for sensitive data storage (not UserDefaults)
  • Use URLSession with certificate pinning
  • Use Codable with safe decoding (prevents deserialization issues)
  • Use NSPredicate carefully (prevents injection)
  • Use App Transport Security (ATS) to enforce HTTPS
  • Use Jailbreak detection libraries
  • Use SwiftLint with security rules
  • Use CryptoKit for cryptography (iOS 13+)

AI-Assisted Coding Rules

AI coding assistants are now part of most teams' work. Treat their output as an unapproved code sample in 27002's terms:

  • Do not paste secrets, customer data or confidential code into assistants that are not approved for that data.
  • Use only assistants approved by the organisation, with data-retention and training settings agreed.
  • Review AI-generated code like any untrusted contribution: same review, same SAST, SCA and secret scanning.
  • Check licence and provenance where the assistant reproduces existing code.
  • Do not let an assistant add dependencies without the usual component approval.

Code Samples From the Internet

Snippets from forums, gists and blogs are "unapproved code samples" until reviewed. Before use: understand what the code does, check its licence, check it against your standard (input validation, error handling, crypto), and record where it came from in the commit message.

IDE and Pre-Commit Guardrails

27002 asks you to configure development tools to help enforce secure code:

  • pre-commit hooks for secret scanning and linting;
  • IDE plugins for SAST and dependency warnings;
  • dependency pinning (lock files) and an approved-registry setting;
  • shared editor configuration checked into the repository.

Secure Coding in CI/CD Pipeline

Modern secure coding integrates directly into the CI/CD pipeline:

Developer Commit → Pre-Commit Hooks → CI Build → SAST → SCA → 
Unit Tests → Build Artifact → DAST → Deploy → Runtime Monitoring

Stage 1: Pre-Commit Hooks

  • git-secrets or detect-secrets, prevent secrets from being committed
  • lint-staged with security linting, catch issues before commit
  • husky for Git hooks automation

Stage 2: CI Build, SAST

  • Run SAST on every commit/PR
  • Block builds on critical/high findings (configurable threshold)
  • Generate SARIF output for GitHub/GitLab security dashboards
  • Comment findings directly on PR for developer awareness

Stage 3: CI Build, SCA

  • Scan dependencies for known vulnerabilities
  • Block builds on CVEs above severity threshold
  • Generate SBoM for compliance
  • Suggest updates via Dependabot/Renovate

Stage 4: CI Build, Security Unit Tests

  • Test authentication flows
  • Test authorization boundaries
  • Test input validation
  • Test output encoding
  • Test session management
  • Test error handling

Stage 5: DAST

  • Run DAST on staging environment
  • Test running application for runtime vulnerabilities
  • Validate that SAST findings are actually exploitable (or not)
  • Test business logic vulnerabilities (SAST cannot find these)

Stage 6: Runtime Monitoring

  • RASP (Runtime Application Self-Protection) for production
  • Monitor for OWASP Top 10 attack patterns
  • Block attacks in real-time
  • Generate security events for SIEM

Security Code Review Process

Not all code can be reviewed by security experts, but security-critical code must be:

What to Review:

  • Authentication and authorization code
  • Input validation and sanitization functions
  • Cryptographic implementations
  • Session management code
  • File upload and download handlers
  • API endpoints (especially public-facing)
  • Data access layers (database queries)
  • Integration points (third-party APIs, webhooks)
  • Error handling and logging
  • Configuration handling

Code Review Checklist:

CategoryCheckPass/Fail
Input ValidationAll user input is validated before use☐
Output EncodingAll output is contextually encoded☐
AuthenticationAuthentication is enforced on all sensitive endpoints☐
AuthorizationAuthorization checks are server-side and on every request☐
CryptographyStrong algorithms are used, keys are managed securely☐
Session ManagementSessions are secure, timeout, rotation, invalidation☐
Error HandlingErrors don't expose sensitive information☐
LoggingSecurity events are logged without sensitive data☐
SecretsNo hardcoded secrets, secrets are in vault/environment☐
DependenciesNo known vulnerable dependencies☐
File OperationsFile paths are validated, upload restrictions enforced☐
API SecurityRate limiting, authentication, input validation on APIs☐
ConfigurationSecure defaults, no debug mode in production☐
ConcurrencyRace conditions, deadlock prevention, thread safety☐
Memory SafetyNo buffer overflows, use-after-free, integer overflows☐

Code Review Process:

  1. Developer submits code for review (PR)
  2. Automated SAST runs and reports findings
  3. Peer reviewer checks code quality and functionality
  4. Security champion reviews security-critical code paths
  5. Security findings are addressed or risk-accepted
  6. Security approval is required for critical/high-risk changes
  7. Code is merged only after all approvals

Vulnerability Remediation Process

SeveritySLAEscalation
Critical24 hoursCISO notification, emergency patch process
High7 daysSecurity team tracking, daily status updates
Medium30 daysDevelopment team tracking, weekly status
Low90 daysBacklog tracking, quarterly review
InformationalNext releaseBacklog tracking

Remediation Workflow:

  1. Vulnerability identified (SAST, DAST, manual review, external report)
  2. Vulnerability triaged and severity assigned (CVSS or custom scoring)
  3. Ticket created in tracking system (Jira, Azure DevOps, GitHub Issues)
  4. Developer assigned and fixes within SLA
  5. Fix verified by security team (re-test, code review)
  6. Deployed through normal change management
  7. Vulnerability closed in tracking system
  8. Metrics updated

Tools, Technologies, and Solutions

SAST Tools

ToolLanguagesBest For
SonarQube25+ languagesCode quality + security, CI/CD integration
Checkmarx25+ languagesEnterprise, deep analysis, compliance
Fortify25+ languagesEnterprise, complete reporting
CodeQL10+ languagesGitHub-native, deep analysis, open source
BanditPythonPython-specific, fast, open source
BrakemanRubyRuby on Rails specific
ESLint Security PluginJavaScriptJavaScript/Node.js specific
gosecGoGo-specific, fast, open source
SpotBugs (FindSecBugs)JavaJava-specific, extensive rule set
PMD SecurityJava, Apex, JavaScriptMulti-language, fast
PVS-StudioC/C++, C#, JavaDeep static analysis, MISRA support
CoverityC/C++, Java, C#Enterprise, high precision
Clang Static AnalyzerC/C++, Objective-CFree, open source, IDE integration
InferC/C++, Java, Objective-CFacebook's analyzer, fast, open source
Horusec15+ languagesMulti-language, open source, CI/CD
SonarCloud25+ languagesCloud-based, SaaS, GitHub/GitLab integration
ReshiftJava, JavaScriptCloud-native, lightweight, developer-friendly

SCA (Software Composition Analysis) Tools

ToolBest ForPricing model
OWASP Dependency-CheckFree, open source, multi-languageFree
Sonatype Nexus LifecycleEnterprise, policy enforcementEnterprise pricing
WhiteSource (Mend)Enterprise, completeEnterprise pricing
GitHub DependabotGitHub-native, automatic PRsFree
RenovateOpen source, multi-platform, configurableFree
FOSSACompliance-focused, license + securityFree / Commercial
Black DuckEnterprise, deep open source analysisEnterprise pricing
DebrickedAI-powered, fastCommercial
Jfrog XrayArtifact repository integrationCommercial

Secrets Detection Tools

ToolBest For
GitHub Secret ScanningGitHub-native
GitLab Secret DetectionGitLab-native
TruffleHogOpen source, deep scanning, many providers
Git-secretsAWS-focused, Git hooks
Detect-secretsYelp's tool, CI/CD friendly
GitleaksFast, lightweight, open source
GitGuardianEnterprise, complete
SpectralOpsEnterprise, AI-powered

DAST Tools

ToolBest ForPricing model
OWASP ZAPFree, web applications, CI/CDFree
Netsparker (Invicti)Accurate, automated, CI/CDCommercial
AppSpiderEnterprise, completeEnterprise pricing
ProbelyAPI security, developer-friendlyCommercial
CrackMapExecNetwork + applicationFree
W3AFOpen source, web applicationFree
NucleiFast, template-based, CI/CDFree / Commercial

RASP Tools

ToolBest ForPricing model
Signal SciencesWAF + RASP, cloud-nativeCommercial
Imperva RASPEnterprise, completeEnterprise pricing
Contrast SecurityIAST + RASP, developer-friendlyCommercial
HdivIAST + RASP, JavaCommercial
ThreatMapperOpen source, cloud-nativeFree (open source)
SqreenDeveloper-friendly, SaaSCommercial
AppSensorOpen source, application-layer detectionFree

Secure Coding Training Platforms

PlatformBest For
HackerEarthIndian platform, coding challenges
CodebashingDeveloper-friendly, bite-sized lessons
OWASP WebGoatFree, hands-on, web application security
OWASP Juice ShopFree, modern, gamified
Damn Vulnerable Web App (DVWA)Free, beginner-friendly
MutillidaeFree, complete, OWASP Top 10
Singahi Secure Coding WorkshopIndian context, customized, hands-on

Policy and Procedure Templates

Secure Coding Policy (Template)

Template

Security Code Review Procedure (Template)

Template


Risk Assessment and Treatment

Risk Assessment for Secure Coding

Risk IDRisk DescriptionLikelihoodImpactRisk LevelMitigation
R-001Developers not trained on secure coding, introducing vulnerabilitiesHighHighCriticalMandatory training, secure coding standard, SAST enforcement
R-002SAST tools not integrated, vulnerabilities missedMediumHighHighCI/CD integration, mandatory SAST, build blocking
R-003Security code review skipped for critical codeMediumHighHighMandatory review checklist, security champion program, merge gates
R-004Vulnerable dependencies not updatedHighMediumHighSCA scanning, automated updates, dependency management
R-005Hardcoded secrets in codeMediumHighHighSecrets detection, pre-commit hooks, vault usage, developer training
R-006Outsourced code not subject to secure codingMediumHighHighVendor policy, contract terms, SAST/SCA for vendor code, review requirements
R-007Legacy code not reviewed for securityHighMediumHighLegacy code review program, compensating controls, modernization plan
R-008Business pressure overrides security fixesMediumHighHighRisk acceptance process, CISO approval for critical/high deferrals, metrics visibility
R-009Secure coding standard not updatedMediumMediumMediumAnnual review, CVE integration, threat intelligence feed
R-010Developers circumvent security toolsMediumMediumMediumPolicy enforcement, audit logs, management commitment, culture change

Risk Treatment Options

RiskTreatmentResidual Risk
R-001Training + standard + mentoringLow
R-002CI/CD integration + automated enforcementLow
R-003Mandatory process + checklist + champion programLow
R-004SCA + automated updates + dependency pinningLow
R-005Pre-commit hooks + vault + training + detectionLow
R-006Vendor management + contract + scanningLow
R-007Legacy program + compensating controls + modernizationMedium
R-008Risk acceptance + governance + metricsLow
R-009Annual review + automated monitoringLow
R-010Culture + policy + enforcement + rewardsLow

Audit and Compliance Checklist

Pre-Audit Self-Assessment

#QuestionEvidenceStatus
1Is there a documented Secure Coding Policy?Policy document☐
2Is there a documented Secure Coding Standard?Standard document☐
3Are developers trained on secure coding?Training records☐
4Is SAST integrated into CI/CD?CI/CD pipeline config☐
5Is SCA integrated into CI/CD?CI/CD pipeline config☐
6Are critical/high vulnerabilities blocked from deployment?Pipeline records☐
7Is there a security code review process?Procedure document☐
8Are security code reviews conducted for critical code?Review records☐
9Is there a vulnerability remediation SLA?SLA document☐
10Are vulnerabilities tracked to closure?Vulnerability tracking system☐
11Are secrets detected in code before commit?Pre-commit hook config☐
12Are there security champions in development teams?Champion list☐
13Is there a secure coding reference/wiki?Wiki/documentation☐
14Is secure coding covered in onboarding?Onboarding records☐
15Is outsourced code subject to secure coding requirements?Vendor contracts☐
16Is there a process for handling new CVEs in dependencies?Process document☐
17Are secure coding metrics tracked?Metrics dashboard☐
18Is there a language-specific secure coding standard?Language standards☐
19Is secure coding integrated into the SDLC?SDLC documentation☐
20Are security unit tests written for critical functionality?Test records☐
21Is DAST run on applications before deployment?DAST records☐
22Is there a process for risk-accepting vulnerabilities?Risk acceptance records☐
23Are developers incentivized for secure coding?Incentive records☐
24Is there a process for reporting security bugs?Bug bounty / reporting process☐
25Are secure coding practices audited?Audit records☐
26Is there a secure coding maturity assessment?Assessment records☐
27Are AI/ML code covered by secure coding guidelines?AI/ML guidelines☐
28Is there a process for handling false positives from SAST?False positive process☐
29Are secure coding standards reviewed annually?Review records☐
30Are build logs retained for audit?Build log retention☐

Auditor Interview Questions

Be prepared to answer:

  1. "What secure coding standard does your organization follow?"
  2. "How are developers trained on secure coding?"
  3. "Show me the SAST configuration for [application]."
  4. "How do you handle security code review?"
  5. "What is your vulnerability remediation SLA?"
  6. "How do you prevent hardcoded secrets in code?"
  7. "How do you handle vulnerable dependencies?"
  8. "How do you enforce secure coding on outsourced development?"
  9. "Show me evidence that security-critical code is reviewed."
  10. "How do you measure secure coding effectiveness?"

Common Audit Findings and How to Avoid Them

FindingCausePrevention
"No secure coding standard"Process gapCreate and approve standard; base on OWASP/CERT
"SAST not integrated into CI/CD"Tool gapIntegrate SAST; block builds on critical findings
"Developers not trained on secure coding"Training gapMandatory training; annual refresh; onboarding
"Security code review not conducted"Process gapMandatory checklist; champion program; merge gates
"Vulnerabilities not tracked to closure"Tracking gapVulnerability management system; SLA enforcement
"Hardcoded secrets in repository"Prevention gapPre-commit hooks; secrets detection; vault training
"Outdated dependencies with known CVEs"Dependency gapSCA scanning; automated updates; dependency management
"No secure coding for outsourced code"Vendor gapVendor contract terms; SAST/SCA for vendor code
"Legacy code not reviewed"Legacy gapLegacy review program; compensating controls
"No DAST for runtime validation"Testing gapDAST on staging; runtime monitoring

Metrics and KPIs

Figure · Measures

The measures that show A.8.28 is working

  • SAST Coverage100%Monthly
  • SCA Coverage100%Monthly
  • Secrets Detection Coverage100%Monthly
  • Security Code Review Rate> 90%Monthly
  • Training Completion Rate100%Quarterly
Targets and reporting cadence as defined in the table below, where the formula for each is given.

Process Metrics

MetricFormulaTargetFrequency
SAST Coverage(# of apps with SAST / # of apps) × 100100%Monthly
SCA Coverage(# of apps with SCA / # of apps) × 100100%Monthly
Secrets Detection Coverage(# of repos with secrets detection / # of repos) × 100100%Monthly
Security Code Review Rate(# of critical code paths reviewed / # of critical code paths) × 100> 90%Monthly
Training Completion Rate(# of trained developers / # of developers) × 100100%Quarterly
Vulnerability Remediation SLA Compliance(# of vulns fixed within SLA / # of vulns) × 100> 90%Monthly
Build Block Rate(# of builds blocked for security / # of builds) × 100< 5%Monthly
Champion Coverage(# of teams with champion / # of teams) × 100100%Quarterly
Policy Update Rate(# of policy updates / year)> 2Annually
False Positive Rate(# of false positives / # of SAST findings) × 100< 20%Quarterly

Outcome Metrics

MetricFormulaTargetFrequency
Vulnerability DensityCritical/high vulnerabilities per 1000 LOC< 0.5Per release
Mean Time to Remediate (MTTR)Average days from discovery to fix< 7 days (critical)Monthly
Production Security DefectsSecurity defects found in production per release< 2Per release
Dependency Vulnerability Rate(# of vulnerable dependencies / # of total dependencies) × 100< 5%Monthly
Secrets in Code Rate(# of secrets found in code / # of code scans) × 1000Monthly
Security Test Pass Rate(# of security tests passed / # of security tests) × 100> 95%Per release
Compliance Audit FindingsSecure coding-related audit findings0Per audit
Developer Security ScoreAverage security score per developer> 80/100Quarterly
Time to Security Audit ReadinessTime to prepare for security audit< 2 weeksPer audit
Cost of Security ReworkCost of fixing security issues post-releaseDecreasingQuarterly

Dashboard Sample

┌─────────────────────────────────────────────────────────────────────┐
│                  SECURE CODING DASHBOARD                            │
│                    [Organization] — [Month Year]                    │
├─────────────────────────────────────────────────────────────────────┤
│  SAST COVERAGE: 100%         ██████████████████████  Target: 100%│
│  SCA COVERAGE: 100%          ██████████████████████  Target: 100%  │
│  REVIEW RATE: 94%            ███████████████████░░░  Target: 90%  │
│  TRAINING: 98%               ████████████████████░░  Target: 100% │
│  VULN DENSITY: 0.4           ██░░░░░░░░░░░░░░░░░░░  Target: <0.5  │
│  MTTR (CRITICAL): 2.1 days   ███░░░░░░░░░░░░░░░░░░  Target: <7   │
│  PROD DEFECTS: 1             ░░░░░░░░░░░░░░░░░░░░░  Target: <2   │
│  DEP VULN RATE: 3%           █░░░░░░░░░░░░░░░░░░░░  Target: <5%  │
│  SECRETS IN CODE: 0          ░░░░░░░░░░░░░░░░░░░░░  Target: 0     │
│  SEC TEST PASS: 97%          ███████████████████░░░  Target: 95%  │
└─────────────────────────────────────────────────────────────────────┘

Common Pitfalls and How to Avoid Them

Pitfall 1: "SAST Is Too Noisy"

Symptom: Developers ignore SAST findings because of too many false positives.

Reality: Modern SAST tools (Semgrep, CodeQL) have significantly reduced false positives. Configuration tuning and custom rule development can further reduce noise.

Solution:

  • Tune SAST rules to your technology stack
  • Suppress false positives with documented justification
  • Use high-confidence rules only for build blocking
  • Gradually expand rule set as developers become more security-aware

Pitfall 2: "We Don't Have Time for Secure Coding"

Symptom: Security is deprioritized to meet deadlines.

Reality: Fixing vulnerabilities in production takes 10-100x longer than fixing them during development. Secure coding saves time overall.

Solution:

  • Show time-to-fix data: development vs. production
  • Integrate security into daily workflow (not separate activity)
  • Use automation to reduce manual effort
  • Start with critical/high vulnerabilities only

Pitfall 3: "We Use a Framework, So We're Secure"

Symptom: Developers assume frameworks handle all security.

Reality: Frameworks provide security features, but developers must use them correctly. Frameworks don't prevent business logic flaws, misconfiguration, or custom code vulnerabilities.

Solution:

  • Train developers on framework security features (and how to misuse them)
  • Review custom code even when using secure frameworks
  • Test for business logic vulnerabilities (DAST, manual testing)
  • Don't disable framework security features for convenience

Pitfall 4: "Security Is the Security Team's Job"

Symptom: Developers write code and "throw it over the wall" to security.

Reality: Security is everyone's responsibility. Developers who write insecure code create work for themselves and the security team.

Solution:

  • Security champion program
  • Developer training and empowerment
  • Make security part of developer KPIs
  • Reward secure coding, don't just punish mistakes

Pitfall 5: "We Reviewed It Once, We're Done"

Symptom: Code is reviewed once and never revisited.

Reality: New vulnerabilities are discovered constantly. Code must be re-scanned when new CVEs affect dependencies, when new SAST rules are added, and when the threat landscape changes.

Solution:

  • Continuous scanning in CI/CD
  • Regular dependency updates and re-scanning
  • Annual code security audit
  • Monitor for new CVEs affecting your stack

Pitfall 6: "Outsourced Code Is Not Our Problem"

Symptom: Vendor code is accepted without security review.

Reality: Vendor code running in your environment is your risk. Many breaches originate from vulnerable third-party components.

Solution:

  • Include secure coding requirements in vendor contracts
  • Run SAST/SCA on vendor code
  • Conduct security acceptance testing
  • Include security SLAs in vendor agreements

Pitfall 7: "We Only Need to Fix Critical Vulnerabilities"

Symptom: Only critical vulnerabilities are fixed; highs and mediums are ignored.

Reality: Attack chains often combine medium vulnerabilities to achieve critical impact. A medium vulnerability + a medium vulnerability = critical breach.

Solution:

  • Fix all vulnerabilities within SLA, not just critical
  • Understand attack chain risk (how vulnerabilities combine)
  • Use risk-based prioritization, not severity-only

Pitfall 8: "Security Tools Replace Secure Coding Knowledge"

Symptom: Developers rely entirely on SAST/DAST and don't learn secure coding.

Reality: Tools catch known patterns but miss business logic flaws, novel vulnerabilities, and architectural issues. Developer knowledge is irreplaceable.

Solution:

  • Invest in training, not just tools
  • Use CTFs and hands-on labs (OWASP Juice Shop, WebGoat)
  • Encourage developers to understand WHY vulnerabilities exist, not just fix them
  • Security champions mentor developers on secure coding patterns

Illustrative Scenarios

Hypothetical scenarios: composite examples for guidance, not real organisations or verified outcomes.

Scenario 1: Fast-Growing SaaS Team With No Coding Standard

Situation. An HR-tech SaaS company grows from 10 to 40 developers in a year. A penetration test finds SQL injection, cross-site scripting and broken access control. There is no coding standard, no SAST and no security review.

What applying 8.28 looks like.

  1. A short secure coding standard for the stack (Django and React), based on the OWASP Cheat Sheets, with a minimum baseline.
  2. SAST, SCA and secret scanning in CI, plus pre-commit secret scanning and IDE plugins.
  3. A secure-coding workshop with hands-on labs; one security champion per team.
  4. Security review by a champion for authentication, authorisation and data-access code.
  5. A library inventory (SBOM) and a rule that AI-generated and copied code gets the same review.

Lesson. Standards, automation and trained reviewers together change outcomes; tools alone do not.

Scenario 2: Legacy Trading Platform

Situation. A securities firm's trading platform includes old Java code with known deserialization and injection risks. SAST is run by hand once a quarter, and dependency vulnerabilities are not tracked.

What applying 8.28 looks like.

  1. SAST and SCA in every build, with gates on new critical findings.
  2. A Java secure coding standard drawn from the SEI CERT Oracle Coding Standard for Java and OWASP guidance.
  3. Mandatory security review for trading-critical code; security unit tests for authentication and authorisation paths.
  4. A risk-ranked plan to fix legacy findings, with accepted risks recorded.
  5. Evidence kept for SEBI CSCRF reviews and ISO audits.

Lesson. For legacy code, stop new defects first, then pay down the old ones by risk.


Multi-Framework Mapping

Figure · Matrix

Comparison: Level 1 to Level 3

UseRelevance
Level 1All applicationsBaseline coding checks
Level 2Most business applicationsDefault verification level
Level 3Critical applicationsDeepest verification
Condensed from the table below, which carries the full detail for each cell.

OWASP ASVS Mapping

ASVS LevelUse forRelevance to A.8.28
Level 1All applicationsBaseline coding checks (validation, encoding, authentication basics)
Level 2Most business applicationsDefault verification level for secure coding
Level 3Critical applicationsDeepest verification

ASVS chapters on validation and encoding, cryptography, error handling and logging, data protection, files and APIs give testable coding requirements. ASVS 5.0 (May 2025) reorganised the chapters; reference the version you use.

PCI DSS v4.0.1 Mapping

PCI DSS RequirementSecure Coding Focus
6.2.1Bespoke and custom software developed securely
6.2.2Developers trained at least once every 12 months
6.2.3Code reviewed before release to find and fix vulnerabilities
6.2.4Techniques that prevent common attacks (injection, XSS, access-control flaws, and others)
6.3.2Inventory of bespoke and third-party components

DPDP Act 2023: Coding Implications

DPDP Act SectionSecure Coding Implication
Section 8(4)Appropriate technical and organisational measures, code must implement data minimization, encryption, access control
Section 8(5)Reasonable security safeguards, code must implement technical safeguards for data protection
Section 8(6)Personal data breach intimation, code must detect and log breaches

NIST SP 800-53 Rev 5 Mapping

NIST ControlDescriptionA.8.28 Mapping
SA-15Development process, standards, toolsSecure coding standards and tools
SI-10Information input validationInput validation in code
SI-11Error handlingSecure error handling in code
SC-28Protection of information at restEncryption in code
AC-6Least privilegeAuthorization in code
AU-6Audit reviewLogging in code

COBIT 2019 Mapping

COBIT PracticeDescriptionA.8.28 Mapping
BAI03.03Develop solution componentsSecure coding during development
BAI03.06Perform quality assuranceCode review and testing
BAI06.01Evaluate, prioritise and authorise change requestsSecure deployment of updates

CIS Controls v8 Mapping

CIS SafeguardImplementation GroupA.8.28 Mapping
16.1 Secure application development processIG2Coding standard within the process
16.4 Inventory of third-party software componentsIG2Library inventory
16.9 Train developers in application securityIG2Developer training
16.12 Code-level security checksIG3SAST and code analysis

Regulatory and Industry Context

India

RegulationSecure Coding RelevanceKey Mandates
DPDP Act 2023CriticalSection 8(4) (Appropriate technical and organisational measures); code must implement technical safeguards
IT Act 2000HighSection 43A: Reasonable security practices; secure coding is a reasonable practice
RBI GuidelinesCritical for banksCybersecurity framework requires secure coding for banking applications
SEBI RegulationsCritical for marketsCyber resilience framework requires secure coding for trading systems
IRDAI GuidelinesCritical for insuranceInformation security requires secure coding for customer data handling
CERT-InHighSecurity best practices include secure coding

International

RegulationRelevanceKey Mandates
PCI DSS v4.0.1Critical for card dataReq 6.3, 6.5: Secure coding for payment applications
GDPRHighArt 25: Data protection by design; Art 32: Security of processing
HIPAACritical for healthSecurity Rule: Technical safeguards require secure coding
SOXHighIT general controls require secure coding for financial systems
NIST CSF 2.0HighPR.PS-06: Secure software development practices
CCPA/CPRAHighSecurity requirements for personal information handling
LGPDHighSecurity measures in code
PDPAHighProtection obligations require secure coding

Roles and Responsibilities (RACI)

RACI Matrix for Secure Coding

ActivityCISOSecurity LeadDev ManagerSecurity ChampionDeveloperQA LeadDevOps Lead
Define secure coding policyARCCIII
Maintain secure coding standardIR/ACCCII
Select SAST/SCA toolsARCCIIC
Configure CI/CD securityICICIIR/A
Conduct developer trainingIR/ACCIII
Write secure codeICICR/AII
Security code reviewIAIRCCI
Fix vulnerabilitiesICCCR/AII
Verify fixesIAICCRI
Track vulnerabilitiesIR/ACCICI
Manage dependenciesICICCIR/A
Audit secure codingR/ACIIICI
Metrics and reportingR/ACIIIIC
Vendor secure codingARCCIII
Emerging tech guidelinesARCCCII

Legend: R = Responsible, A = Accountable, C = Consulted, I = Informed

Role Descriptions

RoleKey ResponsibilitiesRequired Skills
CISOPolicy ownership, governance, board reporting, exception approvalSecurity leadership, risk management, business acumen
Security LeadMaintains standards, configures tools, trains champions, reviews codeApplication security, secure coding, SAST/DAST, training
Development ManagerEnsures team compliance, allocates time for security, supports trainingDevelopment management, security awareness, team leadership
Security ChampionConducts code reviews, trains team, advocates security, triages findingsDevelopment + security, communication, influence, mentoring
DeveloperWrites secure code, fixes vulnerabilities, asks for help, participates in trainingSoftware development, secure coding practices, testing
QA LeadValidates security fixes, tests security requirements, supports DASTTesting methodologies, security testing, automation
DevOps LeadMaintains CI/CD security pipeline, configures SAST/SCA, manages secretsDevOps, CI/CD, security tools, infrastructure

Documentation and Evidence Requirements

ISO 27001 does not mandate specific documents for this control. If you select it, keep the documented information you need to show it is planned and working (clause 7.5), and set retention in your own retention schedule. Typical records:

DocumentPurposeSuggested retentionOwner
Secure Coding PolicyGovernance frameworkPer retention scheduleCISO
Secure Coding StandardDeveloper rules and guidelinesCurrent version + your retention periodSecurity Lead
Language-Specific GuidelinesDetailed rules per languageCurrent version + your retention periodSecurity Lead
SAST ConfigurationTool setup and rulesCurrent version + your retention periodDevOps Lead
SCA ConfigurationDependency scanning setupCurrent version + your retention periodDevOps Lead
Code Review ChecklistSecurity review checklistCurrent version + your retention periodSecurity Lead
Training MaterialsDeveloper training contentPer retention scheduleSecurity Lead
Training RecordsStaff competency evidencePer retention scheduleHR / Security
Vulnerability Tracking RecordsVulnerability lifecyclePer retention scheduleSecurity Lead
Remediation RecordsFix verification evidencePer retention scheduleDeveloper
Build LogsCI/CD pipeline evidence1 yearDevOps Lead
Audit RecordsAudit findings and remediationPer retention scheduleCISO
Exception RecordsApproved deviationsPer retention scheduleCISO
Metrics ReportsKPI trackingPer retention scheduleSecurity Lead
Champion Program RecordsChampion assignments and activitiesPer retention scheduleSecurity Lead
Vendor Secure Coding RequirementsContract terms for outsourced codePer retention scheduleSecurity Lead
Secure Coding Wiki/DocumentationDeveloper referenceCurrent versionSecurity Lead
False Positive RecordsSuppressed findings with justificationPer retention scheduleSecurity Lead
Annual Standard ReviewStandard update evidencePer retention scheduleSecurity Lead

Evidence for Audit

Audit QuestionEvidence Required
"Show me the secure coding policy"Approved Secure Coding Policy
"Show me the secure coding standard"Secure Coding Standard document
"How are developers trained?"Training records, completion certificates
"Show me SAST configuration"CI/CD pipeline config, SAST tool config
"Show me vulnerability tracking"Vulnerability management system, tracking records
"How are vulnerabilities remediated?"Remediation records, SLA compliance reports
"Show me security code review records"Review checklists, meeting records
"How do you prevent secrets in code?"Pre-commit hook config, secrets detection records
"How do you handle dependencies?"SCA records, dependency update records
"How do you handle outsourced code?"Vendor contracts, SAST/SCA records for vendor code

Continuous Improvement

Improvement Cycle

Plan → Implement → Measure → Review → Improve

Plan: Set targets for vulnerability density, MTTR, training coverage, tool effectiveness.

Implement: Deploy tools, conduct training, enforce code review, track vulnerabilities.

Measure: Track KPIs, conduct surveys, analyze audit results, monitor incidents.

Review: Monthly metrics review, quarterly process review, annual complete review.

Improve: Update standards, tune tools, enhance training, adopt new techniques, gamify.

Improvement Triggers

TriggerAction
New CVE affecting your stackUpdate SCA rules, notify developers, patch dependencies
New vulnerability type discoveredUpdate secure coding standard, add SAST rules, train developers
SAST tool update with new rulesEvaluate new rules, add to CI/CD, train on new findings
Security incidentRoot cause analysis, update standard if coding issue, train on incident
Audit findingUpdate process, standard, or training to address finding
Developer feedbackRefine standard, improve training, tune tools
New language/framework adoptedCreate language-specific guidelines, configure SAST
Industry benchmarkCompare metrics, set improvement targets
Tool evolutionEvaluate new tools, migrate if beneficial
Regulatory changeUpdate compliance checklist, add regulatory requirements to standard

Maturity Advancement Path

From LevelTo LevelKey ActionsTypical Timeline
1 (Ad-hoc)2 (Managed)Create policy + standard; deploy SAST for pilot; conduct initial training1–2 months
2 (Managed)3 (Defined)Deploy to all teams; integrate CI/CD; establish code review; train champions3–4 months
3 (Defined)4 (Quantified)Define KPIs; enforce SLAs; gamify; advanced training; DAST integration3–4 months
4 (Quantified)5 (Optimizing)AI-assisted review; predictive prevention; zero-vulnerability culture; continuous improvement6–12 months

FAQ

Q1: What is the most important secure coding practice?

A: Input validation is the single most important practice. The majority of vulnerabilities (injection, XSS, XXE, SSRF, path traversal) are caused by trusting user input. Validate every input, every time, on the server side.

Q2: Do we need to review every line of code for security?

A: No. Focus security code review on security-critical code paths: authentication, authorization, input validation, output encoding, cryptography, session management, file handling, and API endpoints. Use automated tools for the rest.

Q3: How do we handle legacy code that has no secure coding?

A: Prioritize by risk. Use SAST to identify the most vulnerable files. Apply compensating controls (WAF, input validation at gateway) where code cannot be changed immediately. Plan a remediation roadmap.

Q4: What if developers don't have time to learn secure coding?

A: Make secure coding part of their daily workflow, not a separate activity. Use IDE plugins (Snyk, Semgrep) that show vulnerabilities as they code. Use short, bite-sized training (10-minute modules) rather than week-long courses. Start with the top 5 vulnerability types for your stack.

Q5: Are there secure coding standards for AI/ML?

A: Yes, but they are evolving. Focus on: input sanitization for model inference, adversarial strength testing, secure model serialization, data pipeline validation, and access control for model artifacts. See the OWASP Top 10 for LLM Applications and the OWASP Machine Learning Security Top 10.

Q6: How do we measure secure coding effectiveness?

A: Track vulnerability density, MTTR, production security defects, dependency vulnerability rate, and training completion. See Section 13 for a full KPI framework.

Q7: What is the best SAST tool?

A: The best tool depends on your languages, budget, and integration needs. For small teams: Semgrep (free, fast, customizable). For enterprise: Checkmarx or SonarQube. For GitHub-native: CodeQL. For open source: SonarQube Community + OWASP Dependency-Check.

Q8: How do we handle false positives from SAST?

A: Document false positives with justification and suppress them in the tool. Tune rules to your technology stack. Use high-confidence rules only for build blocking. Track false positive rate as a KPI.

Q9: Should we use SAST, DAST, or both?

A: Both. SAST finds code-level issues early (shift-left). DAST finds runtime issues that SAST misses (business logic, configuration, environment). SCA is also essential for dependency vulnerabilities. IAST (Contrast, Hdiv) provides the best of both worlds but requires runtime instrumentation.

Q10: How do we enforce secure coding on outsourced development?

A: Include secure coding requirements in contracts, run SAST/SCA on vendor code, require security code review for deliverables, and include security acceptance criteria in acceptance testing.

Q11: What is the difference between SAST and SCA?

A: SAST (Static Application Security Testing) scans your source code for security vulnerabilities. SCA (Software Composition Analysis) scans your third-party dependencies for known vulnerabilities (CVEs). Both are essential and complement each other.

Q12: How often should we train developers on secure coding?

A: Initial training before writing production code. Annual refresher for all developers. Advanced training for security champions. Just-in-time training when new vulnerability types or technologies are introduced.

Q13: Can we use AI/LLMs to help with secure coding?

A: Yes, with caution. AI coding assistants (GitHub Copilot, ChatGPT) can suggest secure code, but they also suggest insecure code. Developers must review AI-generated code for security. Use AI for: generating secure coding examples, explaining vulnerability fixes, creating test cases. Do NOT use AI for: cryptographic implementations, security-critical code without review, or replacing security training.

Q14: What is the Security Champion program?

A: A program where one developer per team is trained as a security advocate. Champions conduct security code reviews, mentor teammates on secure coding, triage security findings, and bridge the gap between the security team and development team.

Q15: How do we handle security bugs reported by users or external researchers?

A: Establish a vulnerability disclosure policy (VDP) and bug bounty program if appropriate. Have a clear process for receiving, triaging, and responding to external reports. Thank reporters, fix issues promptly, and disclose responsibly.


References and Further Reading

Standards and Guidelines

  1. ISO/IEC 27001:2022: Information Security, Cybersecurity and Privacy Protection, Information Security Management Systems, Requirements. ISO, 2022.
  2. ISO/IEC 27002:2022: Information Security, Cybersecurity and Privacy Protection, Information Security Controls. ISO, 2022.
  3. NIST SP 800-53 Rev 5: Security and Privacy Controls for Information Systems and Organizations. NIST, 2020.
  4. OWASP Top 10:2025 (final January 2026; the 2021 edition is still widely referenced). OWASP.
  5. OWASP Application Security Verification Standard (ASVS) 5.0 (2025); v4.0.3 (2021) is still widely used.
  6. OWASP Software Assurance Maturity Model (SAMM) v2.0. OWASP, 2020.
  7. CWE Top 25: Most Dangerous Software Weaknesses. MITRE, 2023.
  8. SEI CERT C Coding Standard (2016 edition; maintained online): Carnegie Mellon Software Engineering Institute.
  9. SEI CERT C++ Coding Standard and SEI CERT Oracle Coding Standard for Java: Carnegie Mellon Software Engineering Institute (maintained online).
  10. MISRA C:2012: Guidelines for the Use of the C Language in Critical Systems, 2012.
  11. PCI DSS v4.0.1: Payment Card Industry Data Security Standard. PCI SSC, 2024.
  12. CIS Controls v8: Center for Internet Security, 2021.

Secure Coding Books and Resources

  1. "The Art of Software Security Assessment": Mark Dowd et al., Addison-Wesley, 2006.
  2. "Secure Coding in C and C++": Robert Seacord, Addison-Wesley, 2013.
  3. "24 Deadly Sins of Software Security": Michael Howard et al., McGraw-Hill, 2009.
  4. "Software Security: Building Security In": Gary McGraw, Addison-Wesley, 2006.
  5. "Threat Modeling: Designing for Security": Adam Shostack, Wiley, 2014.
  6. "Hacking: The Art of Exploitation": Jon Erickson, No Starch Press, 2008.
  7. OWASP Cheat Sheet Series: https://cheatsheetseries.owasp.org/
  8. OWASP Testing Guide: https://owasp.org/www-project-web-security-testing-guide/

Training Platforms and Labs

  1. OWASP WebGoat: https://owasp.org/www-project-webgoat/
  2. OWASP Juice Shop: https://owasp.org/www-project-juice-shop/
  3. Damn Vulnerable Web App (DVWA): https://github.com/digininja/DVWA
  4. Mutillidae: https://github.com/webpwnized/mutillidae
  5. Secure Code Warrior: https://www.securecodewarrior.com/
  6. HackEDU: https://www.hackedu.com/
  7. HackerEarth: https://www.hackerearth.com/
  8. Codebashing: https://www.codebashing.com/
  9. Cybrary: https://www.cybrary.it/

Indian Regulatory Resources

  1. Digital Personal Data Protection Act 2023: Government of India, 2023.
  2. RBI Master Direction on Information Technology Governance, Risk, Controls and Assurance Practices: Reserve Bank of India, 7 November 2023 (in force from 1 April 2024); and RBI Cyber Security Framework in Banks: circular of 2 June 2016.
  3. SEBI Cybersecurity and Cyber Resilience Framework (CSCRF) for SEBI Regulated Entities, circular of 20 August 2024.
  4. IRDAI Guidelines on Information and Cybersecurity: Insurance Regulatory and Development Authority of India, 2023.
  5. IT Act 2000 (as amended): Ministry of Electronics and Information Technology, India.

Industry Research

  1. IBM Cost of a Data Breach Report 2024: IBM Security and Ponemon Institute, 2024.
  2. Verizon Data Breach Investigations Report 2024: Verizon, 2024.
  3. BSIMM: Building Security In Maturity Model (use the latest edition).
  4. NIST SP 800-218: Secure Software Development Framework (SSDF) v1.1. NIST, 2022.

How Singahi can help

Singahi is one team for compliance, assessment and managed security. We help growing companies implement and certify ISO 27001:2022, and stay secure afterward.


Continue the toolkit

How we can help

Working toward this?

If a certification or a customer's security questionnaire is what brought you here, tell us where you are. We'll give you an honest read on the work and the timeline, with no obligation.

What happens next

  1. Tell us the trigger

    A questionnaire, an audit date or an investor ask. The short form or a call both work.

  2. A practitioner replies

    A senior practitioner, not a bot, within four business hours.

  3. You get a scoped next step

    An honest view of what the work involves. No pressure, no theatre.