InfoSec Notes
HubCybersecurity vs Information SecurityHistory of Information SecurityImportance of Information SecuritySecurity Principles and the CIA TriadWhat is Information Security?Accountability in Information SecurityAuthentication in Information SecurityAuthorization in Information SecurityAvailability in Information SecurityConfidentiality in Information SecurityIntegrity in Information SecurityNon-Repudiation in Information SecurityAES - Advanced Encryption StandardAsymmetric Key CryptographyDES - Data Encryption StandardDigital SignaturesEncryption vs DecryptionCryptographic Hash FunctionsIntroduction to CryptographyPublic Key Infrastructure (PKI)RSA AlgorithmSymmetric Key CryptographyIntroduction to Access ControlAttribute-Based Access Control (ABAC)Discretionary Access Control (DAC)Mandatory Access Control (MAC)Role-Based Access Control (RBAC) — Information SecurityZero Trust Security ArchitectureFirewalls in Network SecurityIntrusion Detection Systems (IDS)Intrusion Prevention Systems (IPS)Network Monitoring and AnalysisNetwork Security BasicsSecure Network DesignVirtual Private Networks (VPN)Wireless Network SecurityAPI SecurityIntroduction to Application SecuritySecurity Code ReviewDependency and Supply Chain SecurityDynamic Application Security Testing (DAST)Secure Software Development LifecycleStatic Application Security Testing (SAST)Web Authentication MechanismsCross-Site Scripting (XSS)Cross-Site Request Forgery (CSRF)File Upload SecurityHTTPS and SSL/TLSSecure Coding Practices — Information SecuritySession Management SecuritySQL Injection Attacks and PreventionIntroduction to Web SecurityOS Access Control ModelsEndpoint SecurityFile System Permissions and SecurityLinux SecurityIntroduction to OS SecurityUser Account ManagementWindows SecurityCloud Security FundamentalsCloud Security Best PracticesContainer Security — Information SecurityData Security in the CloudCloud Identity and Access ManagementKubernetes SecurityShared Responsibility Model — Information SecurityIntroduction to Digital ForensicsDisk ForensicsDigital Evidence CollectionDigital Forensic ToolsIncident Investigation ProceduresMemory ForensicsNetwork ForensicsContainment StrategiesDetection and Analysis PhaseEradication and RecoveryIntroduction to Incident ResponseIncident Response LifecycleIncident Response PlaybooksPost-Incident Review and Lessons LearnedBusiness Continuity PlanningDisaster Recovery PlanningRisk Assessment MethodologyIntroduction to Risk ManagementSecurity ControlsThreat ModelingVulnerability AssessmentCompliance ManagementGDPR Data Protection OverviewISO 27001 Information Security ManagementNIST Cybersecurity FrameworkSecurity Audits and AssessmentsSecurity GovernanceSecurity Policies and StandardsCloud Security Interview QuestionsCryptography Interview QuestionsInformation Security CheatsheetInformation Security Interview QuestionsNetwork Security Interview QuestionsGlossary of Information Security TermsImportant Security Concepts ReferenceRecommended Books and Learning ResourcesSecurity Tools OverviewIncident Response LabLog Analysis ProjectNetwork Monitoring ProjectPassword Manager ProjectSecure Login System ProjectVulnerability Scanner ProjectInsider ThreatsMalware Types and AnalysisPhishing Attacks and PreventionRansomware AttacksSecurity Threats OverviewSocial Engineering AttacksSpyware and Surveillance SoftwareTrojan Horse MalwareComputer VirusesNetwork Worms
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
Example
Core Secure Coding Principles:
=================================
1. INPUT VALIDATION
- Validate all input on server side
- Use whitelist (allowlist) over blacklist
- Validate type, length, range, format
2. OUTPUT ENCODING
- Encode output based on context (HTML, JS, URL, CSS)
- Use framework-provided encoding functions
- Never trust stored data
3. AUTHENTICATION & SESSION
- Use proven frameworks (never roll your own)
- Implement proper password policies
- Regenerate sessions after login
4. ACCESS CONTROL
- Deny by default
- Check authorization on every request
- Validate object-level access
5. ERROR HANDLING
- Never expose stack traces to users
- Log errors securely server-side
- Fail securely (deny access on error)
Input Validation Framework
Example
import re
from typing import Any
from dataclasses import dataclass
@dataclass
class ValidationRule:
field: str
required: bool = True
min_length: int = 0
max_length: int = 1000
pattern: str = None
allowed_values: list = None
class InputValidator:
"""Comprehensive input validation."""
def validate(self, data: dict, rules: list) -> dict:
errors = []
cleaned = {}
for rule in rules:
value = data.get(rule.field)
# Required check
if rule.required and (value is None or value == ''):
errors.append(f"{rule.field} is required")
continue
if value is None:
continue
# Type coercion and length
value = str(value).strip()
if len(value) < rule.min_length:
errors.append(f"{rule.field} too short (min {rule.min_length})")
if len(value) > rule.max_length:
errors.append(f"{rule.field} too long (max {rule.max_length})")
# Pattern matching (whitelist)
if rule.pattern and not re.match(rule.pattern, value):
errors.append(f"{rule.field} contains invalid characters")
# Allowed values (enum)
if rule.allowed_values and value not in rule.allowed_values:
errors.append(f"{rule.field} has invalid value")
cleaned[rule.field] = value
return {"valid": len(errors) == 0, "errors": errors, "data": cleaned}
# Usage
validator = InputValidator()
result = validator.validate(
{"username": "alice123", "email": "alice@example.com", "role": "user"},
[
ValidationRule("username", pattern=r'^[a-zA-Z0-9_]{3,20}$'),
ValidationRule("email", pattern=r'^[\w.+-]+@[\w-]+\.[\w.-]+$'),
ValidationRule("role", allowed_values=["user", "admin"]),
]
)
Secure Error Handling
python example
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.
Continue the lesson path
Study next in this module
01Web SecurityHTTPS and SSL/TLSDeep dive into HTTPS, SSL/TLS protocol handshake, certificate verification, cipher suites, and secure transport layer communication.02Web SecuritySession Management SecurityBest practices for secure session management including token generation, cookie attributes, fixation prevention, and timeout strategies.03Web SecurityFile Upload SecuritySecuring file upload features against malicious uploads including shell injection, path traversal, MIME type attacks, and implementing proper server-side validation.04Web SecuritySQL Injection Attacks and PreventionComplete guide to SQL injection vulnerabilities covering attack types, exploitation techniques, prevention with parameterized queries, and real-world case studies.