Security Basics cheat sheet
151 commands from every lesson of Security Basics — SSH, TLS and Certificates, on one page.
The CIA triad
Confidentiality | Only the right people can read it (encryption, access control) |
Integrity | Nobody can change it unnoticed (hashes, signatures, permissions) |
Availability | It works when needed (backups, redundancy, DDoS protection) |
Principles
Defence in depth | Several independent layers, so one failure is not a breach |
Least privilege | Every user and program gets only the access it needs |
Small attack surface | Fewer open ports, services, packages and accounts |
Secure by default | The default setting is the safe one |
Assume breach | Plan detection and recovery, not only prevention |
Look at your own exposure
sudo ss -tulpn | Which programs are listening on which ports |
sudo journalctl -u ssh --since today | grep -c 'Failed password' | How many SSH password guesses today |
last -n 20 | Recent logins |
Risk words
Asset | Something of value: data, a server, a reputation |
Threat | Who or what could cause harm: a criminal group, a careless admin, a flood |
Vulnerability | A weakness that could be used: a bug, a weak password, an open port |
Exploit | A method or code that uses a vulnerability |
Risk | Likelihood × impact of a threat using a vulnerability against an asset |
Zero-day | A vulnerability attackers use before a fix exists |
CVE | A public ID for a known vulnerability, e.g. CVE-2024-6387 |
CVSS | A 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 / auditing | Recording who did what, and when |
Encoding, encryption, hashing
echo -n 'hello' | base64 | Encoding: reversible by anyone, no secret involved |
openssl enc -aes-256-cbc -pbkdf2 -in f -out f.enc | Encryption: reversible only with the key |
echo -n 'hello' | sha256sum | Hashing: one-way fingerprint, cannot be reversed |
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 signature | Hash of the data, signed with a private key; anyone with the public key can verify |
Try them
openssl genpkey -algorithm ed25519 -out priv.pem | Make a private key |
openssl pkey -in priv.pem -pubout -out pub.pem | Derive its public key |
openssl pkeyutl -sign -inkey priv.pem -rawin -in msg.txt -out msg.sig | Sign a file |
openssl pkeyutl -verify -pubin -inkey pub.pem -rawin -in msg.txt -sigfile msg.sig | Verify the signature |
sha256sum file.iso | Check a download against its published hash |
Host keys
ls /etc/ssh/ssh_host_*_key.pub | The server's public host keys |
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub | Fingerprint of the server's host key (run on the server) |
ssh-keygen -F server.example.com | Is this host already in my known_hosts? |
ssh-keygen -R server.example.com | Remove a host's old key from known_hosts (after verifying the change) |
ssh-keyscan -t ed25519 server.example.com | Fetch a host key (verify its fingerprint separately) |
Seeing what happens
ssh -v user@server | Verbose: key exchange, host key, which auth methods are tried |
ssh -o PreferredAuthentications=publickey user@server | Try key authentication only |
ssh -Q kex | Key exchange algorithms your client supports |
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_ed25519 | Add or change a key's passphrase |
ssh-keygen -lf ~/.ssh/id_ed25519.pub | Show a key's fingerprint |
ssh-copy-id -i ~/.ssh/id_ed25519.pub asha@server | Append your public key to the server's authorized_keys |
ssh-keygen -t ed25519-sk | Key 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_ed25519 | Load a key; enter the passphrase once |
ssh-add -t 8h ~/.ssh/id_ed25519 | Load it for 8 hours only |
ssh-add -l | List loaded keys |
Permissions (server side)
chmod 700 ~/.ssh | Directory: owner only |
chmod 600 ~/.ssh/authorized_keys | File: owner read/write only |
sudo journalctl -u ssh -n 50 | See why sshd refused a key (e.g. bad ownership or modes) |
Test and apply safely
sudo sshd -t | Check 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 ssh | Apply; existing sessions stay connected |
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@host | Confirm password login is refused |
fail2ban and firewall
sudo apt install fail2ban | Ban IPs that keep failing to log in |
sudo fail2ban-client status sshd | Currently banned IPs |
sudo fail2ban-client set sshd unbanip 198.51.100.7 | Unban an address |
sudo ufw allow from 203.0.113.0/24 to any port 22 proto tcp | Allow SSH only from your network |
sudo ufw limit 22/tcp | Rate-limit new SSH connections |
SSH certificates
ssh-keygen -t ed25519 -f user_ca | Create a user certificate authority key |
ssh-keygen -s user_ca -I asha -n asha -V +8h id_ed25519.pub | Sign a user key: valid for user asha, 8 hours |
TrustedUserCAKeys /etc/ssh/user_ca.pub | sshd_config: trust keys signed by this CA |
Look at a site's TLS
curl -vI https://example.com | Handshake summary, certificate subject, issuer and dates, then headers |
openssl s_client -connect example.com:443 -servername example.com </dev/null | Full handshake, chain and negotiated version |
curl -sI https://example.com | grep -i strict-transport | Is HSTS set? |
curl -sI http://example.com | grep -i location | Does HTTP redirect to HTTPS? |
Words
SSL | Old name; all SSL versions are broken and disabled. Today it's TLS |
TLS 1.2 / 1.3 | Current versions; 1.3 is faster and simpler |
SNI | The hostname the client asks for, so one IP can serve many sites |
HSTS | Header telling browsers: only ever use HTTPS for this site |
Read a certificate
openssl x509 -in cert.pem -noout -text | Everything on the certificate |
openssl x509 -in cert.pem -noout -subject -issuer -dates | Who, issued by whom, valid from/to |
openssl x509 -in cert.pem -noout -ext subjectAltName | The names it is valid for |
openssl x509 -in cert.pem -noout -fingerprint -sha256 | SHA-256 fingerprint |
openssl s_client -connect host:443 -servername host </dev/null 2>/dev/null | openssl x509 -noout -subject -ext subjectAltName -dates | Read 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 -text | Check a CSR before sending it |
openssl x509 -in cert.der -inform der -out cert.pem | DER → PEM |
openssl pkcs12 -export -inkey site.key -in cert.pem -certfile chain.pem -out site.pfx | Key + certificate + chain → PKCS#12 (.pfx) |
openssl pkcs12 -in site.pfx -nodes | Look inside a .pfx |
Chains
openssl s_client -connect host:443 -servername host -showcerts </dev/null | Print every certificate the server sends |
openssl verify -CAfile root.pem -untrusted intermediate.pem leaf.pem | Verify a leaf through an intermediate to a root |
cat leaf.pem intermediate.pem > fullchain.pem | Build the chain file a server should send (leaf first) |
Trust stores
/etc/ssl/certs/ca-certificates.crt | Debian/Ubuntu system bundle |
sudo cp myca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates | Trust a private CA on Debian/Ubuntu |
sudo cp myca.crt /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust | Trust a private CA on RHEL/Fedora |
keytool -importcert -alias myca -file myca.crt -cacerts | Trust a private CA in Java's store |
Public CA controls
dig CAA example.com | Which CAs may issue for this domain |
crt.sh | Search Certificate Transparency logs for certificates issued for your domains |
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.ext | CA signs the server certificate |
openssl verify -CAfile ca.crt web.crt | Check the chain |
Trust it
curl --cacert ca.crt https://web.lab.test | Trust the CA for one command |
sudo cp ca.crt /usr/local/share/ca-certificates/lab-root.crt && sudo update-ca-certificates | Trust it system-wide (Debian/Ubuntu) |
certbot (nginx)
sudo apt install certbot python3-certbot-nginx | Install certbot with the nginx plugin |
sudo certbot --nginx -d example.com -d www.example.com | Get a certificate and configure nginx |
sudo certbot certonly --webroot -w /var/www/html -d example.com | Get a certificate only, using a web root |
sudo certbot renew --dry-run | Test renewal against the staging CA |
sudo certbot certificates | List certificates and their expiry |
systemctl list-timers | grep certbot | Confirm the automatic renewal timer exists |
Files
/etc/letsencrypt/live/<name>/fullchain.pem | Certificate + intermediate (use this for ssl_certificate) |
/etc/letsencrypt/live/<name>/privkey.pem | Private key |
/etc/letsencrypt/renewal-hooks/deploy/ | Scripts run after a successful renewal (e.g. reload a service) |
Check expiry
openssl x509 -in cert.pem -noout -enddate | Expiry date of a certificate file |
openssl x509 -in cert.pem -noout -checkend 2592000 | Exit 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 -enddate | Expiry of the certificate a live server sends |
curl -vI https://host 2>&1 | grep 'expire date' | Quick check with curl |
sudo certbot certificates | Expiry of certbot-managed certificates |
Monitor
probe_ssl_earliest_cert_expiry - time() < 21*86400 | Prometheus blackbox exporter alert: under 21 days left |
crt.sh | Find certificates issued for your domains (inventory) |
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/null | Exactly 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 subjectAltName | Names, issuer and dates of the served certificate |
timedatectl | Is the clock right and synchronised? |
openssl s_client -connect host:443 -tls1_2 </dev/null | Force a TLS version to test support |
Passwords on Linux
sudo grep '^asha:' /etc/shadow | cut -d: -f2 | cut -c1-4 | Hash method prefix: $y$ = yescrypt, $6$ = SHA-512 crypt |
sudo passwd -l olduser | Lock an account's password |
sudo chage -l asha | Password ageing for a user |
Secrets in code
gitleaks detect --source . | Scan a repository (including history) for secrets |
gitleaks protect --staged | Scan staged changes before committing (pre-commit hook) |
git log -p -S 'AKIA' | Find commits that added or removed a string |
echo '.env' >> .gitignore | Keep local secret files out of Git |
What is listening
sudo ss -tulpn | TCP/UDP listening sockets with the owning process |
sudo ss -tlpn 'sport = :5432' | Who listens on one port |
nmap -Pn your.server.ip | What is reachable from outside (run from another machine you own) |
ufw
sudo ufw default deny incoming | Block all incoming by default |
sudo ufw default allow outgoing | Allow outgoing |
sudo ufw allow OpenSSH | Allow SSH BEFORE enabling |
sudo ufw allow 80,443/tcp | Allow web traffic |
sudo ufw enable | Turn it on |
sudo ufw status numbered | List rules |
sudo ufw delete 3 | Delete rule number 3 |
Patching (Ubuntu/Debian)
sudo apt update && apt list --upgradable | What can be upgraded |
sudo apt upgrade | Install upgrades |
sudo apt install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgrades | Automatic security updates |
cat /var/run/reboot-required | Does a new kernel or library need a reboot? |
sudo needrestart | Which services still run old libraries |
Verify the result
sudo sshd -T | grep -Ei '^(permitrootlogin|passwordauthentication)' | Both should be 'no' |
sudo ufw status verbose | Default deny incoming; only 22 (restricted), 80, 443 allowed |
sudo ss -tulpn | Nothing unexpected on 0.0.0.0 |
systemctl status unattended-upgrades fail2ban | Both active |
sudo certbot renew --dry-run | Renewal works |
curl -sI https://example.com | grep -i strict-transport | HSTS present |
curl -sI http://example.com | head -1 | 301 redirect to HTTPS |