# LockNKey Custom Semgrep Rules

This directory contains custom Semgrep security rules tailored for the LockNKey password manager project.

## 📁 Rule Categories

### 1. **encryption.yml** - Cryptographic Security
Detects cryptographic vulnerabilities:
- ✅ Hardcoded encryption keys (CWE-321)
- ✅ Weak XOR encryption (CWE-327)
- ✅ Hardcoded JWT secrets (CWE-798)
- ✅ Insecure random number generation (CWE-338)

**Rules:** 4 total (3 ERROR, 1 WARNING)

### 2. **browser-extension.yml** - Extension Security
Detects browser extension vulnerabilities:
- ✅ Unencrypted chrome.storage usage (CWE-311)
- ✅ Unsafe message passing with eval() (CWE-94)
- ✅ Missing origin validation (CWE-346)
- ✅ Overly broad permissions (CWE-250)
- ✅ Insecure HTML injection (CWE-79)

**Rules:** 5 total (2 ERROR, 3 WARNING)

### 3. **quantum-crypto.yml** - Post-Quantum Security
Detects quantum cryptography misuse:
- ✅ Weak Kyber variants (Kyber-512)
- ✅ Missing hybrid encryption
- ✅ Weak Dilithium variants (Dilithium2)
- ✅ Quantum key reuse (CWE-323)
- ✅ Missing SPHINCS+ fallback

**Rules:** 5 total (4 WARNING, 1 INFO)

### 4. **authentication.yml** - Auth & Session Security
Detects authentication vulnerabilities:
- ✅ Missing JWT verification (CWE-306)
- ✅ JWT without expiration (CWE-613)
- ✅ Passwords in GET requests (CWE-598)
- ✅ Weak password hashing (CWE-916)
- ✅ Missing rate limiting (CWE-307)
- ✅ Cookies without secure flag (CWE-614)
- ✅ Hardcoded API keys (CWE-798)

**Rules:** 7 total (4 ERROR, 3 WARNING)

## 🚀 Usage

### Via MCP Tool (Recommended)
The security-engineer agent automatically uses these rules:
```bash
# Agent will run:
semgrep_scan(files=[...])  # Uses .semgrep/config.yml
```

### Via CLI
```bash
# Scan with custom rules
semgrep --config=.semgrep/config.yml

# Scan specific rule file
semgrep --config=.semgrep/rules/encryption.yml backend/

# Scan and auto-fix
semgrep --config=.semgrep/config.yml --autofix
```

### Via CI/CD
```yaml
# .github/workflows/security.yml
- name: Semgrep Security Scan
  run: |
    semgrep --config=.semgrep/config.yml \
      --json \
      --output=semgrep-results.json
```

## 📊 Rule Statistics

| Category | ERROR | WARNING | INFO | Total |
|----------|-------|---------|------|-------|
| Encryption | 3 | 1 | 0 | 4 |
| Browser Extension | 2 | 3 | 0 | 5 |
| Quantum Crypto | 0 | 4 | 1 | 5 |
| Authentication | 4 | 3 | 0 | 7 |
| **TOTAL** | **9** | **11** | **1** | **21** |

## 🎯 Coverage

### Languages Supported
- ✅ JavaScript
- ✅ TypeScript
- ✅ Python
- ✅ JSON (manifest files)

### Project Areas Covered
- ✅ Backend services (quantum, vault, auth)
- ✅ Frontend (Next.js app)
- ✅ Browser extension
- ✅ Configuration files

### OWASP Top 10 Coverage
- ✅ A01: Broken Access Control
- ✅ A02: Cryptographic Failures
- ✅ A03: Injection
- ✅ A04: Insecure Design
- ✅ A05: Security Misconfiguration
- ✅ A07: Identification and Authentication Failures

## 🔧 Customization

### Adding New Rules
1. Create new rule in appropriate category file
2. Follow the template:
```yaml
rules:
  - id: rule-name-kebab-case
    pattern: |
      code pattern to match
    message: |
      Description of vulnerability

      Fix: How to remediate
    severity: ERROR|WARNING|INFO
    languages: [javascript, typescript]
    metadata:
      category: security
      cwe: CWE-XXX
      owasp: A0X:2021
      confidence: HIGH|MEDIUM|LOW
      likelihood: HIGH|MEDIUM|LOW
      impact: CRITICAL|HIGH|MEDIUM|LOW
      subcategory: [vuln]
```

### Disabling Rules
Use inline comments:
```javascript
// semgrep-ignore: rule-id - justification
const key = 'test-key';  // OK for testing
```

### Testing Rules
```bash
# Test rule on specific file
semgrep --config=.semgrep/rules/encryption.yml \
  --test \
  path/to/test/file.js
```

## 📖 Resources

- **Semgrep Documentation**: https://semgrep.dev/docs
- **Rule Writing Guide**: https://semgrep.dev/docs/writing-rules/overview
- **LockNKey Security**: See `CLAUDE.md` for security requirements
- **CWE Database**: https://cwe.mitre.org/
- **OWASP Top 10**: https://owasp.org/Top10/

## 🔄 Maintenance

### When to Update Rules
- ✅ After discovering new vulnerability patterns
- ✅ When adding new features (e.g., new quantum algorithms)
- ✅ After security audits or penetration tests
- ✅ When CWE/OWASP guidelines change

### Rule Quality Checklist
- [ ] Clear, actionable message
- [ ] Specific fix recommendation
- [ ] Appropriate severity level
- [ ] CWE and OWASP mappings
- [ ] Low false positive rate
- [ ] Tested on real code

## 📝 Examples

### Example: Hardcoded Key Detection
**Code:**
```typescript
const key = 'lockn-key-storage-encryption-key';
```

**Semgrep Finds:**
```
ERROR: Hardcoded encryption key detected: key = 'lockn-key-storage-encryption-key'
  Rule: hardcoded-encryption-key
  CWE: CWE-321
  Fix: Use environment variables or Web Crypto API
```

### Example: Weak XOR Encryption
**Code:**
```typescript
function encrypt(data: string): string {
  return data ^ key;
}
```

**Semgrep Finds:**
```
ERROR: Weak XOR encryption detected in function: encrypt
  Rule: weak-xor-encryption
  CWE: CWE-327
  Fix: Use AES-256-GCM via Web Crypto API
```

## 🤝 Contributing

To add new rules:
1. Identify vulnerability pattern
2. Write rule following template
3. Test rule on real code
4. Update this README
5. Document in security-engineer agent

---

**Last Updated:** 2025-10-20
**Total Rules:** 21
**Maintained By:** Security Team
