Beste praktijken op het gebied van beveiliging
2.5.x ✅ 4.0.x ✅
Dit document biedt uitgebreide best practices op het gebied van beveiliging voor ontwikkelaars van XOOPS-modules. Als u deze richtlijnen volgt, zorgt u ervoor dat uw modules veilig zijn en geen kwetsbaarheden introduceren in XOOPS-installaties.
Beveiligingsprincipes
Section titled “Beveiligingsprincipes”Elke XOOPS-ontwikkelaar moet deze fundamentele beveiligingsprincipes volgen:
- Defense in Depth: Implementeer meerdere lagen beveiligingscontroles
- Least Privilege: Geef alleen de minimaal noodzakelijke toegangsrechten op
- Invoervalidatie: Vertrouw nooit op gebruikersinvoer
- Standaard beveiligd: Beveiliging moet de standaardconfiguratie zijn
- Keep It Simple: Complexe systemen zijn moeilijker te beveiligen
Gerelateerde documentatie
Section titled “Gerelateerde documentatie”- CSRF-bescherming - Tokensysteem en XoopsSecurity-klasse
- Invoer-opschoning - MyTextSanitizer en validatie
- SQL-Injectiepreventie - Databasebeveiligingspraktijken
Snelle referentiechecklist
Section titled “Snelle referentiechecklist”Controleer het volgende voordat u uw module vrijgeeft:
- Alle formulieren bevatten XOOPS-tokens
- Alle gebruikersinvoer wordt gevalideerd en opgeschoond
- Alle uitvoer wordt correct geëscaped
- Alle databasequery’s gebruiken geparametriseerde instructies
- Bestandsuploads zijn correct gevalideerd
- Er zijn authenticatie- en autorisatiecontroles uitgevoerd
- Foutafhandeling onthult geen gevoelige informatie
- Gevoelige configuratie is beveiligd
- Bibliotheken van derden zijn up-to-date
- Er zijn beveiligingstests uitgevoerd
Authenticatie en autorisatie
Section titled “Authenticatie en autorisatie”Gebruikersauthenticatie controleren
Section titled “Gebruikersauthenticatie controleren”// Check if user is logged inif (!is_object($GLOBALS['xoopsUser'])) { redirect_header(XOOPS_URL, 3, _NOPERM); exit();}Gebruikersrechten controleren
Section titled “Gebruikersrechten controleren”// Check if user has permission to access this moduleif (!$GLOBALS['xoopsUser']->isAdmin($xoopsModule->mid())) { redirect_header(XOOPS_URL, 3, _NOPERM); exit();}
// Check specific permission$moduleHandler = xoops_getHandler('module');$module = $moduleHandler->getByDirname('mymodule');$moduleperm_handler = xoops_getHandler('groupperm');$groups = $GLOBALS['xoopsUser']->getGroups();
if (!$moduleperm_handler->checkRight('mymodule_view', $item_id, $groups, $module->getVar('mid'))) { redirect_header(XOOPS_URL, 3, _NOPERM); exit();}Modulerechten instellen
Section titled “Modulerechten instellen”// Create permission in install/update function$gpermHandler = xoops_getHandler('groupperm');$gpermHandler->deleteByModule($module->getVar('mid'), 'mymodule_view');
// Add permission for all groups$groups = [XOOPS_GROUP_ADMIN, XOOPS_GROUP_USERS, XOOPS_GROUP_ANONYMOUS];foreach ($groups as $group_id) { $gpermHandler->addRight('mymodule_view', 1, $group_id, $module->getVar('mid'));}Sessiebeveiliging
Section titled “Sessiebeveiliging”Beste praktijken voor sessieafhandeling
Section titled “Beste praktijken voor sessieafhandeling”- Bewaar geen gevoelige informatie tijdens de sessie
- Genereer sessie-ID’s opnieuw na wijzigingen in login/rechten
- Valideer sessiegegevens voordat u deze gebruikt
// Regenerate session ID after loginsession_regenerate_id(true);
// Validate session dataif (isset($_SESSION['mymodule_user_id'])) { $user_id = (int)$_SESSION['mymodule_user_id']; // Verify user exists in database}Sessiefixatie voorkomen
Section titled “Sessiefixatie voorkomen”// After successful loginsession_regenerate_id(true);$_SESSION['mymodule_user_ip'] = $_SERVER['REMOTE_ADDR'];
// On subsequent requestsif ($_SESSION['mymodule_user_ip'] !== $_SERVER['REMOTE_ADDR']) { // Possible session hijacking attempt session_destroy(); redirect_header('index.php', 3, 'Session error'); exit();}Beveiliging van bestandsuploads
Section titled “Beveiliging van bestandsuploads”Bestandsuploads valideren
Section titled “Bestandsuploads valideren”// Check if file was uploaded properlyif (!isset($_FILES['userfile']) || $_FILES['userfile']['error'] != UPLOAD_ERR_OK) { redirect_header('index.php', 3, 'File upload error'); exit();}
// Check file sizeif ($_FILES['userfile']['size'] > 1000000) { // 1MB limit redirect_header('index.php', 3, 'File too large'); exit();}
// Check file type$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];if (!in_array($_FILES['userfile']['type'], $allowed_types)) { redirect_header('index.php', 3, 'Invalid file type'); exit();}
// Validate file extension$filename = $_FILES['userfile']['name'];$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];if (!in_array($ext, $allowed_extensions)) { redirect_header('index.php', 3, 'Invalid file extension'); exit();}XOOPS-uploader gebruiken
Section titled “XOOPS-uploader gebruiken”include_once XOOPS_ROOT_PATH . '/class/uploader.php';
$allowed_mimetypes = ['image/gif', 'image/jpeg', 'image/png'];$maxsize = 1000000; // 1MB$maxwidth = 1024;$maxheight = 768;$upload_dir = XOOPS_ROOT_PATH . '/uploads/mymodule';
$uploader = new XoopsMediaUploader( $upload_dir, $allowed_mimetypes, $maxsize, $maxwidth, $maxheight);
if ($uploader->fetchMedia('userfile')) { $uploader->setPrefix('mymodule_');
if ($uploader->upload()) { $filename = $uploader->getSavedFileName(); // Save filename to database } else { echo $uploader->getErrors(); }} else { echo $uploader->getErrors();}Geüploade bestanden veilig opslaan
Section titled “Geüploade bestanden veilig opslaan”// Define upload directory outside web root$upload_dir = XOOPS_VAR_PATH . '/uploads/mymodule';
// Create directory if it doesn't existif (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true);}
// Move uploaded filemove_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . '/' . $safe_filename);Foutafhandeling en logboekregistratie
Section titled “Foutafhandeling en logboekregistratie”Veilige foutafhandeling
Section titled “Veilige foutafhandeling”try { $result = someFunction(); if (!$result) { throw new Exception('Operation failed'); }} catch (Exception $e) { // Log the error xoops_error($e->getMessage());
// Display a generic error message to the user redirect_header('index.php', 3, 'An error occurred. Please try again later.'); exit();}Beveiligingsgebeurtenissen registreren
Section titled “Beveiligingsgebeurtenissen registreren”// Log security eventsxoops_loadLanguage('logger', 'mymodule');$GLOBALS['xoopsLogger']->addExtra('Security', 'Failed login attempt for user: ' . $username);Configuratiebeveiliging
Section titled “Configuratiebeveiliging”Gevoelige configuratie opslaan
Section titled “Gevoelige configuratie opslaan”// Define configuration path outside web root$config_path = XOOPS_VAR_PATH . '/configs/mymodule/config.php';
// Load configurationif (file_exists($config_path)) { include $config_path;} else { // Handle missing configuration}Configuratiebestanden beveiligen
Section titled “Configuratiebestanden beveiligen”Gebruik .htaccess om configuratiebestanden te beveiligen:
# In .htaccess<Files "config.php"> Order Allow,Deny Deny from all</Files>Bibliotheken van derden
Section titled “Bibliotheken van derden”Bibliotheken selecteren
Section titled “Bibliotheken selecteren”- Kies actief onderhouden bibliotheken
- Controleer op beveiligingsproblemen
- Controleer of de licentie van de bibliotheek compatibel is met XOOPS
Bibliotheken bijwerken
Section titled “Bibliotheken bijwerken”// Check library versionif (version_compare(LIBRARY_VERSION, '1.2.3', '<')) { xoops_error('Please update the library to version 1.2.3 or higher');}Bibliotheken isoleren
Section titled “Bibliotheken isoleren”// Load library in a controlled wayfunction loadLibrary($file){ $allowed = ['parser.php', 'formatter.php'];
if (!in_array($file, $allowed)) { return false; }
include_once XOOPS_ROOT_PATH . '/modules/mymodule/libraries/' . $file; return true;}Beveiligingstests
Section titled “Beveiligingstests”Handmatige testchecklist
Section titled “Handmatige testchecklist”- Test alle formulieren met ongeldige invoer
- Probeer authenticatie en autorisatie te omzeilen
- Test de functionaliteit voor het uploaden van bestanden met kwaadaardige bestanden
- Controleer op XSS-kwetsbaarheden in alle uitvoer
- Test op SQL-injectie in alle databasequery’s
Geautomatiseerd testen
Section titled “Geautomatiseerd testen”Gebruik geautomatiseerde tools om te scannen op kwetsbaarheden:
- Analysetools voor statische code
- Scanners voor webapplicaties
- Afhankelijkheidscontroles voor bibliotheken van derden
Uitvoer ontsnapt
Section titled “Uitvoer ontsnapt”HTML-context
Section titled “HTML-context”// For regular HTML contentecho htmlspecialchars($variable, ENT_QUOTES, 'UTF-8');
// Using MyTextSanitizer$myts = MyTextSanitizer::getInstance();echo $myts->htmlSpecialChars($variable);JavaScript-context
Section titled “JavaScript-context”// For data used in JavaScriptecho json_encode($variable);
// For inline JavaScriptecho 'var data = ' . json_encode($variable) . ';';URL-context
Section titled “URL-context”// For data used in URLsecho htmlspecialchars(urlencode($variable), ENT_QUOTES, 'UTF-8');Sjabloonvariabelen
Section titled “Sjabloonvariabelen”// Assign variables to Smarty template$GLOBALS['xoopsTpl']->assign('title', htmlspecialchars($title, ENT_QUOTES, 'UTF-8'));
// For HTML content that should be displayed as-is$GLOBALS['xoopsTpl']->assign('content', $myts->displayTarea($content, 1, 1, 1, 1, 1));Bronnen
Section titled “Bronnen”#security #best-practices #xoops #module-ontwikkeling #authenticatie #autorisatie