feat: printer import via SNMP v2c/v3 scan with page counter and supplies

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 09:39:50 +01:00
1 parent 05d34e4823
commit 235fb8e26a
12 files changed
+1957 -44

No files matched your search

+1
View File
@@ -84,3 +84,4 @@ class FakeNetBox:
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
interfaces=Endpoint())
self.tenancy = SimpleNamespace(tenants=Endpoint())
self.extras = SimpleNamespace(custom_fields=Endpoint())
+201
View File
@@ -0,0 +1,201 @@
"""Minimal SNMP agent on localhost for tests (v2c and v3 USM)."""
import hmac
import socket
import struct
import threading
from netbox_sync.core import snmp
from netbox_sync.core.snmp import (
AUTH_PROTOCOLS,
GET,
GET_BULK,
GET_NEXT,
INTEGER,
OCTET_STRING,
PRIV_PROTOCOLS,
REPORT,
RESPONSE,
TripleDES,
children,
dec_oid,
dec_value,
decode,
enc_int,
enc_oid,
enc_str,
localize,
oid_key,
password_to_key,
priv_key,
seq,
tlv,
)
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
ENGINE_ID = bytes.fromhex("80001f8880c71100000000000000000001")
def encode_value(value):
if isinstance(value, bool):
return enc_int(int(value))
if isinstance(value, int):
return enc_int(value)
if isinstance(value, tuple) and value[0] == "oid":
return enc_oid(value[1])
if isinstance(value, tuple) and value[0] == "ip":
return tlv(snmp.IP_ADDRESS, bytes(int(part) for part in value[1].split(".")))
if isinstance(value, tuple) and value[0] == "counter":
return enc_int(value[1], snmp.COUNTER32)
return enc_str(value)
class Agent:
def __init__(self, mib, community="public", users=None):
self.mib = {oid.strip("."): value for oid, value in mib.items()}
self.order = sorted(self.mib, key=oid_key)
self.community = community.encode()
self.users = users or {} # name -> credential record
self.boots, self.time = 3, 1000
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.port = self.sock.getsockname()[1]
self.requests = 0
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def close(self):
self.sock.close()
# MIB --------------------------------------------------------------
def _next(self, oid):
key = oid_key(oid)
return next((item for item in self.order if oid_key(item) > key), None)
def _bindings(self, pdu_type, oids, non_repeaters, repetitions):
result = []
if pdu_type == GET:
for oid in oids:
value = self.mib.get(oid)
result.append(seq(enc_oid(oid), encode_value(value) if value is not None
else tlv(snmp.NO_SUCH_OBJECT, b"")))
else:
count = repetitions if pdu_type == GET_BULK else 1
for oid in oids:
current = oid
for _ in range(max(1, count)):
nxt = self._next(current)
if nxt is None:
result.append(seq(enc_oid(current), tlv(snmp.END_OF_MIB_VIEW, b"")))
break
result.append(seq(enc_oid(nxt), encode_value(self.mib[nxt])))
current = nxt
return seq(*result)
def _response(self, request_id, bindings, kind=RESPONSE):
return tlv(kind, enc_int(request_id) + enc_int(0) + enc_int(0) + bindings)
@staticmethod
def _read_pdu(tag, content):
request_id, a, b, varbinds = children(content)
oids = [dec_oid(children(binding)[0][1]) for _t, binding in children(varbinds[1])]
return tag, dec_value(INTEGER, request_id[1]), dec_value(INTEGER, a[1]), dec_value(INTEGER, b[1]), oids
# serving ----------------------------------------------------------
def _serve(self):
while True:
try:
data, addr = self.sock.recvfrom(65535)
except OSError:
return
self.requests += 1
try:
answer = self._handle(data)
except Exception: # noqa: BLE001 - ignore garbage like a real agent
answer = None
if answer:
self.sock.sendto(answer, addr)
def _handle(self, data):
_tag, content, _pos = decode(data)
items = children(content)
version = dec_value(INTEGER, items[0][1])
if version == 1:
if items[1][1] != self.community:
return None
tag, request_id, a, b, oids = self._read_pdu(*items[2])
bindings = self._bindings(tag, oids, a, b)
return seq(enc_int(1), enc_str(self.community), self._response(request_id, bindings))
return self._handle_v3(data, items)
def _handle_v3(self, data, items):
_v, header, (_t, usm_raw), (data_tag, data_raw) = items
header_items = children(header[1])
msg_id = dec_value(INTEGER, header_items[0][1])
flags = header_items[2][1][0]
_t, usm_content, _p = decode(usm_raw)
engine_id, _boots, _time, user, auth_params, priv_params = (item[1] for item in children(usm_content))
user = bytes(user).decode()
def report(oid):
body = seq(enc_str(ENGINE_ID), enc_str(b""), self._response(
msg_id, seq(seq(enc_oid(oid), enc_int(1, snmp.COUNTER32))), REPORT))
usm = seq(enc_str(ENGINE_ID), enc_int(self.boots), enc_int(self.time), enc_str(user), enc_str(b""),
enc_str(b""))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(b"\x00"), enc_int(3)),
enc_str(usm), body)
if not engine_id:
return report("1.3.6.1.6.3.15.1.1.4.0")
record = self.users.get(user)
if record is None:
return report("1.3.6.1.6.3.15.1.1.3.0")
hash_func, size = AUTH_PROTOCOLS[record["auth_protocol"]]
auth_key = localize(password_to_key(record["auth_password"], hash_func), ENGINE_ID, hash_func)
position = data.find(auth_params)
zeroed = data[:position] + b"\x00" * len(auth_params) + data[position + len(auth_params):]
if not flags & 1 or hmac.new(auth_key, zeroed, hash_func).digest()[:size] != auth_params:
return report("1.3.6.1.6.3.15.1.1.5.0")
protocol = record.get("priv_protocol")
key = priv_key(record["priv_password"], ENGINE_ID, hash_func, PRIV_PROTOCOLS[protocol]) if protocol else None
if data_tag == OCTET_STRING:
plain = self._crypt(protocol, key, bytes(data_raw), bytes(priv_params), _boots, _time, decrypt=True)
_t, scoped, _p = decode(plain)
else:
scoped = data_raw
_ce, _cn, pdu = children(scoped)
tag, request_id, a, b, oids = self._read_pdu(*pdu)
scoped_out = seq(enc_str(ENGINE_ID), enc_str(b""), self._response(request_id, self._bindings(tag, oids, a, b)))
salt = b""
if protocol:
salt = struct.pack(">Q", 99) if protocol != "DES" else struct.pack(">II", self.boots, 77)
encrypted = self._crypt(protocol, key, scoped_out, salt, dec_value(INTEGER, enc_int(self.boots)[2:]),
self.time, decrypt=False)
body = enc_str(encrypted)
else:
body = scoped_out
out_flags = flags & 0x03
def build(params):
usm = seq(enc_str(ENGINE_ID), enc_int(self.boots), enc_int(self.time), enc_str(user), enc_str(params),
enc_str(salt))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(bytes([out_flags])), enc_int(3)),
enc_str(usm), body)
packet = build(b"\x00" * size)
return build(hmac.new(auth_key, packet, hash_func).digest()[:size])
@staticmethod
def _crypt(protocol, key, data, salt, boots, engine_time, decrypt):
if protocol == "DES":
iv = bytes(a ^ b for a, b in zip(key[8:16], salt))
cipher = Cipher(TripleDES(key[:8] * 3), modes.CBC(iv))
if not decrypt:
data += b"\x00" * (-len(data) % 8)
else:
boots = boots if isinstance(boots, int) else dec_value(INTEGER, boots)
engine_time = engine_time if isinstance(engine_time, int) else dec_value(INTEGER, engine_time)
return snmp.aes_cfb(key, struct.pack(">II", boots, engine_time) + salt, data, decrypt)
worker = cipher.decryptor() if decrypt else cipher.encryptor()
return worker.update(data) + worker.finalize()
+148
View File
@@ -0,0 +1,148 @@
from types import SimpleNamespace
import pytest
from fake_netbox import FakeNetBox, Record
from snmp_agent import Agent
from netbox_sync.core import printers, snmp
from netbox_sync.core.printers import PrinterSyncEngine, printer_key, read_printer, supplies_text, to_import
IP = "10.20.0.50"
MIB = {
printers.SYS_DESCR: "HP ETHERNET MULTI-ENVIRONMENT,ROM none,JETDIRECT,JD153,EEPROM JSI24090012",
printers.SYS_OBJECT_ID: ("oid", "1.3.6.1.4.1.11.2.3.9.1"),
printers.SYS_NAME: "NPI1A2B3C",
printers.SYS_LOCATION: "Geschäftsstelle 1. OG",
printers.SYS_CONTACT: "IT",
f"{printers.HR_DEVICE_TYPE}.1": ("oid", printers.HR_PRINTER),
f"{printers.HR_DEVICE_TYPE}.2": ("oid", "1.3.6.1.2.1.25.3.1.4"),
f"{printers.HR_DEVICE_DESCR}.1": "HP Color LaserJet Pro M454dw",
f"{printers.HR_PRINTER_STATUS}.1": 3,
f"{printers.HR_PRINTER_ERRORS}.1": b"\x20\x00", # low toner
f"{printers.PRT_SERIAL}.1": "vnb3k12345",
f"{printers.PRT_LIFE_COUNT}.1.1": ("counter", 48211),
f"{printers.PRT_SUPPLIES}.3.1.1": 1, f"{printers.PRT_SUPPLIES}.3.1.2": 2,
f"{printers.PRT_SUPPLIES}.5.1.1": 21, f"{printers.PRT_SUPPLIES}.5.1.2": 21,
f"{printers.PRT_SUPPLIES}.6.1.1": "Black Cartridge HP W2030A",
f"{printers.PRT_SUPPLIES}.6.1.2": "Cyan Cartridge HP W2031A",
f"{printers.PRT_SUPPLIES}.8.1.1": 2400, f"{printers.PRT_SUPPLIES}.8.1.2": 100,
f"{printers.PRT_SUPPLIES}.9.1.1": 600, f"{printers.PRT_SUPPLIES}.9.1.2": -3,
f"{printers.PRT_COLORANT}.1.1": "black", f"{printers.PRT_COLORANT}.1.2": "cyan",
f"{printers.PRT_INPUT}.9.1.2": 250, f"{printers.PRT_INPUT}.10.1.2": 120,
f"{printers.PRT_INPUT}.13.1.2": "Fach 2",
f"{printers.PRT_DISPLAY}.1.1": "Bereit",
f"{printers.IF_TABLE}.2.2": "eth0", f"{printers.IF_TABLE}.3.2": 6,
f"{printers.IF_TABLE}.6.2": bytes.fromhex("a0b1c2d3e4f5"),
f"{printers.IP_ADDR_IFINDEX}.{IP}": 2,
f"{printers.IP_ADDR_MASK}.{IP}": ("ip", "255.255.255.0"),
"1.3.6.1.2.1.47.1.1.1.1.10.1": "20240115",
}
USER = {"version": "3", "username": "scan", "auth_protocol": "SHA", "auth_password": "authpass123",
"priv_protocol": "AES", "priv_password": "privpass123"}
@pytest.fixture
def agent():
instance = Agent(MIB, community="geheim", users={"scan": USER})
yield instance
instance.close()
def _client(agent, record):
return snmp.SnmpClient("127.0.0.1", record, timeout=0.5, retries=0, port=agent.port)
def test_v2c_get_and_walk(agent):
client = _client(agent, {"version": "2c", "community": "geheim"})
assert client.get([printers.SYS_NAME])[printers.SYS_NAME] == b"NPI1A2B3C"
walked = client.walk(printers.PRT_SUPPLIES)
assert len(walked) == 10 and all(snmp.in_subtree(oid, printers.PRT_SUPPLIES) for oid in walked)
with pytest.raises(snmp.SnmpTimeout):
_client(agent, {"version": "2c", "community": "public"}).get([printers.SYS_NAME])
@pytest.mark.parametrize("auth, priv", [("SHA", "AES"), ("MD5", "DES"), ("SHA-256", "AES-256"), ("SHA-512", ""),
("SHA-224", "AES-192")])
def test_v3_auth_and_privacy(auth, priv):
record = dict(USER, auth_protocol=auth, priv_protocol=priv)
agent = Agent(MIB, users={"scan": record})
try:
client = _client(agent, record)
assert client.get([printers.SYS_NAME])[printers.SYS_NAME] == b"NPI1A2B3C"
assert len(client.walk(printers.PRT_SUPPLIES)) == 10
finally:
agent.close()
def test_connect_tries_all_credentials_and_explains_v3_errors(agent):
wrong_v3 = dict(USER, id="b", auth_password="falsch-falsch")
client, notes = snmp.connect("127.0.0.1", [{"id": "a", "version": "2c", "community": "public"}, wrong_v3,
dict(USER, id="c")], timeout=0.3, retries=0, port=agent.port)
assert client.credential.record["id"] == "c"
assert notes == ["SNMPv3 scan: falsches Authentifizierungs-Passwort oder -Protokoll"]
with pytest.raises(snmp.SnmpAuthError, match="unbekannter Benutzer"):
snmp.connect("127.0.0.1", [dict(USER, username="nobody")], timeout=0.3, retries=0, port=agent.port)
def test_printer_data_is_read_from_standard_mibs(agent):
info = read_printer(_client(agent, {"version": "2c", "community": "geheim"}), IP)
assert info["manufacturer"] == "HP" and info["model"] == "Color LaserJet Pro M454dw"
assert info["serial"] == "VNB3K12345" and info["mac"] == "A0:B1:C2:D3:E4:F5" and info["prefix_length"] == 24
assert info["page_count"] == 48211 and info["color"] is True and info["firmware"] == "20240115"
assert info["site_hint"] == "Geschäftsstelle 1. OG" and info["status"] == "bereit"
assert info["errors"] == ["wenig Toner"] and info["display"] == ["Bereit"]
assert info["trays"] == [{"name": "Fach 2", "media": "", "capacity": 250, "level": "120/250 Blatt"}]
assert supplies_text(info["supplies"]) == "Black Cartridge HP W2030A: 25 %\nCyan Cartridge HP W2031A: vorhanden"
def test_non_printer_is_ignored():
agent = Agent({printers.SYS_NAME: "switch", printers.SYS_OBJECT_ID: ("oid", "1.3.6.1.4.1.9.1.1")})
try:
assert read_printer(_client(agent, {"version": "2c", "community": "public"}), IP) is None
finally:
agent.close()
def _netbox():
nb = FakeNetBox()
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=7, name="Kunde", group=None))
nb.dcim.sites.records.append(Record(nb.dcim.sites, id=21, name="Geschäftsstelle", tenant=SimpleNamespace(id=7)))
nb.dcim.device_roles.records.append(Record(nb.dcim.device_roles, id=31, name="Drucker"))
old = Record(nb.dcim.devices, id=201, name="Drucker EG", serial="", tenant=SimpleNamespace(id=7),
role=SimpleNamespace(id=31), site=SimpleNamespace(id=21), description="", primary_ip4=None,
custom_fields={"printer_page_count": 100})
nb.dcim.devices.records.append(old)
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=301, name="eth0", device=old, mac_address=None))
nb.ipam.ip_addresses.records.append(Record(nb.ipam.ip_addresses, id=401, address="10.20.0.60/24", vrf=None,
assigned_object_type="dcim.interface",
assigned_object=SimpleNamespace(id=301, device=SimpleNamespace(id=201)),
assigned_object_id=301, tenant=None))
return nb
def test_sync_creates_fields_and_printers_and_updates_counters(agent):
info = read_printer(_client(agent, {"version": "2c", "community": "geheim"}), IP)
new = to_import(dict(info, ip=IP, snmp="SNMPv2c", notes=[]))
known = to_import(dict(info, ip="10.20.0.60", snmp="SNMPv2c", notes=[], serial="", mac="",
name="Drucker EG", page_count=200))
nb = _netbox()
engine = PrinterSyncEngine(nb, role_id=31)
engine.load_context(7)
items = [new, known]
engine.match(items)
assert known["method"] in ("Name", "IP-Adresse") and new.get("device") is None
preview = engine.sync(items, {printer_key(new): {"site": 21, "tenant": 7}}, role_id=31, dry_run=True)
assert preview["errors"] == [] and nb.extras.custom_fields.created == []
assert any("Seitenzähler" in change for change in preview["changes"])
report = engine.sync(items, {printer_key(new): {"site": 21, "tenant": 7}}, role_id=31, dry_run=False)
assert report["errors"] == []
assert {field["name"] for field in nb.extras.custom_fields.created} == {name for name, *_ in printers.CUSTOM_FIELDS}
created = nb.dcim.devices.created[-1]
assert created["name"] == "NPI1A2B3C" and created["serial"] == "VNB3K12345" and "platform" not in created
assert created["custom_fields"]["printer_page_count"] == 48211 and created["custom_fields"]["printer_color"]
assert nb.dcim.manufacturers.created[0]["name"] == "HP"
assert nb.dcim.device_types.created[0]["model"] == "Color LaserJet Pro M454dw"
assert nb.ipam.ip_addresses.created[-1]["address"] == f"{IP}/24"
assert nb.dcim.devices.get(201).custom_fields["printer_page_count"] == 200