Create Secure Website Foundations And Advanced Strategies

Published

create secure website
Table of Contents

Building a secure website is no longer optional but a critical imperative in an era where cyber threats evolve at unprecedented speeds. From foundational security principles like the CIA triad to advanced encryption strategies and infrastructure hardening, every layer of defense must be meticulously designed to safeguard user data and maintain operational integrity. This guide dissects actionable frameworks, from OWASP Top 10 compliance to zero-trust architecture, while integrating security seamlessly into development workflows through automated tools and defensive coding practices.

The modern web demands more than reactive measures—it requires proactive, layered defenses that address authentication vulnerabilities, data encryption, and infrastructure risks. Whether deploying multi-factor authentication, implementing field-level encryption for sensitive fields, or configuring a hardened cloud environment with least-privilege access, each decision shapes the resilience of your digital assets. By adopting structured methodologies—such as role-based access control, secure file upload systems, and Web Application Firewalls—organizations can mitigate risks while optimizing performance and scalability.

create secure website

Core Security Foundations for Website Development

Website security is built upon a structured framework of principles, frameworks, and technical implementations that mitigate risks at every stage of development. The CIA triad—Confidentiality, Integrity, and Availability—serves as the cornerstone, ensuring data protection, trustworthiness, and uninterrupted access. Modern architectures increasingly adopt least privilege and zero-trust models, where access is granted minimally and continuously verified. These principles must be embedded into architecture, coding practices, and infrastructure to create a defense-in-depth strategy.

Security frameworks like OWASP Top 10 and NIST SP 800-53 provide actionable guidelines tailored to web applications. While OWASP focuses on common vulnerabilities (e.g., injection, broken authentication), NIST offers broader risk management controls. Implementing these frameworks requires aligning technical controls with business objectives, such as encrypting data in transit (TLS 1.3) and enforcing multi-factor authentication (MFA).

Foundational Security Principles and Their Application in Web Architecture

The CIA triad defines core security objectives:
  • Confidentiality ensures unauthorized users cannot access data (e.g., via encryption, role-based access control).
  • Integrity guarantees data remains unaltered (e.g., checksums, digital signatures).
  • Availability maintains system uptime (e.g., DDoS protection, redundant servers).
  • Least privilege limits user/system permissions to only what is necessary, reducing attack surfaces. Zero trust eliminates implicit trust, requiring authentication and authorization for every request, even within internal networks. For example, a web application should:

  • Enforce JWT validation for API requests.
  • Use short-lived tokens with strict scope.
  • Log and monitor all access attempts.
  • Defense-in-depth combines multiple layers (network, application, data) to prevent single-point failures. A breach in one layer (e.g., SQL injection) should not compromise the entire system.

    Comparison of Security Frameworks: OWASP Top 10 vs. NIST Guidelines

    Security frameworks provide structured approaches to identify and mitigate risks. Below is a comparison of OWASP Top 10 (2021) and NIST SP 800-53, with actionable steps for web developers:
    FrameworkFocus AreaKey ControlsImplementation Steps
    OWASP Top 10Application-layer vulnerabilitiesInjection, Broken Authentication, Sensitive Data Exposure, etc.Use parameterized queries (prevent SQLi), enforce password policies, and sanitize inputs.
    NIST SP 800-53System-wide risk managementAccess Control (AC), Audit and Accountability (AU), System and Information Integrity (SI).Deploy SIEM tools (e.g., Splunk), enforce least privilege, and conduct penetration testing.
    OWASP Top 10 is ideal for developers, while NIST aligns with enterprise compliance (e.g., FedRAMP, ISO 27001). For example:
  • OWASP recommends Content Security Policy (CSP) to mitigate XSS.
  • NIST mandates continuous monitoring (AU-12) for anomaly detection.
  • Actionable Insight: Combine OWASP’s vulnerability-focused controls with NIST’s risk management processes. For instance, use OWASP ZAP for dynamic testing and NIST’s SCAP for compliance automation.

    Essential Security Headers and Their Configurations for Apache/Nginx

    Security headers harden HTTP responses against exploits like XSS, clickjacking, and data leakage. Below is a checklist of critical headers with server-specific configurations:

    Context: Headers like CSP, HSTS, and X-Frame-Options must be deployed during development and enforced in production. Misconfigurations (e.g., overly permissive CSP) can break functionality.

    HeaderPurposeApache ConfigurationNginx Configuration
    Content Security Policy (CSP)Mitigates XSS by restricting resource sources.`Header always set Content-Security-Policy "default-src 'self'; script-src 'self' https:; object-src 'none'"``add_header Content-Security-Policy "default-src 'self'; script-src 'self' https:; object-src 'none'";`
    HTTP Strict Transport Security (HSTS)Enforces HTTPS to prevent SSL stripping.`Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"``add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";`
    X-Frame-OptionsPrevents clickjacking by denying iframe embedding.`Header always set X-Frame-Options "DENY"``add_header X-Frame-Options "DENY";`
    X-Content-Type-OptionsStops MIME-sniffing attacks.`Header always set X-Content-Type-Options "nosniff"``add_header X-Content-Type-Options "nosniff";`
    Referrer-PolicyControls referral information leakage.`Header always set Referrer-Policy "strict-origin-when-cross-origin"``add_header Referrer-Policy "strict-origin-when-cross-origin";`
    Best Practices:
  • Test headers using SecurityHeaders.com or Mozilla Observatory.
  • Use mod_headers (Apache) or ngx_headers_module (Nginx) for dynamic header management.
  • For CSP, start with a report-only mode (`Content-Security-Policy-Report-Only`) to avoid breaking applications.
  • Critical Note: HSTS must be preloaded via Google’s HSTS Preload List for maximum effectiveness. CSP should be incrementally tightened and monitored via CSP violation reports.

    Integrating Security into the Software Development Lifecycle (SDLC)

    Security must be baked into every SDLC phase, from requirements to deployment. Below is a structured approach with tools and examples:

    Context: Traditional SDLC models often treat security as an afterthought. DevSecOps shifts security left, embedding it into CI/CD pipelines.

    SDLC PhaseSecurity ActivityTools/Examples
    RequirementsIdentify security requirements (e.g., GDPR compliance, data classification).Threat modeling (STRIDE), OWASP ASVS.
    DesignArchitect for security (e.g., microservices isolation, API gateways).OWASP Architecture Review, CIS Benchmarks.
    DevelopmentEnforce secure coding practices (e.g., input validation, encryption).Static Application Security Testing (SAST): SonarQube, Bandit.
    TestingConduct dynamic analysis (DAST) and penetration testing.DAST: OWASP ZAP, Burp Suite. Pen Testing: Metasploit, Cobalt Strike.
    DeploymentHarden infrastructure (e.g., container security, secret management).Kubernetes: Pod Security Policies (PSP). Secrets: HashiCorp Vault, AWS Secrets Manager.
    MonitoringDetect and respond to anomalies in real-time.SIEM: Splunk, ELK Stack. Runtime Protection: Aqua Security, Prisma Cloud.
    Code Example: Integrating SonarQube for SAST in CI/CD

    # GitHub Actions workflow for SonarQube analysis
    name: SonarQube Scan
    on: [push]
    jobs:
    sonarqube:
    runs-on: ubuntu-latest
    steps:

  • uses: actions/checkout@v2
  • name: SonarQube Scan
  • uses: SonarSource/sonarqube-scan-action@master
    env:
    SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
    SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

    Key Metrics to Monitor:

  • Vulnerability density (critical/high issues per 1,000 lines of code).
  • Security hotspots (potential flaws requiring manual review).
  • Compliance gaps (e.g., OWASP ASVS Level 1 failures).
  • DevSecOps Principle: Automate security checks in pipelines (e.g., fail

    Secure Authentication and Authorization Mechanisms

    Authentication and authorization form the bedrock of website security, ensuring that only legitimate users access resources while maintaining data integrity and confidentiality. Secure mechanisms mitigate risks such as credential theft, privilege escalation, and unauthorized data exposure. This section explores multi-factor authentication (MFA) workflows, role-based access control (RBAC) implementation, password storage best practices, and OAuth/OpenID Connect flows, with practical examples and security trade-offs.

    Multi-Factor Authentication (MFA) Implementation

    MFA enhances security by requiring users to provide two or more verification factors, reducing reliance on passwords alone. Hardware tokens (e.g., YubiKey, RSA SecurID) and software tokens (e.g., TOTP via Google Authenticator) are commonly used, with fallback methods ensuring accessibility during token failures.

    Hardware/Software Token Workflows
    Hardware tokens generate one-time passwords (OTPs) via cryptographic challenges, while software tokens rely on time-based or counter-based algorithms. Both require:

  • Registration Phase: User enrollment via QR code scanning (TOTP) or physical device pairing.
  • Authentication Phase: Submission of OTP alongside credentials, with server-side validation against stored secrets.
  • Fallback Methods: SMS-based OTPs or backup codes for users without hardware access, documented in compliance policies.
  • Example Workflow (TOTP with PHP)

    // Generate TOTP secret during registration (e.g., using Google Authenticator)
    $secret = bin2hex(random_bytes(10)); // Base32-encoded secret stored securely
    $qrCodeUrl = 'otpauth://totp/Issuer:User?secret=' . base32_encode($secret) . '&issuer=Issuer';

    // Validate OTP during login
    $otp = $_POST['otp'];
    $timeStep = floor(time() / 30);
    $hash = hash_hmac('sha1', str_pad($timeStep, 8, '0', STR_PAD_LEFT), base32_decode($secret));
    $code = substr(hash_hmac('sha1', $hash, ''), -6);
    if ($otp === $code) { / Proceed / }

    Security Considerations

  • Token Synchronization: Ensure time drift handling (e.g., ±30 seconds for TOTP).
  • Phishing Resistance: Enforce FIDO2/U2F for hardware tokens to prevent man-in-the-middle attacks.
  • Backup Codes: Rotate codes post-use and store encrypted in the database.
  • Role-Based Access Control (RBAC) with Database Schema

    RBAC restricts system access based on user roles, reducing administrative overhead and enforcing least-privilege principles. A well-designed schema separates roles, permissions, and user-role assignments, with permission matrices defining granular controls.

    Database Schema Example (PostgreSQL)

    CREATE TABLE roles (
    role_id SERIAL PRIMARY KEY,
    name VARCHAR(50) UNIQUE NOT NULL, -- e.g., 'admin', 'editor'
    description TEXT
    );

    CREATE TABLE permissions (
    permission_id SERIAL PRIMARY KEY,
    name VARCHAR(50) UNIQUE NOT NULL, -- e.g., 'create_post', 'delete_user'
    resource VARCHAR(50) NOT NULL
    );

    CREATE TABLE role_permissions (
    role_id INT REFERENCES roles(role_id),
    permission_id INT REFERENCES permissions(permission_id),
    PRIMARY KEY (role_id, permission_id)
    );

    CREATE TABLE users (
    user_id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    -- Other fields...
    );

    CREATE TABLE user_roles (
    user_id INT REFERENCES users(user_id),
    role_id INT REFERENCES roles(role_id),
    PRIMARY KEY (user_id, role_id)
    );

    Permission Matrix for Common Roles

    Permission Guest Editor Admin
    View Posts ✓ ✓ ✓
    Create Post ✓ ✓
    Delete User ✓
    Manage Roles ✓
    Implementation Best Practices
  • Dynamic Permissions: Use middleware (e.g., Express.js `isAuthorized`) to enforce checks at runtime.
  • Audit Logging: Log permission changes for compliance (e.g., `user_id`, `action`, `timestamp`).
  • Role Hierarchies: Avoid circular dependencies (e.g., `admin` inheriting from `editor`).
  • Password Storage Best Practices

    Weak password storage (e.g., plaintext, MD5) enables credential stuffing and brute-force attacks. Modern hashing algorithms (bcrypt, Argon2) incorporate salt, adaptive cost factors, and memory-hard functions to resist attacks.

    Algorithm Comparison

    AlgorithmKey FeaturesSecurity Notes
    bcryptAdaptive cost, saltedDefault in many frameworks (e.g., Django).
    Argon2Memory-hard, resistant to GPU attacksWinner of PHC, recommended for high-risk systems.
    PBKDF2Iteration-based, saltedLess secure than bcrypt/Argon2.
    Code Snippets for Secure Hashing
  • PHP (bcrypt)
  • $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
    if (password_verify($input_password, $hash)) { / Valid / }

    - Python (Argon2)

    import argon2
    ph = argon2.PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)
    hash = ph.hash("password")
    ph.verify(hash, "password") # Raises exception on failure

    - JavaScript (bcrypt via Node.js)

    const bcrypt = require('bcrypt');
    const saltRounds = 10;
    const hash = await bcrypt.hash(password, saltRounds);
    const match = await bcrypt.compare(inputPassword, hash);

    Critical Practices

  • Salting: Use cryptographically secure salts (e.g., `random_bytes(16)`) per password.
  • Cost Factors: Adjust based on system performance (e.g., `cost=12` for bcrypt).
  • Rainbow Table Protection: Store only hashes, never plaintext or reversible encryptions.
  • OAuth 2.0/OpenID Connect Flows and Security Trade-offs

    OAuth 2.0 delegates authorization, while OpenID Connect (OIDC) extends it for identity verification. Each flow balances security with usability, with trade-offs in token management and attack surfaces.

    Flow Comparison Table

    Flow Use Case Security Trade-offs Mitigations
    Authorization Code Server-side apps (high security) Requires PKCE for public clients; token exchange via backend. Use HTTPS, short-lived codes, and PKCE for mobile/web.
    Implicit (Deprecated) Legacy single-page apps (SPAs) No server-side validation; access tokens exposed in client. Avoid; migrate to Authorization Code + PKCE.
    PKCE (Proof Key for Code Exchange) Public clients (mobile/web) Adds complexity but prevents code interception. Mandatory for OAuth 2.1; use `code_challenge` and `code_verifier`.
    Client Credentials Machine-to-machine (no user) Tokens stored in client; risk of leakage. Restrict scope; rotate credentials frequently.
    OpenID Connect Extensions
  • ID
  • create secure website - Ilustrasi 2

    Data Protection and Encryption Strategies

    Data integrity, confidentiality, and availability are foundational to secure website development. Encryption serves as a critical mechanism to safeguard sensitive information from unauthorized access, whether in transit or at rest. Modern encryption standards—such as AES-256 for data at rest and TLS 1.3 for data in transit—mitigate risks of interception, tampering, and exfiltration. Equally critical is the implementation of robust key management workflows, which ensure cryptographic keys are generated, stored, rotated, and revoked securely. This section explores encryption methodologies, SQL injection mitigation techniques, secure file handling, and field-level encryption for sensitive data, emphasizing practical deployment and performance trade-offs.

    Encryption Methods for Data at Rest and in Transit

    Data encryption protects information from unauthorized access by transforming it into an unreadable format without the appropriate cryptographic keys. The choice of encryption method depends on the data’s state (rest or transit) and compliance requirements.

    Encryption for Data at Rest
    Data at rest includes stored databases, files, and backups. AES (Advanced Encryption Standard) is the gold standard for symmetric encryption, with AES-256 providing 256-bit keys for robust security. Transparent Data Encryption (TDE) automates encryption by encrypting entire databases or filesystems without application-level changes. Key management is critical; keys must be stored in Hardware Security Modules (HSMs) or cloud-based Key Management Services (KMS) like AWS KMS or Azure Key Vault.

    AES-256 Encryption Example (Python using PyCryptodome):
    ```python
    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes

    key = get_random_bytes(32) # 256-bit key
    cipher = AES.new(key, AES.MODE_GCM)
    plaintext = b"Sensitive data to encrypt"
    ciphertext, tag = cipher.encrypt_and_digest(plaintext)
    ```

    Encryption for Data in Transit
    Data in transit is vulnerable during transmission between clients and servers. TLS 1.3 is the current standard, offering forward secrecy, reduced latency, and improved security against downgrade attacks. Mutual TLS (mTLS) extends this by requiring both client and server to authenticate, suitable for high-security environments like APIs or internal services.
    TLS 1.3 Configuration (Nginx Example):
    ```
    ssl_protocols TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256';
    ```
    Key Management Workflows
    Keys must be rotated periodically (e.g., annually or after exposure) and stored securely. Best practices include:
  • Key Hierarchy: Use a master key to derive data encryption keys (DEKs) for granular access control.
  • Automated Rotation: Integrate key rotation with CI/CD pipelines to minimize downtime.
  • Access Controls: Restrict key access via IAM policies or HSM-based authentication.
  • SQL Injection Prevention Techniques

    SQL injection exploits vulnerabilities in dynamic SQL queries to manipulate databases. Prepared statements (parameterized queries) and Object-Relational Mapping (ORM) frameworks are primary defenses. Below are technical implementations across languages.

    Prepared Statements
    Prepared statements separate SQL logic from data, preventing malicious input from altering query structure.

    SQL (PostgreSQL Example):
    ```sql
    -- Vulnerable (String Concatenation)
    query = "SELECT FROM users WHERE username = '" + user_input + "'";

    -- Secure (Parameterized Query)
    query = "SELECT FROM users WHERE username = $1";
    cursor.execute(query, (user_input,));
    ```

    ORM Best Practices
    ORMs like SQLAlchemy (Python) or Sequelize (Node.js) abstract SQL, reducing injection risks. Below are secure implementations:
    Python (SQLAlchemy):
    ```python
    from sqlalchemy import create_engine, text

    engine = create_engine("postgresql://user:pass@localhost/db")
    with engine.connect() as conn:
    result = conn.execute(text("SELECT FROM users WHERE username = :username"),
    {"username": user_input})
    ```

    Node.js (Sequelize):
    ```javascript
    const user = await User.findOne({
    where: { username: req.body.username },
    // Sequelize automatically escapes inputs
    });
    ```
    Additional Mitigations
  • Input Validation: Reject non-alphanumeric characters where applicable (e.g., usernames).
  • Least Privilege: Database users should have minimal required permissions.
  • Web Application Firewalls (WAFs): Deploy rules to detect and block SQLi patterns.
  • Secure File Upload System Design

    File uploads introduce risks of malware, sensitive data exposure, and storage abuse. A defense-in-depth approach combines client-side validation, server-side scanning, and secure storage practices.

    Client-Side Validation
    Validate file types, sizes, and formats before upload to reduce server load and mitigate risks. Use libraries like `file-type` (Node.js) or `Pillow` (Python) to verify MIME types.

    JavaScript (Client-Side Check):
    ```javascript
    const allowedTypes = ["image/jpeg", "image/png"];
    if (!allowedTypes.includes(file.type)) {
    throw new Error("Invalid file type");
    }
    ```
    Server-Side Scanning
    Deploy antivirus tools like ClamAV to scan uploads for malware. Integrate with APIs or CLI tools for automated scanning.
    Python (ClamAV Integration):
    ```python
    import clamd

    cd = clamd.ClamdUnixSocket()
    scan_result = cd.scan("/path/to/uploaded_file")
    if scan_result:
    raise ValueError("Malware detected")
    ```

    Storage Best Practices
  • S3 Bucket Policies: Enforce encryption (SSE-S3 or SSE-KMS) and restrict public access.
  • Chunked Uploads: Use multipart uploads (e.g., AWS S3 Multipart Upload) for large files to avoid timeouts.
  • Immutable Storage: Configure object lock (e.g., AWS S3 Object Lock) to prevent deletion/modification.
  • AWS S3 Bucket Policy (Encryption Enforcement):
    ```json
    {
    "Version": "2012-10-17",
    "Statement": [
    {
    "Effect": "Deny",
    "Principal": "*",
    "Action": "s3:PutObject",
    "Resource": "arn:aws:s3:::bucket-name/*",
    "Condition": {
    "StringNotEquals": {"s3:x-amz-server-side-encryption": "AES256"}
    }
    }
    ]
    }
    ```

    Field-Level Encryption for Sensitive Data

    Field-level encryption (FLE) protects specific database columns (e.g., credit card numbers, PII) by encrypting data before storage. Libraries like AWS KMS or OpenSSL provide tools for key management and encryption.

    AWS KMS Integration
    AWS KMS handles key generation, rotation, and encryption. Use the `aws-kms` SDK to encrypt/decrypt fields.

    Python (AWS KMS Encryption):
    ```python
    import boto3
    from botocore.exceptions import ClientError

    kms = boto3.client("kms")
    key_id = "arn:aws:kms:us-east-1:123456789012:key/abcd1234"

    def encrypt_data(plaintext):
    try:
    response = kms.encrypt(KeyId=key_id, Plaintext=plaintext.encode())
    return response["CiphertextBlob"]
    except ClientError as e:
    raise e

    encrypted_data = encrypt_data("4111111111111111") # Credit card example
    ```

    OpenSSL for Custom Encryption
    For non-cloud environments, OpenSSL provides symmetric encryption (e.g., AES-256) with manual key management.
    Bash (OpenSSL Encryption):
    ```bash

    Encrypt

    echo "SensitiveData" | openssl enc -aes-256-cbc -base64 -out encrypted.txt -pass pass:securepassword

    # Decrypt
    openssl enc -d -aes-256-cbc -base64 -in encrypted.txt -pass pass:securepassword
    ```

    Performance Considerations
  • Overhead: Field-level encryption adds latency (~10–50ms per operation). Optimize by caching encryption keys in memory.
  • Query Limitations: Encrypted fields cannot be indexed or searched natively; use searchable encryption (e.g., AWS KMS with CloudSearch) or deterministic encryption for specific use cases.
  • Key Rotation: Automate key rotation to mitigate exposure risks, but test impacts on application performance.

    Defensive Programming and Vulnerability Mitigation

  • Defensive programming integrates security best practices into the development lifecycle to proactively identify and mitigate vulnerabilities before deployment. This approach minimizes attack surfaces by enforcing strict input validation, output encoding, and secure coding patterns while leveraging framework-specific protections. Below, frameworks like React, Django, and Laravel are examined for vulnerability mitigation, alongside secure coding patterns for Java, Ruby, and Go. Additionally, Web Application Firewall (WAF) implementation and penetration testing workflows are detailed to ensure comprehensive defense.

    Mitigating Common Vulnerabilities in Modern Frameworks

    Frameworks abstract many security risks but require explicit configuration to address vulnerabilities like Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and Server-Side Request Forgery (SSRF). Below are framework-specific implementations with context-aware protections.

    React (Client-Side XSS Mitigation)
    React’s virtual DOM inherently reduces XSS risks by escaping dynamic content, but unsafe practices (e.g., `dangerouslySetInnerHTML`) require explicit safeguards.

    Use `DOMPurify` for sanitization or React’s built-in `escape` utilities:
    ```jsx
    import DOMPurify from 'dompurify';
    const cleanInput = DOMPurify.sanitize(userInput);
    return
    {cleanInput}
    ;
    ```
    Django (CSRF and SSRF Protection)
    Django’s middleware enforces CSRF tokens by default, but SSRF risks require explicit URL validation.
    Validate URLs against a whitelist:
    ```python
    from django.core.validators import URLValidator
    validator = URLValidator()
    try:
    validator(user_url) # Raises ValidationError for unsafe URLs
    except:
    raise ValueError("Invalid or malicious URL")
    ```
    Laravel (SQL Injection Prevention)
    Laravel’s Eloquent ORM uses prepared statements, but raw queries demand parameterization.
    Use query builder with binding:
    ```php
    $users = DB::table('users')
    ->where('name', '=', $request->input('name'))
    ->get();
    ```

    Secure Coding Patterns and Anti-Patterns

    Secure coding patterns enforce input validation, output encoding, and least-privilege principles. Below is a comparative table for Java, Ruby, and Go, alongside anti-patterns to avoid.
    Pattern Java (Spring) Ruby (Rails) Go Avoid
    Input Validation @Valid @RequestBody UserDto with Hibernate Validator validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } if !regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString(input) { return errors.New("Invalid") } Trusting user input without validation (e.g., SQL queries with string concatenation).
    Output Encoding StringEscapeUtils.escapeHtml4(userInput) (Apache Commons Text) CGI.escapeHTML(userInput) html.EscapeString(userInput) (Go’s html package) Directly embedding user input in HTML/JavaScript without encoding.
    Secure Session Handling @CookieValue("JSESSIONID") String sessionId with HttpOnly/Secure flags config.session_options[:same_site] = :strict http.SetCookie(&http.Cookie{Name: "session", HttpOnly: true, Secure: true}) Storing sensitive data in session cookies or using insecure attributes.

    Web Application Firewall (WAF) Implementation

    A WAF filters malicious traffic by inspecting HTTP requests against custom rules. Below outlines the deployment of ModSecurity and Cloudflare, with examples for blocking SQLi and XSS payloads.

    ModSecurity Rule Example (SQL Injection Blocking)
    ```apache
    SecRule REQUEST_FILENAME "@beginsWith /api/" \
    "id:1001,phase:2,t:none,pass,nolog,ctl:ruleRemoveById=941110"
    SecRule ARGS "@detectSQLi" \
    "id:1002,phase:2,t:urlDecodeUni,log,deny,status:403,msg:'SQL Injection Attempt'"
    ```

    Cloudflare WAF Rule (XSS Payload Blocking)
    1. Navigate to Security > WAF > Custom Rules.
    2. Add a rule with:

  • Field: `uri`
  • Operator: `contains`
  • Value: `