# Perform security administration tasks

> Find risky SUID files, set password aging, spot open ports, limit users, see who logged in, and set up sudo.

Source: https://aminbytes.dev/bytes/security/security-administration/


Security is mostly routine. Nobody breaks into a well run server with movie-style hacking: they use a forgotten account with a weak password, a service you didn't know was listening, or a program that runs as root when it shouldn't. This byte is the checklist an admin runs through to catch those things early.

You'll look for dangerous file permissions, control passwords, find open ports, set limits on what users can use, check who has logged in, and hand out root powers carefully with `sudo`.

## Audit files with SUID and SGID

Normally a program runs with *your* permissions. A file with the **SUID** (set user ID) bit runs with the permissions of the file's **owner** instead. **SGID** (set group ID) does the same for the group. That's how `passwd` lets a normal user write to `/etc/shadow`, which only root can change:

```bash
ls -l /usr/bin/passwd /usr/bin/wall
```

```console
-rwsr-xr-x 1 root root  68248 Mar 23  2025 /usr/bin/passwd
-rwxr-sr-x 1 root tty   23136 Apr  9  2025 /usr/bin/wall
```

The `s` in the owner's execute spot means SUID. The `s` in the group's spot means SGID. A SUID root program with a bug can give an attacker a root shell, so you want to know exactly which ones exist. Use `find` with `-perm`:

```bash
# SUID files (4000)
sudo find / -perm -4000 -type f 2>/dev/null

# SGID files (2000)
sudo find / -perm -2000 -type f 2>/dev/null

# Either one: a slash means "any of these bits"
sudo find / -perm /6000 -type f -exec ls -l {} \; 2>/dev/null
```

```console
/usr/bin/chsh
/usr/bin/su
/usr/bin/mount
/usr/bin/passwd
/usr/bin/sudo
/usr/bin/newgrp
/usr/bin/chfn
/usr/bin/umount
/usr/bin/gpasswd
```

| `-perm` form | Meaning |
| --- | --- |
| `-perm 4755` | Mode is **exactly** 4755 |
| `-perm -4000` | **All** these bits are set (SUID, other bits don't matter) |
| `-perm /6000` | **Any** of these bits is set (SUID or SGID) |
| `-perm -u+s` / `-perm -g+s` | Same as `-4000` / `-2000`, written symbolically |

`2>/dev/null` hides "Permission denied" noise. Add `-xdev` to stay on one filesystem and skip `/proc` and network mounts.

> [!TIP]
> Save the list once on a fresh system, then compare later: `sudo find / -xdev -perm /6000 -type f | sort > /root/suid.today` and `diff /root/suid.baseline /root/suid.today`. A new SUID file you didn't install is a red flag.

To remove the bit from a file that doesn't need it: `sudo chmod u-s /path/to/file` (or `g-s` for SGID).

## Passwords and password aging

`passwd` sets passwords. A normal user changes their own, root can change anyone's:

```bash
passwd                  # change your own password
sudo passwd alice       # set alice's password
sudo passwd -l alice    # lock the password (puts ! in front of the hash)
sudo passwd -u alice    # unlock it
sudo passwd -e alice    # expire it now: alice must pick a new one at next login
sudo passwd -d alice    # delete the password (empty: avoid this)
sudo passwd -S alice    # show status
```

```console
alice P 2026-11-28 0 99999 7 -1
```

The status line reads: user, `P` (usable password, `L` locked, `NP` no password), last change, minimum days, maximum days, warning days, inactive days. The exact format differs a little between Debian and RHEL.

**Password aging** decides how long a password lives. `chage` (change age) manages it, and `chage -l` lists it:

```bash
sudo chage -l alice
```

```console
Last password change                                    : Nov 28, 2026
Password expires                                        : never
Password inactive                                       : never
Account expires                                         : never
Minimum number of days between password change          : 0
Maximum number of days between password change          : 99999
Number of days of warning before password expires       : 7
```

| `chage` option | Sets |
| --- | --- |
| `-m 1` | Minimum days between changes |
| `-M 90` | Maximum days a password is valid |
| `-W 7` | Days of warning before it expires |
| `-I 14` | Inactive days after expiry before the account is locked |
| `-E 2027-06-30` | Date the whole account expires (`-E -1` removes it) |
| `-d 0` | Last change date: `0` forces a new password at next login |

```bash
sudo chage -M 90 -m 1 -W 7 -I 14 alice
sudo chage -d 0 alice
```

Run `chage alice` with no options and it asks for each value interactively. Defaults for **new** users come from `/etc/login.defs` (`PASS_MAX_DAYS`, `PASS_MIN_DAYS`, `PASS_WARN_AGE`).

`usermod` can do some of the same from the account side:

| `usermod` option | Effect |
| --- | --- |
| `-L` / `-U` | Lock / unlock the password |
| `-e 2027-06-30` | Account expiry date (like `chage -E`) |
| `-f 14` | Inactive days (like `chage -I`) |
| `-s /usr/sbin/nologin` | Give a login shell that refuses logins |
| `-aG sudo` | Append the user to a group (here: give sudo rights on Debian) |

> [!WARNING]
> Locking the password (`passwd -l`, `usermod -L`) does not stop a login with an SSH key. To block an account completely, also expire it (`usermod -e 1` or `chage -E 0`) or change its shell to `nologin`.

## Find open ports

Every listening port is a door into the machine. Look from the inside first, with `ss` (modern) or `netstat` (legacy, from the `net-tools` package):

```bash
sudo ss -tulpn
sudo netstat -tulpn
```

This is the `netstat` output. `ss` shows the same facts in slightly different columns:

```console
Proto Recv-Q Send-Q Local Address    Foreign Address  State   PID/Program name
tcp        0      0 0.0.0.0:22       0.0.0.0:*        LISTEN  812/sshd
tcp        0      0 127.0.0.1:25     0.0.0.0:*        LISTEN  1033/master
tcp6       0      0 :::22            :::*             LISTEN  812/sshd
udp        0      0 0.0.0.0:68       0.0.0.0:*                644/dhclient
```

The options are the same for both: `-t` TCP, `-u` UDP, `-l` listening only, `-p` show the program (needs root), `-n` numbers instead of names. `127.0.0.1:25` only accepts local connections. `0.0.0.0:22` accepts them from anywhere.

To find out **which process** owns a port or file, use `lsof` (list open files) or `fuser`:

```bash
sudo lsof -i :22          # who uses port 22
sudo lsof -i -P -n        # every network connection, numeric
sudo fuser -v 22/tcp      # PIDs using TCP port 22
```

```console
COMMAND PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    812 root    3u  IPv4  21345      0t0  TCP *:22 (LISTEN)
sshd    812 root    4u  IPv6  21347      0t0  TCP *:22 (LISTEN)
```

`fuser` also works on files and mounts: `fuser -vm /mnt/usb` shows who keeps a disk busy, and `fuser -k 8080/tcp` kills the processes using that port. `lsof /var/log/syslog` shows who has a file open.

Then look from the **outside** with `nmap`, a port scanner. It shows what an attacker on the network would see, which can differ from `ss` because of a firewall:

```bash
nmap localhost                 # the 1000 most common TCP ports
sudo nmap -sS 192.168.1.10     # SYN scan (needs root)
sudo nmap -sU -p 53,123 192.168.1.10   # UDP ports
nmap -p- 192.168.1.10          # all 65535 TCP ports
nmap -sV 192.168.1.10          # also guess service versions
```

```console
Starting Nmap 7.94 ( https://nmap.org ) at 2026-12-01 10:02 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000070s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT    STATE SERVICE
22/tcp  open  ssh
25/tcp  open  smtp
631/tcp open  ipp

Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds
```

Install it with `sudo apt install nmap` or `sudo dnf install nmap`.

> [!CAUTION]
> Only scan machines you own or have written permission to test. Scanning other people's networks can break their rules or the law.

## Limit logins, processes and memory

One user running a runaway script can eat all the memory or start thousands of processes (a "fork bomb"). Limits stop that. The shell builtin `ulimit` shows and sets them for the current shell and everything it starts:

```bash
ulimit -a          # show all limits
ulimit -u          # max user processes
ulimit -n          # max open files
ulimit -Sn 512     # lower the soft limit for open files
ulimit -v 1000000  # max virtual memory, in KB
```

```console
core file size              (blocks, -c) 0
file size                   (blocks, -f) unlimited
max memory size             (kbytes, -m) unlimited
open files                          (-n) 1024
max user processes                  (-u) 15420
cpu time                   (seconds, -t) unlimited
virtual memory              (kbytes, -v) unlimited
```

Each limit has a **soft** value (the one in force, `-S`) and a **hard** value (the ceiling, `-H`). A user can raise the soft limit up to the hard one, and can lower the hard limit, but only root can raise a hard limit again. Setting a value without `-S` or `-H` sets both.

To make limits permanent per user or group, root edits `/etc/security/limits.conf` (or a file in `/etc/security/limits.d/`). PAM's `pam_limits` module applies it at login:

```text {title="/etc/security/limits.conf"}
# <domain>   <type>  <item>      <value>
*            soft    core        0
alice        hard    nproc       100
@students    hard    maxlogins   2
@students    hard    as          2000000
```

`nproc` limits processes, `maxlogins` limits simultaneous logins, `as` limits the address space (memory, in KB), `nofile` limits open files. A `@` means a group.

 (Side note: Services started by systemd don't go through a PAM login, so `limits.conf` doesn't apply to them. Their limits go in the unit file instead, like `LimitNOFILE=4096`.)

## Who is and was logged in

```bash
who        # who is logged in now
w          # same, plus uptime, load and what each user runs
last       # login history, newest first
last alice # only alice
sudo lastb # failed login attempts
```

```console
$ who
alice    pts/0        2026-12-01 09:12 (192.168.1.20)
bob      tty1         2026-12-01 08:55

$ w
 10:04:31 up 3 days,  2:11,  2 users,  load average: 0.08, 0.03, 0.01
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
alice    pts/0    192.168.1.20     09:12    0.00s  0.05s  0.00s w
bob      tty1     -                08:55    1:09m  0.02s  0.02s -bash

$ last
alice    pts/0        192.168.1.20     Tue Dec  1 09:12   still logged in
bob      tty1                          Tue Dec  1 08:55   still logged in
alice    pts/1        192.168.1.20     Mon Nov 30 14:02 - 17:45  (03:43)
reboot   system boot  6.1.0-27-amd64   Sat Nov 28 07:53   still running

wtmp begins Sun Nov  1 00:00:12 2026
```

`who` reads `/var/run/utmp` (current sessions). `last` reads `/var/log/wtmp` (history), and `lastb` reads `/var/log/btmp` (failures). `who -b` shows the last boot time and `whoami` prints your own name.

 (Side note: Some newer releases, like Debian 13, replace the old `wtmp` file with a small database to avoid the year 2038 problem. `last` then comes from the `wtmpdb` package, but you use it the same way.)

## su and sudo

`su` (substitute user) starts a shell as another user. It asks for the **target** user's password:

```bash
su -            # become root with a full login environment
su - alice      # become alice
su -c 'systemctl restart nginx'    # run one command as root
```

The `-` (or `-l`) gives you a login shell: the target's environment, home and `PATH`. Without it you keep most of your own environment.

`sudo` runs a single command as root (or another user) and asks for **your own** password. Every use is logged, and root's password never has to be shared. Ubuntu doesn't even set a root password: sudo is the only way in.

```bash
sudo apt update           # one command as root
sudo -u bob whoami        # run as bob
sudo -i                   # a root login shell
sudo -l                   # what am I allowed to run?
sudo -k                   # forget the cached password now
```

After you type your password, sudo remembers it for a few minutes (5 by default). Logs land in `/var/log/auth.log` on Debian/Ubuntu and `/var/log/secure` on RHEL/Fedora, or in `journalctl`.

### /etc/sudoers

Who may do what is set in `/etc/sudoers`. Always edit it with `visudo`, which checks the syntax before saving. The rule format is `who where=(as_whom) what`:

```text {title="/etc/sudoers"}
# user    hosts=(run as user:group)  commands
root      ALL=(ALL:ALL) ALL

# Debian/Ubuntu: members of group "sudo" may run anything
%sudo     ALL=(ALL:ALL) ALL

# RHEL/Fedora use group "wheel" instead
# %wheel  ALL=(ALL)     ALL

# alice may restart the web server, without a password
alice     ALL=(root) NOPASSWD: /usr/bin/systemctl restart nginx

@includedir /etc/sudoers.d
```

A `%` means a group. So the easiest way to make someone an admin is to add them to that group:

```bash
sudo usermod -aG sudo alice     # Debian/Ubuntu
sudo usermod -aG wheel alice    # RHEL/Fedora
```

Prefer small files in `/etc/sudoers.d/` over editing the main file: `sudo visudo -f /etc/sudoers.d/alice`. Older versions write the include line as `#includedir`: the `#` there is not a comment.

## Exam checklist

- SUID is `4000`, SGID is `2000`, sticky is `1000`. `find / -perm -4000` finds SUID files, `-perm /6000` finds either.
- `passwd -l`/`-u` lock and unlock, `passwd -e` expires a password, `passwd -S` shows status.
- `chage -l` lists aging, `-M` max days, `-m` min days, `-W` warning, `-I` inactive, `-E` account expiry, `-d 0` forces a change.
- `ss` or `netstat -tulpn` shows listening ports from inside; `nmap` scans from outside.
- `lsof -i :port` and `fuser -v port/tcp` show which process uses a port; `fuser -k` kills it.
- `ulimit -a` shows limits; soft (`-S`) vs hard (`-H`); permanent limits in `/etc/security/limits.conf` (`nproc`, `maxlogins`, `as`, `nofile`).
- `who` and `w` show current users (`/var/run/utmp`), `last` shows history (`/var/log/wtmp`), `lastb` failed logins.
- `su` asks for the target's password, `sudo` for your own. `su -` gives a login shell.
- Edit `/etc/sudoers` only with `visudo`. Admin groups: `sudo` on Debian/Ubuntu, `wheel` on RHEL/Fedora.


## Byte check

1. Which command lists every file on the system with the **SUID** bit set?
   - **`find / -perm -4000 -type f`** (correct)
   - `find / -perm -2000 -type f`
   - `find / -perm -1000 -type d`
   SUID is the `4` in the special-bits digit, so `-perm -4000` matches it. `2000` is SGID and `1000` is the sticky bit.

2. You want user `alice` to change her password at her next login. Which command does that?
   - `chage -E 0 alice`
   - **`chage -d 0 alice`** (correct)
   - `usermod -L alice`
   `chage -d 0` sets the last change date to day zero, so the password counts as expired and must be changed. `-E 0` expires the whole account, and `usermod -L` locks the password.

3. What is the safe way to edit `/etc/sudoers`?
   - `sudo nano /etc/sudoers`
   - **`visudo`** (correct)
   - `chmod 644 /etc/sudoers` first, then edit it
   `visudo` locks the file and checks the syntax before saving. A typo saved straight into sudoers can lock everyone out of sudo.


