SNMP-Trap-Tools(at)Work

SNMP-Trap-Tools(at)Work / Technical description

SNMP Trap Receiver

SNMP v1/v2c/v3 trap and inform receiver with web GUI for Rocky Linux 9

Version 2.2.0Revised 2026-10-11

1. Summary

SNMP Trap Receiver receives SNMP notifications (traps and informs, SNMP v1, v2c and v3) from network devices and servers, translates the numeric object identifiers to names using MIB files, stores every notification in log files and shows them live in a web GUI in English or Norwegian.

Version 2.0 replaces the earlier Docker container. It runs as a hardened systemd service on Rocky Linux 9 (also the minimal installation) and is installed from one self-contained file without internet access.

2. Purpose and scope

Receives

SNMPv1 Trap-PDU, SNMPv2c Trap and InformRequest, SNMPv3 Trap and InformRequest (USM: noAuthNoPriv, authNoPriv, authPriv) over UDP/IPv4 and UDP/IPv6

Translates

Trap OID and variable names using uploaded vendor MIBs and the built-in IETF MIBs

Stores

Human-readable text log and JSON Lines log, both rotated

Shows

Live list with filter, details per trap, CSV export, receiver status, MIB management, log download, licence information

Does not

Forward traps, send e-mail, poll devices, store traps in a database

3. Architecture

  network devices                     Rocky Linux 9 server
 ┌───────────────┐  UDP 162   ┌────────────────────────────────────────────────┐
 │ switch/router ├──────────► │  snmp-trap-receiver.service  (user snmptrap)   │
 │ ESXi, UPS ... │  v1/v2c/v3 │                                                │
 └───────────────┘            │  ┌────────────────────┐   ┌─────────────────┐  │
                              │  │ TrapReceiver       │   │ MibManager      │  │
                              │  │ thread + asyncio   ├──►│ pysmi compiler  │  │
                              │  │ pysnmp 7 engine    │   │ OID→name lookup │  │
                              │  └─────────┬──────────┘   └─────────────────┘  │
                              │            │ record                            │
                              │   ring buffer (2000)  +  snmp_traps.log/.jsonl │
                              │            ▲                                   │
                              │  ┌─────────┴──────────┐                        │
 ┌─────────┐  HTTP 8081       │  │ Flask app on       │                        │
 │ browser ├────────────────► │  │ Waitress (8 thr.)  │                        │
 └─────────┘  GUI + JSON API  │  └────────────────────┘                        │
                              └────────────────────────────────────────────────┘

One process contains everything. The SNMP engine runs in its own thread with its own asyncio event loop. The web server runs in Waitress worker threads and reads from the receiver’s in-memory ring buffer. The two meet only in a lock-protected deque, so a slow browser never delays trap reception.

3.1. Modules

Module Responsibility

trapreceiver/config.py

Reads /etc/snmp-trap-receiver/config.ini. Every key has a safe default. Also updates single keys, keeping comments and file ownership.

trapreceiver/receiver.py

TrapReceiver: builds the pysnmp engine, binds transports, checks the binds, handles notifications, writes logs, keeps the ring buffer and statistics. Start, stop and restart while the process keeps running.

trapreceiver/mibs.py

MibManager: validates and stores uploads, compiles MIBs offline, resolves OIDs to names.

trapreceiver/web.py

Flask application: login, CSRF, security headers, pages and JSON API.

trapreceiver/i18n.py

All GUI texts in English and Norwegian (121 keys; both languages must have the same keys or the module refuses to load).

trapreceiver/manual.py

Shows the user manual (docs/en/User-Manual.md, docs/no/Brukermanual.md) in the GUI. A small Markdown renderer without dependencies: all text is HTML-escaped first, links may only point to #anchors or http(s).

trapreceiver/selftest.py

End-to-end test on a temporary port and temporary directories.

trapreceiver/main.py

Command line: serve, set-password, compile-mibs, import-mibs, selftest, version.

trapreceiver/mibs_base/

25 standard IETF MIB sources plus a stub for RFC-1212.

trapreceiver/templates/, static/

HTML templates, Bootstrap 5.3.7, the application’s own JavaScript and CSS.

4. Trap processing

4.1. Reception

For every listen entry the receiver opens a UDP transport (IPv4 or IPv6) in pysnmp. pysnmp binds sockets asynchronously, so the receiver waits for every bind and reports each failure, for example Address already in use or Address family not supported. If no address can be bound, the receiver stays stopped and shows the error. If only some can be bound, it runs on those and shows a warning.

Communities are registered as SNMPv1/v2c security entries. SNMPv3 users are registered in USM with their authentication and privacy protocols. A v3 trap is accepted only if the user is registered for the sender’s snmpEngineID (engine_id in the configuration). A v3 inform uses the receiver’s own engine ID and needs no engine_id.

4.2. Community check

An observer on the pysnmp execution point rfc2576.processIncomingMsg:writable sees every v1/v2c message before it is authorised:

  • The community actually used is remembered for the log.

  • If it is unknown and accept_any_community = false, the message is dropped by pysnmp, and the receiver counts it as rejected and writes a REJECTED line with the sender address to the text log.

  • If accept_any_community = true, the community is mapped to the first configured one so the message is accepted, while the log still shows the community the device actually sent.

4.3. Notification handling

pysnmp’s NotificationReceiver calls the receiver for every accepted trap or inform and acknowledges informs automatically. The receiver then:

  1. takes the source address and port from the transport information;

  2. takes the SNMP version and PDU type (trap or inform) from the message context;

  3. resolves every variable binding through the MIB view (name and value formatting, for example enumerations and DisplayString);

  4. extracts snmpTrapOID.0 and sysUpTime.0; for SNMPv1 traps pysnmp has already converted the Trap-PDU to the SNMPv2 form, so snmpTrapAddress.0, snmpTrapCommunity.0 and snmpTrapEnterprise.0 are included as variables;

  5. builds a record, adds it to the ring buffer, and writes it to both log files.

4.4. Record format

Each line of snmp_traps.jsonl is one JSON object:

{"id": 17, "time": "2026-10-02 10:45:20", "ts": 1790930720.642,
 "source": "192.0.2.31", "source_port": 49052, "version": "v2c",
 "kind": "trap", "security": "public",
 "trap_oid": "1.3.6.1.6.3.1.1.5.3", "trap_name": "IF-MIB::linkDown",
 "uptime": "123456",
 "varbinds": [
   {"oid": "1.3.6.1.2.1.2.2.1.1.12", "name": "IF-MIB::ifIndex.12",
    "value": "12", "type": "Integer"},
   {"oid": "1.3.6.1.2.1.2.2.1.8.12", "name": "IF-MIB::ifOperStatus.12",
    "value": "down", "type": "Integer"}]}

id

Sequence number. Continues after a restart, because the buffer is reloaded from the JSON log

security

Community (v1/v2c) or USM user name (v3)

kind

trap or inform

name

Empty if no loaded MIB defines the OID

The text log has the same content in readable form:

[2026-10-02 10:45:20] TRAP v2c from 192.0.2.31:49052 (community: public)
  snmpTrapOID = IF-MIB::linkDown (1.3.6.1.6.3.1.1.5.3)
  sysUpTime = 123456
  IF-MIB::ifIndex.12 = 12
  IF-MIB::ifOperStatus.12 = down

5. MIB handling

5.1. Upload

  1. The extension must be .mib, .txt, .my, .smi or none.

  2. The file must not be empty, must be at most mib_max_kb and must not contain NUL bytes in its first 4 KB.

  3. The module name is read from the content (NAME DEFINITIONS ::= BEGIN) and must match ^[A-Za-z][A-Za-z0-9-]{0,127}$.

  4. The file is written atomically as <data_dir>/mibs/source/<NAME>. The name the browser sent is only shown in the list, never used as a path. Path traversal is therefore impossible.

5.2. Compilation

All uploaded modules are compiled with pysmi to pysnmp Python modules in <data_dir>/mibs/compiled/. Each module is compiled separately, so one broken file does not stop the others, and each gets its own status:

ok

Compiled and loaded

error

Message from the parser, or missing: A, B when imported modules cannot be found

pending

Not yet compiled

Sources for IMPORTS, in this order: the upload directory, the directories in mib_search_dirs (for example /usr/share/snmp/mibs if net-snmp-libs is installed), and the bundled IETF MIBs. pysmi’s HTTP reader is never used. Its dependency requests is replaced by a stub that refuses to download, so compilation is strictly offline.

5.3. Standard MIBs

At the first start of a version, the bundled standard MIBs that define common notifications and objects are compiled once into <data_dir>/mibs/base/ (about 1.5 s): IF-MIB, IANAifType-MIB, HOST-RESOURCES-MIB, IP-MIB, TCP-MIB, UDP-MIB, DISMAN-EVENT-MIB, NOTIFICATION-LOG-MIB and their imports. Together with the modules pysnmp ships (SNMPv2-MIB, RFC1213-MIB, …) this means that for example IF-MIB::linkDown or SNMPv2-MIB::coldStart are shown by name without any upload. Uploaded modules take precedence over these.

5.4. Resolution

After every compilation a new MibViewController is built from pysnmp’s built-in modules and all compiled modules, and it is swapped in under a lock. Every new trap is resolved against it. Traps that were already received keep the names they had when they arrived.

6. Configuration

File: /etc/snmp-trap-receiver/config.ini (owner root:snmptrap, mode 0640). Restart the service after a change.

Section Key Default Meaning

[web]

host

0.0.0.0

Address of the web GUI

port

8081

TCP port

auth

true

Require a password

password_hash

(set by installer)

scrypt hash (Werkzeug); set with set-password

secret_key

(random)

Signs the session cookie

default_language

en

en or no

session_hours

12

Session lifetime

[receiver]

listen

0.0.0.0:162

Comma-separated host:port; IPv6 as [::]:162

autostart

true

Start receiving when the service starts

communities

public

Accepted communities

accept_any_community

false

Accept every community

buffer_size

2000

Traps kept in memory for the GUI

[storage]

data_dir

/var/lib/snmp-trap-receiver

MIB sources, compiled modules, status

log_dir

/var/log/snmp-trap-receiver

Trap logs

log_max_mb

20

Rotation size per file

log_backups

10

Rotated files kept per log

mib_max_kb

2048

Largest MIB upload

mib_search_dirs

/usr/share/snmp/mibs

Extra MIB source directories

[v3user:NAME]

auth_protocol

none

md5, sha, sha224, sha256, sha384, sha512

auth_key

Authentication pass phrase

priv_protocol

none

des, 3des, aes128, aes192, aes256

priv_key

Privacy pass phrase

engine_id

Sender’s engine ID in hex (v3 traps)

7. Web GUI and API

7.1. Pages

Traps

Live list, newest first, updated every 2 seconds. Free-text filter (all words must match source, OID, name or value), version filter, pause, clear view, CSV export. Click a row to see all variables with OID, name, value and type.

MIB files

Upload one or several files, status per module with error text, download source, delete, compile again.

Receiver

Running/stopped, listen addresses, failed addresses, counters for received, rejected and errors, configured communities and v3 users, last error. Start, stop and restart.

Logs

All log files including rotated ones, with size, time and download.

Footer

Version and links to Licences (component list from third_party_inventory.json, filterable by licence), Licence report and Third-party notices (searchable).

The selected tab is remembered in the browser. The layout works down to phone width; on narrow screens two columns of the trap list are hidden.

7.2. Endpoints

Path Method Purpose

/login, /logout

GET/POST, POST

Session

/lang/<en|no>

GET

Set the language cookie

/

GET

Main page

/legal?doc=components|report|notices

GET

Licence viewer

/manual

GET

User manual in the selected language, with contents and search. The Manual button links to /manual#<tab>

/healthz

GET

{"ok": true, "receiver": true, "version": "2.2.0"} – no login, for monitoring

/api/status

GET

Receiver status and counters

/api/traps?since=N

GET

Traps with id > N (max 1000)

/api/traps/clear

POST

Clear the in-memory list (logs are not changed)

/api/receiver/<start|stop|restart>

POST

Control the receiver

/api/mibs

GET/POST

List / upload (multipart/form-data, field mib_file, several allowed)

/api/mibs/compile

POST

Compile all again

/api/mibs/<module>/delete

POST

Delete a module

/api/mibs/<module>/source

GET

Download the source

/api/logs

GET

List log files

/download/log/<file>

GET

Download a log file (only the trap logs and their rotations)

/download/traps.csv

GET

CSV of the traps in memory

/api/legal, /api/legal/<report|notices>

GET

Licence data in the selected language

7.3. Security

  • Authentication: one password, stored as an scrypt hash. After five failed attempts from one address within 15 minutes, logins from that address are refused for 30 s, doubling up to 15 min.

  • Session: signed cookie, HttpOnly, SameSite=Strict, 12 h.

  • CSRF: every POST needs the session’s token (header X-CSRF-Token or form field).

  • Headers: Content-Security-Policy: default-src 'self' without inline script or style, X-Frame-Options: DENY, nosniff, Referrer-Policy: no-referrer, Cache-Control: no-store on the API.

  • Output: all trap content is escaped before it is shown. In the CSV export, cells starting with =, +, - or @ get a leading ' so spreadsheets cannot run them as formulas.

  • Uploads: see Upload.

8. Languages

English is the default; the configuration can change the default and each user can switch with EN/NO in the top bar (stored in a cookie for one year). The server renders the page in the selected language, and the same dictionary is passed to JavaScript, so dynamic texts follow the language. The licence report is served in the selected language; the third-party notices are in English (original licence texts).

9. Installation and operation

9.1. Files and users

Path Owner, mode Content

/opt/snmp-trap-receiver/app/

root, 0755

Application

/opt/snmp-trap-receiver/venv/

root, 0755

Python environment built from the bundled wheels

/opt/snmp-trap-receiver/docs/

root

This documentation, licence files

/opt/snmp-trap-receiver/.previous/

root

Previous version after an upgrade

/etc/snmp-trap-receiver/config.ini

root:snmptrap, 0640

Configuration (contains the secret key and v3 keys)

/var/lib/snmp-trap-receiver/

snmptrap, 0750

MIB sources, compiled modules, status.json

/var/log/snmp-trap-receiver/

snmptrap, 0750

snmp_traps.log, snmp_traps.jsonl and rotations

/usr/local/bin/snmp-trap-receiver

root, 0755

Command line wrapper

9.2. systemd unit

The service runs as the system user snmptrap. It gets exactly one capability, CAP_NET_BIND_SERVICE, to bind UDP 162. The unit also sets NoNewPrivileges, ProtectSystem=strict (everything read-only except the data and log directories), ProtectHome, PrivateTmp, PrivateDevices, kernel and control-group protection, RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX, RestrictNamespaces, LockPersonality and UMask=0027. It restarts automatically after a failure (Restart=on-failure).

SELinux needs no changes: the service runs in the unconfined_service_t domain like other programs under /opt.

9.3. Command line

snmp-trap-receiver serve

Run receiver and web GUI (used by systemd)

snmp-trap-receiver set-password [--password-stdin | --generate]

Set the web password (root)

snmp-trap-receiver import-mibs FILES…​

Import and compile MIB files

snmp-trap-receiver compile-mibs

Compile all uploaded MIBs; exit code 2 if any fail

snmp-trap-receiver selftest

End-to-end test (see Verification)

snmp-trap-receiver version

Version

As root, every command except set-password runs as the user snmptrap, so files keep the right owner.

9.4. Offline installer

snmp-trap-receiver-offline-installer.run is a bash script followed by a gzip-compressed tar archive. The script uses python3 to check the archive’s SHA-256, unpacks it with the tarfile data filter (no absolute paths, no ..), and starts install.sh. Neither tar nor pip needs to be installed on the server.

install.sh:

  1. checks root, OS, Python 3.9, architecture against the bundle, glibc ≥ 2.34 (needed by the cryptography wheel) and the checksum of every file (SHA256SUMS);

  2. stops a running service on an upgrade;

  3. creates the user and the directories;

  4. builds a new virtual environment with python3 -m venv --without-pip and installs the pinned wheels with the bundled pip wheel (--no-index --no-deps --only-binary=:all:). pip itself is not installed into the environment;

  5. checks that the packages import, then swaps the new version in and moves the old one to .previous/;

  6. creates the configuration on first install (random secret key, generated password) or keeps the existing one, then applies options given on the command line;

  7. optionally imports MIBs;

  8. installs the systemd unit, opens firewalld ports, restarts the service and waits for /healthz;

  9. runs the self-test.

9.5. Building the installer

On any machine with internet access:

bash build-offline-installer.sh            # x86_64 + aarch64

The script downloads the wheels in Application/requirements.lock for CPython 3.9 on both architectures (manylinux 2014/2_17/2_28/2_34), checks that every package exists for every architecture, generates THIRD_PARTY_NOTICES.txt and third_party_inventory.json from the wheels (including the GPL scan), copies the application and documentation, runs an offline installation and the self-test with Python 3.9 if the build host has it, runs pip-audit if it is installed, and writes the installer, a plain .tar.gz and their checksums to Offline-Installation/.

To update dependencies, change Application/requirements.in, resolve with Python 3.9 and write the result to requirements.lock.

10. Verification

snmp-trap-receiver selftest uses a free high UDP port on 127.0.0.1 and temporary directories, so it never disturbs the running service. It checks:

  • cryptography is available (SNMPv3 privacy);

  • a test MIB uploaded with the file name ../../evil/selftest.mib is stored under its module name only;

  • the MIB compiles offline against the bundled IETF MIBs; a non-MIB file is rejected;

  • the receiver binds; a v1 trap, a v2c trap, a v2c inform and a v3 authPriv trap (SHA/AES) are sent and all four are received with the right version and kind;

  • the trap OID and variables are resolved through the uploaded MIB; source address recorded; a wrong community is rejected and counted; both logs are written;

  • web: login required, wrong password refused, login works, the English page is the default, a POST without a CSRF token is refused, the traps API, MIB upload through the API, log download, refusal of path traversal in log download, CSV export, the user manual in English and Norwegian, the Norwegian page, security headers, licence inventory and both licence documents in both languages, stop and start through the API.

The installer runs the self-test after every installation.

11. Limits

  • HTTP only. For access across untrusted networks, bind the GUI to 127.0.0.1 and use an SSH tunnel, or put a TLS reverse proxy in front.

  • One shared password; no user accounts or audit trail of GUI actions (start, stop, upload and delete are written to the journal with the client address).

  • The in-memory list holds buffer_size traps; older ones are only in the log files.

  • Measured capacity: about 700 traps per second on one CPU core, with bursts of 2,000 traps received without loss. The receiver asks for a 4 MB socket receive buffer; the kernel caps it at net.core.rmem_max (Rocky 9 default: 208 KB, enough for a few hundred traps in one burst). For sites with large trap storms, raise the cap: echo net.core.rmem_max=4194304 > /etc/sysctl.d/90-snmp-trap-receiver.conf && sysctl --system.

12. Licences

All third-party components are under permissive licences. See License-Report.md, THIRD_PARTY_NOTICES.txt and third_party_inventory.json.

Appendix A: Ports

Port

Protocol

Direction

Purpose

162

UDP

in

SNMP traps and informs (configurable)

8081

TCP

in

Web GUI (configurable)

Appendix B: Documents

Installation-Guide.md

Installation, configuration, operation, upgrade

Audit-Report.md

Audit of the Docker version and what was fixed

License-Report.md

Licences and GPL scan

THIRD_PARTY_NOTICES.txt

Full licence texts

third_party_inventory.json

Machine-readable component list

CHANGELOG.md

Changes

Need something that sends traps to test the receiver with? Technical description for SNMP Trap Sender