Skip to content
Back to search

VibeSec-Skill

SkillWorks with Claude CodeGitHub

This skill helps Claude write secure web applications. Use this when working on any web application or when a user requests a scan or audit to ensure security best practices are followed.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/behisecc-vibesec-skill/badge.svg)](/listings/behisecc-vibesec-skill)

HTML

<a href="/listings/behisecc-vibesec-skill"><img src="/api/listings/behisecc-vibesec-skill/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

- <details><summary>Claude Code</summary>

* Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`

* Add it to `~/.claude/skills` (global) or `.claude/skills` in your project directory (project-only). </details>

- <details><summary>Cursor</summary>

* Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`

* Add it to `~/.cursor/skills` (global) or `.cursor/skills` in your project directory (project-only). </details>

- <details><summary>Codex</summary>

* Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`

* Add it to `~/.agents/skills` (global) or `.agents/skills` in your project directory (project-only).

</details>

- <details><summary>Github Copilot</summary>

* Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`

* Add it to `~/.copilot/skills` (global) or `.github/skills` in your project directory (project-only).

</details>

- <details><summary>Antigravity</summary>

* Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`

* Add it to `~/.gemini/antigravity/skills/` (global) or `.agent/skills/` in your project directory (project-only).

</details>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 758 lines · 1 finding marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: VibeSec-Skill
  3. description: This skill helps Claude write secure web applications. Use this when working on any web application or when a user requests a scan or audit to ensure security best practices are followed.
  4. ---
  5. # Secure Coding Guide for Web Applications
  6. ## Overview
  7. This guide provides comprehensive secure coding practices for web applications. As an AI assistant, your role is to approach code from a **bug hunter's perspective** and make applications **as secure as possible** without breaking functionality.
  8. **Key Principles:**
  9. - Defense in depth: Never rely on a single security control
  10. - Fail securely: When something fails, fail closed (deny access)
  11. - Least privilege: Grant minimum permissions necessary
  12. - Input validation: Never trust user input, validate everything server-side
  13. - Output encoding: Encode data appropriately for the context it's rendered in
  14. ---
  15. ## Access Control Issues
  16. Access control vulnerabilities occur when users can access resources or perform actions beyond their intended permissions.
  17. ### Core Requirements
  18. For **every data point and action** that requires authentication:
  19. 1. **User-Level Authorization**
  20. - Each user must only access/modify their own data
  21. - No user should access data from other users or organizations
  22. - Always verify ownership at the data layer, not just the route level
  23. 2. **Use UUIDs Instead of Sequential IDs**
  24. - Use UUIDv4 or similar non-guessable identifiers
  25. - Exception: Only use sequential IDs if explicitly requested by user
  26. 3. **Account Lifecycle Handling**
  27. - When a user is removed from an organization: immediately revoke all access tokens and sessions
  28. - When an account is deleted/deactivated: invalidate all active sessions and API keys
  29. - Implement token revocation lists or short-lived tokens with refresh mechanisms
  30. ### Authorization Checks Checklist
  31. - [ ] Verify user owns the resource on every request (don't trust client-side data)
  32. - [ ] Check organization membership for multi-tenant apps
  33. - [ ] Validate role permissions for role-based actions
  34. - [ ] Re-validate permissions after any privilege change
  35. - [ ] Check parent resource ownership (e.g., if accessing a comment, verify user owns the parent post)
  36. ### Common Pitfalls to Avoid
  37. - **IDOR (Insecure Direct Object Reference)**: Always verify the requesting user has permission to access the requested resource ID
  38. - **Privilege Escalation**: Validate role changes server-side; never trust role info from client
  39. - **Horizontal Access**: User A accessing User B's resources with the same privilege level
  40. - **Vertical Access**: Regular user accessing admin functionality
  41. - **Mass Assignment**: Filter which fields users can update; don't blindly accept all request body fields
  42. ### Implementation Pattern
  43. ```
  44. # Pseudocode for secure resource access
  45. function getResource(resourceId, currentUser):
  46. resource = database.find(resourceId)
  47. if resource is null:
  48. return 404 # Don't reveal if resource exists
  49. if resource.ownerId != currentUser.id:
  50. if not currentUser.hasOrgAccess(resource.orgId):
  51. return 404 # Return 404, not 403, to prevent enumeration
  52. return resource
  53. ```
  54. ---
  55. ## Client-Side Bugs
  56. ### Cross-Site Scripting (XSS)
  57. Every input controllable by the user—whether directly or indirectly—must be sanitized against XSS.
  58. #### Input Sources to Protect
  59. **Direct Inputs:**
  60. - Form fields (email, name, bio, comments, etc.)
  61. - Search queries
  62. - File names during upload
  63. - Rich text editors / WYSIWYG content
  64. **Indirect Inputs:**
  65. - URL parameters and query strings
  66. - URL fragments (hash values)
  67. - HTTP headers used in the application (Referer, User-Agent if displayed)
  68. - Data from third-party APIs displayed to users
  69. - WebSocket messages
  70. - postMessage data from iframes
  71. - LocalStorage/SessionStorage values if rendered
  72. **Often Overlooked:**
  73. - Error messages that reflect user input
  74. - PDF/document generators that accept HTML
  75. - Email templates with user data
  76. - Log viewers in admin panels
  77. - JSON responses rendered as HTML
  78. - SVG file uploads (can contain JavaScript)
  79. - Markdown rendering (if allowing HTML)
  80. #### Protection Strategies
  81. 1. **Output Encoding** (Context-Specific)
  82. - HTML context: HTML entity encode (`<` → `&lt;`)
  83. - JavaScript context: JavaScript escape
  84. - URL context: URL encode
  85. - CSS context: CSS escape
  86. - Use framework's built-in escaping (React's JSX, Vue's {{ }}, etc.)
  87. 2. **Content Security Policy (CSP)**
  88. ```
  89. Content-Security-Policy:
  90. default-src 'self';
  91. script-src 'self';
  92. style-src 'self' 'unsafe-inline';
  93. img-src 'self' data: https:;
  94. font-src 'self';
  95. connect-src 'self' https://api.yourdomain.com;
  96. frame-ancestors 'none';
  97. base-uri 'self';
  98. form-action 'self';
  99. ```
  100. - Avoid `'unsafe-inline'` and `'unsafe-eval'` for scripts
  101. - Use nonces or hashes for inline scripts when necessary
  102. - Report violations: `report-uri /csp-report`
  103. 3. **Input Sanitization**
  104. - Use established libraries (DOMPurify for HTML)
  105. - Whitelist allowed tags/attributes for rich text
  106. - Strip or encode dangerous patterns
  107. 4. **Additional Headers**
  108. - `X-Content-Type-Options: nosniff`
  109. - `X-Frame-Options: DENY` (or use CSP frame-ancestors)
  110. ---
  111. ### Cross-Site Request Forgery (CSRF)
  112. Every state-changing endpoint must be protected against CSRF attacks.
  113. #### Endpoints Requiring CSRF Protection
  114. **Authenticated Actions:**
  115. - All POST, PUT, PATCH, DELETE requests
  116. - Any GET request that changes state (fix these to use proper HTTP methods)
  117. - File uploads
  118. - Settings changes
  119. - Payment/transaction endpoints
  120. **Pre-Authentication Actions:**
  121. - Login endpoints (prevent login CSRF)
  122. - Signup endpoints
  123. - Password reset request endpoints
  124. - Password change endpoints
  125. - Email/phone verification endpoints
  126. - OAuth callback endpoints
  127. #### Protection Mechanisms
  128. 1. **CSRF Tokens**
  129. - Generate cryptographically random tokens
  130. - Tie token to user session
  131. - Validate on every state-changing request
  132. - Regenerate after login (prevent session fixation combo)
  133. 2. **SameSite Cookies**
  134. ```
  135. Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly
  136. ```
  137. - `Strict`: Cookie never sent cross-site (best security)
  138. - `Lax`: Cookie sent on top-level navigations (good balance)
  139. - Always combine with CSRF tokens for defense in depth
  140. 3. **Double Submit Cookie Pattern**
  141. - Send CSRF token in both cookie and request body/header
  142. - Server validates they match
  143. #### Edge Cases and Common Mistakes
  144. - **Token presence check**: CSRF validation must NOT depend on whether the token is present, always require it
  145. - **Token per form**: Consider unique tokens per form for sensitive operations
  146. - **JSON APIs**: Don't assume JSON content-type prevents CSRF; validate Origin/Referer headers AND use tokens
  147. - **CORS misconfiguration**: Overly permissive CORS can bypass SameSite cookies
  148. - **Subdomains**: CSRF tokens should be scoped because subdomain takeover can lead to CSRF
  149. - **Flash/PDF uploads**: Legacy browser plugins could bypass SameSite
  150. - **GET requests with side effects**: Never perform state changes on GET
  151. - **Token leakage**: Don't include CSRF tokens in URLs
  152. - **Token in URL vs Header**: Prefer custom headers (X-CSRF-Token) over URL parameters
  153. #### Verification Checklist
  154. - [ ] Token is cryptographically random (use secure random generator)
  155. - [ ] Token is tied to user session
  156. - [ ] Token is validated server-side on all state-changing requests
  157. - [ ] Missing token = rejected request
  158. - [ ] Token regenerated on authentication state change
  159. - [ ] SameSite cookie attribute is set
  160. - [ ] Secure and HttpOnly flags on session cookies
  161. ---
  162. ### Secret Keys and Sensitive Data Exposure
  163. No secrets or sensitive information should be accessible to client-side code.
  164. #### Never Expose in Client-Side Code
  165. **API Keys and Secrets:**
  166. - Third-party API keys (Stripe, AWS, etc.)
  167. - Database connection strings
  168. - JWT signing secrets
  169. - Encryption keys
  170. - OAuth client secrets
  171. - Internal service URLs/credentials
  172. **Sensitive User Data:**
  173. - Full credit card numbers
  174. - Social Security Numbers
  175. - Passwords (even hashed)
  176. - Security questions/answers
  177. - Full phone numbers (mask them: ***-***-1234)
  178. - Sensitive PII that isn't needed for display
  179. **Infrastructure Details:**
  180. - Internal IP addresses
  181. - Database schemas
  182. - Debug information
  183. - Stack traces in production
  184. - Server software versions
  185. #### Where Secrets Hide (Check These!)
  186. - JavaScript bundles (including source maps)
  187. - HTML comments
  188. - Hidden form fields
  189. - Data attributes
  190. - LocalStorage/SessionStorage
  191. - Initial state/hydration data in SSR apps
  192. - Environment variables exposed via build tools (NEXT_PUBLIC_*, REACT_APP_*)
  193. #### Best Practices
  194. 1. **Environment Variables**: Store secrets in `.env` files
  195. 2. **Server-Side Only**: Make API calls requiring secrets from backend only
  196. ---
  197. ## Open Redirect
  198. Any endpoint accepting a URL for redirection must be protected against open redirect attacks.
  199. ### Protection Strategies
  200. 1. **Allowlist Validation**
  201. ```
  202. allowed_domains = ['yourdomain.com', 'app.yourdomain.com']
  203. function isValidRedirect(url):
  204. parsed = parseUrl(url)
  205. return parsed.hostname in allowed_domains
  206. ```
  207. 2. **Relative URLs Only**
  208. - Only accept paths (e.g., `/dashboard`) not full URLs
  209. - Validate the path starts with `/` and doesn't contain `//`
  210. 3. **Indirect References**
  211. - Use a mapping instead of raw URLs: `?redirect=dashboard` → lookup to `/dashboard`
  212. ### Bypass Techniques to Block
  213. | Technique | Example | Why It Works |
  214. |-----------|---------|--------------|
  215. | @ symbol | `https://legit.com@evil.com` | Browser navigates to evil.com with legit.com as username |
  216. | Subdomain abuse | `https://legit.com.evil.com` | evil.com owns the subdomain |
  217. | Protocol tricks | `javascript:alert(1)` | XSS via redirect |
  218. | Double URL encoding | `%252f%252fevil.com` | Decodes to `//evil.com` after double decode |
  219. | Backslash | `https://legit.com\@evil.com` | Some parsers normalize `\` to `/` |
  220. | Null byte | `https://legit.com%00.evil.com` | Some parsers truncate at null |
  221. | Tab/newline | `https://legit.com%09.evil.com` | Whitespace confusion |
  222. | Unicode normalization | `https://legіt.com` (Cyrillic і) | IDN homograph attack |
  223. | Data URLs | `data:text/html,<script>...` | Direct payload execution |
  224. | Protocol-relative | `//evil.com` | Uses current page's protocol |
  225. | Fragment abuse | `https://legit.com#@evil.com` | Parsed differently by different libraries |
  226. ### IDN Homograph Attack Protection
  227. - Convert URLs to Punycode before validation
  228. - Consider blocking non-ASCII domains entirely for sensitive redirects
  229. ---
  230. ### Password Security
  231. #### Password Requirements
  232. - Minimum 8 characters (12+ recommended)
  233. - No maximum length (or very high, e.g., 128 chars)
  234. - Allow all characters including special chars
  235. - Don't require specific character types (let users choose strong passwords)
  236. #### Storage
  237. - Use Argon2id, bcrypt, or scrypt
  238. - Never MD5, SHA1, or plain SHA256
  239. ---
  240. ## Server-Side Bugs
  241. ### Server-Side Request Forgery (SSRF)
  242. Any functionality where the server makes requests to URLs provided or influenced by users must be protected.
  243. #### Potential Vulnerable Features
  244. - Webhooks (user provides callback URL)
  245. - URL previews
  246. - PDF generators from URLs
  247. - Image/file fetching from URLs
  248. - Import from URL features
  249. - RSS/feed readers
  250. - API integrations with user-provided endpoints
  251. - Proxy functionality
  252. - HTML to PDF/image converters
  253. #### Protection Strategies
  254. 1. **Allowlist Approach** (Preferred)
  255. - Only allow requests to pre-approved domains
  256. - Maintain a strict allowlist for integrations
  257. 2. **Network Segmentation**
  258. - Run URL-fetching services in isolated network
  259. - Block access to internal network, cloud metadata
  260. #### IP and DNS Bypass Techniques to Block
  261. | Technique | Example | Description |
  262. |-----------|---------|-------------|
  263. | Decimal IP | `http://2130706433` | 127.0.0.1 as decimal |
  264. | Octal IP | `http://0177.0.0.1` | Octal representation |
  265. | Hex IP | `http://0x7f.0x0.0x0.0x1` | Hexadecimal |
  266. | IPv6 localhost | `http://[::1]` | IPv6 loopback |
  267. | IPv6 mapped IPv4 | `http://[::ffff:127.0.0.1]` | IPv4-mapped IPv6 |
  268. | Short IPv6 | `http://[::]` | All zeros |
  269. | DNS rebinding | Attacker's DNS returns internal IP | First request resolves to external IP, second to internal |
  270. | CNAME to internal | Attacker domain CNAMEs to internal | DNS points to internal hostname |
  271. | URL parser confusion | `http://attacker.com#@internal` | Different parsing behaviors |
  272. | Redirect chains | External URL redirects to internal | Follow redirects carefully |
  273. | IPv6 scope ID | `http://[fe80::1%25eth0]` | Interface-scoped IPv6 |
  274. | Rare IP formats | `http://127.1` | Shortened IP notation |
  275. #### DNS Rebinding Prevention
  276. 1. Resolve DNS before making request
  277. 2. Validate resolved IP is not internal
  278. 3. Pin the resolved IP for the request (don't re-resolve)
  279. 4. Or: Resolve twice with delay, ensure both resolve to same external IP
  280. #### Cloud Metadata Protection
  281. Block access to cloud metadata endpoints:
  282. - AWS: `169.254.169.254`
  283. - GCP: `metadata.google.internal`, `169.254.169.254`, `http://metadata`
  284. - Azure: `169.254.169.254`
  285. - DigitalOcean: `169.254.169.254`
  286. #### Implementation Checklist
  287. - [ ] Validate URL scheme is HTTP/HTTPS only
  288. - [ ] Resolve DNS and validate IP is not private/internal
  289. - [ ] Block cloud metadata IPs explicitly
  290. - [ ] Limit or disable redirect following
  291. - [ ] If following redirects, validate each hop
  292. - [ ] Set timeout on requests
  293. - [ ] Limit response size
  294. - [ ] Use network isolation where possible
  295. ---
  296. ### Insecure File Upload
  297. File uploads must validate type, content, and size to prevent various attacks.
  298. #### Validation Requirements
  299. **1. File Type Validation**
  300. - Check file extension against allowlist
  301. - Validate magic bytes/file signature match expected type
  302. - Never rely on just one check
  303. **2. File Content Validation**
  304. - Read and verify magic bytes
  305. - For images: attempt to process with image library (detects malformed files)
  306. - For documents: scan for macros, embedded objects
  307. - Check for polyglot files (files valid as multiple types)
  308. **3. File Size Limits**
  309. - Set maximum file size server-side
  310. - Configure web server/proxy limits as well
  311. - Consider per-file-type limits (images smaller than videos)
  312. #### Common Bypasses and Attacks
  313. | Attack | Description | Prevention |
  314. |--------|-------------|------------|
  315. | Extension bypass | `shell.php.jpg` | Check full extension, use allowlist |
  316. | Null byte | `shell.php%00.jpg` | Sanitize filename, check for null bytes |
  317. | Double extension | `shell.jpg.php` | Only allow single extension |
  318. | MIME type spoofing | Set Content-Type to image/jpeg | Validate magic bytes |
  319. | Magic byte injection | Prepend valid magic bytes to malicious file | Check entire file structure, not just header |
  320. | Polyglot files | File valid as both JPEG and JavaScript | Parse file as expected type, reject if invalid |
  321. | SVG with JavaScript | `<svg onload="alert(1)">` | Sanitize SVG or disallow entirely |
  322. | XXE via file upload | Malicious DOCX, XLSX (which are XML) | Disable external entities in parser |
  323. | ZIP slip | `../../../etc/passwd` in archive | Validate extracted paths |
  324. | ImageMagick exploits | Specially crafted images | Keep ImageMagick updated, use policy.xml |
  325. | Filename injection | `; rm -rf /` in filename | Sanitize filenames, use random names |
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 430 on GitHub
  326. | Content-type confusion | Browser MIME sniffing | Set `X-Content-Type-Options: nosniff` |
  327. #### Magic Bytes Reference
  328. | Type | Magic Bytes (hex) |
  329. |------|-------------------|
  330. | JPEG | `FF D8 FF` |
  331. | PNG | `89 50 4E 47 0D 0A 1A 0A` |
  332. | GIF | `47 49 46 38` |
  333. | PDF | `25 50 44 46` |
  334. | ZIP | `50 4B 03 04` |
  335. | DOCX/XLSX | `50 4B 03 04` (ZIP-based) |
  336. #### Secure Upload Handling
  337. 1. **Rename files**: Use random UUID names, discard original
  338. 2. **Store outside webroot**: Or use separate domain for uploads
  339. 3. **Serve with correct headers**:
  340. - `Content-Disposition: attachment` (forces download)
  341. - `X-Content-Type-Options: nosniff`
  342. - `Content-Type` matching actual file type
  343. 4. **Use CDN/separate domain**: Isolate uploaded content from main app
  344. 5. **Set restrictive permissions**: Uploaded files should not be executable
  345. ---
  346. ### SQL Injection
  347. SQL injection occurs when user input is incorporated into SQL queries without proper handling.
  348. #### Prevention Methods
  349. **1. Parameterized Queries (Prepared Statements)** — PRIMARY DEFENSE
  350. ```sql
  351. -- VULNERABLE
  352. query = "SELECT * FROM users WHERE id = " + userId
  353. -- SECURE
  354. query = "SELECT * FROM users WHERE id = ?"
  355. execute(query, [userId])
  356. ```
  357. **2. ORM Usage**
  358. - Use ORM methods that automatically parameterize
  359. - Be cautious with raw query methods in ORMs
  360. - Watch for ORM-specific injection points
  361. **3. Input Validation**
  362. - Validate data types (integer should be integer)
  363. - Whitelist allowed values where applicable
  364. - This is defense-in-depth, not primary defense
  365. #### Injection Points to Watch
  366. - WHERE clauses
  367. - ORDER BY clauses (often overlooked—can't use parameters, must whitelist)
  368. - LIMIT/OFFSET values
  369. - Table and column names (can't parameterize—must whitelist)
  370. - INSERT values
  371. - UPDATE SET values
  372. - IN clauses with dynamic lists
  373. - LIKE patterns (also escape wildcards: %, _)
  374. #### Additional Defenses
  375. - **Least privilege**: Database user should have minimum required permissions
  376. - **Disable dangerous functions**: Like `xp_cmdshell` in SQL Server
  377. - **Error handling**: Never expose SQL errors to users
  378. ---
  379. ### XML External Entity (XXE)
  380. XXE vulnerabilities occur when XML parsers process external entity references in user-supplied XML.
  381. #### Vulnerable Scenarios
  382. **Direct XML Input:**
  383. - SOAP APIs
  384. - XML-RPC
  385. - XML file uploads
  386. - Configuration file parsing
  387. - RSS/Atom feed processing
  388. **Indirect XML:**
  389. - JSON/other format converted to XML server-side
  390. - Office documents (DOCX, XLSX, PPTX are ZIP with XML)
  391. - SVG files (XML-based)
  392. - SAML assertions
  393. - PDF with XFA forms
  394. #### Prevention by Language/Parser
  395. **Java:**
  396. ```java
  397. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  398. dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  399. dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
  400. dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  401. dbf.setExpandEntityReferences(false);
  402. ```
  403. **Python (lxml):**
  404. ```python
  405. from lxml import etree
  406. parser = etree.XMLParser(resolve_entities=False, no_network=True)
  407. # Or use defusedxml library
  408. ```
  409. **PHP:**
  410. ```php
  411. libxml_disable_entity_loader(true);
  412. // Or use XMLReader with proper settings
  413. ```
  414. **Node.js:**
  415. ```javascript
  416. // Use libraries that disable DTD processing by default
  417. // If using libxmljs, set { noent: false, dtdload: false }
  418. ```
  419. **.NET:**
  420. ```csharp
  421. XmlReaderSettings settings = new XmlReaderSettings();
  422. settings.DtdProcessing = DtdProcessing.Prohibit;
  423. settings.XmlResolver = null;
  424. ```
  425. #### XXE Prevention Checklist
  426. - [ ] Disable DTD processing entirely if possible
  427. - [ ] Disable external entity resolution
  428. - [ ] Disable external DTD loading
  429. - [ ] Disable XInclude processing
  430. - [ ] Use latest patched XML parser versions
  431. - [ ] Validate/sanitize XML before parsing if DTD needed
  432. - [ ] Consider using JSON instead of XML where possible
  433. ---
  434. ### Path Traversal
  435. Path traversal vulnerabilities occur when user input controls file paths, allowing access to files outside intended directories.
  436. #### Vulnerable Patterns
  437. ```python
  438. # VULNERABLE
  439. file_path = "/uploads/" + user_input
  440. file_path = base_dir + request.params['file']
  441. template = "templates/" + user_provided_template
  442. ```
  443. #### Prevention Strategies
  444. **1. Avoid User Input in Paths**
  445. ```python
  446. # Instead of using user input directly
  447. # Use indirect references
  448. files = {'report': '/reports/q1.pdf', 'invoice': '/invoices/2024.pdf'}
  449. file_path = files.get(user_input) # Returns None if invalid
  450. ```
  451. **2. Canonicalization and Validation**
  452. ```python
  453. import os
  454. def safe_join(base_directory, user_path):
  455. # Ensure base is absolute and normalized
  456. base = os.path.abspath(os.path.realpath(base_directory))
  457. # Join and then resolve the result
  458. target = os.path.abspath(os.path.realpath(os.path.join(base, user_path)))
  459. # Ensure the commonpath is the base directory
  460. if os.path.commonpath([base, target]) != base:
  461. raise ValueError("Error!")
  462. return target
  463. ```
  464. **3. Input Sanitization**
  465. - Remove or reject `..` sequences
  466. - Remove or reject absolute path indicators (`/`, `C:`)
  467. - Whitelist allowed characters (alphanumeric, dash, underscore)
  468. - Validate file extension if applicable
  469. #### Path Traversal Checklist
  470. - [ ] Never use user input directly in file paths
  471. - [ ] Canonicalize paths and validate against base directory
  472. - [ ] Restrict file extensions if applicable
  473. - [ ] Test with various encoding and bypass techniques
  474. ---
  475. ## Security Headers Checklist
  476. Include these headers in all responses:
  477. ```
  478. Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  479. Content-Security-Policy: [see XSS section]
  480. X-Content-Type-Options: nosniff
  481. X-Frame-Options: DENY
  482. Referrer-Policy: strict-origin-when-cross-origin
  483. Cache-Control: no-store (for sensitive pages)
  484. ```
  485. ---
  486. ## JWT Security
  487. JWT misconfigurations can lead to full authentication bypass and token forgery.
  488. ### Vulnerabilities
  489. | Vulnerability | Prevention |
  490. |---------------|------------|
  491. | `alg: none` attack | Always verify algorithm server-side, reject `none` |
  492. | Algorithm confusion | Explicitly specify expected algorithm, never derive from token |
  493. | Weak HMAC secrets | Use 256+ bit cryptographically random secrets |
  494. | Missing expiration | Always set `exp` claim |
  495. | Token in localStorage | Store in httpOnly, Secure, SameSite=Strict cookies, never localStorage |
  496. ### Secure Implementation
  497. ```javascript
  498. // 1. SIGNING
  499. // Always use environment variables for secrets
  500. const secret = process.env.JWT_SECRET;
  501. const token = jwt.sign({
  502. sub: userId,
  503. iat: Math.floor(Date.now() / 1000),
  504. exp: Math.floor(Date.now() / 1000) + (15 * 60), // 15 mins (Short-lived)
  505. jti: crypto.randomUUID() // Unique ID for revocation/blacklisting
  506. }, secret, {
  507. algorithm: 'HS256'
  508. });
  509. // 2. SENDING (Cookie Best Practices)
  510. // Protect against XSS and CSRF
  511. res.cookie('token', token, {
  512. httpOnly: true,
  513. secure: true,
  514. sameSite: 'strict'
  515. });
  516. // 3. VERIFYING
  517. // CRITICAL: Whitelist the allowed algorithm
  518. jwt.verify(token, secret, { algorithms: ['HS256'] }, (err, decoded) => {
  519. if (err) {
  520. // Handle invalid token
  521. }
  522. // Trust the payload
  523. });
  524. ```
  525. ### JWT Checklist
  526. - [ ] Algorithm explicitly specified on verification (never trust token header)
  527. - [ ] `alg: none` rejected
  528. - [ ] Secret is 256+ bits of random data (not a password or phrase)
  529. - [ ] `exp` claim always set and validated
  530. - [ ] Tokens stored in httpOnly cookies (not localStorage/sessionStorage)
  531. - [ ] Refresh token rotation implemented (old refresh token invalidated on use)
  532. ---
  533. ## API Security
  534. ### Mass Assignment
  535. Accepting unfiltered request bodies can lead to privilege escalation.
  536. ```javascript
  537. // VULNERABLE — user can set { role: "admin" } in request body
  538. User.update(req.body)
  539. // SECURE — whitelist allowed fields
  540. const allowed = ['name', 'email', 'avatar']
  541. const updates = pick(req.body, allowed)
  542. User.update(updates)
  543. ```
  544. This applies to any ORM/framework — always explicitly define which fields a request can modify.
  545. ### GraphQL
  546. | Vulnerability | Prevention |
  547. | :--- | :--- |
  548. | Introspection in production | Disable introspection in production environments. |
  549. | Query depth attack | Implement query depth limiting (e.g., maximum of 10 levels). |
  550. | Query complexity attack | Calculate and enforce strict query cost limits. |
  551. | Batching attack | Limit the number of operations allowed per single request. |
  552. ```javascript
  553. const server = new ApolloServer({
  554. introspection: process.env.NODE_ENV !== 'production',
  555. validationRules: [
  556. depthLimit(10),
  557. costAnalysis({ maximumCost: 1000 })
  558. ]
  559. })
  560. ```
  561. ---
  562. ## General Security Principles
  563. When generating code, always:
  564. 1. **Validate all input server-side** — Never trust client-side validation alone
  565. 2. **Use parameterized queries** — Never concatenate user input into queries
  566. 3. **Encode output contextually** — HTML, JS, URL, CSS contexts need different encoding
  567. 4. **Apply authentication checks** — On every endpoint, not just at routing
  568. 5. **Apply authorization checks** — Verify the user can access the specific resource
  569. 6. **Use secure defaults**
  570. 7. **Handle errors securely** — Don't leak stack traces or internal details to users
  571. 8. **Keep dependencies updated** — Use tools to track vulnerable dependencies
  572. When unsure, choose the more restrictive/secure option and document the security consideration in comments.
README.md · README · 131 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # VibeSec-Skill
  2. > **Stop vibe coding vulnerabilities into production.**
  3. An AI skill that brings 5+ years of bug bounty hunting experience directly into your AI coding workflow - so LLM models write secure code from the start.
  4. ## Introduction
  5. Vibe coding is fun until your app ends up on social media for all the wrong reasons.
  6. We have all seen the posts/memes:
  7. * API keys hardcoded in JavaScript bundles
  8. * IDOR vulnerabilities allowing user data dumps
  9. * No authentication for sensitive pages
  10. * Weak passwords for admin panels
  11. Security gaps aren't obvious until someone exploits them. Without the right guidance, AI will confidently ship vulnerable patterns alongside your features.
  12. VibeSec is an AI Skill that acts as a security-first co-pilot. It teaches your selected model to approach your code from a bug hunter's perspective, catching vulnerabilities before they ship.
  13. ## 📚 Table of Contents
  14. - [VibeSec-Skill](#VibeSec-Skill)
  15. - [📥 Installation](#-installation)
  16. - [🛡️ Covered Vulnerabilities](#️-covered-vulnerabilities)
  17. - [🚀 Quick Start](#-quick-start)
  18. - [🤝 Contribution](#-contribution)
  19. - [📬 Contact](#-contact)
  20. >[!Tip]
  21. >This skill already covers 60-70% of the common vulnerabilities. However, if you need a more robust version with more vulnerability coverage, please visit [vibesec.sh](https://vibesec.sh/)
  22. ## 📥 Installation
  23. - <details><summary>Claude Code</summary>
  24. * Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`
  25. * Add it to `~/.claude/skills` (global) or `.claude/skills` in your project directory (project-only).
  26. </details>
  27. - <details><summary>Cursor</summary>
  28. * Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`
  29. * Add it to `~/.cursor/skills` (global) or `.cursor/skills` in your project directory (project-only).
  30. </details>
  31. - <details><summary>Codex</summary>
  32. * Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`
  33. * Add it to `~/.agents/skills` (global) or `.agents/skills` in your project directory (project-only).
  34. </details>
  35. - <details><summary>Github Copilot</summary>
  36. * Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`
  37. * Add it to `~/.copilot/skills` (global) or `.github/skills` in your project directory (project-only).
  38. </details>
  39. - <details><summary>Antigravity</summary>
  40. * Clone this repository: `git clone https://github.com/BehiSecc/VibeSec-Skill`
  41. * Add it to `~/.gemini/antigravity/skills/` (global) or `.agent/skills/` in your project directory (project-only).
  42. </details>
  43. ## 🛡️ Covered Vulnerabilities
  44. VibeSec provides comprehensive protection against:
  45. | Category | Covered Vulnerabilities |
  46. |----------|-----------------|
  47. | **Access Control** | IDOR, Privilege Escalation, Horizontal/Vertical Access, Mass Assignment, Token Revocation |
  48. | **Client-Side** | XSS (Stored, Reflected, DOM), CSRF, Secret Key Exposure, Open Redirect |
  49. | **Server-Side** | SSRF, SQL Injection, XXE, Path Traversal, Insecure File Upload |
  50. | **Authentication** | Weak Passwords, Session Management, Account Lifecycle, JWT Security |
  51. | **API Security** | Mass Assignment, GraphQL Security |
  52. ### Deep Coverage Includes:
  53. - ✅ **Bypass techniques** - Not just "sanitize input" but specific bypasses attackers use
  54. - ✅ **Edge cases** - URL fragments, DNS rebinding, polyglot files, Unicode tricks
  55. - ✅ **Framework-aware** - Patterns for React, Vue, Node.js, Python, Java, .NET
  56. - ✅ **Cloud-aware** - Metadata endpoint protection for AWS, GCP, Azure
  57. - ✅ **Checklists** - Actionable verification steps for each vulnerability class
  58. ## 🚀 Quick Start
  59. ```markdown
  60. # Add the skill to your project dir:
  61. "I'm building a [web app description]. Please follow secure coding practices."
  62. # Claude/Codex/etc will now automatically:
  63. # - Implement proper access controls
  64. # - Add security headers
  65. # - Validate and sanitize all inputs
  66. # - Flag potential security issues
  67. ```
  68. ## 🤝 Contribution
  69. If you have suggestions, improvements, or new resources to add:
  70. 1. Fork this repo
  71. 2. Make your changes
  72. 3. Submit a Pull Request
  73. You can also open an **Issue** 🐛 if you spot something that needs fixing.
  74. ## 📬 Contact
  75. If you want to contact me, you can reach me on [X](https://x.com/Behi_Sec).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.