Archives For gonzo

I wrote an introductory article on how the audio subsystem on SBCs work: CODECs, I2S, DTS, whole nine yards. WordPress editor didn’t seem to be a very convenient tool for this kind of write up so I gave asciidoc a try and so far liked it.

Link to the article:

Some time ago Filippo Valsorda wrote yubikey-agent, seamless SSH agent for YubiKeys. I really like YubiKeys and worked on the FreeBSD support for U2F in Chromium and pyu2f, getting yubikey-agent ported looked like an interesting project. It took some hacking to make it work but overall it wasn’t hard. Following is the roadmap on how to get it set up on FreeBSD. The actual details depend on your system (as you will see)

The first step is to set up middleware for accessing smart cards (YubiKey implements CCID smart-card protocol). The pcsc-lite package provides a daemon and a library for clients to communicate with the daemon. ccid is a plugin for pcsc-lite that implements the actual CCID protocol over USB. devd rules are to make the daemon re-scan USB devices on hotplug

sudo pkg install ccid pcsc-lite
sudo mkdir -p /usr/local/etc/devd
sudo tee /usr/local/etc/devd/pcscd.conf << __EOF__
attach 100 {
        device-name "ugen[0-9]+";
        action "/usr/local/sbin/pcscd -H";
detach 100 {
        device-name "ugen[0-9]+";
        action "/usr/local/sbin/pcscd -H";

sudo service devd restart
sudo sysrc pcscd_enable="YES
sudo service pcscd start

go and git are build requirements for the app. go get command is required because FreeBSD support was only recently merged into piv-go and the latest release, referenced in go.mod, still does not have it. go install command installs the app in ~/go/bin/. When new version of piv-go is released and yubikey-agent switches to using it, all these commands can be replaced with single go get command.

sudo pkg install go git
git clone
cd yubikey-agent
go get
go build
go install

The binary is in ~/go/bin/ directory, you can add it to your $PATH to type less.

The next step is setting up a Yubikey, it’s well documented on the official site. One caveat though is if PIN length is less than 6 chars the setup fails with the somewhat confusing message: “‼️ The default PIN did not work.”

The actual usage of yubikey-agent depends on your setup. First of all, yubikey-agent is a “eventually GUI” app. At some point, when entering PIN is required it starts pinentry command which task is to present user with a dialog entry, get PIN, and pass it to the app. There are multiple pinentry flavors, with different front-ends: TTY, Qt, GTK. gopass module used in yubikey-agent does not work with plain TTY backend, and requires pinentry to be a GUI app. On Debian/Ubuntu users can switch between flavors and make /usr/bin/pinentry point to either Qt5 or GTK version, but in FreeBSD /usr/local/bin/pinentry is always TTY one. I worked around it by installing pinentry-qt5 package and making symlink.

sudo pkg install pinentry-qt5
sudo ln -s /usr/local/bin/pinentry-qt5 /usr/local/bin/pinentry

If you need /usr/local/bin/pinentry to be TTY version for some other stuff, there may be a problem. How to work around this depends on your requirements. I don’t have a ready recipe.

Because yubikey-agent is “eventually GUI” you can either start it in .xsession or .xinitrc files or start it some other way with DISPLAY env variable set. Other than that official documentation is a good source of information on how to use it.

Whenever I sit down to work at the coffee shop I’ve never been before my preparation routine looks more or less like this: ifconfig wlan0 list scan, copy SSID, vim /etc/wpa_supplicant.conf, service netif restart. The WM I use, i3, does not have fancy network managers that nicely offer you to join available WiFi networks. It’s mildly annoying but not annoying enough to actually make me open a browser and go looking for ways to automate this procedure. Implementing such a utility, on the other hand, sounds like a nice weekend project.

I wanted to try out the Go language for a long time but didn’t have a good idea for a project and this WiFi manager tool looked like a good fit to learn how stuff is done there because it required: starting a child process and parsing its output, file I/O, work with strings, TUI elements.

The data management bits were easy, the standard library provides all the required functionality, and for TUI framework I picked up termui. Midway through implementation, I realized that the main use case of the framework is to present data, and interacting with the user was not its forte, but I decided to press on and just hack something together. It was just for fun after all. It worked out acceptable in the end.

Without further ado, let me introduce Chai-Fi, the minimalistic wpa_supplicant.conf “manager” for FreeBSD. To be used in coffee shops, guest networks, and other locations. It’s got a bunch of stuff hardcoded, not very portable between different TERMs and probably won’t look nice with non-Unicode fonts. But hey, it works on my laptop. Who knows, might work on yours

If you want to jump right into the action check out freebsd-mkova repo. Below are some technical details on what OVA is and its internals.

In addition to installation media like DVD or memstick, FreeBSD RE ships FreeBSD releases as a virtual disk image in a number of formats. This is a convenient way when you start your whole VM using bhyve or qemu, as a single CLI command and pass the image location as an argument. It’s less handy if you try to create VM using GUI-based tools like VMWare or VirtualBox. You need to create VM and then configure it to use the image as a drive. Not an awful lot of work but still.

At my $DAYJOB I came across another way of shipping VM-based products called virtual appliance. Essentially it’s a pre-configured virtual machine with disk image included in a self-contained file that can be imported by hypervisor software using couple of mouse clicks or a single command like VBoxManage import. The file format for this kind of deliverables is OVA

Internally OVA is a tar(1) archive that includes OVF file, disk image or images in VMDK format, and optional manifest (list of files with checksums). OVF file is an XML file with VM description that looks like this. More information on the format can be found at

So on the surface, we need to take official VMDK, create XML file and package them both in .tar archive. Unfortunately, there is a problem: VMDK format comes in several flavors and while FreeBSD RE ships monolithic sparse, OVA needs the image in stream-optimized flavor.

As the name implies monolithic-sparse format does not have every single sector of the virtual disk in the file, it only stores the data that was written by OS. The standard unit of data on disk is a sector, usually 512 bytes long. VMDK organizes sectors in grains: a sequence of sectors. The size of the grain (in sectors) is defined in the VMDK header as a grainSize field. So if an image is N sectors long there are N/grainSize grains. Only grains with the content that is different from all-zeroes are stored in the image file. To organize fast random access to the stored data in the image VMDK maintains a two-level index: grain directory and grain table. Grain table is a fixed-size array (numGTEsPerGT field in the header) with offsets of the grain in VMDK. If offset is zero it means the grain is not present in the file and its content is all-zeroes. Grain tables’ offsets, in turn, are stored in grain directory. And again if offset in the directory is zero it means none of the grains in the table is present in the image. The sequence of steps to read sector X from the VMDK is approximately this:

grainIdx := [X / grainSize]                 // Find the grain index 
gtIdx := [grainIdx / numGTEsPerGt] // Find the grain table index
gtOffset := grainDirectory[gtIdx] // Find grain table offset // if gtOffset is zero return empty sector
grainTable := readAt(gtOffset) // read grain table data
grainOffset := grainTable[X % grainSize] // find grain offset // if grainOffset is zero return empty sector
sectorData := readAt(grainOffset + (X % grainSize)) // read sector data

The VMDK file layout for monolithic sparse format would look like:

[header] [imageDescriptor] [GrainDirectory] [GrainTable0] … [GrainTableN ] [ Grain0 ] [GrainX ] [ GrainY ] … [ GrainZ

The stream-optimized VMDK operates with the same concepts: grain, grain table, grain directory but organizes them differently. Again as the name implies it’s optimized for streaming which means no random access to the image file so it lays out elements a bit differently. GD, GT, grains are prefixed with the markers and can be detected as the software reads file from the network. Also, grains can be compressed to save bandwidth. The stream-optimized VMDK layout looks like this:

[ header ] [imageDescriptor] [GrainMarker] [Grain] … [GrainMarker] [Grain] [GrainTableMarker] [GrainTable0] … [GrainDirectoryMarker] [GrainDirectory] [FooterMarker][FinalHeader] [EndOfStreamMarker]

the FinalHeader is the copy of the header with the gdOffset field set to point to [GrainDirectory] location

As you can see the conversion from monolithic sparse to stream optimized is quite straightforward. I spent some time implementing it over the holiday break, added OVF generation logic and shipped freebsd-mkova. I wanted to write it in Go to practice a new language but was turned off by the XML generation and namespaces support in it, it felt unnecessary verbose and clunky. Will try to find some other project for Go my studies.

CentOS 7 VM boot issue

January 10, 2020 — Leave a comment

If you’re building OVA based on CentOS 7 and your VM is stuck during boot at “tsc: Refined TSC clocksource calibration: NNNN.MMM MHz” message do not despair! It means the kernel can not find the root device and just waits for it to pop up. Which is not going to happen. In my case, it was a lack of required drivers loaded boot-time. Following line in an OVA build script resolved the issue:

dracut --regenerate-all --force --add-drivers "sd_mod mptspi" 

This post is just a breadcrumb for people googling for the line from the boot log. Might save you some time (might save future me some time).

Audio for RK3399

November 30, 2019 — 3 Comments

Last two weeks I’ve been working on audio support for Firefly-RK3399. Full support requires a number of things that are not quite there or not available in the mainline FreeBSD kernel. The main low-level hardware functionality consists of two parts: I2S block in the SoC and RT5640 audiocodec that converts digital audio to an analog signal. They talk to each other using the I2S protocol. A little bit higher is FDT virtual “devices” called simple-audio-card. This part is responsible for coordinating the setup of both hardware components: make sure they agree on a number of channels, a number of bits per sample and clock specifics of the I2S protocol. There is no code for it in the FreeBSD kernel, so I had to just hardcode these things in both hardware drivers.

The other obviously missing part was I2S clocks in the CRU unit drivers. This was easily fixable by just consulting with RK3399 TRM. Still, having added the clocks support I couldn’t get the signal on the physical pin. Thanks to manu@ who pointed out that some stuff might be missing in io-domain and power regulators area it was resolved too after setting bit 1 of GRF_IO_VSEL register

With all these bits in place, I was able to get sound out of headphones, but it was distorted. My first instinct was to blame mismatch of clocks/formats between I2S and codec, so I spent two very frustrating days experimenting with setting polarities and data formats just to find out that there is GPIO that controls headphone output on Firefly-RK3399. This is Firefly-specific bit and only referenced in the Firefly fork of the Rockchip fork of the Linux kernel. The way it’s implemented loud noises still can pass through the filter to headphones, so at max volume, you can here laud parts as a series of pops and grunts. By manually configuring GPIO4_C5 (gpioc4/pin21) I finally was able to get clear sound out of the Firefly.

On the bright side now I know how to convert an I2S stream captured by a Saleae logic analyzer to wav file:

The next step is to check how much work would it take to implement the simple-audio-card part. The (very hacky) WIP is at

Recreating Sneakers scene

September 28, 2019 — Leave a comment

(Not a FreeBSD topic)

A long time ago, in my teens, I watched movie Sneakers and was very impressed by it. It was exactly how I imagined hackers at work: bare PCBs, signal probes, de-scrambling encrypted information right on the screen. I was so impressed by the latter part that I went to re-create a bit of “No more secrets” scene using the only technologies I knew back then: Turbo Pascal running on MS-DOS. It wasn’t an exact replica but it was close enough and I was quite happy with the result. The program itself hasn’t survived my numerous moves from one apartment to another and got lost along with all the floppy discs sometime in the early aughts.

Recently I re-watched the movie and turned out that it holds up pretty well and still fun to watch. I thought that it would be a fun experience to re-create my small demo and check if I still remember any of the Pascal and DOS APIs. Equipped with Pascal for PC book published in ’91, some MS-DOS guides from the internet and a Guinness 4-pack I walked a short walk down the memory lane and it was fun. The result is published on Github. The demo in action:

FreeBSD support for pyu2f

September 22, 2019 — Leave a comment

After long hiatus (because $JOB) I’m trying to find some time to spend on FreeBSD-related projects, looking for small ones that can be done over weekend or a bit more. One of the ideas came from Ed Maste’s twitter: implement FreeBSD support for pyu2f. Since I already spent some time working on FreeBSD U2F support for Chromium it felt like a good small project.

The challenging part of the project was not U2F/HID but interfacing ioctl with Python, something I have never done before. It wasn’t super complex and I learned about Python’s ctype module.

Even more challenging though was to find a code to verify the implementation. Turned out there was no script to run end-to-end test. The closest I managed to find was this code in Xpra project. I used it as a base to write following test that registers app and then signs a pseudo challenge. It only verifies the interface part and doesn’t care about the actual signatures/keys:

import os
from pyu2f import u2f
from pyu2f import model

APP_ID = 'wordpress'
REGISTRATION_DAT = 'registration.dat'

device = u2f.GetLocalU2FInterface(ORIGIN)

# Try to register new app or read saved registration data if it exists
if os.path.exists(REGISTRATION_DAT):
    with open(REGISTRATION_DAT, 'rb') as f:
        rd =
    r = device.Register(APP_ID, b'ABCD', [])
    rd = r.registration_data
    with open(REGISTRATION_DAT, 'wb+') as f:

# extract public key, key handle length, and key handle
pubkey = bytes(rd[1:66])
# this is for Python3, use ord(rd[66]) for Python2
khl = rd[66]
key_handle = bytes(rd[67:67 + khl])

# Try to authenticate
key = model.RegisteredKey(key_handle)
response = device.Authenticate(APP_ID, b'012345678', [key])
print (response.signature_data)
print (response.client_data)

The final result is in my fork of pyu2f repo, on freebsd branch.

Inky pHat on FreeBSD/Pi

November 14, 2018 — Leave a comment

About a month ago I purchased Inky pHat from Pimoroni, Pi hat with 220×104 red and black eInk screen. The device has an SPI interface with three additional GPIO signals: reset pin, command/data pin, and busy pin. Reset and busy pins are self-explanatory: the former resets device MCU the latter signals to the Pi whether the MCU is busy handling previous command/data. Command/data signals the type of SPI transaction that is about to be sent to Inky: low means command, high – data. It more or less matches interface to SSD1306 OLED display I played with before.

There is no datasheet or protocol description, so I used Pimoroni’s python library as a reference.

To communicate with the device over SPI, you need to apply spigen device-tree overlay and load spigen driver. For Raspberry Pi 3 you probably need a patch from this review applied. To load overlay add respective dtbo name to the fdt_overlays variable in /boot/loader.conf, e.g.:


I didn’t have any practical purpose for the device in mind so after several failed attempts to output RGB images in two color I ended up writing random ornament generator:



I was updating my laptop to the latest HEAD today and noticed that my bash prompt looks ugly in default console color scheme. So what with one thing and another I ended up writing color themes support for vt(4). Just because it was fun thing to do. The idea is that you can redefine any ANSI color in console using variable in /boot/loader.conf, i.e.:

kern.vt.color.0.rgb="0,0,0" # color 0 is black
# or
kern.vt.color.15.rgb="#ffffff" # color 15 is white

Here is how my Tomorrow Night theme looks like:


It works only with framebuffer-based console like efifb or i915kms.
Patch: console-color-theme.diff