Repository navigation
feat(threat shield): join insights block list #1887
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| #!/bin/sh | ||
|
|
||
| # | ||
| # Copyright (C) 2026 Nethesis S.r.l. | ||
| # SPDX-License-Identifier: GPL-2.0-only | ||
| # | ||
|
|
||
| # Registered units: run ts-ip after an update to add the Insights hook and feed definition. | ||
| # ts-ip preserves a custom block hook, so it runs unless the Insights hook is already set. | ||
|
|
||
| [ -n "$(uci -q get ns-plug.config.secret)" ] || exit 0 | ||
| [ "$(uci -q get banip.global.ban_blockhook)" = "/usr/libexec/ts-insights-hook" ] && exit 0 | ||
|
|
||
| /usr/sbin/ts-ip | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
packages/ns-threat_shield/files/send-insights-blocklist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| #!/usr/bin/python3 | ||
| # | ||
| # Copyright (C) 2026 Nethesis S.r.l. | ||
| # SPDX-License-Identifier: GPL-2.0-only | ||
| # | ||
|
|
||
| # Send the IPs blocked by banip, spooled by ts-insights-hook, to Nethesis Insights. | ||
| # Run by cron, does nothing if the unit is not registered. | ||
| # Only the errors dropping events are logged, unless banip.global.ban_debug is set. | ||
|
|
||
| import base64 | ||
| import http.client | ||
| import ipaddress | ||
| import json | ||
| import os | ||
| import syslog | ||
| import urllib.request | ||
|
|
||
| from euci import EUci | ||
|
|
||
| SPOOL_DIR = "/var/run/ns-insights" | ||
| SPOOL = os.path.join(SPOOL_DIR, "threat-events.jsonl") | ||
| SENDING = SPOOL + ".sending" | ||
|
|
||
| DEFAULT_URL = "https://insights.nethesis.it/blocklist/v1/events" | ||
| MAX_DECISIONS_PER_REQUEST = 500 | ||
| MAX_SPOOLED_EVENTS = 5000 | ||
| TIMEOUT = 20 | ||
|
|
||
|
|
||
| def read_config(uci): | ||
| """Return (url, system_id, secret), or None if the unit is not registered.""" | ||
| system_id = uci.get("ns-plug", "config", "system_id", default="") | ||
| secret = uci.get("ns-plug", "config", "secret", default="") | ||
| if not system_id or not secret: | ||
| return None | ||
|
|
||
| url = uci.get("ns-plug", "config", "insights_blocklist_url", default=DEFAULT_URL) | ||
|
|
||
| return url, system_id, secret | ||
|
|
||
|
|
||
| def read_spool(): | ||
| """Take the spooled lines and remove the spool file.""" | ||
| if not os.path.exists(SPOOL): | ||
| return [] | ||
|
|
||
| # move the file first, so the hook can keep writing a new one | ||
| os.rename(SPOOL, SENDING) | ||
| with open(SENDING) as spool: | ||
| lines = spool.readlines() | ||
| os.unlink(SENDING) | ||
|
|
||
| return lines | ||
|
|
||
|
|
||
| def is_reportable(value): | ||
| """Only public addresses are sent.""" | ||
| try: | ||
| return ipaddress.ip_address(value).is_global | ||
| except ValueError: | ||
| return False | ||
|
|
||
|
|
||
| def parse_events(lines): | ||
| """Return the valid and reportable decisions, the most recent ones if over the cap.""" | ||
| decisions = [] | ||
|
|
||
| for line in lines: | ||
| line = line.strip() | ||
| if not line: | ||
| continue | ||
| try: | ||
| decision = json.loads(line) | ||
| value = decision["value"] | ||
| except (ValueError, KeyError, TypeError): | ||
| continue | ||
|
|
||
| if is_reportable(value): | ||
| decisions.append(decision) | ||
|
|
||
| if len(decisions) > MAX_SPOOLED_EVENTS: | ||
| syslog.syslog( | ||
| syslog.LOG_DEBUG, | ||
| f"too many events, dropped the {len(decisions) - MAX_SPOOLED_EVENTS} oldest", | ||
| ) | ||
| decisions = decisions[-MAX_SPOOLED_EVENTS:] | ||
|
|
||
| return decisions | ||
|
|
||
|
|
||
| def send_batch(config, decisions): | ||
| """Post a batch of decisions, any 2xx response means they are queued.""" | ||
| url, system_id, secret = config | ||
| payload = json.dumps( | ||
| {"schema_version": 1, "system_id": system_id, "decisions": decisions} | ||
| ).encode() | ||
| credentials = base64.b64encode(f"{system_id}:{secret}".encode()).decode() | ||
| request = urllib.request.Request( | ||
| url, | ||
| data=payload, | ||
| method="POST", | ||
| headers={ | ||
| "Content-Type": "application/json", | ||
| "Authorization": f"Basic {credentials}", | ||
| }, | ||
| ) | ||
|
|
||
| with urllib.request.urlopen(request, timeout=TIMEOUT) as response: | ||
| response.read() | ||
|
|
||
|
|
||
| def main(): | ||
| syslog.openlog("send-insights-blocklist") | ||
|
|
||
| uci = EUci() | ||
| debug = uci.get("banip", "global", "ban_debug", default="0") == "1" | ||
| syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG if debug else syslog.LOG_ERR)) | ||
|
|
||
| config = read_config(uci) | ||
| if config is None: | ||
| return | ||
|
|
||
| decisions = parse_events(read_spool()) | ||
| sent = 0 | ||
| for index in range(0, len(decisions), MAX_DECISIONS_PER_REQUEST): | ||
| batch = decisions[index : index + MAX_DECISIONS_PER_REQUEST] | ||
| try: | ||
| send_batch(config, batch) | ||
| except (http.client.HTTPException, OSError) as error: | ||
| syslog.syslog( | ||
| syslog.LOG_ERR, | ||
| f"push failed, dropped {len(decisions) - index} events: {error}", | ||
| ) | ||
| break | ||
|
|
||
| sent += len(batch) | ||
|
|
||
| if sent: | ||
| syslog.syslog(syslog.LOG_DEBUG, f"pushed {sent} events") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| #!/bin/sh | ||
|
|
||
| # | ||
| # Copyright (C) 2026 Nethesis S.r.l. | ||
| # SPDX-License-Identifier: GPL-2.0-only | ||
| # | ||
|
|
||
| # banip ban_blockhook: append a blocked IP to the spool, send-insights-blocklist sends it. | ||
| # Args: $1 IP; the other banip args ($2 family, $3 log count, $4 Set expiry) are not used | ||
|
|
||
| SPOOL_DIR="/var/run/ns-insights" | ||
| SPOOL="${SPOOL_DIR}/threat-events.jsonl" | ||
|
|
||
| [ -n "$1" ] || exit 0 | ||
|
|
||
| [ -d "${SPOOL_DIR}" ] || mkdir -p "${SPOOL_DIR}" | ||
|
|
||
| printf '{"value":"%s","scope":"Ip","type":"ban","scenario":"nethsecurity/banip-log","origin":"banip","created_at":"%s"}\n' \ | ||
| "$1" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" >>"${SPOOL}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| #!/bin/sh | ||
|
|
||
| # | ||
| # Copyright (C) 2026 Nethesis S.r.l. | ||
| # SPDX-License-Identifier: GPL-2.0-only | ||
| # | ||
|
|
||
| # ns-plug register/unregister hook: ts-ip does not reload banip, since it also runs during upgrades | ||
|
|
||
| /usr/sbin/ts-ip | ||
| # the banip log service reads the hook, the feeds and the allowlist only on start | ||
| /etc/init.d/banip reload | ||
| exit 0 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.