base64

# encode string
echo -n "asdf" | base64 -w 0

# encode file
base64 -w 0 /etc/prometheus/prometheus.yaml

# encode string when -w 0 is not available
echo -n "asdf" | base64 | tr -d \\n

# encode file when -w 0 is not available
base64 /etc/prometheus/prometheus.yaml | tr -d \\n
# decode string
echo -n "YXNkZg==" | base64 -d

# decode file
echo -n "YXNkZg==" | base64 -d > asdf.txt
# show contents of encoded string
echo -n "asdf" | base64 -w 0 | base64 -d | od -c

bash

set

# -e fail on non zero exit codes
# -u fail on unbound variables
# -x enable tracing
# -o pipefail fail on non zero exit codes inside a pipe
set -euxo pipefail

unset

COLOR="blue"
echo ${COLOR} # output blue
unset COLOR
echo ${COLOR} # empty output

colors

GRAY=$'\033[0;90m'
RED=$'\033[0;91m'
GREEN=$'\033[0;92m'
YELLOW=$'\033[0;93m'
BLUE=$'\033[0;94m'
MAGENTA=$'\033[0;95m'
CYAN=$'\033[0;96m'
WHITE=$'\033[0;97m'
RESET=$'\033[0m'

printf "%sERROR:%s script not running as root\n" "${RED}" "${RESET}"

chaining

true && echo ok || echo ko  # output is ok
false && echo ok || echo ko # output is ko

timestamp

echo ${EPOCHSECONDS}
echo ${EPOCHREALTIME}

mktemp

# create a temp directory
mktemp -d

# create a temp directory and store it as a variable
TEMP_DIR="$(mktemp -d)"

sed

# replace "deb cdrom" with "# deb cdrom"
sed -i 's/^deb cdrom/# deb cdrom/' /etc/apt/sources.list

# if a line doesn't start with a "#" and contains the word "cdrom" change it to start with a "# "
sed -i '/^#/! {/cdrom/ s/^/# /}' /etc/apt/sources.list

# replace "IPV6=yes" with "IPV6=no"
sed -i 's/IPV6=yes/IPV6=no/g' /etc/default/ufw

heredoc

# output is /bin/bash
cat << EOF > file.txt
$SHELL
EOF

# output is $SHELL
cat << 'EOF' > file.txt
$SHELL
EOF

# output is /bin/bash - ignore the leading tab characters
cat <<- EOF > file.txt
	$SHELL
EOF

# output is $SHELL - ignore the leading tab characters
cat <<- 'EOF' > file.txt
	$SHELL
EOF

# the path has spaces - fix by quoting the path
cat << 'EOF' > "$HOME/Library/Application Support/Code/User/settings.json"
{
    "diffEditor.ignoreTrimWhitespace": false,
    "explorer.compactFolders": false,
    "extensions.ignoreRecommendations": true,
}
EOF

# the path has spaces - fix by escaping the spaces
cat << 'EOF' > $HOME/Library/Application\ Support/Code/User/settings.json
{
    "diffEditor.ignoreTrimWhitespace": false,
    "explorer.compactFolders": false,
    "extensions.ignoreRecommendations": true,
}
EOF

cron

# view the crontab of the current user
crontab -l

# view the crontab of another user
crontab -u user2 -l

# edit the crontab of the current user
crontab -e

# edit the crontab of another user
crontab -u user2 -e

# delete the crontab of the current user
crontab -r

# delete the crontab of another user
crontab -u user2 -r

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * command to be executed
# view the system-wide crontab
cat /etc/crontab

# list the system-wide cron files
ls -l /etc/cron.d

# create a system-wide cron job via /etc/cron.d - remember to add a newline at the end of the file
cat << 'EOF' > /etc/cron.d/test
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
SHELL=/bin/sh
MAILTO=""
CRON_TZ=Europe/Paris
* * * * * root /usr/bin/echo "system-wide cron job ran at $(/usr/bin/date)"
EOF
chown root:root /etc/cron.d/test
chmod 644 /etc/cron.d/test

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
# view the system-wide scheduled scripts
ls -l /etc/cron.hourly
ls -l /etc/cron.daily
ls -l /etc/cron.weekly
ls -l /etc/cron.monthly

# create a system-wide scheduled script - remember to make it executable and not include dots (.) in the filename
cat << 'EOF' > /etc/cron.hourly/test
#!/bin/bash
set -euo pipefail
echo "system-wide scheduled script ran at $(/usr/bin/date)"
EOF
chown root:root /etc/cron.hourly/test
chmod +x /etc/cron.hourly/test
# *	any value
# ,	value list separator 1,15 * * * * minute 1 and 15
# -	range of values      * * * * 1-5  every minute monday to friday
# /	step values          */5 * * * *  every 5 minutes
# @yearly                0 0 1 1 *
# @annually              0 0 1 1 *
# @monthly               0 0 1 * *
# @weekly                0 0 * * 0
# @daily                 0 0 * * *
# @hourly                0 * * * *
# @reboot                when the cron daemon starts or restarts
# cron environment is minimal - $PATH $SHELL etc might not be what you expect

# setting the PATH at the top of the crontab file
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
* * * * * echo "$(date)"

# skip setting the PATH and use full paths in the cron command
* * * * * /usr/bin/echo "$(/usr/bin/date)"

# setting the SHELL at the top of the crontab file
SHELL=/bin/bash
* * * * * /usr/bin/echo "$(/usr/bin/date)"

# setting the SHELL inline in the cron command
* * * * * /bin/bash -c '/usr/bin/echo "$(/usr/bin/date)"'

# cron emails job output (stdout/stderr) unless MAILTO="" is set
MAILTO=""
* * * * * /usr/bin/echo "$(/usr/bin/date)"

# send cron emails to specific address
MAILTO=admin@example.com
* * * * * /usr/bin/echo "$(/usr/bin/date)"

# cron schedules jobs using the system timezone unless CRON_TZ= is set
CRON_TZ=Europe/Paris
* * * * * /usr/bin/echo "$(/usr/bin/date)"
# send stdout and stderr to file
* * * * * /usr/local/bin/test.sh >> /var/log/test.log 2>&1

# discard output completely
* * * * * /usr/local/bin/test.sh > /dev/null 2>&1

# log stdout and let cron email stderr (if MAILTO= is set)
* * * * * /usr/local/bin/test.sh >> /var/log/test.log

# separate stdout and stderr
* * * * * /usr/local/bin/test.sh >> /var/log/test.out 2>> /var/log/test.err
# this will run every Sunday AND every 1st of the month NOT every Sunday that is also the 1st of the month
0 0 1 * 0 echo "$(date)"
# percent-signs (%) in the command unless escaped with backslash (\) are changed into newline characters
* * * * * /usr/bin/echo "hello%world"  # output is "hello" and on a new line "world"
* * * * * /usr/bin/echo "hello\%world" # output is "hello%world"
# view all configured cron jobs
cat /etc/crontab
ls /etc/cron.d/
ls /etc/cron.daily/
ls /etc/cron.hourly/
ls /etc/cron.weekly/
ls /etc/cron.monthly/
ls /var/spool/cron/crontabs/
# troubleshooting
systemctl status cron
journalctl -u cron

curl

# resolve the domain to a specific address
curl https://example.com --resolve 'example.com:443:10.0.0.2'
# resolve the domain to a specific address and skip tls verification
curl -k https://example.com --resolve 'example.com:443:10.0.0.2'
curl --insecure https://example.com --resolve 'example.com:443:10.0.0.2'
# on HTTP return code != 200 exit with code 22
curl --fail

# on HTTP return code != 200 exit with code 22 and print body
curl --fail-with-body

# maximum time for the whole operation in seconds
curl -m 5
curl --max-time 5

# if an HTTP request fails retry up to this many times with an increasing delay between each retry 1s, 2s, 4s, 8s
curl --retry 4

# sleep this amount of time before each retry when a transfer has failed with a transient error
curl --retry-delay 5

# hides the progress meter and error messages
curl -s
curl --silent

# enables error messages when -s is used
curl -S
curl --show-error

dd

# dd if=image of=device
dd if=/var/lib/libvirt/images/debian-13.0.0-amd64-DVD-1.iso of=/dev/sdx status=progress
# create a file with predefined size
dd if=/dev/zero of=big.file bs=1MB count=1000
du -h big.file
# create a bootable usb
ISO="debian-13.0.0-amd64-DVD-1.iso" # https://cdimage.debian.org/debian-cd/current/amd64/iso-dvd/
DEVICE="sdb" # lsblk

curl -LO https://cdimage.debian.org/debian-cd/current/amd64/iso-dvd/${ISO}
curl -LO https://cdimage.debian.org/debian-cd/current/amd64/iso-dvd/SHA256SUMS
sha256sum --ignore-missing --check SHA256SUMS

fdisk -l /dev/${DEVICE}
wipefs -a -f /dev/${DEVICE}
fdisk /dev/${DEVICE} # g n ENTER ENTER ENTER y w
lsblk # umount /dev/${DEVICE}1
dd if=${ISO} of=/dev/${DEVICE} status=progress

du

# get the size of a file
du -h /var/log/dpkg.log

# get the size of a folder
du -sh /var/log

find

# find a file with the name resolv.conf
find / -name "resolv.conf"

# find a file with the name resolv.conf - case-insensitive
find / -iname "rEsOlV.cOnF"

# find all files with a .yaml extension
find / -name "*.yaml"

git

# initial setup
git config --global user.email user@users.noreply.github.com
git config --global init.defaultBranch master
git config --global core.autocrlf input
git config --list --show-origin

journalctl

# logs from current system boot
journalctl -b

# logs from previous system boot
journalctl -b -1

# list system boots
journalctl --list-boots
# logs from a specific service
journalctl -u nginx.service

# logs from multiple services
journalctl -u nginx.service -u mysql.service
# logs from a specific time range
journalctl --since "1 hour ago"
journalctl --since "2 days ago"
journalctl --since "2015-06-26 23:15:00" --until "2015-06-26 23:20:00"
# follow logs
journalctl -f
journalctl -u mysql.service -f
journalctl -n 50 --since "1 hour ago"
# logs from a specific user or service account
journalctl _UID=108

nfs

# server
apt install -y nfs-kernel-server
systemctl start nfs-server.service
systemctl enable nfs-server.service
mkdir /var/nfs
echo '/var/nfs 10.0.0.0/24(rw,sync,no_subtree_check,all_squash)' >> /etc/exports
chown -R nobody:nogroup /var/nfs
systemctl restart nfs-server.service

# server firewall
ufw allow from 10.0.0.0/24 to 10.0.0.3 port 2049 proto tcp
ufw reload
# client
apt install -y nfs-common
mkdir /nfs
echo '10.0.0.3:/var/nfs /nfs nfs defaults 0 0' >> /etc/fstab

# client fix mount on boot
cat << 'EOF' > /etc/network/if-up.d/fstab
#!/bin/bash
mount -a
EOF
chmod +x /etc/network/if-up.d/fstab
# troubleshooting
nfsstat
nfsstat --mounts
nfsstat --client
nfsstat --server
nmap -p 2049 10.0.0.3
nmap -p 111 --script=nfs-showmount 10.0.0.3

nmap

# scan all tcp ports
nmap -p- -sS --reason example.com

# retrieve the tls certificate from a server
nmap -p 443 --script ssl-cert example.com

openssl

# encrypt
openssl enc -aes-256-cbc -pbkdf2 -salt -in backup.zip -out backup.enc

# decrypt
openssl enc -aes-256-cbc -pbkdf2 -d -in backup.enc -out backup.zip
# display the details of a tls certificate
CERTIFICATE="/etc/kubernetes/pki/apiserver.crt"
openssl x509 -in ${CERTIFICATE} -text -noout
# decode and display the details of a tls certificate
echo -n "LS0tL[...]tLS0K" | base64 -d | openssl x509 -text -noout
# retrieve and display the details of a tls certificate
URL="google.com"
echo | openssl s_client -showcerts -servername ${URL} -connect ${URL}:443 2>/dev/null | openssl x509 -inform pem -noout -text
echo | openssl s_client -showcerts -servername ${URL} -connect ${URL}:443 2>/dev/null | openssl x509 -inform pem -noout -enddate

scp

# copy from local to remote
scp -r /path/from/local user@server:/path/to/remote

# copy from remote to local
scp -r user@server:/path/from/remote /path/to/local

# copy from remote to local on the current directory
scp -r user@server:/path/from/remote .

ssh

# generate an rsa key
ssh-keygen -t rsa -b 4096
# create a config file
cat << 'EOF' > ~/.ssh/config
Host server01
  HostName 10.20.30.41
  User user
Host server02
  HostName 10.20.30.42
  User user
Host server03
  HostName 10.20.30.43
  User user
  ProxyJump server02
EOF
chmod 600 ~/.ssh/config
# use specific ssh config based on a condition - man ssh_config
cat << 'EOF' > $HOME/.ssh/config
Match originalhost server localnetwork 10.0.0.0/24
  HostName 10.0.0.3
  User user
Host server
  HostName 172.16.32.3
  User user
EOF
chmod 600 $HOME/.ssh/config
# fetch your public key from github
curl https://github.com/korliaftis.keys
# fetch your public key from github and add it to the authorized_keys file
curl https://github.com/korliaftis.keys >> /home/user/.ssh/authorized_keys
chmod 600 /home/user/.ssh/authorized_keys
# -f run in the background
# -p specify ssh port if not the default
# -N don't execute any remote command
# -L local port forwarding
# -R remote port forwarding
# -D dynamic port forwarding

# local port forwarding
ssh -L [LOCAL_IP:]LOCAL_PORT:DESTINATION:DESTINATION_PORT [USER@]SSH_SERVER

# remote port forwarding
ssh -R [REMOTE:]REMOTE_PORT:DESTINATION:DESTINATION_PORT [USER@]SSH_SERVER

# dynamic port forwarding
ssh -D [LOCAL_IP:]LOCAL_PORT [USER@]SSH_SERVER

stat

# get the creation date of a file or folder
stat /var/log
stat /var/log/dpkg.log

swap

# disable swap for the current session
swapoff -a

# disable swap partition from getting auto mounted at boot
sed '/^#/! {/swap/ s/^/# /}' -i /etc/fstab

tar

# extract archive
tar -xvzf archive.tar.gz

# list files in archive
tar -tzvf archive.tar.gz

# create archive
tar -czvf archive.tar.gz /path/to/directory-or-file

tmux

# start | list | attach | detach | kill
tmux
tmux ls
tmux attach
CTRL B : detach-client
CTRL B : kill-session
# zoom pane
CTRL B z
# mouse scrolling
CTRL B [
# show pane numbers
CTRL B q
# move pane right
CTRL B }
# move pane left
CTRL B {
# split pane right
CTRL B :split-pane -h
CTRL B %
# split pane down
CTRL B :split-pane -v
CTRL B "
# change pane layout
CTRL B SPACE
CTRL B : select-layout tiled
CTRL B : select-layout even-horizontal
CTRL B : select-layout even-vertical
# change selected pane
CTRL B o
CTRL B ARROW KEYS
# rotate all panes
CTRL B : CTRL o
CTRL B : rotate-window
# resize pane
CTRL B : resize-pane -UDLR 20
# close pane
CTRL B x

ufw

apt install -y ufw
sed -i 's/IPV6=yes/IPV6=no/g' /etc/default/ufw
ufw default deny
ufw logging low
ufw allow 22/tcp
echo 'y' | ufw enable
ufw status verbose
# allow from a specific network to any ip but at a specific port and protocol
ufw allow from 10.0.0.0/24 to any port 445 proto tcp

# allow from a specific network to a specific ip, port and protocol
ufw allow from 10.0.0.0/24 to 10.0.0.2 port 445 proto tcp

umask

# view the current mask value
umask

# view the current mask value in symbolic notation
umask -S

# change the umask value only for the current session
umask 077

wakeonlan

server

INTERFACE="enp2s0"
apt install -y ethtool
ethtool ${INTERFACE} # "Wake-on: g" means enabled
cat << EOF > /etc/network/interfaces.d/${INTERFACE}
auto ${INTERFACE}
iface ${INTERFACE} inet dhcp
  ethernet-wol g
EOF
systemctl restart networking.service
ethtool ${INTERFACE}

client

apt install -y wakeonlan
echo "alias wol='wakeonlan 58:8a:5a:0d:7c:8a'" >> /home/user/.bash_aliases

wireguard

server

apt install -y wireguard
cd /etc/wireguard
wg genkey | tee privatekey | wg pubkey > publickey
touch wg0.conf
chmod -R 600 /etc/wireguard/*

WG_SUBNET="172.16.32.0/24"
SERVER_PORT="65001"
SERVER_WG_IP="172.16.32.1"
SERVER_PRIVATE_KEY=$(cat /etc/wireguard/privatekey)

SERVER_INTERFACE=""  # ens3
SERVER_PUBLIC_IP=""  # 73.173.101.129
CLIENT_WG_IP=""      # 172.16.32.2
CLIENT_PUBLIC_KEY="" # YRrQ69zJk8jpez9X9DqFzq0i+4KGKCds3zdC5kJv4HM=

cat << EOF > /etc/wireguard/wg0.conf
[Interface]
Address = ${SERVER_WG_IP}
ListenPort = ${SERVER_PORT}
PrivateKey = ${SERVER_PRIVATE_KEY}
PostUp = echo 1 > /proc/sys/net/ipv4/ip_forward; iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ${SERVER_INTERFACE} -j MASQUERADE
PostDown = echo 0 > /proc/sys/net/ipv4/ip_forward; iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ${SERVER_INTERFACE} -j MASQUERADE

[Peer]
PublicKey = ${CLIENT_PUBLIC_KEY}
AllowedIPs = ${CLIENT_WG_IP}
PersistentKeepalive = 10
EOF

ufw allow from any to ${SERVER_PUBLIC_IP} port ${SERVER_PORT} proto udp
ufw allow from ${WG_SUBNET} to ${SERVER_WG_IP} port 22 proto tcp
ufw reload
ufw status verbose

ufw status numbered
ufw delete 1
ufw reload
ufw status verbose

systemctl enable wg-quick@wg0.service
history -c && history -w

client

apt install -y wireguard
cd /etc/wireguard
wg genkey | tee privatekey | wg pubkey > publickey
touch wg0.conf
chmod -R 600 /etc/wireguard/*

WG_SUBNET="172.16.32.0/24"
SERVER_PORT="65001"
CLIENT_PRIVATE_KEY=$(cat /etc/wireguard/privatekey)

CLIENT_WG_IP=""      # 172.16.32.2
SERVER_PUBLIC_IP=""  # 73.173.101.129
SERVER_PUBLIC_KEY="" # YRrQ69zJk8jpez9X9DqFzq0i+4KGKCds3zdC5kJv4HM=

cat << EOF > /etc/wireguard/wg0.conf
[Interface]
Address = ${CLIENT_WG_IP}
PrivateKey = ${CLIENT_PRIVATE_KEY}

[Peer]
PublicKey = ${SERVER_PUBLIC_KEY}
AllowedIPs = ${WG_SUBNET}
PersistentKeepalive = 10
Endpoint = ${SERVER_PUBLIC_IP}:${SERVER_PORT}
EOF

ufw allow from ${WG_SUBNET} to ${CLIENT_WG_IP} port 22 proto tcp
ufw reload
ufw status verbose

systemctl enable wg-quick@wg0.service
history -c && history -w

troubleshooting

wg show
wg showconf wg0
journalctl -u wg-quick@wg0.service
tcpdump -i any 'udp port 65001'
tcpdump -n -i any 'udp port 65001'
ufw status numbered
systemctl restart wg-quick@wg0.service

ykman

# install ykman
apt install yubikey-manager

# set fido2 pin
ykman fido access change-pin

# add new ssh key to the yubikey that requires touch to use
ssh-keygen -t ed25519-sk -O resident -C ""

# add new ssh key to the yubikey that requires touch and pin to use
ssh-keygen -t ed25519-sk -O resident -O verify-required -C ""

# list existing ssh keys on the yubikey
ykman fido credentials list

# delete existing ssh keys on the yubikey
ykman fido credentials delete <credential-id>

# add resident key temporarily to the ssh-agent
ssh-add -K

# list or remove all keys from the ssh-agent
ssh-add -l
ssh-add -D

# start the ssh-agent if not already running
[ -z "${SSH_AUTH_SOCK}" ] && eval "$(ssh-agent -s)"

# download key handles locally
install -d -m 700 ${HOME}/.ssh && cd ${HOME}/.ssh
ssh-keygen -K
mv ${HOME}/.ssh/id_ed25519_sk_rk ${HOME}/.ssh/id_ed25519_sk
mv ${HOME}/.ssh/id_ed25519_sk_rk.pub ${HOME}/.ssh/id_ed25519_sk.pub