Merge pull request 'Zertifikatsprüfung als Opt-in: pro Site und für SMTP' (#17) from feature/ssl-verify into main
All checks were successful
CI / PHP Lint (push) Successful in 37s
CI / PHP Lint-1 (push) Successful in 40s
Release-Paket / ZIP bauen und veröffentlichen (push) Successful in 11s
CI / Unit Tests & Static Analysis (push) Successful in 42s

This commit is contained in:
Friederich Loheide 2026-09-25 05:12:50 +00:00
commit 3a5b95119c
19 changed files with 136 additions and 35 deletions

View file

@ -184,8 +184,16 @@ cd Unifi-Voucher-Tool
- **Site ID:** UniFi Site ID (meist `default`) - **Site ID:** UniFi Site ID (meist `default`)
- **Controller URL:** `https://unifi.example.com:11443` - **Controller URL:** `https://unifi.example.com:11443`
- **Benutzername / Passwort:** UniFi Admin-Zugangsdaten - **Benutzername / Passwort:** UniFi Admin-Zugangsdaten
- **Zertifikat des Controllers prüfen:** optional, siehe unten
3. **Verbindung testen** klicken, dann speichern 3. **Verbindung testen** klicken, dann speichern
> **Zertifikatsprüfung:** UniFi-Geräte liefern ab Werk ein selbst signiertes
> Zertifikat, deshalb ist die Prüfung standardmäßig **aus** – sonst käme keine
> Verbindung zustande. Läuft der Controller unter seinem echten Namen mit einem
> gültigen Zertifikat (eigene CA oder Let's Encrypt), schalten Sie die Prüfung
> pro Site ein; die Verbindung ist dann gegen Man-in-the-Middle abgesichert.
> Für den Mailversand gibt es denselben Schalter unter **Einstellungen → SMTP**.
### Voucher erstellen ### Voucher erstellen
1. Startseite öffnen (Login je nach Konfiguration optional) 1. Startseite öffnen (Login je nach Konfiguration optional)
@ -418,6 +426,7 @@ Das Tool ist auf einen sicheren Standardbetrieb ausgelegt:
| **OAuth** | `state`-Validierung gegen Login-CSRF | | **OAuth** | `state`-Validierung gegen Login-CSRF |
| **Brute-Force** | Login-Rate-Limiting + Throttle der öffentlichen Voucher-Erstellung | | **Brute-Force** | Login-Rate-Limiting + Throttle der öffentlichen Voucher-Erstellung |
| **Sessions** | HttpOnly, SameSite, strict mode + absolutes Timeout | | **Sessions** | HttpOnly, SameSite, strict mode + absolutes Timeout |
| **TLS zum Controller** | Zertifikatsprüfung pro Site einschaltbar (aus, solange der Controller self-signed ist) |
| **Fehler** | `display_errors` aus, `log_errors` an (kein Info-Leak) | | **Fehler** | `display_errors` aus, `log_errors` an (kein Info-Leak) |
Mitgeliefert wird eine `.htaccess` im Projektstamm mit Sicherheits-Headern Mitgeliefert wird eine `.htaccess` im Projektstamm mit Sicherheits-Headern

View file

@ -29,7 +29,7 @@ if (isset($_GET['export']) && isset($_GET['token']) && $auth->validateCsrfToken(
'note' => 'Site-Passwörter sind mit dem APP_KEY dieser Installation verschlüsselt.', 'note' => 'Site-Passwörter sind mit dem APP_KEY dieser Installation verschlüsselt.',
], ],
'settings' => $db->fetchAll("SELECT setting_key, setting_value FROM settings"), 'settings' => $db->fetchAll("SELECT setting_key, setting_value FROM settings"),
'sites' => $db->fetchAll("SELECT name, site_id, unifi_controller_url, unifi_username, unifi_password, is_active, public_access FROM sites"), 'sites' => $db->fetchAll("SELECT name, site_id, unifi_controller_url, unifi_username, unifi_password, ssl_verify, is_active, public_access FROM sites"),
'voucher_templates' => $db->fetchAll("SELECT name, max_uses, expire_minutes, description, qos_rate_max_down, qos_rate_max_up, qos_usage_quota, is_active FROM voucher_templates"), 'voucher_templates' => $db->fetchAll("SELECT name, max_uses, expire_minutes, description, qos_rate_max_down, qos_rate_max_up, qos_usage_quota, is_active FROM voucher_templates"),
// Display-Seiten samt Token: sonst zeigen aufgehängte QR-Codes nach // Display-Seiten samt Token: sonst zeigen aufgehängte QR-Codes nach
// einem Restore ins Leere. Site und Profil werden über den Namen // einem Restore ins Leere. Site und Profil werden über den Namen
@ -84,13 +84,13 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import'])) {
$exists = $db->fetchOne("SELECT id FROM sites WHERE name = ? AND site_id = ?", [$s['name'], $s['site_id']]); $exists = $db->fetchOne("SELECT id FROM sites WHERE name = ? AND site_id = ?", [$s['name'], $s['site_id']]);
if ($exists) { if ($exists) {
$db->query( $db->query(
"UPDATE sites SET unifi_controller_url=?, unifi_username=?, unifi_password=?, is_active=?, public_access=? WHERE id=?", "UPDATE sites SET unifi_controller_url=?, unifi_username=?, unifi_password=?, ssl_verify=?, is_active=?, public_access=? WHERE id=?",
[$s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (int)$s['is_active'], (int)$s['public_access'], $exists['id']] [$s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (int)($s['ssl_verify'] ?? 0), (int)$s['is_active'], (int)$s['public_access'], $exists['id']]
); );
} else { } else {
$db->query( $db->query(
"INSERT INTO sites (name, site_id, unifi_controller_url, unifi_username, unifi_password, is_active, public_access) VALUES (?,?,?,?,?,?,?)", "INSERT INTO sites (name, site_id, unifi_controller_url, unifi_username, unifi_password, ssl_verify, is_active, public_access) VALUES (?,?,?,?,?,?,?,?)",
[$s['name'], $s['site_id'], $s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (int)$s['is_active'], (int)$s['public_access']] [$s['name'], $s['site_id'], $s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (int)($s['ssl_verify'] ?? 0), (int)$s['is_active'], (int)$s['public_access']]
); );
} }
$counts['sites']++; $counts['sites']++;

View file

@ -44,7 +44,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do_import'])) {
$controller = new UniFiController( $controller = new UniFiController(
$site['unifi_controller_url'], $site['unifi_username'], $site['unifi_controller_url'], $site['unifi_username'],
Crypto::decrypt($site['unifi_password']), $site['site_id'] Crypto::decrypt($site['unifi_password']), $site['site_id'],
$site['ssl_verify'] ?? 0
); );
$created = 0; $created = 0;

View file

@ -29,7 +29,7 @@ if (isset($_GET['ajax_stats'])) {
if ($syncFirst) { if ($syncFirst) {
foreach ($sites as $site) { foreach ($sites as $site) {
try { try {
$ctrl = new UniFiController($site['unifi_controller_url'], $site['unifi_username'], Crypto::decrypt($site['unifi_password']), $site['site_id']); $ctrl = new UniFiController($site['unifi_controller_url'], $site['unifi_username'], Crypto::decrypt($site['unifi_password']), $site['site_id'], $site['ssl_verify'] ?? 0);
$ctrl->syncVouchersToDatabase($db, $site['id']); $ctrl->syncVouchersToDatabase($db, $site['id']);
} catch (Exception $e) { } catch (Exception $e) {
$syncErrors[$site['id']] = $e->getMessage(); $syncErrors[$site['id']] = $e->getMessage();

View file

@ -111,6 +111,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
$settings['smtp_password'] = trim($_POST['smtp_password']); $settings['smtp_password'] = trim($_POST['smtp_password']);
} }
$settings['smtp_encryption'] = trim($_POST['smtp_encryption'] ?? 'tls'); $settings['smtp_encryption'] = trim($_POST['smtp_encryption'] ?? 'tls');
$settings['smtp_verify_ssl'] = isset($_POST['smtp_verify_ssl']) ? '1' : '0';
$settings['smtp_from_email'] = trim($_POST['smtp_from_email'] ?? ''); $settings['smtp_from_email'] = trim($_POST['smtp_from_email'] ?? '');
$settings['smtp_from_name'] = trim($_POST['smtp_from_name'] ?? ''); $settings['smtp_from_name'] = trim($_POST['smtp_from_name'] ?? '');
} }
@ -208,6 +209,7 @@ $cs = [
'smtp_username' => $db->getSetting('smtp_username', ''), 'smtp_username' => $db->getSetting('smtp_username', ''),
'smtp_password' => $db->getSetting('smtp_password', ''), 'smtp_password' => $db->getSetting('smtp_password', ''),
'smtp_encryption' => $db->getSetting('smtp_encryption', 'tls'), 'smtp_encryption' => $db->getSetting('smtp_encryption', 'tls'),
'smtp_verify_ssl' => $db->getSetting('smtp_verify_ssl', '0'),
'smtp_from_email' => $db->getSetting('smtp_from_email', ''), 'smtp_from_email' => $db->getSetting('smtp_from_email', ''),
'smtp_from_name' => $db->getSetting('smtp_from_name', ''), 'smtp_from_name' => $db->getSetting('smtp_from_name', ''),
'system_url' => $db->getSetting('system_url', $autoDetectedUrl), 'system_url' => $db->getSetting('system_url', $autoDetectedUrl),
@ -562,6 +564,8 @@ $adminBase = '';
<div class="form-group"><label>Benutzername</label><input type="text" name="smtp_username" value="<?= htmlspecialchars($cs['smtp_username']) ?>"></div> <div class="form-group"><label>Benutzername</label><input type="text" name="smtp_username" value="<?= htmlspecialchars($cs['smtp_username']) ?>"></div>
<div class="form-group"><label>Passwort</label><input type="password" name="smtp_password" placeholder="<?= __('settings_leave_empty') ?>"></div> <div class="form-group"><label>Passwort</label><input type="password" name="smtp_password" placeholder="<?= __('settings_leave_empty') ?>"></div>
</div> </div>
<div class="checkbox-group" style="margin-bottom:6px;"><input type="checkbox" name="smtp_verify_ssl" id="smtp_verify_ssl" <?= $cs['smtp_verify_ssl'] == '1' ? 'checked' : '' ?>><label for="smtp_verify_ssl" style="margin:0;"><?= __('settings_smtp_verify') ?></label></div>
<p class="help-text" style="margin-bottom:16px;"><?= __('settings_smtp_verify_hint') ?></p>
<div class="form-grid"> <div class="form-grid">
<div class="form-group"><label>Absender E-Mail</label><input type="email" name="smtp_from_email" value="<?= htmlspecialchars($cs['smtp_from_email']) ?>"></div> <div class="form-group"><label>Absender E-Mail</label><input type="email" name="smtp_from_email" value="<?= htmlspecialchars($cs['smtp_from_email']) ?>"></div>
<div class="form-group"><label><?= __('settings_smtp_from_name') ?></label><input type="text" name="smtp_from_name" value="<?= htmlspecialchars($cs['smtp_from_name']) ?>"></div> <div class="form-group"><label><?= __('settings_smtp_from_name') ?></label><input type="text" name="smtp_from_name" value="<?= htmlspecialchars($cs['smtp_from_name']) ?>"></div>

View file

@ -32,15 +32,16 @@ if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['edit_site'])) {
$username = trim($_POST['username']); $username = trim($_POST['username']);
$password = $_POST['password']; $password = $_POST['password'];
$publicAccess = isset($_POST['public_access']) ? 1 : 0; $publicAccess = isset($_POST['public_access']) ? 1 : 0;
$sslVerify = isset($_POST['ssl_verify']) ? 1 : 0;
if (empty($name)||empty($siteIdStr)||empty($controllerUrl)||empty($username)) throw new Exception(__('error_fill_all')); if (empty($name)||empty($siteIdStr)||empty($controllerUrl)||empty($username)) throw new Exception(__('error_fill_all'));
if (!empty($password)) { if (!empty($password)) {
$test = UniFiController::testConnection($controllerUrl,$username,$password,$siteIdStr); $test = UniFiController::testConnection($controllerUrl,$username,$password,$siteIdStr,$sslVerify);
if ($test !== true) throw new Exception('Verbindung fehlgeschlagen: '.$test); if ($test !== true) throw new Exception('Verbindung fehlgeschlagen: '.$test);
$db->execute("UPDATE sites SET name=?,site_id=?,unifi_controller_url=?,unifi_username=?,unifi_password=?,public_access=? WHERE id=?", $db->execute("UPDATE sites SET name=?,site_id=?,unifi_controller_url=?,unifi_username=?,unifi_password=?,ssl_verify=?,public_access=? WHERE id=?",
[$name,$siteIdStr,$controllerUrl,$username,Crypto::encrypt($password),$publicAccess,$siteId]); [$name,$siteIdStr,$controllerUrl,$username,Crypto::encrypt($password),$sslVerify,$publicAccess,$siteId]);
} else { } else {
$db->execute("UPDATE sites SET name=?,site_id=?,unifi_controller_url=?,unifi_username=?,public_access=? WHERE id=?", $db->execute("UPDATE sites SET name=?,site_id=?,unifi_controller_url=?,unifi_username=?,ssl_verify=?,public_access=? WHERE id=?",
[$name,$siteIdStr,$controllerUrl,$username,$publicAccess,$siteId]); [$name,$siteIdStr,$controllerUrl,$username,$sslVerify,$publicAccess,$siteId]);
} }
$auth->writeAuditLog($_SESSION['user_id'],'site_edit','site',$siteId,"Site {$name} aktualisiert"); $auth->writeAuditLog($_SESSION['user_id'],'site_edit','site',$siteId,"Site {$name} aktualisiert");
$success = __('sites_updated'); $success = __('sites_updated');
@ -60,11 +61,12 @@ if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_site'])) {
$username = trim($_POST['username']); $username = trim($_POST['username']);
$password = $_POST['password']; $password = $_POST['password'];
$publicAccess = isset($_POST['public_access']) ? 1 : 0; $publicAccess = isset($_POST['public_access']) ? 1 : 0;
$sslVerify = isset($_POST['ssl_verify']) ? 1 : 0;
if (empty($name)||empty($siteId)||empty($controllerUrl)||empty($username)) throw new Exception(__('error_fill_all')); if (empty($name)||empty($siteId)||empty($controllerUrl)||empty($username)) throw new Exception(__('error_fill_all'));
$test = UniFiController::testConnection($controllerUrl,$username,$password,$siteId); $test = UniFiController::testConnection($controllerUrl,$username,$password,$siteId,$sslVerify);
if ($test !== true) throw new Exception('Verbindung fehlgeschlagen: '.$test); if ($test !== true) throw new Exception('Verbindung fehlgeschlagen: '.$test);
$newId = $db->execute("INSERT INTO sites (name,site_id,unifi_controller_url,unifi_username,unifi_password,public_access) VALUES (?,?,?,?,?,?)", $newId = $db->execute("INSERT INTO sites (name,site_id,unifi_controller_url,unifi_username,unifi_password,ssl_verify,public_access) VALUES (?,?,?,?,?,?,?)",
[$name,$siteId,$controllerUrl,$username,Crypto::encrypt($password),$publicAccess]); [$name,$siteId,$controllerUrl,$username,Crypto::encrypt($password),$sslVerify,$publicAccess]);
$auth->writeAuditLog($_SESSION['user_id'],'site_create','site',$newId,"Site {$name} erstellt"); $auth->writeAuditLog($_SESSION['user_id'],'site_create','site',$newId,"Site {$name} erstellt");
$success = __('sites_added'); $success = __('sites_added');
} catch (Exception $e) { $error = $e->getMessage(); } } catch (Exception $e) { $error = $e->getMessage(); }
@ -140,6 +142,9 @@ $currentPage = 'sites';
<?php if ($site['public_access']): ?> <?php if ($site['public_access']): ?>
<span class="badge badge-info"><i class="fas fa-globe" aria-hidden="true"></i> <?= __('status_public') ?></span> <span class="badge badge-info"><i class="fas fa-globe" aria-hidden="true"></i> <?= __('status_public') ?></span>
<?php endif; ?> <?php endif; ?>
<?php if (!empty($site['ssl_verify'])): ?>
<span class="badge badge-secondary" title="<?= __('sites_ssl_verify_hint') ?>"><i class="fas fa-lock" aria-hidden="true"></i> <?= __('sites_ssl_badge') ?></span>
<?php endif; ?>
</div> </div>
</div> </div>
<div class="site-info"> <div class="site-info">
@ -157,7 +162,7 @@ $currentPage = 'sites';
</div> </div>
</div> </div>
<div class="site-actions"> <div class="site-actions">
<button onclick="openEditModal(<?= $site['id'] ?>, '<?= htmlspecialchars($site['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['site_id'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['unifi_controller_url'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['unifi_username'], ENT_QUOTES) ?>', <?= $site['public_access'] ?>)" <button onclick="openEditModal(<?= $site['id'] ?>, '<?= htmlspecialchars($site['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['site_id'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['unifi_controller_url'], ENT_QUOTES) ?>', '<?= htmlspecialchars($site['unifi_username'], ENT_QUOTES) ?>', <?= (int)($site['public_access'] ?? 0) ?>, <?= (int)($site['ssl_verify'] ?? 0) ?>)"
class="btn btn-secondary btn-sm"> class="btn btn-secondary btn-sm">
<i class="fas fa-edit" aria-hidden="true"></i> <?= __('btn_edit') ?> <i class="fas fa-edit" aria-hidden="true"></i> <?= __('btn_edit') ?>
</button> </button>
@ -214,6 +219,11 @@ $currentPage = 'sites';
<input type="checkbox" id="add_public" name="public_access"> <input type="checkbox" id="add_public" name="public_access">
<label for="add_public" style="margin:0;"><?= __('sites_public') ?></label> <label for="add_public" style="margin:0;"><?= __('sites_public') ?></label>
</div> </div>
<div class="form-group checkbox-group">
<input type="checkbox" id="add_ssl_verify" name="ssl_verify">
<label for="add_ssl_verify" style="margin:0;"><?= __('sites_ssl_verify') ?></label>
</div>
<p class="help-text"><?= __('sites_ssl_verify_hint') ?></p>
<div style="display:flex;gap:10px;margin-top:20px;"> <div style="display:flex;gap:10px;margin-top:20px;">
<button type="submit" class="btn btn-primary" style="flex:1;" id="addSiteSubmitBtn"> <button type="submit" class="btn btn-primary" style="flex:1;" id="addSiteSubmitBtn">
<i class="fas fa-save" aria-hidden="true"></i> <?= __('sites_add') ?> <i class="fas fa-save" aria-hidden="true"></i> <?= __('sites_add') ?>
@ -264,6 +274,11 @@ $currentPage = 'sites';
<input type="checkbox" id="edit_public_access" name="public_access"> <input type="checkbox" id="edit_public_access" name="public_access">
<label for="edit_public_access" style="margin:0;"><?= __('sites_public') ?></label> <label for="edit_public_access" style="margin:0;"><?= __('sites_public') ?></label>
</div> </div>
<div class="form-group checkbox-group">
<input type="checkbox" id="edit_ssl_verify" name="ssl_verify">
<label for="edit_ssl_verify" style="margin:0;"><?= __('sites_ssl_verify') ?></label>
</div>
<p class="help-text"><?= __('sites_ssl_verify_hint') ?></p>
<div style="display:flex;gap:10px;margin-top:20px;"> <div style="display:flex;gap:10px;margin-top:20px;">
<button type="submit" class="btn btn-primary" style="flex:1;" id="editSiteSubmitBtn"> <button type="submit" class="btn btn-primary" style="flex:1;" id="editSiteSubmitBtn">
<i class="fas fa-save" aria-hidden="true"></i> <?= __('btn_save') ?> <i class="fas fa-save" aria-hidden="true"></i> <?= __('btn_save') ?>
@ -281,7 +296,7 @@ $currentPage = 'sites';
function openModal() { document.getElementById('addSiteModal').classList.add('active'); } function openModal() { document.getElementById('addSiteModal').classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); } function closeModal(id) { document.getElementById(id).classList.remove('active'); }
function openEditModal(id, name, siteIdStr, controllerUrl, username, publicAccess) { function openEditModal(id, name, siteIdStr, controllerUrl, username, publicAccess, sslVerify) {
document.getElementById('edit_site_id').value = id; document.getElementById('edit_site_id').value = id;
document.getElementById('edit_name').value = name; document.getElementById('edit_name').value = name;
document.getElementById('edit_site_id_str').value = siteIdStr; document.getElementById('edit_site_id_str').value = siteIdStr;
@ -289,6 +304,7 @@ function openEditModal(id, name, siteIdStr, controllerUrl, username, publicAcces
document.getElementById('edit_username').value = username; document.getElementById('edit_username').value = username;
document.getElementById('edit_password').value = ''; document.getElementById('edit_password').value = '';
document.getElementById('edit_public_access').checked = publicAccess == 1; document.getElementById('edit_public_access').checked = publicAccess == 1;
document.getElementById('edit_ssl_verify').checked = sslVerify == 1;
document.getElementById('editSiteModal').classList.add('active'); document.getElementById('editSiteModal').classList.add('active');
} }

View file

@ -44,7 +44,7 @@ if (isset($_GET['ajax_get_vouchers']) && isset($_GET['site_id'])) {
if (!$site) { echo json_encode(['success'=>false,'message'=>__('error_site_not_found')]); exit; } if (!$site) { echo json_encode(['success'=>false,'message'=>__('error_site_not_found')]); exit; }
if ($syncFirst) { if ($syncFirst) {
try { try {
$ctrl = new UniFiController($site['unifi_controller_url'],$site['unifi_username'],Crypto::decrypt($site['unifi_password']),$site['site_id']); $ctrl = new UniFiController($site['unifi_controller_url'],$site['unifi_username'],Crypto::decrypt($site['unifi_password']),$site['site_id'],$site['ssl_verify'] ?? 0);
$ctrl->syncVouchersToDatabase($db,$siteId); $ctrl->syncVouchersToDatabase($db,$siteId);
$db->execute("INSERT INTO settings (setting_key,setting_value) VALUES ('last_cron_sync',NOW()) ON DUPLICATE KEY UPDATE setting_value=NOW()"); $db->execute("INSERT INTO settings (setting_key,setting_value) VALUES ('last_cron_sync',NOW()) ON DUPLICATE KEY UPDATE setting_value=NOW()");
} catch (Exception $e) { error_log("Sync error: ".$e->getMessage()); } } catch (Exception $e) { error_log("Sync error: ".$e->getMessage()); }
@ -83,7 +83,7 @@ if (isset($_POST['ajax_delete']) && isset($_POST['voucher_id']) && isset($_POST[
$siteId = (int)$_POST['site_id']; $siteId = (int)$_POST['site_id'];
$site = $db->fetchOne("SELECT * FROM sites WHERE id=? AND is_active=1", [$siteId]); $site = $db->fetchOne("SELECT * FROM sites WHERE id=? AND is_active=1", [$siteId]);
if (!$site) { echo json_encode(['success'=>false,'message'=>__('error_site_not_found')]); exit; } if (!$site) { echo json_encode(['success'=>false,'message'=>__('error_site_not_found')]); exit; }
$ctrl = new UniFiController($site['unifi_controller_url'],$site['unifi_username'],Crypto::decrypt($site['unifi_password']),$site['site_id']); $ctrl = new UniFiController($site['unifi_controller_url'],$site['unifi_username'],Crypto::decrypt($site['unifi_password']),$site['site_id'],$site['ssl_verify'] ?? 0);
if ($ctrl->deleteVoucher($voucherId)) { if ($ctrl->deleteVoucher($voucherId)) {
$db->execute("DELETE FROM vouchers WHERE unifi_voucher_id=? AND site_id=?", [$voucherId,$siteId]); $db->execute("DELETE FROM vouchers WHERE unifi_voucher_id=? AND site_id=?", [$voucherId,$siteId]);
echo json_encode(['success'=>true,'message'=>'Voucher erfolgreich gelöscht!']); echo json_encode(['success'=>true,'message'=>'Voucher erfolgreich gelöscht!']);

View file

@ -60,7 +60,8 @@ if ($method === 'POST') {
$site['unifi_controller_url'], $site['unifi_controller_url'],
$site['unifi_username'], $site['unifi_username'],
Crypto::decrypt($site['unifi_password']), Crypto::decrypt($site['unifi_password']),
$site['site_id'] $site['site_id'],
$site['ssl_verify'] ?? 0
); );
$voucher = $controller->createVoucher($fullName, $maxUses, $expireMinutes, $qos); $voucher = $controller->createVoucher($fullName, $maxUses, $expireMinutes, $qos);
if (!is_array($voucher) || empty($voucher['formatted_code'])) { if (!is_array($voucher) || empty($voucher['formatted_code'])) {

View file

@ -174,7 +174,8 @@ try {
$site['unifi_controller_url'], $site['unifi_controller_url'],
$site['unifi_username'], $site['unifi_username'],
Crypto::decrypt($site['unifi_password']), Crypto::decrypt($site['unifi_password']),
$site['site_id'] $site['site_id'],
$site['ssl_verify'] ?? 0
); );
$stats = $controller->syncVouchersToDatabase($db, $site['id']); $stats = $controller->syncVouchersToDatabase($db, $site['id']);

View file

@ -15,6 +15,7 @@ CREATE TABLE IF NOT EXISTS `sites` (
`unifi_controller_url` VARCHAR(255) NOT NULL, `unifi_controller_url` VARCHAR(255) NOT NULL,
`unifi_username` VARCHAR(100) NOT NULL, `unifi_username` VARCHAR(100) NOT NULL,
`unifi_password` VARCHAR(255) NOT NULL, `unifi_password` VARCHAR(255) NOT NULL,
`ssl_verify` TINYINT(1) NOT NULL DEFAULT 0,
`is_active` TINYINT(1) DEFAULT 1, `is_active` TINYINT(1) DEFAULT 1,
`public_access` TINYINT(1) DEFAULT 0, `public_access` TINYINT(1) DEFAULT 0,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

View file

@ -46,7 +46,8 @@ if (isset($_GET['deep']) && $_GET['deep'] == '1') {
foreach ($db->fetchAll("SELECT * FROM sites WHERE is_active=1") as $site) { foreach ($db->fetchAll("SELECT * FROM sites WHERE is_active=1") as $site) {
$r = UniFiController::testConnection( $r = UniFiController::testConnection(
$site['unifi_controller_url'], $site['unifi_username'], $site['unifi_controller_url'], $site['unifi_username'],
Crypto::decrypt($site['unifi_password']), $site['site_id'] Crypto::decrypt($site['unifi_password']), $site['site_id'],
$site['ssl_verify'] ?? 0
); );
$ok = ($r === true); $ok = ($r === true);
$controllers[$site['name']] = $ok ? 'ok' : 'unreachable'; $controllers[$site['name']] = $ok ? 'ok' : 'unreachable';

View file

@ -7,6 +7,7 @@ class Mailer {
private $smtpUsername; private $smtpUsername;
private $smtpPassword; private $smtpPassword;
private $smtpEncryption; private $smtpEncryption;
private $smtpVerifySsl = false;
private $fromEmail; private $fromEmail;
private $fromName; private $fromName;
@ -22,6 +23,10 @@ class Mailer {
$this->smtpUsername = $this->db->getSetting('smtp_username', ''); $this->smtpUsername = $this->db->getSetting('smtp_username', '');
$this->smtpPassword = $this->db->getSetting('smtp_password', ''); $this->smtpPassword = $this->db->getSetting('smtp_password', '');
$this->smtpEncryption = $this->db->getSetting('smtp_encryption', 'tls'); $this->smtpEncryption = $this->db->getSetting('smtp_encryption', 'tls');
// Zertifikat des Mailservers pruefen? Standard aus, damit sich
// bestehende Installationen mit eigenem Server nicht ploetzlich
// nicht mehr verbinden koennen.
$this->smtpVerifySsl = $this->db->getSetting('smtp_verify_ssl', '0') === '1';
$this->fromEmail = $this->db->getSetting('smtp_from_email', 'noreply@' . $_SERVER['HTTP_HOST']); $this->fromEmail = $this->db->getSetting('smtp_from_email', 'noreply@' . $_SERVER['HTTP_HOST']);
$this->fromName = $this->db->getSetting('smtp_from_name', $this->db->getSetting('app_title', 'UniFi Voucher System')); $this->fromName = $this->db->getSetting('smtp_from_name', $this->db->getSetting('app_title', 'UniFi Voucher System'));
} }
@ -128,9 +133,9 @@ class Mailer {
private function connectToSmtp() { private function connectToSmtp() {
$context = stream_context_create([ $context = stream_context_create([
'ssl' => [ 'ssl' => [
'verify_peer' => false, 'verify_peer' => $this->smtpVerifySsl,
'verify_peer_name' => false, 'verify_peer_name' => $this->smtpVerifySsl,
'allow_self_signed' => true 'allow_self_signed' => !$this->smtpVerifySsl
] ]
]); ]);

View file

@ -10,12 +10,19 @@ class UniFiController {
private $csrfToken = null; private $csrfToken = null;
private $sessionCookie = null; private $sessionCookie = null;
private $loggedIn = false; private $loggedIn = false;
/**
* Zertifikat pruefen? Standard aus, weil UniFi-Controller meist ein
* selbst signiertes Zertifikat verwenden. Wer einen eigenen Namen samt
* gueltigem Zertifikat betreibt, schaltet es pro Site ein.
*/
private $sslVerify = false;
public function __construct($controllerUrl, $username, $password, $siteId) { public function __construct($controllerUrl, $username, $password, $siteId, $sslVerify = false) {
$this->controllerUrl = rtrim($controllerUrl, '/'); $this->controllerUrl = rtrim($controllerUrl, '/');
$this->username = $username; $this->username = $username;
$this->password = $password; $this->password = $password;
$this->siteId = $siteId; $this->siteId = $siteId;
$this->sslVerify = (bool)$sslVerify;
$this->cookieFile = tempnam(sys_get_temp_dir(), 'UNIFI_'); $this->cookieFile = tempnam(sys_get_temp_dir(), 'UNIFI_');
} }
@ -41,7 +48,8 @@ class UniFiController {
'password' => $this->password 'password' => $this->password
]), ]),
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYPEER => $this->sslVerify,
CURLOPT_SSL_VERIFYHOST => $this->sslVerify ? 2 : 0,
CURLOPT_COOKIEJAR => $this->cookieFile, CURLOPT_COOKIEJAR => $this->cookieFile,
CURLOPT_COOKIEFILE => $this->cookieFile, CURLOPT_COOKIEFILE => $this->cookieFile,
CURLOPT_TIMEOUT => 10, CURLOPT_TIMEOUT => 10,
@ -122,7 +130,8 @@ class UniFiController {
$options = [ $options = [
CURLOPT_URL => $url, CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYPEER => $this->sslVerify,
CURLOPT_SSL_VERIFYHOST => $this->sslVerify ? 2 : 0,
CURLOPT_TIMEOUT => 10, CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
@ -326,9 +335,9 @@ class UniFiController {
} }
// Verbindung testen // Verbindung testen
public static function testConnection($controllerUrl, $username, $password, $siteId) { public static function testConnection($controllerUrl, $username, $password, $siteId, $sslVerify = false) {
try { try {
$controller = new self($controllerUrl, $username, $password, $siteId); $controller = new self($controllerUrl, $username, $password, $siteId, $sslVerify);
$controller->login(); $controller->login();
return true; return true;
} catch (Exception $e) { } catch (Exception $e) {

View file

@ -35,7 +35,8 @@ class VoucherService
$site['unifi_controller_url'], $site['unifi_controller_url'],
$site['unifi_username'], $site['unifi_username'],
Crypto::decrypt($site['unifi_password']), Crypto::decrypt($site['unifi_password']),
$site['site_id'] $site['site_id'],
$site['ssl_verify'] ?? 0
); );
$voucher = $controller->createVoucher($fullName, $maxUses, $expireMinutes, $qos); $voucher = $controller->createVoucher($fullName, $maxUses, $expireMinutes, $qos);

View file

@ -180,6 +180,9 @@ return [
'sites_password_edit'=> 'Neues Passwort', 'sites_password_edit'=> 'Neues Passwort',
'sites_password_hint'=> 'Nur ausfüllen wenn Sie das Passwort ändern möchten', 'sites_password_hint'=> 'Nur ausfüllen wenn Sie das Passwort ändern möchten',
'sites_public' => 'Öffentlicher Zugriff (ohne Login nutzbar)', 'sites_public' => 'Öffentlicher Zugriff (ohne Login nutzbar)',
'sites_ssl_verify' => 'Zertifikat des Controllers prüfen',
'sites_ssl_verify_hint' => 'Nur einschalten, wenn der Controller unter seinem echten Namen mit einem gültigen Zertifikat erreichbar ist. UniFi-Geräte liefern ab Werk ein selbst signiertes Zertifikat – dann bleibt die Prüfung aus.',
'sites_ssl_badge' => 'Zertifikat geprüft',
'sites_none' => 'Noch keine Sites konfiguriert. Fügen Sie Ihre erste Site hinzu!', 'sites_none' => 'Noch keine Sites konfiguriert. Fügen Sie Ihre erste Site hinzu!',
'sites_added' => 'Site erfolgreich hinzugefügt!', 'sites_added' => 'Site erfolgreich hinzugefügt!',
'sites_updated' => 'Site erfolgreich aktualisiert!', 'sites_updated' => 'Site erfolgreich aktualisiert!',
@ -440,6 +443,8 @@ return [
'settings_defaults_hint' => 'Diese Werte werden als Vorgabe im Voucher-Formular verwendet.', 'settings_defaults_hint' => 'Diese Werte werden als Vorgabe im Voucher-Formular verwendet.',
'settings_cron_what' => 'Was macht der Cron-Job?', 'settings_cron_what' => 'Was macht der Cron-Job?',
'settings_smtp_from_name' => 'Absender Name', 'settings_smtp_from_name' => 'Absender Name',
'settings_smtp_verify' => 'Zertifikat des Mailservers prüfen',
'settings_smtp_verify_hint' => 'Aus, solange der Mailserver ein selbst signiertes Zertifikat verwendet.',
'settings_tpl_voucher_mail' => 'Voucher E-Mail', 'settings_tpl_voucher_mail' => 'Voucher E-Mail',
'settings_tpl_user_notify' => 'Benutzer-Benachrichtigung', 'settings_tpl_user_notify' => 'Benutzer-Benachrichtigung',
'settings_editor_hint' => 'Der Editor (TinyMCE, MIT-Lizenz) wird lokal aus', 'settings_editor_hint' => 'Der Editor (TinyMCE, MIT-Lizenz) wird lokal aus',

View file

@ -180,6 +180,9 @@ return [
'sites_password_edit'=> 'New Password', 'sites_password_edit'=> 'New Password',
'sites_password_hint'=> 'Leave blank to keep current password', 'sites_password_hint'=> 'Leave blank to keep current password',
'sites_public' => 'Public Access (usable without login)', 'sites_public' => 'Public Access (usable without login)',
'sites_ssl_verify' => 'Verify the controller certificate',
'sites_ssl_verify_hint' => 'Only enable this if the controller is reachable under its real host name with a valid certificate. UniFi devices ship with a self-signed certificate – leave it off in that case.',
'sites_ssl_badge' => 'Certificate verified',
'sites_none' => 'No sites configured yet. Add your first site!', 'sites_none' => 'No sites configured yet. Add your first site!',
'sites_added' => 'Site added successfully!', 'sites_added' => 'Site added successfully!',
'sites_updated' => 'Site updated successfully!', 'sites_updated' => 'Site updated successfully!',
@ -440,6 +443,8 @@ return [
'settings_defaults_hint' => 'These values are used as defaults in the voucher form.', 'settings_defaults_hint' => 'These values are used as defaults in the voucher form.',
'settings_cron_what' => 'What does the cron job do?', 'settings_cron_what' => 'What does the cron job do?',
'settings_smtp_from_name' => 'Sender name', 'settings_smtp_from_name' => 'Sender name',
'settings_smtp_verify' => 'Verify the mail server certificate',
'settings_smtp_verify_hint' => 'Leave off while the mail server uses a self-signed certificate.',
'settings_tpl_voucher_mail' => 'Voucher email', 'settings_tpl_voucher_mail' => 'Voucher email',
'settings_tpl_user_notify' => 'User notification', 'settings_tpl_user_notify' => 'User notification',
'settings_editor_hint' => 'The editor (TinyMCE, MIT licensed) is served locally from', 'settings_editor_hint' => 'The editor (TinyMCE, MIT licensed) is served locally from',

View file

@ -149,4 +149,41 @@ class UniFiControllerTest extends TestCase
$this->assertArrayNotHasKey('qos_overwrite', $controller->calls[0]['data']); $this->assertArrayNotHasKey('qos_overwrite', $controller->calls[0]['data']);
$this->assertArrayNotHasKey('down', $controller->calls[0]['data']); $this->assertArrayNotHasKey('down', $controller->calls[0]['data']);
} }
/**
* Die Zertifikatspruefung ist bewusst ein Opt-in: UniFi-Controller
* liefern ab Werk ein selbst signiertes Zertifikat. Eine neue Site ohne
* gesetztes Feld darf sich deshalb nicht ploetzlich anders verhalten.
*/
public function testCertificateCheckIsOffByDefault(): void
{
$controller = new UniFiController('https://unifi.example.com:8443', 'api', 'geheim', 'default');
$this->assertFalse($this->sslVerifyOf($controller));
}
public function testCertificateCheckCanBeEnabled(): void
{
$controller = new UniFiController('https://unifi.example.com:8443', 'api', 'geheim', 'default', 1);
$this->assertTrue($this->sslVerifyOf($controller), 'Der Schalter muss bis zu cURL durchschlagen');
}
/** Werte aus der Datenbank kommen als Strings zurueck. */
public function testCertificateCheckAcceptsDatabaseValues(): void
{
$aus = new UniFiController('https://unifi.example.com:8443', 'api', 'geheim', 'default', '0');
$an = new UniFiController('https://unifi.example.com:8443', 'api', 'geheim', 'default', '1');
$this->assertFalse($this->sslVerifyOf($aus));
$this->assertTrue($this->sslVerifyOf($an));
}
private function sslVerifyOf(UniFiController $controller): bool
{
$property = new \ReflectionProperty(UniFiController::class, 'sslVerify');
$property->setAccessible(true);
return (bool)$property->getValue($controller);
}
} }

View file

@ -115,10 +115,10 @@ class Database {
} }
if (str_contains($s, 'from sites')) { if (str_contains($s, 'from sites')) {
return [ return [
['id'=>1,'name'=>'Hauptstandort Nord','site_id'=>'default','unifi_controller_url'=>'https://unifi.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>1,'created_at'=>'2026-01-12 09:00:00'], ['id'=>1,'name'=>'Hauptstandort Nord','site_id'=>'default','unifi_controller_url'=>'https://unifi.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>1,'ssl_verify'=>1,'public_access'=>1,'created_at'=>'2026-01-12 09:00:00'],
['id'=>2,'name'=>'Campus West','site_id'=>'campus-west','unifi_controller_url'=>'https://unifi.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>1,'created_at'=>'2026-02-03 11:30:00'], ['id'=>2,'name'=>'Campus West','site_id'=>'campus-west','unifi_controller_url'=>'https://unifi.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>1,'ssl_verify'=>0,'public_access'=>1,'created_at'=>'2026-02-03 11:30:00'],
['id'=>3,'name'=>'Showroom Berlin','site_id'=>'showroom','unifi_controller_url'=>'https://unifi-b.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>1,'created_at'=>'2026-04-21 15:10:00'], ['id'=>3,'name'=>'Showroom Berlin','site_id'=>'showroom','unifi_controller_url'=>'https://unifi-b.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>1,'ssl_verify'=>0,'public_access'=>0,'created_at'=>'2026-04-21 15:10:00'],
['id'=>4,'name'=>'Lager Süd','site_id'=>'lager','unifi_controller_url'=>'https://unifi-s.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>0,'created_at'=>'2026-06-08 08:45:00'], ['id'=>4,'name'=>'Lager Süd','site_id'=>'lager','unifi_controller_url'=>'https://unifi-s.example.com:8443','unifi_username'=>'voucher-api','unifi_password'=>'x','is_active'=>1,'use_ssl'=>0,'ssl_verify'=>0,'public_access'=>0,'created_at'=>'2026-06-08 08:45:00'],
]; ];
} }
if (str_contains($s, 'count(v.id) as voucher_count') || str_contains($s, 'from users u left join vouchers')) { if (str_contains($s, 'count(v.id) as voucher_count') || str_contains($s, 'from users u left join vouchers')) {

View file

@ -0,0 +1,5 @@
-- Zertifikatspruefung pro Site einschaltbar. Standard aus, weil
-- UniFi-Controller meist ein selbst signiertes Zertifikat verwenden;
-- bestehende Installationen verhalten sich damit unveraendert.
ALTER TABLE `sites` ADD COLUMN `ssl_verify` TINYINT(1) NOT NULL DEFAULT 0 AFTER `unifi_password`;