InfoSec Notes
Essential secure coding practices for web developers covering input validation, output encoding, error handling, and OWASP guidelines for building resilient applications.
Principles of Secure Coding
Secure coding is the practice of writing software that is resistant to security vulnerabilities. It's far more cost-effective to prevent vulnerabilities during development than to patch them after deployment.
The OWASP Secure Coding Guidelines
Input Validation Framework
Secure Error Handling
import logging
import traceback
logger = logging.getLogger('security')
def secure_error_handler(func):
"""Decorator for secure error handling."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except PermissionError:
logger.warning(f"Authorization failure in {func.__name__}")
return {"error": "Access denied"}, 403
except ValueError as e:
logger.info(f"Validation error in {func.__name__}: {e}")
return {"error": "Invalid input"}, 400
except Exception as e:
# Log full error internally
logger.error(f"Unhandled error in {func.__name__}: {traceback.format_exc()}")
# Return generic message to user (never expose internals)
return {"error": "An internal error occurred"}, 500
return wrapperSecure Coding Checklist
| Category | Practice | Bad Example | Good Example |
|---|---|---|---|
| SQL | Parameterized queries | f"SELECT...{input}" | cursor.execute("SELECT...?", (input,)) |
| XSS | Output encoding | f"<p>{name}</p>" | f"<p>{escape(name)}</p>" |
| Auth | Constant-time compare | if token == stored | hmac.compare_digest(token, stored) |
| Secrets | Environment variables | API_KEY = "abc123" | API_KEY = os.environ["API_KEY"] |
| Files | Path validation | open(user_path) | open(os.path.join(BASE, basename)) |
| Crypto | Use libraries | Custom AES impl | cryptography.fernet.Fernet |
Interview Questions
- What is the principle of least privilege in code and how do you apply it?
- Code should only have the minimum permissions needed to function. Apply by: using restricted database users per service, dropping privileges after initialization, running with non-root OS users, requesting minimal API scopes, and limiting file system access to specific directories.
- Why is server-side validation required even when client-side validation exists?
- Client-side validation can be bypassed easily (browser dev tools, curl, proxy tools). It's a UX convenience only. Server-side validation is the security boundary — all input must be validated server-side regardless of client-side checks.
- Explain defensive programming and give three examples.
- Defensive programming assumes input is malicious and systems will fail. Examples: validate all inputs even from "trusted" internal APIs, check return values and handle null/empty cases, use timeouts on all external calls, validate data after deserialization, and fail closed (deny access on error).
- What is the difference between whitelist and blacklist validation?
- Whitelist (allowlist) defines exactly what IS allowed and rejects everything else — more secure, harder to bypass. Blacklist defines what is NOT allowed — easily bypassed with encoding, new patterns, or variations. Always prefer whitelist.
- How do you securely store and manage application secrets?
- Never hardcode in source code. Use: environment variables (minimum), secrets managers (AWS Secrets Manager, HashiCorp Vault), encrypted configuration, key management services. Rotate secrets regularly, audit access, and use different secrets per environment.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Secure Coding Practices — Information Security.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Information Security topic.
Search Terms
information-security, information security, information, security, web, secure, coding, practices
Related Information Security Topics