Push Tracker
ria-ran--sim-drop/server/utils.py
A ashkan@beigi.net 8672b0de6b Add Phase-1 eSIM provisioning implementation
Full working closed-loop eSIM provisioning stack (spec in claude.md / plan/):
Flask API, SQLite subscriber store, credential/profile generator, Open5GS
and free5gc core adapters, captive portal, operational scripts, systemd
units, network configs, and a 44-test suite.

Profile generation currently returns a mock JSON profile; real SGP.22
generation via pySim is the planned Phase-2 upgrade.

Fixes two bugs found while getting the suite green:
- generate_imsi hardcoded a 10-digit MSIN, producing 16-digit IMSIs for a
  3-digit MNC; MSIN length is now 15 - len(mcc) - len(mnc).
- check_rate_limit compared timestamps as strings across mismatched formats
  (SQLite CURRENT_TIMESTAMP vs Python isoformat); both sides now normalized
  via SQLite datetime() so the window check is chronologically correct.

Add .gitignore for venv, caches, runtime config.yaml, and databases.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 05:56:31 +00:00

78 lines
2.2 KiB
Python

import os
import re
import logging
from typing import Optional
import yaml
logger = logging.getLogger(__name__)
_MAC_RE = re.compile(r"^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$")
_REQUIRED_CONFIG_KEYS = ["network", "server", "database", "rate_limiting", "profile"]
def validate_mac(mac: str) -> bool:
"""Return True if mac is a valid colon-separated MAC address."""
return bool(mac and _MAC_RE.match(mac))
def normalize_mac(mac: str) -> str:
"""Return a lowercase, colon-separated MAC address.
Accepts input with dashes, dots, or no separators.
"""
clean = mac.lower().replace("-", ":").replace(".", ":")
# Handle 12-char no-separator format
if ":" not in clean and len(clean) == 12:
clean = ":".join(clean[i : i + 2] for i in range(0, 12, 2))
return clean
def validate_imsi(imsi: str) -> bool:
"""Return True if imsi is exactly 15 decimal digits."""
return bool(imsi) and imsi.isdigit() and len(imsi) == 15
def load_config(path: str) -> dict:
"""Load and minimally validate a YAML config file."""
if not os.path.exists(path):
raise FileNotFoundError(f"Config file not found: {path}")
with open(path) as f:
cfg = yaml.safe_load(f)
for key in _REQUIRED_CONFIG_KEYS:
if key not in cfg:
raise ValueError(f"Missing required config section: '{key}'")
return cfg
def hex_to_bytes(h: str) -> bytes:
return bytes.fromhex(h)
def bytes_to_hex(b: bytes) -> str:
return b.hex()
def get_client_ip(request) -> str:
"""Return the real client IP, respecting X-Forwarded-For from nginx."""
forwarded = request.headers.get("X-Forwarded-For")
if forwarded:
return forwarded.split(",")[0].strip()
return request.remote_addr or ""
def get_mac_from_arp(ip: str) -> Optional[str]:
"""Attempt to resolve a MAC address from /proc/net/arp for the given IP."""
try:
with open("/proc/net/arp") as f:
for line in f:
parts = line.split()
if len(parts) >= 4 and parts[0] == ip:
mac = parts[3]
if validate_mac(mac):
return normalize_mac(mac)
except Exception as exc:
logger.debug(f"ARP lookup failed for {ip}: {exc}")
return None