Blog
06 · Cybersecurity & System DefensePart 0121 min read

Cybersecurity Fundamentals: How Web Applications Are Attacked & Defended (OWASP, SQLi, IDOR, XSS & Cryptography)

Hands-on application security for software engineers: vulnerable vs. secure C# code for SQL Injection, IDOR multi-tenant leaks, and XSS, plus salted PBKDF2/Argon2id password hashing and TLS 1.3 / AES-256 encryption.

Emirhan Uluksar
Emirhan Uluksar

Founder & Principal Software Architect · Digital HAT

0 views
Cybersecurity Fundamentals: How Web Applications Are Attacked & Defended (OWASP, SQLi, IDOR, XSS & Cryptography)

When you ship a visual UI bug to production, a customer notices it and opens a support ticket. When you ship a cybersecurity vulnerability to production, your customers don't notice it—automated attack bots scanning your endpoints 24/7 do! When a database is breached or enterprise customer accounts are compromised, what you lose is not merely database rows, but years of hard-earned institutional trust and GDPR / HIPAA compliance.

In this comprehensive application security guide, we skip vague theoretical warnings and compare how an attacker exploits vulnerable code versus how we engineer 100% resilient defenses in C# (.NET 9) and TypeScript side by side.

What You Will Master Step by Step in This Cybersecurity Guide:
1. Defense-in-Depth Architecture and the folder structure of an enterprise .NET security layer.
2. OWASP Top 10 Threat Matrix: Attack vectors, business impact, and definitive engineering mitigations.
3. Attack 1 — SQL Injection (SQLi): How a single quote (' OR 1=1 --) dumps an entire database, and how parameterized queries eliminate it.
4. Attack 2 — IDOR (Insecure Direct Object Reference): The #1 vulnerability in multi-tenant B2B software and how to enforce JWT tenant ownership.
5. Attack 3 — XSS & Browser Security Headers (CSP, HSTS, X-Frame-Options): Writing a production ASP.NET Core security headers middleware.
6. Password Hashing & Authenticated Encryption: Salted PBKDF2-SHA512 / Argon2id with constant-time comparison and AES-256-GCM field-level encryption.
Cybersecurity and OWASP Defense Layers: WAF, TLS 1.3, Parameterized SQL and Argon2

1. Defense-in-Depth Architecture & Enterprise Security Folder Structure

In enterprise software architecture, security never relies on a single perimeter wall. If an attacker bypasses client-side validation, they must hit API rate limiting; if they forge a request parameter, they must hit strict cryptographic tenant-ownership checks; and even if physical database storage were stolen, sensitive fields must remain unreadable due to AES-256-GCM column encryption. Here is how we structure the security core of a production .NET 9 solution:

DigitalHat.Enterprise.Security/
├── 1. Middleware/
│   ├── SecurityHeadersMiddleware.cs          # CSP, HSTS, X-Frame-Options, X-Content-Type-Options
│   └── TenantOwnershipEnforcementFilter.cs   # Prevents IDOR cross-tenant data leaks automatically
├── 2. Cryptography/
│   ├── PasswordHasher.cs                     # 128-bit CSPRNG Salt + PBKDF2-SHA512 + FixedTimeEquals
│   └── AesGcmFieldEncryptor.cs               # Authenticated AES-256-GCM encryption for PII/secrets
├── 3. Authentication/
│   ├── JwtTokenService.cs                    # Short-lived (15 min) Access Token + HttpOnly Refresh Token
│   └── ClaimsPrincipalExtensions.cs          # Tamper-proof CompanyId / UserId extraction from JWT claims
└── 4. Persistence/
    └── ParameterizedQueryRepository.cs       # 100% SQL-Injection-proof EF Core & Dapper queries
OWASP Threat Category Attacker Exploitation Vector Business & Compliance Impact Definitive Engineering Mitigation
A01: Broken Access Control (IDOR) Mutating /api/invoices/1045 to 1046 to read another company's invoice. Cross-tenant B2B data breach, regulatory fines, and contract termination. Enforce WHERE Id = @id AND CompanyId = @jwtCompanyId on every query.
A02: Cryptographic Failures Storing passwords with fast hashes (MD5/SHA1) or leaving PII unencrypted at rest. GPU clusters crack leaked password hashes in seconds via rainbow/brute-force attacks. Salted Argon2id / PBKDF2 (120k+ iterations) for passwords; AES-256-GCM for sensitive PII.
A03: Injection (SQLi / Command) Injecting ' OR 1=1 -- or ; DROP TABLE into login or search fields. Full database exfiltration, authentication bypass, or data destruction. Never concatenate SQL strings; use EF Core LINQ or FromSqlInterpolated.
A07: XSS & Session Hijacking Injecting <script>fetch(...)</script> into profile or comment fields. Arbitrary JavaScript execution in victim browsers and session token theft. Strict HTML Encoding, HttpOnly + Secure + SameSite=Strict cookies, and CSP headers.

2. SQL Injection (SQLi): Vulnerable Code vs. 100% Immune Code

SQL Injection occurs when untrusted user input is concatenated directly into a raw SQL command string. Because data and executable code are mixed in the same text buffer, the database engine interprets user-supplied characters like ' and -- as structural SQL commands:

// ❌ VULNERABLE CODE (NEVER WRITE THIS IN PRODUCTION!):
// Suppose an attacker submits this in the email field:  ' OR 1=1 --
string rawSql = $"SELECT * FROM \"Users\" WHERE \"Email\" = '{request.Email}' AND \"PasswordHash\" = '{hash}'";

// Resulting SQL executed by PostgreSQL:
// SELECT * FROM "Users" WHERE "Email" = '' OR 1=1 --' AND "PasswordHash" = '...'
// In SQL, '--' comments out the remainder of the line! The password check vanishes completely,
// and because '1=1' is always TRUE, the attacker logs in as the first row in the table (usually the System Admin)!

// ✅ SECURE CODE 1 (Entity Framework Core LINQ - Automatically Parameterized):
var user = await _dbContext.Users
    .AsNoTracking()
    .FirstOrDefaultAsync(u => u.Email == request.Email && u.IsActive, ct);

// ✅ SECURE CODE 2 (Raw SQL via FormattableString / FromSqlInterpolated):
// EF Core does NOT concatenate {request.Email}; it binds it as a separate SQL parameter (@p0) over the wire protocol.
// Even if the input contains quotes or SQL keywords, PostgreSQL treats it strictly as a literal string value:
var users = await _dbContext.Users
    .FromSqlInterpolated($"SELECT * FROM \"Users\" WHERE \"Email\" = {request.Email}")
    .AsNoTracking()
    .ToListAsync(ct);

3. IDOR (Insecure Direct Object Reference): The #1 Vulnerability in B2B SaaS

Imagine Company A logs into your B2B platform and fetches its own invoice: GET /api/invoices/8f14e45f-ceea-467a-a838-123456789abc. If an employee at Company A swaps that GUID with another invoice ID and your API returns Company B's confidential financial invoice, your application suffers from an Insecure Direct Object Reference (IDOR) vulnerability.

Placing [Authorize] on a controller only verifies "Is this user logged in?" It does not verify "Does this specific database record belong to the logged-in user's organization (CompanyId / TenantId)?"

// File Path: Features/Invoices/InvoicesController.cs
// ❌ VULNERABLE CONTROLLER (Checks InvoiceId, but fails to verify tenant ownership!):
[Authorize]
[HttpGet("vulnerable/{invoiceId:guid}")]
public async Task<IActionResult> GetInvoiceVulnerable(Guid invoiceId, CancellationToken ct)
{
    var invoice = await _dbContext.Invoices.FirstOrDefaultAsync(x => x.Id == invoiceId, ct);
    return Ok(invoice); // CRITICAL BREACH: Leaks a competitor's confidential invoice!
}

// ✅ HARDENED CONTROLLER (Binds the query to the cryptographically signed CompanyId inside the JWT):
[Authorize]
[HttpGet("{invoiceId:guid}")]
public async Task<IActionResult> GetInvoiceSecure(Guid invoiceId, CancellationToken ct)
{
    // 1. Read the caller's organization ID from the verified JWT claim—NEVER from a query string or request body:
    Guid authenticatedCompanyId = User.GetAuthenticatedCompanyId();

    // 2. Query requires BOTH the InvoiceId AND the authenticated CompanyId to match:
    var invoice = await _dbContext.Invoices
        .AsNoTracking()
        .Where(x => x.Id == invoiceId && x.CompanyId == authenticatedCompanyId)
        .Select(x => new InvoiceDto(x.Id, x.InvoiceNumber, x.TotalAmount, x.IssuedAtUtc))
        .FirstOrDefaultAsync(ct);

    // 3. Return 404 NotFound (instead of 403 Forbidden) so attackers cannot probe whether an ID exists:
    if (invoice is null)
        return NotFound();

    return Ok(invoice);
}

4. Cross-Site Scripting (XSS) & Enterprise Security Headers Middleware

In addition to HTML-encoding untrusted text (WebUtility.HtmlEncode), every production ASP.NET Core application should attach strict browser defense headers via a dedicated middleware:

// File Path: Middleware/SecurityHeadersMiddleware.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace DigitalHat.Enterprise.Security.Middleware;

public sealed class SecurityHeadersMiddleware
{
    private readonly RequestDelegate _next;

    public SecurityHeadersMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext context)
    {
        var headers = context.Response.Headers;

        // 1. Prevent MIME-type sniffing attacks (stops browsers from executing uploaded text files as scripts):
        headers["X-Content-Type-Options"] = "nosniff";

        // 2. Defeat Clickjacking by prohibiting external sites from embedding your app inside an <iframe>:
        headers["X-Frame-Options"] = "DENY";

        // 3. HSTS: Force browsers to connect exclusively over HTTPS for the next 365 days:
        headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains; preload";

        // 4. Lock down referrer leakage and sensitive browser hardware APIs:
        headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
        headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()";

        // 5. Content-Security-Policy (CSP): Only execute scripts originating from our own trusted origin:
        headers["Content-Security-Policy"] =
            "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; frame-ancestors 'none'; object-src 'none';";

        await _next(context);
    }
}

5. Password Hashing (Salted PBKDF2-SHA512) & AES-256-GCM Authenticated Encryption

Passwords must never be encrypted reversibly; they must be one-way hashed using an intentionally slow key-derivation function (PBKDF2-SHA512 or Argon2id) with a unique 128-bit random Salt per user and verified in constant time (CryptographicOperations.FixedTimeEquals) to prevent timing attacks.

Conversely, when you must store reversible sensitive fields (such as tax IDs, IBANs, or third-party API credentials), use AES-256-GCM (Galois/Counter Mode), which provides both confidentiality and a 128-bit cryptographic authentication tag ensuring the ciphertext was never tampered with:

// File Path: Cryptography/EnterpriseCryptographyService.cs
using System;
using System.Security.Cryptography;
using System.Text;

namespace DigitalHat.Enterprise.Security.Cryptography;

public static class PasswordHasher
{
    private const int SaltSize = 16;        // 128-bit cryptographic random salt
    private const int KeySize = 32;         // 256-bit derived hash output
    private const int Iterations = 120_000; // High work factor to neutralize GPU brute-force attacks

    public static (string HashBase64, string SaltBase64) HashPassword(string plainPassword)
    {
        byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);
        byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
            password: plainPassword,
            salt: salt,
            iterations: Iterations,
            hashAlgorithm: HashAlgorithmName.SHA512,
            outputLength: KeySize
        );

        return (Convert.ToBase64String(hash), Convert.ToBase64String(salt));
    }

    public static bool VerifyPassword(string plainPassword, string storedHashBase64, string storedSaltBase64)
    {
        byte[] salt = Convert.FromBase64String(storedSaltBase64);
        byte[] expectedHash = Convert.FromBase64String(storedHashBase64);

        byte[] actualHash = Rfc2898DeriveBytes.Pbkdf2(
            password: plainPassword,
            salt: salt,
            iterations: Iterations,
            hashAlgorithm: HashAlgorithmName.SHA512,
            outputLength: KeySize
        );

        // Constant-time comparison prevents Timing Side-Channel Attacks:
        return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
    }
}

public sealed class AesGcmFieldEncryptor
{
    private readonly byte[] _masterKey; // 32-Byte (256-bit) Master Key injected from environment variables

    public AesGcmFieldEncryptor(byte[] masterKey)
    {
        if (masterKey is null || masterKey.Length != 32)
            throw new ArgumentException("AES-256-GCM master key must be exactly 32 bytes (256 bits).");
        _masterKey = masterKey;
    }

    public string EncryptSensitiveField(string plainText)
    {
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize); // 12-byte (96-bit) unique Nonce
        byte[] cipherBytes = new byte[plainBytes.Length];
        byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize]; // 16-byte (128-bit) Integrity Authentication Tag

        using var aesGcm = new AesGcm(_masterKey, AesGcm.TagByteSizes.MaxSize);
        aesGcm.Encrypt(nonce, plainBytes, cipherBytes, tag);

        // Pack [Nonce (12B) + Tag (16B) + Ciphertext (NB)] into a single Base64 payload:
        byte[] combined = new byte[nonce.Length + tag.Length + cipherBytes.Length];
        Buffer.BlockCopy(nonce, 0, combined, 0, nonce.Length);
        Buffer.BlockCopy(tag, 0, combined, nonce.Length, tag.Length);
        Buffer.BlockCopy(cipherBytes, 0, combined, nonce.Length + tag.Length, cipherBytes.Length);

        return Convert.ToBase64String(combined);
    }
}

6. Up Next: Zero-Trust Network Security & Linux Server Hardening

We have fortified our application code against SQL Injection, IDOR, XSS, password cracking, and data tampering. In Part 2 of our Cybersecurity Series, we drop down to the infrastructure and network layer to configure Zero-Trust Loopback Isolation (127.0.0.1), Linux UFW Firewalls, Fail2Ban automated intrusion blocking, ASP.NET Core Rate Limiting, and zero-leak secret management!

Did you find this engineering guide helpful?

Give it a like or share it with your team and network.

0 views
Share This Guide: