# Security & Vulnerability Scanning

> **Status**: Planning  
> **Priority**: High  
> **Last Updated**: March 2026

---

## Overview

Security hardening and vulnerability scanning strategy for Shamra Academia. Covers authentication, input validation, dependency scanning, infrastructure security, and compliance.

---

## Current Security Posture

### ✅ Implemented

| Feature | Status | Notes |
|---------|--------|-------|
| HTTPS everywhere | ✅ | SSL via Let's Encrypt |
| Password hashing | ✅ | bcrypt via Symfony Security |
| CSRF protection | ✅ | Symfony forms |
| SQL injection prevention | ✅ | Doctrine ORM parameterized queries |
| Session security | ✅ | Stored in `var/sessions/`, not `/tmp` |
| Admin route obscurity | ✅ | `/jim19ud83/...` prefix |
| Role-based access | ✅ | `ROLE_ADMIN`, `ROLE_USER` |
| Rate limiting | ⚠️ Partial | Only on login (via fail2ban) |
| Dependency updates | ⚠️ Partial | Manual composer updates |
| Security headers | ⚠️ Partial | Some missing |
| Input sanitization | ⚠️ Partial | Needs audit |
| File upload validation | ⚠️ Partial | OCR, profile images |

### ❌ Not Yet Implemented

| Feature | Priority | Notes |
|---------|----------|-------|
| 2FA for admins | High | TOTP or WebAuthn |
| API rate limiting | High | Prevent abuse |
| WAF | Medium | Web Application Firewall |
| Automated dependency scanning | Medium | Dependabot, Snyk |
| Penetration testing | Medium | Third-party audit |
| Content Security Policy | Medium | XSS prevention |
| Subresource Integrity | Low | CDN script validation |

---

## Vulnerability Scanning Tools

### 1. Dependency Scanning

```bash
# Symfony security checker (built-in)
composer audit

# OWASP Dependency Check
# https://owasp.org/www-project-dependency-check/

# Snyk (free tier available)
snyk test --file=composer.lock
```

**Automated Setup (GitHub Actions)**:
```yaml
# .github/workflows/security.yml
name: Security Scan
on:
  schedule:
    - cron: '0 6 * * 1'  # Weekly Monday 6am
  push:
    paths:
      - 'composer.lock'

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Composer Audit
        run: composer audit --format=json > audit.json
      - name: Upload results
        uses: actions/upload-artifact@v4
        with:
          name: security-audit
          path: audit.json
```

### 2. Static Analysis (SAST)

```bash
# PHPStan (already in project)
vendor/bin/phpstan analyse src/

# Psalm security analysis
vendor/bin/psalm --taint-analysis

# SonarQube (self-hosted or cloud)
sonar-scanner
```

### 3. Dynamic Analysis (DAST)

| Tool | Purpose | Cost |
|------|---------|------|
| **OWASP ZAP** | Web app scanner | Free |
| **Nikto** | Web server scanner | Free |
| **Nuclei** | Template-based scanner | Free |
| **Burp Suite** | Manual + automated | Paid |
| **Acunetix** | Enterprise scanner | Paid |

**ZAP Quick Scan**:
```bash
# Docker-based scan
docker run -t owasp/zap2docker-stable zap-baseline.py \
  -t https://shamra-academia.com \
  -r zap-report.html
```

### 4. Infrastructure Scanning

```bash
# SSL/TLS check
testssl.sh https://shamra-academia.com

# Security headers check
curl -I https://shamra-academia.com | grep -E "^(X-|Content-Security|Strict)"

# Nmap port scan
nmap -sV -sC shamra-academia.com
```

---

## Security Headers Checklist

Add to Apache config or `.htaccess`:

```apache
# Security headers
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"

# Content Security Policy (start with report-only)
Header always set Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://www.googletagmanager.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' https://api.openai.com https://api.anthropic.com;"

# HSTS (enable after testing)
# Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
```

**Verify with**:
- https://securityheaders.com
- https://observatory.mozilla.org

---

## Known Vulnerabilities to Address

### High Priority

1. **Rate Limiting on API Endpoints**
   - OCR submission: Max 10/minute per user
   - Search API: Max 60/minute per IP
   - Login: Max 5 attempts/15 minutes (already via fail2ban)

2. **File Upload Security**
   - Validate MIME types server-side (not just extension)
   - Scan uploads with ClamAV
   - Store outside webroot

3. **Admin 2FA**
   - Implement TOTP via `scheb/2fa-bundle`
   - Require for all `/jim19ud83/` routes

### Medium Priority

4. **Session Hardening**
   ```yaml
   # config/packages/framework.yaml
   session:
       cookie_secure: true
       cookie_httponly: true
       cookie_samesite: lax
       gc_maxlifetime: 3600  # 1 hour
   ```

5. **Database Connection Encryption**
   - Enable TLS between app server and MySQL
   - Verify with: `SHOW STATUS LIKE 'Ssl_cipher';`

6. **Log Sensitive Data Masking**
   - Mask emails, IPs in logs
   - PII compliance

### Low Priority

7. **Subresource Integrity**
   ```html
   <script src="https://cdn.example.com/lib.js" 
           integrity="sha384-..." 
           crossorigin="anonymous"></script>
   ```

8. **DNS Security**
   - CAA records
   - DNSSEC

---

## Penetration Testing Scope

### In Scope
- `shamra-academia.com` (production)
- `staging.shamra-academia.com` (if exists)
- All authenticated user flows
- Admin dashboard
- API endpoints
- File upload/download
- Search functionality
- Payment flows (if any)

### Out of Scope
- Third-party services (OpenAI, Anthropic, Elasticsearch cloud)
- Physical security
- Social engineering

### Test Types
1. **Authentication Testing**
   - Password brute force
   - Session hijacking
   - Token security

2. **Authorization Testing**
   - IDOR (Insecure Direct Object Reference)
   - Privilege escalation
   - Role bypass

3. **Injection Testing**
   - SQL injection
   - XSS (stored, reflected, DOM)
   - Command injection
   - LDAP injection

4. **Business Logic Testing**
   - Credit manipulation
   - Rate bypass
   - Workflow abuse

---

## Incident Response Plan

### Severity Levels

| Level | Description | Response Time |
|-------|-------------|---------------|
| P1 Critical | Data breach, full compromise | < 1 hour |
| P2 High | Auth bypass, SQL injection | < 4 hours |
| P3 Medium | XSS, info disclosure | < 24 hours |
| P4 Low | Minor issues | < 1 week |

### Response Steps

1. **Detect** — Monitor logs, alerts, user reports
2. **Contain** — Isolate affected systems
3. **Eradicate** — Remove threat, patch vulnerability
4. **Recover** — Restore services, verify integrity
5. **Post-mortem** — Document, improve defenses

### Contacts
- Security Lead: [TBD]
- Cloud Provider: Azure Support
- Legal: [TBD]

---

## Compliance Considerations

| Regulation | Relevance | Status |
|------------|-----------|--------|
| GDPR | User data (EU users) | ⚠️ Partial |
| CCPA | California users | ⚠️ Review needed |
| FERPA | Education data (if US students) | ❓ Unknown |

### GDPR Checklist
- [ ] Privacy policy updated
- [ ] Data processing records
- [ ] Right to deletion implemented
- [ ] Data export (DSAR) capability
- [ ] Breach notification process
- [ ] DPO appointed (if required)

---

## Implementation Roadmap

### Phase 0 (Tomorrow) — Critical
- [ ] **Admin 2FA** — Implement TOTP via `scheb/2fa-bundle` for all admin routes

### Phase 1 (Week 1-2) — Quick Wins
- [ ] Add security headers to Apache
- [ ] Run `composer audit` and fix vulnerabilities
- [ ] Enable session cookie security flags
- [ ] Implement API rate limiting

### Phase 2 (Week 3-4) — Core Security
- [ ] Admin 2FA with TOTP
- [ ] File upload hardening
- [ ] OWASP ZAP baseline scan
- [ ] Fix all High/Critical findings

### Phase 3 (Month 2) — Automation
- [ ] GitHub Actions security scanning
- [ ] Automated dependency updates
- [ ] Log monitoring alerts
- [ ] WAF evaluation

### Phase 4 (Month 3) — Audit
- [ ] Third-party penetration test
- [ ] Security policy documentation
- [ ] Team security training
- [ ] Incident response drill

---

## Resources

- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Symfony Security Best Practices](https://symfony.com/doc/current/security.html)
- [Mozilla Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security)
- [CIS Apache Benchmarks](https://www.cisecurity.org/benchmark/apache_http_server)
