Development

This commit is contained in:
Matthew Grotke 2026-06-01 12:58:06 -04:00
parent 6f23a57220
commit 4f5f2a8071
5 changed files with 157 additions and 9 deletions

View file

@ -828,5 +828,10 @@
"redirect_to": "192.168.40.1",
"vlan": "vpn"
}
]
],
"radius_options": {
"mac_format": "aabbccddeeff",
"apply_to": "all",
"logging": false
}
}

View file

@ -1825,6 +1825,8 @@ def remove_nat_service():
RADIUS_SECRET_FILE = SCRIPT_DIR / ".radius-secret"
RADIUS_CLIENTS_CONF = Path("/etc/freeradius/3.0/clients.conf")
RADIUS_USERS_FILE = Path("/etc/freeradius/3.0/users")
RADIUS_CONF_FILE = Path("/etc/freeradius/3.0/radiusd.conf")
RADIUS_LOG_FILE = Path("/var/log/freeradius/radius.log")
def radius_clients(data):
"""Return list of (reservation, vlan) tuples where radius_client is True."""
@ -1877,12 +1879,26 @@ def build_radius_clients_conf(data, secret):
]
return "\n".join(lines)
def _fmt_mac(raw, fmt):
c = raw.replace(':', '').replace('-', '').lower()
pairs = [c[i:i+2] for i in range(0, 12, 2)]
upper = fmt[0].isupper()
if fmt in ('aabbccddeeff', 'AABBCCDDEEFF'):
sep = ''
elif fmt in ('aa-bb-cc-dd-ee-ff', 'AA-BB-CC-DD-EE-FF'):
sep = '-'
else:
sep = ':'
joined = sep.join(pairs)
return joined.upper() if upper else joined
def build_radius_users(data):
"""
Generate freeradius users file.
Each MAC reservation across all VLANs gets an entry mapping it to its VLAN ID.
Unknown MACs fall through to DEFAULT which returns the radius_default VLAN.
MACs are formatted without colons (FreeRADIUS MAB format).
MAC format and DEFAULT rule scope are read from radius_options in config.
"""
default_vlan = next(
(v for v in data["vlans"] if v.get("radius_default") is True), None
@ -1890,6 +1906,10 @@ def build_radius_users(data):
if default_vlan is None:
die("No VLAN has radius_default: true. Cannot generate RADIUS users file.")
opts = data.get('radius_options', {})
mac_fmt = opts.get('mac_format', 'aabbccddeeff')
apply_to = opts.get('apply_to', 'all')
lines = [
"# Generated by core.py -- do not edit manually.",
"# Edit config.json and re-run: sudo python3 core.py --apply",
@ -1900,12 +1920,13 @@ def build_radius_users(data):
for r in data.get("dhcp_reservations", []):
if r.get("enabled") is not True:
continue
mac = r.get("mac", "").replace(":", "").lower()
if not mac:
raw_mac = r.get("mac", "")
if not raw_mac:
continue
vlan = vlan_by_name.get(r.get("vlan", ""))
if not vlan:
continue
mac = _fmt_mac(raw_mac, mac_fmt)
vlan_id = vlan.get('vlan_id')
lines += [
f"# {r['description']} -> VLAN {vlan_id} ({vlan['name']})",
@ -1916,10 +1937,15 @@ def build_radius_users(data):
"",
]
default_id = default_vlan.get('vlan_id')
default_id = default_vlan.get('vlan_id')
default_check = (
"DEFAULT NAS-Port-Type = Wireless-802.11, Auth-Type := Accept"
if apply_to == 'wireless'
else "DEFAULT Auth-Type := Accept"
)
lines += [
f"# Default -- unknown MACs land on VLAN {default_id} ({default_vlan['name']})",
"DEFAULT Auth-Type := Accept",
default_check,
f" Tunnel-Type = VLAN,",
f" Tunnel-Medium-Type = IEEE-802,",
f" Tunnel-Private-Group-Id = \"{default_id}\"",
@ -1928,6 +1954,24 @@ def build_radius_users(data):
return "\n".join(lines)
def _set_freeradius_log(enabled):
"""Enable or disable auth logging lines in radiusd.conf."""
if not RADIUS_CONF_FILE.exists():
return False
import re
value = 'yes' if enabled else 'no'
content = RADIUS_CONF_FILE.read_text()
updated = re.sub(r'(?m)^(\s*auth\s*=\s*)(yes|no)', rf'\g<1>{value}', content)
updated = re.sub(r'(?m)^(\s*auth_accept\s*=\s*)(yes|no)', rf'\g<1>{value}', updated)
updated = re.sub(r'(?m)^(\s*auth_reject\s*=\s*)(yes|no)', rf'\g<1>{value}', updated)
if updated == content:
print(f"radiusd.conf: auth logging already {'enabled' if enabled else 'disabled'}.")
return False
RADIUS_CONF_FILE.write_text(updated)
print(f"radiusd.conf: auth logging {'enabled' if enabled else 'disabled'}.")
return True
def apply_radius(data):
"""Write FreeRADIUS config files and restart the service."""
secret = ensure_radius_secret()
@ -1935,7 +1979,10 @@ def apply_radius(data):
clients_content = build_radius_clients_conf(data, secret)
users_content = build_radius_users(data)
changed = False
opts = data.get('radius_options', {})
logging = opts.get('logging', False)
changed = _set_freeradius_log(logging)
for path, content in [(RADIUS_CLIENTS_CONF, clients_content),
(RADIUS_USERS_FILE, users_content)]:
existing = path.read_text() if path.exists() else None