Battery on my Surface Pro 3

Devices which use batteries should not be stored at full charge. Unfortunately that’s what effectively happens when you constantly connect it to power. Like my Surface Pro 3 does.

My old Dell had a feature to stop charging at 80%. My Samsung tablet can do something similar. Turns out my old Surface Pro 3 can do the same. It’s just labeled “Kiosk Mode” and it’s in the UEFI (enter via Power+Vol Up). It stops charging at 50%.

You can also check the battery health:

How to create a battery report on a Surface

And this is how the report looks like:

My battery report

Reversing Bits

Part of my morning routing is to read news. One source is Google News which pointed me today to this article: Reverse Engineering an Unknown Microcontroller. While highly interesting by itself, this section struck me:

The constants 0x55, 0xAA, 0xCC, and 0x33 were staring me in the face. Could it be? Was someone stupid enough to…? Yup… These are the constants for a clever way to reverse the order of bits in a byte.

While I recognized the bit patterns (01010101, 10101010, 11001100 and 00110011) I did not know how those are used to reverse bits.

Clearly an unacceptable situation which needs to be fixed!

Reversing Bits – Normal Way

Reversing bits is simple in C. Loop through all bits and check if they are set. If they are, set the bits in the result in reverse order (bit 0 is set, then set bit 15 in case of 16 bit integers):

#define BITS 16

unsigned int reverse1(unsigned int n) {
  unsigned int res = 0;
  for (int i = 0; i < BITS; ++i)
    if (n & (1 << i))
      res |= (1 << ((BITS - 1) - i));
  return res;

and I always imagined the code is optimized well enough that it’s sufficiently fast. Works for all bit length too. And gcc (since v5 latest) optimizes it well (from here):

        xor     eax, eax
        xor     r8d, r8d
        mov     esi, 1
        mov     r9d, 15
        mov     edx, esi
        mov     ecx, eax
        sal     edx, cl
        test    edx, edi
        je      .L2
        mov     ecx, r9d
        mov     edx, esi
        sub     ecx, eax
        sal     edx, cl
        or      r8d, edx
        add     eax, 1
        cmp     eax, 16
        jne     .L3
        mov     eax, r8d

i is in the register eax, res is r8d and n is in rdi.

Reversing Bits – With 0xAA and 0xCC

But it turns out you can reverse bits like this too:

unsigned int reverse2(unsigned int n) {
   n = (n & 0xAAAA) >> 1 | (n & 0x5555) << 1;
   n = (n & 0xCCCC) >> 2 | (n & 0x3333) << 2;
   n = (n & 0xF0F0) >> 4 | (n & 0x0F0F) << 4;
   n = (n & 0xFF00) >> 8 | (n & 0x00FF) << 8;
   return n;

And it’s clever how this works. Imagine a byte n with its bits named 76543210 which are the bit positions of its bits.

  • The first line swaps bit pairs: you start with 76543210 and get 67452301
  • The second line swaps 2 bit pairs: 45670123
  • The third line swaps 4 bit pairs: 01234567, which is the reverse of where we started

Reminds me of SIMD. The fourth line swaps the top and bottom 8 bits of the 16 bit number n. Doubling the bit size is a simple extra instruction (plus double the size of the constants).

And here is the generated code (gcc v11):

        mov     eax, edi
        shr     edi
        add     eax, eax
        and     edi, 5555h
        and     eax, 0AAAAh
        or      edi, eax
        mov     eax, edi
        sal     edi, 2
        shr     eax, 2
        and     edi, 0CCCCh
        and     eax, 3333h
        or      eax, edi
        mov     edx, eax
        sal     eax, 4
        shr     edx, 4
        and     eax, 0F0F0h
        and     edx, 0F0Fh
        or      edx, eax
        mov     eax, edx
        sal     edx, 8
        shr     eax, 8
        movzx   edx, dx
        or      eax, edx

Obviously way faster since there’s no loop and no branch. It is also known since 1983. I obviously never needed to reverse bits.

I guess this proves my point about learning stuff in general and in particular in IT: There’s way too much knowledge to know or learn everything. You only learn when you need it. Or when you stumble upon it accidentally.

step-ca and ACME

For my home Kubernetes installation I guess it’s time to enable TLS. Can’t use Let’s Encrypt for this as my internal network is not reachable and while I have workaround for this problem, I’d rather use my internal Certificate Authority via step-ca.

It’s actually simpler than I thought it is, mainly because the documentation I found first included options which were not explained at all. Turns out they are indeed fully optional… Thus on the CA server do:

step ca provisioner add acme --type ACME

This adds the ACME provisioner to the ~/.step/config/ca.json file:

  "type": "ACME",
  "name": "myacme",
  "forceCN": true,
  "claims": {
     "maxTLSCertDuration": "12h",
     "defaultTLSCertDuration": "2h

The first 2 items were added by above command. The next were added by me. They are optional. Restart step-ca:

harald@r2s1:~$ sudo systemctl restart step-ca
harald@r2s1:~$ systemctl status step-ca
● step-ca.service - Step Certificates
     Loaded: loaded (/etc/systemd/system/step-ca.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2021-05-11 18:27:39 JST; 15s ago
   Main PID: 547880 (step-ca)
      Tasks: 8 (limit: 998)
     Memory: 10.5M
     CGroup: /system.slice/step-ca.service
             └─547880 /usr/local/bin/step-ca /home/harald/.step/config/ca.json --password-file /home/harald/.step/pass/key_pass.txt

To create a new certificate on a different machine which runs no HTTP server on port 80:

❯ sudo REQUESTS_CA_BUNDLE=$(step path)/certs/root_ca.crt \
    certbot certonly --standalone  \
    --server https://ca.lan:8443/acme/acme/directory
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator standalone, Installer None
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): my.mail@some.mail.server

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at None. You must agree in order to register
with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: n
Account registered.
Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): m75q.lan
Requesting a certificate for m75q.lan
Performing the following challenges:
http-01 challenge for m75q.lan
Waiting for verification...
Cleaning up challenges

 - Congratulations! Your certificate and chain have been saved at:
   Your key file has been saved at:
   Your certificate will expire on 2021-05-11. To obtain a new or
   tweaked version of this certificate in the future, simply run
   certbot again. To non-interactively renew *all* of your
   certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:
   Donating to EFF:          

And now let’s renew:

❯ sudo openssl x509 -in /etc/letsencrypt/live/m75q.lan/fullchain.pem -noout -text | grep After
            Not After : May 11 11:16:01 2021 GMT
❯ sudo REQUESTS_CA_BUNDLE=$(step path)/certs/root_ca.crt \
    certbot renew --server https://ca.lan:8443/acme/acme/directory
❯ sudo openssl x509 -in /etc/letsencrypt/live/m75q.lan/fullchain.pem -noout -text | grep After
            Not After : May 11 11:17:04 2021 GMT

This is documented here. Note that the certificate ends up in /etc/letsencrypt/live/ and because root ran the command, you need root to get it out. Not the way it should be, but this is more a test for the ACME provider for step-ca.

Protocol Buffers and Node.js

Kafka can encode a message via Avro or Protocol Buffers which are both binary protocols. They are comparable to each other (see here) but since gRPC uses Protocol Buffers and it seems it can do anything Avro can do (plus more), maybe a good time to dig into it a bit.

For debugging, here is a web page which can decode a ProtoBuf message. Nice for debugging.

Google docs for ProtoBuf for JavaScript is here. Here a quick working example:

const messages = require('./addressbook_pb');

let message = new messages.Person();

message.setName("Harald K");

let phone1 = new messages.Person.PhoneNumber();

let phone2 = new messages.Person.PhoneNumber();


console.log("message object:");

console.log("message as JSON:");

let binBuffer=Buffer.from(message.serializeBinary());
console.log("Binary serialized:");
console.log("And in hex:");
let s=""
for (const i of binBuffer) {
    s+=i.toString(16).padStart(2, '0')+" ";

// Now let's convert the binary ProtoBuf message into a proper object again

let message2 = messages.Person.deserializeBinary(binBuffer);
console.log("Converted from binary:");
console.log("...and as Object:");

The addressbook.proto is from here.

Kafka & Schema

Once you understand how Kafka works, it’s so easy to find use-cases for it. To learn to understand it better, a local install helps a lot though, plus some interactive tools and libraries to produce and consume data.

  1. Follow the Confluent quick start Docker demo
  2. Configure zoe
  3. See users and pageviews data via zoe
  4. Consume the same data via KafkaJS
  5. Make KafkaJS use the schema registry via confluent-schema-registry

Zoe config file. Note the KafkaAvroDeserializer.

❯ cat ~/.zoe/config/default.yml
      bootstrap.servers: "t620.lan:9092"
      key.deserializer: "org.apache.kafka.common.serialization.StringDeserializer"
      value.deserializer: "io.confluent.kafka.serializers.KafkaAvroDeserializer"
      key.serializer: "org.apache.kafka.common.serialization.StringSerializer"
      value.serializer: "org.apache.kafka.common.serialization.ByteArraySerializer"
    registry: ${SCHEMA_REGISTRY:-http://t620.lan:8081}
      mygroup: my-group-id
        name: "users"
        subject: "users-value"
  default: "local"

View users via zoe:

❯ zoe --silent --cluster default topics consume users

And now via Node.js:

// Use with
// And its users producer

const { Kafka } = require('kafkajs')
const { SchemaRegistry } = require('@kafkajs/confluent-schema-registry')

const kafka = new Kafka({ clientId: 'my-app', brokers: ['t620.lan:9092'] })
const registry = new SchemaRegistry({ host: 'http://t620.lan:8081/' })
const consumer = kafka.consumer({ groupId: 'test14-group' })

const run = async () => {
  await consumer.connect()
  await consumer.subscribe({ topic: 'users', fromBeginning: true })

    eachMessage: async ({ topic, partition, message }) => {
      // const decodedKey = await registry.decode(message.key)
      const decodedKey = message.key.toString();
      const decodedValue = await registry.decode(message.value)
      console.log({ decodedKey, decodedValue })
      // console.log(`message=${JSON.stringify(message)}`)


which prints out users like

  decodedKey: 'User_2',
  decodedValue: Users {
    registertime: 1516972272723,
    userid: 'User_2',
    regionid: 'Region_5',
    gender: 'FEMALE'

Note for ARM64 users

While I usually use my ThinkCentre for development work, I have a small ARMv8 machine which I use for small stuff. Node.js runs very well on it and so does Python.

However to install the Python package confluent-kafka, I am supposed to install the latest librdkafka-dev from here. Except this is amd64 only. So no Python confluent-kafka on ARMv8 unfortunately.

OBS and Fun With WebEx

At work we use WebEx for video conferencing. Not the worst choice. I like video conferencing as I think it makes meetings better and more fun. Also nice to see people once in a while when working from home. Then on March 15 this came up:

This Dilbert strip immediately made me think: I want that too! But how?

Our WebEx is limited by corporate policies, so no fancy backgrounds and certainly no closing credit plugins if they even exist. There had to be a way: it’s a technical problem, so there must be a technical solution.

Searching a bit around made me find OBS which is normally used to stream to Twitch/YouTube/etc. or to record things like lesson videos. And it has a “Virtual Camera” feature which does exactly when you think it does: it presents its output as a new video camera device which other programs can use as their video input.

And it works! Except in WebEx. Turns out WebEx does not like this. However WebEx does not mind NDI stream as an input and OBS can output such a stream via the NDI Tools.

So all I need now is:

  1. Have OBS set up with NDI Tools
  2. Create 2 scenes in OBS: my webcam’s picture and the same plus scrolling text (AKA the closing credits)
  3. Enable NDI Output (in the Tools menu of OBS)
  4. In WebEx application, choose the NDI camera as video source
  5. When you want the closing credits to show, switch the scene

There’s of course a lot more potential fun inside OBS:

Side Effects

As an unexpected side effect while learning about OBS, I fixed my light during video conferences (Key/Fill/Back lights), made me stand out from the background more, learned how boring cameras are when they statically point at you, made the sound better via some audio filters, and I looked into the world of Shaders, which are super interesting but I think that’s too deep into that rabbit hole…

Fun with PIV with my YubiKey 3 Neo

Turns out that my マイナンバーカード is not the only thing which can do things like signing files and PIV is the official(?) standard for this. My old Yubikey 3 Neo can do that too thanks to the yubico-piv-tool.

And it’s basically the same as the マイナンバーカード except I have to set up everything myself.

As on my マイナンバーカード there’s 2 slots for 2 different keys and certificates:

  • Slot 9a for identification
  • Slot 9c for signing

Creating them is simple. I just show the ones for the signing slot 9c:

❯ yubico-piv-tool -s9c -AECCP256 -agenerate -o
❯ yubico-piv-tool -s9c -S'/CN=Harald Kubota/OU=Home/O=lan/' -averify -arequest -i -o f2-9c.csr
Enter PIN: 
Successfully verified PIN.
Successfully generated a certificate request.
# I need a DNS Name. And 8670h is about 1 year.
❯ step ca sign --set=dnsNames='["test5.lan"]' --not-after=8760h f2-9c.csr f2-9c.crt
✔ Provisioner: myCA@home (JWK) [kid: IFXxmmZDCX76WMNbFfUoBOBZdubx0SG45Jsd0VGxaz1]
✔ Please enter the password to decrypt the provisioner key: 
✔ CA: https://ca.lan:8443
✔ Certificate: f2-9c.crt
❯ yubico-piv-tool -s9c -aimport-certificate -i f2-9c.crt
Successfully imported a new certificate.

And here is how to sign a file and verify the signature:

❯ yubico-piv-tool -averify-pin --sign -s9c -HSHA256 -AECCP256 -i test.txt -o test.signature
Enter PIN: 
Successfully verified PIN.
Signature successful!

❯ yubico-piv-tool -s9c -aread-certificate >f2-9c.crt
❯ openssl x509 -pubkey -in f2-9c.crt -noout >
❯ openssl dgst -sha256 -verify -signature test.signature test.txt
Verified OK

マイナンバーカード fun!

Got a Smart Card reader, so the fun can begin!

PDF Signing

This is most common, so it’s best documented.

For Windows you need:

Old non-Unicode software, not well tested on non-Japanese PCs
  • Optional: Import the root certificate as it’s documented in the English description.
  • PDF Signing software from here
  • Usage is simple enough. Worked on my first try.
  • To test, get Acrobat Reader DC. Don’t forget to un-click all unwanted extra-software.
  • In Acrobat, go to Edit/Preferences and click on Signatures/Verification’s More… button and enable Windows Integration:
  • Alternatively import the user signing CA certificate into Acrobat Reader so it trusts it.

Now the previously signed PDF should show up in Acrobat as signed:


Far more interesting (for me) is signing arbitrary files to proof that those are “mine”.

myna is a simple program for Windows, Linux and Mac to do all basic things the マイナンバーカード can do. Usage is simple (Windows here):

> myna.exe jpki cms sign -i INPUTFILE -o OUTPUTFILE
> myna.exe jpki cms verify FILE

Note that the both command needs the マイナンバーカード available. The OUTPUTFILE is in PKCS#7 format. Verification via openssl is possible:

$ openssl cms -verify -inform DER -in FILE -CAfile jpki.pem

The jpki.pem is the PEM encoded root certificate from your マイナンバーカード . But in return you don’t need the card at this point.

If you want to see who signed:

$ openssl pkcs7 -print_certs -inform DER -in test-signed.p7m -noout
subject=C = JP, L = Tokyo-to, L = Xxx-shi, CN = 

issuer=C = JP, O = JPKI, OU = JPKI for digital signature, OU = Japan Agency for Local Authority Information Systems

# Many more cert details:
$ openssl pkcs7 -print_certs -inform DER -in test-signed.p7m -noout -text

# Actual verify:
$ openssl cms -verify -inform DER -in test-signed.p7m -CAfile jpki.pem -cmsout -print
  contentType: pkcs7-signedData (1.2.840.113549.1.7.2)
    version: 1
        algorithm: sha1 (
        parameter: <ABSENT>
      eContentType: pkcs7-data (1.2.840.113549.1.7.1)
        0000 - 4d 6f 64 65 6c 73 50 61-74 68 3d 22 4d 6f 64   ModelsPath="Mod
        00b4 - 76 65 32 44 22 0a                              ve2D".
          version: 2
          serialNumber: 4xxxxxx5
            algorithm: sha256WithRSAEncryption (1.2.840.113549.1.1.11)
            parameter: NULL
          issuer: C=JP, O=JPKI, OU=JPKI for digital signature, OU=Japan Agency for Local Authority Information Systems
            notBefore: Feb 15 19:11:22 2021 GMT
            notAfter: Xxx xx 14:59:59 2025 GMT
          subject: C=JP, L=Tokyo-to, L=Xxx-shi, CN=2xxxxxxxxxxxxxxxxxxxxxxxxxxA

You should be able to recognize the signing serial number: that’s the user certificate on the マイナンバーカード.

Other Notes

There’s 4 certificates on the card:

  • user certificate
  • the CA’s public certificate which signed the user certificate
  • user signing certificate
  • the CA’s public certificate which signed the user signing certificate

asn1decode shows the internal structure of data, but a lot of data is hidden in “OCTET STRING” like this:

 1637:d=8  hl=3 l= 176 cons: SEQUENCE
 1640:d=9  hl=2 l=   3 prim: OBJECT            :X509v3 Authority Key Identifier
 1645:d=9  hl=3 l= 168 prim: OCTET STRING      [HEX DUMP]:3081A580144DE017DE4B7F473DCD867A62D38B134ACE83558AA18186A48183308180310B3009060355040613024A50310D300B060355040A0C044A504B4931233021060355040B0C1A4A504B4920666F72206469676974616C207369676E6174757265313D303B060355040B0C344A6170616E204167656E637920666F72204C6F63616C20417574686F7269747920496E666F726D6174696F6E2053797374656D7382040132C4AB
 1816:d=8  hl=2 l=  29 cons: SEQUENCE
 1818:d=9  hl=2 l=   3 prim: OBJECT            :X509v3 Subject Key Identifier

You can display that data in the binary blob like this:

harald@r2s1:~/t$ openssl asn1parse -inform DER -in test-signed.p7m -strparse 1645
    0:d=0  hl=3 l= 165 cons: SEQUENCE
    3:d=1  hl=2 l=  20 prim: cont [ 0 ]
   25:d=1  hl=3 l= 134 cons: cont [ 1 ]
   28:d=2  hl=3 l= 131 cons: cont [ 4 ]
   31:d=3  hl=3 l= 128 cons: SEQUENCE
   34:d=4  hl=2 l=  11 cons: SET
   36:d=5  hl=2 l=   9 cons: SEQUENCE
   38:d=6  hl=2 l=   3 prim: OBJECT            :countryName
   43:d=6  hl=2 l=   2 prim: PRINTABLESTRING   :JP
   47:d=4  hl=2 l=  13 cons: SET
   49:d=5  hl=2 l=  11 cons: SEQUENCE
   51:d=6  hl=2 l=   3 prim: OBJECT            :organizationName
   56:d=6  hl=2 l=   4 prim: UTF8STRING        :JPKI
   62:d=4  hl=2 l=  35 cons: SET
   64:d=5  hl=2 l=  33 cons: SEQUENCE
   66:d=6  hl=2 l=   3 prim: OBJECT            :organizationalUnitName
   71:d=6  hl=2 l=  26 prim: UTF8STRING        :JPKI for digital signature
   99:d=4  hl=2 l=  61 cons: SET
  101:d=5  hl=2 l=  59 cons: SEQUENCE
  103:d=6  hl=2 l=   3 prim: OBJECT            :organizationalUnitName
  108:d=6  hl=2 l=  52 prim: UTF8STRING        :Japan Agency for Local Authority Information Systems
  162:d=1  hl=2 l=   4 prim: cont [ 2 ]

Got my マイナンバーカード!

For anyone outside Japan this is probably not of any interest. Please pass. Nothing to see here.

For me it was interesting: this is a smart card which can also use NFC, which makes it very interesting: How does it work? What data is inside? Can I look at it? Can other people look at it (without the PIN)? Why does it have 2 different PINs?

Things I learned in half a day since I got my MyNumber card:

  • It can do NFC too.
  • This app works to read data off the card. Including pictures, certificates and other stuff. Interesting.
  • On this site it explains the file system structure and other internals of the card. Very interesting.
  • That unrelated app works great to read my Suica/PASMO card. And both apps work and they figure out which card is for which app. Neat.
  • Here is a 5 year old article about how to use the data via its PKCS#11 API. And how to use this for ssh with OpenSC. I did that a while ago with a YubiKey. I prefer the YubiKey form factor a lot.
  • I got so many gadgets at home, but no Smart Card reader/writer. I should get this fixed so I can read the certificate with my PC. Makea paying tax via e-Tax much easier too.
Create your website with
Get started