Mijia LYWSD03MMC, BLE and Node.js

That hard-to-remember product name is a Bluetooth LE enabled small thermometer and hygrometer from Xiaomi. The special thing about it is that Aaron Christophel created a GitHub repo about how to re-flash it with firmware which makes it way more useful: it now advertises the temperature, humidity and battery level which makes it very easy to pick up.

So I got 4 of those and re-flashed them:

  1. Access https://atc1441.github.io/TelinkFlasher.html with a WebBluetooth capable browser
  2. Click on Connect and connect
  3. Click on Do Activation
  4. Click on Choose firmware and use the ATC_Thermometer.bin from above repo
  5. Click on Start Flashing
  6. Wait about 60s
  7. Wait until it reboot. The display will show the 3 last bytes of the MAC address for easier reference later on.

Connect to the newly flashed device. You can change some settings with the buttons at the end of the web page (e.g. disable the “Show battery in LCD” if you measure and record it anyway).

Scripts for finding them and reading data out of them is here.

Reading them out is very simple with above scripts:

❯ node read-thermometer.js -s ATC_C1CADA,ATC_D01337 -e 10 -t
environment,host=m75q,sensor=ATC_C1CADA temp=22.5,humidity=37,battery=100
environment,host=m75q,sensor=ATC_D01337 temp=20.7,humidity=44,battery=100

which you can feed via telegraf. Here the telegraf.conf snippet:

  commands = ["node ~/git/LYWSD03MMC/read-thermometer/read-thermometer.js -s ATC_C1CADA,ATC_D01337 -t"]
  timeout = "12s"
  data_format = "influx"

And the result are very nice graphs in Grafana (3 sensors):

Temperatures recorded via BLE from 3 LYWSD03MMC sensors

firejail Command Completions for zsh

Command completions are awesome when they work. A great example is the docker command completion. It helps a lot: if you don’t know the possible commands or options, it shows them to you. If you do know them, you only have to type few letters and hit <TAB>. The best is when shows options which it dynamically generates, e.g. when you want to inspect an image, “docker image inspect <TAB><TAB>” will show you the images you can inspect. A real time saver.

Using firejail made me want to have command completion for it too as it has a ton of command line options. And some of them can have dynamic updates. There’s a completion script for bash part of the firejail repo, but no zsh.

So I created one. Was an interesting experience. And definitely helps me using firejail.

Most helpful was this blog post which is one of the very few simple zsh completion examples I found.

Comparing Sandboxing Tools

The motivation came from here:


When programming in Node.js, a huge problem is that “npm install” downloads libraries you did not specify. It downloaded all dependencies listed in package.json, but it also downloaded their dependencies and the dependencies of their dependencies etc., which is code you did not explicitly ask for. While you can point your direct dependencies to trustworthy sources, you have no control about anything further down the line. In short: this is a (known) security hazard. A recent example is here. Auditing code in npm helps, but the whole concept is a fundamental problem.

Dart and Deno are reducing the problem significantly since you have to name all dependencies, but it does not necessarily help you if that dependency itself is compromised.

The runtime of Deno as well as wasmtime use a sandbox-approach to mitigate that: you have to enable access explicitly to anything: A Deno program has very few permissions otherwise. From a security point of view, this is much better.

Node.js nor Python have no sandbox model and when loading libraries from the Internet, which both do a lot, do you always know what you get? So I’m looking for choices how to retrofit programs with potentially questionable code.

My requirements:

  • Possible to use ad-hoc: I want to run a program with somehow limited access (e.g.: no root and no ability to become root, network access only when I allowed it, no access to files it does not need access to)
  • Protect my files from programs which run as me and thus with my normal privileges (e.g. very few program would need access to my ssh keys)

Test case:

  • Run a Node.js program which wants to read ~/.test_me and access http://www.google.com. It should not be able to do either unless it’s enabled.

Here the simple Node.js program:

const fs=require('fs');
const fetch=require('node-fetch');

async function accessStuff() {
  try {
    let f=await fs.promises.readFile(`${process.env.HOME}/.test_me`);
    console.log(`File: ${f}`);
  } catch(e) {
    console.log(`Error while accessing .test_me: ${e}`);
  fetch('http://www.google.com', {
                method: 'get',
    .then(res => res.text())
    .then(body => console.log(body.split('\n').slice(0,1)))
    .catch(e => {
      console.error(`Error: ${e}`);

(async function () {
try {
  await accessStuff();
} catch(e) {
  console.error(`Error: ${e}`);

and a sample run without limitations:

❯ node index.js 
File: test 1

[...many more lines from .test.me...]
  `<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"
[...some HTML code from www.google.com...]

When it comes to security and sandboxing, those choices came up after a quick check with Google:

System-wide Mandatory Access Control (MAC)

SELinux needs special policies/contexts set up for the whole system. While this is great, it’s something root does. I see no simple way to do ad-hoc configurations to run a single command with the “correct” permissions. Plus the policy files are not easy to read nor write.

AppArmor is similar. A bit easier to read policy files, but they are all root owned, so not suitable for ad-hoc commands.

Both have a point to secure the complete system with the user explicitly not allowed to change the policies. Their purpose it not to protect the user from hurting themselves.

Sandbox Tools

Docker or containers in general provide a good way of isolation from the rest of the system and via bind mounts you can allow access to files or directories easily, but you have to create a container image first, upload it to a container registry and download and run it (Update: turns out that this is not required and a locally created image can be executed without problems). While it has its use, creating containers is a significant overhead if it’s needed for every program you are suspicious about.

minijail from Google looks good:

Minijail […] provides an executable that can be used to launch and sandbox other programs, […]


Installing on Debian was straightforward (needs kernel-headers and libcap-dev). Running a command with a specific user-definable policy is possible:

 # minijail0 -S /usr/share/minijail0/$(uname -m)/cat.policy -- \\
             /bin/cat /proc/self/seccomp_filter
but the examples/ directory was a small shock to me: a single example, and not a well explained one.

❯ cat examples/cat.policy 
# In this directory, test with:
# make LIBDIR=.
# ./minijail0 -n -S examples/cat.policy -- /bin/cat /proc/self/status
# This policy only works on x86_64.

read: 1
write: 1
restart_syscall: 1
rt_sigreturn: 1
exit_group: 1

open: 1
openat: 1
close: 1
fstat: 1
# Enforce W^X.
mmap: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE
fadvise64: 1

While there is a tool to record the uses system calls (via strace) to create a policy (similar to what SELinux’s audit2allow tool), that means running a potentially harmful program once without restrictions. Plus the policy file is not exactly easy to understand. And the documentation does not help.

This is a dead end for my purpose.

bubblewrap is used as security layer for Ubuntu’s FlatPack installations. Using it is very command-line-option intensive, but a wrapper script will handle this. A test run:

❯ cat bwrap.test 

bwrap \
 --dev /dev \
 --ro-bind /lib /lib \
 --ro-bind /usr/bin /usr/bin \
 --ro-bind /bin /bin \
 --ro-bind /etc/resolv.conf /etc/resolv.conf \
 --ro-bind $HOME/js $HOME/js \
 --ro-bind $HOME/.test_me $HOME/.test_me \
 --tmpfs /tmp \
 --unshare-all \
 --share-net \
~/js/node/bin/node index.js

❯ ./bwrap.test 
~/.test_me contains: test 1
  `<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"
[...some more HTML code...]

Removing the “–share-net” and removing the “–ro-bind” for .test_me stops both”

❯ ./bwrap.test 
Error while accessing .test_me: Error: ENOENT: no such file or directory, open '/home/harald/.test_me'
Error: FetchError: request to http://www.google.com/ failed, reason: getaddrinfo ENOTFOUND www.google.com

Note that you also need /etc/resolv.conf too to allow resolving DNS names. Also the order of “–unshare-all” and “–share-net” is important as the last one wins.

firejail is conceptually similar to bubblewrap, but beside having a large list of command line options, it also has configuration files in /etc/firejail/ and it also allows user-owned configurations (default in ~/.config/firejail):

❯ cat ~/.config/firejail/nodejs.profile
whitelist /home/harald/js
#whitelist /home/harald/.test_me
net none
include /usr/local/etc/firejail/whitelist-common.inc
include /usr/local/etc/firejail/default.profile

❯ firejail --profile=~/.config/firejail/nodejs.profile node index.js
Reading profile /home/harald/.config/firejail/nodejs.profile
Reading profile /usr/local/etc/firejail/whitelist-common.inc
Reading profile /usr/local/etc/firejail/default.profile
Reading profile /usr/local/etc/firejail/disable-common.inc
Reading profile /usr/local/etc/firejail/disable-passwdmgr.inc
Reading profile /usr/local/etc/firejail/disable-programs.inc
Parent pid 231521, child pid 231522
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Child process initialized in 94.84 ms
Error while accessing .test_me: Error: ENOENT: no such file or directory, open '/home/harald/.test_me'
Error: FetchError: request to http://www.google.com/ failed, reason: getaddrinfo ENOTFOUND www.google.com

Parent is shutting down, bye...
❯ firejail --quiet --net=none node index.js
Error while accessing .test_me: Error: EACCES: permission denied, open '/home/harald/.test_me'
Error: FetchError: request to http://www.google.com/ failed, reason: getaddrinfo ENOTFOUND www.google.com

The last sample shows that you don’t need to create a separate profile but similar to bwrap you can use command line options for most settings.

Uncommenting the “whitelist /home/harald/.test_me” line allows access to that file. Commenting out the “net none” allows network access. Per default network access is granted, but you can change this in /etc/firejail/default.profile. Once disabled in a profile, it cannot be re-enabled though. (Update: A “–ignore=net” option will ignore the “net none” in a profile).

After above tests I found out you can skip the “–profile=~/.config/firejail/PROFILENAME” if PROFILENAME is the binary name plus “.profile” as firejail will pick this up automatically. Very neat!

❯ firejail node index.js 
Reading profile /home/harald/.config/firejail/node.profile
Reading profile /etc/firejail/whitelist-common.inc

And you can make it less verbose too and with sensible defaults you don’t even need to create any profiles. E.g. shell history files are inaccessible by default:

❯ firejail --quiet bash
$ cd
$ cat .bash_history 
cat: .bash_history: Permission denied
$ ls -la .bash_history
-r-------- 1 nobody nogroup 0 Dec 30 23:39 .bash_history

My Conclusion

SELinux and AppArmor are not something users can manage by themselves. Different scope than what I am looking for.

Using containers, especially when running as non-root works as long as you want to use containers anyway. Otherwise it’s a huge overhead: create container image, store it in a registry, and then run it. Any code changes would need a new container image to be created. Good for certain workload, especially those which will run as containers anyway later on. While I use containers extensively, a lot of programs I run are not a container.

bubblewrap works. It needs an extensive list of options to be useful. That’s not hard to put into a script. Since you have to add a lot of options and there’s no default options you can specify, it’s very explicit about permissions which makes it easier to debug since everything is configured when running your suspicious program. As the order of options is important, I can see this getting complicated quickly for non-trivial programs. Here is an example. Luckily most programs are trivial: few accesses are needed plus some capabilities like network access.

firejail got the spot between security and ease-of-use right in my opinion: sensible defaults (e.g. disabling at and crontab commands) with profiles for many programs. You can also have user-configurable profiles and they are not hard to create. The amount of extra work when using firejail is low: just adding “firejail” before the command helps a lot already out-of-the-box by hiding sensitive files and disabling miss-usable commands. Creating a specific profile makes this very configurable. And if you name the profiles like the binary you plan to use, it’s both simple to use while still being configurable.

Note that no solution is 100% secure. There’s always a trade-off between convenience and security. Unless you enforce it, if it’s inconvenient, it won’t be done. I’m guilty myself: Although I know how important backups are, I did them only occasionally (about twice a year) in the past. A year ago I finally completely automated it and only since then I have regular backups.

PS: While testing I experienced firejail to not be able run programs which have capabilities set if you use “caps.drop all” which is included in the default profile. See bug report. Can’t say yet if it’s a bug or badly worded option or lack of documentation or just unexpected behavior.

Humanoid Hunt! In Dart!

After doing a quick&dirty Node.js implementation of the Humanoid Hunt puzzle, I tried the same in Dart. It’s surprisingly similar, but this time I tried to create tests and I wanted to see what will be the result when I try the “real” puzzle.

And ‘lo and behold: after creating all the logic and test to confirm them working as expected, the first try with the actual puzzle data worked! Makes a good point about unit tests being fully capable to verify the logic.

That said, it took me easily twice as much time to write the tests and the code (as expected). But for any further changes, I can be assured to not have broken something.

Humanoid Hunt!

Sometimes advertising is fun. I turned off my ad-blocker for certain web pages, and while I usually get boring advertising, once in a while you get a good and interesting looking one.

In this case: https://hunt.reaktor.com/ : it’s a programming quest similar to Google Foobar Challenge, but much shorter and simpler, yet with a very similar sense of story telling and fun.

Here the 3 challenges I had and solved via Node.js (just because I can). No solutions here in this post. Maybe some spoilers.

First one. Simple decoding a number written in binary ASCII and simple processing the decoded array. The lines are 40 bytes each (=320 zeros or ones). You could do this manually.

Second one. Counting how many times characters were used. The signal is 30k in size.

Third one took me longest (as it should). Some hints: The two-dimensional space is 128×128 large. If you print it out, you’ll see the start near the top left corner and the finish area is on the top right (multiple finish points end there).

Looks like a maze, though, so first attempt of a simple dead-end-elimination did not work well. What works is flood-fill. https://www.youtube.com/watch?v=Zwh-QNlsurI has a nice explanation for this.

Out of the 11 finishes, 4 worked. The distances were 1071, 1072, 1073 and 1074 steps. If you look at the displayed maze, you’ll immediately spot the 7 false finishes (and not only as I marked them in red). So make sure you flood-fill starting at the finish.

As for the run time for the last test: it’s only 0.8s on a Ryzen 5 Pro 3400GE. The code itself is 280 lines long with 110 lines being the input signal data.


Complexity is low enough to solve them yourself, even if you did not attend computer science classes. This is a great method to weed out those who claim to be able to program but in reality cannot. And it’s fun so that some people (like me) do this for…fun! I was also curious about the story after the first very simple challenge.

I was a bit disappointed about it ending after only 3 puzzles. Google has 5 challenges (or more, as I could not solve the 5th one), so I expected harder and harder puzzles, but for the purpose of screening potential employees, this is sufficient. Google certainly can set the bar higher as their skill requirements are higher too.

I liked that the implementation language was free to choose. Google’s Foobar is limited to Java or Python only. Java is not my thing and Python I don’t enjoy that much.

All in all, good fun for an idle day! Recommended.

ESP8266 and LEDs

After the short excurse with Blynk in the previous post I wanted to do the same without a company between. After all, controlling an LED is rather simple.

So back to basics: MQTT it is. Got a Mosquitto instance on the Internet with the following docker-compose.yml definition:

version: '2'
    image: toke/mosquitto
      - "1883:1883"
      - "./mqtt/config:/mqtt/config"
      - "./mqtt/log:/mqtt/log"
      - "./mqtt/data:/mqtt/data"
    restart: always

Very basic configuration. No TLS, but I defined a user. Not secure, but good enough for now.

The Espruino program running on the ESP8266 is simple (slightly updated as I found out that properly reconnecting/re-subscribing is critical):


var debug=false;

var mqtt = require("MQTT").connect({
  host: "mqtt.my.domain.org",
  username: "MY_USERNAME",
  password: "MY_PASSWORD",

var myPixel=[0, 0, 0];
const ledPin=D2;

function updateLED(v) {
  np.write(ledPin, v);

// s: RxxxGxxxBxxx with xxx=0..255
// All valid: R0G0B0, G255R0B0, G10, G80B80R

function getRGB(s) {
    var rgb=[-1, -1, -1];
    var currentIndex=-1;

    for (let i=0; i<s.length; ++i) {
        switch(s[i]) {
            case 'r':
            case 'R': currentIndex=0; rgb[currentIndex]=0; break;
            case 'g':
            case 'G': currentIndex=1; rgb[currentIndex]=0; break;
            case 'b':
            case 'B': currentIndex=2; rgb[currentIndex]=0; break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                if (currentIndex!=-1) {

    var res={};
    if (rgb[0]!=-1) { res.r=Math.min(rgb[0], 255); }
    if (rgb[1]!=-1) { res.g=Math.min(rgb[1], 255); }
    if (rgb[2]!=-1) { res.b=Math.min(rgb[2], 255); }
    return res;

function setLED(s) {
  let values=getRGB(s);
  if (values.hasOwnProperty('r')) myPixel[1]=values.r;
  if (values.hasOwnProperty('g')) myPixel[0]=values.g;
  if (values.hasOwnProperty('b')) myPixel[2]=values.b;

function log(s) {
  if (debug) {

// Program starts here


mqtt.on("connected", () => {
  log("Subscribing to LED");

mqtt.on('disconnected', () => {
  //  updateLED([0,20,0]);
  //  setTimeout(()=>{updateLED([0,0,0]);},50);
  //}, 500);
  }, 1000);

mqtt.on('error', (err) => {
  log("Got error: "+error);

mqtt.on('publish', function (pub) {
  log("topic: "+pub.topic);
  log("message: "+pub.message);

mqtt.on('subscribed', () => {
  log("Subscription successful");

mqtt.on('subscribed_fail', () => {
  log("Subscription failed");

mqtt.on('unsubscribed', () => {
  log("unsubscribed received");

mqtt.on('ping_reply', () => {
  log("ping_reply received");

mqtt.on('puback', () => {
  log("puback received");

mqtt.on('pubcomp', () => {
  log("pubcomp received");

Test via plumber:

❯ plumber write mqtt --topic="LED" --client-id="Plumber-1" --address="tcp://MY_USERNAME:MY_PASSWORD@mqtt.my.domain.org:1883" --input-data "R200G0B200"

Testing also works with MQTTlens.

And there we go: An Internet controllable LED! Total costs: Wemos D1 mini: $3, WS2812B LED module: $1.

Blynk and M5Stack

Using my M5Stack with Blynk makes sense: it has plenty sensors and a display and LEDs.

❯ export AMPY_PORT=/dev/ttyUSB0
❯ export AMPY_BAUD=115200
❯ ampy ls /flash
❯ ampy mkdir /flash/lib
❯ ampy put BlynkLib.py /flash/lib/BlynkLib.py
❯ ampy get /flash/boot.py > boot.py
# Edit boot.py to include /flash/lib in the Python search path
# Like this:
#import machine, os, sys
#    sd = machine.SDCard(slot=3, miso=19, mosi=23, sck=18, cs=4)
#    sd.info()
#    os.mount(sd, '/sd')
#    print("SD card mounted at \"/sd\"")
#    sys.path.append('/flash/lib')
#    pass
❯ ampy put boot.py /flash/boot.py

Sample program:

from m5stack import *
from m5ui import *
from uiflow import *

import BlynkLib

blynk = BlynkLib.Blynk(BLYNK_AUTH)


# Register virtual pin handler
def v3_write_handler(value):
  s='Current slider value:'+str(v)+'.'
  lcd.text(0, 20, s)

while True:

Using the Bylnk App update Virtual Pin 3 and the value should be displayed on the M5Stack’s LCD.

Blynk IoT Platform

Yesterday I read an article about blink(1) which is essentially a USB connected and controlled RGB LED light. I got some ESP8266 and some WS2812 LEDs to do the same, and it even can connect via WiFi and the Internet. So that’ll what do on Sunday.

Somehow I arrived at Blynk which is a totally different thing, but they can be combined to make a LED light which is Internet connected and can be controlled via an API or the Blynk app. Neat!

Here’s the trivial Espruino code running on the ESP8266:

var Blynk = require('http://tiny.cc/blynk-js');

var SSID = 'MY_SSID';

const np=require("neopixel");

var pixel=[0, 0, 0];

function updatePixel() {
  np.write(2, pixel);

function setLED(intensity) {

function setRedBlink(count) {
  var time=0;
  for (var i=0 ; i<count; ++i) {
    setTimeout(()=>{pixel[1]=255; updatePixel();}, time);
    time += 200;
    setTimeout(()=>{pixel[1]=0; updatePixel();}, time);
    time += 200;

function blynkInit() {
  var blynk = new Blynk.Blynk(AUTH);

  var v1 = new blynk.VirtualPin(1);
  var v2 = new blynk.VirtualPin(2);

  v1.on('write', function(param) {
  v2.on('write', function(param) {

  blynk.on('connect', function() { console.log("Blynk ready."); });
  blynk.on('disconnect', function() { console.log("DISCONNECT"); });

function onInit() {


and on the Blynk app side there’s 2 sliders: one for the intensity of the first (green) LED (virtual Pin 1), and one for how many times to blink the 2nd (red) LED (virtual Pin 2).

LED controlled by Blynk App


A quick and non-micro benchmark to figure out how the ARM and AMD CPUs I have and what AWS has relate to each other in terms of single-thread performance.

Comparison is between

  • AWS t4g-micro (1 CPU)
  • IBM M75q (Ryzen 5 3400GE @ 3.3 GHz)
  • NanoPi R2S (RK3328, 4xCortex A53 @ 1.3GHz, 64 bit)
  • CubieTruck (AllWinner A20, 2xCortex A7 @ 1 GHz, 32 bit)

Below is the node-sqlite3 results from https://github.com/JoshuaWise/better-sqlite3 with Node.js v14.15 and sqlite 3.31 (average of 2 runs):

node-sqlite3 (mostly)t4g-microM75qRK3328A20
read rows individually19932152492160884
read 100 rows19661405320144
iterating over 100 rows2071552410
inserting rows individually17214130851556530
inserting 100 rows2501913013
tar tfv node-v14.15.1-linux-arm64.tar.xz1.5s1.4s5.2s10.5s
Very simple benchmark table

The last one has its stdout redirected to /dev/null.

NanoPi R2S: My First ARMv8

Got my first Linux ARMv8 (64 bit, as opposed to the ARMv7 instruction set which is 32 bit) machine (manufacturer link):

Here a graph CPU load over CPU temperature:

As you can see, the heat sink does it job quite well (room temperature was about 19°C). The case gets warm, but not hot (below 50°C I’d estimate).

The whole thing is powered via micro-USB (+5V) and needs about 400mA when idle and about 100mA extra per 100% busy core running at 1.3GHz.

Create your website at WordPress.com
Get started