owasp-secure-code
>
Works with
---
name: owasp-secure-code
description: >
license: Apache-2.0
---
# OWASP Secure Code
Proactive secure coding guidance and security auditing based on OWASP Top 10 (2021) and OWASP API Security Top 10 (2023). Operates in two modes: **Proactive Mode** (applied automatically while writing code) and **Audit Mode** (invoked explicitly for a full codebase security review).
## Proactive Mode
When writing or modifying code, automatically apply these detection rules. For each issue found, cite the OWASP category and apply the fix inline.
### Detection Rules
#### 1. SQL/NoSQL Injection (A03:2021 / API8:2023)
**Detect:** String concatenation or template literals used to build SQL/NoSQL queries, raw query methods with user input.
**Enforce:**
- Always use parameterized queries or ORM methods
- Never interpolate user input into query strings
- Validate and type-check all query parameters before use
```typescript
// WRONG
const user = await db.query(`SELECT * FROM users WHERE id = '${req.params.id}'`);
// CORRECT
const user = await prisma.user.findUnique({ where: { id: parseInt(req.params.id) } });
```
#### 2. Cross-Site Scripting / XSS (A03:2021)
**Detect:** `innerHTML`, `dangerouslySetInnerHTML`, `document.write()`, unescaped template engine output (`<%- %>`, `| safe`, `{!! !!}`), `v-html`.
**Enforce:**
- Use framework-native text rendering (React JSX auto-escapes, `{{ }}` in Jinja2 with autoescape)
- Sanitize any required HTML with DOMPurify or equivalent
- Set Content-Security-Policy headers to restrict inline scripts
#### 3. Open Redirect (A01:2021)
**Detect:** User input used in `res.redirect()`, `window.location`, `Location` header, `<meta http-equiv="refresh">`.
**Enforce:**
- Validate redirect URLs against an allowlist of permitted domains/paths
- Use relative paths only, or strip the scheme and host from user input
- Never pass raw user input to redirect functions
#### 4. File Upload Vulnerabilities (A04:2021 / A05:2021)
**Detect:** File upload handlers, `multer`, `express-fileupload`, `MultipartFile`, `UploadFile`, form `enctype="multipart/form-data"`.
**Enforce:**
- Validate MIME type and file extension against an allowlist
- Enforce maximum file size limits
- Store uploaded files outside the webroot with randomized names
- Scan for malware if possible
- Never serve uploaded files directly without content-type validation
#### 5. Insecure Deserialization (A08:2021)
**Detect:** `JSON.parse()` on unvalidated input, `pickle.loads()`, `yaml.load()` (without SafeLoader), Java `ObjectInputStream.readObject()`, `eval()`, `Function()`.
**Enforce:**
- Validate deserialized data with a schema (zod, pydantic, JSON Schema)
- Use safe loaders (`yaml.safe_load`, `SafeLoader`)
- Never use `pickle` or Java native serialization on untrusted input
- Avoid `eval()` and `new Function()` entirely
#### 6. Sensitive Data in Logs (A09:2021)
**Detect:** Logging statements (`console.log`, `logger.info`, `log.debug`, `System.out.println`) that reference variables named `password`, `token`, `secret`, `apiKey`, `creditCard`, `ssn`, `authorization`, `cookie`, `session`.
**Enforce:**
- Redact sensitive fields before logging
- Use structured logging with explicit field allowlists
- Never log full request bodies, headers, or authentication tokens
- Mask PII (show only last 4 digits of card numbers, etc.)
#### 7. Missing Security Headers (A05:2021)
**Detect:** HTTP response creation, Express/Fastify/Flask/Spring app initialization without security header middleware.
**Enforce:**
- Use `helmet` (Node.js), `flask-talisman` (Python), or Spring Security headers
- Required headers: `Content-Security-Policy`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Strict-Transport-Security`, `Referrer-Policy`
- Set `SameSite`, `Secure`, and `HttpOnly` flags on all cookies
#### 8. Broken Authentication (A07:2021 / API2:2023)
**Detect:** Password handling, session creation, JWT signing, login endpoints, token storage.
**Enforce:**
- Hash passwords with bcrypt/scrypt/argon2 (never MD5/SHA-1/SHA-256 alone)
- Use constant-time comparison for tokens and passwords
- Set session expiry and implement token rotation
- Enforce rate limiting on authentication endpoints
- Never store tokens in localStorage (use httpOnly cookies)
#### 9. Information Leakage via Error Handling (A04:2021)
**Detect:** Error handlers, catch blocks that return error details, `app.use(errorHandler)`, stack trace exposure.
**Enforce:**
- Return generic error messages to clients (`"Something went wrong"`)
- Log detailed errors server-side only
- Never expose stack traces, SQL errors, or internal paths in responses
- Use different error detail levels for development vs. production
#### 10. Server-Side Request Forgery (A10:2021 / API7:2023)
**Detect:** `fetch()`, `axios`, `http.get`, `requests.get`, `RestTemplate` with user-controlled URLs.
**Enforce:**
- Validate and allowlist target URLs/domains
- Block requests to internal/private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.169.254)
- Use a URL parser to verify scheme (allow only http/https)
- Disable redirects or re-validate after each redirect
## Audit Mode
When invoked explicitly (e.g., "run a security audit", "OWASP review", "scan for vulnerabilities"), perform a full codebase security review.
### Audit Procedure
1. **Identify the technology stack** — Detect frameworks, languages, and dependencies
2. **Scan for each OWASP Top 10 (2021) category** — A01 through A10
3. **Scan for each OWASP API Security Top 10 (2023) category** — API1 through API10
4. **Rate each finding by severity** — CRITICAL, HIGH, MEDIUM, LOW
5. **Generate the report** using the template below
### Severity Rating Guide
| Severity | Criteria |
|----------|----------|
| CRITICAL | Exploitable with no authentication, leads to data breach or RCE (e.g., SQL injection, unauthenticated admin access) |
| HIGH | Exploitable with low-privilege access, significant data exposure (e.g., broken access control, XSS with session theft) |
| MEDIUM | Requires specific conditions to exploit, limited impact (e.g., missing security headers, verbose errors) |
| LOW | Best practice violation, minimal direct risk (e.g., missing rate limiting, outdated but non-vulnerable dependency) |
### Report Format Template
```markdown
# Security Audit Report
**Date:** YYYY-MM-DD
**Scope:** [files/directories scanned]
**Stack:** [detected technologies]
## Executive Summary
- **CRITICAL:** N findings
- **HIGH:** N findings
- **MEDIUM:** N findings
- **LOW:** N findings
- **Total:** N findings
## Findings
### [SEVERITY] Finding Title — OWASP Category ID
**File:** `path/to/file.ts:42`
**Category:** A03:2021 — Injection
**Description:** Brief explanation of the vulnerability and its potential impact.
**Vulnerable Code:**
\```typescript
// The vulnerable code as found in the codebase
\```
**Recommended Fix:**
\```typescript
// The corrected code with security controls applied
\```
**References:**
- OWASP: https://owasp.org/Top10/A03_2021-Injection/
- CWE: CWE-89
---
(Repeat for each finding)
## Recommendations Summary
1. [Priority-ordered list of remediation actions]
2. ...
## Checklist Verification
- [ ] All parameterized queries verified
- [ ] Authentication flows reviewed
- [ ] Authorization checks on every endpoint
- [ ] Input validation on all user inputs
- [ ] Security headers configured
- [ ] Error handling does not leak internals
- [ ] Logging does not contain sensitive data
- [ ] Dependencies checked for known vulnerabilities
- [ ] SSRF protections in place for outbound requests
- [ ] Rate limiting configured on sensitive endpoints
```
## Quick Reference Table
### OWASP Top 10 (2021)
| ID | Category | What to Detect | Fix Pattern |
|----|----------|----------------|-------------|
| A01 | Broken Access Control | Missing auth checks on endpoints, direct object references without ownership validation, CORS misconfiguration | Enforce auth middleware on all routes, validate resource ownership, restrict CORS origins |
| A02 | Cryptographic Failures | Hardcoded secrets, weak hashing (MD5/SHA1), HTTP for sensitive data, missing encryption at rest | Use env vars for secrets, bcrypt/argon2 for passwords, enforce HTTPS, encrypt PII at rest |
| A03 | Injection | String-concatenated queries, unescaped HTML output, OS command with user input | Parameterized queries, output encoding, avoid shell execution |
| A04 | Insecure Design | Missing rate limiting, no input length limits, no threat model, business logic flaws | Threat modeling, input validation schemas, rate limiting, abuse case testing |
| A05 | Security Misconfiguration | Default credentials, verbose errors in production, unnecessary features enabled, missing headers | Harden configs, disable debug mode, remove defaults, add security headers |
| A06 | Vulnerable Components | Outdated dependencies with known CVEs, unpatched frameworks | Regular `npm audit` / `pip audit` / dependency scanning, automated updates |
| A07 | Auth Failures | Weak password policies, missing MFA, session fixation, credential stuffing susceptibility | Strong password rules, MFA, session regeneration, rate limiting, bcrypt |
| A08 | Integrity Failures | Unvalidated CI/CD pipelines, `eval()` on untrusted data, missing SRI on CDN scripts, auto-update without verification | SRI hashes, signed artifacts, validate deserialized data with schemas |
| A09 | Logging Failures | No audit logging, sensitive data in logs, no alerting on failures, insufficient log detail | Structured logging with redaction, audit trails, monitoring/alerting |
| A10 | SSRF | User-controlled URLs in server-side HTTP calls, URL redirects following internal paths | URL allowlists, block private IPs, disable redirects, validate schemes |
### OWASP API Security Top 10 (2023)
| ID | Category | What to Detect | Fix Pattern |
|----|----------|----------------|-------------|
| API1 | Broken Object Level Auth | API endpoints accessing resources by ID without ownership check | Validate resource ownership in every data access layer |
| API2 | Broken Authentication | Weak token generation, missing rate limits on login, tokens in URLs | Strong token generation, rate limiting, tokens in headers only |
| API3 | Broken Object Property Level Auth | API returning more fields than needed, mass assignment | Explicit response DTOs, allowlist assignable fields |
| API4 | Unrestricted Resource Consumption | No pagination limits, unbounded queries, missing rate limiting | Enforce pagination, query limits, rate limiting per user |
| API5 | Broken Function Level Auth | Admin endpoints accessible to regular users, missing role checks | Role-based middleware, principle of least privilege |
| API6 | Unrestricted Access to Sensitive Business Flows | No bot protection on purchase/booking flows, missing CAPTCHA | CAPTCHA, device fingerprinting, rate limiting, abuse detection |
| API7 | Server Side Request Forgery | User-supplied URLs fetched server-side | URL allowlists, block internal IPs, validate schemes |
| API8 | Security Misconfiguration | Missing CORS config, permissive methods, debug endpoints exposed | Strict CORS, disable unused methods, remove debug routes |
| API9 | Improper Inventory Management | Deprecated API versions still running, undocumented endpoints | API versioning policy, endpoint inventory, retire old versions |
| API10 | Unsafe Consumption of APIs | Trusting third-party API responses without validation | Validate all external API responses, timeout, circuit breaker |
## Reference Files
- [references/owasp-top10-2021.md](references/owasp-top10-2021.md) — Full OWASP Top 10 (2021) with code examples in TypeScript, Python, and Java
- [references/owasp-api-security.md](references/owasp-api-security.md) — Full OWASP API Security Top 10 (2023) with code examples in TypeScript, Python, and Java
- [references/checklists.md](references/checklists.md) — Consolidated security checklists by development phaseMore Security skills
azure-cost
microsoft/azure-skills
Azure cost management: query costs, forecast spending, optimize to reduce waste. WHEN: \"Azure costs\", \"Azure bill\", \"cost breakdown\", \"how much am I spending\", \"forecast spending\", \"optimize costs\", \"reduce spending\", \"orphaned resources\", \"rightsize VMs\", \"cost spike\", \"reduce storage costs\", \"AKS cost\". DO NOT USE FOR: deploying resources, provisioning, diagnostics, or security audits.
entra-app-registration
microsoft/azure-skills
Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.
azure-messaging
microsoft/azure-skills
Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing issues, and SDK configuration problems. WHEN: event hub SDK error, service bus SDK issue, messaging connection failure, AMQP error, event processor host issue, message lock lost, message lock expired, lock renewal, lock renewal batch, send timeout, receiver disconnected, SDK troubleshooting, azure messaging SDK, event hub consumer, service bus queue issue, topic subscription error, enable logging event hub, service bus logging, eventhub python, servicebus java, eventhub javascript, servicebus dotnet, event hub checkpoint, event hub not receiving messages, service bus dead letter, batch processing lock, session lock expired, idle timeout, connection inactive, link detach, slow reconnect, session error, duplicate events, offset reset, receive batch.

