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

Sniffing HTTPS traffic

Still possible in 2022, thanks to a little tool going by the name „burpsuit“. It’s easy: Set up a proxy server and configure your end device to use that proxy.

Starting with Android Nougat the cert has to be installed at system-level. For this, you have to enable root debugging in the developer settings and transfer the file manually using adb. Full explanation here.

openssl x509 -inform der -in burp.der -out burp.pem

mv burp.pem openssl x509 -inform pem -subject_hash_old -in burp.pem | head -1.0

With adb root move cert to /system/etc/security/cacerts/ and chmod 644.


Patching APK’s

Ever run into a situation where you can no longer use an older version of an app because it forces you to update? Or the app tries to take money from for unlocking an already built-in but inaccessible „premium feature“?

Patching APK’s consists of these steps:

  1. Unpacking the APK: apktool d -r some.apk -o output_dir
  2. Patching the smali byte-code: Remove or change using your favorite editor
  3. Packing the code back to an APK: apktool b output_dir -o modded.apk
  4. Signing the new APK:
    1. Create key (only needed once): keytool -genkey -v -keystore key.keystore -alias robocoffee -keyalg RSA -keysize 2048 -validity 10000
    2. Sign with key: jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore key.keystore modded.apk robocoffee ~/Android/Sdk/build-tools/<version>/apksigner sign --ks key.keystore modded.apk
  5. Install new APK: adb install modded.apk

Decompiling APK’s

You can decompile even minified / obfuscated APK’s using one of these tools (I prefer the latter). Why would you want to do that? For example, when you like a feature in an App and reverse-engineer how it’s done.

Decompile into Java source code using Procryon:

  1. apktool d -s some.apk -o output_dir
  2. dex2jar output_dir/classes.dex
  3. procyon-decompiler classes-dex2jar.jar -o decompiled_dir

Or alternatively, one tool to rule them all: jadx --deobf some.apk

In my opinion JADX with the built-in deobfuscator gives the most readable results. Note however that some blocks might now be decompiled in either case, leaving you no other option but to read nasty byte-code.

Hardware Stupid

How to toast a micro controller

  1. Short peripheral chip by applying the wrong voltage to either one of its inputs
  2. Connect the shorted chip to your micro controllers power outputs, effectively shorting it too

Lesson: Don’t mess with micro controllers in the middle of the night, especially not when you’re tired and lazy.