Custom firmware on LKS32

Linko Semiconductor Co., LTD. is a privately held company specialized development of ICs for motion control, based in Nanjing (China). It produces cost-effective ICs with integrated MCU (motor control unit); the LKS32 comes with a 32bit MCU.

I’m interesting in running custom firmware on this chip because Xiaomi, more specifically Brightway, uses it in it’s latest electric scooters models. For experimentation, I ordered a few matching LKS32MC081 samples from a friendly seller on Alibaba.

One of the LKS32MC081 chips I bought

Programming the chip

All relevant documents and software for programming the LKS32MC08x chip can be found here: https://www.lksmcu.com/index.php/LKS08Series-en/.

Even though one should be able to manually program the chip using the flash controller registers, I found it more convenient to use the tools provided by Linkosemi.

I was able to compile and download a custom Blinky program (attached below) onto the chip.

Running Blinky on LKS32MC081

Attachment: Blinky program for LKS32MC08x

int main(void)
  while (1)
    GPIO_SetBits(GPIO0, GPIO_Pin_6);
    GPIO_ResetBits(GPIO0, GPIO_Pin_6);

Custom firmware on Xiaomi (Yeelight) night lamp

SWD debugger attached to Yeelight BLE module

The Xiaomi Mi Motion Activated Night Light is a relatively cheap device that comes with a Xiaomi MHCB05P BLE module (the same module is used in the latest Xiaomi electric scooters).

I was able to dump the existing firmware, since the flash was not read-out protected. After this, I compiled and download my own code to the module.

The LED strip of the light is connected to P0_0 of the BLE module and I flashed some classic Blinky code that turns the GPIO pin on and off in a fixed interval.

Running Blinky custom firmware on Yeelight

Going further

The next step is publishing a BLE service that allows turning the lamp on and off. It would also be interesting to make use of the motion sensor and broadcast messages over BLE whenever motion is detected.

Hardware RevEng Security

Hacking Brightway scooters: A case study

Xiaomi 3 Lite dashboard with attached SWD and UART wires

Choose your character!

Brightway (Brightway Innovation Intelligent Technology (Suzhou) Co., Ltd.) produces scooters for the NAVEE and Xiaomi brand. The latest additions to the Xiaomi portfolio are the Electric Scooter 3 Lite, 4, 4 Pro and 4 Ultra. With exception of the 4 Pro, all are produced by Brightway. If you’re hearing the name Brightway for the first time and want to learn more about every Xiaomi scooter released, check out my previous blog post.

The cheapest Xiaomi/Brightway model is the 3 Lite. It costs almost the same as the Xiaomi/Ninebot Mi 1S, but has somewhat weaker specs, such as a 5200mAh instead of a 7650mAh battery. So what’s the point of buying this seemingly inferior scooter? Well… it’s security research! By studying the inner workings of the 3 Lite, both from a hardware and a software standpoint, we can shed a light onto how serious Brightway takes security in their scooters.

In this blog post, I will be dismantling my newly bought 3 Lite scooter. After an initial introduction, I’m giving insights into the pairing and activation procedure, after which I describe the available registers, the command and message format and the structure of the serial numbers. It follows a detailed description of all the hardware and respective SOC memory layouts, after which I look at the UART and BLE protocols. Lastly, I will talk about the obvious security flaws discovered in the 3 Lite and how this relates to all other new Xiaomi scooter models.


In this section, I’ll be giving a short overview over the essential scooter components, for those of you who are not familiar with previous Xiaomi models or electric scooters in general.

Even though riding the scooter is possible without any app whatsoever, Xiaomi requires you to watch a training video and prove that your the legitimate owner of the vehicle. Only after this is done, restrictions imposed upon speed and such are lifted. Apart from that, an app is helpful for reading or controlling scooter parameters (more in section „Info registers“).

Diagram showing all components involved in the scooter communication, based on the latest Xiaomi specification

Several components are involved in the communication between your phone and the scooter. The communication process is the following:

  1. Create secure channel between the app on your phone and the scooter BLE module, which for Xiaomi scooters is located within the dashboard.
  2. Send commands from app to scooter over the secure BLE channel.
  3. Pass commands designated to the electronic speed controller (ESC) or battery management system (BMS) via UART bus.
    Commands can have different targets: the dashboard (BLE) itself, ESC or BMS.
  4. Pass responses, packed into commands, back to the user over the secure BLE channel.

To ensure device security, each one of these components and pathways needs to be secure.

Pairing process

Xiaomi started rolling out a stronger bonding mechanism with the 3 Lite and 4 Pro models. For connecting with the scooter, you have to download the Xiaomi Mi Home app. After scanning for scooters and selecting your 3 Lite scooter, the app asks for the camera permission. Now, you scan a QR code that’s printed on top of a sticker that covers the dashboard. After the QR code is verified by the app backend server, you’re connected. A button press is no longer required.

The QR code is stored in the app and can be viewed while being connected to the scooter. The app tells you to take a screenshot of the QR code in case you lose the original one.

Usage note: Every time you remove the scooter from the app and re-add it, you have to scan the QR code. However, the verification fails unless you do a BLE hard-reset first (throttle + 5x button press).


When you first turn on the 3 Lite it will constantly beep and be speed-limited to 10 km/h. Just like with previous (Xiaomi/Ninebot) models, you have to activate it. The activation button becomes available after watching the usual introduction video in the Mi Home app.

I’m greeted by a firmware update dialog immediately after connecting to the scooter. This update is not mandatory and the dialog can be dismissed.

Mi Home app offering firmware update for 3 Lite

Info registers

At this point, I will refer to the Mi Home scooter app as the „Brightway plugin“. The way Mi Home works is that it provides an API which vendors can use to integrate their hardware, as a plugin. Now, since the 3 Lite is produced by Brightway, their plugin looks and feels different from the Ninebot plugin some us of are used to. Nonetheless, the provided functionality and available information is equivalent. By looking into the Brightway plugin script source code, we can locate all register addresses with their respective functions (typos included [sic]).

[Weak=1E, Middle=3C, Strong=5A]
Registers described in the plugin JSON

Command and package format

The Brightway plugin script gives further insight into the command types and how a package is defined.

Command types

A package consists of DATA plus the checksum of DATA. A custom function is used to calculate the checksum. DATA is defined as follows:

  • TYPE is a command type (see table)
  • ADDRESS is a register address (see table)
  • REST is the number of packages remaining, in the case where multiple packages have to be send
  • LEN is the length of the PAYLOAD
  • PAYLOAD is the actual hex values to transmit

Both the command sent to the scooter and the commands received follow this format specification.

Serial numbers

Brightway scooters have a 20-character SN format:
5-digit prefix + '/' + 14-character suffix.

The SN prefix is used to identify different regions. The following table shows all known prefixes for the 3 Lite (valid prefixes start with a ‚3‘) and their restrictions.

SN PrefixRegionBacklightOnCruiseControlSpeed
All 3 Lite SN regions with their restrictions
✅: No restriction
❌: Restricted

SNs are stored on MCU (ref. 0x93FC in EEC0130, 0x23f14 in image) but read and processed by BLE (ref. 0x1e63e in MCU0214).

BLE Encryption / Decryption

The 3 Lite broadcasts the BLE device name „dreame.scooter.epro“. The naming choice isn’t surprising: in my last blog post I explained the relation between Brightway and Dreame.

NrfConnect showing the 3 Lite BLE broadcast data

The 3 Lite provides a BLE GATT service for authentication and another service for TX/RX and broadcasting the button press using the followings UUIDs:

  • Service: 00000101-0065-6C62-2E74-6F696D2E696D
  • TX/RX: 00000100-0065-6C62-2E74-6F696D2E696D
  • Button: 00000102-0065-6C62-2E74-6F696D2E696D

For BLE authentication the Brightway plugin uses MIOT BLE SecurityLock: encryptMessage() and not encryptMessageWithToken(). What’s the difference, you ask?

  • encryptMessage() uses MIOTBluetooth.encryptMessageXiaoMiBLE() -> securityChipEncrypt() [Same as StandardAuthEncrypt()] -> ECDH with secp256r1 curve (we know this crypto)
  • encryptMessageWithToken() uses MIOTBluetooth.miotBleEncrypt() -> miotBleEncrypt() -> BLECipher (MixA, MixB, old crypto)

We already know the type of encryption/decryption scheme used. What’s new is the call of the function securityChipEncrypt(). Wait, what… Security chip? Very interesting! A BLE packet sniff reveals an exchange of certificates, likely related to the QR code. Further, memory footprints contains records of a 7-step authentication process involving the secure chip. This is a noticeable divergence from previous authentication methods.

Unverified: Since the QR code is used for bonding, it likely contains data which can only be decoded by the Mi Home app. This data could be the certificate (public key) that is transmitted in the key-exchange.

Hardware breakdown

The following section identifies all ICs used by the manufacturer. This is a necessary step for the examining device security and the potential for modification.

Starting with the dashboard, it has the label „P2185_Display_V2.0 211126“ printed on it. The dashboard looks almost identical to the „P2223_Display_V1.0.1 20220111“ of the NAVEE S65. Luckily for us, both boards expose them SWD ports! The P2223 has all SWD pins labeled, the P2185 has not (but, it’s easy to find out). Check the image below for the correct SWD pin assignment.

P2185 („3 Lite“): SWD pins identified
P2223 (NAVEE S65): [Source] reveals a lot of internal information

We already observed the app code hinting at the existence of a secure chip. When first examining the hardware, I could not find any such chip. Only with the help of my microscope and zooming into one of the small ICs on the dashboard I could locate a component that turned out the be the legendary „MJA1“ secure chip!

Dashboard comes with a MJA1 secure chip – I’m probably the first person posting a photo of this special Xiaomi component!
VendorPart numberFunction
Xiaomi/RealtekMHCB05P-IB module with RTL8762C chipBLE Mesh
XiaomiMJA1 HCIWSecure chip
?????? (hidden underneath display)20-Pin Display driver IC
Dashboard components

As for the ESC, the part numbers are difficult to read, since the board is potted in a thick layer of transparent encapsulation resin (too thick to be conformal coating). Nevertheless, I could identify all but one component with my microscope, by using its integrated light source past the reflective layer.

VendorPart NumberFunction
LinkosemiLKS32MC081C8T8Motor control unit
ThinkisemiP55NF061N-channel power MOSET
Silan (SL)SD4931Current mode PWM controller
SamwinSW062R08E8T6x N-channel enhanced mode MOSFET
Controller (ESC) components
The only ESC component I could not identify

This SoCs!

Having identified all hardware components, it took me quite some time to gather the relevant documents and get a clear understanding of the SoC characteristics. This section lists the specs and the memory mapping table of each SoC.

BLERTL8762C (MHCB05P)Cortex-M4ARMv7-M128KB384KB512KB
SOC specs: MCU has limited resources – logic is handled by BLE!
AreaStart addressEnd addressSizeFunction
ROM0x00x5 FFFF384KBBootloader, BT-Stack, Flash driver
RAM (Data)0x20 00000x21 BFFF112KBRAM code
> ROM Data0x20 00000x20 2FFF12KBVariables of ROM
> Main Stack0x20 30000x20 37FF2KBMSP
> Patch RAM10x20 38000x20 7BFF17KBVariables/RAM code of Patch
> APP/Data RAM0x20 7C000x21 7FFF65KBVariables/RAM code of APP + Data heap
> Patch RAM20x21 80000x21 BFFF16KBOptional, same as Patch RAM1
RAM (Cache)0x21 C0000x21 FFFF12KBSpeed up SPI Flash R/W
SPI Flash (Cached)0x80 00000x9F FFFF512KBWith cache (faster)
> Reserved0x80 00000x80 0FFFReserved
> OEM Header0x80 10000x80 1FFFConfig: BT address, AES Key, flash layout
> OTA Bank 0Data and code
> OTA Bank 1Same as Bank 0
> FTLAccess flash with logic address
> OTA TempOTA backup
> APP DefinedUser defined
Memory mapping: RTL8762C
AreaStart addressEnd address
RAM0x2000 00000x2000 1FFF
SYS CTRL0x4000 00000x4000 03FF
FLASH CTRL0x4000 04000x4000 07FF
Memory mapping: LKS32MC08x


The bus between dashboard and controller is no longer realized by a single-wire (1-wire) UART, like in previous Xiaomi scooter models. The 3 Lite downright uses the standard UART mode: one wire for TX, one wire for RX. The MCU-UART is configured as follows: baudrate = 19200, data length = 8 bit, stop bit len = 1 bit, LSB, even parity, check disabled, multi-drop disabled.

Curiously, my recordings do not contain messages, but pulses with three possible state values.

UART protocol: only three different values

A single pulse follows the pattern: F[H|L][H|L]

In reality, only two of the four possible combinations are used: FLL, FHL. We can conclude that FLL translates to „0“ and FHL translates to „1“. I visualized the sampled data using a tool called binocle, which helps identifying recurring patterns.

Commands send via UART-TX, visualized with binocle
Data received via UART-RX, visualized with binocle

At the time of conducting the experiments and recording the UART transmission, I didn’t know about the correct parameter stated in the first paragraph. For recording the data, I used a higher baudrate than specified by the MCU. Please leave a comment, if you can verify seeing similar values and patterns in your recording with the correct baudrate set.

If we assume these captures to be accurate, then it means that both the BLE and MCU have a buffer to store incoming packets and then translate them back to messages, as defined in the „Commands and message format“ section.

3 Lite: Security oversights

Both the dashboard and controller board expose debugging pins (SWD). These have been left active and allow connection via OpenOCD. I quickly discovered the first security oversight by Brightway: the manufacturer left the content of both SOCs unprotected! I was able to generate full dumps of both BLE and MCU firmware, without any special measures, following the memory mapping tables laid out above.

The second oversight is that the firmware update (OTA) files for both the BLE (called „EEC“) and MCU come unencrypted, meaning that they can be decompiled without further measures. Analysis of these files allowed me draw some of the conclusions in this blog post, e.g., about the UART configuration. I could further observe that the MCU firmware, being very limited in size, contains almost no logic and that its main purpose is motor control.

Last year, Xiaomi introduced firmware signing to secure the BLE firmware from tampering. The BLE/EEC firmware for 3 Lite is signed in accordance to this new Xiaomi standard. However, the MCU firmware is not! This could potentially allow altering the content of the update (OTA) file before passing it to the BLE. This has the hard requirement of having the authentication and update procedure fully reverse-engineered.

What’s strange about the MCU firmware OTA file is that it’s almost three times larger than the MCU flash size. Next to the MCU flash/app content, this file contains one large code section of what seems to be executable DFU loader code and another section of what seems to be executable post-installation / setup code. Should it prove to be correct that the MCU OTA file is packed with executable code that the BLE willingly executes, one could try injecting their own code. This has a potential to defeat every security measure mentioned so far, but also serious implications for the scooter safety. But again, proving this would require full knowledge of the authentication and update process.

While the authentication process (pairing with QR code, secure key exchange) doesn’t seem to have any obvious flaws, Brightway has left room for debugging and possible modification of the scooter. It is a misunderstanding that authentication with a secure chip provides absolute security. It’s main safety mechanism is to prevent tampering with the device of someone else, because we don’t have the QR code (certificate) to pair with that (secure chip). The secure chip doesn’t prevent you from hacking your own scooter. This is how it should be!

3 Lite: Custom firmware?

The Realtek BLE module uses SPI to communicate with the flash. The (unsurprising) fact is that this module doesn’t allow writing bytes to the memory-mapped flash directly. The RTL8762C SoC comes with a feature called block protect and the manual states the following regarding write protection: „The protected flash zone can’t be written and erased. If necessary, user can unlock flash first, and then write or erase, finally lock the flash to the previous level.“ Realtek provides both an API for reading and writing to flash and tools for programming. This means that flashing a custom firmware to the BLE module is just a matter of figuring out the correct programming procedure!

As for the MCU: If you’re familiar with the flash controller in STM32, the LKS32 MCU isn’t too different. It has a register for enabling the programming mode, a register for the address to program and a register for the data to be written to that address. In my tests, writing single bytes (words) using the LKS32 flash controller was unsuccessful (also, writing single bytes to the memory-mapped flash didn’t succeed). Based on hints in the manual, it’s very likely that a prior erasure of the flash region to be written to is necessary!

BLE custom firmware

Up to this point, everything I did so far was non-destructive. In order to not risk bricking my newly brought scooter and keeping the factory settings intact, I bought a much cheaper Xiaomi device that comes with the exact same BLE module for experimentation. Both devices contain the exact same ROM image and there’s no setting (so called „eFuse“) in EEPROM that might potentially disable flashing. Therefore, the process and outcome of flashing the scooter BLE module is expected to be exactly the same.

I was able to erase the existing firmware from the BLE module and flash a modified 3 Lite BLE firmware back to it. My modification, for demonstration, is simply changing the device name from „dreame.scooter.epro“ to „dreame.scooter.nono“ . This shows that a 3 Lite custom firmware could very much be possible, in theory!

Successfully flashed back modified firmware to Xiaomi BLE module with device name altered

MCU custom firmware

Custom firmware can be flashed to LKS32MC081 MCU without limitations using the SWD port. After flashing the original 3 Lite MCU firmware, I was able to erase and reprogram the chip with a modified original firmware.

What about other new Xiaomi models?

Thanks to internal FCC documents we can tell that the hardware of the Xiaomi/Brightway 3 Lite and the Xiaomi/Brightway 4 (non-Pro) model look similar. The MCU has the same amount of pins and we can make out exposed SWD pads. Overall, the board design, including caps and connectors, looks familiar. Chances are, that the 4 Ultra comes with the hardware described in this post.

The Xiaomi/Ninebot 4 Pro, like all other other new Xiaomi scooter models, uses the same BLE module as the 3 Lite, as disclosed by a Bluetooth certification. This means that the 4 Pro uses the same BLE stack and Xiaomi core libraries for authentication. As for the controller, the 4 Pro uses a STM32 based board in the tradition of previous Ninebot scooters; the STM32 MCU is well established in the scooter modding community.

Xiaomi/Brightway 3 Lite: MCU with 48 pins underneath blue cap
Xiaomi/Brightway 4: [Source] shows MCU, also with 48 pins, blue cap and SWD pads

In a nutshell, the new Xiaomi models could be pwned as follows:

For 3 Lite + 4 + 4 Ultra, the easy way would be to modify the existing MCU firmware and flash it via SWD. The hard way would be developing and flashing a custom BLE firmware for the (Realtek) BLE module that bypasses the secure chip, with a custom MCU OTA flashing procedure.

For the 4 Pro, there is no easy way at this time. A possible way is to develop and flash a custom ESC firmware for the STM32 board. This firmware could be based, for example, on the OpenSource SmartESC firmware. The hard way would involve a custom BLE firmware, just like for the other models (same BLE module).


In this research, I had an extensive look at the hardware, software and security implemented by Brightway, the new Xiaomi scooter supplier, by examining their 3 Lite scooter model. I could fully dump both the BLE and MCU flash content, get a glimpse at the OTA procedure and the command & communication protocol used by in the 3 Lite.

My conclusion is that Brightway scooters, at the example of the 3 Lite, are secure from hostile takeover by a third party, thanks to the use BLE authentication using the secure chip, but open for your own modifications!

I have shown that both chips can be (re-)programmed through the respective (enabled) SWD port: I was able to flash a modified 3 Lite BLE to an identical Xiaomi BLE module, which suggests that BLE custom firmware is possible on the actual device. I was also able to flash (and re-flash) the original 3 Lite MCU firmware to an identical LKS32 MCU, which suggestes that MCU custom firmware is possible.

At the time of writing, I could not discover any security exploits that would warrant a notification of the manufacturer. As for the security flaws, such as missing encryption and read-out protection of the firmware files, I assume that the manufacturer is well aware thereof. Please understand that I will not go into detail of the exact flashing procedures. Further, the question how regional restrictions such as speed limits can be removed are not the scope of my research.


Xiaomi scooters: a complete product guide

Xiaomi recently added three new scooter models to their portfolio: Xiaomi Electric Scooter 3 Lite, Xiaomi Electric Scooter 4 (Canada) and Xiaomi Electric Scooter 4 Pro. This blog post seeks to explore the Xiaomi scooter product line and its interweb with different manufacturers.

Ultimately, this blog article seeks to answer the question, if any of the new models can be hacked or not.

History: Xiaomi, Mi, Mijia?

Xiaomi released its first scooter, the „Xiaomi Mi Electric Scooter“, also known as „Xiaomi Mijia M365“, in December 2016. „Mi“ and „Mijia“ are two brands used by Xiaomi for smart home devices. The „Mijia“ brand is more prominent in Asian regions, whereas the „Mi“ brand is used globally.

The „Mi“ label was dropped from the latest scooters model names. But, the „Mijia“ brand still exists in Asian regions.

Who produces Xiaomi scooters?

Xiaomi is primarily a design and marketing company, meaning that it does not manufacture all of its products in-house. Instead, Xiaomi partners with a network of suppliers and contract manufacturers to produce its products.

For example, Xiaomi works with Foxconn, a major contract manufacturer, to produce some of its smartphones. It also works with other manufacturers for different product categories, such as Huami for its wearables and Viomi for its home appliances.

Unsurprisingly, Xiaomi does not actually produce scooters. The producers are named in the following list, together with detailed information on each released scooter model and their internal device naming (Xiaomi Mi Home App):

  • Ninebot (Changzhou) Tech Co., Ltd. [founded in 2012, acquired the U.K. based Segway Inc. in 2015]
    • M365 [ninebot.scooter.v1]
    • M365 Pro [ninebot.scooter.v2]
    • Mi 1S [ninebot.scooter.v3]
    • Mi Pro 2 [ninebot.scooter.v4]
    • Mi Lite (Essential) [ninebot.scooter.v5]
    • Mijia 1S (China) [ninebot.scooter.v6]
    • Mi 3 [ninebot.scooter.v7]
    • 4 Pro (old version?) [ninebot.scooter.v8]
    • Mi 3 (new version?) [ninebot.scooter.v10]
    • 4 Go [ninebot.scooter.v13]
    • 4 Pro [ninebot.scooter.15/v15]
    • 5 Pro (China) [ninebot.scooter.v16]
  • Brightway Innovation Intelligent Technology (Suzhou) Co., Ltd. [founded in 2020]
    • NAVEE Electric Scooter S65 [dreame.scooter.p2223]
    • Mijia Electric Scooter 3 Youth Edition (China) [dreame.scooter.t2185]
    • Xiaomi Electric Scooter 3 Lite [dreame.scooter.epro]
    • Xiaomi Electric Scooter 4 [dreame.scooter.t2201]
    • Xiaomi Electric Scooter 4 Ultra [dreame.scooter.p2301]
    • Xiaomi Electric Scooter 4 Lite [navee1.scooter.t2210]
    • NAVEE Electric Scooter V40 [navee1.scooter.t2208]
    • NAVEE Electric Scooter V50 [navee1.scooter.t2211]
    • NAVEE Electric Scooter S65C [navee1.scooter.t2214]

Brightway scooters?

Up until recently, all „Xiaomi“ scooters were produced by Ninebot. This changed when Brightway came to light in 2020.

Brightway first released a scooter for the Chinese market, named 米家电动滑板车3青春版 (Mijia Electric Scooter 3 Youth Edition). This scooter is now available globally under the name „Xiaomi Electric Scooter 3 Lite“. Fun fact: The original name indicates it’s target audience (youngsters), which explains why the scooter has the weakest specs of all scooters in the Xiaomi portfolio.

Furthermore, Brightway has its own scooter brand: NAVEE TECH. Even if Brightway doesn’t use the NAVEE brand for all Xiaomi models, they left traces with „Navee“ tags all over the place, for example, in the Xiaomi 3 Lite FCC documents.

Brightway vs. Dreame

In the Xiaomi Mi Home app, all Brightway scooter model names start with „dreame.scooter“. This is strange, because „Dreame“ mainly produces vacuum cleaning robots… So the question is: How is Brightway related to Dreame?

My research concludes that Brightway and Dreame are both brands owned by the Chinese company Shenzhen Liwei Electronics Co., Ltd. (also known as Liwei Century or Liwei Chuangzhi).

Liwei Electronics is a leading manufacturer of home appliances, including vacuum cleaners, air purifiers, and other cleaning products. Dreame is Liwei’s premium brand of vacuum cleaners and other cleaning products, while Brightway is… well… a scooter brand.

With regards to the Mi Home app, I assume, that Liwei Electronics wanted to bundle both their Dreame and Brightway products within the Xiaomi Mi Ecosystem and found the easiest way to achieve this by using the already existing „dreame“ namespace/account.


Ninebot scooters have had a long-standing reputation for being hacker-friendly. However, this changed last year with the introduction of new security features (cryptographic signatures) specifically aimed at preventing tampering with the device firmware. Now, with the „4 Pro“ model, Ninebot put a nail in the coffin of firmware manipulation: They added a secure chip, dubbed „MJA1“, to (possibly) store encryption keys and cryptographic functions. Secure chips usually come with a physical protection layer that, for example, causes the chip to erase itself when tampered with physically. (Side note: Xiaomi also uses the „MJA1“ in other devices, such as the „Vacuum-Mop 2“ robot vacuum cleaner and the „Smart Camera 2 PTZ“ security cam.)
It can be said that, starting with the „4 Pro“, all upcoming Ninebot scooters will be difficult to hack.

However, public information about Brightway scooters (including the „3 Lite“, „4“ and NAVEE scooters) do not seem to indicate similar measures: FCC documents from the NAVEE Electric Scooter S65 show a dashboard equipped with a Realtek MCU (AMB1) and exposed serial wire pins (CLK/DIO/G), meaning: a potential for further exploration!

https://fccid.io/2A4GZ-S655001B „Internal photo“ of NAVEE Electric Scooter S65

To be continued…


Fixing keyring errors in Linux

Simple refresh should update keys and get rid of signature errors.

gpg --refresh-keys

For arch linux, make sure to update the keyring:

sudo pacman -S archlinux-keyring


Ultimate De’Longhi Dedica EC680/685 Tuning Guide

With a price of €150 the De’Longhi Dedica EC685 is by far the cheapest portafilter espresso machine one can get. It is the successor to the EC680 model with minor differences in frother and tray.

Out of the box the EC680/685, despite the overwhelmingly positive reviews, delivers horribly tasting espresso: Sour, bitter and lifeless. If you ask why there is such a discrepancy between reviews and results, I guess it’s because many reviewers simply don’t know what to expect.

With the right modifications you can get espresso shots tasting equally as good or better than in most cafe’s. The modifications come at a price: at first your espresso will taste far worse than before! But: You’ll receive the ability to tune the extraction process and hence the taste and flavor.

Necessary modifications

It’s actually very simple: Replace the basket, get a bottomless portafilter and strip the frother.

The biggest issue comes from the original pressurized baskets. Baskets found in gastronomical espresso machines have plenty of laser cut holes. The EC680/685 has exactly one hole. Because this machine uses a vibratory pump, pressure is build up by blockage of the pathway. To deliver somewhat constant pressure the basket is designed such that it forces the water through a tiny hole, this is why it’s called a pressurized basket.

So how do you achieve constant pressure without a pressurized basket? The answer is simple: By grinding your beans extremely fine, so fine, that the ground beans act as a natural counterpart for the vibratory pump. This of course comes with a plethora of new issues, but none which a true barista would mind learning to deal with.

A bottomless portafilter

DIY bottomless portafilter

This is a MUST have if you want to learn anything remotely about your coffee extraction. By opening up the portafilter you’ll get a clear glimpse at the shape and color of the extraction stream and also potential flaws in your coffee tamp.

For my project I ordered an original DeLonghi portafilter and cut down both the portafilter holder and the included basket with a Dremel tool:

Graef filter baskets

A standard recommendation for the EC680/685 are these Graef filter baskets, comparable to VST baskets on the German market. I have tested them and I do not recommend them for this machine!

One important metric for sieves is the nominal open area of the basket, i.e. the ratio between open and closed surface. If you have more or bigger holes you have more open area than with a few tiny holes. Now there are two problems with the Graef sieves: 1) The nominal open area is too large and 2) The 14g basket is missing the conic shape necessary for building up the required pressure!

So overall, you’ll not be able to reduce the extraction flow and hit the correct extraction times and yields using these baskets. The modified original basket on the other hand, both though its conic shape and smaller holes, is able to hit almost perfect extraction parameters.

Fundamentals of espresso

No matter what machine you have, without quality roasted beans you’re not going anywhere. Even though it’s temping to buy cheap beans for learning I wouldn’t recommend doing so: Uneven roasts, bean sizes and fragments all lead to an unpredictable extraction and varying results.

Now, given you have the right beans you’ll have to make sure that you understand the coffee extraction process. We have the following parameters to play with, ordered by importance:

  1. Grind size, from coarse to very fine
  2. Brew ratio
  3. Water temperature

Grind size

We’ve already learned that the grind size controls the pressure in this machine. For espresso, the finer you grind, the more area is created for the water to extract. Generally, you’ll want to go as fine as possible. We’ll get into the physics another time, for now this rule of thumb are enough to find the perfect grind setting:

  1. Grind so fine that you choke your machine (nothing comes out, machine aborts process)
  2. Set the grinder one step coarser at a time until you see a very slow but constant flow

Many people like me bought the Graef CM800 grinder together with their DeLonghi machine. This grinder has one flaw: It’s not specifically designed for espresso-grade grinds. It can, however, be „fine-tuned“, by removing the outer shell, removing the screw on the inner grinder and rotating the inner piece three steps in FINE direction (inner piece clock-wise). The effect of this is that the outer scale (the one you normally look at) gets shifted to the left: What was before the grind setting „5“ now becomes „15“. This gives you more room to work with finer grind settings. Another thing is that pressing down on the hopper while grinding helps getting a more even grind.

CM800: Move screw three steps in FINE direction to get finer grinds

If your grind and tamp are not even enough you’ll get what’s called channeling: Water under pressure seeks the path with lowest resistance, creating channels. The presence of channels the bottomless portafilter is noticeable through coffee spurts in random directions. Because the contact time of this channeled water with the coffee is almost non-existent, this water will taste sour and body-less if it makes way into the cup.

Chances are that this is what you’ve been drinking before, because with the normal portafilter defects in the tamp are invisible. Once you get a constant, single stream your tamp is free of channeling and your coffee is guaranteed to taste well.

Brew ratio

The next thing you want to set up is the brew ratio, i.e. the weight of the ground coffee beans vs. the weight of extracted coffee (including water). Don’t rely on the specs of the basket, measure the weight of the portafilter with and without the ground coffee and you have your input weight. Stay constant with your input weight, learn to always dose in the same amount without gauge.

Then, measure the weight of the cup without coffee and with coffee to get the output weight (the yield). Now divide the output weight by the input weight and you have your brew ratio. If your output weight is around two times as much as the input weight (brew ratio 1:2), voila! If not: press and hold the start button on the machine for one or two cups to program the extraction time. If you need more coffee in the cup, you need more time, if it’s too much coffee in the cup, you need less time. Adjust the time by releasing the cup button sooner (less time) or later (more time). You’re done once you hit your brew ratio for consecutive trials.

See how extraction time is not really a parameter you set. You only set up the grind size and brew ratio, extraction time is just a result. If the time, given the correct grind setting and brew ratio, is around 20 seconds, good, if not, ignore.

Water temperature

Many guides recommend 92 degrees as the extraction temperature for espresso. With the EC680/685 we have no direct control over the temperature and the temperature itself is very instable: Depending on whether it’s the first, second or third coffee in a row the temperature changes, but also across the extraction the temperature drops quickly.

The EC680/685 has the option to change the temperature from low, middle to high. After testing all settings (and doing tricks like „temperature surfing“) I recommend leaving the temperature setting untouched! While not perfect, the machine is able to produce temperatures high enough to deliver good extraction. Only one thing is extremely important: Preheating the brewing group! This is easily done by removing the portafilter and then making one cup of coffee without coffee.

There have been some studies on the importance of temperature in coffee extraction. Up to a certain point, gradually more coffee practicals get dissolved as the temperature increases. But we’re talking about minor varieties, bean/roast quality and grind size are far, far more important!

Source: http://blog.beanbuddies.eu/wordpress/wp-content/uploads/2015/06/Coffee-in-Australia.png

Exploring Xiaomi’s new firmware security measures

Xiaomi Mi 1S dashboard with attached SWD Debugger (four wires, left) and UART sniffer (two wires, right)

Updated 2022-04-21: Added main picture, added in-depth details with references, added appendix, updated inaccurate paragraph on ESC firmware

Chinese tech giant Xiaomi started rolling out new security measures to counter illegal modification of their device’s firmware. I own a Xiaomi Mi 1S Electric Scooter and can tell that this product is affected. Out of personal curiosity I wanted to have a look…

OTA firmware updates

To inspect device firmware one doesn’t necessarily need access to the hardware (as demonstrated in the main picture) – intercepting the chip’s flashing process is much more convenient!

Today, the firmware of most electronic devices is updated „over-the-air“ (OTA). Meaning, the firmware file is no longer downloaded and installed by the user manually, but rather through an automated process. With OTA updates the user usually never gets to see the actual firmware.

Because firmware is subject to copyright laws the user no longer runs into the legal risk of accidentally sharing the file. On the downside, the user never gets to see the content of the installed files. After all, the firmware could contain code meant to spy on you or worse – you would never find out. Or could you?

Capturing firmware files

Every update procedure involves downloading a file which is then installed onto the device. Just because these steps are invisible to the user it doesn’t mean that they don’t happen. The easiest way to capture the file is by sniffing network traffic. Another way is to access the filesystem or dump the RAM of the application used to perform the update.

The Xiaomi electric scooters actually come with three firmware files, one for each component: battery management system (BMS), electronic speed controller (ESC) and the dashboard BLE chip:

Retrieved firmware files

Simply observing the new firmware filenames one can see that the BLE firmware file is now equipped with a _signed appendix and ESC firmware starts with an EC_. With a brief look into the file contents one finds the same two certificates attached to the file ends:

New data found appended to firmware
– Green: Identifier (with 4-byte checksum)
– Yellow: Root certificate
– Red: App certificate
– Blue: Signature


Running the attached certificates through openssl reveals the first one to be a root certificate (Mijia Root), the second one to be an application level certificate (Mijia Open) and the underlying cryptographic algorithm: ecdsa-with-SHA256.

Application level certificate including EC public key and digital signature

The Elliptic Curve Digital Signature Algorithm (ECDSA) uses public-key cryptography to validate the authenticity of the message/data. In public-key cryptography a pair of keys is generated: a private key and a public key. In Elliptic Curve cryptography (ECC) this pair is generated from (geometric/mathematical) elliptic curves. This is far more secure than lets say prime numbers in RSA.

SHA256 is a hash algorithm designed by the NSA. Meaning, no one besides the NSA can produce the data from the hash :). SHA256 produces a hash of 256 bit length for any input message/data.

Data signing and validation with ECDSA

In order to sign (or encrypt) data in public-key infrastructure a key pair is needed. Naturally, for ECDSA an EC key pair with private and public key is generated before all else.

To calculate the EC signature following three steps are then ran:

  1. Calculate SHA256 of firmware data
  2. Choose random number (the „nonce“, must be secure!!) to generate a point on the selected ECC curve (here: prime256v1)
  3. Calculate the signature using nonce, selected point, private key and hash

(To keep this post simple, formulas have been omitted and steps simplified.)

For signature validation, the public key is used to retrieve the original file hash back from digital signature. This file hash is than compared to the hash of the received data to tell whether the same data, which was signed, is received, or if it has been tampered with.

Source: https://www.segger.com/products/security-iot/emsecure/variations/emsecure-ecdsa/

Back to our case: To validate the signed firmware files you can use my script from the appendix. It first separates the (application level) certificate and data signature (signature bytes follow after the last certificate) from the firmware data, and then runs openssl to verify the signature against the firmware data given the public key from the certificate. In short: Running the command bash verify.sh <firmware_file> will give you the message „Verified OK“ if the file was correctly signed.

Using this method, the verification for both captured firmware files succeeds. We can conclude that the firmware itself must be doing a similar verification.

BLE_signed: A deep dive

We already know that the new BLE firmware is signed, but it’s also not encrypted. This means it can be disassembled and analyzed!

It’s easy to find out that the section containing the certificates (at the end of the file) is referenced from within the flash procedure [1]. And if a certain condition is not fulfilled the flash procedure never finalizes [2]. Based on the previous examinations of signature verification there’s reason to believe that the function involved in this condition compares the file hash of the received data against the original file hash calculated from the signature and public key contained in the certificate [3].

Furthermore, hints to a new flash procedure can be found in the BLE firmware [5]: It contains a whole new set of functions that (together with previously mentioned function for signature verification) are all situated in a block in the beginning of the firmware [4], indicating a newly added library. This new procedure is structurally similar to the existing flash procedure and it intercepts all flash commands designated to the ESC [6]. Scary stuff!

References (ESC_BLE_V1.5.7)

  1. 0x7794
  2. 0x3670
  3. 0xd9d0 & 0xda42
  4. 0x404 to 0x6f4
  5. 0xcda4
  6. 0x3d4e

EC_ESC: More insights

The ESC firmware can be decrypted in the same way as previous firmware files (after truncating the certificates), but the BLE firmware now acts as a gatekeeper: By monitoring the UART communication between dashboard (BLE) and controller (ESC) we observe that when performing the ESC update… nothing happens! Only after 50% progress the transmission of data from BLE to ESC starts (an excerpt of the new UART log can be found in the appendix). Previously, flash commands designated to the ESC where simply passed through the BLE.

Observing this behavior we can bridge a logical gap: The new flash procedure found in the BLE firmware (see last paragraph in previous section) is responsible for the memory management of all intercepted packets! Only after a full transfer and verification the procedure is finalized. Since both BLE and ESC firmware come with the same public key and a unique signature, the verification procedure must follow the same principle.

We summarize the new flash procedure for ESC firmware as follows:

  1. ESC flash commands get intercepted by BLE
  2. BLE writes firmware data into own flash!
  3. Using the same procedure as before the signature of the data is verified
  4. If verification succeeds the data is passed on to the ESC


The new security measures are on-par with today’s security standards. BLE firmware is signed using ECC and signatures only pass validation if they’re signed using the correct private key.

Xiaomi seems to have taken security concerns from users and authorities seriously. Instead of simply swapping out keys, new security features with signed firmware files have been implemented.

These measures can be seen as secure given the following context:

  • A secure random number generator to generate the nonce for the signature. If a static nonce was used it could allow an attacker to recover the EC private key, like in the PlayStation 3 hack.
  • The firmware is secure against buffer overflows or other memory exploitation techniques. If an attacker finds a way to modify the memory or memory address of the stored public key a different key pair could be used to sign the data.


split.py – Python script to split firmware file into data, certificate and signature (root certificate omitted):

import sys

if __name__ == "__main__":
    filename = sys.argv[1]
    with open(filename, 'rb') as f:
        data = f.read()

        pattern = b"\x2d\x2d\x2d\x2d\x2d"
        i = data.find(pattern, 0xdfff)
        if i == -1:
            i = data.find(pattern)
        fw, appendix = data[:i], data[i:]

        i_s = appendix.rfind(pattern)
        i_ce = appendix.rfind(pattern, 0, i_s)
        i_cs = appendix.rfind(pattern, 0, i_ce)
        sign = appendix[len(pattern)+1+i_s:]
        cert = appendix[len(pattern)+1+i_cs:i_ce]

        with open(filename + ".data", 'wb') as outf:
        with open(filename + ".cert", 'wb') as outf:
            outf.write("-----BEGIN CERTIFICATE-----\n".encode())
            outf.write("-----END CERTIFICATE-----\n".encode())
        with open(filename + ".sign", 'wb') as outf:

verify.sh – Bash script to verify the firmware against the appended signature and public key:

# 1. split BLE_signed into three parts: data + certs + signature
python split.py $1

# 2. extract pub_key from cert
openssl x509 -in "$1.cert" -noout -pubkey -out "$1.pub"

# 3. verify data using pub_key and signature
openssl dgst -verify "$1.pub" -keyform PEM -sha256 -signature "$1.sign" -binary "$1.data" 

UART log showing delayed start of ESC flash process:

... (after ~50% progress) ...

55aa82200800774019f6456798d91633253245117bb42fda8615773a193048ac6ca5e7887a    +++9c234555c92c4a4d859272586ced17e9870a2595f14d09fc57ac2a3f458ec2747a67a43    +++d9cb848dee0e60a61e37f77007626122be78bb9bb75f1f47eab43db66f791e5e4c83c5c    +++944f892ab056f19d0fe2a4c2a7949a9cb53aba77e15fa3cdd454f8bf

55aa82200801b54e0814f03f3514412eb5d248c0df64b01510b93f9bebdada5ffb5bd2e137    +++b0503272551b249e5e5cb65df0d6258ef2588c50e45658f5afc81993f69f843eeb124d0    +++f5ef52ef9391fd54ca3f0f766812e4a768539741a3ed3a667411f6397e84f667095cf38    +++1cfdc4e946fba41ae24cb996340d0b6faf9c43cc62aa8e3a4bcc39c0

Bootloop after OTA update

If your Android fails to boot after an update, don’t panic! Hold the power and volume down / volume up key (depending on phone) to boot into fastboot mode. From here, you can flash an update that fixes the issue. If no such update is available, you likely have to wait for it.

Now, on LineageOS recovery you can click on „Apply update“ and then select ADB. This allows you to use adb to „sideload“ the update file. Just download the latest image and type adb sideload <filename>.

Don’t flash the update again! You will lose your other flash bank, too. This error doesn’t come from the system update but rather files that got corrupted.

From fastboot mode simply switch back to the alternate flash bank by typing fastboot --set-active="a" if you have slot B active or fastboot --set-active="b" if you have slot A active. Check the active slot („current_slot“) with fastboot getvar all.

Chances are that your phone might boot again :0


Uploading PIP packages

python3 setup.py sdist

python3 -m twine upload –repository pypi dist/<package-name><version>*


Create Cert for HTTPS

openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes