Реверс-инжиниринг. Это просто!
исследование устройств, ремонт, разработка
ZigBee sniffer
Для просмотра радиоканала использую CC2531 + Wireshark. Опишу процесс настройки.
1. Железо
Что бы прошить CC2531 нужен CC-Debuger.
2. Программное обеспечение
3. Прошивка
Устанавливаем все вышеперечисленное. Подключить CC2531 к CC-Debuger, подать питание на плату. Если все сделано правильно, то нажатие на кнопку RESET, на программаторе, приведет к включению зеленого светодиода расположенного рядом с кнопкой. Далее: Запустить \Texas Instruments\SmartRF Tools\Flash Programmer\bin\SmartRFProg.exe Выбрать файл прошивки \Texas Instruments\SmartRF Tools\Packet Sniffer\bin\general\firmware\sniffer_fw_cc2531.hex В поле Actions выбрать Erase, program and verify, нажать кнопку Perform actions; Если чип правильно определяется программатором и в ПО, но при прошивке вылазит ошибка, то попробуйте в начале выполнить действие Erase и после этого пункт 3. Драйвер на новое устройство, CC2531 Sniffer, устанавливается из той же папки что и драйвер для CC-Debuger.
4. TiWsPc
Программа создает pipe для трансляции данных от CC2531 в Wireshark. Запустить TiWsPc.exe. Нажать Device Configuration. Должно быть такое окно
В поле Configuration выбирается номер канала для прослушивания. Для примера 11. Нажать Start. Run на зеленом фоне говорит об успехе. Окно конфигурации можно закрыть. В основном окне нам понадобится строка \.\pipe\tiwspc_data , позже её нужно будет внести в настройки Wireshark.
5. Настройка Wireshark
Запускаем Wireshark.exe. Переходим в Edit / Preferences… / Protocols / ZigBee / Edit / В поле Security Level выбрать AES-128, 32 bit Нажать кнопку + и внести ключ 5A:69:67:42:65:65:41:6C:6C:69:61:6E:63:65:30:39 Сохранить все изменения.
Это стандартный ключ, в некоторых случаях могут быть другие.
С главного окна Wireshark переходим Capture / Options… / Manage Interfaces… / Pipes Нажать кнопку +. Будет создан канал с названием New Pipe. Переименовать его в \.\pipe\tiwspc_data (из TiWsPc). Сохранить изменения и перейти в главное окно.
В качестве объекта захвата (Capture) выбрать созданный pipe и нажать старт (Ctrl+E). Устройство готово к работе.
6. Общая информация
В окне вывода Wireshark ничего не будет если на выбранном канале (TiWsPc) нет активности.
Помимо стандартного ключа, внесенного в Wireshark, есть ещё один ключ который выдается устройствам при подключении к координатору. (чаще всего так, но могут быть варианты) Wireshark умеет самостоятельно перехватывать этот ключ и применять его для расшифровки последующих сообщений. После перезапуска Wireshark перехваченный ключ будет утерян, так его лучше сохранить в случае длительной работы с созданной сетью.
На тему настройки Wireshark есть видео от Freescale.
# Sniff Zigbee traffic
Sniffing Zigbee traffic can be handy sometimes. E.g. when you want to analyze the commands used by a device.
# With CC2531
# Prerequisites
- Computer
- Ubuntu / Debian machine (tested with Ubuntu 18.04 / 18.10 and Debian 10)
- Windows machine (tested with Windows 10)
- CC2531 stick
# 1. Flashing the CC2531 stick
The CC2531 needs to be flashed with a sniffer firmware. Flash the firmware using the instructions from Flashing the CC2531.
# Linux
The firmware is included with PACKET-SNIFFER
open in new window (not PACKET-SNIFFER-2!). Download PACKET-SNIFFER. As the sniffer firmware is only available in the windows installer we need to extract the hex file. This would require 7zip (p7zip-full or p7zip-plugins package depending on distro)
# Windows (and possibly Ubuntu)
For Windows this firmware is included with ZBOSS
open in new window . Register an account and download Zigbee sniffer package rev. 2.0. Included in the ZIP file is the firmware in subfolder zb_sniffer_bin\zb_sniffer_target\CC2531 USB dongle\zboss_sniffer.hex . Please note that ZBOSS is also available for Ubuntu 64-bit.
# 2. Installing required tools
# Ubuntu / Debian
# Windows
Download and install the latest version of Wireshark
open in new window . ZBOSS itself is portable and won’t need to be installed.
# 3. Sniffing traffic
On Ubuntu / Debian start wireshark with sudo whsniff -c ZIGBEE_CHANNEL_NUMBER | wireshark -k -i — . Note: Depending on your distro and installed packages, this may result in a broken pipe after some time. You will notice that Wireshark has stopped capturing, and attmpeting to resume by clicking the shark fin icon will present you with an error end of file on pipe magic during open , if this happens you may need to start with wireshark -k -i instead. Alternative uses are detailed on the whsniff project page
For Windows run the ZBOSS executable in gui\zboss_sniffer.exe , enter the path to your Wireshark executable and click on the Start button. For ZBOSS make sure the correct Zigbee channel is set, by default it will sniff on channel 0x0C (12) but the default Zigbee2MQTT channel is 11 ( 0x0B (11) ).
Wireshark will start and log the Zigbee messages. As these messages are encrypted we need to add 2 encryption keys. The first one is the Trust Center link key, which is the same for (almost) every Zigbee network. The second one is the network encryption key (Transport Key).
Add the Trust Center link key by going to to Edit -> Preferences -> Protocols -> ZigBee. Set Security Level to AES-128 Encryption, 32-bit Integrity Protection and click on Edit. Click on + and add 5A:69:67:42:65:65:41:6C:6C:69:61:6E:63:65:30:39 with Byte Order Normal.
Next we need to figure out the network encryption key (Transport Key). There are two ways to do this:
By default, if you haven’t changed network_key in your configuration.yaml this will be 01:03:05:07:09:0B:0D:0F:00:02:04:06:08:0A:0C:0D . If you changed your network_key , then convert each number into its 2-digit hexadecimal value, and combine them all with : between. E.g. [1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13] -> 01:03:05:07:09:0B:0D:0F:00:02:04:06:08:0A:0C:0D .
You can paste your network_key below to convert it. PS: Of course it gets not sent anywhere, just a local in-browser converter.
If you don’t want to translate the numbers, the network encryption key is also exposed when a device joins the network. Pair a new device to the network (or re-pair an existing one) and grab the message where the Info is Device Announcement. . Open the message and expand ZigBee Network Layer Data -> ZigBee Security Header.
Copy the key value, as shown above and go to Edit -> Preferences -> Protocols -> ZigBee -> Edit and add the key with Byte Order Normal.
Now Wireshark is able to decrypt the messages. When e.g. turning on a light you will see a message similar to:
# Troubleshooting
- If you get couldn’t run /usr/bin/dumpcap in child process: permission denied when running whsniff, check if /usr/bin/dumpcap is executable for everyone. Or chmod 755 /usr/bin/dumpcap .
- You may need to remove modemmanager as this has been known to cause issues. Howto
# With HUSBZB-1 and EZSP USB sticks
If you happen to have a spare HUSBZB-1 or EZSP stick, you can also use this to sniff traffic.
# Prerequisites
- Computer
- Ubuntu machine (tested with 18.10)
- Windows machine (tested with Windows 10)
- HUSBZB-1 or EZSP stick
- Wireshark
- Java
# 1. Install drivers
# Ubuntu
On linux systems, the HUSBZB-1 or EZSP stick should work out of the box with no modifications.
# Windows
Found on https://www.amazon.com/gp/customer-reviews/RSPH6UCG0N3WK/
- Download Silicon Labs CP210x drivers (Amazon won’t let me link this, but it should be easy to Google)
- Extract drivers to a folder (I’ll use C:\CP210x_Windows_Drivers as an example)
- Open Windows Device Manager (Win+X, M)
- Right-click on «Other Devices > HubZ ZigBee Com Port» (NOT Z-Wave) and select «Update driver»
- Select «Browse my computer for driver software»
- Select «Let me pick from a list of available drivers on my computer»
- Leave «Show All Devices» selected and click «Next»
- Click «Have Disk»
- Enter the folder name where you extracted the downloaded drivers: C:\CP210x_Windows_Drivers
- Select «Silicon Labs CP210x USB to UART Bridge» and click «Next»
- Windows will prompt that it cannot confirm the device ID, click «Yes» to proceed.
- Write down the com port of the ZigBee device, something like COM5 or COM6.
- You can find this by going to «Ports (COM & LPT)» in the device manager
# 2. Installing required tools
Both Windows and Ubuntu use the same program for sniffing. Scroll down to the bottom of the README of https://github.com/zsmartsystems/com.zsmartsystems.zigbee.sniffer to find how a precompiled jar file can be downloaded.
# Ubuntu
No extra software besides ZigbeeSniffer.jar and Wireshark is needed
# Windows
Download and install https://nmap.org/npcap/ and make sure you select to install the «Npcap Loopback Adapter» when installing. It shouldn’t matter whether or not you use Winpcap compatibility mode.
# 3. Sniffing traffic
In a terminal or command line, run java -jar ZigbeeSniffer.jar -baud 57600 -flow hardware -port
Once you have the application running, you should see it connect to and start sniffing traffic on the network.
After that, open up Wireshark and start capturing on the loopback adapter.
Then, apply a filter udp.port == 17754 in order to filter down to only Zigbee traffic.
Lastly, follow the steps of the CC2531 instructions above to set up your encryption keys the same.
zsmartsystems/com.zsmartsystems.zigbee.sniffer
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This project uses the com.zsmartsystems.zigbee.dongle.ember driver to provide a ZigBee sniffer interface for Wireshark, and optionally write the data to a Silabs compatible event log. The software will connect to an Ember dongle using a serial interface, and send UDP packets on port 17754 which can be received and displayed by Wireshark.
To use Wireshark, the loopback interface needs to be selected, and then a filter udp port 17754 is used to only display ZigBee packets.
Set the port -r,—ipport Set the remote IP port -s,—silabs Log data to a Silabs ISD compatible event log -t,—timeout NCP restart timeout in seconds -w,—pcap Log data to a Wireshark pcap compatible log -d,—device-id Set the device ID that will be included in ZEP frame»>
Note that the IP address will default to the local host on the assumption that you are running Wireshark on the same computer as the sniffer. The ipport will default to 17754 which is the port used for the ZigBee Encapsulation Protocol — changing this may stop Wireshark displaying ZigBee data.
Example command line -:
The software will print an output to the console for each packet that is received to allow confirmation it is working. When running Wireshark, these should also be seen in the Wireshark window.
If the NCP fails to receive a valid frame with the timeout period set with the timeout command line parameter, then the NCP will be restarted. This will allow the sniffer to recover from serial port or NCP communications problems. The timer defaults to 30 seconds.
A compiled JAR file can be found here along with further documentation.
When using Wireshark to display the packets, the raw IEEE 802.15.4 packet received by the Ember module is first encapsulated in a «TI CC24xx» frame format, then in a ZEPv2 (ZigBee Encapsulation Protocol version 2) frame format before being sent using UDP. Using the «TI CC24xx» frame format permit passing the RSSI value but has also limitations:
- The «RSSI» value is correctly sent using a signed integer value in dBm
- The «FCS Valid» field is always set to true as the Ember module discards invalid packets
- The «LQI Correlation Value» is limited to a range of 0 to 127 (whereas the Ember module and the norm are defining this value for the range 0 to 255), so the displayed value is divided by 2.
Jerome-PS/JN516xSniffer
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
readme.md
Transform a Xiaomi Zigbee gadget into a Zigbee sniffer.
This has been tested on the Xiaomi Smart Button.
Quickstart on Linux
Start sniffing session from terminal:
Running ./Sniff.py -h will give you a list of detected serial ports.
Quickstart on macOS
Start sniffing session from terminal:
Running ./Sniff.py -h will give you a list of detected serial ports.
Quickstart on Windows
Open command line, cd to the folder containing the scripts and launch:
Running python Sniff.py -h will give you a list of detected serial ports.
Table Of Content
Compiling the sniffer
You will need the NXP JN-SW-4163 SDK in order to compile the source code.
There is a precompiled binary in the bin folder. TODO: Check that it is up to date.
Compiling on macOS or Linux
You can use the latest version of JennicModuleProgrammer in order to flash you JN5169 device.
Compiling on Windows
You can download NXP’s Beyond Studio in order to compile the source code. In eclipse, use the import from C/C++ Makefile menu. You can then use the programmer integrated in the IDE. Do not use any other programmer provided by NXP, because they do not support JN5169 (at least none that I could try out).
Using the sniffer
Using on macOS or Linux
On Linux, you will need to be in the dialout group, in order to have enough access rights to access the serial port, as well as in the wireshark group for executing pcap. The script will prompt you to do it if it detects the issue.
Using on Windows
If you are using Windows, you will have to run the Sniffer.py script (you’ll need the win32api and PySerial modules). You must pass the serial port name as the first parameter and optionally the wireshark.exe path as the second argument. Sadly, lua script parameter forwarding does not seem to work. So you might have to use the GUI in order to set your preferences. You can use an installed version of Wireshark or WiresharkPortable. You will need to run the python script as follows (from the directory where the .py and .lua scripts are and change the COM port and path as needed):
You must send a start command in order to initialize Wireshark and the sniffer device and subsequently get packets. Use the ZB menu. You will not see anything in Wireshark until you send the start command using the Tools/ZB/ZB Start menu command. Please make sure to select the correct channel, or you won’t capture any frames. The Sniffer will send you a dummy frame to indicate the current channel every time you change it.
Using the GUI to set the preferences
Note that changing the parameters in this dialog will try and send an update to the MCU.
Xiaomi Door sensor
Wiring colors are :
- Purple: Tx (OUT from MCU)
- Green : Rx (IN to MCU)
- Bleue : nBootloader
- Red : 3V3
- White : nReset
- Black : GND You can optionally connect the nReset signal to your serial port nRTS signal and your nBootloader to the nDTR output.
Xiaomi smart button
- Purple: Tx (OUT from MCU)
- Green : Rx (IN to MCU)
- Bleue : nBootloader
- Red : 3V3
- White : nReset
- Black : GND You can optionally connect the nReset signal to your serial port nRTS signal and your nBootloader to the nDTR output.
Xiaomi smart button UART1
- For UART1 Tx, on this side of the resistor, we have the CPU pin directly.
- You can find some GND on this tantalum capacitor.
This project is based on work from @KiwiHC16 . He also helped me debug this documentation and a few version incompatibilities.
Wireshark might get confused if your MCU sends data before Wireshark has been initialised properly. To avoid this, please reset your MCU and ask it to send data with the ZB/start menu.
You can debug the communication with the following command:
You can view the file content like this:
The lua script creates a file named lua.log in the folder wireshark is started.
You can also pass the dissector parameters through environment varaibles:
FIFO troubles (obsolete)
If you get stuck with remaining data in the FIFO that repeatedly crashes wireshark, you can destroy the pipe and re-create it:
This should not be necessary any more, as the FIFOs are destroyed when leaving the Sniff.py script.
The Sniff.py script has been developped using Python3.6, so this, or a more recent, version of Python3 is recommended. It has not been extensively tested using Python2.
- Add LQI information to the packet
- Add frame duration computation as well as inter frame gap (wireshark)
Original serial queuing functions took 43125us for 26 bytes (166us/byte) and 4923 us for 31 bytes (159us/byte) with a 115200 baud/s UART and 10272us for 26 bytes (395us/byte) and 12860 for 31 bytes (415us/byte) with a 1MBaud/s UART. What the hell? memcpy algo takes 636 us for 26 bytes (24us/byte) and 848 for 43 bytes (20us/byte). The longer runtime/byte might come from the fact that the likeliness of having time stolen by an ISR is higher if you take more time. I might do some additional tests with disabled IT to try and get more consistent results.
At 2.4GHz, Zigbee uses a 62500 Hz symbol clock. These symbols encode 4 bits each, providing an on the air bitrate of 250Kbits/s.
Packets are timed with this clock, and have therefore a 16µs resolution.
Send ACK between macSIFSPeriod = 12 symbols >> 192µs and macAckWaitDuration = macSIFSPeriod + phySHRDuration + ceiling(7 × phySymbolsPerOctet) = 12 symbols +
bits are 250kHz (4µs), symbols are 62.5kHz (16-ary, so 4 bits/symbol) 192µs
- Check IT priority, so UART does not prevent packet management at the radio level.
- Fill Tx FIFO before starting Tx ISR to limit the number of ISR.
About
Transform a Xiaomi Zigbee gadget into a Zigbee sniffer.