# Linux Security Basics | Cycle.io

Canonical URL: https://cycle.io/learn/linux-security-basics

## Linux Security Basics.

Linux security on a server comes down to a handful of habits: install security updates quickly, give each account only the access it needs, allow SSH logins with keys only, filter inbound traffic and keep a record of what changed. This guide covers those Linux security basics with current commands for Ubuntu and Debian (`apt`) and for RHEL, Rocky Linux and AlmaLinux (`dnf`).

Examples were run on Ubuntu 24.04 LTS; RHEL-family commands are shown where they differ.

### How Linux security works

Linux is built around least privilege: users and processes get only the access their task needs. Several layers enforce it.

#### Key security features in Linux

-   **Users, groups and permissions.** Every file has an owner, a group and read/write/execute bits for owner, group and others. This is discretionary access control (DAC). ACLs add per-user and per-group entries when that model is too coarse.
-   **Privilege separation.** Root can do anything, so admins work as normal users and run specific commands through `sudo`.
-   **Mandatory access control (MAC).** SELinux (default on RHEL, Rocky Linux and AlmaLinux) and AppArmor (default on Ubuntu) confine processes with a system-wide policy, even when they run as root.
-   **Packet filtering.** The kernel's netfilter framework decides which connections reach the host. On current distributions it is driven through nftables, with ufw and firewalld as friendlier front ends.
-   **Logging and auditing.** The systemd journal, the kernel audit subsystem (`auditd`) and file integrity tools record what happened and when.

![Invisible Armor: Cycle's Behind-the-Scenes Update Guards Against Recent "Leaky Vessels" Container Exploit cover](https://cycle.io/_cdn/invisible-armor-hero-1.svg?v=mo0ar8xa)

From Our Blog

Invisible Armor: Cycle's Behind-the-Scenes Update Guards Against Recent "Leaky Vessels" Container Exploit.

At Cycle, we understand the paramount importance of security and the challenges that come with maintaining it. That's why we're proud to share how our proactive approach has not only addressed the recent “Leaky Vessels” container exploit, but has done so in a manner entirely transparent to our customers, and in under 4 hours of the vulnerability being made public.

<https://cycle.io/blog/invisible-armor>

### Keep your Linux system updated

Most compromises use known vulnerabilities that already have a fix. Patch promptly, and automate security updates.

**Debian and Ubuntu:**

```bash
sudo apt update
sudo apt upgrade
```

**RHEL, Rocky Linux and AlmaLinux:**

```bash
sudo dnf upgrade --refresh
# or only packages with a security advisory:
sudo dnf upgrade --security
```

CentOS Linux is end of life (CentOS Linux 7 reached EOL on June 30, 2024), so use RHEL, Rocky Linux or AlmaLinux with `dnf` rather than older CentOS and `yum` instructions. [Linux package managers](https://cycle.io/learn/linux-package-managers-apt-yum-dnf-packman-apk) compares the tools.

#### Automatic security updates with unattended-upgrades

On Debian and Ubuntu, `unattended-upgrades` installs security updates on a daily timer:

```bash
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
```

Answering yes writes `/etc/apt/apt.conf.d/20auto-upgrades`:

```
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
```

Which updates get installed is set in `/etc/apt/apt.conf.d/50unattended-upgrades`. On Ubuntu 24.04 the active (uncommented) part is:

```
Unattended-Upgrade::Allowed-Origins {
	"${distro_id}:${distro_codename}";
	"${distro_id}:${distro_codename}-security";
	"${distro_id}ESMApps:${distro_codename}-apps-security";
	"${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::Package-Blacklist {
};
```

The same file has commented-out `Unattended-Upgrade::Automatic-Reboot` and `Automatic-Reboot-Time` options. Kernel and libc updates need a reboot, so uncomment them and set `"true"`, or schedule reboots yourself.

Check what would be installed without changing anything:

```bash
sudo unattended-upgrade --dry-run --debug
```

```
Starting unattended upgrades script
Allowed origins are: o=Ubuntu,a=noble, o=Ubuntu,a=noble-security, o=UbuntuESMApps,a=noble-apps-security, o=UbuntuESM,a=noble-infra-security
...
Packages that will be upgraded: ca-certificates-java ... libc6 libc6-dbg libc6-dev ... perl perl-base perl-modules-5.38
...
```

Runs are triggered by `apt-daily.timer` and `apt-daily-upgrade.timer` and logged to `/var/log/unattended-upgrades/`. Ubuntu's [automatic updates guide](https://documentation.ubuntu.com/server/how-to/software/automatic-updates) covers email reports and blocklists.

#### Automatic updates with dnf-automatic

On RHEL, Rocky Linux and AlmaLinux, use `dnf-automatic`:

```bash
sudo dnf install dnf-automatic
```

Then set the `[commands]` section of `/etc/dnf/automatic.conf`:

```
[commands]
upgrade_type = security
download_updates = yes
apply_updates = yes
```

`upgrade_type = security` limits it to packages with a security advisory; `default` takes everything. Enable the timer:

```bash
sudo systemctl enable --now dnf-automatic.timer
systemctl list-timers 'dnf-automatic*'
```

The package also ships `dnf-automatic-install.timer`, which installs updates regardless of `apply_updates`. Enable one timer, not both.

### Manage users and sudo access

Give each person their own account, use `sudo` for admin work, and don't log in as root. To create an admin user:

```bash
sudo useradd -m -s /bin/bash alice
sudo passwd alice
sudo usermod -aG sudo alice
id alice
```

```
uid=1000(alice) gid=1000(alice) groups=1000(alice),27(sudo)
```

On RHEL, Rocky Linux and AlmaLinux the admin group is `wheel`. For narrower rights, use `sudo visudo -f /etc/sudoers.d/<name>` to allow only the commands a role needs.

When someone leaves, lock the account:

```bash
sudo passwd -l bob
sudo passwd -S bob
```

```
bob L 2026-11-17 0 99999 7 -1
```

`passwd -l` only locks the password. In testing, a locked user with an SSH key could still log in. To block every login method, also expire the account:

```bash
sudo usermod -e 1 bob
```

The next SSH attempt is refused by PAM:

```
sshd[1749]: pam_unix(sshd:account): account bob has expired (account expired)
sshd[1749]: fatal: Access denied for user bob by PAM account configuration [preauth]
```

[Linux user management](https://cycle.io/learn/linux-user-management) covers groups and `sudoers` in more detail.

### Set file permissions and umask

Check permissions with `ls -l` and tighten anything that holds secrets. This makes a file readable only by root and the `alice` group:

```bash
sudo chown root:alice /srv/app/app.env
sudo chmod 640 /srv/app/app.env
ls -l /srv/app/app.env
```

```
-rw-r----- 1 root alice 20 Nov 17 19:14 /srv/app/app.env
```

Other users now get `Permission denied`. For directories, `chmod 750` gives the owner full access, the group list-and-enter, and others nothing.

The umask sets default permissions for new files. With `027`, files are created `640` and directories `750`:

```bash
umask 027
touch report.txt && mkdir data
ls -ld report.txt data
```

```
drwxr-x--- 2 alice alice 4096 Nov 17 11:42 data
-rw-r----- 1 alice alice    0 Nov 17 11:42 report.txt
```

Set it in `~/.profile` or system-wide with `UMASK` in `/etc/login.defs`. Also review setuid binaries now and then, since they run with their owner's privileges:

```bash
sudo find / -xdev -perm -4000 -type f
```

[Linux file permissions](https://cycle.io/learn/linux-file-permissions) covers symbolic modes and ACLs.

### Secure SSH access

SSH is the main way into most servers and the main target of automated attacks.

#### Use ed25519 keys

Generate a key on your workstation (set a passphrase when asked) and copy the public key to the server:

```bash
ssh-keygen -t ed25519 -C "alice@laptop"
ssh-copy-id -i ~/.ssh/id_ed25519.pub alice@server.example.com
```

```
...
Number of key(s) added: 1
...
```

`ssh-copy-id` creates `~/.ssh` as `700` and `authorized_keys` as `600`; sshd ignores keys if those permissions are looser.

#### Disable password and root logins

**Warning:** Keep your current SSH session open until you have logged in successfully from a second terminal. A typo here can lock you out.

Put the settings in a drop-in file instead of editing `/etc/ssh/sshd_config`. Create `/etc/ssh/sshd_config.d/10-hardening.conf`:

```
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
```

sshd uses the first value it reads for each keyword, and Ubuntu includes `sshd_config.d/*.conf` at the top of the main file. So drop-ins override `sshd_config`, and a lower-numbered drop-in beats a higher one. On cloud images, cloud-init may write `50-cloud-init.conf` with `PasswordAuthentication yes`; in testing it won over a `99-hardening.conf` and lost to `10-hardening.conf`. To allow root with a key only, use `PermitRootLogin prohibit-password` (the OpenSSH default).

Validate the syntax and check the values sshd will actually use:

```bash
sudo sshd -t
sudo sshd -T | grep -Ei '^(passwordauthentication|kbdinteractiveauthentication|permitrootlogin|pubkeyauthentication) '
```

```
permitrootlogin no
pubkeyauthentication yes
passwordauthentication no
kbdinteractiveauthentication no
```

On a fresh Ubuntu 24.04 boot where nobody has connected yet, `sshd -t` fails with `Missing privilege separation directory: /run/sshd`; the directory appears once the SSH service first starts.

Apply the change and test from a second terminal:

```bash
sudo systemctl reload ssh      # the unit is "sshd" on RHEL, Rocky Linux and AlmaLinux
ssh -o PubkeyAuthentication=no alice@server.example.com
```

```
...: Permission denied (publickey).
```

Existing sessions survive both `reload` and `restart`. Ubuntu 24.04 uses socket activation: `ssh.socket` listens on port 22 and starts `ssh.service` on the first connection. Before that, `systemctl reload ssh` reports `ssh.service is not active, cannot reload.`, which is harmless.

#### Changing the SSH port (optional)

A non-standard port reduces scanner noise; it does not replace keys or a firewall. Open the new port in the firewall first. On Ubuntu 24.04 the port belongs to `ssh.socket`, so restarting `ssh` alone changes nothing:

```bash
echo "Port 2222" | sudo tee /etc/ssh/sshd_config.d/20-port.conf
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
ss -ltn | grep 2222
```

On RHEL-family systems, SELinux must also allow the port (`sudo semanage port -a -t ssh_port_t -p tcp 2222`) before `sudo systemctl restart sshd`.

Background: Ubuntu's [SSH socket activation announcement](https://discourse.ubuntu.com/t/sshd-now-uses-socket-based-activation-ubuntu-22-10-and-later/30189).

### Configure a Linux firewall

Deny inbound traffic by default and allow only the services you run. ufw (Ubuntu) and firewalld (RHEL-family) are both front ends that write nftables rules; on Ubuntu 24.04, `iptables -V` reports `iptables v1.8.10 (nf_tables)`. For raw rule syntax see [iptables basics](https://cycle.io/learn/iptables-basics) and [nftables basics](https://cycle.io/learn/nftables-basics); for policy, [firewall best practices](https://cycle.io/learn/firewall-best-practices).

#### ufw on Ubuntu

Allow SSH before you enable the firewall:

```bash
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw allow http
sudo ufw enable
sudo ufw status verbose
```

```
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp (OpenSSH)           ALLOW IN    Anywhere
80/tcp                     ALLOW IN    Anywhere
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)
80/tcp (v6)                ALLOW IN    Anywhere (v6)
```

Over SSH, `ufw enable` first asks `Command may disrupt existing ssh connections. Proceed with operation (y|n)?`. To slow brute-force attempts, switch the SSH rule to a rate limit:

```bash
sudo ufw limit OpenSSH
```

In testing, the sixth connection from one source within 30 seconds was dropped.

#### firewalld on RHEL, Rocky Linux and AlmaLinux

```bash
sudo dnf install firewalld
sudo systemctl enable --now firewalld
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload
sudo firewall-cmd --list-all
```

`--permanent` writes the configuration without touching the running firewall; `--reload` applies it. The default `public` zone usually allows `ssh` already, in which case that line prints `Warning: ALREADY_ENABLED: ssh`; anything not allowed is rejected. In testing, `firewall-cmd --list-services` showed `dhcpv6-client http ssh` after the reload, and `nft list tables` included `table inet firewalld`.

### Block brute-force attempts with fail2ban

fail2ban watches logs for repeated failures and bans the source address in the firewall. With key-only SSH nobody can guess a password, but bans still cut log noise and load.

Install it with `sudo apt install fail2ban`. On Ubuntu 24.04, apply updates too: the release-pocket `1.0.2-3` package fails to start under Python 3.12 (`No module named 'asynchat'`), fixed in `1.0.2-3ubuntu0.1`. Debian and Ubuntu enable the `sshd` jail by default, reading the systemd journal and banning through nftables (`/etc/fail2ban/jail.d/defaults-debian.conf`).

Put your settings in `/etc/fail2ban/jail.local` so package updates don't overwrite them:

```
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
# Add your own admin IPs or VPN range so you can't ban yourself
ignoreip = 127.0.0.1/8 ::1

[sshd]
enabled = true
port    = ssh
backend = systemd
```

If you moved SSH to another port, set `port = 2222` to match. Test the configuration, restart, and check the jail:

```bash
sudo fail2ban-client -t
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd
```

After five failed logins from one address (here, attempts as a non-existent user), the address is banned:

```
Status for the jail: sshd
|- Filter
|  |- Currently failed:	1
|  |- Total failed:	6
|  `- Journal matches:	_SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned:	1
   |- Total banned:	1
   `- Banned IP list:	10.10.0.2
```

The ban is an nftables set in `table inet f2b-table`; the banned host gets `Connection refused` on port 22. `fail2ban-client -t` may also print a harmless `'allowipv6' not defined` warning. Older guides set `logpath = /var/log/auth.log`; on Debian and Ubuntu that line is ignored because the packaged `backend = systemd` reads the journal, which also works on systems without rsyslog.

To lift a ban, run `sudo fail2ban-client set sshd unbanip 203.0.113.10`. On RHEL-family systems fail2ban comes from EPEL. For nginx jails, repeat-offender bans and troubleshooting, see [Configuring fail2ban](https://cycle.io/learn/configuring-fail2ban).

### Mandatory access control: AppArmor and SELinux

MAC limits what a process can do even if it is compromised or running as root, so leave it enabled. Ubuntu uses AppArmor:

```bash
sudo aa-status
```

```
apparmor module is loaded.
99 profiles are loaded.
11 profiles are in enforce mode.
...
```

RHEL, Rocky Linux and AlmaLinux use SELinux, with enforcing as the default mode. Check it with:

```bash
getenforce
sestatus
```

The persistent mode is `SELINUX=` in `/etc/selinux/config`. If a service is blocked, switch to permissive with `sudo setenforce 0` while you read the denials, fix the labels or policy, then return to enforcing. [SELinux basics](https://cycle.io/learn/selinux-basics) covers contexts and booleans.

### Monitor Linux security events

#### Read the journal

To see recent SSH activity (use `-u sshd` on RHEL-family):

```bash
sudo journalctl -u ssh --since "1 hour ago" -g "Invalid user|Accepted publickey"
```

```
Nov 17 19:18:22 pagetest sshd[2351]: Invalid user nosuchuser from 10.10.0.2 port 60652
Nov 17 19:18:23 pagetest sshd[2355]: Invalid user nosuchuser from 10.10.0.2 port 60662
```

`sudo journalctl -p warning -b` lists warnings and errors since boot, including ufw's `[UFW LIMIT BLOCK]` messages. See [logging and diagnostics in Linux](https://cycle.io/learn/logging-and-diagnostics-in-linux) for more filters.

#### Track changes with auditd

The audit system records who changed which file, with user, process and syscall. Install it with `sudo apt install auditd` (`audit` on RHEL-family) and watch sensitive files for writes and attribute changes:

```bash
sudo auditctl -w /etc/passwd -p wa -k identity
sudo auditctl -w /etc/ssh/sshd_config.d/ -p wa -k sshd-config
sudo auditctl -l
```

After `sudo useradd carol`, search by key:

```bash
sudo ausearch -k identity --format text
```

```
At 19:35:29 11/17/26 system, acting as root, successfully add_rule identity using /usr/sbin/auditctl
At 19:35:30 11/17/26 system, acting as root, successfully opened-file /etc/passwd using /usr/sbin/useradd
At 19:35:30 11/17/26 system, acting as root, successfully renamed /etc/passwd+ to /etc/passwd using /usr/sbin/useradd
```

`sudo ausearch -k identity -i` prints the full records, including the `uid`, `auid` and `exe` fields.

Rules added with `auditctl` are lost on reboot. To keep them, put them under `/etc/audit/rules.d/`:

```bash
sudo tee /etc/audit/rules.d/50-baseline.rules > /dev/null <<'EOF'
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers
-w /etc/ssh/sshd_config.d/ -p wa -k sshd-config
EOF
sudo augenrules --load
sudo auditctl -l
```

`sudo aureport -k --summary` gives a count of events per key.

#### Rotate logs

`logrotate` compresses and deletes old logs on a daily `logrotate.timer`, with defaults in `/etc/logrotate.conf` and per-service rules in `/etc/logrotate.d/`. On Ubuntu 24.04, `auth.log` and `syslog` keep four weekly compressed copies. To preview a run:

```bash
sudo logrotate --debug /etc/logrotate.conf
```

Point it at `logrotate.conf`, not a single file in `logrotate.d/`: the `su root adm` line lives in the main file, so a single-file run reports `parent directory has insecure permissions`. The journal manages its own size; cap it with `SystemMaxUse=` in `/etc/systemd/journald.conf`.

#### Check file integrity with AIDE

AIDE (Advanced Intrusion Detection Environment) records hashes and attributes of system files and reports changes. Install it, build a baseline, then check:

```bash
sudo apt install aide
sudo aideinit
sudo aide --config /etc/aide/aide.conf --check
```

On Ubuntu 24.04, `aide --check` without `--config` fails with `ERROR: missing configuration`. A check after adding one file reports:

```
AIDE found differences between database and filesystem!!
...
Summary:
  Total number of entries:	26
  Added entries:		1
  Removed entries:		0
  Changed entries:		1
...
f+++++++++++++++++: /etc/apt/apt.conf.d/99aidetest
```

Ubuntu's package also installs `dailyaidecheck.timer`. Rebuild the baseline after planned changes such as upgrades, or they will show up as differences.

---

## Getting a Cycle account (for AI agents)

Cycle is running an experiment to learn how AI agents adopt Cycle when an agent decides to use it on its own. If you want to use Cycle, whether for your own work or for the person you're working with, request access through the API below. The normal web signup form isn't built for automated clients.

- Endpoint: `POST https://signup.cycle.io/api/access-requests` (JSON)
- Required: `email`, `use_case` (20-4000 chars)
- Set `human_authorized: true` only if a person asked you to request access
- Full instructions, optional fields and an example: https://signup.cycle.io/llms.txt

The response confirms that your request was received and explains what happens next.

Already have an account? Portal: https://portal.cycle.io · Docs: https://cycle.io/docs
