Menu

Security

Step 3 of 3 LPIC-1 110.3weight 4

Securing data with encryption

“Use OpenSSH keys, agents and tunnels, and encrypt, sign and verify files with GnuPG.”

View .md

Anything you send over a network can be read by the machines in between, and any file on a disk can be read by whoever gets the disk. Encryption turns that data into noise for everyone except the people with the right key. On Linux, two tools do most of this work: OpenSSH for secure logins, file copies and tunnels, and GnuPG for encrypting and signing files and email.

Both rely on public key cryptography. You create a key pair: a private key you keep secret, and a public key you can hand to anyone. What one key locks, only the other can unlock. That one idea explains host keys, SSH logins, GPG encryption and signatures.

OpenSSH client basics#

ssh opens an encrypted shell on another machine, by default on TCP port 22:

bash
ssh alice@192.168.1.10              # log in as alice
ssh -p 2222 alice@server.example    # another port
ssh -l alice server.example         # -l is another way to give the user
ssh alice@server.example uptime     # run one command and come back
ssh -i ~/.ssh/work_key alice@server.example   # use a specific key
ssh -v alice@server.example         # verbose: shows why a login fails

scp and sftp copy files over the same encrypted connection:

bash
scp report.pdf alice@server.example:/tmp/
scp alice@server.example:/var/log/syslog .

Typing options every time gets old. Put them in your own ~/.ssh/config. The system-wide defaults for every user live in /etc/ssh/ssh_config:

~/.ssh/configtext
Host web1
    HostName 192.168.1.10
    User alice
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

Now ssh web1 is enough. Don’t confuse the two config files: ssh_config is for the client, sshd_config is for the server (the d is for daemon).

Host keys: is this really my server?#

Every SSH server has its own key pairs, the host keys, created when OpenSSH is installed. They prove the server’s identity, so nobody can pretend to be your server and catch your password. They live in /etc/ssh/, one pair per algorithm:

Private key (mode 600, root only)Public key (mode 644)Note
/etc/ssh/ssh_host_rsa_key/etc/ssh/ssh_host_rsa_key.pubRSA, widely supported
/etc/ssh/ssh_host_dsa_key/etc/ssh/ssh_host_dsa_key.pubDSA, obsolete and no longer created
/etc/ssh/ssh_host_ecdsa_key/etc/ssh/ssh_host_ecdsa_key.pubECDSA (elliptic curve)
/etc/ssh/ssh_host_ed25519_key/etc/ssh/ssh_host_ed25519_key.pubEd25519, modern and preferred

The first time you connect, ssh shows the server’s key fingerprint and asks if you trust it:

console
The authenticity of host '192.168.1.10 (192.168.1.10)' can't be established.
ED25519 key fingerprint is SHA256:Xq4n0y7c1pX3VbJqzWm2c0A9yJ5kQe1hT8rLx2bUo6E.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.1.10' (ED25519) to the list of known hosts.

To check it properly, compare with the fingerprint shown on the server itself:

bash
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
console
256 SHA256:Xq4n0y7c1pX3VbJqzWm2c0A9yJ5kQe1hT8rLx2bUo6E root@web1 (ED25519)

Once you say yes, the public host key is saved in ~/.ssh/known_hosts. An admin can also list trusted host keys for every user in /etc/ssh/ssh_known_hosts. On the next visit, ssh compares silently. If the key changed, it refuses and shows a big warning:

console
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

That’s either an attack or a reinstalled server. If you know the server was reinstalled, remove the old entry with ssh-keygen -R 192.168.1.10 and connect again.

Tip

If you clone a VM, the clones share the same host keys. Give each one its own: delete /etc/ssh/ssh_host_*, run sudo ssh-keygen -A (creates any missing host keys), then restart the server: sudo systemctl restart ssh on Debian/Ubuntu, sshd on RHEL/Fedora.

Log in with keys instead of passwords#

A key login is safer than a password (nothing to guess) and more convenient. Create a key pair with ssh-keygen:

bash
ssh-keygen -t ed25519 -C "alice@laptop"
console
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/alice/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/alice/.ssh/id_ed25519
Your public key has been saved in /home/alice/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:9mJt2cX0bQ7yH1vK3nP5sL8wR4eD6fA2uZ0iO9gT1kM alice@laptop

The -t option picks the type, and the default file names follow it:

TypePrivate keyPublic keyNote
-t rsa -b 4096~/.ssh/id_rsa~/.ssh/id_rsa.pubWorks everywhere; use 3072 or 4096 bits
-t dsa~/.ssh/id_dsa~/.ssh/id_dsa.pubObsolete, refused by modern OpenSSH
-t ecdsa~/.ssh/id_ecdsa~/.ssh/id_ecdsa.pubElliptic curve
-t ed25519~/.ssh/id_ed25519~/.ssh/id_ed25519.pubShort, fast, the best choice today

The private key never leaves your machine and should have a passphrase. The public key (.pub) goes to every server you want to log in to, into the file ~/.ssh/authorized_keys of the target user. ssh-copy-id does that for you:

bash
ssh-copy-id alice@server.example

Or by hand, which shows what really happens:

bash
cat ~/.ssh/id_ed25519.pub | ssh alice@server.example \
  'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'

Each line of authorized_keys is one public key:

~/.ssh/authorized_keystext
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJx3...kQ alice@laptop

Important

The server ignores your keys if ~/.ssh or authorized_keys can be written by other users. Keep ~/.ssh at 700, private keys and authorized_keys at 600.

OpenSSH 7.0 (2015) turned off DSA keys by default, and OpenSSH 10.0 (2025) removed DSA support completely. The exam still lists the id_dsa and ssh_host_dsa_key files, so know the names, but don’t create them.

On the server side, /etc/ssh/sshd_config decides what’s allowed. Two common hardening lines are PasswordAuthentication no (keys only) and PermitRootLogin no. Restart the server after changing it.

ssh-agent and ssh-add#

With a passphrase on your key, you’d type it on every connection. ssh-agent is a small program that holds your unlocked keys in memory, and ssh-add hands keys to it. You type the passphrase once per session:

bash
eval "$(ssh-agent)"           # start an agent for this shell
ssh-add                       # add the default keys (~/.ssh/id_*)
ssh-add ~/.ssh/work_key       # add a specific key
ssh-add -t 3600 ~/.ssh/id_ed25519   # forget it after an hour
ssh-add -l                    # list loaded keys
ssh-add -D                    # remove all keys from the agent
console
Agent pid 4242
Enter passphrase for /home/alice/.ssh/id_ed25519:
Identity added: /home/alice/.ssh/id_ed25519 (alice@laptop)
256 SHA256:9mJt2cX0bQ7yH1vK3nP5sL8wR4eD6fA2uZ0iO9gT1kM alice@laptop (ED25519)

ssh-agent prints shell commands that set SSH_AUTH_SOCK, which is how ssh finds the agent. That’s why you wrap it in eval. Desktop sessions usually start an agent for you.

ssh -A forwards your agent to the server, so you can hop on to a third machine with your keys. Only do it on servers you trust: root there can use your agent while you’re connected.

SSH tunnels#

SSH can carry other connections inside its encrypted tunnel. That’s port forwarding:

OptionDirectionExample
-L local_port:host:portListen on your machine, connect from the serverReach a database that only listens on the server
-R remote_port:host:portListen on the server, connect from your machineShow a local dev site to the server side
-D portA SOCKS proxy on your machineBrowse through the server
bash
# Local: your port 5433 reaches PostgreSQL on the server's own localhost:5432
ssh -L 5433:localhost:5432 alice@db.example

# Remote: port 9000 on the server reaches port 3000 on your laptop
ssh -R 9000:localhost:3000 alice@server.example

# Dynamic: a SOCKS proxy on localhost:1080
ssh -D 1080 alice@server.example

# -N: no remote command, just the tunnel. -f: go to the background
ssh -fN -L 8080:intranet.example:80 alice@gateway.example

In -L 5433:localhost:5432, the localhost is resolved on the server, so it means the server itself. In the last example the server connects on to a third machine, intranet.example, and you open http://localhost:8080 in your browser.

X11 tunnels#

X11 is the classic Linux graphics system, and it can show a window from a remote program on your own screen. SSH can tunnel that too:

bash
ssh -X alice@server.example     # X11 forwarding (with security limits)
ssh -Y alice@server.example     # "trusted" X11 forwarding, fewer limits
xclock &                        # runs on the server, the window opens on your screen
echo $DISPLAY
console
localhost:10.0

The server must allow it with X11Forwarding yes in /etc/ssh/sshd_config and have xauth installed. ssh sets DISPLAY to a fake display like localhost:10.0 that leads back through the tunnel. Your own machine needs a running X server (or XWayland).

GnuPG: encrypt and sign files#

GnuPG (gpg) is the free implementation of OpenPGP. It uses the same public/private idea:

  • To encrypt for Bob, use Bob’s public key. Only Bob’s private key can decrypt it.
  • To sign, use your private key. Anyone with your public key can verify it came from you, unchanged.

Create your keys#

bash
gpg --full-generate-key       # asks for type, size, expiry, name, email, passphrase
gpg --gen-key                 # quicker, uses the defaults
gpg --list-keys               # public keys (short: gpg -k)
gpg --list-secret-keys        # your private keys (short: gpg -K)
console
/home/alice/.gnupg/pubring.kbx
------------------------------
pub   ed25519 2026-12-01 [SC] [expires: 2029-11-30]
      3F2A9C1E7B4D8A60C5E1F2B39D7A4C8E1B6F0A52
uid           [ultimate] Alice Example <alice@example.com>
sub   cv25519 2026-12-01 [E] [expires: 2029-11-30]

The main key (pub) can sign and certify ([SC]). A subkey (sub) does encryption ([E]). The long hex string is the fingerprint, the key’s real identity. GnuPG 2.4 (Ubuntu 24.04) defaults to Ed25519 keys like these. GnuPG 2.2 (Debian 12) defaults to RSA 3072.

Everything lives in ~/.gnupg/, which must be mode 700:

PathHolds
~/.gnupg/pubring.kbxYour public keyring (older versions: pubring.gpg)
~/.gnupg/private-keys-v1.d/Your private keys
~/.gnupg/trustdb.gpgHow much you trust each key
~/.gnupg/openpgp-revocs.d/Revocation certificates made with each new key
~/.gnupg/gpg.confOptions for gpg
~/.gnupg/gpg-agent.confOptions for gpg-agent

Share public keys#

bash
gpg --export --armor alice@example.com > alice.asc   # your public key as text
gpg --import bob.asc                                 # add Bob's key
gpg --fingerprint bob@example.com                    # show his fingerprint
gpg --sign-key bob@example.com                       # vouch for it after checking
gpg --keyserver keys.openpgp.org --send-keys 3F2A9C1E7B4D8A60C5E1F2B39D7A4C8E1B6F0A52
gpg --keyserver keys.openpgp.org --recv-keys <bob's fingerprint>

--armor (-a) gives readable text instead of binary. Before you trust an imported key, compare its fingerprint with Bob in person or by phone. Otherwise gpg warns that “It is NOT certain that the key belongs to the person named in the user ID”.

Encrypt and decrypt#

bash
gpg --encrypt --recipient bob@example.com report.pdf      # creates report.pdf.gpg
gpg -e -a -r bob@example.com notes.txt                    # creates notes.txt.asc (text)
gpg --symmetric secrets.tar      # (-c) passphrase only, no keys: secrets.tar.gpg

Bob decrypts with his private key:

bash
gpg --output report.pdf --decrypt report.pdf.gpg
gpg -d notes.txt.asc            # prints to the screen
console
gpg: encrypted with cv25519 key, ID 8C1D2E3F4A5B6C7D, created 2026-12-01
      "Bob Example <bob@example.com>"

Sign and verify#

CommandOutputUse it for
gpg --sign file (-s)file.gpg (binary, file inside)Signed and compressed together
gpg --clearsign filefile.asc (readable text with signature)Emails, text you still want to read
gpg --detach-sign file (-b)file.sig (signature only)Downloads: the file stays untouched
bash
gpg --detach-sign release.tar.gz           # creates release.tar.gz.sig
gpg --verify release.tar.gz.sig release.tar.gz
console
gpg: Signature made Tue 01 Dec 2026 10:15:02 AM UTC
gpg:                using EDDSA key 3F2A9C1E7B4D8A60C5E1F2B39D7A4C8E1B6F0A52
gpg: Good signature from "Alice Example <alice@example.com>" [ultimate]

If even one byte of the file changes, you get BAD signature instead. You can combine both jobs: gpg -se -r bob@example.com file signs and encrypts in one go.

Revoke a key#

If your private key is stolen or lost, you revoke it: you publish a signed statement that says “don’t use this key any more”. You need a revocation certificate, so make one right after creating the key and keep it somewhere safe and offline:

bash
gpg --output revoke-alice.asc --gen-revoke alice@example.com

GnuPG 2.1 and later also create one automatically in ~/.gnupg/openpgp-revocs.d/<fingerprint>.rev. When the day comes, import it and publish the revoked key:

bash
gpg --import revoke-alice.asc
gpg --keyserver keys.openpgp.org --send-keys 3F2A9C1E7B4D8A60C5E1F2B39D7A4C8E1B6F0A52

The automatic .rev file has a : in front of its first -----BEGIN line so it can’t be imported by accident. Remove that colon before you import it.

gpg-agent#

Like ssh-agent, gpg-agent remembers your passphrase for a while, so you don’t type it for every file. In GnuPG 2.1 and later it also does every private key operation, and gpg starts it automatically. Tune it in ~/.gnupg/gpg-agent.conf:

~/.gnupg/gpg-agent.conftext
default-cache-ttl 600
max-cache-ttl 7200

Reload it after a change with gpgconf --reload gpg-agent, or stop it with gpgconf --kill gpg-agent so it forgets every cached passphrase. With enable-ssh-support it can even stand in for ssh-agent.

Exam checklist#

  • ssh client config: ~/.ssh/config per user, /etc/ssh/ssh_config system-wide. The server uses /etc/ssh/sshd_config.
  • Host keys: /etc/ssh/ssh_host_{rsa,dsa,ecdsa,ed25519}_key and .pub. They prove the server’s identity. ssh-keygen -A creates missing ones.
  • Clients remember host keys in ~/.ssh/known_hosts (system-wide: /etc/ssh/ssh_known_hosts). ssh-keygen -R host removes one.
  • User keys: ssh-keygen -t rsa|dsa|ecdsa|ed25519 makes ~/.ssh/id_<type> and id_<type>.pub. The public key goes into the server’s ~/.ssh/authorized_keys.
  • ssh-agent holds unlocked keys, ssh-add loads them (-l list, -D delete all). Start it with eval "$(ssh-agent)".
  • Tunnels: -L local forward, -R remote forward, -D SOCKS, -N no command, -f background. X11: ssh -X or -Y, needs X11Forwarding yes.
  • gpg: --gen-key, --list-keys, --export -a, --import, -e -r encrypt, -d decrypt, -c symmetric, --sign, --clearsign, --detach-sign, --verify.
  • Encrypt with the recipient’s public key; sign with your own private key.
  • Revocation: gpg --gen-revoke, import it, then send the key to a keyserver. Keys and config live in ~/.gnupg/; gpg-agent caches passphrases.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. You run ssh -L 8080:localhost:80 alice@server. What does that do?
  2. Which file on a server lists the public keys allowed to log in as a user?
  3. Bob wants to send you an encrypted file with GnuPG. Which key does he use?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy