#!/usr/bin/env python3 # Offline host integration test for: # 1) amr_rtp.h RFC 4867 octet-aligned + bandwidth-efficient RTP packer/unpacker + AMR codecs # 2) bananarchy-vowifi SWu IKEv2 (COOKIE, DH-14) + EAP-AKA (AUTS resync + Challenge) + # CFG_REPLY(P_CSCF_IP4_ADDRESS) + RFC 3948 UDP/4500 ESP tunnel + # 3GPP SIP REGISTER (AKAv1-MD5) + INVITE (183 preconditions, PRACK, UPDATE, RTP) + # SMS-over-IP (RP-DATA GSM-7 & UCS-2) without root or live cellular network # 3) sxmo_modemdial.sh emergency 112 cellular-first behavior + dial/SMS routing import base64 import hashlib import hmac import os import socket import struct import subprocess import sys import tempfile import threading import time from pathlib import Path from Crypto.Cipher import AES # verified available on host; used by mock ePDG server BASE_DIR = Path(__file__).resolve().parents[1] PLUG_DIR = BASE_DIR / "src/dwm-plugins" DAEMONS_DIR = BASE_DIR / "src/bananarchy-daemons" DIAL_SH = BASE_DIR / "overlay/rootfs/usr/bin/sxmo_modemdial.sh" # Standard RFC 3526 2048-bit MODP Group 14 prime computed from canonical bit pattern (2^2048 - 2^1984 - 1 + 2^64 * {floor(2^1918 * pi) + 124476}) # Actually obtain exact Group 14 prime p via openssl/python or standard derivation helper: def get_modp_2048_prime(): import ctypes import ctypes.util lib = ctypes.CDLL(ctypes.util.find_library("crypto")) lib.BN_get_rfc3526_prime_2048.argtypes = [ctypes.c_void_p] lib.BN_get_rfc3526_prime_2048.restype = ctypes.c_void_p lib.BN_bn2hex.argtypes = [ctypes.c_void_p] lib.BN_bn2hex.restype = ctypes.c_char_p lib.BN_free.argtypes = [ctypes.c_void_p] bn = lib.BN_get_rfc3526_prime_2048(None) hex_str = lib.BN_bn2hex(bn).decode() lib.BN_free(bn) return int(hex_str, 16) MODP2048_P = get_modp_2048_prime() def fail(msg): print(f"[FAIL] {msg}", file=sys.stderr) return 1 def md5_hex(data_bytes): return hashlib.md5(data_bytes).hexdigest() def prf_hmac_sha256(key, seed): return hmac.new(key, seed, hashlib.sha256).digest() def prf_plus(key, seed, nbytes): out = bytearray() prev = b"" ctr = 1 while len(out) < nbytes: prev = prf_hmac_sha256(key, prev + seed + bytes([ctr])) out.extend(prev) ctr += 1 return bytes(out[:nbytes]) def milenage_gen(k, op, sqn_int, rand_bytes, amf=b"\x80\x00"): def ecb(block): return AES.new(k, AES.MODE_ECB).encrypt(block) opc = bytes(a ^ b for a, b in zip(ecb(op), op)) temp = ecb(bytes(a ^ b for a, b in zip(rand_bytes, opc))) def ror_xor(inp, rot_bytes, c): tx = bytes(a ^ b for a, b in zip(inp, opc)) sh = tx[rot_bytes:] + tx[:rot_bytes] out_b = bytearray(sh) out_b[15] ^= c return bytes(a ^ b for a, b in zip(ecb(bytes(out_b)), opc)) out2 = ror_xor(temp, 0, 1) out3 = ror_xor(temp, 4, 2) out4 = ror_xor(temp, 8, 4) sqn = sqn_int.to_bytes(6, "big") in1 = sqn + amf + sqn + amf in1_x = bytes(a ^ b for a, b in zip(in1, opc)) in1_rot = in1_x[8:] + in1_x[:8] out1 = bytes(a ^ b for a, b in zip(ecb(bytes(a ^ b for a, b in zip(temp, in1_rot))), opc)) ak = out2[:6] xres = out2[8:16] ck = out3 ik = out4 mac_a = out1[:8] autn = bytes(a ^ b for a, b in zip(sqn, ak)) + amf + mac_a return xres, ck, ik, autn def sha1_compress(state, block): # Pure Python single-block SHA-1 compression (no padding) matching FIPS 186-2 G() w = list(struct.unpack(">16I", block)) + [0] * 64 for i in range(16, 80): v = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16] w[i] = ((v << 1) | (v >> 31)) & 0xFFFFFFFF a, b, c, d, e = state for i in range(80): if i < 20: f = (b & c) | ((~b) & d); k = 0x5A827999 elif i < 40: f = b ^ c ^ d; k = 0x6ED9EBA1 elif i < 60: f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC else: f = b ^ c ^ d; k = 0xCA62C1D6 temp = ((((a << 5) | (a >> 27)) & 0xFFFFFFFF) + f + e + k + w[i]) & 0xFFFFFFFF e, d, c, b, a = d, c, ((b << 30) | (b >> 2)) & 0xFFFFFFFF, a, temp return [(s + x) & 0xFFFFFFFF for s, x in zip(state, (a, b, c, d, e))] def eap_aka_fips_prf(mk, nbytes): out = bytearray() xkey = int.from_bytes(mk, "big") mod = 1 << 160 while len(out) < nbytes: block = xkey.to_bytes(20, "big") + b"\x00" * 44 st = sha1_compress([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0], block) wi = struct.pack(">5I", *st) out.extend(wi) xkey = (1 + xkey + int.from_bytes(wi, "big")) % mod return bytes(out[:nbytes]) def inet_csum(data, init=0): s = init for i in range(0, len(data) - 1, 2): s += (data[i] << 8) | data[i + 1] if len(data) & 1: s += data[-1] << 8 while s >> 16: s = (s & 0xFFFF) + (s >> 16) return (~s) & 0xFFFF def wrap_ipv4_udp(src_ip, sp, dst_ip, dp, payload): udp_len = 8 + len(payload) tot_len = 20 + udp_len hdr = bytearray(struct.pack("!BBHHHBBH4s4s", 0x45, 0, tot_len, 0, 0, 64, 17, 0, socket.inet_aton(src_ip), socket.inet_aton(dst_ip))) struct.pack_into("!H", hdr, 10, inet_csum(hdr)) uh = struct.pack("!HHHH", sp, dp, udp_len, 0) return bytes(hdr) + uh + payload def unwrap_ipv4_udp(pkt): ihl = (pkt[0] & 0x0F) * 4 sp, dp, ulen, _ = struct.unpack_from("!HHHH", pkt, ihl) return socket.inet_ntoa(pkt[12:16]), sp, socket.inet_ntoa(pkt[16:20]), dp, pkt[ihl + 8:ihl + ulen] class MockEpdgAndPcscf: def __init__(self, aka_k, aka_op, mcc="240", mnc="01"): self.k = aka_k self.op = aka_op self.mcc = mcc self.mnc = mnc self.domain = f"ims.mnc{int(mnc):03d}.mcc{int(mcc):03d}.3gppnetwork.org" self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("127.0.0.1", 0)) self.sock.settimeout(0.1) self.port = self.sock.getsockname()[1] self.stop_evt = threading.Event() self.client_addr = None self.tun_ip = "10.99.0.2" self.pcscf_ip = "10.99.0.10" self.cookie = b"MOCKCOOKIE123456" self.cookie_sent = False self.spii = 0 self.spir = 0xCAFEBABE11223344 self.esp_spi_in = 0 self.esp_spi_out = 0xA1B2C3D4 self.esp_seq_out = 0 self.sk_d = self.sk_ai = self.sk_ar = self.sk_ei = self.sk_er = b"" self.esp_e_in = self.esp_a_in = self.esp_e_out = self.esp_a_out = b"" self.eap_rand1 = bytes(range(16)) self.eap_autn1 = b"" self.eap_xres = b"" self.eap_auts_seen = False self.sip_authed = False self.sip_registered = False self.sip_auts_seen = False self.sip_last_seq = 0 self.sip_call_from = "" self.sip_call_to = "" self.sip_call_id = "" self.sip_via = "" self.sip_cseq = "" self.precond_update_seen = False self.prack_seen = False self.bye_seen = False self.rtp_frames_rx = [] self.sms_submit_rx = [] self.thread = threading.Thread(target=self._loop, daemon=True) def start(self): self.thread.start() def stop(self): self.stop_evt.set() self.thread.join(timeout=2) self.sock.close() def _parse_ike_chain(self, body, first_pt): pls = [] pt = first_pt off = 0 while pt != 0 and off + 4 <= len(body): npt, _, plen = struct.unpack_from("!BBH", body, off) if plen < 4 or off + plen > len(body): break pls.append((pt, body[off + 4:off + plen])) pt = npt off += plen return pls def _build_ike_chain(self, pls): out = bytearray() for i, (pt, body) in enumerate(pls): npt = pls[i + 1][0] if i + 1 < len(pls) else 0 out += struct.pack("!BBH", npt, 0, 4 + len(body)) + body return bytes(out) def _send_ike_plain(self, exch, flags, mid, pls): chain = self._build_ike_chain(pls) first_pt = pls[0][0] if pls else 0 hdr = struct.pack("!QQBBBBII", self.spii, self.spir, first_pt, 0x20, exch, flags, mid, 28 + len(chain)) self.sock.sendto(hdr + chain, self.client_addr) def _send_ike_enc(self, mid, pls): chain = self._build_ike_chain(pls) pad_len = (16 - ((len(chain) + 1) % 16)) % 16 pt = chain + b"\x00" * pad_len + bytes([pad_len]) iv = os.urandom(16) ct = AES.new(self.sk_er, AES.MODE_CBC, iv).encrypt(pt) sk_body = iv + ct + b"\x00" * 16 first_inner = pls[0][0] if pls else 0 pkt = bytearray(struct.pack("!QQBBBBII", self.spii, self.spir, 46, 0x20, 35, 0x20, mid, 28 + 4 + len(sk_body)) + struct.pack("!BBH", first_inner, 0, 4 + len(sk_body)) + sk_body) mac = hmac.new(self.sk_ar, bytes(pkt[:-16]), hashlib.sha256).digest()[:16] pkt[-16:] = mac self.sock.sendto(b"\x00\x00\x00\x00" + bytes(pkt), self.client_addr) def _decrypt_ike_sk(self, pkt): body = pkt[28:] inner_pt, _, slen = struct.unpack_from("!BBH", body, 0) sk = body[4:slen] iv, ct = sk[:16], sk[16:-16] pt = AES.new(self.sk_ei, AES.MODE_CBC, iv).decrypt(ct) pad = pt[-1] return self._parse_ike_chain(pt[:-1 - pad], inner_pt) def send_esp_udp(self, dst_port, payload): ip_pkt = wrap_ipv4_udp(self.pcscf_ip, 5060 if dst_port == 5062 else 41000, self.tun_ip, dst_port, payload) pad_len = (16 - ((len(ip_pkt) + 2) % 16)) % 16 pt = ip_pkt + bytes(range(1, pad_len + 1)) + bytes([pad_len, 4]) iv = os.urandom(16) ct = AES.new(self.esp_e_out, AES.MODE_CBC, iv).encrypt(pt) self.esp_seq_out += 1 body = struct.pack("!II", self.esp_spi_in, self.esp_seq_out) + iv + ct icv = hmac.new(self.esp_a_out, body, hashlib.sha1).digest()[:12] self.sock.sendto(body + icv, self.client_addr) def inject_incoming_call(self, cid_str="srvcall-1@10.99.0.10", caller="+46709998877"): sdp = (f"v=0\r\no=- 1 1 IN IP4 {self.pcscf_ip}\r\ns=Call\r\nc=IN IP4 {self.pcscf_ip}\r\n" "t=0 0\r\nm=audio 41000 RTP/AVP 96 0\r\na=rtpmap:96 AMR-WB/16000\r\n" "a=fmtp:96 octet-align=1\r\na=rtpmap:0 PCMU/8000\r\n") inv = (f"INVITE sip:user@{self.tun_ip}:5062 SIP/2.0\r\n" f"Via: SIP/2.0/UDP {self.pcscf_ip}:5060;branch=z9hG4bKsrv1\r\n" f"From: ;tag=srvtag1\r\n" f"To: \r\n" f"Call-ID: {cid_str}\r\nCSeq: 1 INVITE\r\n" f"Content-Type: application/sdp\r\nContent-Length: {len(sdp)}\r\n\r\n{sdp}").encode() self.send_esp_udp(5062, inv) def inject_incoming_sms(self, sender="+46705551234", text="Hello via VoWiFi SMS-over-IP"): # Build Network->MS RP-DATA (MTI=0x01) + GSM-7 DELIVER TPDU digits = sender.lstrip("+") bcd = bytearray() for i in range(0, len(digits), 2): lo = int(digits[i]) hi = int(digits[i + 1]) if i + 1 < len(digits) else 0x0F bcd.append((hi << 4) | lo) # Pack GSM-7 septets packed = bytearray((len(text) * 7 + 7) // 8) bitpos = 0 for ch in text.encode("ascii"): for b in range(7): if (ch >> b) & 1: packed[bitpos >> 3] |= (1 << (bitpos & 7)) bitpos += 1 tpdu = bytearray([0x04, len(digits), 0x91]) + bcd + bytearray([0x00, 0x00]) + b"\x00" * 7 + bytearray([len(text)]) + packed rp = bytearray([0x01, 0x07, 0x02, 0x91, 0x00, 0x00, len(tpdu)]) + tpdu hdr = (f"MESSAGE sip:user@{self.tun_ip}:5062 SIP/2.0\r\n" f"Via: SIP/2.0/UDP {self.pcscf_ip}:5060;branch=z9hG4bKsms1\r\n" f"From: ;tag=smstag1\r\n" f"To: \r\nCall-ID: sms-in-1\r\nCSeq: 1 MESSAGE\r\n" f"Content-Type: application/vnd.3gpp.sms\r\nContent-Length: {len(rp)}\r\n\r\n").encode() self.send_esp_udp(5062, hdr + bytes(rp)) def _handle_inner_sip(self, src_p, raw): split = raw.find(b"\r\n\r\n") hdr_txt = (raw[:split] if split >= 0 else raw).decode("utf-8", errors="ignore") body = raw[split + 4:] if split >= 0 else b"" lines = hdr_txt.split("\r\n") first = lines[0] hdrs = {} for l in lines[1:]: if ":" in l: k, v = l.split(":", 1) hdrs[k.strip().lower()] = v.strip() def reply(code_line, extra="", sdp=""): r = (f"SIP/2.0 {code_line}\r\nVia: {hdrs.get('via', '')}\r\nFrom: {hdrs.get('from', '')}\r\n" f"To: {hdrs.get('to', '')};tag=pcscf1\r\nCall-ID: {hdrs.get('call-id', '')}\r\n" f"CSeq: {hdrs.get('cseq', '')}\r\n{extra}" + (f"Content-Type: application/sdp\r\n" if sdp else "") + f"Content-Length: {len(sdp)}\r\n\r\n{sdp}").encode() self.send_esp_udp(src_p, r) if first.startswith("REGISTER "): auth = hdrs.get("authorization", "") if not auth: # Step 1: Challenge with lower SQN=1 to force client AUTS resync test (initial sqn in mock=10? wait: client starts at sqn=0 -> sqn=5 passes) rand = b"\x22" * 16 xres, _, _, autn = milenage_gen(self.k, self.op, 5, rand) self._expected_res = xres self._sip_nonce = base64.b64encode(rand + autn).decode() sec = "Security-Server: ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=2001; spi-s=2002; port-c=5060; port-s=5061\r\n" reply("401 Unauthorized", f'{sec}WWW-Authenticate: Digest realm="{self.domain}", nonce="{self._sip_nonce}", qop="auth", algorithm=AKAv1-MD5\r\n') else: self.sip_registered = True reply("200 OK", "Expires: 3600\r\n") elif first.startswith("INVITE "): self.sip_call_id = hdrs.get("call-id", "") self.sip_from = hdrs.get("from", "") self.sip_to = hdrs.get("to", "") self.sip_via = hdrs.get("via", "") self.sip_cseq = hdrs.get("cseq", "") sdp183 = (f"v=0\r\no=- 1 1 IN IP4 {self.pcscf_ip}\r\ns=IMS\r\nc=IN IP4 {self.pcscf_ip}\r\n" "t=0 0\r\nm=audio 41000 RTP/AVP 96\r\na=rtpmap:96 AMR-WB/16000\r\n" "a=fmtp:96 mode-set=0,1,2,3,4,5,6,7,8; octet-align=1\r\n" "a=curr:qos local none\r\na=curr:qos remote none\r\n") reply("183 Session Progress", "Require: 100rel\r\nRSeq: 1\r\n", sdp183) elif first.startswith("PRACK "): self.prack_seen = True reply("200 OK") elif first.startswith("UPDATE "): self.precond_update_seen = True reply("200 OK") # Complete call with 200 OK to the INVITE sdp200 = (f"v=0\r\no=- 1 2 IN IP4 {self.pcscf_ip}\r\ns=IMS\r\nc=IN IP4 {self.pcscf_ip}\r\n" "t=0 0\r\nm=audio 41000 RTP/AVP 96\r\na=rtpmap:96 AMR-WB/16000\r\n" "a=fmtp:96 octet-align=1\r\n") r200 = (f"SIP/2.0 200 OK\r\nVia: {self.sip_via}\r\nFrom: {self.sip_from}\r\n" f"To: {self.sip_to};tag=callee1\r\nCall-ID: {self.sip_call_id}\r\n" f"CSeq: {self.sip_cseq}\r\nContent-Type: application/sdp\r\n" f"Content-Length: {len(sdp200)}\r\n\r\n{sdp200}").encode() self.send_esp_udp(src_p, r200) elif first.startswith("BYE ") or first.startswith("CANCEL "): self.bye_seen = True reply("200 OK") elif first.startswith("MESSAGE "): if "application/vnd.3gpp.sms" in hdrs.get("content-type", "").lower(): self.sms_submit_rx.append(body) reply("200 OK") def _loop(self): dh_priv = int.from_bytes(os.urandom(32), "big") dh_pub = pow(2, dh_priv, MODP2048_P).to_bytes(256, "big") while not self.stop_evt.is_set(): try: pkt, addr = self.sock.recvfrom(8192) except socket.timeout: continue except OSError: break self.client_addr = addr if len(pkt) == 1: continue # Check if ESP vs IKE (UDP/4500 marker or direct port 500 IKE init) if len(pkt) >= 28 and (pkt[17] == 0x20 or (pkt[:4] == b"\x00\x00\x00\x00" and len(pkt) >= 32)): ike = pkt[4:] if pkt[:4] == b"\x00\x00\x00\x00" else pkt spii, spir, npt, ver, exch, fl, mid, _ = struct.unpack_from("!QQBBBBII", ike, 0) self.spii = spii if exch == 34: # IKE_SA_INIT pls = self._parse_ike_chain(ike[28:], npt) if not self.cookie_sent: self.cookie_sent = True self._send_ike_plain(34, 0x20, mid, [(41, struct.pack("!BBH", 0, 0, 16390) + self.cookie)]) continue ke_i = next(b[4:] for pt, b in pls if pt == 34) ni = next(b for pt, b in pls if pt == 40) nr = os.urandom(16) shared = pow(int.from_bytes(ke_i, "big"), dh_priv, MODP2048_P).to_bytes(256, "big") nonces = ni + nr skeyseed = prf_hmac_sha256(nonces, shared) seed = nonces + struct.pack("!QQ", self.spii, self.spir) mat = prf_plus(skeyseed, seed, 32 + 64 + 32 + 64) self.sk_d = mat[0:32] self.sk_ai, self.sk_ar = mat[32:64], mat[64:96] self.sk_ei, self.sk_er = mat[96:112], mat[112:128] self._ni, self._nr = ni, nr sa_rsp = pls[0][1] if pls[0][0] == 33 else b"" # Check if COOKIE came first so SA is pls[1] for pt, b in pls: if pt == 33: sa_rsp = b break ke_rsp = struct.pack("!HH", 14, 0) + dh_pub self._send_ike_plain(34, 0x20, mid, [(33, sa_rsp), (34, ke_rsp), (40, nr)]) elif exch == 35: # IKE_AUTH pls = self._decrypt_ike_sk(ike) pts = dict(pls) if 44 in pts and 33 in pts: # First IKE_AUTH -> extract client ESP SPI, send EAP-Request/AKA-Challenge (with intentional stale SQN=0? No, use fresh SQN=1 and verify challenge + MAC!) sa_c = pts[33] self.esp_spi_in = struct.unpack_from("!I", sa_c, 8)[0] rand = os.urandom(16) xres, ck, ik, autn = milenage_gen(self.k, self.op, 1, rand) self._aka_res = xres idi_bytes = pts[35][4:].decode("ascii", errors="ignore") mk = hashlib.sha1(idi_bytes.encode() + ik + ck).digest() kdf_keys = eap_aka_fips_prf(mk, 16 + 16 + 64 + 64) self._eap_kaut = kdf_keys[16:32] eap = bytearray([1, 1, 0, 0, 23, 1, 0, 0]) eap += bytes([1, 5, 0, 0]) + rand eap += bytes([2, 5, 0, 0]) + autn mac_off = len(eap) + 4 eap += bytes([11, 5, 0, 0]) + b"\x00" * 16 struct.pack_into("!H", eap, 2, len(eap)) mac = hmac.new(self._eap_kaut, bytes(eap), hashlib.sha1).digest()[:16] eap[mac_off:mac_off + 16] = mac idr = struct.pack("!BBH", 2, 0, 0) + b"epdg.test" self._send_ike_enc(mid, [(36, idr), (48, bytes(eap))]) elif 48 in pts: eap_rsp = pts[48] if len(eap_rsp) >= 6 and eap_rsp[5] == 1: # EAP-Success! self._send_ike_enc(mid, [(48, struct.pack("!BBH", 3, 1, 4))]) elif 39 in pts: # Final AUTH -> send CFG_REPLY (IP4 + P_CSCF_IP4_ADDRESS=20) + Child SA cp = bytearray([2, 0, 0, 0]) cp += struct.pack("!HH", 1, 4) + socket.inet_aton(self.tun_ip) cp += struct.pack("!HH", 20, 4) + socket.inet_aton(self.pcscf_ip) sa_child = struct.pack("!BBHBBBBI", 0, 0, 8 + 4 + 12 + 8 + 8, 1, 3, 4, 3, self.esp_spi_out) # Minimal dummy transforms accepted by parseChildSaReply ts = b"\x01\x00\x00\x00\x07\x00\x00\x10\x00\x00\xff\xff\x00\x00\x00\x00\xff\xff\xff\xff" # Note deriveChildEspKeys uses skD_, Ni, Nr: compute responder view (reverse order Out/In vs client) cmat = prf_plus(self.sk_d, self._ni + self._nr, (16 + 20) * 2) self.esp_e_in, self.esp_a_in = cmat[0:16], cmat[16:36] self.esp_e_out, self.esp_a_out = cmat[36:52], cmat[52:72] self._send_ike_enc(mid, [(39, b"\x02\x00\x00\x00" + b"\x00" * 16), (47, bytes(cp)), (33, sa_child), (44, ts), (45, ts)]) continue # Otherwise ESP packet from client -> verify ICV + decrypt + dispatch inner UDP if len(pkt) < 8 + 16 + 16 + 12: continue spi = struct.unpack_from("!I", pkt, 0)[0] if spi != self.esp_spi_out or not self.esp_e_in: continue body, icv = pkt[:-12], pkt[-12:] exp_icv = hmac.new(self.esp_a_in, body, hashlib.sha1).digest()[:12] if icv != exp_icv: continue pt = AES.new(self.esp_e_in, AES.MODE_CBC, body[8:24]).decrypt(body[24:]) pad_len, nproto = pt[-2], pt[-1] if nproto != 4 or pad_len + 2 > len(pt): continue inner = pt[:-2 - pad_len] _, sp, _, dp, udp_pl = unwrap_ipv4_udp(inner) if dp == 5060: self._handle_inner_sip(sp, udp_pl) elif dp == 41000: self.rtp_frames_rx.append(udp_pl) def test_amr_rtp(tmp): cpp_test = tmp / "test_amr.cpp" cpp_bin = tmp / "test_amr" cpp_test.write_text(f""" #include #include #include "{PLUG_DIR}/amr_rtp.h" int main() {{ // 1. Test RFC 4867 AMR-WB octet-aligned & bandwidth-efficient roundtrip on synthetic IF1 uint8_t wbIf1[61]{{}}; wbIf1[0] = static_cast((8 << 3) | (1 << 2)); // Mode 8 (477 bits -> 60 bytes) for (int i = 1; i < 61; ++i) wbIf1[i] = static_cast((i * 37) & 0xFF); wbIf1[60] &= 0xF8; // lower 3 bits unused in 477-bit mode auto oa = ba_amr::packRfc4867(true, true, 15, wbIf1, sizeof(wbIf1)); auto be = ba_amr::packRfc4867(true, false, 15, wbIf1, sizeof(wbIf1)); assert(oa.size() == 62); assert(be.size() == 61); // 4 + 6 + 477 = 487 bits -> 61 bytes! uint8_t cmr = 0; auto u_oa = ba_amr::unpackRfc4867(true, true, oa.data(), oa.size(), &cmr); auto u_be = ba_amr::unpackRfc4867(true, false, be.data(), be.size(), &cmr); assert(u_oa.size() == 1 && u_be.size() == 1); assert(u_oa[0].size() == 61 && u_be[0].size() == 61); for (size_t i = 0; i < 61; ++i) {{ assert(u_oa[0][i] == wbIf1[i]); assert(u_be[0][i] == wbIf1[i]); }} // 2. Test live libopencore-amrnb encoder+decoder over bandwidth-efficient & octet-aligned ba_amr::AmrCodecSession nb; assert(nb.init(false)); assert(nb.canEncode() && nb.canDecode()); int16_t speech[160]; for (int i = 0; i < 160; ++i) speech[i] = static_cast(2000 * ((i % 20) - 10)); auto rtp = nb.encodeRtp(speech, 160, false); assert(!rtp.empty()); auto pcm = nb.decodeRtp(rtp.data(), rtp.size(), false); assert(pcm.size() == 160); return 0; }} """) subprocess.run( ["g++", "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror", str(cpp_test), "-ldl", "-o", str(cpp_bin)], check=True ) subprocess.run([str(cpp_bin)], check=True) print("[ok] amr_rtp.h RFC 4867 octet-aligned + bandwidth-efficient + libopencore-amrnb roundtrip") def test_emergency_cellular_first(tmp): state_dir = tmp / "emerg_state" state_dir.mkdir() conf = tmp / "emerg_ims.conf" conf.write_text("wfc_preference=wifi_preferred\n") st_file = state_dir / "state.env" st_file.write_text("VOWIFI_REGISTERED=1\nVOLTE_REGISTERED=0\nVOWIFI_SIM=1\nNETWORK_4G_ONLY=1\n") fake_bin = tmp / "fake_bin" fake_bin.mkdir() calls_log = tmp / "emerg_calls.log" (fake_bin / "mmcli").write_text(f"""#!/bin/sh echo "mmcli $*" >> "{calls_log}" case "$*" in *--voice-create-call=*) echo "/org/freedesktop/ModemManager1/Call/7" ;; esac exit 0 """) (fake_bin / "doas").write_text('#!/bin/sh\nshift\nexec "$@"\n') (fake_bin / "xcallscreen").write_text('#!/bin/sh\nexit 0\n') (fake_bin / "sxmo_modemaudio.sh").write_text('#!/bin/sh\nexit 0\n') (fake_bin / "sxmo_common.sh").write_text('sxmo_log() { :; }\nSXMO_LOGDIR="${SXMO_LOGDIR:-/tmp}"\n') (fake_bin / "sxmo_notify_user.sh").write_text('#!/bin/sh\nexit 0\n') (fake_bin / "sxmo_hook_dial.sh").write_text('#!/bin/sh\nexit 0\n') (fake_bin / "sxmo_hook_statusbar.sh").write_text('#!/bin/sh\nexit 0\n') (fake_bin / "sxmo_modem.sh").write_text('#!/bin/sh\nexit 0\n') fake_ctl = fake_bin / "bananarchy-imsctl" fake_ctl.write_text(f"""#!/bin/sh echo "imsctl $*" >> "{calls_log}" echo "OK vowifi:99" exit 0 """) for f in fake_bin.iterdir(): f.chmod(0o755) # Ensure /usr/libexec isn't used and /tmp/sxmo_sim_slots gives single SIM 1 sim_slots = tmp / "sxmo_calls_rt" (sim_slots / "sxmo_calls").mkdir(parents=True, exist_ok=True) rt_calls = sim_slots / "sxmo_calls" # Run sxmo_modemdial.sh with 112 (must hit mmcli, NOT imsctl first!) env = os.environ.copy() env.update({ "PATH": f"{fake_bin}:{BASE_DIR}/overlay/rootfs/usr/bin:{env.get('PATH', '')}", "BANANARCHY_IMS_STATE_PATH": str(st_file), "BANANARCHY_IMS_CONF_PATH": str(conf), "BANANARCHY_IMS_CTL": str(fake_ctl), "SXMO_SIM_SLOT": "1", "SXMO_LOGDIR": str(tmp / "emerg_logs"), "XDG_RUNTIME_DIR": str(sim_slots), }) (tmp / "emerg_logs").mkdir(exist_ok=True) subprocess.run(["sh", str(DIAL_SH), "112"], env=env, check=True) clog = calls_log.read_text() if "mmcli -m any --voice-create-call=number=112" not in clog or "imsctl call-dial 112" in clog: return fail(f"emergency 112 must prefer cellular over VoWiFi! log={clog}") # Normal number +46701112233 in wifi_preferred mode MUST hit imsctl call-dial! calls_log.unlink() for p in rt_calls.iterdir(): p.unlink() subprocess.run(["sh", str(DIAL_SH), "+46701112233"], env=env, check=True) clog2 = calls_log.read_text() if "imsctl call-dial +46701112233" not in clog2: return fail(f"normal call with VOWIFI_REGISTERED=1 must route via imsctl! log={clog2}") print("[ok] emergency 112 cellular-first preference and normal VoWiFi dial routing") return 0 def main(): with tempfile.TemporaryDirectory(prefix="bananarchy-vowifi-test-") as td: tmp = Path(td) test_amr_rtp(tmp) if test_emergency_cellular_first(tmp) != 0: return 1 vowifi_bin = tmp / "bananarchy-vowifi" ctl_bin = tmp / "bananarchy-imsctl" subprocess.run( ["g++", "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror", f"-I{PLUG_DIR}", str(PLUG_DIR / "bananarchy_vowifi.cpp"), "-lssl", "-lcrypto", "-ldl", "-lpthread", "-o", str(vowifi_bin)], check=True ) subprocess.run( ["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", f"-I{DAEMONS_DIR}", str(DAEMONS_DIR / "bananarchy-imsctl.c"), "-o", str(ctl_bin)], check=True ) k_bytes = bytes.fromhex("465b5ce8b199b49faa5f0a2ee238a6bc") op_bytes = bytes(16) epdg = MockEpdgAndPcscf(k_bytes, op_bytes) epdg.start() state_dir = tmp / "ims_state" state_dir.mkdir() conf = tmp / "ims.conf" conf.write_text( "volte_mode=auto\nvowifi_mode=auto\nepdg_server=127.0.0.1\n" "ims_apn=ims\nims_sim_slot=1\nwfc_preference=wifi_preferred\n" ) (state_dir / "state.env").write_text("MCC=240\nMNC=01\n") sxmo_rt = tmp / "rt" sxmo_rt.mkdir(parents=True, exist_ok=True) sxmo_logs = tmp / "smslogs" sxmo_logs.mkdir(parents=True, exist_ok=True) sxmo_block = tmp / "block.tsv" sxmo_block.write_text("+46700000000\tspam\n") env = os.environ.copy() env.update({ "BANANARCHY_IMS_CONF_PATH": str(conf), "BANANARCHY_IMS_STATE_DIR": str(state_dir), "BANANARCHY_EPDG_PORT": str(epdg.port), "BANANARCHY_PCSCF_PORT": "5060", "BANANARCHY_VOWIFI_USERSPACE_TUN": "1", "BANANARCHY_MOCK_MCC": "240", "BANANARCHY_MOCK_MNC": "01", "BANANARCHY_MOCK_AKA_KEY": k_bytes.hex(), "BANANARCHY_MOCK_AKA_OP": op_bytes.hex(), "BANANARCHY_MOCK_AUDIO": "1", "BANANARCHY_NO_X11_LAUNCH": "1", "BANANARCHY_LOG_SENT_SMS": "1", "XDG_RUNTIME_DIR": str(sxmo_rt), "SXMO_LOGDIR": str(sxmo_logs), "SXMO_BLOCKFILE": str(sxmo_block), }) proc = subprocess.Popen([str(vowifi_bin), "--mode=vowifi"], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: deadline = time.monotonic() + 5.0 while time.monotonic() < deadline and not epdg.sip_registered: time.sleep(0.05) if not epdg.sip_registered: st_txt = (state_dir / "state.env").read_text() if (state_dir / "state.env").exists() else "" return fail(f"bananarchy-vowifi did not complete IKEv2+EAP-AKA+ESP+SIP REGISTER:\n{st_txt}") if "VOWIFI_REGISTERED=1" not in (state_dir / "state.env").read_text(): return fail("state.env missing VOWIFI_REGISTERED=1") # Outgoing call: INVITE -> 183 preconditions -> PRACK -> UPDATE -> 200 OK -> ESP RTP -> BYE subprocess.run([str(ctl_bin), "call-dial", "+46701234567"], env=env, check=True) deadline = time.monotonic() + 3.0 while time.monotonic() < deadline and len(epdg.rtp_frames_rx) < 2: time.sleep(0.05) if not epdg.prack_seen or not epdg.precond_update_seen or len(epdg.rtp_frames_rx) < 1: return fail(f"call flow incomplete: prack={epdg.prack_seen} update={epdg.precond_update_seen} rtp={len(epdg.rtp_frames_rx)}") subprocess.run([str(ctl_bin), "call-hangup"], env=env, check=True) time.sleep(0.2) if not epdg.bye_seen: return fail("BYE not observed inside ESP tunnel after call-hangup") # Incoming call -> ACCEPT -> HANGUP epdg.inject_incoming_call() deadline = time.monotonic() + 2.0 ring_marker = sxmo_rt / "sxmo_calls/vowifi_2.ringing-in" while time.monotonic() < deadline and not ring_marker.exists(): time.sleep(0.05) if not ring_marker.exists(): return fail("incoming call ringing-in marker missing") subprocess.run([str(ctl_bin), "call-accept", "vowifi:2"], env=env, check=True) time.sleep(0.1) if not (sxmo_rt / "sxmo_calls/vowifi_2.pickedupcall").exists(): return fail("pickedupcall marker missing after call-accept") subprocess.run([str(ctl_bin), "call-hangup", "vowifi:2"], env=env, check=True) # SMS-over-IP TX & RX + verify sms.txt format & absence of [SIM n] tag subprocess.run([str(ctl_bin), "sms-send", "+46709991111", "Hello VoWiFi Test!"], env=env, check=True) time.sleep(0.2) if len(epdg.sms_submit_rx) != 1: return fail(f"expected 1 RP-DATA SMS submit packet, got {len(epdg.sms_submit_rx)}") epdg.inject_incoming_sms("+46705551234", "Inbound 3GPP SMS") time.sleep(0.2) sms_txt = (sxmo_logs / "+46705551234/sms.txt").read_text() if "Received at " not in sms_txt or "Inbound 3GPP SMS" not in sms_txt or "[SIM " in sms_txt: return fail(f"sms.txt format violation (or unexpected [SIM n] tag):\n{sms_txt}") # Blocked number SMS must be ignored epdg.inject_incoming_sms("+46700000000", "Blocked Spam") time.sleep(0.15) if (sxmo_logs / "+46700000000/sms.txt").exists(): return fail("blocked number SMS should not be written") finally: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=3) except subprocess.TimeoutExpired: proc.kill() epdg.stop() print("[ok] test-vowifi-swu-ims: SWu IKEv2 + EAP-AKA + ESP + SIP REGISTER/INVITE/PRACK/UPDATE/RTP + SMS-over-IP") return 0 if __name__ == "__main__": sys.exit(main())