#!/usr/bin/env python3 """Constrained NetworkManager GSM profile management; no shell or SIM secrets.""" import json import re import shutil import subprocess import sys UUID = re.compile(r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') APN = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9.-]{0,99}$') NAME = re.compile(r'^[^\x00-\x1f\x7f]{1,64}$') def execute(args, runner=subprocess.run): try: proc = runner(['nmcli', '--wait', '15', *args], capture_output=True, text=True, timeout=22, check=False) return {'ok': proc.returncode == 0, 'error': '' if proc.returncode == 0 else (proc.stderr.strip() or 'NetworkManager rejected request')[:300], 'output': proc.stdout} except (OSError, subprocess.TimeoutExpired) as exc: return {'ok': False, 'error': str(exc)[:300], 'output': ''} def list_profiles(runner=subprocess.run): if not shutil.which('nmcli'): return {'ok': False, 'profiles': [], 'error': 'nmcli not installed'} result = execute(['-g', 'UUID,TYPE,NAME', 'connection', 'show'], runner) if not result['ok']: return {'ok': False, 'profiles': [], 'error': result['error']} profiles = [] # UUID and type are ASCII and fixed width; name may contain colons. for line in result['output'].splitlines(): parts = line.split(':', 2) if len(parts) != 3 or not UUID.fullmatch(parts[0]) or parts[1] not in ('gsm', 'cdma'): continue profiles.append({'uuid': parts[0], 'name': parts[2], 'type': parts[1]}) return {'ok': True, 'profiles': profiles, 'error': ''} def manage(action, value='', apn='', runner=subprocess.run): if action not in ('create', 'activate', 'deactivate', 'delete'): return {'ok': False, 'error': 'Unsupported action'} if not shutil.which('nmcli'): return {'ok': False, 'error': 'nmcli not installed'} if action == 'create': if not NAME.fullmatch(value) or not APN.fullmatch(apn): return {'ok': False, 'error': 'Invalid profile name or APN'} args = ['connection', 'add', 'type', 'gsm', 'con-name', value, 'apn', apn, 'connection.autoconnect', 'no'] else: if not UUID.fullmatch(value): return {'ok': False, 'error': 'Invalid connection UUID'} # Restrict operations to mobile profiles, not arbitrary network connections. profiles = list_profiles(runner) if not profiles['ok']: return {'ok': False, 'error': profiles['error']} if value.lower() not in {p['uuid'].lower() for p in profiles['profiles']}: return {'ok': False, 'error': 'Not a mobile connection'} if action == 'activate': args = ['connection', 'up', 'uuid', value] elif action == 'deactivate': args = ['connection', 'down', 'uuid', value] else: args = ['connection', 'delete', 'uuid', value] result = execute(args, runner) return {'ok': result['ok'], 'error': result['error']} if __name__ == '__main__': if len(sys.argv) < 2: response = {'ok': False, 'error': 'Missing action'} elif sys.argv[1] == 'list' and len(sys.argv) == 2: response = list_profiles() elif len(sys.argv) == 4 and sys.argv[1] == 'create': response = manage('create', sys.argv[2], sys.argv[3]) elif len(sys.argv) == 3: response = manage(sys.argv[1], sys.argv[2]) else: response = {'ok': False, 'error': 'Invalid arguments'} print(json.dumps(response, ensure_ascii=False)) sys.exit(0 if response['ok'] else 1)