diff --git a/CHANGELOG.md b/CHANGELOG.md index f6e6a856..80894c99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ --- develop --- +* docs: Add a NOTICE file and a SPDX `.license` file for every recommendation catalogue, and `copyright`, `license`, `license_url` and `source` fields in each catalogue's JSON. The vendor-derived catalogues are marked as separate works aggregated with the plugin and not licensed under the GPL; the NVIDIA catalogue's Cumulus Linux records are identified as CC BY-NC-SA 4.0 +* change: The Cisco recommendation catalogue (docs/cisco.json.gz) is no longer loaded automatically on install or upgrade; every catalogue is now imported only on request. Records an earlier upgrade loaded are kept +* feature: Add a manually importable Linux pattern recommendation catalogue in docs/linux-wazuh.json.gz with 411 records converted from 315 rules of the Wazuh 4.14.11 ruleset (GPL-2.0), covering core Linux services, mail, network services and databases; contrib/recommendations/extract_wazuh_rules.py converts the rules and decoders, and build_catalogues.py now keeps the regex and program fields +* docs: Add a Recommendation sources and licensing table to the README naming, for every bundled catalogue, its vendor, source, copyright holder and license, and how it was obtained * feature: Add pattern recommendations. A recommendation may carry a PCRE pattern (`regex`) and an optional syslog program (`program`, which may start or end with a `*` wildcard); it is then matched by the pattern instead of its identifier, after identifier matches, and applies to every sender except a Cacti device recognised as a different vendor. Patterns are validated on save and import (they must compile, be at most 1,024 characters and not match an empty message), run under a reduced PCRE backtracking limit, and are loaded once per request (at most 2,000, within PHP's compiled-pattern cache). Flagging a page of messages runs at most 200,000 pattern evaluations, and a failed pattern load reports that recommendations could not be loaded. The Recommendations page gains Pattern and Program fields, a Pattern column and a Match By filter; import and export carry the new fields only for records that use them. Upgrades add the `regex` and `program` columns to `syslog_recommendations` * feature: Add a manually importable Linux recommendation catalogue in docs/linux.json.gz with the 102 entries of systemd's journal message catalog (v262.2), keyed on the journal MESSAGE_ID that rsyslog or syslog-ng forwarders can append to the message; contrib/recommendations/extract_systemd_catalog.py converts the catalog for build_catalogues.py, and devices whose sysDescr or template mentions Linux but no network vendor are now recognised as Linux for recommendation scoping * dev: Sync js/cards.js with the Cacti core Card API controller (Cacti/cacti#8928): defer a card refresh until an in-flight grow or shrink settles so it no longer reverts the resize, target drops by row start so a taller card no longer captures a drop in a later row and a dragged card alone in its row no longer jumps up a row, and bind the add-card control once so a re-initialised grid receives added cards diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..5b5d09e7 --- /dev/null +++ b/NOTICE @@ -0,0 +1,56 @@ +Cacti Syslog Plugin - licensing notice +====================================== + +The Syslog plugin's code is Copyright (C) 2004-2026 The Cacti Group and is +licensed under the GNU General Public License, version 2 or (at your option) +any later version. See LICENSE. + +Recommendation catalogues (docs/*.json.gz) +------------------------------------------ + +The recommendation catalogues are data files that the plugin can import on +request. None is loaded automatically. Each catalogue has a .license +file next to it with its SPDX copyright and license tags, and the same +copyright, license, license_url and source fields at the top of its JSON +document. + +Openly licensed catalogues, distributed under their own licenses: + + docs/linux.json.gz systemd journal message catalog. + Copyright systemd contributors. + LGPL-2.1-or-later. + docs/linux-wazuh.json.gz Converted from the Wazuh ruleset. + Copyright Wazuh, Inc.; portions Copyright + Trend Micro, Inc. (OSSEC). GPL-2.0-only, so the + "or later" option of the plugin's license does + not extend to this file. + +Vendor-derived catalogues: + + docs/arista.json.gz, docs/cisco.json.gz, docs/dell.json.gz, + docs/fortinet.json.gz, docs/hpe.json.gz, docs/huawei.json.gz, + docs/juniper.json.gz, docs/mikrotik.json.gz, docs/nokia.json.gz, + docs/nvidia.json.gz, docs/paloalto.json.gz + +These catalogues are separate works aggregated with the Syslog plugin. They are +not part of the plugin and are not licensed under the GNU General Public +License. Their content is condensed from the vendors' public documentation, +which remains Copyright its respective owners, all rights reserved, and is +subject to each owner's terms. Their .license files name those terms with +LicenseRef- identifiers (for example LicenseRef-Cisco-Terms-of-Use); these are +references to the vendor's terms of use, not open licenses. The terms are +linked from the "Recommendation sources and licensing" section of README.md +and in each file's license_url field. The catalogues are provided for +reference and interoperability with the vendors' products. Check the vendor's +terms before redistributing a catalogue outside your organisation. + +docs/nvidia.json.gz is partly openly licensed: its Cumulus Linux switchd and +FRRouting records come from NVIDIA networking documentation licensed under +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +(CC-BY-NC-SA-4.0, https://docs.nvidia.com/networking-ethernet-software/license/), +which permits non-commercial sharing with attribution under the same license. +That license is not compatible with the GPL. Its Xid and SXid records come from +documentation under the NVIDIA Terms of Service. + +Trademarks are the property of their respective owners. This notice describes +where the data comes from and is not legal advice. diff --git a/README.md b/README.md index 7f1ea22f..31ef76c6 100644 --- a/README.md +++ b/README.md @@ -857,6 +857,9 @@ matched by that regular expression instead, and its identifier only names it checks stop after 200,000 pattern evaluations, so a very large page (such as Show All) cannot stall the request; rows beyond that point show only identifier matches, and opening a message still lists its pattern matches. +* A pattern recommendation with the same vendor, message and explanation as one + already matched is skipped, so a recommendation split into several patterns + (for example one per program) is listed once. ```json { @@ -877,16 +880,13 @@ Syslog Administration realm). You can add, edit, and delete records, filter by vendor, severity and whether they match by identifier or pattern, and import or export them as JSON. A recommendation is identified by its vendor and identifier. -The bundled Cisco data in `docs/cisco.json.gz` is loaded once, the first time -the plugin is installed or upgraded to 5.0 (see -[Important: Upgrading the Plugin](#important-upgrading-the-plugin); the page -returns Permission Denied until the upgrade has run). It is read with PHP's zlib extension; -without it the load is skipped and a warning is logged. Records that already exist -are never overwritten and records you delete are not restored by later upgrades. -To reload it manually, import `docs/cisco.json.gz` from the Recommendations page -and choose to keep existing recommendations. This replaces the former -`docs/recommendations.sql.gz` SQL seed without changing its one-time seed flag. -The Cisco catalogue retains the CEMDB/php-syslog-ng data and field values. +No catalogue is loaded automatically. Import the ones you need from the +Recommendations page; see [Recommendation sources and licensing](#recommendation-sources-and-licensing) +for the terms that cover each file. Before this change, `docs/cisco.json.gz` +was loaded once when the plugin was installed or upgraded to 5.0. Records loaded +that way are kept, and you can delete them on the Recommendations page (filter +by vendor Cisco and use the Delete action). The Cisco catalogue retains the +CEMDB/php-syslog-ng data and field values. A curated, manually importable Juniper EX Series catalogue is available in `docs/juniper.json.gz`. Its 14 ESWD records are based on Juniper's System Log @@ -915,6 +915,7 @@ lists the source documents, versions and retrieval dates of each file, and | `docs/paloalto.json.gz` | Palo Alto Networks | 364 | PAN-OS System log event IDs from the Syslog Severity Reference, such as `tunnel-status-down`. Generic event IDs (`general`, `auth`) and event IDs that are ordinary networking phrases other vendors also log (`link-down`, `admin-down`, `auth-fail`, `lacp-up`) are excluded. Few records have a recommended action. | | `docs/mikrotik.json.gz` | MikroTik | 11 | RouterOS has no message IDs and MikroTik publishes no message catalogue; only documented messages that carry a distinctive word are included (for example `hashtype`, `auto-initialization`, `hw-limit`, `bpdu-guard`, `CTSYNC`, `deassigned`). | | `docs/linux.json.gz` | Linux | 102 | systemd's journal message catalog (systemd v262.2), keyed on the 32-digit hexadecimal journal `MESSAGE_ID`, such as `be02cf6855d2428ba40df7e9d022f03d` for a failed unit start. Covers units, PID 1, journald, logind, core dumps, the OOM killer, shutdown and time changes. Only matches when the forwarder appends the ID; see [Linux and systemd message IDs](#linux-and-systemd-message-ids). | +| `docs/linux-wazuh.json.gz` | Linux | 411 | [Pattern recommendations](#pattern-recommendations) converted from the Wazuh 4.14.11 ruleset: core Linux (syslog, kernel, sshd, PAM, su, sudo, systemd, auditd, AppArmor, firewalld, Docker, USB), mail (Postfix, Sendmail, Exim, Dovecot, Courier and others), network services (BIND, Unbound, FTP servers, Samba, Apache, nginx, Squid, OpenVPN and others) and databases and applications (MySQL, MariaDB, PostgreSQL, MongoDB, Redis, ClamAV, Puppet, FreeIPA). Matched by message text and program, so no forwarder change is needed. Explanations are Wazuh's one-line rule descriptions with its classification; there are no recommended actions. | Numeric identifiers, such as HPE event IDs, Fortinet log IDs and FRRouting error codes, only match messages from a Cacti device whose vendor is recognised @@ -1007,6 +1008,54 @@ reason, for example `SYSLOG WARNING: Recommendation import rejected record 12 (identifier 'LINK UPDOWN'): the identifier contains spaces or line breaks`, followed by a one-line summary of the whole import. +### Recommendation sources and licensing + +The table below lists every recommendation catalogue in `docs/` with the vendor +it applies to and where its records come from. **Copyright and license** names +who owns the source material and the terms it is published under. **How it was +obtained** summarises how the records were produced. + +Two catalogues come from openly licensed sources: the systemd catalogue +(LGPL-2.1-or-later) and the Wazuh-derived catalogue (GPL-2.0 only, so the +plugin's "or later" option does not extend to that file). Those records keep +their source's license and copyright notices. All the others are condensed from +vendors' public documentation, which remains the copyright of the vendor under +the website terms linked below. They are **not covered by this plugin's GPL**: +the plugin's license grant applies to its code and to its openly licensed data, +not to vendor-derived catalogues. Those records are short summaries that link +back to the vendor's page in their `reference` field, and the vendor's own +documentation is the authoritative text. Check the linked terms before you +redistribute a catalogue outside your organisation. No catalogue is loaded +automatically; each is imported only when an administrator chooses to. + +Every catalogue has a `.license` file next to it (for example +`docs/linux-wazuh.json.gz.license`) with SPDX copyright and license tags, and +the same information is in the `copyright`, `license`, `license_url` and +`source` fields at the top of its JSON document. Vendor terms are named with +`LicenseRef-` identifiers, such as `LicenseRef-Cisco-Terms-of-Use`; they refer +to the vendor's terms of use and are not open licenses. The [NOTICE](NOTICE) +file summarises the licensing of the whole plugin and states that the +vendor-derived catalogues are separate works aggregated with it, not part of +the plugin. This section describes where the data comes from; it is not legal +advice. Source documents, versions and retrieval dates are listed in +[RECOMMENDATION_SOURCES.md](docs/RECOMMENDATION_SOURCES.md). + +| Vendor | File | Source | Copyright and license | How it was obtained | +|--------|------|--------|-----------------------|---------------------| +| Arista | `docs/arista.json.gz` | EOS System Message Guide (EOS 4.15, 2015) | © Arista Networks, Inc.; proprietary documentation, [Arista Terms of Use](https://www.arista.com/en/terms-of-use) | Extracted from Internet Archive copies of the public EOS 4.15 System Message Guide PDF. | +| Cisco | `docs/cisco.json.gz` | Cisco Error Message Database (CEMDB) | © Cisco and/or its affiliates; proprietary documentation, [Cisco Terms of Use](https://www.cisco.com/c/en/us/about/legal/terms-conditions.html) and [Copyright Use Policies](https://www.cisco.com/c/en/us/about/brand-center/copyright-use.html). The data was distributed with the GPL-2.0 php-syslog-ng project. | Converted from the CEMDB data shipped with php-syslog-ng; no longer loaded automatically. | +| Dell | `docs/dell.json.gz` | PowerEdge Error and Event Messages Reference (EEMI), SmartFabric OS10 System Log Message Reference, OS9 configuration guide | © Dell Inc.; proprietary documentation, [Dell Terms of Use](https://www.dell.com/en-us/legal/lp/site-terms-of-use) | Extracted from Dell's public EEMI guide and OS10 and OS9 documentation pages. | +| Fortinet | `docs/fortinet.json.gz` | FortiOS 7.6.8 Log Message Reference | © Fortinet, Inc.; proprietary documentation, [Fortinet Legal, Limited License](https://www.fortinet.com/corporate/about-us/legal) | Generated from the public FortiOS Log Message Reference pages; explanations are built from the documented message, type and level. | +| HPE | `docs/hpe.json.gz` | Comware 5 and 7 System Log Messages References, AOS-CX 10.17 and ArubaOS-Switch 16.10 Event Log Message References | © Hewlett Packard Enterprise Development LP; proprietary documentation, [HPE Terms of Use](https://www.hpe.com/us/en/about/legal/terms-of-use.html) | Extracted from public HPE and Aruba log message reference guides on support.hpe.com. | +| Huawei | `docs/huawei.json.gz` | CloudEngine and S-series (VRP5 and VRP8) Log References | © Huawei Technologies Co., Ltd.; proprietary documentation, [Huawei Terms of Use](https://www.huawei.com/en/legal) | Extracted from Huawei's public log references through its regional documentation mirror. | +| Juniper | `docs/juniper.json.gz` | Juniper System Log Explorer (EX Series `ESWD` messages) | © Juniper Networks, Inc.; proprietary documentation, [Juniper Legal Notices](https://www.juniper.net/us/en/legal-notices.html) | Hand-curated from 14 EX Series entries in Juniper's public System Log Explorer. | +| Linux | `docs/linux.json.gz` | systemd journal message catalog (systemd v262.2) | systemd contributors; open source, [LGPL-2.1-or-later](https://github.com/systemd/systemd/blob/v262.2/catalog/systemd.catalog.in) | Converted from systemd's `catalog/systemd.catalog.in` with `contrib/recommendations/extract_systemd_catalog.py`. | +| Linux | `docs/linux-wazuh.json.gz` | Wazuh ruleset 4.14.11 (rules and decoders, based on OSSEC) | © Wazuh Inc., portions © Trend Micro Inc.; open source, [GPL-2.0](https://github.com/wazuh/wazuh/blob/v4.14.11/LICENSE) | Converted from the Wazuh rule and decoder XML with `contrib/recommendations/extract_wazuh_rules.py`. | +| MikroTik | `docs/mikrotik.json.gz` | RouterOS documentation pages on help.mikrotik.com | MikroTik; no license or terms are stated for the documentation | Hand-picked from messages documented on public RouterOS help pages. | +| Nokia | `docs/nokia.json.gz` | SR OS 25.10 Log Events Guide | © Nokia; proprietary documentation, [Nokia Terms of Use](https://www.nokia.com/notices/terms/) | Extracted from the public SR OS Log Events Guide HTML pages. | +| NVIDIA | `docs/nvidia.json.gz` | Cumulus Linux 5.18 switchd and FRRouting Log Message References, Xid errors, Fabric Manager SXid errors | © NVIDIA Corporation & affiliates. The Cumulus Linux switchd and FRRouting records come from NVIDIA networking documentation licensed [CC BY-NC-SA 4.0](https://docs.nvidia.com/networking-ethernet-software/license/) (non-commercial sharing with attribution, under the same license; not GPL-compatible). The Xid and SXid records come from documentation under the [NVIDIA Terms of Service](https://www.nvidia.com/en-us/about-nvidia/terms-of-service/). The FRRouting `[EC nnnnnnnn]` code numbers are defined by the GPL-2.0-or-later FRRouting software. | Extracted from NVIDIA's public Cumulus Linux, Xid and Fabric Manager documentation. | +| Palo Alto Networks | `docs/paloalto.json.gz` | PAN-OS System Log Reference, System Log Fields and selected Knowledge Base articles | © Palo Alto Networks, Inc.; proprietary documentation, [Palo Alto Networks Terms of Use](https://www.paloaltonetworks.com/legal-notices/terms-of-use) | Extracted from the public PAN-OS System Log Reference; most explanations are generated from the documented message and severity. | + ## Settings The settings are under Settings > Syslog. Selected names and defaults: diff --git a/contrib/recommendations/build_catalogues.py b/contrib/recommendations/build_catalogues.py index 9e42fdeb..86545fba 100755 --- a/contrib/recommendations/build_catalogues.py +++ b/contrib/recommendations/build_catalogues.py @@ -22,9 +22,17 @@ the plugin's docs/ directory. Usage: build_catalogues.py VENDOR < extracted/.json - VENDOR is one of: arista dell fortinet hpe huawei linux mikrotik nokia nvidia paloalto + VENDOR is one of: arista cisco dell fortinet hpe huawei juniper linux linux-wazuh mikrotik nokia nvidia + paloalto -For linux, the extracted JSON comes from extract_systemd_catalog.py. +For linux, the extracted JSON comes from extract_systemd_catalog.py; for +linux-wazuh, from extract_wazuh_rules.py. cisco and juniper have no extractor; +refresh their licensing metadata without touching their records with +build_catalogues.py --metadata-only cisco (it reads docs/cisco.json.gz itself). + +Each build also writes docs/.json.gz.license with SPDX copyright and +license tags, and puts the same copyright, license, license_url and source in +the JSON document, from LICENSING below. """ import gzip @@ -33,15 +41,56 @@ import os import sys +# Who owns each catalogue's source material and under which terms. LicenseRef- +# identifiers name vendor terms of use; they are not open licenses (see NOTICE). +LICENSING = { + 'arista': ('Arista Networks, Inc.', 'LicenseRef-Arista-Terms-of-Use', + 'https://www.arista.com/en/terms-of-use', 'Arista EOS System Message Guide (EOS 4.15)'), + 'cisco': ('Cisco Systems, Inc. and/or its affiliates', 'LicenseRef-Cisco-Terms-of-Use', + 'https://www.cisco.com/c/en/us/about/legal/terms-conditions.html', + 'Cisco Error Message Database (CEMDB), as distributed with php-syslog-ng'), + 'dell': ('Dell Inc. or its subsidiaries', 'LicenseRef-Dell-Terms-of-Use', + 'https://www.dell.com/en-us/legal/lp/site-terms-of-use', + 'Dell PowerEdge EEMI guide, SmartFabric OS10 System Log Message Reference, OS9 configuration guide'), + 'fortinet': ('Fortinet, Inc.', 'LicenseRef-Fortinet-Terms-of-Use', + 'https://www.fortinet.com/corporate/about-us/legal', 'FortiOS 7.6.8 Log Message Reference'), + 'hpe': ('Hewlett Packard Enterprise Development LP', 'LicenseRef-HPE-Terms-of-Use', + 'https://www.hpe.com/us/en/about/legal/terms-of-use.html', + 'HPE Comware, AOS-CX and ArubaOS-Switch log message references'), + 'huawei': ('Huawei Technologies Co., Ltd.', 'LicenseRef-Huawei-Terms-of-Use', + 'https://www.huawei.com/en/legal', 'Huawei CloudEngine and S-series Log References'), + 'juniper': ('Juniper Networks, Inc.', 'LicenseRef-Juniper-Terms-of-Use', + 'https://www.juniper.net/us/en/legal-notices.html', 'Juniper System Log Explorer'), + 'linux': ('systemd contributors', 'LGPL-2.1-or-later', + 'https://github.com/systemd/systemd/blob/v262.2/LICENSE.LGPL2.1', + 'https://github.com/systemd/systemd/blob/v262.2/catalog/systemd.catalog.in'), + 'linux-wazuh': ('Wazuh, Inc.; Trend Micro, Inc. (OSSEC)', 'GPL-2.0-only', + 'https://github.com/wazuh/wazuh/blob/v4.14.11/LICENSE', + 'https://github.com/wazuh/wazuh/tree/v4.14.11/ruleset'), + 'mikrotik': ('SIA Mikrotikls (MikroTik)', 'LicenseRef-MikroTik-Documentation', + 'https://help.mikrotik.com/docs/', 'MikroTik RouterOS documentation (help.mikrotik.com)'), + 'nokia': ('Nokia', 'LicenseRef-Nokia-Terms-of-Use', 'https://www.nokia.com/notices/terms/', + 'Nokia SR OS 25.10 Log Events Guide'), + 'nvidia': ('NVIDIA Corporation & affiliates', 'CC-BY-NC-SA-4.0 AND LicenseRef-NVIDIA-Terms-of-Service', + 'https://docs.nvidia.com/networking-ethernet-software/license/ (Cumulus Linux switchd and FRRouting ' + 'records); https://www.nvidia.com/en-us/about-nvidia/terms-of-service/ (Xid and SXid records)', + 'NVIDIA Cumulus Linux 5.18 log message references, Xid and Fabric Manager documentation'), + 'paloalto': ('Palo Alto Networks, Inc.', 'LicenseRef-PaloAltoNetworks-Terms-of-Use', + 'https://www.paloaltonetworks.com/legal-notices/terms-of-use', + 'PAN-OS System Log Reference and Knowledge Base articles'), +} + # Output names are taken from this table, never from the command line. -VENDORS = {name: name for name in - ('arista', 'dell', 'fortinet', 'hpe', 'huawei', 'linux', 'mikrotik', 'nokia', 'nvidia', 'paloalto')} +VENDORS = {name: name for name in LICENSING} DOCS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'docs') FIELDS = ['vendor', 'identifier', 'component', 'severity', 'message', 'explanation', 'recommended_action', 'reference'] +# Pattern record fields, kept only when set. +OPTIONAL_FIELDS = ['regex', 'program'] + # Identifiers that are ordinary words or protocol terms other vendors also log # as a single token; they would show this vendor's advice for unrelated messages. EXCLUDE = { @@ -80,9 +129,20 @@ def build(vendor, source): continue seen.add(key) - out.append({field: record.get(field, None if field == 'severity' else '') for field in FIELDS}) + record_out = {field: record.get(field, None if field == 'severity' else '') for field in FIELDS} + record_out.update({field: record[field] for field in OPTIONAL_FIELDS if record.get(field)}) + out.append(record_out) + + write(vendor, out) - text = json.dumps({'format': 'syslog-recommendations', 'version': 1, 'recommendations': out}, + print('%s: kept %d, no text %d, excluded %d, duplicate %d' % (vendor, len(out), empty, excluded, duplicate)) + + +def write(vendor, records): + """Write the catalogue with its licensing metadata, and its .license file.""" + copyright, license, license_url, origin = LICENSING[vendor] + text = json.dumps({'format': 'syslog-recommendations', 'version': 1, 'copyright': copyright, 'license': license, + 'license_url': license_url, 'source': origin, 'recommendations': records}, indent=2, ensure_ascii=False) + '\n' with open(os.path.join(DOCS_DIR, vendor + '.json.gz'), 'wb') as fh: @@ -90,17 +150,26 @@ def build(vendor, source): with gzip.GzipFile(filename='', mode='wb', fileobj=fh, compresslevel=9, mtime=0) as gz: gz.write(text.encode('utf-8')) - print('%s: kept %d, no text %d, excluded %d, duplicate %d' % (vendor, len(out), empty, excluded, duplicate)) + with open(os.path.join(DOCS_DIR, vendor + '.json.gz.license'), 'w', encoding='utf-8') as fh: + fh.write('SPDX-FileCopyrightText: %s\nSPDX-License-Identifier: %s\n' % (copyright, license)) def main(argv): - vendor = VENDORS.get(argv[1]) if len(argv) == 2 else None + metadata_only = len(argv) == 3 and argv[1] == '--metadata-only' + vendor = VENDORS.get(argv[-1]) if len(argv) == 2 or metadata_only else None if vendor is None: sys.stderr.write(__doc__) return 2 - build(vendor, io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')) + if metadata_only: + # Keep the shipped records exactly; only the licensing fields change. + with gzip.open(os.path.join(DOCS_DIR, vendor + '.json.gz'), 'rt', encoding='utf-8') as fh: + records = json.load(fh)['recommendations'] + write(vendor, records) + print('%s: metadata refreshed, %d records unchanged' % (vendor, len(records))) + else: + build(vendor, io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')) return 0 diff --git a/contrib/recommendations/extract_wazuh_rules.py b/contrib/recommendations/extract_wazuh_rules.py new file mode 100755 index 00000000..6b4fa650 --- /dev/null +++ b/contrib/recommendations/extract_wazuh_rules.py @@ -0,0 +1,542 @@ +#!/usr/bin/env python3 +# +-------------------------------------------------------------------------+ +# | Copyright (C) 2004-2026 The Cacti Group | +# | | +# | This program is free software; you can redistribute it and/or | +# | modify it under the terms of the GNU General Public License | +# | as published by the Free Software Foundation; either version 2 | +# | of the License, or (at your option) any later version. | +# | | +# | This program is distributed in the hope that it will be useful, | +# | but WITHOUT ANY WARRANTY; without even the implied warranty of | +# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +# | GNU General Public License for more details. | +# +-------------------------------------------------------------------------+ +"""Convert Wazuh ruleset rules into syslog-recommendations pattern records. + +Reads the rule and decoder XML of a Wazuh release (ruleset/rules and +ruleset/decoders, GPL-2.0) and writes, on standard output, a +syslog-recommendations document whose records are pattern records: the +rule's own / conditions and those it inherits through if_sid +and decoded_as become one PCRE pattern, and the program named by the rule +or its decoder becomes the record's program. The output is the input of +build_catalogues.py linux-wazuh. + +Only rules that can be evaluated on a syslog message alone are converted. +Skipped: level 0 rules, correlation rules (frequency, if_matched_*, same_*, +different_*), rules that test fields a Wazuh decoder extracted (srcip, user, +field, ...), rules that inherit through if_group or if_level, rules without a +message condition, and the generic rules listed in EXCLUDE. Records are +ordered program-bound first, then by severity, because the plugin tries +pattern records in import order. + +Usage: extract_wazuh_rules.py TAG RULESET_DIR > linux-wazuh.json + RULESET_DIR is the release's ruleset directory (with rules/ and decoders/). +""" + +import collections +import json +import os +import re +import sys +import xml.etree.ElementTree as ET + +# The rule files converted, by group. +GROUPS = { + 'Core Linux': ['0020-syslog_rules.xml', '0085-pam_rules.xml', '0095-sshd_rules.xml', '0285-systemd_rules.xml', + '0290-firewalld_rules.xml', '0305-dropbear_rules.xml', '0315-apparmor_rules.xml', + '0365-auditd_rules.xml', '0375-usb_rules.xml', '0455-docker_rules.xml'], + 'Mail': ['0025-sendmail_rules.xml', '0030-postfix_rules.xml', '0035-spamd_rules.xml', '0040-imapd_rules.xml', + '0045-mailscanner_rules.xml', '0055-courier_rules.xml', '0155-dovecot_rules.xml', + '0160-vmpop3d_rules.xml', '0165-vpopmail_rules.xml', '0325-opensmtpd_rules.xml', '0515-exim_rules.xml'], + 'Network services': ['0090-telnetd_rules.xml', '0115-arpwatch_rules.xml', '0170-ftpd_rules.xml', + '0175-proftpd_rules.xml', '0180-pure-ftpd_rules.xml', '0185-vsftpd_rules.xml', + '0195-named_rules.xml', '0200-smbd_rules.xml', '0205-racoon_rules.xml', + '0250-apache_rules.xml', '0260-nginx_rules.xml', '0275-squid_rules.xml', + '0335-unbound_rules.xml', '0400-openvpn_rules.xml'], + 'Databases and applications': ['0295-mysql_rules.xml', '0300-postgresql_rules.xml', '0320-clam_av_rules.xml', + '0340-puppet_rules.xml', '0380-redis_rules.xml', '0420-freeipa_rules.xml', + '0450-mongodb_rules.xml', '0535-mariadb_rules.xml'], +} + +# Conditions on values a Wazuh decoder extracted, or on other events; a +# syslog message alone cannot be checked against them. +UNSUPPORTED = { + 'if_group', 'if_level', 'if_matched_sid', 'if_matched_group', 'if_fts', 'same_source_ip', 'same_srcip', + 'same_user', 'same_id', 'same_location', 'same_srcport', 'same_dstport', 'same_protocol', 'same_action', + 'same_dstip', 'same_url', 'same_field', 'different_srcip', 'different_url', 'different_srcgeoip', + 'different_field', 'notsame_source_ip', 'notsame_user', 'notsame_id', 'notsame_field', 'srcip', 'dstip', + 'srcport', 'dstport', 'user', 'srcuser', 'dstuser', 'url', 'id', 'action', 'status', 'protocol', + 'system_name', 'extra_data', 'hostname', 'data', 'location', 'field', 'list', 'srcgeoip', 'dstgeoip', + 'time', 'weekday', 'category', 'check_diff', 'mitre_technique', 'global_frequency', +} + +OSREGEX_CLASS = { + 'w': '[A-Za-z0-9@_-]', 'W': '[^A-Za-z0-9@_-]', 'd': '[0-9]', 'D': '[^0-9]', 's': ' ', 'S': '[^ ]', + 't': '\\t', 'p': '[()*+,.:;<=>?\\[\\]!"\'#$%&|{}-]', '.': '.', +} + +SEVERITY_BY_LEVEL = [(12, 2), (10, 3), (7, 4), (4, 5), (1, 6)] + +# The longest pattern the plugin imports. +MAX_PATTERN_LENGTH = 1024 + +# Rules too generic to explain anything; they would match most error messages. +EXCLUDE = { + '1002': 'matches any message containing a common word such as error, failed or denied', +} + + +def read_xml(base, name): + # Only read files directly inside the ruleset directory being converted. + base = os.path.realpath(base) + path = os.path.realpath(os.path.join(base, os.path.basename(name))) + + if os.path.dirname(path) != base or not path.endswith('.xml'): + raise ValueError('refusing to read %r outside %r' % (name, base)) + + with open(path, encoding='utf-8', errors='replace') as fh: + text = fh.read() + + # The files hold several top-level elements; wrap them so they parse. + body = re.sub(r'<\?xml[^>]*\?>', '', text) + body = re.sub(r'', '', body, flags=re.S) + body = re.sub(r'&(?!(amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);)', '&', body) + body = re.sub(r'<(?![A-Za-z/!?])', '<', body) + + return text, ET.fromstring('' + body + '') + + +def pcre_literal(text): + return re.sub(r'([\\^$.|?*+()\[\]{}/#\s-])', lambda m: '\\' + m.group(1) if m.group(1) != ' ' else ' ', text) + + +def split_alternatives(text): + """Split on | that is not escaped with a backslash.""" + out, current, i = [], '', 0 + + while i < len(text): + if text[i] == '\\' and i + 1 < len(text): + current += text[i:i + 2] + i += 2 + continue + + if text[i] == '|': + out.append(current) + current = '' + else: + current += text[i] + i += 1 + + out.append(current) + + return out + + +def osmatch_to_pcre(text): + alternatives = [] + + for alt in text.split('|'): + start = alt.startswith('^') + end = alt.endswith('$') and len(alt) > (1 if start else 0) + core = alt[1 if start else 0:len(alt) - (1 if end else 0)] + alternatives.append(('^' if start else '') + pcre_literal(core) + ('$' if end else '')) + + return '(?i)(?:' + '|'.join(alternatives) + ')' + + +def osregex_to_pcre(text): + alternatives = [] + + for alt in split_alternatives(text): + out, i = '', 0 + + if alt.startswith('^'): + out, i = '^', 1 + + while i < len(alt): + c = alt[i] + + if c == '\\' and i + 1 < len(alt): + n = alt[i + 1] + i += 2 + + if n in OSREGEX_CLASS: + out += OSREGEX_CLASS[n] + + if i < len(alt) and alt[i] in '+*': + out += alt[i] + i += 1 + else: + out += pcre_literal(n) + continue + + if c == '$' and i == len(alt) - 1: + out += '$' + elif c in '()': + out += '(?:' if c == '(' else ')' + else: + out += pcre_literal(c) + i += 1 + + alternatives.append(out) + + return '(?i)(?:' + '|'.join(alternatives) + ')' + + +def expression(text, kind): + if kind == 'pcre2': + return '(?:' + text + ')' + + return osregex_to_pcre(text) if kind == 'osregex' else osmatch_to_pcre(text) + + +def program_names(text): + """The program globs an osmatch program_name accepts, or None when it is not a plain list. + + ^name$ is exact, ^name a prefix (name*), name$ a suffix (*name) and a bare + name matches anywhere (*name*), as OS_Match does. + """ + names = [] + + for alt in text.split('|'): + alt = alt.strip() + start, end = alt.startswith('^'), alt.endswith('$') + name = alt[1 if start else 0:len(alt) - (1 if end else 0)] + + if not re.fullmatch(r'[A-Za-z0-9_.@/-]+', name): + return None + names.append(('' if start else '*') + name + ('' if end else '*')) + + return names + + +def collect_condition(element, tag, default_kind): + """A rule's or decoder's condition of one tag: concatenated text and the last label's attributes.""" + labels = element.findall(tag) + + if not labels: + return None + + text = ''.join((label.text or '') for label in labels) + kind = labels[-1].get('type', default_kind) + negate = labels[-1].get('negate', 'no') == 'yes' + + if kind == 'osmatch' and text.startswith('!'): + text, negate = text[1:], not negate + + return {'text': text, 'kind': kind, 'negate': negate} + + +class Ruleset: + def __init__(self, root): + self.root = root + self.rules = {} + self.vars = {} + self.decoders = collections.defaultdict(list) + self.children = collections.defaultdict(list) + self.text = {} + + for name in sorted(os.listdir(os.path.join(root, 'rules'))): + if not name.endswith('.xml'): + continue + text, tree = read_xml(os.path.join(root, 'rules'), name) + self.text[name] = text + + for var in tree.iter('var'): + self.vars[var.get('name')] = (var.text or '').strip() + + for rule in tree.iter('rule'): + self.rules[rule.get('id')] = (name, rule) + + for name in sorted(os.listdir(os.path.join(root, 'decoders'))): + if not name.endswith('.xml'): + continue + _, tree = read_xml(os.path.join(root, 'decoders'), name) + + for decoder in tree.iter('decoder'): + if decoder.find('parent') is None: + self.decoders[decoder.get('name')].append(decoder) + else: + self.children[decoder.get('name')].append(decoder) + + def expand(self, text): + for name in sorted(self.vars, key=len, reverse=True): + text = re.sub(r'(?= minimum: + return value + + return None + + +def line_of(text, rule_id): + index = text.find('= 0 else None + + +def explanation(rule, rule_id, level, group): + # Wazuh concatenates a rule's elements into one description. + description = ''.join(d.text or '' for d in rule.findall('description')).strip() + description = re.sub(r'\$\((\w+)\)', r'[\1]', description) + parts = [description if description.endswith('.') else description + '.'] + info = [i.text.strip() for i in rule.findall('info') if (i.get('type') or 'text') == 'text' and (i.text or '').strip()] + + if info: + parts.append(' '.join(info)) + + groups = [g for g in re.split(r'[,\s]+', ','.join((g.text or '') for g in rule.findall('group'))) if g and not re.match( + r'(pci_dss|gdpr|hipaa|nist_800_53|tsc|gpg13)_', g)] + mitre = [m.text.strip() for m in rule.iter('id') if m.text and re.match(r'T\d{4}', m.text.strip())] + detail = 'Wazuh rule %s (%s, level %d)' % (rule_id, group, level) + + if groups: + detail += ', groups: ' + ', '.join(groups) + + if mitre: + detail += ', MITRE ATT&CK: ' + ', '.join(mitre) + parts.append(detail + '.') + + return description, ' '.join(parts) + + +def main(argv): + if len(argv) != 3: + sys.stderr.write(__doc__) + return 2 + + tag, root = argv[1], argv[2] + ruleset = Ruleset(root) + records, skipped = [], collections.Counter() + + for group, files in GROUPS.items(): + for name in files: + if name not in ruleset.text: + skipped['missing file ' + name] += 1 + continue + + for rule_id, (rule_file, rule) in ruleset.rules.items(): + if rule_file != name: + continue + + level = int(rule.get('level', '0')) + + if level == 0: + skipped['level 0'] += 1 + continue + + if rule_id in EXCLUDE: + skipped['excluded as too generic'] += 1 + continue + + variants = ruleset.variants(rule_id) + + if variants is None: + skipped['correlation or decoded fields'] += 1 + continue + + variants = [(p, c) for p, c in variants if c] + + # A program-bound variant whose conditions include all of an + # any-program variant's matches nothing that one does not. + variants = [(p, c) for p, c in variants if p is None or not any( + q is None and all(x in c for x in d) for q, d in variants)] + + if not variants: + skipped['no message condition'] += 1 + continue + + message, text = explanation(rule, rule_id, level, group) + links = [i.text.strip() for i in rule.findall('info') if i.get('type') == 'link' and (i.text or '').strip()] + line = line_of(ruleset.text[name], rule_id) + reference = 'https://github.com/wazuh/wazuh/blob/%s/ruleset/rules/%s%s' % (tag, name, '#L%d' % line if line else '') + component = re.sub(r'(?:^\d+-)|(?:_rules\.xml$)', '', name) + by_program = {} + + for programs, conditions in variants: + for program in programs or ['']: + patterns = by_program.setdefault(program, []) + pattern = combine(ruleset, conditions) + + if pattern not in patterns: + patterns.append(pattern) + + # One record per program: alternatives of the same rule become + # one OR pattern, so a message cannot match the rule twice. A + # join longer than the plugin accepts stays split; the plugin + # still lists the rule once, as the records share their text. + expanded = [] + + for program, patterns in by_program.items(): + joined = '|'.join('(?:%s)' % p for p in patterns) + + if len(patterns) > 1 and len(joined) <= MAX_PATTERN_LENGTH: + patterns = [joined] + expanded.extend((program, p) for p in patterns) + + for index, (program, pattern) in enumerate(expanded): + records.append({ + 'vendor': 'Linux', + 'identifier': 'wazuh-%s%s' % (rule_id, '' if index == 0 else '-%d' % (index + 1)), + 'component': program.strip('*') or component, + 'severity': severity(level), + 'message': message, + 'explanation': text, + 'recommended_action': '', + 'reference': '\n'.join([reference] + links), + 'regex': pattern, + 'program': program, + }) + + for reason, count in sorted(skipped.items()): + sys.stderr.write('skipped %d: %s\n' % (count, reason)) + sys.stderr.write('records %d\n' % len(records)) + + # Pattern records are tried in import order: rules bound to a program + # first, then the more severe, so specific advice wins over generic. + records.sort(key=lambda r: (r['program'] == '', 7 if r['severity'] is None else r['severity'], + int(re.match(r'wazuh-(\d+)', r['identifier']).group(1)), r['identifier'])) + + json.dump({'format': 'syslog-recommendations', 'version': 1, 'recommendations': records}, sys.stdout, + indent=2, ensure_ascii=False) + sys.stdout.write('\n') + + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/docs/RECOMMENDATION_SOURCES.md b/docs/RECOMMENDATION_SOURCES.md index a3529e65..3080087e 100644 --- a/docs/RECOMMENDATION_SOURCES.md +++ b/docs/RECOMMENDATION_SOURCES.md @@ -11,14 +11,16 @@ imported manually. Each was built from public vendor documentation. No login-pro Catalogues that are not covered by this build: -- `docs/cisco.json.gz`: Cisco CEMDB data via php-syslog-ng. It is seeded automatically. +- `docs/cisco.json.gz`: Cisco CEMDB data via php-syslog-ng. It is no longer loaded automatically. - `docs/juniper.json.gz`: Juniper System Log Explorer, 14 curated EX Series `ESWD` records. ## Build The final step is `contrib/recommendations/build_catalogues.py`. It is run once per vendor, with the extracted JSON on standard input (`build_catalogues.py hpe < hpe.json`), and writes `docs/.json.gz`. -For Linux, `contrib/recommendations/extract_systemd_catalog.py` produces the extracted JSON (see [Linux](#linux)). +For Linux, `contrib/recommendations/extract_systemd_catalog.py` produces the extracted JSON (see [Linux](#linux)), +and `contrib/recommendations/extract_wazuh_rules.py` produces it for `linux-wazuh` (see +[Linux (Wazuh)](#linux-wazuh)). For each vendor it: 1. Reads the extracted `.json` (envelope `{"format":"syslog-recommendations","version":1,"recommendations":[...]}`). @@ -28,8 +30,13 @@ For each vendor it: 4. Drops case-insensitive duplicate identifiers. The first occurrence is kept. 5. Keeps these 8 fields, in this order: `vendor`, `identifier`, `component`, `severity`, `message`, `explanation`, `recommended_action`, `reference`. Missing fields become `""`, or `null` for `severity`. + The pattern-record fields `regex` and `program` follow when they are set. 6. Writes UTF-8 JSON with 2-space indentation (`ensure_ascii=False`) and a trailing newline, compressed with gzip level 9, `mtime=0` and an empty file name, so the output is reproducible. +7. Adds the `copyright`, `license` (SPDX expression), `license_url` and `source` fields from the `LICENSING` + table to the document, and writes the same copyright and license as SPDX tags to + `docs/.json.gz.license`. `build_catalogues.py --metadata-only ` refreshes only these, keeping + the shipped records exactly; it is the way to update `cisco` and `juniper`, which have no extractor. Excluded identifiers. These are generic words that would match other vendors' messages: @@ -236,6 +243,70 @@ contrib/recommendations/build_catalogues.py linux < linux.json - Only the English entries are used. The catalog's translations (`systemd..catalog.in`) are not. - Catalogs shipped by other packages in `/usr/lib/systemd/catalog/`, such as dbus-broker's, are not included. - Most Linux services (sshd, the kernel, postfix and so on) log without a `MESSAGE_ID`, so they are not covered. + `docs/linux-wazuh.json.gz` covers them with pattern records. + +## Linux (Wazuh) + +**Records: 411** pattern records from 315 Wazuh rules: core Linux 133, network services 160, mail 71, databases +and applications 47. 328 records name a program, and 83 match the message text alone. + +| Document | Release | License | URL | Retrieved | +|---|---|---|---|---| +| Wazuh ruleset rules (`ruleset/rules/*.xml`) and decoders (`ruleset/decoders/*.xml`) | Wazuh v4.14.11 | GPL-2.0 (© Wazuh Inc.; portions © Trend Micro Inc., from OSSEC) | https://github.com/wazuh/wazuh/tree/v4.14.11/ruleset | 2026-12-03 | +| Wazuh rules syntax and regular expression syntax (OS_Match, OS_Regex, PCRE2) | current | | https://documentation.wazuh.com/current/user-manual/ruleset/ruleset-xml-syntax/regex.html | 2026-12-03 | + +Build: + +```shell +git clone --depth 1 --branch v4.14.11 --filter=blob:none --sparse https://github.com/wazuh/wazuh.git wazuh +git -C wazuh sparse-checkout set ruleset/rules ruleset/decoders +contrib/recommendations/extract_wazuh_rules.py v4.14.11 wazuh/ruleset > linux-wazuh.json +contrib/recommendations/build_catalogues.py linux-wazuh < linux-wazuh.json +``` + +The converted rule files are listed by group in `GROUPS` in `extract_wazuh_rules.py`: + +- **Core Linux:** syslog (including kernel, su, sudo, cron and user management), PAM, sshd, systemd, firewalld, + Dropbear, AppArmor, auditd, USB and Docker. +- **Mail:** Sendmail, Postfix, spamd, imapd, MailScanner, Courier, Dovecot, vm-pop3d, vpopmail, OpenSMTPD and Exim. +- **Network services:** telnetd, arpwatch, ftpd, ProFTPD, Pure-FTPd, vsftpd, BIND (named), Samba (smbd), racoon, + Apache, nginx, Squid, Unbound and OpenVPN. +- **Databases and applications:** MySQL, PostgreSQL, ClamAV, Puppet, Redis, FreeIPA, MongoDB and MariaDB. + +- **Identifier:** `wazuh-`, such as `wazuh-5710`. A rule gets one record per program its variants + (several decoder programs or several parent rules) name, with `-2`, `-3`, ... appended. Variants with the same + program are joined into one pattern, `(?:A)|(?:B)`, and a program-bound variant is dropped when its conditions + include all of an any-program variant's. Because every record of a rule has the same message and explanation, + the plugin shows each rule at most once for a message. +- **Pattern:** the rule's own `` and `` and those it inherits through `if_sid` and `decoded_as` + (including the decoder's `prematch`) are combined into one PCRE pattern. A single condition is used as is. + Several conditions become lookaheads tested from the start of the message, `^(?=.*?A)(?=.*?B)`, with + `(?!...)` for negated ones. OS_Match and OS_Regex are compiled case-insensitive by Wazuh, so their conversions + start with `(?i)`; PCRE2 expressions are kept as written. OS_Regex classes are expanded (`\w` to + `[A-Za-z0-9@_-]`, `\s` to a space, `\p` to its punctuation set, `\.` to any character) and its `$VARIABLE`s + from `0010-rules_config.xml` are substituted. +- **Program:** from the rule's or its decoder's `program_name`. `^name$` gives `name`, `^name` gives `name*`, + `name$` gives `*name` and a bare `name` gives `*name*`, using the `*` wildcards that pattern records accept. +- **Severity:** from the Wazuh level: 12 and above Critical (2), 10-11 Error (3), 7-9 Warning (4), 4-6 Notice + (5), 1-3 Informational (6). +- **Fields:** `message` is the rule description, with its `` elements joined as Wazuh does and + `$(field)` placeholders written as `[field]`. `explanation` is + the description, any `` text, and the rule's ID, group, level, Wazuh groups (compliance-mapping groups + omitted) and MITRE ATT&CK techniques. `reference` links to the rule's line in the Wazuh repository, followed by + any `` URLs. `recommended_action` is empty because Wazuh documents none. +- **Order:** records are written program-bound first, then most severe first. The plugin tries pattern records in + import order and shows at most three recommendations, so specific rules come before generic ones. +- **Filtering and gaps:** + - Skipped: 203 level 0 rules (grouping and ignore rules), 195 rules that need correlation (`frequency`, + `if_matched_sid`, `same_*`) or values a Wazuh decoder extracted (`srcip`, `user`, `field`, `url`, ...), 2 with + no message condition, and rule 1002, which matches any message containing a common word such as error, + failed or denied. + - Wazuh applies rules to the message after the syslog header, which matches the message the plugin stores. Rules + written for log files rather than syslog (for example MySQL's `MySQL log:` prefix or Apache error-log + timestamps) are converted but rarely match syslog messages. + - OS_Regex does not backtrack, but PCRE does, so a converted pattern can match slightly more than the original + rule. + - The descriptions are short, and no recommended actions are provided. ## MikroTik diff --git a/docs/arista.json.gz b/docs/arista.json.gz index bd07ebb4..c3c2bd65 100644 Binary files a/docs/arista.json.gz and b/docs/arista.json.gz differ diff --git a/docs/arista.json.gz.license b/docs/arista.json.gz.license new file mode 100644 index 00000000..6524f09c --- /dev/null +++ b/docs/arista.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Arista Networks, Inc. +SPDX-License-Identifier: LicenseRef-Arista-Terms-of-Use diff --git a/docs/cisco.json.gz b/docs/cisco.json.gz index f03acf4d..e49987ea 100644 Binary files a/docs/cisco.json.gz and b/docs/cisco.json.gz differ diff --git a/docs/cisco.json.gz.license b/docs/cisco.json.gz.license new file mode 100644 index 00000000..3b8bde4e --- /dev/null +++ b/docs/cisco.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Cisco Systems, Inc. and/or its affiliates +SPDX-License-Identifier: LicenseRef-Cisco-Terms-of-Use diff --git a/docs/dell.json.gz b/docs/dell.json.gz index df0ccbd7..59d1d2d4 100644 Binary files a/docs/dell.json.gz and b/docs/dell.json.gz differ diff --git a/docs/dell.json.gz.license b/docs/dell.json.gz.license new file mode 100644 index 00000000..b88f933b --- /dev/null +++ b/docs/dell.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Dell Inc. or its subsidiaries +SPDX-License-Identifier: LicenseRef-Dell-Terms-of-Use diff --git a/docs/fortinet.json.gz b/docs/fortinet.json.gz index 06d3138c..66a6bc9a 100644 Binary files a/docs/fortinet.json.gz and b/docs/fortinet.json.gz differ diff --git a/docs/fortinet.json.gz.license b/docs/fortinet.json.gz.license new file mode 100644 index 00000000..e091338a --- /dev/null +++ b/docs/fortinet.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Fortinet, Inc. +SPDX-License-Identifier: LicenseRef-Fortinet-Terms-of-Use diff --git a/docs/hpe.json.gz b/docs/hpe.json.gz index aedac75c..25cf6a0a 100644 Binary files a/docs/hpe.json.gz and b/docs/hpe.json.gz differ diff --git a/docs/hpe.json.gz.license b/docs/hpe.json.gz.license new file mode 100644 index 00000000..7ed7af32 --- /dev/null +++ b/docs/hpe.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Hewlett Packard Enterprise Development LP +SPDX-License-Identifier: LicenseRef-HPE-Terms-of-Use diff --git a/docs/huawei.json.gz b/docs/huawei.json.gz index f51d41a6..23a48f06 100644 Binary files a/docs/huawei.json.gz and b/docs/huawei.json.gz differ diff --git a/docs/huawei.json.gz.license b/docs/huawei.json.gz.license new file mode 100644 index 00000000..5e2affd2 --- /dev/null +++ b/docs/huawei.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Huawei Technologies Co., Ltd. +SPDX-License-Identifier: LicenseRef-Huawei-Terms-of-Use diff --git a/docs/juniper.json.gz b/docs/juniper.json.gz index c8a23c09..5c5a1fe3 100644 Binary files a/docs/juniper.json.gz and b/docs/juniper.json.gz differ diff --git a/docs/juniper.json.gz.license b/docs/juniper.json.gz.license new file mode 100644 index 00000000..17a21b3b --- /dev/null +++ b/docs/juniper.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Juniper Networks, Inc. +SPDX-License-Identifier: LicenseRef-Juniper-Terms-of-Use diff --git a/docs/linux-wazuh.json.gz b/docs/linux-wazuh.json.gz new file mode 100644 index 00000000..a38c6706 Binary files /dev/null and b/docs/linux-wazuh.json.gz differ diff --git a/docs/linux-wazuh.json.gz.license b/docs/linux-wazuh.json.gz.license new file mode 100644 index 00000000..a2a1b14d --- /dev/null +++ b/docs/linux-wazuh.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Wazuh, Inc.; Trend Micro, Inc. (OSSEC) +SPDX-License-Identifier: GPL-2.0-only diff --git a/docs/linux.json.gz b/docs/linux.json.gz index e26077bd..b6d38d02 100644 Binary files a/docs/linux.json.gz and b/docs/linux.json.gz differ diff --git a/docs/linux.json.gz.license b/docs/linux.json.gz.license new file mode 100644 index 00000000..55352830 --- /dev/null +++ b/docs/linux.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: systemd contributors +SPDX-License-Identifier: LGPL-2.1-or-later diff --git a/docs/mikrotik.json.gz b/docs/mikrotik.json.gz index 52edf070..7dc5d2fb 100644 Binary files a/docs/mikrotik.json.gz and b/docs/mikrotik.json.gz differ diff --git a/docs/mikrotik.json.gz.license b/docs/mikrotik.json.gz.license new file mode 100644 index 00000000..28ae7f04 --- /dev/null +++ b/docs/mikrotik.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: SIA Mikrotikls (MikroTik) +SPDX-License-Identifier: LicenseRef-MikroTik-Documentation diff --git a/docs/nokia.json.gz b/docs/nokia.json.gz index 5a64eeb1..3408be01 100644 Binary files a/docs/nokia.json.gz and b/docs/nokia.json.gz differ diff --git a/docs/nokia.json.gz.license b/docs/nokia.json.gz.license new file mode 100644 index 00000000..35af3b2e --- /dev/null +++ b/docs/nokia.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Nokia +SPDX-License-Identifier: LicenseRef-Nokia-Terms-of-Use diff --git a/docs/nvidia.json.gz b/docs/nvidia.json.gz index f41be29d..36e723b2 100644 Binary files a/docs/nvidia.json.gz and b/docs/nvidia.json.gz differ diff --git a/docs/nvidia.json.gz.license b/docs/nvidia.json.gz.license new file mode 100644 index 00000000..44ce5c55 --- /dev/null +++ b/docs/nvidia.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: NVIDIA Corporation & affiliates +SPDX-License-Identifier: CC-BY-NC-SA-4.0 AND LicenseRef-NVIDIA-Terms-of-Service diff --git a/docs/paloalto.json.gz b/docs/paloalto.json.gz index 049f1531..b4d834f1 100644 Binary files a/docs/paloalto.json.gz and b/docs/paloalto.json.gz differ diff --git a/docs/paloalto.json.gz.license b/docs/paloalto.json.gz.license new file mode 100644 index 00000000..d1d3b66f --- /dev/null +++ b/docs/paloalto.json.gz.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Palo Alto Networks, Inc. +SPDX-License-Identifier: LicenseRef-PaloAltoNetworks-Terms-of-Use diff --git a/includes/recommendations.php b/includes/recommendations.php index 79bd3baa..dbc648cf 100644 --- a/includes/recommendations.php +++ b/includes/recommendations.php @@ -49,10 +49,8 @@ const SYSLOG_RECOMMENDATIONS_FORMAT = 'syslog-recommendations'; const SYSLOG_RECOMMENDATIONS_VERSION = 1; -const SYSLOG_RECOMMENDATIONS_SEED_FILE = 'docs/cisco.json.gz'; const SYSLOG_RECOMMENDATIONS_MAX_BYTES = 64 * 1024 * 1024; const SYSLOG_RECOMMENDATIONS_MAX_TEXT = 20000; -const SYSLOG_RECOMMENDATIONS_SEED_FLAG = 'syslog_recommendations_seeded'; // Lookup scope meaning "records of every vendor"; a NUL byte cannot occur in a vendor name. const SYSLOG_RECOMMENDATIONS_ANY_VENDOR = "\0*"; @@ -904,8 +902,9 @@ function syslog_recommendation_scope_sql(string $scope, string $column): array { * * @param bool $reset Forget the loaded patterns (used by tests). * - * @return list|false - * The patterns, oldest first, or false when they could not be loaded. + * @return list|false + * The patterns, oldest first, or false when they could not be loaded. advice identifies the + * recommendation text, or is '' when the record has no message. */ function syslog_recommendation_patterns(bool $reset = false): array|false { static $patterns = null; @@ -917,7 +916,7 @@ function syslog_recommendation_patterns(bool $reset = false): array|false { } if ($patterns === null) { - $rows = syslog_db_fetch_assoc_prepared('SELECT id, vendor, regex, program + $rows = syslog_db_fetch_assoc_prepared('SELECT id, vendor, regex, program, message, explanation FROM syslog_recommendations WHERE regex > ? ORDER BY id @@ -939,11 +938,14 @@ function syslog_recommendation_patterns(bool $reset = false): array|false { continue; } + $message = (string) ($row['message'] ?? ''); + $patterns[] = [ 'id' => (int) $row['id'], 'vendor' => (string) $row['vendor'], 'regex' => syslog_recommendation_regex((string) $row['regex']), - 'program' => strtolower((string) ($row['program'] ?? '')) + 'program' => strtolower((string) ($row['program'] ?? '')), + 'advice' => $message === '' ? '' : hash('sha256', $row['vendor'] . "\0" . $message . "\0" . ($row['explanation'] ?? '')) ]; } } @@ -956,7 +958,9 @@ function syslog_recommendation_patterns(bool $reset = false): array|false { * * A pattern record applies to a sender unless the sender is a Cacti device * recognised as another vendor, and, when it names a program, only to - * messages from that program (ignoring case). + * messages from that program (ignoring case). A record repeating the vendor, + * message and explanation of an earlier match is skipped, so one + * recommendation is not listed twice. * * @param string $message The syslog message text. * @param string $program The syslog program of the message, if known. @@ -979,6 +983,7 @@ function syslog_recommendation_pattern_ids(string $message, string $program, str $previous = ini_get('pcre.backtrack_limit'); $budget = min(SYSLOG_RECOMMENDATIONS_BACKTRACK_LIMIT, max(1, (int) $previous)); $out = []; + $seen = []; ini_set('pcre.backtrack_limit', (string) $budget); @@ -992,6 +997,10 @@ function syslog_recommendation_pattern_ids(string $message, string $program, str continue; } + if ($pattern['advice'] !== '' && isset($seen[$pattern['advice']])) { + continue; + } + if ($checks !== null) { if ($checks < 1) { break; @@ -1002,6 +1011,7 @@ function syslog_recommendation_pattern_ids(string $message, string $program, str if (@preg_match($pattern['regex'], $message) === 1) { $out[] = $pattern['id']; + $seen[$pattern['advice']] = true; if (count($out) >= $limit) { break; @@ -1330,50 +1340,3 @@ function syslog_recommendations_lookup_json(string $message, string $host = '', 'labels' => syslog_recommendations_labels() ], JSON_INVALID_UTF8_SUBSTITUTE); } - -/** - * Load the bundled recommendations the first time the plugin is installed or upgraded. - * - * The seed file is only ever applied once (INSERT IGNORE, so records a user - * added or changed are never overwritten), and a user who removes the bundled - * records is not given them back by a later upgrade. - * - * @param string|null $file An alternative seed file, mainly for tests. - * - * @return int The number of records imported, or -1 when the seed was skipped. - */ -function syslog_recommendations_seed(?string $file = null): int { - $custom = $file !== null; - - if (!$custom && read_config_option(SYSLOG_RECOMMENDATIONS_SEED_FLAG) === '1') { - return -1; - } - - $file = $file ?? dirname(__DIR__) . '/' . SYSLOG_RECOMMENDATIONS_SEED_FILE; - - $payload = syslog_recommendations_read_file($file); - $parsed = $payload === false ? false : syslog_recommendations_parse($payload); - unset($payload); - - if ($parsed === false || $parsed['invalid'] || !$parsed['records']) { - cacti_log('SYSLOG WARNING: Recommendations seed file ' . $file . ' is not readable or contains invalid JSON recommendations (gzip files require PHP zlib)', false, 'SYSTEM'); - - return -1; - } - - if (function_exists('set_time_limit')) { - @set_time_limit(0); - } - - $result = syslog_recommendations_store($parsed['records'], false); - - if ($result['failed']) { - cacti_log('SYSLOG WARNING: Failed to store ' . $result['failed'] . ' recommendation(s) from seed file ' . $file, false, 'SYSTEM'); - } - - if (!$result['failed'] && !$custom) { - set_config_option(SYSLOG_RECOMMENDATIONS_SEED_FLAG, '1'); - } - - return $result['imported']; -} diff --git a/manifest.json b/manifest.json index 552c1fde..da85c626 100644 --- a/manifest.json +++ b/manifest.json @@ -29,6 +29,7 @@ "CHANGELOG.md", "INFO", "LICENSE", + "NOTICE", "README.md", "cli/", "config.php.dist", diff --git a/setup.php b/setup.php index 9da8a42b..85eb624c 100644 --- a/setup.php +++ b/setup.php @@ -1076,10 +1076,6 @@ function syslog_check_upgrade(bool $force = false): bool { } syslog_dashboard_seed_default(); - // Load the bundled recommendations once; records already present are kept. - if ((int) $config['poller_id'] <= 1) { - syslog_recommendations_seed(); - } db_execute_prepared('DELETE FROM plugin_hooks WHERE name = ? AND hook = ?', ['syslog', 'config_insert']); // don't let this script timeout diff --git a/tests/Unit/RecommendationsTest.php b/tests/Unit/RecommendationsTest.php index f9e7e774..8eb3527e 100644 --- a/tests/Unit/RecommendationsTest.php +++ b/tests/Unit/RecommendationsTest.php @@ -9,7 +9,7 @@ /* * Syslog recommendations: import/export normalization, message lookup and the - * one-time seed that the 5.0 upgrade performs. + * bundled catalogues. */ beforeEach(function () { @@ -239,77 +239,6 @@ function recommendation_sample(array $override = []): array { ->and($queries[0])->toContain('WHERE regex > ?'); }); -it('seeds JSON records with prepared inserts without overwriting existing data', function () { - $file = tempnam(sys_get_temp_dir(), 'rec'); - $records = [recommendation_sample(), recommendation_sample(['identifier' => 'B'])]; - file_put_contents($file, json_encode($records)); - - $run = []; - test_override('syslog_db_execute_prepared', function ($sql, $params) use (&$run) { - $run[] = [$sql, $params]; - - return true; - }); - test_override('syslog_db_affected_rows', static fn () => 1); - - try { - expect(syslog_recommendations_seed($file))->toBe(2) - ->and($run)->toHaveCount(2) - ->and($run[0][0])->toStartWith('INSERT IGNORE INTO syslog_recommendations') - ->and($run[0][1])->toBe([...array_values($records[0]), '', '']); - } finally { - unlink($file); - } - - $flag = []; - test_override('read_config_option', static fn ($name) => $name === SYSLOG_RECOMMENDATIONS_SEED_FLAG ? '1' : ''); - test_override('set_config_option', function ($name) use (&$flag) { - $flag[] = $name; - }); - - expect(syslog_recommendations_seed())->toBe(-1)->and($flag)->toBe([]); -}); - -it('seeds from a gzip compressed file', function () { - $file = tempnam(sys_get_temp_dir(), 'rec'); - file_put_contents($file, gzencode(json_encode([recommendation_sample()]), 9)); - - $run = []; - test_override('syslog_db_execute_prepared', function ($sql, $params) use (&$run) { - $run[] = $params; - - return true; - }); - test_override('syslog_db_affected_rows', static fn () => 1); - - try { - expect(syslog_recommendations_seed($file))->toBe(1) - ->and($run[0])->toBe([...array_values(recommendation_sample()), '', '']); - } finally { - unlink($file); - } -}); - -it('reports an unreadable seed file without marking it applied', function () { - $logged = []; - test_override('cacti_log', function ($message) use (&$logged) { - $logged[] = $message; - }); - - expect(syslog_recommendations_seed(sys_get_temp_dir() . '/no-such-seed.json.gz'))->toBe(-1) - ->and($logged[0])->toContain('not readable'); -}); - -it('does not remember a bundled seed that had failing inserts', function () { - $flag = []; - test_override('syslog_db_execute_prepared', static fn () => false); - test_override('set_config_option', function ($name) use (&$flag) { - $flag[] = $name; - }); - - expect(syslog_recommendations_seed())->toBe(0)->and($flag)->toBe([]); -}); - it('counts and logs statements that fail to store', function () { $logged = []; test_override('syslog_db_execute_prepared', static fn () => false); @@ -365,18 +294,6 @@ function recommendation_sample(array $override = []): array { ->and($candidates)->not->toContain('Word121'); }); -it('remembers the bundled seed was applied', function () { - $flag = []; - test_override('syslog_db_execute_prepared', static fn () => true); - test_override('syslog_db_affected_rows', static fn () => 1); - test_override('set_config_option', function ($name, $value) use (&$flag) { - $flag[$name] = $value; - }); - - expect(syslog_recommendations_seed())->toBeGreaterThan(0) - ->and($flag)->toBe([SYSLOG_RECOMMENDATIONS_SEED_FLAG => '1']); -}); - it('ships compressed catalogues that import without losing records or fields', function (string $file, string $vendor, int $count) { $payload = syslog_recommendations_read_file(dirname(__DIR__, 2) . '/docs/' . $file); $decoded = json_decode($payload, true); @@ -400,7 +317,8 @@ function recommendation_sample(array $override = []): array { 'Fortinet' => ['fortinet.json.gz', 'Fortinet', 1462], 'Palo Alto Networks' => ['paloalto.json.gz', 'Palo Alto Networks', 364], 'MikroTik' => ['mikrotik.json.gz', 'MikroTik', 11], - 'Linux' => ['linux.json.gz', 'Linux', 102] + 'Linux' => ['linux.json.gz', 'Linux', 102], + 'Linux (Wazuh)' => ['linux-wazuh.json.gz', 'Linux', 411] ]); it('streams compressed exports across database pages without changing the filters or records', function () { @@ -497,7 +415,8 @@ function recommendation_sample(array $override = []): array { })->with(['checksum', 'truncated', 'trailing']); it('enforces the expanded import limit and accepts content exactly at that limit', function () { - $memory_limit = ini_set('memory_limit', '256M'); + // Leave room for two copies of the expanded file above what the suite already holds. + $memory_limit = ini_set('memory_limit', (string) (memory_get_usage(true) + 256 * 1024 * 1024)); $file = tempnam(sys_get_temp_dir(), 'rec'); $write = static function (int $bytes) use ($file): void { $handle = gzopen($file, 'wb'); @@ -538,33 +457,6 @@ function recommendation_sample(array $override = []): array { } }); -it('does not seed a malformed catalogue or mark it applied', function () { - $file = tempnam(sys_get_temp_dir(), 'rec'); - file_put_contents($file, json_encode([recommendation_sample(), ['explanation' => 'no identifier']])); - $inserts = []; - test_override('syslog_db_execute_prepared', function ($sql) use (&$inserts) { - $inserts[] = $sql; - }); - - try { - expect(syslog_recommendations_seed($file))->toBe(-1)->and($inserts)->toBe([]); - } finally { - unlink($file); - } -}); - -it('marks a seed applied even when all of its records already exist', function () { - $flag = []; - test_override('syslog_db_execute_prepared', static fn () => true); - test_override('syslog_db_affected_rows', static fn () => 0); - test_override('set_config_option', function ($name, $value) use (&$flag) { - $flag[$name] = $value; - }); - - expect(syslog_recommendations_seed())->toBe(0) - ->and($flag)->toBe([SYSLOG_RECOMMENDATIONS_SEED_FLAG => '1']); -}); - it('renders message rows without hover titles or recommendation lookups', function () { syslog_load_plugin_source('includes/functions.php'); @@ -893,10 +785,10 @@ function recommendation_pattern_db(array $records, array $devices = []): PDO { $db->exec("CREATE TABLE syslog_recommendations (id INTEGER PRIMARY KEY, identifier TEXT, vendor TEXT, component TEXT, severity INTEGER, message TEXT, explanation TEXT, recommended_action TEXT, reference TEXT, regex TEXT NOT NULL DEFAULT '', program TEXT NOT NULL DEFAULT '')"); - $insert = $db->prepare('INSERT INTO syslog_recommendations (identifier, vendor, explanation, regex, program) VALUES (?, ?, ?, ?, ?)'); + $insert = $db->prepare('INSERT INTO syslog_recommendations (identifier, vendor, message, explanation, regex, program) VALUES (?, ?, ?, ?, ?, ?)'); foreach ($records as $record) { - $insert->execute([$record[0], $record[1], 'Explained.', $record[2] ?? '', $record[3] ?? '']); + $insert->execute([$record[0], $record[1], $record[4] ?? '', $record[5] ?? 'Explained.', $record[2] ?? '', $record[3] ?? '']); } foreach (['syslog_db_fetch_assoc_prepared', 'syslog_db_fetch_cell_prepared'] as $function) { @@ -985,6 +877,21 @@ function recommendation_pattern_db(array $records, array $devices = []): PDO { ->toBe(['ssh' => true, 'cron' => false, 'cisco' => false, 'oom' => true]); }); +it('lists a recommendation split into several patterns once, but keeps records without a message apart', function () { + recommendation_pattern_db([ + ['rule-a', 'Linux', 'Failed password', 'sshd', 'Same advice'], + ['rule-a-2', 'Linux', 'Failed', '', 'Same advice'], + ['rule-b', 'Linux', 'password', '', 'Other advice'], + ['plain-1', '', 'Failed'], + ['plain-2', '', 'Failed'] + ]); + + expect(array_column(syslog_recommendations_lookup('Failed password for root', 5, '', 'sshd'), 'identifier')) + ->toBe(['rule-a', 'rule-b', 'plain-1', 'plain-2']) + ->and(array_column(syslog_recommendations_lookup('Failed password for root', 5, '', 'cron'), 'identifier')) + ->toBe(['rule-a-2', 'rule-b', 'plain-1', 'plain-2']); +}); + it('treats a pattern that exhausts its backtracking budget as no match and restores the limit', function () { recommendation_pattern_db([['catastrophic', '', '^(a+)+$']]); $limit = ini_get('pcre.backtrack_limit'); @@ -1097,3 +1004,43 @@ function recommendation_require_post(): void {} ->and($messages[0][0])->toBe('syslog_recommendation_invalid') ->and($messages[0][1])->toContain('a valid pattern'); }); + +it('matches real Linux service messages with the bundled Wazuh-derived catalogue', function (string $program, string $message, ?string $expected) { + $records = syslog_recommendations_parse(syslog_recommendations_read_file(dirname(__DIR__, 2) . '/docs/linux-wazuh.json.gz'))['records']; + + recommendation_pattern_db(array_map(static fn (array $r): array => [$r['identifier'], $r['vendor'], $r['regex'] ?? '', $r['program'] ?? '', $r['message'], $r['explanation']], $records)); + + $found = array_column(syslog_recommendations_lookup($message, 3, '', $program), 'identifier'); + $rules = array_map(static fn (string $id): string => preg_replace('/^wazuh-(\d+).*$/', '$1', $id), $found); + + expect($rules)->toBe(array_values(array_unique($rules))); + + if ($expected === null) { + expect($found)->toBe([]); + } else { + expect($found)->toContain($expected); + } +})->with([ + 'kernel OOM' => ['kernel', 'Out of memory: Killed process 4242 (java) total-vm:8123456kB', 'wazuh-5108'], + 'sshd-session bad user' => ['sshd-session', 'Invalid user admin from 192.0.2.1 port 52122', 'wazuh-5710'], + 'sshd root password' => ['sshd', 'Failed password for root from 192.0.2.1 port 52122 ssh2', 'wazuh-5760'], + 'apache segfault' => ['apache2', '[notice] child pid 4242 exit signal Segmentation fault (11)', 'wazuh-30104'], + 'postfix/smtpd DNS' => ['postfix/smtpd', 'warning: hostname mail.example does not resolve to address 192.0.2.1', 'wazuh-3398'], + 'other program' => ['cron', 'Invalid user admin from 192.0.2.1 port 52122', null], + 'ordinary link message' => ['NetworkManager', ' [1733243200.1234] device (eth0): carrier: link connected', null] +]); + +it('ships every catalogue with a .license file that matches its licensing fields', function () { + $files = glob(dirname(__DIR__, 2) . '/docs/*.json.gz'); + + expect($files)->not->toBeEmpty(); + + foreach ($files as $file) { + $document = json_decode((string) gzdecode((string) file_get_contents($file)), true); + $license = @file_get_contents($file . '.license'); + + expect($license)->toBeString(basename($file) . ' has no .license file') + ->and($document)->toHaveKeys(['copyright', 'license', 'license_url', 'source']) + ->and($license)->toBe('SPDX-FileCopyrightText: ' . $document['copyright'] . "\nSPDX-License-Identifier: " . $document['license'] . "\n"); + } +});