Cheat Sheets / Security & Identity

Security Basics cheat sheet

151 commands from every lesson of Security Basics — SSH, TLS and Certificates, on one page.

01 · Why security matters

The CIA triad

ConfidentialityOnly the right people can read it (encryption, access control)
IntegrityNobody can change it unnoticed (hashes, signatures, permissions)
AvailabilityIt works when needed (backups, redundancy, DDoS protection)

Principles

Defence in depthSeveral independent layers, so one failure is not a breach
Least privilegeEvery user and program gets only the access it needs
Small attack surfaceFewer open ports, services, packages and accounts
Secure by defaultThe default setting is the safe one
Assume breachPlan detection and recovery, not only prevention

Look at your own exposure

sudo ss -tulpnWhich programs are listening on which ports
sudo journalctl -u ssh --since today | grep -c 'Failed password'How many SSH password guesses today
last -n 20Recent logins

02 · The vocabulary of security

Risk words

AssetSomething of value: data, a server, a reputation
ThreatWho or what could cause harm: a criminal group, a careless admin, a flood
VulnerabilityA weakness that could be used: a bug, a weak password, an open port
ExploitA method or code that uses a vulnerability
RiskLikelihood × impact of a threat using a vulnerability against an asset
Zero-dayA vulnerability attackers use before a fix exists
CVEA public ID for a known vulnerability, e.g. CVE-2024-6387
CVSSA 0–10 severity score for a vulnerability

The three As

Authentication (authN)Proving who you are: password, key, certificate, MFA
Authorisation (authZ)What you are allowed to do once known
Accounting / auditingRecording who did what, and when

Encoding, encryption, hashing

echo -n 'hello' | base64Encoding: reversible by anyone, no secret involved
openssl enc -aes-256-cbc -pbkdf2 -in f -out f.encEncryption: reversible only with the key
echo -n 'hello' | sha256sumHashing: one-way fingerprint, cannot be reversed

03 · Cryptography without the maths

Building blocks

Symmetric encryption (AES, ChaCha20)One shared key locks and unlocks; very fast; used for the actual data
Asymmetric key pair (RSA, ECDSA, Ed25519)Public key can be shared; private key never leaves its owner
Key exchange (Diffie-Hellman, ECDHE)Two sides agree a shared secret over a public network
Hash (SHA-256)Fixed-size fingerprint of any data; any change gives a different hash
Digital signatureHash of the data, signed with a private key; anyone with the public key can verify

Try them

openssl genpkey -algorithm ed25519 -out priv.pemMake a private key
openssl pkey -in priv.pem -pubout -out pub.pemDerive its public key
openssl pkeyutl -sign -inkey priv.pem -rawin -in msg.txt -out msg.sigSign a file
openssl pkeyutl -verify -pubin -inkey pub.pem -rawin -in msg.txt -sigfile msg.sigVerify the signature
sha256sum file.isoCheck a download against its published hash

04 · How SSH works

Host keys

ls /etc/ssh/ssh_host_*_key.pubThe server's public host keys
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubFingerprint of the server's host key (run on the server)
ssh-keygen -F server.example.comIs this host already in my known_hosts?
ssh-keygen -R server.example.comRemove a host's old key from known_hosts (after verifying the change)
ssh-keyscan -t ed25519 server.example.comFetch a host key (verify its fingerprint separately)

Seeing what happens

ssh -v user@serverVerbose: key exchange, host key, which auth methods are tried
ssh -o PreferredAuthentications=publickey user@serverTry key authentication only
ssh -Q kexKey exchange algorithms your client supports

05 · SSH keys and client configuration

Keys

ssh-keygen -t ed25519 -C 'asha@laptop'New Ed25519 key pair with a comment; set a passphrase when asked
ssh-keygen -p -f ~/.ssh/id_ed25519Add or change a key's passphrase
ssh-keygen -lf ~/.ssh/id_ed25519.pubShow a key's fingerprint
ssh-copy-id -i ~/.ssh/id_ed25519.pub asha@serverAppend your public key to the server's authorized_keys
ssh-keygen -t ed25519-skKey backed by a FIDO2 hardware token (needs the token to log in)

Agent

eval "$(ssh-agent -s)"Start an agent in this shell (desktops usually start one for you)
ssh-add ~/.ssh/id_ed25519Load a key; enter the passphrase once
ssh-add -t 8h ~/.ssh/id_ed25519Load it for 8 hours only
ssh-add -lList loaded keys

Permissions (server side)

chmod 700 ~/.sshDirectory: owner only
chmod 600 ~/.ssh/authorized_keysFile: owner read/write only
sudo journalctl -u ssh -n 50See why sshd refused a key (e.g. bad ownership or modes)

06 · Hardening an SSH server

Test and apply safely

sudo sshd -tCheck the configuration for errors; prints nothing if OK
sudo sshd -T | grep -Ei 'passwordauth|permitroot|kbdinteractive'Show the settings sshd will actually use
sudo systemctl reload sshApply; existing sessions stay connected
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@hostConfirm password login is refused

fail2ban and firewall

sudo apt install fail2banBan IPs that keep failing to log in
sudo fail2ban-client status sshdCurrently banned IPs
sudo fail2ban-client set sshd unbanip 198.51.100.7Unban an address
sudo ufw allow from 203.0.113.0/24 to any port 22 proto tcpAllow SSH only from your network
sudo ufw limit 22/tcpRate-limit new SSH connections

SSH certificates

ssh-keygen -t ed25519 -f user_caCreate a user certificate authority key
ssh-keygen -s user_ca -I asha -n asha -V +8h id_ed25519.pubSign a user key: valid for user asha, 8 hours
TrustedUserCAKeys /etc/ssh/user_ca.pubsshd_config: trust keys signed by this CA

07 · From HTTP to HTTPS

Look at a site's TLS

curl -vI https://example.comHandshake summary, certificate subject, issuer and dates, then headers
openssl s_client -connect example.com:443 -servername example.com </dev/nullFull handshake, chain and negotiated version
curl -sI https://example.com | grep -i strict-transportIs HSTS set?
curl -sI http://example.com | grep -i locationDoes HTTP redirect to HTTPS?

Words

SSLOld name; all SSL versions are broken and disabled. Today it's TLS
TLS 1.2 / 1.3Current versions; 1.3 is faster and simpler
SNIThe hostname the client asks for, so one IP can serve many sites
HSTSHeader telling browsers: only ever use HTTPS for this site

08 · Anatomy of a certificate

Read a certificate

openssl x509 -in cert.pem -noout -textEverything on the certificate
openssl x509 -in cert.pem -noout -subject -issuer -datesWho, issued by whom, valid from/to
openssl x509 -in cert.pem -noout -ext subjectAltNameThe names it is valid for
openssl x509 -in cert.pem -noout -fingerprint -sha256SHA-256 fingerprint
openssl s_client -connect host:443 -servername host </dev/null 2>/dev/null | openssl x509 -noout -subject -ext subjectAltName -datesRead the certificate a live server sends

CSRs and formats

openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout site.key -out site.csr -subj '/CN=site.example.com' -addext 'subjectAltName=DNS:site.example.com'New key and CSR with a SAN
openssl req -in site.csr -noout -textCheck a CSR before sending it
openssl x509 -in cert.der -inform der -out cert.pemDER → PEM
openssl pkcs12 -export -inkey site.key -in cert.pem -certfile chain.pem -out site.pfxKey + certificate + chain → PKCS#12 (.pfx)
openssl pkcs12 -in site.pfx -nodesLook inside a .pfx

09 · Certificate authorities and the chain of trust

Chains

openssl s_client -connect host:443 -servername host -showcerts </dev/nullPrint every certificate the server sends
openssl verify -CAfile root.pem -untrusted intermediate.pem leaf.pemVerify a leaf through an intermediate to a root
cat leaf.pem intermediate.pem > fullchain.pemBuild the chain file a server should send (leaf first)

Trust stores

/etc/ssl/certs/ca-certificates.crtDebian/Ubuntu system bundle
sudo cp myca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificatesTrust a private CA on Debian/Ubuntu
sudo cp myca.crt /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trustTrust a private CA on RHEL/Fedora
keytool -importcert -alias myca -file myca.crt -cacertsTrust a private CA in Java's store

Public CA controls

dig CAA example.comWhich CAs may issue for this domain
crt.shSearch Certificate Transparency logs for certificates issued for your domains

10 · Self-signed certificates and your own CA

Self-signed in one command

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout self.key -out self.crt -days 30 -subj '/CN=app.lab.test' -addext 'subjectAltName=DNS:app.lab.test'Key + self-signed certificate valid 30 days

Private CA

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout ca.key -out ca.crt -days 3650 -subj '/CN=Lab Root CA' -addext 'basicConstraints=critical,CA:TRUE' -addext 'keyUsage=critical,keyCertSign,cRLSign'Create the CA
openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout web.key -out web.csr -subj '/CN=web.lab.test'Server key + CSR
openssl x509 -req -in web.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out web.crt -days 90 -extfile web.extCA signs the server certificate
openssl verify -CAfile ca.crt web.crtCheck the chain

Trust it

curl --cacert ca.crt https://web.lab.testTrust the CA for one command
sudo cp ca.crt /usr/local/share/ca-certificates/lab-root.crt && sudo update-ca-certificatesTrust it system-wide (Debian/Ubuntu)

11 · Free, automated certificates with ACME

certbot (nginx)

sudo apt install certbot python3-certbot-nginxInstall certbot with the nginx plugin
sudo certbot --nginx -d example.com -d www.example.comGet a certificate and configure nginx
sudo certbot certonly --webroot -w /var/www/html -d example.comGet a certificate only, using a web root
sudo certbot renew --dry-runTest renewal against the staging CA
sudo certbot certificatesList certificates and their expiry
systemctl list-timers | grep certbotConfirm the automatic renewal timer exists

Files

/etc/letsencrypt/live/<name>/fullchain.pemCertificate + intermediate (use this for ssl_certificate)
/etc/letsencrypt/live/<name>/privkey.pemPrivate key
/etc/letsencrypt/renewal-hooks/deploy/Scripts run after a successful renewal (e.g. reload a service)

12 · Certificate expiry and renewal

Check expiry

openssl x509 -in cert.pem -noout -enddateExpiry date of a certificate file
openssl x509 -in cert.pem -noout -checkend 2592000Exit code 1 if it expires within 30 days (2592000 s)
echo | openssl s_client -connect host:443 -servername host 2>/dev/null | openssl x509 -noout -enddateExpiry of the certificate a live server sends
curl -vI https://host 2>&1 | grep 'expire date'Quick check with curl
sudo certbot certificatesExpiry of certbot-managed certificates

Monitor

probe_ssl_earliest_cert_expiry - time() < 21*86400Prometheus blackbox exporter alert: under 21 days left
crt.shFind certificates issued for your domains (inventory)

13 · Fixing common TLS errors

Diagnose

curl -v https://host 2>&1 | grep -E 'SSL|subject|issuer|expire|error'First look: version, names, dates, error
openssl s_client -connect host:443 -servername host -showcerts </dev/nullExactly what the server sends; 'Verify return code' at the end
openssl s_client -connect host:443 -servername host </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates -ext subjectAltNameNames, issuer and dates of the served certificate
timedatectlIs the clock right and synchronised?
openssl s_client -connect host:443 -tls1_2 </dev/nullForce a TLS version to test support

14 · Passwords, MFA and secrets

Passwords on Linux

sudo grep '^asha:' /etc/shadow | cut -d: -f2 | cut -c1-4Hash method prefix: $y$ = yescrypt, $6$ = SHA-512 crypt
sudo passwd -l olduserLock an account's password
sudo chage -l ashaPassword ageing for a user

Secrets in code

gitleaks detect --source .Scan a repository (including history) for secrets
gitleaks protect --stagedScan staged changes before committing (pre-commit hook)
git log -p -S 'AKIA'Find commits that added or removed a string
echo '.env' >> .gitignoreKeep local secret files out of Git

15 · Firewalls, open ports and patching

What is listening

sudo ss -tulpnTCP/UDP listening sockets with the owning process
sudo ss -tlpn 'sport = :5432'Who listens on one port
nmap -Pn your.server.ipWhat is reachable from outside (run from another machine you own)

ufw

sudo ufw default deny incomingBlock all incoming by default
sudo ufw default allow outgoingAllow outgoing
sudo ufw allow OpenSSHAllow SSH BEFORE enabling
sudo ufw allow 80,443/tcpAllow web traffic
sudo ufw enableTurn it on
sudo ufw status numberedList rules
sudo ufw delete 3Delete rule number 3

Patching (Ubuntu/Debian)

sudo apt update && apt list --upgradableWhat can be upgraded
sudo apt upgradeInstall upgrades
sudo apt install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgradesAutomatic security updates
cat /var/run/reboot-requiredDoes a new kernel or library need a reboot?
sudo needrestartWhich services still run old libraries

16 · Capstone: harden a new server

Verify the result

sudo sshd -T | grep -Ei '^(permitrootlogin|passwordauthentication)'Both should be 'no'
sudo ufw status verboseDefault deny incoming; only 22 (restricted), 80, 443 allowed
sudo ss -tulpnNothing unexpected on 0.0.0.0
systemctl status unattended-upgrades fail2banBoth active
sudo certbot renew --dry-runRenewal works
curl -sI https://example.com | grep -i strict-transportHSTS present
curl -sI http://example.com | head -1301 redirect to HTTPS