Snippets

Various code snippets colected over the eons. Might be useful to someone.

Debian - List installed packages by disk space

$ dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -n | tail -n 10

Extract a video sample from a larger file

$ ffmpeg  -ss 00:00:10 -i <FILE>.mp4 -t 00:00:15 -async 1 -strict -2 <FILE2>.mp4

Extract audio from a video file

$ ffmpeg -i <FILE>.webm -vn <FILE2>.mp3

Archive a website for offline viewing

$ wget --mirror --convert-links --adjust-extension --page-requisites --no-verbose <SITE_URL>

OpenSSL - decrypt file

$ openssl enc -d -aes-256-cbc -pbkdf2 -k <PASSWORD> <ENCRYPTED_FILE> > <FILE>

OpenSSL - encrypt file

$ openssl enc -aes-256-cbc -pbkdf2 -k <PASSWORD> <FILE> > <ENCRYPTED_FILE>

LUKS - restore backup of LUKS header

$ cryptsetup luksHeaderRestore <DEVICE> --header-backup-file <FILE_NAME>

LUKS - create backup of LUKS header

$ cryptsetup luksHeaderBackup <DEVICE> --header-backup-file <FILE_NAME>

Chromium - take screenshot headless

$ chromium --ignore-certificate-errors -headless --screenshot="<FILE_NAME>.png" <HOST_NAME>

MySQL export database

$ mysqldump --host="<MYSQL_SERVER_HOST>" \
	--user="<MYSQL_SERVER_USER>" \
	--password="<MYSQL_SERVER_PASSWORD>" \
	--default-character-set=latin1 \
	--result-file="./dump.sql" \
	--lock-tables --add-locks --create-options \
	--extended-insert --add-drop-table --disable-keys \
	<MYSQL_DATABASE_NAME>

MySQL import database

$ mysql --user="<MYSQL_SERVER_USER>" --password="<MYSQL_SERVERPASSWORD>" \
	--default-character-set=utf8 \
	<MYSQL_DATABASE_NAME> < dump.sql

Git commit with normalized UTC timezone

$ git config --global alias.utccommit '!git commit --date="$(date --utc +%Y-%m-%dT%H:%M:%S%z)"'

10 most used commands

$ history | awk '{print $2}' | sort | uniq -c | sort -nr | head -n 10

Android - forcing media refresh

$ adb -d shell "am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///sdcard"

Android - reinstall app without losing data

$ adb -d shell "pm uninstall -k com.package.name"

Android - pull raw image of flash memory

$ adb pull /dev/block/mmcblk0 mmcblk0.img

macOS - Unload camera kernel extension

$ sudo kextunload -b /System/Library/Extensions/AppleCameraInterface.kext

Get power draw in watts

$ echo - | awk "{printf \"%.1f\", \
$(( \
  $(cat /sys/class/power_supply/BAT1/current_now) * \
  $(cat /sys/class/power_supply/BAT1/voltage_now) \
)) / 1000000000000 }" ; echo " W "

macOS - Compare SHA-256 of file with the hash

$ shasum -a 256 -c <<< '<SHA-HASH> *<FILE>'

Windows - Check SHA-256 of file

# CMD
CertUtil -hashfile <FILE> SHA256
# Powershell
Get-FileHash <FILE> -Algorithm SHA256

Linux - Check SHA-256 of file

$ sha256sum <FILE>

macOS - Check SHA-256 of file

$ shasum -a 256 <FILE>

macOS - Bless VirtualBox kernel extension

$ spctl kext-consent add VB5E2TV963

IPFS pin and publish a site

#!/usr/bin/env bash
hash=$(ipfs add -r -q "<DIR>" | tail -n 1)
ipfs pin add $hash
ipfs name publish $hash

Parse certificate in DER format

$ openssl asn1parse -in <FILE>.cer -inform der

Convert SVG to PNG (and resize) using Inkscape

$ inkscape -w 64 -h 64 <FILE>.svg -o <FILE>.png

Convert PNG to RGB colorspace

$ magick convert -set colorspace RGB <FILE>.png PNG32:<FILE>.png

Montage multiple images horizontally in a single image

# Montage 5 PNG files named <FILES>1.png to <FILES>5.png, alphabetically
$ magick montage <FILES>*.png -background none -tile 5x1 -geometry +0+0 <FILE>.png

Spoof MAC address to a random value

$ sudo ifconfig en0 ether $(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')
$ sudo ifconfig en0 down
$ sudo ifconfig en0 up

macOS - Get SSID of the network currently connected to

$ /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | \
	awk '/ SSID/ {print substr($0, index($0, $2))}'

macOS - Disable Gatekeeper

$ sudo spctl --master-disable

macOS - Change default Crossover bottles directory

$ defaults write com.codeweavers.CrossOver BottleDir ~/CrossOver

macOS - Set computer name

$ sudo scutil --set ComputerName <COMPUTER_NAME>
$ sudo scutil --set HostName <COMPUTER_NAME>
$ sudo scutil --set LocalHostName <COMPUTER_NAME>
$ sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server \
	NetBIOSName -string "<COMPUTER_NAME>"

Convert RAW disk to VDI format

$ VBoxManage convertfromraw -format VDI <DISK_FILE>.img <DISK_FILE>.vdi

macOS - Remove all .DS_Store files

$ find . -name '.DS_Store' -type f -delete

macOS - Extract files from .pkg

$ pkgutil --expand-full <PKG_FILE> <DESTINATION>

Remove extended attributes from an application (quarantine)

$ xattr -cr <PATH_TO_APP>
or
$ xattr -d com.apple.quarantine <PATH_TO_APP>

Sign text with your GPG key

$ echo '<TEXT>' | gpg --clearsign --armor

Verify GPG signature

$ gpg --verify <FILE>

macOS - Manually codesign a macOS application

$ sudo codesign -f -s - <PATH_TO_APP>

Nginx basic HTTP config

server {
	# Listen IPv4
	listen 80;
	# Listen IPv6
	listen [::]:80;
	root <SOME_DIRECTORY>;
	index index.html index.htm;
	server_name <SERVER_NAME>;
	# Disable logging
	access_log off;
	error_log /dev/null;
	# Redirect to HTTPS
	return 301 https://<SERVER_HOST>$request_uri;
}

Nginx basic HTTPS config

server {
	listen 443 ssl;
	listen [::]:443;
	ssl on;
	ssl_certificate /etc/letsencrypt/live/<SERVER_HOST>/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/<SERVER_HOST>/privkey.pem;
	ssl_session_timeout 5m;
	ssl_session_cache shared:SSL:50m;
	root <SOME_DIRECTORY>;
	index index.html index.htm;
	server_name <SERVER_NAME>;
	access_log off;
	error_log /dev/null;
	server_tokens off;
	add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
	error_page 404 /404.html;
	add_header X-Content-Type-Options "nosniff" always;
	add_header X-Frame-Options "SAMEORIGIN" always;
	add_header X-Xss-Protection "1";
	
	location ~* \.(js|woff2|css|png|jpg|jpeg|gif|ico|json)$ {
		expires 30d;
		add_header Cache-Control "public, no-transform";
	}

	gzip on;
	gzip_disable "msie6";
	gzip_comp_level 6;
	gzip_min_length 1100;
	gzip_buffers 16 8k;
	gzip_proxied any;
	gzip_types
		text/plain
		text/css
		text/js
		text/xml
		text/javascript
		application/javascript
		application/json
		application/xml
		application/rss+xml
		image/svg+xml
		application/font-woff2
		application/vnd.ms-fontobject
		application/x-font
		application/x-font-opentype
		application/x-font-otf
		application/x-font-truetype
		application/x-font-ttf
		application/x-font-woff
		font/opentype
		font/otf
		font/ttf
		font/woff
		font/woff2
		image/x-icon;
}

Nginx basic TOR config

server {
	listen unix:/var/run/nginx-onion-80.sock;
	root <SOME_DIRECTORY>;
	index index.html index.htm;
	server_name <ONION_HOST>.onion;
	allow "unix:";
	deny all;
	# Disable logging
	access_log off;
	error_log /dev/null;
}

torrc config

# Try to run Tor more securely via a syscall sandbox.
Sandbox 1
# Disable the SOCKS port.
SocksPort 0
# We're using unix sockets instead of "127.0.0.1:xxxxx", see nginx conf above.
HiddenServiceDir /var/lib/tor/<DIR>/
HiddenServicePort 80 unix:/var/run/nginx-onion-80.sock

Generate SSH ED25519 key

$ ssh-keygen -o -a 100 -t ed25519 -C "<USER@HOST>"

Generate SSH RSA 4096 key

$ ssh-keygen -t rsa -b 4096 -C "<USER@HOST>"

Display a list of all SSH keys

$ for key in ~/.ssh/id_*; do ssh-keygen -l -f "${key}"; done | uniq

Get all HTTP headers

$ curl -LIN <address>

Download all documents from an address

$ wget -A pdf,jpg,png,gif,bmp,doc,docx -m -r -np --convert-links \
	--execute="robots = off" <ADDRESS>

Check if port is open or closed

$ (: </dev/tcp/127.0.0.1/<PORT>) &>/dev/null && echo "OPEN" || echo "CLOSED"

Convert private key to PEM format

$ openssl rsa -in ~/.ssh/PRIVATE_KEY_FILE -outform pem > PRIVATE_KEY_FILE.pem

Convert a PEM private key to RSA format

$ openssl rsa -in certificate.pem -out domain-rsa.key

Dump all MySQL databases

$ mysqldump --all-databases --all-routines -u root -p > ~/fulldump.sql

Query Google DNS server for all A records that point to a domain

$ dig A +additional +multiline +trace +dnssec <DOMAIN>. @8.8.4.4

Query whois database for all IPv6 assigned to ASN

$ whois -h whois.radb.net '6<ASN>'

Query whois database for all IPv4 assigned to ASN

$ whois -h whois.radb.net 'g<ASN>'
$ VBoxManage setextradata "<VM_NAME>" \
	VBoxInternal2/SharedFoldersEnableSymlinksCreate/<SHARE_NAME> 1

Mount Samba drive

$ smbmount //<REMOTE_IP>/c$ /mnt/target -o username=administrator

SCP copy a file from one remote host to another

$ scp <USERNAME@<REMOTE_IP>:/some/remote/directory/stuff.txt \
	<ANOTHER_USERNAME>@<ANOTHER_REMOTE_IP>:/some/remote/directory/

SCP copy local directory to remote directory

$ scp -r <LOCAL_DIR> <USERNAME>@<REMOTE_IP>:/some/remote/directory/<REMOTE_DIR>

SCP copy remote file to local host

$ scp <USERNAME>@<REMOTE_IP>:<REMOTE_FILE> /some/local/directory

SCP copy local file to remote host

$ scp <LOCAL_FILE> <USERNAME>@<REMOTE_IP>:/some/remote/directory