my-homelab-configs/scripts/monitoring-exporter-access.py

244 lines
12 KiB
Python

#!/usr/bin/env python3
"""Repair narrowly identified exporter access rules; never flush host firewalls."""
import argparse
import ipaddress
import json
from pathlib import Path
import shlex
import shutil
import subprocess
def run(args):
return subprocess.check_output(args, text=True, timeout=90)
def retired_rules(text):
"""Only stale CNI per-port rules, leaving shared HTTP/HTTPS rules intact."""
parsed = [shlex.split(line) for line in text.splitlines()]
owned = {t[t.index('-j') + 1] for t in parsed
if len(t) > 2 and t[:2] == ['-A', 'CNI-HOSTPORT-DNAT']
and '-j' in t and 'k8s-pod-network' in ' '.join(t)}
result = []
for tokens in parsed:
if (len(tokens) > 3 and tokens[0] == '-A' and tokens[1].startswith('CNI-DN-') and tokens[1] in owned
and '--dport' in tokens and tokens[tokens.index('--dport') + 1] == '9100'):
result.append(tokens)
return result
def host():
for service in ('k3s', 'k3s-agent', 'kubelet'):
active = subprocess.run(['systemctl', 'is-active', '--quiet', service]).returncode == 0
if active:
print('Active Kubernetes runtime; CNI rules left untouched.')
return
processes = run(['ps', '-eo', 'comm=']).splitlines()
if any(p.strip() in ('k3s', 'kubelet', 'k3s-server', 'k3s-agent') for p in processes):
raise RuntimeError('Kubernetes runtime process still present; refusing CNI cleanup')
# A retired node's saved hostPort DNAT can shadow an otherwise healthy listener.
for binary in ('iptables', 'iptables-legacy'):
executable = shutil.which(binary) or '/usr/sbin/' + binary
if not Path(executable).exists():
continue
listing = subprocess.run(['sudo', '-n', executable, '-t', 'nat', '-S'], capture_output=True, text=True)
if listing.returncode:
continue
candidates = retired_rules(listing.stdout)
if not candidates:
continue
directory = Path.home() / '.local/share/homelab/exporter-backups'
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
from datetime import datetime, timezone
backup = directory / (datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%f') + '-' + binary + '.rules')
backup.write_text(listing.stdout)
backup.chmod(0o600)
for tokens in candidates:
run(['sudo', '-n', executable, '-w', '5', '-t', 'nat', '-D', *tokens[1:]])
print(f'Removed {len(candidates)} retired TCP/9100 CNI rules ({binary}); HTTP/HTTPS rules preserved. Backup: {backup}')
def email_rules(state):
found = {}
for resource in state.get('resources', []):
if resource.get('mode', 'managed') != 'managed' or resource.get('type') != 'oci_core_network_security_group_security_rule':
continue
for instance in resource.get('instances', []):
if resource['name'] in ('email_ssh', 'email_monitoring') and not instance.get('deposed'):
if resource['name'] in found:
raise ValueError('Ambiguous managed email access rule')
found[resource['name']] = instance['attributes']
if set(found) != {'email_ssh', 'email_monitoring'}:
raise ValueError('Both managed email NSG rules must be present in foundation state')
if len({rule['network_security_group_id'] for rule in found.values()}) != 1:
raise ValueError('Email access rules belong to different NSGs')
return found
def public_source(cidr):
network = ipaddress.ip_network(cidr)
if network.version != 4 or network.prefixlen != 32 or not network.network_address.is_global:
raise ValueError('Email access requires the current public IPv4 /32')
return str(network)
def email_firewall(cidr):
cidr = public_source(cidr)
binary = '/usr/sbin/iptables'
listing = run([binary, '-t', 'filter', '-S', 'INPUT'])
owned = []
for line in listing.splitlines():
tokens = shlex.split(line)
if ('--comment' in tokens and tokens[tokens.index('--comment') + 1] == 'jeannie-email-exporter'
and '--dport' in tokens and tokens[tokens.index('--dport') + 1] == '9100'):
owned.append(tokens)
desired = ['-A', 'INPUT', '-s', cidr, '-p', 'tcp', '-m', 'tcp', '--dport', '9100',
'-m', 'comment', '--comment', 'jeannie-email-exporter', '-j', 'ACCEPT']
if owned == [desired] and listing.splitlines()[1:2] == [shlex.join(desired)]:
return
for tokens in owned:
run([binary, '-w', '5', '-D', *tokens[1:]])
run([binary, '-w', '5', '-I', 'INPUT', '1', *desired[2:]])
print('Email exporter INPUT allowance installed before the image default REJECT.')
def email_host(cidr):
cidr = public_source(cidr)
import os
if os.geteuid() != 0:
raise RuntimeError('Email host firewall setup requires sudo')
destination = Path('/usr/local/lib/jeannie/monitoring-exporter-access.py')
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(__file__, destination)
destination.chmod(0o755)
unit = ('[Unit]\nDescription=Jeannie restricted email exporter access\n'
'After=ufw.service netfilter-persistent.service\nBefore=prometheus-node-exporter.service\n'
'[Service]\nType=oneshot\nRemainAfterExit=yes\n'
f'ExecStart=/usr/bin/python3 {destination} email-firewall --cidr {cidr}\n'
'[Install]\nWantedBy=multi-user.target\n')
Path('/etc/systemd/system/jeannie-email-exporter-access.service').write_text(unit)
run(['ufw', 'allow', 'from', cidr, 'to', 'any', 'port', '9100', 'proto', 'tcp'])
run(['systemctl', 'daemon-reload'])
run(['systemctl', 'enable', 'jeannie-email-exporter-access.service'])
run(['systemctl', 'restart', 'jeannie-email-exporter-access.service'])
run(['systemctl', 'enable', '--now', 'prometheus-node-exporter'])
print('Email exporter service and persistent restricted firewall access reconciled.')
def email(state_path, cidr, cli):
cidr = public_source(cidr)
rules = email_rules(json.loads(Path(state_path).read_text()))
nsg = next(iter(rules.values()))['network_security_group_id']
def oci(*args):
return json.loads(run([cli, 'network', 'nsg', 'rules', *args, '--nsg-id', nsg, '--output', 'json']))['data']
actual = {r['id']: r for r in oci('list', '--all')}
updates = []
previous = []
for name, recorded in rules.items():
rule = actual[recorded['id']]
port = 22 if name == 'email_ssh' else 9100
if (rule.get('direction') != 'INGRESS' or rule.get('protocol') != '6' or
rule.get('source-type') != 'CIDR_BLOCK' or
rule.get('tcp-options', {}).get('destination-port-range') != {'min': port, 'max': port}):
raise ValueError('Live email access rule no longer matches its managed role')
if rule['source'] == cidr:
continue
previous.append(rule)
updates.append({'id': rule['id'], 'direction': 'INGRESS', 'protocol': '6',
'source': cidr, 'sourceType': 'CIDR_BLOCK',
'isStateless': rule.get('is-stateless', False),
'tcpOptions': {'destinationPortRange': {'min': port, 'max': port}}})
if rule.get('description'):
updates[-1]['description'] = rule['description']
if rule.get('tcp-options', {}).get('source-port-range'):
updates[-1]['tcpOptions']['sourcePortRange'] = rule['tcp-options']['source-port-range']
if updates:
directory = Path.home() / '.local/share/homelab/exporter-backups'
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
import time
backup = directory / f'email-nsg-{time.time_ns()}.json'
backup.write_text(json.dumps(previous, indent=2)); backup.chmod(0o600)
oci('update', '--security-rules', json.dumps(updates))
print(f'Updated only managed email SSH/exporter NSG rules to {cidr}; backup: {backup}')
else:
print('Managed email SSH/exporter NSG rules already match the Debian public IPv4.')
def healthy_targets():
import urllib.request
with urllib.request.urlopen('http://127.0.0.1:19090/api/v1/targets', timeout=15) as response:
return {t['scrapePool']: t for t in json.load(response)['data']['activeTargets']}
def reconcile(root):
"""Used by apply and the installed refresh timer, without a source checkout."""
import importlib.util
import time
import urllib.request
root = Path(root)
settings = json.loads((root / 'exporter-settings.json').read_text())
spec = importlib.util.spec_from_file_location('foundation', root / 'oci-foundation-resolve.py')
foundation = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foundation)
config = Path(settings['config'])
names = set(settings['names'])
run(['bash', str(root / 'monitoring-host-exporter.sh')])
with foundation.config_lock(config):
values = foundation.read_config(config, names)
enabled = values.get('LAB_OCI_EMAIL_ENABLED', 'false').lower() in ('true', '1', 'yes')
expected = {'debian-host'}
if enabled:
expected.add('oci-email-node')
with urllib.request.urlopen('https://api.ipify.org', timeout=15) as response:
cidr = public_source(response.read().decode().strip() + '/32')
state = values.get('LAB_OCI_FOUNDATION_STATE_FILE')
if not state or not Path(state).is_absolute():
raise RuntimeError('Automatic exporter repair requires an absolute canonical foundation state path')
foundation.recorded(values, foundation.read_state(Path(state)))
target = healthy_targets().get('oci-email-node', {})
unchanged = all(values.get(name) == cidr for name in
('LAB_OCI_EMAIL_ADMIN_CIDR', 'LAB_OCI_EMAIL_MONITORING_CIDR'))
# Healthy targets need checks, not repeated SSH/systemd/OCI updates.
repair_email = not (target.get('health') == 'up' and unchanged)
if repair_email:
email(state, cidr, settings['cli'])
values.update(LAB_OCI_EMAIL_ADMIN_CIDR=cidr, LAB_OCI_EMAIL_MONITORING_CIDR=cidr)
foundation.atomic_write(config, foundation.config_text({k: v for k, v in values.items() if k in names}))
email_ip = values.get('LAB_EMAIL_PUBLIC_IP')
ipaddress.IPv4Address(email_ip)
if enabled and repair_email:
command = ('temporary=$(mktemp /tmp/jeannie-email-exporter.XXXXXX.py); '
'trap \'rm -f "$temporary"\' EXIT; cat >"$temporary"; '
'sudo -n python3 "$temporary" email-host --cidr ' + shlex.quote(cidr))
key = settings['ssh_key']
user = settings['ssh_user']
subprocess.run(['ssh', '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10',
'-i', key, user + '@' + email_ip, command],
input=Path(__file__).read_bytes(), check=True, timeout=120)
deadline = time.monotonic() + 90
while True:
targets = healthy_targets()
if all(targets.get(name, {}).get('health') == 'up' for name in expected):
print('Exporter checks: ' + ', '.join(name + '=UP' for name in sorted(expected)))
return
if time.monotonic() >= deadline:
raise RuntimeError('Prometheus has not confirmed expected exporter targets UP')
time.sleep(5)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['host', 'email', 'email-host', 'email-firewall', 'reconcile'])
parser.add_argument('--root'); parser.add_argument('--state'); parser.add_argument('--cidr'); parser.add_argument('--cli')
args = parser.parse_args()
if args.action == 'reconcile':
reconcile(args.root)
elif args.action == 'host':
host()
elif args.action == 'email-host':
email_host(args.cidr)
elif args.action == 'email-firewall':
email_firewall(args.cidr)
else:
email(args.state, args.cidr, args.cli)