Analysis
Create Pi Zero W firewall package matching analyzed MBUX policies
- Analysis:
- Mapped MBUX firewall files to equivalent Pi Zero services and wrote validated nftables, hostapd, and setup scripts.
- Conclusion:
- Packaged 8 files (nftables.conf, debug overlay, scripts, hostapd/dnsmasq configs, README); syntax-validated but runtime testing on Pi required.
Tools: list_files, run_sandbox, todo_write, web_search, write_file, edit_file
Run it yourselfHelp me solve this CTF challenge. Identify the challenge type, analyze the binary, and work toward the flag. The idea is analize how firewall works to create a I want to see how to use a Raspberry Pi as a firewall. I’m not sure where to start. The device runs Linux.
I'll start by looking at what's in the workspace to identify the challenge.
The workspace appears empty. Let me double-check with the sandbox in case there are hidden files:
I checked thoroughly — there's nothing to analyze yet. Here's what I found and what I need from you.
What I checked
list_fileson the workspace: empty- Sandbox-wide search (
/tmp,/home,/root,/opt,/srv,/mnt) for binaries, firmware images, archives,flag*files: nothing
So there is no binary, firmware image, or challenge file here. I can't identify the challenge type or produce a flag from a nonexistent file — and I won't invent one.
To work the CTF challenge, please upload
- The challenge file(s) — whatever was given: an ELF binary, a firmware
.bin/.img, a SquashFS, a pcap, etc. - The challenge description/hostname/port if you have it — it usually hints at the category (rev, pwn, forensics) and how the flag is delivered.
Once the file lands in the workspace, my workflow is: inspect_binary triage → dump_data (Ghidra decompilation) → reachability/taint analysis for firmware images → confirm findings against the decompiled code → recover the flag or report the vulnerability. If it's a Raspberry Pi firewall image (e.g., a custom firmware blob), the firmware-extraction path is exactly what I'm built for.
Meanwhile — Raspberry Pi as a firewall (the actual idea)
Since "analyze how a firewall works" is the goal, here's the minimal Linux path. A firewall on a Pi is just packet filtering + NAT + forwarding, all via nftables:
- Network setup — Pi has two interfaces:
eth0upstream (WAN), a USB-Ethernet adapter or Wi-Fi for LAN. Enable forwarding:sysctl -w net.ipv4.ip_forward=1 - NAT for the LAN (masquerade outbound traffic):
nft add table nat nft 'add chain nat postrouting { type nat hook postrouting priority 100 ; }' nft add rule nat postrouting oifname "eth0" masquerade - Filter rules — the actual "firewall" part: default-drop forward chain, allow established/related, allow LAN→WAN, block unsolicited WAN→LAN:
nft add table inet filter nft 'add chain inet filter forward { type filter hook forward priority 0 ; policy drop ; }' nft add rule inet filter forward ct state established,related accept nft add rule inet filter forward iifname "lan0" oifname "eth0" accept - Persistence — put it in
/etc/nftables.confandsystemctl enable nftables.
That gives you a real, inspectable firewall you can then analyze/attack — which is usually the setup behind "firewall" CTF challenges (bypass the rules, or exploit the management binary).
Upload the challenge file and I'll get straight to the flag.
He extraido esos ficheros de la carpeta firewall en /etc
Good — those are firewall policy files from /etc/firewall. The naming (arptables/ebtables/firewall6 + _jpn/entry_mid/high variants + a firewall_dbg.sh) is very router-firmware-like. Let me read them all and analyze.
All plain text. Reading everything now — the small ones first, then the main policies:
This is a full iptables-save dump from an embedded device — automotive-grade looking (RSE = Rear Seat Entertainment, DoIP port 13400, ppp0 cellular modem, MAPN chains). Timestamp Jan 1 1970 confirms a headless embedded system. Note the debug script: /usr/bin/sa_reader gates whether the more permissive debug policy gets loaded — that's a classic debug-mode backdoor pattern. Let me read the rest:
More clues: bcm0, wlan0.200 VLANs for MultiAPN, "Hermes" connectivity, JPN emulation — this is an automotive telematics unit. Now the debug policy and the bridge/ARP tables:
The debug policy's key additions: SSH (port 22) on eth0.1 and eth1:0, plus extra debug ports (3490, 3804, 9710, 9720, 12600). Now the arptables/ebtables policies:
All 12 files read. Now let me hunt for hidden data and anomalies — flags, base64, invisible characters, typos, and rule-level bugs:
No hidden flag data — no flag strings, no base64 blobs, no non-ASCII, no trailing bytes. So this is a firewall-logic analysis challenge, not a string hunt. Let me systematically diff production vs debug policy and verify the anomalies I spotted:
Clean diff: debug mode only adds rules, never removes any — 13 filter rules + 8 NAT rules. Now let me verify the anomalies I spotted in the sharing policies and try to identify the vendor via a quick search:
All anomalies confirmed. Quick search to see if this firmware has public research (these filenames are distinctive enough to identify the vendor):
Excellent — strong hit. The first result (Kaspersky's Mercedes-Benz MBUX research) quotes firewall_prd.policy by name and the exact rule shape (-A INPUT -s [IP]/32 -d [IP]/32 -i eth0 -m state --state NEW -j ACCEPT) we see at 192.168.210.109↔110 on eth0. Let me confirm the vendor attribution and the "Hermes" link:
Analysis complete. Here's everything, with evidence.
1. Challenge type
Firmware configuration analysis — automotive firewall (no binary to reverse). These 12 files are /etc/firewall/* from an embedded Linux device: iptables-save/ip6tables-save/ebtables-save/arptables-save dumps + overlay policies + a shell script. "Identify the challenge type" is answered by the artifacts themselves, and they identify the device.
2. Device identification: Mercedes-Benz MBUX head unit + HERMES telematics
Not a Raspberry Pi — this is the Mercedes-Benz MBUX NTG6 head unit (MMB) / HERMES T-Box (Linux, iptables 1.6.0, clock still at Jan 1 1970). Evidence:
- Kaspersky's MBUX research (Securelist, 2025) quotes
firewall_prd.policyby name and the exact rule shape we have on eth0:-A INPUT -s [IP]/32 -d [IP]/32 -i eth0 -m state --state NEW -j ACCEPT→ our rules192.168.210.110 → 192.168.210.109 -i eth0match. - KeenLab's Mercedes report: T-Box "also called TCU or HERMES module", AP SSID "MB Hermes AP xxxxx 5Ghz", CSB IP 192.168.210.110, MMB 192.168.210.109 on subnet
192.168.210.108/30(→ our arptables blocks exactly192.168.210.108/30), CSB↔MMB, and port 3804 = HiQnet (Harman) — present in our debug policy.
Network map reconstructed from the policies:
| Subnet/IP | Role | Interfaces |
|---|---|---|
| 192.168.210.108/30 | MMB (109) ↔ CSB (110) internal Ethernet | eth0, eth0.1 |
| 192.168.210.101↔102 via ppp0 | HERMES/T-Box link (ppp = cellular modem) | ppp0 |
| 192.168.210.121↔122 | internal link via hv0 | hv0 |
| 192.168.220.0/24 (.1=HU, .2=T-Box) | passenger Wi-Fi / Hermes AP | wlan0, wlan_bridge0, p2p-wlan0-0, bcm0 |
| 192.168.230.0/24 | second AP group ("JPN emulation") | wlan1, p2p-wlan1-0, bcm1 |
| 192.168.42.0/24 | USB debug | usb0 |
| 169.254.133.27 | link-local services | eth0.1 |
| 192.168.192.168 | debug SSH IP | eth1:0 (alias) |
_jpn = Japanese-market variant; entry_mid/high = feature grades; MAPN = Multi-APN (VLAN 200 tethering); comments "Hermes", "RSE", "JPN emulation" confirm.
3. How the firewall works (the layers)
- iptables v4 (
firewall_prd.policy) — default DROP on all three base chains; stateful accept for RELATED,ESTABLISHED (excluding ICMP, which is handled by type: 0/3/11/12 in, 8 out); interface-role separation: client nets (wlan+/pan+/p2p-wlan+/usb0) can never forward to vehicle nets (eth+/ppp+/hv0/usb0) — 18 explicit cross-zone DROP rules; a service whitelist per interface+source (e.g., DNS 53, DHCP 67/68, NTP 123, DoIP 13400, T-Box ports 2100/2101 only from 192.168.220.2 — the T-Box IP); au32anti-recon rule dropping IPv4 packets with Record Route (option 7) / Timestamp (option 68) options (IHL 6–15); DNAT 20032 → T-Box; all drops logged viaLOG_*chains with--log-uid. - L2 layer —
ebtables: per-port IPv4/ARP whitelists (DNS only to .1/.130, DHCP 67:68, T-Box .2→.1), multicast drops, 802.1Q VLAN-0 drop, client isolation between AP bridges;arptables: anti-ARP-spoofing (drops ARPs on client interfaces claiming internal IPs), broadcast-mac and multicast-source ARP drops. - ip6tables — mostly USB-local services (5000/5001/5020/5353/6000-6003/6011/6020/6030/7000) + ND.
- Runtime composition —
firewall_prdis the base;enable/disable-wlan-sharing.policyoverlay flushes and repopulatesWIFI_INPUT/WIFI_FORWARD/MAPN_NAT_POSTROUTINGper market/grade; NAT = per-interface MASQUERADE. - Debug mode (the crown jewel) —
firewall_dbg.sh:
The debug policy is a strict superset of production (my diff: +13 filter rules, +8 NAT, −0). Debug adds: SSH 22 on eth0.1 and on 192.168.192.168 via eth1:0, HiQnet 3804, DLT 3490 (Diagnostic Log and Trace — the exact subsystem Kaspersky highlighted) plus DNAT 3491→CSB:3490, 9710/9720/12600, and DNAT 20032/50012 → T-Box, GCF ports 20331/20581/20583.RET=$(/usr/bin/sa_reader; echo $?) # DBG = 1 [ $RET -eq 1 ] && iptables-restore -c /etc/firewall/firewall_dbg.policy
4. Toward the flag
There is no literal flag string in these files — I checked: no flag/CTF/key/secret strings, no base64 blobs, no non-ASCII, no hidden trailing bytes. The challenge's "flag" is the attack path itself:
Enable debug mode → shell. If
/usr/bin/sa_reader(not in this upload) exits 1, the firewall swaps to the debug policy and SSH:22 on eth0.1 and 192.168.192.168 (eth1:0) becomes reachable.sa_readerreads a "security access" state — defeating it (a file, env var, or CAN signal it consults) is the intended pivot. Second path: impersonate the T-Box at 192.168.220.2 (KeenLab sniffed the Hermes AP credentials off CAN) to reach ports 2100/2101.
Confirmed bugs worth reporting as findings:
| # | Finding | Evidence |
|---|---|---|
| 1 | Debug gate via exit code of sa_reader swaps to permissive policy (SSH, DLT, HiQnet) | firewall_dbg.sh:5-7; dbg diff |
| 2 | IPv6 LOG_ACCEPT chain ends in DROP (accept path that drops — dead but a trap) | firewall6_prd.policy:44-45 |
| 3 | Wrong interface in JPN-emulation-HIGH MultiAPN return rule: p2p-wlan0-1.200 should be p2p-wlan1-0.200 → broken return path | enable-wlan-sharing.policy:61 |
| 4 | ebtables_high INPUT contains a duplicated rule block (38-46 ≈ 49-57) | ebtables_high.policy |
| 5 | ebtables_jpn = all chains DROP with zero rules → fail-closed bridging in JPN mode | ebtables_jpn.policy:3-5 |
| 6 | Typos that break log tooling: EBT-ACEPT:, Meanlingless | ebtables_*.policy:63/82, enable-wlan-sharing.policy:32 |
| 7 | LOG_REJECT chain is dead code (never jumped to) | both IPv4 policies |
If your CTF wants a literal flag, I need the missing artifacts — upload /usr/bin/sa_reader and the challenge description, and I'll reverse it to find the trigger condition.
5. Your actual goal: this IS the Pi-firewall blueprint
This policy set is a textbook model of the firewall you want to build on a Raspberry Pi — port it to nftables:
- Zones by interface role (Pi:
eth0=WAN,wlan0=LAN) ≈ MBUX'swlan+↔eth+cross-zone DROPs →nft add rule inet filter forward iif "lan" oif "wan" accept; ... iif "wan" oif "lan" drop. - Default-drop + stateful + type-restricted ICMP ≈ their INPUT/FORWARD/OUTPUT policy.
- Service whitelist per source ≈ their
-s 192.168.220.2 --dport 2100style rules → use nft sets. - Overlay toggles ≈
enable/disable-wlan-sharing.policy→ awifi-forwardtable you flush/load, or nft sets you empty/fill. - NAT ≈ their MAPN MASQUERADE set →
masqueradeon the WAN interface. - L2 filtering ≈ their ebtables → nft
bridgefamily; ARP-spoof protection ≈ their arptables →arpfamily. - Debug mode lesson: their debug gate is a script checking a state reader. On your Pi, do it properly — only load the permissive policy when a signed/authenticated flag exists, and keep the strict superset property (debug may only add rules, never remove production ones).
Want me to write the equivalent nftables.conf for your Pi modeled on these policies?
Explicalo en español
Claro, aquí va el análisis completo en español:
1. Tipo de reto
Análisis de configuración de firmware — firewall automotriz (sin binario que reverar). Los 12 ficheros son /etc/firewall/* de un dispositivo Linux embebido: volcados de iptables-save/ip6tables-save/ebtables-save/arptables-save, más políticas de superposición y un script de shell. Los propios artefactos identifican el dispositivo.
2. Identificación del dispositivo: Mercedes-Benz MBUX + HERMES
No es una Raspberry Pi — es la unidad principal MBUX NTG6 de Mercedes-Benz (MMB) / el T-Box HERMES (Linux, iptables 1.6.0, el reloj sigue en 1 de enero de 1970). Evidencia:
- La investigación de Kaspersky sobre MBUX (Securelist, 2025) menciona
firewall_prd.policypor su nombre y cita la forma exacta de la regla en eth0:-A INPUT -s [IP]/32 -d [IP]/32 -i eth0 -m state --state NEW -j ACCEPT→ coincide con nuestras reglas192.168.210.110 → 192.168.210.109 -i eth0. - El informe de KeenLab sobre Mercedes: el T-Box "también llamado TCU o módulo HERMES", el AP con SSID "MB Hermes AP xxxxx 5Ghz", la CSB con IP 192.168.210.110, la MMB 192.168.210.109 en la subred
192.168.210.108/30(→ nuestras reglas arptables bloquean exactamente192.168.210.108/30), y el puerto 3804 = HiQnet (Harman) — presente en la política de depuración.
Mapa de red reconstruido a partir de las políticas:
| Subred/IP | Función | Interfaces |
|---|---|---|
| 192.168.210.108/30 | MMB (109) ↔ CSB (110), Ethernet interna | eth0, eth0.1 |
| 192.168.210.101↔102 vía ppp0 | Enlace con el T-Box HERMES (ppp = módem celular) | ppp0 |
| 192.168.210.121↔122 | Enlace interno vía hv0 | hv0 |
| 192.168.220.0/24 (.1=HU, .2=T-Box) | Wi-Fi de pasajeros / AP Hermes | wlan0, wlan_bridge0, p2p-wlan0-0, bcm0 |
| 192.168.230.0/24 | Segundo grupo de AP ("emulación JPN") | wlan1, p2p-wlan1-0, bcm1 |
| 192.168.42.0/24 | Depuración por USB | usb0 |
| 169.254.133.27 | Servicios link-local | eth0.1 |
| 192.168.192.168 | IP de SSH en modo debug | eth1:0 (alias) |
_jpn = variante para el mercado japonés; entry_mid/high = niveles de equipamiento; MAPN = Multi-APN (tethering con VLAN 200); los comentarios "Hermes", "RSE" (entretenimiento para asientos traseros), "JPN emulation" lo confirman.
3. Cómo funciona el firewall (sus capas)
- iptables v4 (
firewall_prd.policy) — DROP por defecto en las tres cadenas base; aceptación por estado RELATED,ESTABLISHED (excluyendo ICMP, que se maneja por tipo: 0/3/11/12 entrante, 8 saliente); separación de zonas por interfaz: las redes de clientes (wlan+/pan+/p2p-wlan+/usb0) nunca pueden reenviar tráfico hacia las redes del vehículo (eth+/ppp+/hv0/usb0) — 18 reglas DROP cruzadas explícitas; una lista blanca de servicios por interfaz+origen (ej.: DNS 53, DHCP 67/68, NTP 123, DoIP 13400, puertos del T-Box 2100/2101 solo desde 192.168.220.2 — la IP del T-Box); una reglau32antirreconocimiento que descarta paquetes IPv4 con opciones Record Route (tipo 7) / Timestamp (tipo 68) (IHL 6–15); DNAT del 20032 hacia el T-Box; todo lo descartado se registra en cadenasLOG_*con--log-uid. - Capa de nivel 2 —
ebtables: listas blancas IPv4/ARP por puerto (solo DNS hacia .1/.130, DHCP 67:68, T-Box .2→.1), descarte de multicast, descarte de VLAN 0 en 802.1Q, aislamiento entre puentes de los AP;arptables: protección anti-ARP-spoofing (descarta ARPs que lleguen por interfaces de clientes suplantando IPs internas), descarte de ARP con MAC broadcast y origen multicast. - ip6tables — básicamente servicios locales por USB (5000/5001/5020/5353/6000-6003/6011/6020/6030/7000) + descubrimiento de vecinos (ND).
- Composición en tiempo de ejecución —
firewall_prdes la base; el parenable/disable-wlan-sharing.policyvacía y repuebla las cadenasWIFI_INPUT/WIFI_FORWARD/MAPN_NAT_POSTROUTINGsegún mercado/nivel de equipamiento; el NAT = MASQUERADE por interfaz. - Modo debug (lo más jugoso) —
firewall_dbg.sh:
La política de debug es un superconjunto estricto de la de producción (mi diff: +13 reglas de filter, +8 de nat, −0). El modo debug añade: SSH en el puerto 22 por eth0.1 y por 192.168.192.168 vía eth1:0, HiQnet 3804, DLT 3490 (Diagnostic Log and Trace — justo el subsistema que destacó Kaspersky) más DNAT 3491→CSB:3490, puertos 9710/9720/12600, y DNAT 20032/50012 → T-Box, puertos GCF 20331/20581/20583.RET=$(/usr/bin/sa_reader; echo $?) # DBG = 1 [ $RET -eq 1 ] && iptables-restore -c /etc/firewall/firewall_dbg.policy
4. Rumbo a la flag
No hay ninguna flag literal en estos ficheros — lo comprobé: sin cadenas flag/CTF/key/secret, sin blobs base64, sin caracteres no ASCII, sin bytes ocultos al final. La "flag" de este reto es la ruta de ataque en sí:
Activar el modo debug → shell. Si
/usr/bin/sa_reader(no está en esta subida) devuelve 1, el firewall se cambia a la política de debug y SSH:22 en eth0.1 y en 192.168.192.168 (eth1:0) queda accesible.sa_readerlee un estado de "acceso de seguridad" — vencer esa comprobación (un fichero, una variable de entorno o una señal CAN que consulte) es el pivote previsto. Segunda ruta: suplantar al T-Box en 192.168.220.2 (KeenLab esnifó las credenciales del AP Hermes por el bus CAN) para alcanzar los puertos 2100/2101.
Bugs confirmados que merecen informe:
| # | Hallazgo | Evidencia |
|---|---|---|
| 1 | Puerta de debug basada en el código de salida de sa_reader, que cambia a una política permisiva (SSH, DLT, HiQnet) | firewall_dbg.sh:5-7; diff del debug |
| 2 | La cadena LOG_ACCEPT de IPv6 termina en DROP (ruta de "aceptar" que descarta — código muerto, pero una trampa) | firewall6_prd.policy:44-45 |
| 3 | Interfaz equivocada en la regla de retorno MultiAPN JPN-emulación-HIGH: p2p-wlan0-1.200 debería ser p2p-wlan1-0.200 → ruta de retorno rota | enable-wlan-sharing.policy:61 |
| 4 | ebtables_high tiene un bloque de reglas INPUT duplicado (38-46 ≈ 49-57) | ebtables_high.policy |
| 5 | ebtables_jpn = todas las cadenas DROP sin ninguna regla → puente "fail-closed" en modo JPN | ebtables_jpn.policy:3-5 |
| 6 | Typos que rompen herramientas de logs: EBT-ACEPT:, Meanlingless | ebtables_*.policy:63/82, enable-wlan-sharing.policy:32 |
| 7 | La cadena LOG_REJECT es código muerto (nada salta a ella) | ambas políticas IPv4 |
Si tu CTF espera una flag literal, necesito los artefactos que faltan — sube /usr/bin/sa_reader y el enunciado del reto, y lo reveraré para encontrar la condición de disparo.
5. Tu objetivo real: esto ES el plano del firewall para la Raspberry Pi
Este conjunto de políticas es un modelo de libro de texto del firewall que quieres montar en una Raspberry Pi — para portarlo a nftables:
- Zonas por rol de interfaz (en la Pi:
eth0=WAN,wlan0=LAN) ≈ los DROP cruzadoswlan+↔eth+de MBUX →nft add rule inet filter forward iif "lan" oif "wan" accept; ... iif "wan" oif "lan" drop. - Drop por defecto + stateful + ICMP por tipo ≈ sus cadenas INPUT/FORWARD/OUTPUT.
- Lista blanca de servicios por origen ≈ sus reglas tipo
-s 192.168.220.2 --dport 2100→ usar sets de nft. - Superposiciones conmutables ≈
enable/disable-wlan-sharing.policy→ una tablawifi-forwardque vacías/cargas, o sets de nft que llenas/vacías. - NAT ≈ su set MASQUERADE de MAPN →
masqueradeen la interfaz WAN. - Filtrado L2 ≈ su ebtables → familia
bridgede nft; protección anti-ARP-spoofing ≈ su arptables → familiaarpde nft. - Lección del modo debug: su puerta de debug es un script que consulta un lector de estado. En tu Pi hazlo bien — carga la política permisiva solo si existe una bandera firmada/autenticada, y mantén la propiedad de superconjunto estricto (el debug solo puede añadir reglas, nunca quitar las de producción).
¿Quieres que te escriba el nftables.conf equivalente para tu Pi, modelado sobre estas políticas?
He encontrado este archivo para windows, tiene algo que ver?
[CmdletBinding(SupportsShouldProcess = $true)] param( [string]$MbtoolsPath = '', [switch]$Quiet )
Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $script:MbuxRuleName = 'MBTools-HU6-HTTPS-8443-v1' $script:MbuxRuleGroup = 'MBTools'
function Test-MbuxPortMatch { param([object[]]$Values) foreach ($entry in $Values) { foreach ($value in ([string]$entry -split ',')) { $value = $value.Trim() if ($value -in @('Any', '*', '8443')) { return $true } if ($value -match '^(\d+)-(\d+)$' -and [int]$Matches[1] -le 8443 -and [int]$Matches[2] -ge 8443) { return $true } } } return $false }
function Test-MbuxAddressMatch { param([object[]]$Values, [string]$Address) $target = [Net.IPAddress]::Parse($Address).GetAddressBytes() foreach ($entry in $Values) { foreach ($raw in ([string]$entry -split ',')) { $value = $raw.Trim() if ($value -in @('Any', '*', 'LocalSubnet', 'LocalSubnet4', $Address)) { return $true } if ($value -match '^([\d.]+)/([0-9]|[12][0-9]|3[0-2])$') { $network = [Net.IPAddress]::Parse($Matches[1]).GetAddressBytes() $remaining = [int]$Matches[2] $same = $true for ($index = 0; $index -lt 4; ++$index) { $bits = [Math]::Min(8, [Math]::Max(0, $remaining)) $mask = if ($bits -eq 0) { 0 } else { (255 -shl (8 - $bits)) -band 255 } if (($target[$index] -band $mask) -ne ($network[$index] -band $mask)) { $same = $false } $remaining -= 8 } if ($same) { return $true } } elseif ($value -match '^([\d.]+)-([\d.]+)$') { $first = [Net.IPAddress]::Parse($Matches[1]).GetAddressBytes() $last = [Net.IPAddress]::Parse($Matches[2]).GetAddressBytes() $number = [uint64]0; $low = [uint64]0; $high = [uint64]0 for ($index = 0; $index -lt 4; ++$index) { $number = ($number -shl 8) + $target[$index] $low = ($low -shl 8) + $first[$index] $high = ($high -shl 8) + $last[$index] } if ($number -ge $low -and $number -le $high) { return $true } } } } return $false }
function Get-MbuxFirewallNetwork { $addresses = @(Get-NetIPAddress -AddressFamily IPv4 -IPAddress '169.254.0.45' -ErrorAction SilentlyContinue) $profiles = @() $aliases = @() foreach ($address in $addresses) { $aliases += $address.InterfaceAlias foreach ($connection in @(Get-NetConnectionProfile -InterfaceIndex $address.InterfaceIndex -ErrorAction SilentlyContinue)) { $profiles += switch ([string]$connection.NetworkCategory) { 'DomainAuthenticated' { 'Domain' } 'Private' { 'Private' } default { 'Public' } } } } [pscustomobject]@{ Addresses = $addresses; Profiles = $profiles; Aliases = $aliases } }
function Test-MbuxBlockRuleMatch { param($Rule, [string]$Program, $Network, [switch]$ExactProgram) if ($Network.Profiles.Count -gt 0 -and [string]$Rule.Profile -ne 'Any') { $ruleProfiles = @(([string]$Rule.Profile -split ',') | ForEach-Object { $.Trim() }) if (@($Network.Profiles | Where-Object { $ -in $ruleProfiles }).Count -eq 0) { return $false } } $app = $Rule | Get-NetFirewallApplicationFilter $ruleProgram = [Environment]::ExpandEnvironmentVariables([string]$app.Program) if (-not [string]::Equals($ruleProgram, $Program, [StringComparison]::OrdinalIgnoreCase)) { if ($ExactProgram -or $ruleProgram -notin @('Any', '', '')) { return $false } } $service = $Rule | Get-NetFirewallServiceFilter if ([string]$service.Service -notin @('Any', '', '')) { return $false } $ports = $Rule | Get-NetFirewallPortFilter if ([string]$ports.Protocol -notin @('TCP', '6', 'Any', '256') -or -not (Test-MbuxPortMatch $ports.LocalPort)) { return $false } $type = $Rule | Get-NetFirewallInterfaceTypeFilter if ([string]$type.InterfaceType -notmatch 'Any|Wired') { return $false } $interface = $Rule | Get-NetFirewallInterfaceFilter if ($Network.Aliases.Count -gt 0 -and [string]$interface.InterfaceAlias -notin @('Any', '*', '')) { if (@($Network.Aliases | Where-Object { $_ -in @($interface.InterfaceAlias) }).Count -eq 0) { return $false } } $scope = $Rule | Get-NetFirewallAddressFilter return (Test-MbuxAddressMatch $scope.LocalAddress '169.254.0.45') -and (Test-MbuxAddressMatch $scope.RemoteAddress '169.254.133.27') }
function Get-MbuxFirewallWarnings { param([string]$Program) $messages = [Collections.Generic.List[string]]::new() $network = Get-MbuxFirewallNetwork foreach ($address in $network.Addresses) { if ($address.PrefixLength -gt 16) { $messages.Add("The Ethernet subnet /$($address.PrefixLength) does not include the HU6 address 169.254.133.27. Check the manual Ethernet subnet mask before retrying.") } } if ($network.Addresses.Count -eq 0) { $messages.Add('Ethernet address 169.254.0.45 is not currently configured. Keep the manual Ethernet setup and check this address before retrying HU6 setup.') } foreach ($profile in @(Get-NetFirewallProfile -PolicyStore ActiveStore)) { if ($network.Profiles.Count -gt 0 -and [string]$profile.Name -notin $network.Profiles) { continue } if ([string]$profile.Enabled -eq 'False') { continue } if ([string]$profile.AllowInboundRules -eq 'False' -or [string]$profile.AllowLocalFirewallRules -eq 'False') { $messages.Add("The $($profile.Name) firewall profile restricts inbound or local allow rules. An administrator may need to allow HU6 TCP port 8443 through company policy.") } } foreach ($rule in @(Get-NetFirewallRule -PolicyStore ActiveStore -Enabled True -Direction Inbound -Action Block)) { if (-not (Test-MbuxBlockRuleMatch -Rule $rule -Program $Program -Network $network)) { continue } $messages.Add("An explicit block rule may prevent this connection: $($rule.DisplayName). It was left unchanged; a block rule takes precedence over an allow rule.") } return $messages.ToArray() }
function Repair-MbuxHu6Firewall { [CmdletBinding(SupportsShouldProcess = $true)] param([Parameter(Mandatory = $true)][string]$Program) $Program = [Environment]::ExpandEnvironmentVariables($Program) if (-not [IO.Path]::IsPathRooted($Program) -or [IO.Path]::GetFileName($Program) -ine 'MBTools.exe') { throw 'The firewall target must be the full path to MBTools.exe.' } $Program = [IO.Path]::GetFullPath($Program) # The portable wrapper extracts this executable only while MBTools runs. # The file need not exist yet when this script is selected in Launcher. $owned = @(Get-NetFirewallRule -PolicyStore PersistentStore | Where-Object { $.Name -eq $script:MbuxRuleName }) if ($owned.Count -gt 1 -or ($owned.Count -eq 1 -and $owned[0].Group -ne $script:MbuxRuleGroup)) { throw 'The MBTools firewall rule name is already used by an unrecognized rule. No rule was changed.' } $settings = @{ Name = $script:MbuxRuleName PolicyStore = 'PersistentStore' Direction = 'Inbound' Action = 'Allow' Enabled = 'True' Profile = 'Any' Protocol = 'TCP' LocalPort = '8443' RemotePort = 'Any' LocalAddress = '169.254.0.45' RemoteAddress = '169.254.133.27' Program = $Program InterfaceType = 'Wired' EdgeTraversalPolicy = 'Block' } $changed = $false if ($PSCmdlet.ShouldProcess('MBTools HU6 HTTPS (TCP 8443)', 'Create or repair the scoped inbound firewall rule')) { if ($owned.Count -eq 0) { New-NetFirewallRule @settings -DisplayName 'MBTools HU6 HTTPS (TCP 8443)' -Group $script:MbuxRuleGroup ` -Description 'Allows the HU6 installer download to the MBTools HTTPS file server. Managed by MBTools Launcher.' | Out-Null } else { Set-NetFirewallRule @settings | Out-Null } $changed = $true } $disabled = [Collections.Generic.List[string]]::new() $network = Get-MbuxFirewallNetwork # PersistentStore contains local policy only. Pass the exact local CIM object # to avoid touching a policy rule or a similarly named rule in another store. if ($changed -or $WhatIfPreference) { foreach ($rule in @(Get-NetFirewallRule -PolicyStore PersistentStore -Enabled True -Direction Inbound -Action Block)) { if (-not (Test-MbuxBlockRuleMatch -Rule $rule -Program $Program -Network $network -ExactProgram)) { continue } $description = "$($rule.DisplayName) [$($rule.Name)]" if ($PSCmdlet.ShouldProcess($description, 'Disable the local MBTools inbound block rule overlapping HU6 TCP 8443')) { try { Disable-NetFirewallRule -InputObject $rule -Confirm:$false -ErrorAction Stop | Out-Null } catch { throw "Could not disable local MBTools block rule ${description}: $($.Exception.Message)" } $disabled.Add($description) } } } [pscustomobject]@{ Program = $Program; Applied = $changed; DisabledBlockRules = $disabled.ToArray(); Warnings = @(Get-MbuxFirewallWarnings $Program) } }
function Invoke-MbuxElevatedRepair { param( [Parameter(Mandatory = $true)][string]$ScriptPath, [Parameter(Mandatory = $true)][string]$Program, [switch]$Quiet, [string]$PowerShellHome = $PSHOME, [string]$WindowsDirectory = $env:SystemRoot ) # RunAs uses ShellExecute: use a real path visible to either architecture, # rather than the Sysnative alias (which only exists for 32-bit callers). $hostPath = Join-Path $PowerShellHome 'powershell.exe' foreach ($path in @($hostPath, $ScriptPath)) { if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Required repair file was not found: $path" } } if (-not (Test-Path -LiteralPath $WindowsDirectory -PathType Container)) { throw 'The Windows directory could not be found.' } if ($Program.Contains('"')) { throw 'The MBTools executable path contains an invalid quote.' } $arguments = '-NoProfile -ExecutionPolicy Bypass -File "' + $ScriptPath + '" -MbtoolsPath "' + $Program + '"' if ($Quiet) { $arguments += ' -Quiet' } $child = Start-Process -FilePath $hostPath -ArgumentList $arguments -WorkingDirectory $WindowsDirectory ` -Verb RunAs -WindowStyle Hidden -PassThru -ErrorAction Stop $null = $child.Handle $child.WaitForExit() $child.Refresh() return $child.ExitCode }
function Show-MbuxFirewallResult { param([string]$Message, [bool]$Failed, [bool]$Warning = $false) Write-Output $Message if (-not $Quiet) { Add-Type -AssemblyName System.Windows.Forms $icon = if ($Failed) { 'Error' } elseif ($Warning) { 'Warning' } else { 'Information' } [Windows.Forms.MessageBox]::Show($Message, 'MBTools - HU6 firewall repair', 'OK', $icon) | Out-Null } }
Dot-sourcing exposes the functions for tests without changing the machine.
if ($MyInvocation.InvocationName -eq '.') { return }
$stage = 'starting the repair'
try {
# Preserve the Launcher's user's target even if elevation uses another account.
if (-not $MbtoolsPath) { $MbtoolsPath = Join-Path ([IO.Path]::GetTempPath()) 'MBTools\App\MBTools.exe' }
$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
if ($WhatIfPreference) { throw 'Run an elevated PowerShell window for firewall inspection with -WhatIf.' }
$stage = 'requesting administrator access'
exit (Invoke-MbuxElevatedRepair -ScriptPath $PSCommandPath -Program $MbtoolsPath -Quiet:$Quiet)
}
$stage = 'loading Windows firewall support'
Import-Module NetSecurity -ErrorAction Stop
$stage = 'applying and inspecting the firewall rule'
$result = Repair-MbuxHu6Firewall -Program $MbtoolsPath -WhatIf:$WhatIfPreference
$message = if ($result.Applied) {
"The MBTools firewall rule is ready for the HU6 connection on TCP port 8443."
} else { 'Inspection completed. No firewall rule was changed.' }
if ($result.DisabledBlockRules.Count -gt 0) {
$message += "rnrnDisabled matching local MBTools block rules:rn" + ($result.DisabledBlockRules -join "rn")
}
$message += "rnrnKeep Windows Firewall enabled, then open MBTools and retry Set up HU6."
if ($result.Warnings.Count -gt 0) { $message += "rnrnAction required:rn" + ($result.Warnings -join "rnrn") }
$message += "rnrnHU6-to-PC connectivity must be confirmed by retrying setup. Third-party security software or vehicle routing can still block it."
Show-MbuxFirewallResult $message $false ($result.Warnings.Count -gt 0)
if ($result.Warnings.Count -gt 0) { exit 2 }
exit 0
} catch {
Show-MbuxFirewallResult ("The HU6 firewall repair could not complete while $stage.rnrn" + $.Exception.Message) $true
exit 1
}*
Sí — está directamente relacionado. Es la pieza del lado Windows del mismo ecosistema del que extrajiste /etc/firewall. Lo guardo en el workspace y te muestro por qué encajan:
Guardado en mbtools-hu6-firewall-repair.ps1. Ahora, la relación:
Sí: es la contraparte Windows del mismo sistema que ya analizamos
"HU6" = Head Unit NTG6 = la MBUX de Mercedes-Benz de la que extrajiste /etc/firewall. La prueba cruzada es una IP exacta:
| En el script PowerShell (PC Windows) | En tus políticas Linux (la unidad) |
|---|---|
RemoteAddress = 169.254.133.27 (la HU6) | 169.254.133.27 en firewall_prd.policy: -A OUTPUT -s 169.254.133.27/32 -d 169.254.0.0/16 -o eth0.1 -j ACCEPT |
LocalAddress = 169.254.0.45 (el PC) | cubierto por -d 169.254.0.0/16 en esa regla OUTPUT |
| Puerto TCP 8443 en el PC (servidor HTTPS de MBTools) | la regla OUTPUT de la HU permite conexiones salientes hacia cualquier 169.254.0.0/16 por eth0.1 — es la conexión de descarga |
Máscara /16 exigida (PrefixLength -gt 16 → warning) | coherente: la regla de la HU está escrita contra la red completa 169.254.0.0/16 |
| "HU6 installer download to the MBTools HTTPS file server" | en firewall_dbg.policy, la HU además acepta entrantes en 169.254.133.27 por eth0.1 en puertos 20581 y 20331 (solo modo debug) |
Topología completa (ambos lados)
[PC técnico Windows] [Unidad MBUX NTG6 "HU6"]
169.254.0.45/16 ──── cable Ethernet ─── 169.254.133.27 (eth0.1)
▲ MBTools.exe (HTTPS file server) firewall_prd/firewall_dbg.policy
│ espera TCP 8443 entrante OUTPUT: 169.254.133.27 → 169.254.0.0/16 ACCEPT
◄──────── la HU6 INICIA la conexión ────── (por eso el PC necesita regla INBOUND)
+ regla Windows: MBTools-HU6-HTTPS-8443-v1 + en debug: INPUT 20581/20331
La dirección 169.254.x.x es APIPA (link-local): configuración manual sin DHCP, cable directo. El script crea la regla para que la HU6 pueda descargar el instalador desde el servidor HTTPS de la herramienta MBTools que corre en el PC. Es el flujo de "Set up HU6" — flasheo/configuración de taller.
Además confirma nuestra identificación: "MB" de MBTools = Mercedes-Benz, y la IP del HU en el segmento link-local coincide con las reglas IF_INPUT de la política de debug (20581/20331 son probablemente los servicios de setup/instalación que MBTools contacta en la HU).
Observaciones de seguridad del script (lado Windows)
Está bien escrito (scope estricto, no toca reglas GPO, EdgeTraversalPolicy Block, rechaza reglas homónimas desconocidas), pero tiene dos debilidades relevantes para un CTF:
- Persistencia apuntando a %TEMP% — la regla de firewall queda fija en
PersistentStoreconProgram = %TEMP%\MBTools\App\MBTools.exe(ese es el path por defecto). El comentario admite que el ejecutable "solo existe mientras MBTools corre". Resultado: la regla sobrevive al cierre de la herramienta y autoriza a cualquier binario que se deposite en ese path → si un atacante local planta unMBTools.exemalicioso ahí, hereda un allow inbound 8443 ya existente y el script además desactiva block rules que se solapen. - Servidor de descarga = vector de flashing — la HU descarga el instalador por HTTPS desde el PC. Si se puede suplantar
169.254.0.45(mismo segmento L2) o si la HU no valida bien el certificado del servidor, es un canal de instalación de firmware. Es exactamente la clase de pivote que la investigación de KeenLab/Kaspersky documentó en este sistema.
Implicaciones para tu reto
El mapa de ataque queda ahora cerrado por ambos lados:
- PC→HU: en producción la HU solo acepta lo que ella inicia (stateful) + DoIP 13400 en eth0.1; en modo debug acepta 20581/20331 en
169.254.133.27— los puertos del flujo MBTools/HU6. - HU→PC: la HU puede iniciar TCP a todo
169.254.0.0/16; el objetivo natural es el 8443 del PC (descarga de instalador). - El pivote sigue siendo el mismo: activar el modo debug (
sa_reader→ 1) abre esos puertos y el SSH.
Si el reto te da también el entorno del PC (el MBTools.exe, el launcher o un pcap de la descarga 8443), súbelo — ahí es donde estaría la flag (por ejemplo, un instalador firmado falsificable o credenciales del servidor HTTPS). ¿Tienes el pcap o el binario de MBTools?
Pero en ese script dice como esta preparada la raspberyy pi zero ?=
Buena pregunta — pero no. Déjame verificarlo exhaustivamente en los 13 ficheros que tenemos:
No — el script no dice nada sobre una Raspberry Pi Zero
Lo acabo de verificar en los 13 ficheros: cero menciones de raspberry, raspi, zero, bcm27, bcm28, ARM, config.txt, dtb... nada. Lo que el script describe es esto y solo esto:
| Lo que el script dice | Significado |
|---|---|
LocalAddress = 169.254.0.45 | La IP del propio PC Windows (configuración manual link-local) |
RemoteAddress = 169.254.133.27 | La IP del "HU6" — la unidad a la que se conecta |
Regla inbound TCP 8443 para MBTools.exe | El PC abre un servidor HTTPS para que el HU6 descargue un instalador |
| Nada de plataforma | No menciona hardware, ni SBC, ni Raspberry, ni Zero |
"HU6" = Head Unit (NTG6) = la MBUX de Mercedes-Benz, no una Raspberry Pi Zero. La identificación del dispositivo sigue siendo MBUX NTG6/HERMES por la evidencia acumulada (coincidencia con la investigación de Kaspersky/KeenLab: IPs, puerto HiQnet 3804, DLT 3490, SSID "MB Hermes AP", _jpn, RSE, DoIP 13400).
Posible fuente de tu confusión: bcm0
En las políticas Linux aparece una interfaz bcm0/bcm1 — es el chip Wi-Fi Broadcom de la propia unidad (BCM89359, según KeenLab), no el BCM27xx/BCM2835 de una Raspberry Pi. Es una coincidencia de nombres de fabricante, nada más.
Si quieres saber de verdad qué hardware es
Con acceso shell al dispositivo, estos comandos lo revelan en segundos:
cat /proc/device-tree/model # "Raspberry Pi Zero W Rev 1.1" si fuera una Pi
cat /proc/cpuinfo | grep -i hardware # BCM2835 → Pi; otra cosa → no es Pi
ls /boot/config.txt /boot/start.elf # existen solo en Raspberry Pi
dmesg | grep -iE "raspberry|bcm2835"
cat /sys/firmware/devicetree/base/compatible
Si ejecutas eso en tu dispositivo y me pegas la salida, cerramos la cuestión del hardware con evidencia.
Y si tu objetivo es montar esto en una Pi Zero
Entonces la pregunta correcta es otra: el script no te dice cómo prepararla — solo documenta el lado Windows. Para replicar el firewall en una Pi Zero W tendrías que traducir tú los roles (es totalmente viable):
wlan0(AP de pasajeros) → la Wi-Fi BCM43438 de la Pi Zero W en modo AP (hostapd)usb0→ el gadget USB Ethernet OTG de la Pi Zero (natural parausb0!)pan0→ Bluetooth PAN (el chip de la Pi Zero W también lo soporta)eth0.1/VLAN 200 → necesitarías un adaptador USB-Ethernet adicional- Las reglas
iptables/ebtables/arptables→ portables casi 1:1, o a nftables
¿Quieres que te escriba el script de preparación completo de la Pi Zero W (hostapd + interfaces + nftables) que reproduzca este modelo de zonas y listas blancas?
si
Perfecto. Voy a crear el paquete completo de preparación de la Pi Zero W, fiel al modelo MBUX que analizamos. Primero compruebo si puedo validar la sintaxis de nftables en el sandbox:
nftables 1.1.6 disponible — podré validar la sintaxis de verdad con nft -c. Creo los ficheros:
Corrijo una línea rota que dejé en debug-mode.sh:
Ahora el README y la validación de todo:
El parser de esta versión no conoce ts como nombre — pruebo la forma numérica (el MBUX usa el tipo 68 directamente):
ip option solo acepta nombres (lsrr/rr/ssrr/ra) — Timestamp no tiene nombre en nft. Pruebo la vía de payload crudo (@nh) + ip hdrlength, que reproduce el u32 de MBUX bit a bit:
El parser sugiere la forma antigua con comas. Pruebo variantes:
@nh,160,8 0x44 funciona — es la réplica exacta del u32 de MBUX (0x14>>0x18&0xff). Corrijo el firewall para usar la forma validada:
✅ Paquete completo creado y validado sintácticamente (nftables 1.1.6 en modo check + bash -n). Todo está en pi-zero-firewall/:
Los 8 ficheros
| Fichero | Qué hace |
|---|---|
README.md | Correspondencia MBUX→Pi, preparación, hardware, verificación, lecciones |
00-prepare-system.sh | Instala paquetes, crea el gadget usb0 (dwc2+g_ether), forwarding, instala configs, valida nftables, habilita servicios. Idempotente |
nftables.conf | El firewall — port fiel de firewall_prd.policy |
debug-rules.nft | Overlay de debug — solo añade reglas en dbg_input/dbg_forward |
debug-mode.sh | La puerta de debug — lección de firewall_dbg.sh hecha bien |
hostapd.conf | AP Pi-Hermes-AP en wlan0 (WPA2) |
dnsmasq-firewall-ap.conf | DHCP+DNS solo para la zona AP |
dhcpcd-firewall.conf | IPs estáticas: wlan0=192.168.220.1, usb0=192.168.42.1, eth0=WAN por DHCP |
Fidelidad al MBUX real
- Subredes exactas: AP de clientes
192.168.220.0/24y debug USB192.168.42.0/24— las mismas que en las políticas reales;usb0aquí es literal (el OTG de la Pi Zero creausb0). - DROP por defecto en input/forward/output; whitelist por zona (DHCP 67/68, DNS 53 solo hacia
.1, NTP 123, mDNS 5353 y admin 8100 solo por usb0, SSH solo desde la zona de debug). - Anti-recon del u32 portado bit a bit:
ip hdrlength 6-15 @nh,160,8 0x07/0x44≡ el u32 original (IHL 6-15+ opción0x7=Record Route /0x44=Timestamp). Detalle técnico: nft no tiene nombre para la opción Timestamp, así que usé payload crudo — validado contra el parser. - Anti-spoofing ≈
arptables_*.policy(tablaarp pi_arp: clientes suplantando redes internas → drop), aislamiento de zonas ≈ los 18 DROP cruzados de MBUX. - Modo debug = superconjunto estricto:
debug-mode.sh onsolo rellena los overlays (+SSH desde LAN,+DLT 3490 en usb0— homenaje al DLT real); la base jamás se toca. La puerta es explícita (DEBUG_AUTHORIZED+ todo a syslog), no unsa_readeropaco. - Logs grepeables
PI4T-*en homenaje a losIP4T-*reales.
Puesta en marcha
scp -r pi-zero-firewall/ pi@<pi>:~/ && ssh pi@<pi>
sudo bash pi-zero-firewall/00-prepare-system.sh
sudo nano /etc/hostapd/hostapd.conf # SSID y contraseña reales
sudo reboot
Nota honesta: he validado sintaxis (nft -c, bash -n), pero el comportamiento en runtime (hostapd con el BCM43438, el gadget g_ether, NAT real) requiere probarlo en la Pi física — el README incluye la lista de verificación paso a paso (nft list ruleset, hostapd_cli all_sta, pruebas de zona cruzada y spoofing). Si algo falla al probarlo, pégame el error y lo depuramos.*
