Secure Coding
Comprehensive guidance for writing secure code, covering OWASP Top 10 2025, CWE Top 25, and language-specific security patterns.
When to Use This Skill
Use this skill when:
- Reviewing code for security vulnerabilities
- Implementing input validation or output encoding
- Learning about common security weaknesses (OWASP, CWE)
- Fixing identified security issues
- Writing security-sensitive code (authentication, authorization, data handling)
- Conducting security code reviews
OWASP Top 10 2025 Quick Reference
| Rank |
Vulnerability |
Key Mitigation |
| A01 |
Broken Access Control |
Server-side access checks, deny by default, CORS restrictions |
| A02 |
Security Misconfiguration |
Hardened configs, remove defaults, disable unnecessary features |
| A03 |
Software Supply Chain Failures |
SCA, SBOM, verify dependencies, integrity checks |
| A04 |
Cryptographic Failures |
Strong encryption (AES-256), TLS 1.2+, no deprecated algorithms |
| A05 |
Injection |
Parameterized queries, input validation, context-aware encoding |
| A06 |
Insecure Design |
Threat modeling, secure design patterns, defense in depth |
| A07 |
Authentication Failures |
MFA, strong passwords, secure session management |
| A08 |
Data Integrity Failures |
Digital signatures, integrity verification, secure CI/CD |
| A09 |
Logging & Alerting Failures |
Centralized logging, anomaly detection, audit trails |
| A10 |
Mishandling Exceptions |
Fail securely, generic error messages, complete exception handling |
For detailed mitigations: See OWASP Top 10 2025 Reference
Core Secure Coding Principles
1. Input Validation
Never trust user input. Validate all inputs on the server side.
using System.Text.RegularExpressions;
// Good: Server-side validation with allowlist
public static partial class InputValidation
{
[GeneratedRegex(@"^[a-zA-Z0-9_]{3,20}$")]
private static partial Regex UsernamePattern();
/// <summary>
/// Validate username against allowlist pattern.
/// </summary>
public static bool ValidateUsername(string username) =>
!string.IsNullOrEmpty(username) && UsernamePattern().IsMatch(username);
}
// Bad: No validation
public string ProcessUsername(string username) => username; // Dangerous!
Validation strategies:
- Allowlist validation: Define what IS allowed (preferred)
- Blocklist validation: Define what is NOT allowed (less secure)
- Type checking: Ensure correct data types
- Range checking: Verify values within expected bounds
- Length limits: Prevent buffer overflows and DoS
2. Output Encoding
Encode output based on context to prevent injection attacks.
| Context |
Encoding Method |
Example |
| HTML body |
HTML entity encoding |
<script> |
| HTML attributes |
Attribute encoding |
' for ' |
| JavaScript |
JavaScript encoding |
\x3Cscript\x3E |
| URL parameters |
URL encoding |
%3Cscript%3E |
| CSS |
CSS encoding |
\3C script\3E |
| SQL |
Parameterized queries |
Use prepared statements |
3. Parameterized Queries (Injection Prevention)
Always use parameterized queries for database operations.
// Good: Parameterized query with SqlCommand
using var cmd = new SqlCommand(
"SELECT * FROM Users WHERE Username = @username AND Status = @status",
connection);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@status", status);
// Good: Parameterized query with Dapper
var users = await connection.QueryAsync<User>(
"SELECT * FROM Users WHERE Username = @Username AND Status = @Status",
new { Username = username, Status = status });
// Bad: String interpolation (SQL Injection vulnerable)
var query = $"SELECT * FROM Users WHERE Username = '{username}'"; // VULNERABLE
4. Authentication Security
- Use strong password hashing: Argon2id, bcrypt, scrypt (see
cryptography skill)
- Implement MFA: Time-based OTP, hardware keys, passkeys
- Secure session management: HttpOnly cookies, secure flag, short expiration
- Account lockout: Prevent brute force attacks
- Credential storage: Never store plaintext passwords
5. Authorization Security
- Deny by default: Require explicit permission grants
- Server-side checks: Never rely on client-side authorization
- Verify object ownership: Check user can access requested resource
- Use indirect references: Map internal IDs to user-specific references
- Implement RBAC/ABAC: Use structured access control models
6. Error Handling
// Good: Generic error message to user, detailed logging
public async Task<IActionResult> ProcessData([FromBody] DataRequest request)
{
try
{
await _dataService.ProcessSensitiveDataAsync(request.Data);
return Ok();
}
catch (DbException ex)
{
_logger.LogError(ex, "Database error processing request for user {UserId}", User.GetUserId());
return StatusCode(500, new { error = "An error occurred" });
}
}
// Bad: Exposing internal details
catch (DbException ex)
{
return StatusCode(500, new { error = ex.Message }); // VULNERABLE - exposes internals
}
Error handling rules:
- Return generic error messages to users
- Log detailed errors server-side
- Never expose stack traces, database errors, or internal paths
- Fail securely (deny access on error)
Language-Specific Patterns
JavaScript/TypeScript
// XSS Prevention - use textContent, not innerHTML
element.textContent = userInput; // Safe
element.innerHTML = userInput; // VULNERABLE
// Use DOMPurify for HTML that must be rendered
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
// Avoid eval() and Function()
eval(userInput); // VULNERABLE
new Function(userInput)(); // VULNERABLE
// Use strict mode
'use strict';
C# / .NET
// Safe process execution - use argument list, avoid shell
using System.Diagnostics;
public static async Task<string> SafeExecuteAsync(string command, params string[] args)
{
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = command,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false, // Safe: no shell interpretation
CreateNoWindow = true
}
};
foreach (var arg in args)
process.StartInfo.ArgumentList.Add(arg); // Safe: no shell escaping needed
process.Start();
var output = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
return output;
}
// Bad: Shell injection vulnerable
Process.Start("cmd", $"/c dir {userInput}"); // VULNERABLE
// Safe file operations - prevent path traversal
public static class SafeFileAccess
{
/// <summary>
/// Safely read a file, preventing path traversal attacks.
/// </summary>
public static string SafeReadFile(string baseDir, string filename)
{
var basePath = Path.GetFullPath(baseDir);
var filePath = Path.GetFullPath(Path.Combine(baseDir, filename));
if (!filePath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))
throw new UnauthorizedAccessException("Path traversal detected");
return File.ReadAllText(filePath);
}
}
// Use parameterized queries with Entity Framework
var users = context.Users
.Where(u => u.Username == username) // Safe - parameterized
.ToList();
// Avoid raw SQL when possible, use parameters if needed
var users = context.Users
.FromSqlRaw("SELECT * FROM Users WHERE Username = {0}", username)
.ToList();
// Anti-forgery tokens for CSRF protection
[ValidateAntiForgeryToken]
public IActionResult UpdateProfile(ProfileModel model)
{
// Process update
}
// Input validation with data annotations
public sealed class UserInput
{
[Required]
[StringLength(100, MinimumLength = 3)]
[RegularExpression(@"^[a-zA-Z0-9_]+$")]
public required string Username { get; init; }
}
Security Code Review Checklist
Input Handling
Output Encoding
Authentication
Authorization
Data Protection
Error Handling
Quick Decision Tree
What security concern are you addressing?
- SQL/NoSQL injection → Use parameterized queries, ORMs
- XSS (Cross-Site Scripting) → Context-aware output encoding, CSP
- CSRF → Anti-forgery tokens, SameSite cookies
- Authentication → See
authentication-patterns skill
- Authorization → See
authorization-models skill
- Cryptography → See
cryptography skill
- Secrets/Credentials → See
secrets-management skill
- API Security → See
api-security skill
References
- OWASP Top 10 2025 Detailed Reference - Complete mitigations and examples
- CWE Top 25 Reference - Most dangerous software weaknesses
- Language-Specific Patterns - Per-language security guides
Related Skills
| Skill |
Relationship |
authentication-patterns |
Auth implementation details (JWT, OAuth, Passkeys) |
authorization-models |
Access control (RBAC, ABAC) |
cryptography |
Encryption, hashing, TLS |
api-security |
API-specific security patterns |
secrets-management |
Credential and secret handling |
Version History
- v1.0.0 (2025-12-26): Initial release with OWASP Top 10 2025, core principles
Last Updated: 2025-12-26
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: secure-coding-33description: Provides guidance on secure coding practices including OWASP Top 10 2025, CWE Top 25, input validation, output encoding, and language-specific security patterns. Use when reviewing code for security vulnerabilities, implementing security controls, or learning secure development practices.4---56# Secure Coding78Comprehensive guidance for writing secure code, covering OWASP Top 10 2025, CWE Top 25, and language-specific security patterns.910## When to Use This Skill1112Use this skill when:1314- Reviewing code for security vulnerabilities15- Implementing input validation or output encoding16- Learning about common security weaknesses (OWASP, CWE)17- Fixing identified security issues18- Writing security-sensitive code (authentication, authorization, data handling)19- Conducting security code reviews2021## OWASP Top 10 2025 Quick Reference2223| Rank | Vulnerability | Key Mitigation |24|------|--------------|----------------|25| A01 | Broken Access Control | Server-side access checks, deny by default, CORS restrictions |26| A02 | Security Misconfiguration | Hardened configs, remove defaults, disable unnecessary features |27| A03 | Software Supply Chain Failures | SCA, SBOM, verify dependencies, integrity checks |28| A04 | Cryptographic Failures | Strong encryption (AES-256), TLS 1.2+, no deprecated algorithms |29| A05 | Injection | Parameterized queries, input validation, context-aware encoding |30| A06 | Insecure Design | Threat modeling, secure design patterns, defense in depth |31| A07 | Authentication Failures | MFA, strong passwords, secure session management |32| A08 | Data Integrity Failures | Digital signatures, integrity verification, secure CI/CD |33| A09 | Logging & Alerting Failures | Centralized logging, anomaly detection, audit trails |34| A10 | Mishandling Exceptions | Fail securely, generic error messages, complete exception handling |3536**For detailed mitigations:** See [OWASP Top 10 2025 Reference](references/owasp-top-10-2025.md)3738## Core Secure Coding Principles3940### 1. Input Validation4142**Never trust user input.** Validate all inputs on the server side.4344```csharp45using System.Text.RegularExpressions;4647// Good: Server-side validation with allowlist48public static partial class InputValidation49{50 [GeneratedRegex(@"^[a-zA-Z0-9_]{3,20}$")]51 private static partial Regex UsernamePattern();5253 /// <summary>54 /// Validate username against allowlist pattern.55 /// </summary>56 public static bool ValidateUsername(string username) =>57 !string.IsNullOrEmpty(username) && UsernamePattern().IsMatch(username);58}5960// Bad: No validation61public string ProcessUsername(string username) => username; // Dangerous!62```6364**Validation strategies:**6566- **Allowlist validation**: Define what IS allowed (preferred)67- **Blocklist validation**: Define what is NOT allowed (less secure)68- **Type checking**: Ensure correct data types69- **Range checking**: Verify values within expected bounds70- **Length limits**: Prevent buffer overflows and DoS7172### 2. Output Encoding7374Encode output based on context to prevent injection attacks.7576| Context | Encoding Method | Example |77|---------|----------------|---------|78| HTML body | HTML entity encoding | `<script>` |79| HTML attributes | Attribute encoding | `'` for `'` |80| JavaScript | JavaScript encoding | `\x3Cscript\x3E` |81| URL parameters | URL encoding | `%3Cscript%3E` |82| CSS | CSS encoding | `\3C script\3E` |83| SQL | Parameterized queries | Use prepared statements |8485### 3. Parameterized Queries (Injection Prevention)8687**Always use parameterized queries for database operations.**8889```csharp90// Good: Parameterized query with SqlCommand91using var cmd = new SqlCommand(92 "SELECT * FROM Users WHERE Username = @username AND Status = @status",93 connection);94cmd.Parameters.AddWithValue("@username", username);95cmd.Parameters.AddWithValue("@status", status);9697// Good: Parameterized query with Dapper98var users = await connection.QueryAsync<User>(99 "SELECT * FROM Users WHERE Username = @Username AND Status = @Status",100 new { Username = username, Status = status });101102// Bad: String interpolation (SQL Injection vulnerable)103var query = $"SELECT * FROM Users WHERE Username = '{username}'"; // VULNERABLE104```105106### 4. Authentication Security107108- **Use strong password hashing**: Argon2id, bcrypt, scrypt (see `cryptography` skill)109- **Implement MFA**: Time-based OTP, hardware keys, passkeys110- **Secure session management**: HttpOnly cookies, secure flag, short expiration111- **Account lockout**: Prevent brute force attacks112- **Credential storage**: Never store plaintext passwords113114### 5. Authorization Security115116- **Deny by default**: Require explicit permission grants117- **Server-side checks**: Never rely on client-side authorization118- **Verify object ownership**: Check user can access requested resource119- **Use indirect references**: Map internal IDs to user-specific references120- **Implement RBAC/ABAC**: Use structured access control models121122### 6. Error Handling123124```csharp125// Good: Generic error message to user, detailed logging126public async Task<IActionResult> ProcessData([FromBody] DataRequest request)127{128 try129 {130 await _dataService.ProcessSensitiveDataAsync(request.Data);131 return Ok();132 }133 catch (DbException ex)134 {135 _logger.LogError(ex, "Database error processing request for user {UserId}", User.GetUserId());136 return StatusCode(500, new { error = "An error occurred" });137 }138}139140// Bad: Exposing internal details141catch (DbException ex)142{143 return StatusCode(500, new { error = ex.Message }); // VULNERABLE - exposes internals144}145```146147**Error handling rules:**148149- Return generic error messages to users150- Log detailed errors server-side151- Never expose stack traces, database errors, or internal paths152- Fail securely (deny access on error)153154## Language-Specific Patterns155156### JavaScript/TypeScript157158```typescript159// XSS Prevention - use textContent, not innerHTML160element.textContent = userInput; // Safe161element.innerHTML = userInput; // VULNERABLE162163// Use DOMPurify for HTML that must be rendered164import DOMPurify from 'dompurify';165element.innerHTML = DOMPurify.sanitize(userInput);166167// Avoid eval() and Function()168eval(userInput); // VULNERABLE169new Function(userInput)(); // VULNERABLE170171// Use strict mode172'use strict';173```174175### C# / .NET176177```csharp178// Safe process execution - use argument list, avoid shell179using System.Diagnostics;180181public static async Task<string> SafeExecuteAsync(string command, params string[] args)182{183 using var process = new Process184 {185 StartInfo = new ProcessStartInfo186 {187 FileName = command,188 RedirectStandardOutput = true,189 RedirectStandardError = true,190 UseShellExecute = false, // Safe: no shell interpretation191 CreateNoWindow = true192 }193 };194195 foreach (var arg in args)196 process.StartInfo.ArgumentList.Add(arg); // Safe: no shell escaping needed197198 process.Start();199 var output = await process.StandardOutput.ReadToEndAsync();200 await process.WaitForExitAsync();201 return output;202}203204// Bad: Shell injection vulnerable205Process.Start("cmd", $"/c dir {userInput}"); // VULNERABLE206207// Safe file operations - prevent path traversal208public static class SafeFileAccess209{210 /// <summary>211 /// Safely read a file, preventing path traversal attacks.212 /// </summary>213 public static string SafeReadFile(string baseDir, string filename)214 {215 var basePath = Path.GetFullPath(baseDir);216 var filePath = Path.GetFullPath(Path.Combine(baseDir, filename));217218 if (!filePath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))219 throw new UnauthorizedAccessException("Path traversal detected");220221 return File.ReadAllText(filePath);222 }223}224225// Use parameterized queries with Entity Framework226var users = context.Users227 .Where(u => u.Username == username) // Safe - parameterized228 .ToList();229230// Avoid raw SQL when possible, use parameters if needed231var users = context.Users232 .FromSqlRaw("SELECT * FROM Users WHERE Username = {0}", username)233 .ToList();234235// Anti-forgery tokens for CSRF protection236[ValidateAntiForgeryToken]237public IActionResult UpdateProfile(ProfileModel model)238{239 // Process update240}241242// Input validation with data annotations243public sealed class UserInput244{245 [Required]246 [StringLength(100, MinimumLength = 3)]247 [RegularExpression(@"^[a-zA-Z0-9_]+$")]248 public required string Username { get; init; }249}250```251252## Security Code Review Checklist253254### Input Handling255256- [ ] All inputs validated on server side257- [ ] Allowlist validation used where possible258- [ ] Length limits enforced259- [ ] Type checking performed260- [ ] File uploads validated (type, size, content)261262### Output Encoding263264- [ ] Context-appropriate encoding applied265- [ ] No raw user input in HTML/JS/SQL266- [ ] Content-Type headers set correctly267- [ ] X-Content-Type-Options: nosniff268269### Authentication270271- [ ] Strong password hashing (Argon2id/bcrypt)272- [ ] Session tokens are random and unpredictable273- [ ] Session invalidation on logout274- [ ] Account lockout after failed attempts275- [ ] Credentials transmitted over HTTPS only276277### Authorization278279- [ ] Access control on every request280- [ ] Deny by default policy281- [ ] Object-level authorization checks282- [ ] No direct object references exposed283284### Data Protection285286- [ ] Sensitive data encrypted at rest287- [ ] TLS 1.2+ for data in transit288- [ ] No sensitive data in URLs or logs289- [ ] Proper key management290291### Error Handling292293- [ ] Generic error messages to users294- [ ] Detailed errors logged securely295- [ ] No stack traces exposed296- [ ] Fail securely (deny on error)297298## Quick Decision Tree299300**What security concern are you addressing?**3013021. **SQL/NoSQL injection** → Use parameterized queries, ORMs3032. **XSS (Cross-Site Scripting)** → Context-aware output encoding, CSP3043. **CSRF** → Anti-forgery tokens, SameSite cookies3054. **Authentication** → See `authentication-patterns` skill3065. **Authorization** → See `authorization-models` skill3076. **Cryptography** → See `cryptography` skill3087. **Secrets/Credentials** → See `secrets-management` skill3098. **API Security** → See `api-security` skill310311## References312313- [OWASP Top 10 2025 Detailed Reference](references/owasp-top-10-2025.md) - Complete mitigations and examples314- [CWE Top 25 Reference](references/cwe-top-25.md) - Most dangerous software weaknesses315- [Language-Specific Patterns](references/language-specific/) - Per-language security guides316317## Related Skills318319| Skill | Relationship |320|-------|-------------|321| `authentication-patterns` | Auth implementation details (JWT, OAuth, Passkeys) |322| `authorization-models` | Access control (RBAC, ABAC) |323| `cryptography` | Encryption, hashing, TLS |324| `api-security` | API-specific security patterns |325| `secrets-management` | Credential and secret handling |326327## Version History328329- v1.0.0 (2025-12-26): Initial release with OWASP Top 10 2025, core principles330331---332333**Last Updated:** 2025-12-26334335---336> Converted and distributed by [TomeVault](https://tomevault.io/claim/melodic-software) — claim your Tome and manage your conversions.337<!-- tomevault:4.0:skill_md:2026-04-11 -->