Merge branch 'main' into PUID

This commit is contained in:
Jokob @NetAlertX
2026-01-04 11:34:22 +11:00
committed by GitHub
17 changed files with 339 additions and 558 deletions

View File

@@ -130,8 +130,8 @@ ENV READ_ONLY_USER=readonly READ_ONLY_GROUP=readonly
ENV NETALERTX_USER=netalertx NETALERTX_GROUP=netalertx ENV NETALERTX_USER=netalertx NETALERTX_GROUP=netalertx
ENV LANG=C.UTF-8 ENV LANG=C.UTF-8
# hadolint ignore=DL3018
RUN apk add --no-cache bash mtr libbsd zip lsblk tzdata curl arp-scan iproute2 iproute2-ss nmap \ RUN apk add --no-cache bash mtr libbsd zip lsblk tzdata curl arp-scan iproute2 iproute2-ss nmap fping \
nmap-scripts traceroute nbtscan net-tools net-snmp-tools bind-tools awake ca-certificates \ nmap-scripts traceroute nbtscan net-tools net-snmp-tools bind-tools awake ca-certificates \
sqlite php83 php83-fpm php83-cgi php83-curl php83-sqlite3 php83-session python3 envsubst \ sqlite php83 php83-fpm php83-cgi php83-curl php83-sqlite3 php83-session python3 envsubst \
nginx supercronic shadow su-exec && \ nginx supercronic shadow su-exec && \

View File

@@ -135,8 +135,8 @@ COPY --chmod=775 --chown=${USER_ID}:${USER_GID} . ${INSTALL_DIR}/
# hadolint ignore=DL3008,DL3027 # hadolint ignore=DL3008,DL3027
RUN apt-get update && apt-get install -y --no-install-recommends \ RUN apt-get update && apt-get install -y --no-install-recommends \
tini snmp ca-certificates curl libwww-perl arp-scan sudo gettext-base \ tini snmp ca-certificates curl libwww-perl arp-scan sudo gettext-base \
nginx-light php php-cgi php-fpm php-sqlite3 php-curl sqlite3 dnsutils net-tools \ nginx-light php php-cgi php-fpm php-sqlite3 php-curl sqlite3 dnsutils net-tools \
python3 python3-dev iproute2 nmap python3-pip zip git systemctl usbutils traceroute nbtscan openrc \ python3 python3-dev iproute2 nmap fping python3-pip zip git systemctl usbutils traceroute nbtscan openrc \
busybox nginx nginx-core mtr python3-venv && \ busybox nginx nginx-core mtr python3-venv && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*

View File

@@ -1,418 +0,0 @@
<?php
//------------------------------------------------------------------------------
// NetAlertX
// Open Source Network Guard / WIFI & LAN intrusion detector
//
// events.php - Front module. Server side. Manage Events
//------------------------------------------------------------------------------
# Puche 2021 / 2022+ jokob jokob@duck.com GNU GPLv3
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// check server/api_server/api_server_start.py for equivalents
// equivalent: /sessions /events
// 🔺----- API ENDPOINTS SUPERSEDED -----🔺
// External files
require dirname(__FILE__).'/init.php';
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
//------------------------------------------------------------------------------
// Action selector
//------------------------------------------------------------------------------
// Set maximum execution time to 1 minute
ini_set ('max_execution_time','60');
// Action functions
if (isset ($_REQUEST['action']) && !empty ($_REQUEST['action'])) {
$action = $_REQUEST['action'];
switch ($action) {
case 'getEventsTotals': getEventsTotals(); break;
case 'getEvents': getEvents(); break;
case 'getDeviceSessions': getDeviceSessions(); break;
case 'getDevicePresence': getDevicePresence(); break;
case 'getEventsCalendar': getEventsCalendar(); break;
default: logServerConsole ('Action: '. $action); break;
}
}
//------------------------------------------------------------------------------
// Query total numbers of Events
//------------------------------------------------------------------------------
function getEventsTotals() {
global $db;
// Request Parameters
$periodDate = $_REQUEST['period'];
$periodDateSQL = "";
$days = "";
switch ($periodDate) {
case '7 days':
$days = "7";
break;
case '1 month':
$days = "30";
break;
case '1 year':
$days = "365";
break;
case '100 years':
$days = "3650"; //10 years
break;
default:
$days = "1";
}
$periodDateSQL = "-".$days." day";
$resultJSON = "";
// check cache if JSON available in a cookie
if(getCache("getEventsTotals".$days) != "")
{
$resultJSON = getCache("getEventsTotals".$days);
} else
{
// one query to get all numbers, which is quicker than multiple queries
$sql = "select
(SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."')) as all_events,
(SELECT Count(*) FROM Sessions as sessions WHERE ( ses_DateTimeConnection >= date('now', '".$periodDateSQL."') OR ses_DateTimeDisconnection >= date('now', '".$periodDateSQL."') OR ses_StillConnected = 1 )) as sessions,
(SELECT Count(*) FROM Sessions WHERE ((ses_DateTimeConnection IS NULL AND ses_DateTimeDisconnection >= date('now', '".$periodDateSQL."' )) OR (ses_DateTimeDisconnection IS NULL AND ses_StillConnected = 0 AND ses_DateTimeConnection >= date('now', '".$periodDateSQL."' )))) as missing,
(SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."') AND eve_EventType LIKE 'VOIDED%' ) as voided,
(SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."') AND eve_EventType LIKE 'New Device' ) as new,
(SELECT Count(*) FROM Events WHERE eve_DateTime >= date('now', '".$periodDateSQL."') AND eve_EventType LIKE 'Device Down' ) as down";
$result = $db->query($sql);
$row = $result -> fetchArray (SQLITE3_NUM);
$resultJSON = json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5]));
// save JSON result to cache
setCache("getEventsTotals".$days, $resultJSON );
}
// Return json
echo ($resultJSON);
}
//------------------------------------------------------------------------------
// Query the List of events
//------------------------------------------------------------------------------
function getEvents() {
global $db;
// Request Parameters
$type = $_REQUEST ['type'];
$periodDate = getDateFromPeriod();
// SQL
$SQL1 = 'SELECT eve_DateTime AS eve_DateTimeOrder, devName, devOwner, eve_DateTime, eve_EventType, NULL, NULL, NULL, NULL, eve_IP, NULL, eve_AdditionalInfo, NULL, devMac, eve_PendingAlertEmail
FROM Events_Devices
WHERE eve_DateTime >= '. $periodDate;
$SQL2 = 'SELECT IFNULL (ses_DateTimeConnection, ses_DateTimeDisconnection) ses_DateTimeOrder,
devName, devOwner, Null, Null, ses_DateTimeConnection, ses_DateTimeDisconnection, NULL, NULL, ses_IP, NULL, ses_AdditionalInfo, ses_StillConnected, devMac
FROM Sessions_Devices ';
// SQL Variations for status
switch ($type) {
case 'all': $SQL = $SQL1; break;
case 'sessions':
$SQL = $SQL2 . ' WHERE ( ses_DateTimeConnection >= '. $periodDate .' OR ses_DateTimeDisconnection >= '. $periodDate .' OR ses_StillConnected = 1 ) ';
break;
case 'missing':
$SQL = $SQL2 . ' WHERE (ses_DateTimeConnection IS NULL AND ses_DateTimeDisconnection >= '. $periodDate .' )
OR (ses_DateTimeDisconnection IS NULL AND ses_StillConnected = 0 AND ses_DateTimeConnection >= '. $periodDate .' )';
break;
case 'voided': $SQL = $SQL1 .' AND eve_EventType LIKE "VOIDED%" '; break;
case 'new': $SQL = $SQL1 .' AND eve_EventType = "New Device" '; break;
case 'down': $SQL = $SQL1 .' AND eve_EventType = "Device Down" '; break;
default: $SQL = $SQL1 .' AND 1==0 '; break;
}
// Query
$result = $db->query($SQL);
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_NUM)) {
if ($type == 'sessions' || $type == 'missing' ) {
// Duration
if (!empty ($row[5]) && !empty($row[6]) ) {
$row[7] = formatDateDiff ($row[5], $row[6]);
$row[8] = abs(strtotime($row[6]) - strtotime($row[5]));
} elseif ($row[12] == 1) {
$row[7] = formatDateDiff ($row[5], '');
$row[8] = abs(strtotime("now") - strtotime($row[5]));
} else {
$row[7] = '...';
$row[8] = 0;
}
// Connection
if (!empty ($row[5]) ) {
$row[5] = formatDate ($row[5]);
} else {
$row[5] = '<missing event>';
}
// Disconnection
if (!empty ($row[6]) ) {
$row[6] = formatDate ($row[6]);
} elseif ($row[12] == 0) {
$row[6] = '<missing event>';
} else {
$row[6] = '...';
}
} else {
// Event Date
$row[3] = formatDate ($row[3]);
}
// IP Order
$row[10] = formatIPlong ($row[9]);
$tableData['data'][] = $row;
}
// Control no rows
if (empty($tableData['data'])) {
$tableData['data'] = '';
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query Device Sessions
//------------------------------------------------------------------------------
function getDeviceSessions() {
global $db;
// Request Parameters
$mac = $_REQUEST['mac'];
$periodDate = getDateFromPeriod();
// SQL
$SQL = 'SELECT IFNULL (ses_DateTimeConnection, ses_DateTimeDisconnection) ses_DateTimeOrder,
ses_EventTypeConnection, ses_DateTimeConnection,
ses_EventTypeDisconnection, ses_DateTimeDisconnection, ses_StillConnected,
ses_IP, ses_AdditionalInfo
FROM Sessions
WHERE ses_MAC="' . $mac .'"
AND ( ses_DateTimeConnection >= '. $periodDate .'
OR ses_DateTimeDisconnection >= '. $periodDate .'
OR ses_StillConnected = 1 ) ';
$result = $db->query($SQL);
// arrays of rows
$tableData = array();
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Connection DateTime
if ($row['ses_EventTypeConnection'] == '<missing event>') {
$ini = $row['ses_EventTypeConnection'];
} else {
$ini = formatDate ($row['ses_DateTimeConnection']);
}
// Disconnection DateTime
if ($row['ses_StillConnected'] == true) {
$end = '...';
} elseif ($row['ses_EventTypeDisconnection'] == '<missing event>') {
$end = $row['ses_EventTypeDisconnection'];
} else {
$end = formatDate ($row['ses_DateTimeDisconnection']);
}
// Duration
if ($row['ses_EventTypeConnection'] == '<missing event>' || $row['ses_EventTypeConnection'] == NULL || $row['ses_EventTypeDisconnection'] == '<missing event>' || $row['ses_EventTypeDisconnection'] == NULL) {
$dur = '...';
} elseif ($row['ses_StillConnected'] == true) {
$dur = formatDateDiff ($row['ses_DateTimeConnection'], ''); //***********
} else {
$dur = formatDateDiff ($row['ses_DateTimeConnection'], $row['ses_DateTimeDisconnection']);
}
// Additional Info
$info = $row['ses_AdditionalInfo'];
if ($row['ses_EventTypeConnection'] == 'New Device' ) {
$info = $row['ses_EventTypeConnection'] .': '. $info;
}
// Push row data
$tableData['data'][] = array($row['ses_DateTimeOrder'], $ini, $end, $dur, $row['ses_IP'], $info);
}
// Control no rows
if (empty($tableData['data'])) {
$tableData['data'] = '';
}
// Return json
echo (json_encode ($tableData));
}
//------------------------------------------------------------------------------
// Query Device Presence Calendar
//------------------------------------------------------------------------------
function getDevicePresence() {
global $db;
// Request Parameters
$mac = $_REQUEST['mac'];
$startDate = '"'. formatDateISO ($_REQUEST ['start']) .'"';
$endDate = '"'. formatDateISO ($_REQUEST ['end']) .'"';
// SQL
$SQL = 'SELECT ses_EventTypeConnection, ses_DateTimeConnection,
ses_EventTypeDisconnection, ses_DateTimeDisconnection, ses_IP, ses_AdditionalInfo, ses_StillConnected,
CASE
WHEN ses_EventTypeConnection = "<missing event>" THEN
IFNULL ((SELECT MAX(ses_DateTimeDisconnection) FROM Sessions AS SES2 WHERE SES2.ses_MAC = SES1.ses_MAC AND SES2.ses_DateTimeDisconnection < SES1.ses_DateTimeDisconnection), DATETIME(ses_DateTimeDisconnection, "-1 hour"))
ELSE ses_DateTimeConnection
END AS ses_DateTimeConnectionCorrected,
CASE
WHEN ses_EventTypeDisconnection = "<missing event>" OR ses_EventTypeDisconnection = NULL THEN
(SELECT MIN(ses_DateTimeConnection) FROM Sessions AS SES2 WHERE SES2.ses_MAC = SES1.ses_MAC AND SES2.ses_DateTimeConnection > SES1.ses_DateTimeConnection)
ELSE ses_DateTimeDisconnection
END AS ses_DateTimeDisconnectionCorrected
FROM Sessions AS SES1
WHERE ses_MAC="' . $mac .'"
AND (ses_DateTimeConnectionCorrected <= date('. $endDate .')
AND (ses_DateTimeDisconnectionCorrected >= date('. $startDate .') OR ses_StillConnected = 1 )) ';
$result = $db->query($SQL);
// arrays of rows
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Event color
if ($row['ses_EventTypeConnection'] == '<missing event>' || $row['ses_EventTypeDisconnection'] == '<missing event>') {
$color = '#f39c12';
} elseif ($row['ses_StillConnected'] == 1 ) {
$color = '#00a659';
} else {
$color = '#0073b7';
}
// tooltip
$tooltip = 'Connection: ' . formatEventDate ($row['ses_DateTimeConnection'], $row['ses_EventTypeConnection']) . chr(13) .
'Disconnection: ' . formatEventDate ($row['ses_DateTimeDisconnection'], $row['ses_EventTypeDisconnection']) . chr(13) .
'IP: ' . $row['ses_IP'];
// Save row data
$tableData[] = array(
'title' => '',
'start' => formatDateISO ($row['ses_DateTimeConnectionCorrected']),
'end' => formatDateISO ($row['ses_DateTimeDisconnectionCorrected']),
'color' => $color,
'tooltip' => $tooltip
);
}
// Control no rows
if (empty($tableData)) {
$tableData = '';
}
// Return json
echo (json_encode($tableData));
}
//------------------------------------------------------------------------------
// Query Presence Calendar for all Devices
//------------------------------------------------------------------------------
function getEventsCalendar() {
global $db;
// Request Parameters
$startDate = '"'. $_REQUEST ['start'] .'"';
$endDate = '"'. $_REQUEST ['end'] .'"';
// SQL
$SQL = 'SELECT SES1.ses_MAC, SES1.ses_EventTypeConnection, SES1.ses_DateTimeConnection,
SES1.ses_EventTypeDisconnection, SES1.ses_DateTimeDisconnection, SES1.ses_IP,
SES1.ses_AdditionalInfo, SES1.ses_StillConnected,
CASE
WHEN SES1.ses_EventTypeConnection = "<missing event>" THEN
IFNULL (
(SELECT MAX(SES2.ses_DateTimeDisconnection)
FROM Sessions AS SES2
WHERE SES2.ses_MAC = SES1.ses_MAC
AND SES2.ses_DateTimeDisconnection < SES1.ses_DateTimeDisconnection
AND SES2.ses_DateTimeDisconnection BETWEEN Date('. $startDate .') AND Date('. $endDate .')
),
DATETIME(SES1.ses_DateTimeDisconnection, "-1 hour")
)
ELSE SES1.ses_DateTimeConnection
END AS ses_DateTimeConnectionCorrected,
CASE
WHEN SES1.ses_EventTypeDisconnection = "<missing event>" THEN
(SELECT MIN(SES2.ses_DateTimeConnection)
FROM Sessions AS SES2
WHERE SES2.ses_MAC = SES1.ses_MAC
AND SES2.ses_DateTimeConnection > SES1.ses_DateTimeConnection
AND SES2.ses_DateTimeConnection BETWEEN Date('. $startDate .') AND Date('. $endDate .')
)
ELSE SES1.ses_DateTimeDisconnection
END AS ses_DateTimeDisconnectionCorrected
FROM Sessions AS SES1
WHERE (SES1.ses_DateTimeConnection BETWEEN Date('. $startDate .') AND Date('. $endDate .'))
OR (SES1.ses_DateTimeDisconnection BETWEEN Date('. $startDate .') AND Date('. $endDate .'))
OR SES1.ses_StillConnected = 1';
$result = $db->query($SQL);
// arrays of rows
while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
// Event color
if ($row['ses_EventTypeConnection'] == '<missing event>' || $row['ses_EventTypeDisconnection'] == '<missing event>') {
$color = '#f39c12';
} elseif ($row['ses_StillConnected'] == 1 ) {
$color = '#00a659';
} else {
$color = '#0073b7';
}
// tooltip
$tooltip = 'Connection: ' . formatEventDate ($row['ses_DateTimeConnection'], $row['ses_EventTypeConnection']) . chr(13) .
'Disconnection: ' . formatEventDate ($row['ses_DateTimeDisconnection'], $row['ses_EventTypeDisconnection']) . chr(13) .
'IP: ' . $row['ses_IP'];
// Save row data
$tableData[] = array(
'resourceId' => $row['ses_MAC'],
'title' => '',
'start' => formatDateISO ($row['ses_DateTimeConnectionCorrected']),
'end' => formatDateISO ($row['ses_DateTimeDisconnectionCorrected']),
'color' => $color,
'tooltip' => $tooltip,
'className' => 'no-border'
);
}
// Control no rows
if (empty($tableData)) {
$tableData = '';
}
// Return json
echo (json_encode($tableData));
}
?>

View File

@@ -290,7 +290,7 @@
"Events_Tablelenght": "Afficher _MENU_ entrées", "Events_Tablelenght": "Afficher _MENU_ entrées",
"Events_Tablelenght_all": "Tous", "Events_Tablelenght_all": "Tous",
"Events_Title": "Évènements", "Events_Title": "Évènements",
"FakeMAC_hover": "", "FakeMAC_hover": "Autodétecté - indique si l'appareil utilise une fausse adresse MAC (qui commence par FA:CE ou 00:1A), typiquement générée par un plugin qui ne peut pas détecter la vraie adresse MAC, ou en créant un appareil factice.",
"GRAPHQL_PORT_description": "Le numéro de port du serveur GraphQL. Assurez vous sue le port est unique a l'échelle de toutes les applications sur cet hôte et vos instances NetAlertX.", "GRAPHQL_PORT_description": "Le numéro de port du serveur GraphQL. Assurez vous sue le port est unique a l'échelle de toutes les applications sur cet hôte et vos instances NetAlertX.",
"GRAPHQL_PORT_name": "Port GraphQL", "GRAPHQL_PORT_name": "Port GraphQL",
"Gen_Action": "Action", "Gen_Action": "Action",

View File

@@ -290,7 +290,7 @@
"Events_Tablelenght": "Mostra _MENU_ elementi", "Events_Tablelenght": "Mostra _MENU_ elementi",
"Events_Tablelenght_all": "Tutti", "Events_Tablelenght_all": "Tutti",
"Events_Title": "Eventi", "Events_Title": "Eventi",
"FakeMAC_hover": "", "FakeMAC_hover": "Rilevato automaticamente: indica se il dispositivo utilizza un indirizzo MAC FALSO (che inizia con FA:CE o 00:1A), in genere generato da un plugin che non riesce a rilevare il MAC reale o quando si crea un dispositivo fittizio.",
"GRAPHQL_PORT_description": "Il numero di porta del server GraphQL. Assicurati che la porta sia univoca in tutte le tue applicazioni su questo host e nelle istanze di NetAlertX.", "GRAPHQL_PORT_description": "Il numero di porta del server GraphQL. Assicurati che la porta sia univoca in tutte le tue applicazioni su questo host e nelle istanze di NetAlertX.",
"GRAPHQL_PORT_name": "Porta GraphQL", "GRAPHQL_PORT_name": "Porta GraphQL",
"Gen_Action": "Azione", "Gen_Action": "Azione",

View File

@@ -290,7 +290,7 @@
"Events_Tablelenght": "Показати записи _МЕНЮ_", "Events_Tablelenght": "Показати записи _МЕНЮ_",
"Events_Tablelenght_all": "Все", "Events_Tablelenght_all": "Все",
"Events_Title": "Події", "Events_Title": "Події",
"FakeMAC_hover": "", "FakeMAC_hover": "Автоматично виявлено вказує, чи пристрій використовує ПІДРОБНУ MAC-адресу (що починається з FA:CE або 00:1A), зазвичай згенеровану плагіном, який не може визначити справжню MAC-адресу, або під час створення фіктивного пристрою.",
"GRAPHQL_PORT_description": "Номер порту сервера GraphQL. Переконайтеся, що порт є унікальним для всіх ваших програм на цьому хості та екземплярах NetAlertX.", "GRAPHQL_PORT_description": "Номер порту сервера GraphQL. Переконайтеся, що порт є унікальним для всіх ваших програм на цьому хості та екземплярах NetAlertX.",
"GRAPHQL_PORT_name": "Порт GraphQL", "GRAPHQL_PORT_name": "Порт GraphQL",
"Gen_Action": "Дія", "Gen_Action": "Дія",

View File

@@ -510,7 +510,7 @@ def mqtt_start(db):
"group": device["devGroup"], "group": device["devGroup"],
"location": device["devLocation"], "location": device["devLocation"],
"network_parent_mac": device["devParentMAC"], "network_parent_mac": device["devParentMAC"],
"network_parent_name": next((dev["devName"] for dev in devices if dev["devMAC"] == device["devParentMAC"]), "") "network_parent_name": next((dev["devName"] for dev in devices if dev["devMac"] == device["devParentMAC"]), "")
} }
# bulk update device sensors in home assistant # bulk update device sensors in home assistant

View File

@@ -11,7 +11,7 @@ sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from const import logPath # noqa: E402, E261 from const import logPath # noqa: E402, E261
from plugin_helper import Plugin_Objects # noqa: E402, E261 from plugin_helper import Plugin_Objects # noqa: E402, E261
from utils.crypto_utils import string_to_mac_hash # noqa: E402 [flake8 lint suppression] from utils.crypto_utils import string_to_fake_mac # noqa: E402 [flake8 lint suppression]
from logger import mylog, Logger # noqa: E402, E261 from logger import mylog, Logger # noqa: E402, E261
from helper import get_setting_value # noqa: E402, E261 from helper import get_setting_value # noqa: E402, E261
import conf # noqa: E402, E261 import conf # noqa: E402, E261
@@ -120,7 +120,7 @@ def main():
if not mac and fake_mac_enabled: if not mac and fake_mac_enabled:
mylog("verbose", [f"[{pluginName}] Generating FAKE MAC for ip: {ip}"]) mylog("verbose", [f"[{pluginName}] Generating FAKE MAC for ip: {ip}"])
mac = string_to_mac_hash(ip) mac = string_to_fake_mac(ip)
if not mac: if not mac:
# Skip devices without MAC if fake MAC not allowed # Skip devices without MAC if fake MAC not allowed

View File

@@ -75,6 +75,34 @@
} }
] ]
}, },
{
"function": "MODE",
"events": ["run"],
"type": {
"dataType": "string",
"elements": [
{ "elementType": "select", "elementOptions": [], "transformers": [] }
]
},
"default_value": "ping",
"options": [
"ping",
"fping"
],
"localized": ["name", "description"],
"name": [
{
"language_code": "en_us",
"string": "Mode"
}
],
"description": [
{
"language_code": "en_us",
"string": "Selects the ICMP engine to use. <code>ping</code> checks devices individually and works even when the ARP / neighbor cache is empty, but is slower on larger networks. <code>fping</code> scans IP ranges in parallel and is significantly faster, but relies on the system neighbor cache to resolve IP addresses to MAC addresses. For most networks, <code>fping</code> is recommended. The default command arguments <code>ICMP_ARGS</code> are compatible with both modes."
}
]
},
{ {
"function": "CMD", "function": "CMD",
"type": { "type": {
@@ -115,7 +143,7 @@
} }
] ]
}, },
"default_value": "-i 0.5 -c 3 -W 4 -w 5", "default_value": "-i 0.5 -c 3 -w 5",
"options": [], "options": [],
"localized": ["name", "description"], "localized": ["name", "description"],
"name": [ "name": [
@@ -127,7 +155,7 @@
"description": [ "description": [
{ {
"language_code": "en_us", "language_code": "en_us",
"string": "Arguments passed to the <code>ping</code> command. Please be careful modifying these." "string": "Arguments passed to the underlying <code>ping</code> or <code>fping</code> command. The default values are compatible with both modes and work well in most environments. Modify with care, and consult the relevant manual pages if advanced tuning is required."
} }
] ]
}, },
@@ -159,6 +187,41 @@
} }
] ]
}, },
{
"function": "FAKE_MAC",
"type": {
"dataType": "boolean",
"elements": [
{
"elementType": "input",
"elementOptions": [
{
"type": "checkbox"
}
],
"transformers": []
}
]
},
"default_value": false,
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Fake MAC"
}
],
"description": [
{
"language_code": "en_us",
"string": "If enabled and the mode is set to <code>fping</code>, the plugin will also discover new devices not already in the database. Enabling this setting generates a fake MAC address from the IP address to track devices. This may cause inconsistencies if IPs change or devices are re-discovered with a different MAC. Static IPs are recommended. Device type and icon might not be detected correctly, and some plugins may fail if they rely on a valid MAC address. When unchecked, devices without a MAC address are skipped."
}
]
},
{ {
"function": "RUN_SCHD", "function": "RUN_SCHD",
"type": { "type": {

View File

@@ -16,6 +16,7 @@ from logger import mylog, Logger # noqa: E402 [flake8 lint suppression]
from helper import get_setting_value # noqa: E402 [flake8 lint suppression] from helper import get_setting_value # noqa: E402 [flake8 lint suppression]
from const import logPath # noqa: E402 [flake8 lint suppression] from const import logPath # noqa: E402 [flake8 lint suppression]
from models.device_instance import DeviceInstance # noqa: E402 [flake8 lint suppression] from models.device_instance import DeviceInstance # noqa: E402 [flake8 lint suppression]
from utils.crypto_utils import string_to_fake_mac # noqa: E402 [flake8 lint suppression]
import conf # noqa: E402 [flake8 lint suppression] import conf # noqa: E402 [flake8 lint suppression]
from pytz import timezone # noqa: E402 [flake8 lint suppression] from pytz import timezone # noqa: E402 [flake8 lint suppression]
@@ -32,13 +33,39 @@ LOG_FILE = os.path.join(LOG_PATH, f'script.{pluginName}.log')
RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log') RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log')
def parse_scan_subnets(subnets):
"""Extract subnet and interface from SCAN_SUBNETS"""
ranges = []
interfaces = []
for entry in subnets:
parts = entry.split("--interface=")
ranges.append(parts[0].strip())
if len(parts) > 1:
interfaces.append(parts[1].strip())
return ranges, interfaces
def get_device_by_ip(ip, all_devices):
"""Get existing device based on IP"""
for device in all_devices:
if device["devLastIP"] == ip:
return device
return None
def main(): def main():
mylog('verbose', [f'[{pluginName}] In script']) mylog('verbose', [f'[{pluginName}] In script'])
timeout = get_setting_value('ICMP_RUN_TIMEOUT') timeout = get_setting_value('ICMP_RUN_TIMEOUT')
args = get_setting_value('ICMP_ARGS') args = get_setting_value('ICMP_ARGS')
in_regex = get_setting_value('ICMP_IN_REGEX') regex = get_setting_value('ICMP_IN_REGEX')
mode = get_setting_value('ICMP_MODE')
fakeMac = get_setting_value('ICMP_FAKE_MAC')
scan_subnets = get_setting_value("SCAN_SUBNETS")
subnets, interfaces = parse_scan_subnets(scan_subnets)
# Initialize the Plugin obj output file # Initialize the Plugin obj output file
plugin_objects = Plugin_Objects(RESULT_FILE) plugin_objects = Plugin_Objects(RESULT_FILE)
@@ -50,33 +77,13 @@ def main():
all_devices = device_handler.getAll() all_devices = device_handler.getAll()
# Compile the regex for efficiency if it will be used multiple times # Compile the regex for efficiency if it will be used multiple times
regex_pattern = re.compile(in_regex) regex_pattern = re.compile(regex)
# Filter devices based on the regex match if mode == "ping":
filtered_devices = [ plugin_objects = execute_ping(timeout, args, all_devices, regex_pattern, plugin_objects)
device for device in all_devices
if regex_pattern.match(device['devLastIP'])
]
mylog('verbose', [f'[{pluginName}] Devices to PING: {len(filtered_devices)}']) elif mode == "fping":
plugin_objects = execute_fping(timeout, args, all_devices, plugin_objects, subnets, interfaces, fakeMac)
for device in filtered_devices:
is_online, output = execute_scan(device['devLastIP'], timeout, args)
mylog('verbose', [f"[{pluginName}] ip: {device['devLastIP']} is_online: {is_online}"])
if is_online:
plugin_objects.add_object(
# "MAC", "IP", "Name", "Output"
primaryId = device['devMac'],
secondaryId = device['devLastIP'],
watched1 = device['devName'],
watched2 = output.replace('\n', ''),
watched3 = '',
watched4 = '',
extra = '',
foreignKey = device['devMac']
)
plugin_objects.write_result_file() plugin_objects.write_result_file()
@@ -88,27 +95,24 @@ def main():
# =============================================================================== # ===============================================================================
# Execute scan # Execute scan
# =============================================================================== # ===============================================================================
def execute_scan(ip, timeout, args): def execute_ping(timeout, args, all_devices, regex_pattern, plugin_objects):
""" """
Execute the ICMP command on IP. Execute ICMP command on filtered devices.
""" """
icmp_args = ['ping'] + args.split() + [ip] # Filter devices based on the regex match
filtered_devices = [
device for device in all_devices
if regex_pattern.match(device['devLastIP'])
]
# Execute command mylog('verbose', [f'[{pluginName}] Devices to PING: {len(filtered_devices)}'])
output = ""
try: for device in filtered_devices:
# try runnning a subprocess with a forced (timeout) in case the subprocess hangs
output = subprocess.check_output(
icmp_args,
universal_newlines=True,
stderr=subprocess.STDOUT,
timeout=(timeout),
text=True
)
mylog('verbose', [f'[{pluginName}] DEBUG OUTPUT : {output}']) cmd = ["ping"] + args.split() + [device['devLastIP']]
output = ""
# Parse output using case-insensitive regular expressions # Parse output using case-insensitive regular expressions
# Synology-NAS:/# ping -i 0.5 -c 3 -W 8 -w 9 192.168.1.82 # Synology-NAS:/# ping -i 0.5 -c 3 -W 8 -w 9 192.168.1.82
@@ -128,31 +132,115 @@ def execute_scan(ip, timeout, args):
# --- 192.168.1.92 ping statistics --- # --- 192.168.1.92 ping statistics ---
# 3 packets transmitted, 0 packets received, 100% packet loss # 3 packets transmitted, 0 packets received, 100% packet loss
# TODO: parse output and return True if online, False if Offline (100% packet loss, bad address) try:
is_online = True output = subprocess.check_output(
cmd, universal_newlines=True, stderr=subprocess.STDOUT, timeout=timeout, text=True
)
mylog("verbose", [f"[{pluginName}] DEBUG OUTPUT : {output}"])
# Check for 0% packet loss in the output
if re.search(r"0% packet loss", output, re.IGNORECASE):
is_online = True is_online = True
elif re.search(r"bad address", output, re.IGNORECASE): if re.search(r"0% packet loss", output, re.IGNORECASE):
is_online = False is_online = True
elif re.search(r"100% packet loss", output, re.IGNORECASE): elif re.search(r"bad address", output, re.IGNORECASE):
is_online = False is_online = False
elif re.search(r"100% packet loss", output, re.IGNORECASE):
is_online = False
return is_online, output if is_online:
except subprocess.CalledProcessError as e: plugin_objects.add_object(
# An error occurred, handle it # "MAC", "IP", "Name", "Output"
mylog('verbose', [f'[{pluginName}] ⚠ ERROR - check logs']) primaryId = device['devMac'],
mylog('verbose', [f'[{pluginName}]', e.output]) secondaryId = device['devLastIP'],
watched1 = device['devName'],
watched2 = output.replace('\n', ''),
watched3 = '',
watched4 = '',
extra = '',
foreignKey = device['devMac']
)
return False, output mylog('verbose', [f"[{pluginName}] ip: {device['devLastIP']} is_online: {is_online}"])
except subprocess.CalledProcessError as e:
mylog("verbose", [f"[{pluginName}] ⚠ ERROR - check logs"])
mylog("verbose", [f"[{pluginName}]", e.output])
except subprocess.TimeoutExpired:
mylog("verbose", [f"[{pluginName}] TIMEOUT - process terminated"])
return plugin_objects
def execute_fping(timeout, args, all_devices, plugin_objects, subnets, interfaces, fakeMac):
"""
Run fping command and return alive IPs
"""
cmd = ["fping", "-a"]
if interfaces:
cmd += ["-I", ",".join(interfaces)]
# Build a lookup dict once
device_map = {d["devLastIP"]: d for d in all_devices if d.get("devLastIP")}
known_ips = list(device_map.keys())
online_ips = []
cmd += args.split()
cmd += subnets
cmd += known_ips
mylog("verbose", [f"[{pluginName}] fping cmd: {' '.join(cmd)}"])
try:
output = subprocess.check_output(
cmd,
stderr=subprocess.DEVNULL,
timeout=timeout,
text=True
)
online_ips = [line.strip() for line in output.splitlines() if line.strip()]
except subprocess.CalledProcessError:
online_ips = []
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
mylog('verbose', [f'[{pluginName}] TIMEOUT - the process forcefully terminated as timeout reached']) mylog("verbose", [f"[{pluginName}] fping timeout"])
return False, output online_ips = []
return False, output # process all online IPs
for onlineIp in online_ips:
if onlineIp in known_ips:
# use lookup dict instead of looping
device = device_map.get(onlineIp)
if device:
plugin_objects.add_object(
primaryId = device['devMac'],
secondaryId = device['devLastIP'],
watched1 = device['devName'],
watched2 = 'mode:fping',
watched3 = '',
watched4 = '',
extra = '',
foreignKey = device['devMac']
)
else:
mylog("none", [f"[{pluginName}] ERROR reverse device lookup failed unexpectedly for {onlineIp}"])
elif fakeMac:
fakeMacFromIp = string_to_fake_mac(onlineIp)
plugin_objects.add_object(
primaryId = fakeMacFromIp,
secondaryId = onlineIp,
watched1 = "(unknown)",
watched2 = 'mode:fping',
watched3 = '',
watched4 = '',
extra = '',
foreignKey = fakeMacFromIp
)
else:
mylog('verbose', [f"[{pluginName}] Skipping: {onlineIp}, as new IP and ICMP_FAKE_MAC setting not enabled"])
# =============================================================================== # ===============================================================================

View File

@@ -16,7 +16,7 @@ from plugin_helper import Plugin_Objects # noqa: E402 [flake8 lint suppression]
from logger import mylog, Logger # noqa: E402 [flake8 lint suppression] from logger import mylog, Logger # noqa: E402 [flake8 lint suppression]
from helper import get_setting_value # noqa: E402 [flake8 lint suppression] from helper import get_setting_value # noqa: E402 [flake8 lint suppression]
from const import logPath # noqa: E402 [flake8 lint suppression] from const import logPath # noqa: E402 [flake8 lint suppression]
from utils.crypto_utils import string_to_mac_hash # noqa: E402 [flake8 lint suppression] from utils.crypto_utils import string_to_fake_mac # noqa: E402 [flake8 lint suppression]
import conf # noqa: E402 [flake8 lint suppression] import conf # noqa: E402 [flake8 lint suppression]
from pytz import timezone # noqa: E402 [flake8 lint suppression] from pytz import timezone # noqa: E402 [flake8 lint suppression]
@@ -159,7 +159,7 @@ def parse_nmap_xml(xml_output, interface, fakeMac):
if (ip != '' and mac != '') or (ip != '' and fakeMac): if (ip != '' and mac != '') or (ip != '' and fakeMac):
if mac == '' and fakeMac: if mac == '' and fakeMac:
mac = string_to_mac_hash(ip) mac = string_to_fake_mac(ip)
devices_list.append({ devices_list.append({
'name': hostname, 'name': hostname,

View File

@@ -23,7 +23,7 @@ from helper import get_setting_value # noqa: E402 [flake8 lint suppression]
from const import logPath # noqa: E402 [flake8 lint suppression] from const import logPath # noqa: E402 [flake8 lint suppression]
import conf # noqa: E402 [flake8 lint suppression] import conf # noqa: E402 [flake8 lint suppression]
from pytz import timezone # noqa: E402 [flake8 lint suppression] from pytz import timezone # noqa: E402 [flake8 lint suppression]
from utils.crypto_utils import string_to_mac_hash # noqa: E402 [flake8 lint suppression] from utils.crypto_utils import string_to_fake_mac # noqa: E402 [flake8 lint suppression]
# Setup timezone & logger using standard NAX helpers # Setup timezone & logger using standard NAX helpers
conf.tz = timezone(get_setting_value('TIMEZONE')) conf.tz = timezone(get_setting_value('TIMEZONE'))
@@ -228,7 +228,7 @@ def gather_device_entries():
# ensure fake mac if enabled # ensure fake mac if enabled
if PIHOLEAPI_FAKE_MAC and is_mac(tmpMac) is False: if PIHOLEAPI_FAKE_MAC and is_mac(tmpMac) is False:
tmpMac = string_to_mac_hash(ip) tmpMac = string_to_fake_mac(ip)
entries.append({ entries.append({
'mac': tmpMac, 'mac': tmpMac,

View File

@@ -421,12 +421,60 @@ function getDevicesPresence (status) {
$('#tableDevicesBox')[0].className = 'box box-'+ color; $('#tableDevicesBox')[0].className = 'box box-'+ color;
$('#tableDevicesTitle').html (tableTitle); $('#tableDevicesTitle').html (tableTitle);
// Define new datasource URL and reload const protocol = window.location.protocol.replace(':', '');
$('#calendar').fullCalendar ('option', 'resources', 'php/server/devices.php?action=getDevicesListCalendar&status='+ deviceStatus); const host = window.location.hostname;
$('#calendar').fullCalendar ('refetchResources'); const port = getSetting("GRAPHQL_PORT"); // Or Flask server port
const apiToken = getSetting("API_TOKEN");
const apiBase = `${protocol}://${host}:${port}`;
// -----------------------------
// Load Devices as Resources
// -----------------------------
const devicesUrl = `${apiBase}/devices/by-status?status=${deviceStatus}`;
$.ajax({
url: devicesUrl,
method: "GET",
headers: {
"Authorization": `Bearer ${apiToken}`
},
success: function(devices) {
// FullCalendar expects resources array
const resources = devices.map(dev => ({
id: dev.devMac,
title: dev.devName
}));
$('#calendar').fullCalendar('option', 'resources', resources);
$('#calendar').fullCalendar('refetchResources');
}
});
// -----------------------------
// Load Events
// -----------------------------
const eventsUrl = `${apiBase}/sessions/calendar?start=${startDate}&end=${endDate}`;
$('#calendar').fullCalendar('removeEventSources'); $('#calendar').fullCalendar('removeEventSources');
$('#calendar').fullCalendar('addEventSource', { url: `php/server/events.php?period=${period}&start=${startDate}&end=${endDate}&action=getEventsCalendar` }); $('#calendar').fullCalendar('addEventSource', {
url: eventsUrl,
method: "GET",
headers: {
"Authorization": `Bearer ${apiToken}`
},
success: function(response) {
// Flask returns { "sessions": [...] } → FullCalendar needs array
const events = response.sessions || [];
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('renderEvents', events, true);
},
error: function(err) {
console.error('Failed to load events:', err);
}
});
}; };
</script> </script>

View File

@@ -24,8 +24,8 @@ fi
# Install dependencies # Install dependencies
apt-get install -y \ apt-get install -y \
tini snmp ca-certificates curl libwww-perl arp-scan perl apt-utils cron sudo gettext-base \ tini snmp ca-certificates curl libwww-perl arp-scan perl apt-utils cron sudo gettext-base \
nginx-light php php-cgi php-fpm php-sqlite3 php-curl sqlite3 dnsutils net-tools \ nginx-light php php-cgi php-fpm php-sqlite3 php-curl sqlite3 dnsutils net-tools \
python3 python3-dev iproute2 nmap python3-pip zip usbutils traceroute nbtscan avahi-daemon avahi-utils openrc build-essential git python3 python3-dev iproute2 nmap fping python3-pip zip usbutils traceroute nbtscan avahi-daemon avahi-utils openrc build-essential git
# alternate dependencies # alternate dependencies
sudo apt-get install nginx nginx-core mtr php-fpm php8.2-fpm php-cli php8.2 php8.2-sqlite3 -y sudo apt-get install nginx nginx-core mtr php-fpm php8.2-fpm php-cli php8.2 php8.2-sqlite3 -y

View File

@@ -156,7 +156,7 @@ fi
apt-get install -y --no-install-recommends \ apt-get install -y --no-install-recommends \
tini snmp ca-certificates curl libwww-perl arp-scan perl apt-utils cron sudo \ tini snmp ca-certificates curl libwww-perl arp-scan perl apt-utils cron sudo \
php8.4 php8.4-cgi php8.4-fpm php8.4-sqlite3 php8.4-curl sqlite3 dnsutils net-tools mtr \ php8.4 php8.4-cgi php8.4-fpm php8.4-sqlite3 php8.4-curl sqlite3 dnsutils net-tools mtr \
python3 python3-dev iproute2 nmap python3-pip zip usbutils traceroute nbtscan \ python3 python3-dev iproute2 nmap fping python3-pip zip usbutils traceroute nbtscan \
avahi-daemon avahi-utils build-essential git gnupg2 lsb-release \ avahi-daemon avahi-utils build-essential git gnupg2 lsb-release \
debian-archive-keyring python3-venv debian-archive-keyring python3-venv

View File

@@ -62,7 +62,7 @@ apt-get install -y --no-install-recommends \
# Install plugin dependencies # Install plugin dependencies
apt-get install -y --no-install-recommends \ apt-get install -y --no-install-recommends \
dnsutils mtr arp-scan snmp iproute2 nmap zip usbutils traceroute nbtscan avahi-daemon avahi-utils dnsutils mtr arp-scan snmp iproute2 nmap fping zip usbutils traceroute nbtscan avahi-daemon avahi-utils
# nginx-core install nginx and nginx-common as dependencies # nginx-core install nginx and nginx-common as dependencies
apt-get install -y --no-install-recommends \ apt-get install -y --no-install-recommends \

View File

@@ -176,10 +176,10 @@ class DeviceInstance:
if "*" in mac: if "*" in mac:
# Wildcard matching # Wildcard matching
sql_pattern = mac.replace("*", "%") sql_pattern = mac.replace("*", "%")
cur.execute("DELETE FROM Devices WHERE devMAC LIKE ?", (sql_pattern,)) cur.execute("DELETE FROM Devices WHERE devMac LIKE ?", (sql_pattern,))
else: else:
# Exact match # Exact match
cur.execute("DELETE FROM Devices WHERE devMAC = ?", (mac,)) cur.execute("DELETE FROM Devices WHERE devMac = ?", (mac,))
deleted_count += cur.rowcount deleted_count += cur.rowcount
conn.commit() conn.commit()
@@ -191,7 +191,7 @@ class DeviceInstance:
"""Delete devices with empty MAC addresses.""" """Delete devices with empty MAC addresses."""
conn = get_temp_db_connection() conn = get_temp_db_connection()
cur = conn.cursor() cur = conn.cursor()
cur.execute("DELETE FROM Devices WHERE devMAC IS NULL OR devMAC = ''") cur.execute("DELETE FROM Devices WHERE devMac IS NULL OR devMac = ''")
deleted = cur.rowcount deleted = cur.rowcount
conn.commit() conn.commit()
conn.close() conn.close()