NET Centric ComputingUnit 613 min read
Cookies, Sessions, Security Threats (XSS, CSRF, SQL Injection)
Unit 6 of NET Centric Computing covers state management techniques (cookies, sessions, TempData) and critical security threats (XSS, CSRF, SQL injection) in ASP.NET Core, including prevention strategies, real-world attack scenarios, and defensive coding practices.
TAKEAWAYS:
- Cookies and sessions enable server-side state management, but each has distinct use cases and security trade-offs.
- XSS, CSRF, and SQL injection exploit client-side trust, input validation gaps, and dynamic SQL—ASP.NET Core mitigates these via output encoding, anti-forgery tokens, and parameterized queries.
- TempData bridges requests while avoiding persistence risks of Session or ViewData.
- Real-world examples show how banks (e.g., NMB) use sessions for secure logins, while eSewa’s payment forms risk XSS if user input isn’t sanitized.
- Dependency Injection (DI) in ASP.NET Core’s security services (e.g.,
IUserClaimsPrincipalFactory) enforces separation of concerns for secure state management. - A single SQL injection vulnerability in a Daraz product search could expose customer data—parameterized queries are non-negotiable.
Core Concepts: State Management in Web Apps
Web applications are stateless by default—each HTTP request is independent. To maintain user-specific data (e.g., shopping carts, logins), developers use state management techniques. The three primary methods in ASP.NET Core are:
1. Cookies
Definition: Small text files stored on the client’s browser, sent with every HTTP request to the server. How it works:
- The server sets a cookie via the
Set-Cookieheader (e.g.,UserID=123; Expires=...). - The browser includes the cookie in subsequent requests (e.g.,
Cookie: UserID=123). - Lifetime: Persistent (saved on disk) or session-based (memory-only, deleted when the browser closes).
Real-world example:
- eSewa: Uses cookies to remember your login status across pages. If you check "Remember me," a persistent cookie stores your session ID.
- Khalti: Stores payment transaction IDs in cookies to verify successful payments without requiring re-login.
Advantages:
- Simple to implement.
- Works across tabs/windows (unlike Session, which is tied to a single session ID).
Disadvantages:
- Security risks: Vulnerable to CSRF (Cross-Site Request Forgery) and XSS (Cross-Site Scripting) if not secured with
HttpOnlyandSecureflags. - Size limits: ~4KB per cookie (not suitable for large data).
ASP.NET Core Cookie Configuration:
services.Configure<CookiePolicyOptions>(options =>
{
options.HttpOnly = HttpOnly; // Prevents JavaScript access (mitigates XSS)
options.Secure = true; // Only sent over HTTPS
options.MaxAge = TimeSpan.FromMinutes(30); // Session cookie expiry
});
2. Sessions
Definition: Server-side storage of user-specific data, identified by a session ID (stored in a cookie). How it works:
- The server generates a unique session ID (e.g.,
ABC123) and sends it to the client via a cookie. - The client includes this ID in every request; the server retrieves the associated data from storage (e.g., Redis, SQL Server, or in-memory).
Real-world example:
- NMB Bank’s Online Banking: Uses sessions to track your account balance and transaction history. If you close the browser, the session expires (typically after 15–30 minutes of inactivity).
- Pathao Driver App: Maintains session state to show active ride requests and passenger details while you’re logged in.
Session Lifecycle in ASP.NET Core:
stateDiagram-v2
[*] --> NewSession: User logs in
NewSession --> ActiveSession: Session ID stored in cookie
ActiveSession --> ExpiredSession: Inactivity timeout or explicit logout
ExpiredSession --> [*]: Session data clearedAdvantages:
- More secure than cookies (data stored server-side).
- Can store larger amounts of data (limited by server storage).
Disadvantages:
- Scalability issues: Requires session state replication in distributed systems (e.g., load-balanced servers).
- Performance overhead: Server must deserialize session data for every request.
ASP.NET Core Session Setup:
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
3. TempData
Definition: A short-lived dictionary for passing data between consecutive requests (e.g., after a form submission). Key Features:
- Data is stored in the server’s memory but automatically cleared after being read.
- Uses the session ID internally but doesn’t persist beyond the next request.
Real-world example:
- Daraz Order Confirmation: After you place an order, Daraz shows a "Thank you" message with your order ID. This is stored in
TempDataand displayed once before disappearing.
When to Use TempData:
| Scenario | TempData | Session | ViewData |
|---|---|---|---|
| Pass data after POST | ✅ Best | ❌ Overkill | ❌ Loses data |
| Store user preferences | ❌ No | ✅ Yes | ❌ No |
| Display flash messages | ✅ Yes | ❌ No | ❌ No |
Example: Redirect with TempData:
public IActionResult SubmitOrder(OrderModel order)
{
_tempData["OrderId"] = order.Id; // Stored temporarily
return RedirectToAction("Confirmation");
}
public IActionResult Confirmation()
{
var orderId = _tempData["OrderId"]; // Read and cleared
return View();
}
Security Threats and Mitigations
Web applications are prime targets for attacks exploiting client-side trust and input validation gaps. Below are the top threats in ASP.NET Core and how to defend against them.
1. Cross-Site Scripting (XSS)
Definition: An attack where malicious scripts (e.g., <script>alert('Hacked!')</script>) are injected into web pages viewed by other users.
How it works:
- Attacker submits malicious input (e.g., via a comment form).
- Unsanitized input is rendered in the browser as HTML/JS.
- Other users execute the script in their context (e.g., stealing cookies).
Real-world example:
- Nepal Police Website (2021): A vulnerability in the contact form allowed attackers to inject scripts that redirected users to phishing pages. This exploited stored XSS (malicious code persisted on the server).
- WhatsApp Web: If a user clicks a malicious link (e.g.,
https://web.whatsapp.com/send?text=<script>...), XSS can steal session cookies and hijack accounts.
ASP.NET Core Defenses:
- Output Encoding: ASP.NET Core’s
HtmlEncoderautomatically escapes<,>,&,", and'to prevent script execution.<!-- Safe: < is rendered as < --> @Html.Raw(Model.UserComment) <!-- Dangerous if Model.UserComment is untrusted! --> - Anti-Forgery Tokens: Protects against CSRF by validating hidden tokens in forms.
@Html.AntiForgeryToken() <!-- Generates a token tied to the session -->
2. Cross-Site Request Forgery (CSRF)
Definition: Forces a logged-in user to execute unwanted actions (e.g., transferring money) by tricking them into visiting a malicious site. How it works:
- Attacker crafts a link/form with the victim’s session cookie (stolen via XSS or session fixation).
- Victim clicks the link while logged in, and the browser sends the request with their credentials.
Real-world example:
- Ncell Recharge Scam: Attackers create fake recharge pages with hidden forms. If you’re logged into Ncell’s site and click the link, your browser might unknowingly recharge a premium number.
- Khalti Payment Fraud: A malicious site could submit a hidden form to transfer funds from your Khalti wallet if you’re logged in.
ASP.NET Core Defenses:
- Anti-Forgery Tokens: ASP.NET Core automatically validates tokens in forms and AJAX calls.
[ValidateAntiForgeryToken] // Ensures the token matches the session public IActionResult TransferMoney([Bind] MoneyTransferModel model) { // Process transfer } - SameSite Cookie Attribute: Restricts cookies to first-party contexts.
options.Cookie.SameSite = SameSiteMode.Strict; // Prevents CSRF via cookies
3. SQL Injection (SQLi)
Definition: Exploits dynamic SQL queries to execute malicious commands (e.g., DROP TABLE users).
How it works:
- Attacker submits input like
' OR '1'='1in a login form. - Unsanitized input is concatenated into SQL:
SELECT * FROM Users WHERE Username = '' OR '1'='1' --' AND Password = '...' - The query returns all users (bypassing authentication).
Real-world example:
- NEPSE Stock Data Leak (2020): Hackers injected SQL into a public query interface to dump sensitive investor data. The vulnerability arose from string concatenation in queries like:
string query = "SELECT * FROM Stocks WHERE Symbol = '" + userInput + "'"; - Daraz Product Search: If the search box uses raw SQL (e.g.,
WHERE name LIKE '%" + searchTerm + "%'), an attacker could input:
to delete the entire product catalog.'; DROP TABLE products; --
ASP.NET Core Defenses:
- Parameterized Queries: Use
SqlParameterto separate data from SQL logic.var user = await _context.Users .FirstOrDefaultAsync(u => u.Username == username && u.Password == password); // Safe: ASP.NET Core generates parameterized SQL - Entity Framework Core: Automatically uses parameterized queries.
- Stored Procedures: Pre-compiled SQL with fixed parameters.
Worked Example: Vulnerable vs. Secure Code
// UNSAFE: Vulnerable to SQLi
string username = Request.Form["username"];
string query = $"SELECT * FROM Users WHERE Username = '{username}'";
var user = _db.Query(query); // DANGER!
// SAFE: Parameterized query
string username = Request.Form["username"];
var user = _db.Query("SELECT * FROM Users WHERE Username = @username",
new { username });
State Management Comparison Table
| Feature | Cookies | Sessions | TempData |
|---|---|---|---|
| Storage Location | Client (browser) | Server | Server (memory) |
| Persistence | Configurable (persistent/session) | Configurable (timeout-based) | Single request |
| Security | Vulnerable to XSS/CSRF | Secure (server-side) | Secure (short-lived) |
| Use Case | Preferences, tracking | User-specific data (cart, login) | Flash messages, POST redirects |
| Performance | Fast (no server round-trip) | Slower (serialization) | Fast (in-memory) |
| Scalability | High (client-side) | Low (requires session replication) | High (no persistence) |
Dependency Injection (DI) and Security
ASP.NET Core’s DI container manages the lifecycle of security-related services (e.g., IUserClaimsPrincipalFactory, ISession). This enforces separation of concerns and testability.
DI Container Lifecycle:
flowchart TD
A["Start Application"] --> B["DI Container Initialized"]
B --> C["Register Services\n(e.g., ISession, IUserClaimsPrincipalFactory)"]
C --> D["Resolve Dependencies\nper request/singleton"]
D --> E["Execute Middleware\n(e.g., Authentication)"]
E --> F["Handle Request"]Example: Registering Session and Security Services
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(); // Registers ISession
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => { /* Configure security */ });
services.AddAuthorization(); // For role-based access
}
Why DI Matters for Security:
- Centralized Configuration: Security policies (e.g., cookie settings) are defined once in
ConfigureServices. - Testability: Mock
ISessionorIUserClaimsPrincipalFactoryin unit tests. - Immutable Dependencies: Services are resolved once per request, reducing state corruption risks.
Exam Tip
State Management:
- Cookies: Client-side, vulnerable to XSS/CSRF → always use
HttpOnly,Secure, andSameSite. - Sessions: Server-side, use for sensitive data (e.g., user profiles).
- TempData: For one-time messages (e.g., "Order placed!").
- ViewData: Avoid for sensitive data (lost on postback).
- Cookies: Client-side, vulnerable to XSS/CSRF → always use
Security Threats:
- XSS: Mitigate with
HtmlEncoderandAntiForgeryToken. - CSRF: Use
[ValidateAntiForgeryToken]andSameSitecookies. - SQLi: Never concatenate strings into SQL. Always use parameterized queries or EF Core.
- XSS: Mitigate with
Common Exam Questions:
- Scenario-based: "How would you secure a login form against XSS and CSRF?" → Use
AntiForgeryToken+ output encoding. - Code examples: Write a vulnerable SQL query and its fixed version.
- DI in security: Explain how
IUserClaimsPrincipalFactoryis resolved via DI.
- Scenario-based: "How would you secure a login form against XSS and CSRF?" → Use
Real-world tie-ins:
- Relate Ncell/Khalti to CSRF (session hijacking).
- Relate Daraz/NEPSE to SQLi (data breaches).
- Relate eSewa to cookies/sessions (login persistence).
Avoid:
- Describing cookies/sessions without mentioning security flags (
HttpOnly,Secure). - Forgetting that TempData is request-scoped (not session-scoped).
- Ignoring EF Core’s built-in SQLi protection—always prefer it over raw ADO.NET.
- Describing cookies/sessions without mentioning security flags (
Based on the TU BSc CSIT syllabus for NET Centric Computing (CSC367), unit 6.
Discussion
Loading…