Security Architecture & Hardening Guide — LightPath Training Portal¶
Scope: Threat model, authentication & brute-force defense, account active lifecycle, RBAC & course scoping, strict zero-inline-style CSP (
style-src 'self'), same-origin verification, CSRF/XSS/path/CSV protections, SHA-256 tamper-evident audit hash chains, PostgreSQL SQL sandbox isolation, and Docker container quotas.
1. Threat Model & Trust Boundaries¶
During live training workshops and standalone cloud hosting, the portal enforces four security boundaries:
1. Unauthenticated Internet/LAN Surface: Login, self-registration (self_registration toggle), and public Qualiopi certificate lookup (page=verify). Must resist user enumeration, credential stuffing, session fixation, and CSRF.
2. Authenticated Student vs Course Content: Students must access only courses in their enrolled_courses assignment, cannot inspect locked lab solutions (lock_solutions) or locked certification exams (lock_exam), and cannot forge quiz scores (api_submit_quiz).
3. Trainer vs Administrator Privilege Separation: Trainers (trainer) hold classroom operations (cohort, qna, docker, attendance countersignature, OPCO/SCORM exports) while Administrators (admin) exclusively manage users, enrollments, custom courses, audit exports, system health, and runtime feature flags.
4. Untrusted Student SQL vs Host/Container OS: Student queries submitted via api_run_sql run inside per-user Docker PostgreSQL 18 containers (lp_pg18_user_<id>) as non-superuser lms_student, blocked from filesystem/shell escape vectors and runaway resource exhaustion.
2. Authentication, Sessions & Brute-Force Protection (src/Core/Auth.php)¶
- Password Hashing & Minimum Policy: Passwords hash via PHP
PASSWORD_BCRYPT. Minimum password length is6characters (registerUser()andchangePassword()), and newly registered accounts explicitly initialize'active' => true. - Account Active Lifecycle (
Auth::isUserActive()): Evaluatesfalse,0, and'0'as suspended. Enforced inside bothAuth::verifyCredentials()(constant-time dummy check on suspended accounts) andAuth::currentUser(), which actively calls$this->logout()if an authenticated user is suspended mid-session. Administrators manage active status and resets viasetUserActive()(protecting super-admin#1from self/accidental suspension),adminResetUserPassword(), and bulk actions. - Anti-Enumeration Timing Defense:
verifyCredentials()evaluatespassword_verify($password, self::DUMMY_BCRYPT_HASH)whenever an email does not exist or is inactive, preventing timing-based account discovery. - Persistent Multi-Bucket Rate Limiting & Admin Unlock:
MAX_LOGIN_ATTEMPTS = 5per normalizedemail|ipbucket withinLOCKOUT_SECONDS = 300(5 minutes).MAX_IP_LOGIN_ATTEMPTS = 25peripbucket within300seconds to mitigate distributed password spraying.- Counters persist atomically through
StorageInterface(getLoginThrottle(),recordLoginFailure(),clearLoginThrottle(),listLoginThrottles()) viamutateFile(), eliminating cookie/session reset bypasses. Administrators can inspect active lockouts and trigger 1-click unlock (admin_unlock_throttle) from Administration -> Utilisateurs. - Verified Password Changes & Session Regeneration:
Auth::changePassword($userId, $currentPassword, $newPassword)requirespassword_verify($currentPassword, ...)before rotatingpassword_hash, and regenerates the session ID (session_regenerate_id(true)) whenever invoked in an active web session. - Session Hardening (src/bootstrap.php):
session.use_strict_mode=1,session.use_only_cookies=1,httponly=true,samesite=Lax, TLS-awaresecure.- src/bootstrap.php aligns
session.gc_maxlifetimeand session cookielifetimedynamically with'session_idle_ttl'in config/app.php (7200seconds default), whileAuth::login()regenerates session IDs (session_regenerate_id(true)) andAuth::currentUser()terminates idle sessions automatically.
3. Role-Based Access Control (RBAC) & Server-Side Integrity¶
- Strict Role Allowlist:
Auth::VALID_ROLES = ['student', 'trainer', 'admin']enforced viaAuth::isValidRole()on user creation,admin_update_user, and CSV import (JsonStorage::importUsersFromCsv()). - Course Enrollment Scoping:
Auth::canAccessCourse($user, $courseSlug)grants global access totrainer/adminstaff; for students, unset/nullenrolled_coursesdefaults to['postgresql-18'], while an explicit empty array[]denies all courses (preventing unauthorized URL course switching). - Explicit HTTP
403Enforcement: Privileged endpoints and admin-only operations (users,courses,audit,system,admin_update_enrollments,admin_reset_user_progress,admin_toggle_course,admin_delete_course,admin_save_features,export_audit_csv) return HTTP403on insufficient role rather than silent no-op HTTP200responses. - Server-Side Quiz Grading: When a module Markdown file contains quiz questions parsed by
MarkdownParser::extractQuizQuestions(),api_submit_quizrejects client-forgedscore/totalsubmissions lacking a validanswersmap (400 Bad Request).
4. HTTP Headers, CSRF, XSS, Path & CSV Protections (src/Core/Security.php)¶
Security Response Headers (Security::sendSecurityHeaders())¶
Emitted on every web response via bootstrap.php:
| Header | Value / Purpose |
|---|---|
X-Content-Type-Options |
nosniff — disables MIME-type sniffing |
X-Frame-Options |
SAMEORIGIN — prevents cross-origin clickjacking |
Referrer-Policy |
strict-origin-when-cross-origin |
Permissions-Policy |
unload=*, fullscreen=(self) |
Cross-Origin-Opener-Policy |
same-origin — isolates browsing context group |
Content-Security-Policy |
default-src 'self'; script-src 'self' 'sha256-Y+Iy31+SIVnkv2t35OtFkyF8C43lr3XQSadODH27V58='; style-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self' |
Strict-Transport-Security |
max-age=31536000; includeSubDomains (emitted automatically over HTTPS / reverse-proxy TLS) |
Info
Strict Zero-Inline-Style & Standalone Document CSP (P1-6 Resolved): All LMS portal routes emit style-src 'self' with zero 'unsafe-inline' and zero inline style= attributes across src/ and templates/ (dynamic progress widths hydrate via data-progress + CSSOM in public/assets/js/app.js, and verification QR SVGs use .lms-qr-verify-svg in public/assets/css/app.css). Only self-contained inline .html course previews streamed by DownloadController::streamFile() emit Security::sendStandaloneDocumentCspHeader(array $extraScriptHashes = []), which scopes style-src 'self' 'unsafe-inline' and validated per-document inline <script> SHA-256 hashes strictly to that standalone HTML frame (never adding script-src 'unsafe-inline').
Input/Output Sanitization, CSRF & Same-Origin Helpers¶
- CSRF Tokens (
getCsrfToken,verifyCsrfToken): Per-session 256-bit token viarandom_bytes(32)validated with constant-timehash_equals()across POST forms and mutatingapi_*calls. - Same-Origin Request Verification (
Security::verifySameOriginRequest()): Validates HTTPOrigin(preferred) orRefererhostname and port (when present) againstHTTP_HOST/SERVER_NAMEon mutating web requests while gracefully allowing absent headers in CLI/curl harness runs and rejecting cross-origin origins,Origin: null, and port mismatches. - XSS Output Encoding (
Security::e): Wrapshtmlspecialchars(..., ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). Delegated listeners inpublic/assets/js/app.jsreplace legacy inline event handlers. - Path Traversal Prevention (
isSafeRelativePath,isPathInside,sanitizeFilename): Validates downloadable files, course assets, and video streams against canonicalrealpath()roots (DownloadController.php). - Spreadsheet Formula Neutralization (
Security::sanitizeCsvCell()): Prefixes leading'when non-numeric strings begin with\tor\r, or whenltrim(..., " \t\r\n")begins with=,+,-, or@. Applied across user imports, OPCO attendance exports, Cohort KPI exports, Qualiopi exports, and Audit CSV exports. - Inline Static HTML Preview Isolation:
DownloadController::streamFile()rewrites local../assets/links toassets/, injectsPermissions-Policy: unload=*, computes unique'sha256-...'digests for trusted static inline<script>blocks before prepending the unload shim, emitsSecurity::sendStandaloneDocumentCspHeader($inlineHashes)when$disp === 'inline'fortext/html, and appendsSecurity::renderUnloadShimScript()(pagehide).Security::sendSecurityHeaders()computes the exact SHA-256 hash ofSecurity::UNLOAD_SHIM_JS('sha256-Y+Iy31+SIVnkv2t35OtFkyF8C43lr3XQSadODH27V58=') to eliminate'unsafe-inline'from bothscript-srcandstyle-srcon portal pages.
5. PostgreSQL SQL Sandbox & Container Isolation (src/Docker/LabSqlRunner.php, src/Docker/DockerManager.php)¶
Least-Privilege Database Execution (lms_student)¶
Provisioned idempotently by SakilaSeeder::getSandboxRoleSql():
- Role lms_student has LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS.
- Explicitly revoked: pg_execute_server_program, pg_read_server_files, pg_write_server_files.
- Granted schema privileges: pg_read_all_stats and pg_stat_scan_tables (for pg_stat_* observability exercises) plus USAGE, CREATE on schema public and DML/sequence rights on public objects.
- Untrusted student SQL via api_run_sql runs with psql -X -U lms_student, whereas trusted system validation (api_validate_lab, api_run_oracle, CLI oracle) uses $trustedOracle = true.
Timeout Enforcement & Command Filtering¶
- Transport & Timeouts: SQL payloads travel base64-encoded (
$b64 = base64_encode($sql);->base64 -d) intopsql -XwithPGOPTIONS="-c statement_timeout=15000 -c lock_timeout=10000", executed via non-blockingproc_open()timeouts (execCommandWithTimeout). - Lexical Scanner & Blocked Escalation Vectors (
LabSqlRunner::stripCommentsAndLiterals()): - A single-pass lexical scanner strips
--line comments, nested/* /* */ */block comments,'...'string literals, and dollar-quoted PostgreSQL blocks ($$...$$,$tag$...$tag$) intocomments_strippedandoutside_quotes. - All interactive
psqlbackslash commands (\!,\copy,\o,\w,\i,\connect/\c,\cd,\e*,\prompt,\watch,\setenv,\g,\gx,\gset,\gexec,\lo_import,\lo_export,\lo_unlink—'Commandes backslash interactives non autorisées') are rejected strictly on$outsideQuotes, avoiding false positives inside dollar-quotedDO $$ ... $$blocks. - Timeout overrides (
SET/RESETonstatement_timeout/lock_timeout/ALL, andset_config(...)targeting timeout keywords or dynamic||expressions) are checked on both raw SQL and$commentsStrippedbefore literal stripping—blocking nestedDO $$ BEGIN EXECUTE 'SET statement_timeout = 0'; END $$;bypasses while allowing benign queries such asSELECT current_setting('statement_timeout'). - Server-side OS/privilege escalation:
COPY ... FROM/TO PROGRAM,ALTER SYSTEM,ALTER USER/ALTER ROLE,SET/RESET ROLEorSESSION AUTHORIZATION(checked across both raw and$commentsStrippedSQL for untrusted learners), and filesystem functions (pg_read_file,pg_read_binary_file,pg_ls_dir,pg_stat_file,lo_import,lo_export). - Shared-Cluster Fallback Protection (
$allowSharedFallback = false):DockerManager::seedUserContainer(),DockerManager::getContainerLogs(), savepoint operations (createSavepoint(),listSavepoints(),restoreSavepoint(),deleteSavepoint()),runPgbenchBenchmark(),inspectPgDiagnostics(), andcheckLabReadiness()deny falling back to sharedpg_formation_primaryunless$allowSharedFallback === true(passed solely for$auth->isStaff($currentUser)in HTTP endpoints and hostbin/lab-runner.php). - Savepoint & Benchmark Parameter Boundaries: Savepoint identifiers enforce
^[a-zA-Z0-9_-]{1,32}$(max5per user, DB allowlist['formation_pg', 'dvdrental', 'postgres']); boundedpgbenchclamps$clients(1..8) and$durationSeconds(1..5) under non-blockingexecCommandWithTimeout().
Container Resource Quotas (DockerManager::startUserContainer())¶
Every per-user container lp_pg18_user_<id> launches with hardened cgroup and privilege limits:
- --shm-size=512m (PostgreSQL shared memory / parallel query workers)
- --memory=1g --cpus=1.0 --pids-limit=256 (fork-bomb and noisy-neighbor protection)
- --security-opt=no-new-privileges --restart=no
- --label lms.managed=lightpath --label lms.user_id=<id>
- Host capacity cap: max_containers (default 40).
6. Cryptographic Certificates & Tamper-Evident Audit Hash Chain¶
- Certificate Codes:
JsonStorage::saveExamAttempt()generates unpredictable identifiers matchingLP-PG18-CERT-<uid>-<8HEX>via CSPRNGstrtoupper(bin2hex(random_bytes(4))). - Audit Retention & Monthly Rotation:
JsonStorage::logAuditEvent()retains up to1,000active events inaudit_logsand archives overflow entries into monthlyaudit_logs_YYYYMMfiles atomically insidemutateFile()rather than truncating history. - SHA-256 Tamper-Evident Audit Hash Chain (
verifyAuditIntegrity()): Each newly written audit entry stores deterministicprev_hashandentry_hashSHA-256 chain links acrossaudit_logsand monthlyaudit_logs_YYYYMMarchives.StorageInterface::verifyAuditIntegrity(bool $includeArchives = false): arrayreturns['valid' => bool, 'total_checked' => int, 'chained_entries' => int, 'legacy_unchained' => int, 'broken_links' => array], cleanly distinguishing pre-chain historical rows (legacy_unchained) from tampered payloads or brokenprev_hashlinks. - Production Secrets Hygiene: Set
LMS_CERT_HMAC_SECRET(orAPP_SECRET) and override the development container password (postgres) via dedicated deployment environment configuration;AdminService::getSystemHealthReport()flags development defaults in Administration -> Système.