Linux Hardening
Physical Security
- secure physical access to computers
- lock rooms
- maintain access control
Secure Single User Mode
- Single User Mode is an easy way to gain access to a Linux system
- gives full root access without requiring a password
- gain by:
- Restart system
- interrupt boot process to get to boot menu
- In Grub boot loader: press
eto edit the configuration- may differ on other OS
- Find line that starts with
linux- this line tells the boot loader where kernel is
- give an argument of
sto boot into single user mode- can also use
Sor1
- can also use
- boot with
CTRL+x
- Some newer OS require a root password
- To require a root password for single user mode on
initsystems:- login as
root - edit the
/etc/sysconfig/init - Change
SINGLE=/sbin/sushelltoSINGLE=/sbin/sulogin - Reboot system
- login as
- To require a root password for single user mode on
systemdsystems:- login as
root - go to
/lib/systemd/system - edit
emergency.serviceandrescue.service - change
ExecStartline from using/usr/sbin/sushellto/usr/sbin/sulogin
- login as
- Make sure a password is set for the root account
Secure the Bootloader
- The above can be bypassed by telling the kernel to use a shell as the init system
- bypasses the init system and opens a root shell
- edit bootloader config by appending
init=/bin/bashto the linux kernel line
- To protect against this, need to require a password on the GRUB bootloader before making any changes
- create a config file in
/etc/grub.d- name to
40_custom
- name to
- add
set superusers="root"andpassword root <password>- can use any user here
- can encrypt password with
grub2-mkpasswd-pbkdf2- then can set
password_pbkdf2 root <output of previous command>- e.g.,
grub.pbkdf2.sha512.HASH
- e.g.,
- then can set
- Rebuild
grub.cfgfilegrub2-mkconfig -o /boot/grub2/grub.cfg- command may vary
- on Ubuntu:
update-grub
- on Ubuntu:
- refer to doc for your distribution
- create a config file in
- It is also possible to use an OS install media with troubleshooting tools to disable the above grub config changes
- to protect against this, use disk encryption
Disk Encryption
dm-crypt (device mapper crypt) is a kernel level encryption subsystem that provides transparent disk encryption.
- means the files are available immediately after mounting a file system on a
dm-cryptencrypted device - creates a new block device in
/dev/mapper- writes are encrypted
- reads are decrypted
- encryption is below the file system layer, so can use like any other block device
Linux Unified Key Setup (LUKS) is a standard for Linux disk encryption and is a frontend for dm-crypt.
- compatible across distributions
- uses passphrases that decrypt the master key for the actual encryption
- allows use of multiple passphrases
- stores the required setup information in the partition header
- so is portable and enables migration of data seamlessly
- great for removable media too
- Encrypt during install
- easy, with sane defaults
- but you give up some control
- prompts for passphrase on boot
Setup LUKS on a New Device
- can be used on any block device
- will remove all data on the partition
- install
cryptsetup sudo fdisk -lto find the device file associated with device- Optionally, secure erase the disk by filling with random data
sudo shred -v -n 1 /dev/sdb- writes random data to disk with verbose output and 1 pass
- Initialize device
sudo cryptsetup format /dev/sdb
- Open device
sudo cryptsetup luksOpen /dev/sdb <name of device to use>- block device created in
/dev/mapper/<name>
- Format device
sudo mkfs -t ext4 /dev/mapper/<name>
- Mount filesystem
sudo mount /dev/mapper/<name> <dir-to-mount>
- Close device
sudo cryptsetup luksClose <name>
Encrypt an Existing Device
- backup the content on the device
- then encrypt the new device
- then restore the backup to the device
Disable Control-Alt-Delete
- On
systemdsystems:systemctl mask ctrl-alt-del.target- disables
systemctl daemon-reload- make change effective
Account Security
Pluggable Authentication Module (PAM)
A pluggable authentication module (PAM) is a centralized authentication mechanism used on Linux systems.
- configuration files
/etc/pam.d/etc/pam.d/login/etc/pam.d/sshd
- format
module_interface control_flag module_name module_args
- 4 kinds of module interfaces
- auth - authenticates users
- account - verifies if access is permitted
- password - changes a user’s password
- session - manages user’s sessions
- control flags
- tell PAM what to do with a result
- required - modules result must be successful to continue
- requisite - similar to required, but no other modules are invoked
- sufficient - authenticates user if no required modules have failed, otherwise ignored
- optional - causes result of module to be ignored unless its the only module that references the interface
- include - includes configuration from another file
- there are also complex control flags in attribute=value pairs
Password Security
- enforce strong passwords
- use shadow passwords
/etc/passwdfile will showxfor passwords- stored in
/etc/shadow - enable shadow passwords:
pwconv - disable:
pwunconv
- can set default password aging options in
/etc/login.defsPASS_MAX_DAYSPASS_MIN_DAYSPASS_MIN_LENPASS_WARN_AGE
Lock Account
- To lock an account:
passwd -l account - To unlock an account:
passwd -u account - Can disable interactive use of account by setting it’s shell to
nologin- in
/etc/passwd, this looks like:- CentOS:
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin - Ubuntu:
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
- CentOS:
- To lock, can use the
chsh(change shell) command- syntax:
chsh -s SHELL ACCOUNT - e.g.,
chsh -s /sbin/nologin jason
- syntax:
- in
- Can disable logins for a user for a period of time with the
pam_nologinmodule- enabled in pam config file
- looks for
/etc/nologinor/var/run/nologin - disables logins and displays contents of nologin file
Intrusion Prevention System with fail2ban
fail2banmonitors authentication log files and creates a firewall rule to block the IP address of attacker attempting brute force attack- typically configured to automatically unban after a certain period of time
- can be used for any service that writes login attempts to a log file
- not just Linux logins
- ships with filters for popular software services
Multifactor Authentication
- Google Authenticator PAM module
- when connecting with
ssh, will be prompted for a code in Google Authenticator
- when connecting with
- DuoSecurity’s
pam_duomodule - RSA SecurID PAM module
- these use TOTP codes
Root Account Security
- don’t use
rootaccount for normal daily activity - avoid logging in as
root- escalate privileges from normal account as needed
- use
sudoinstead ofsusudohas better audit logging of activity- who ran what and when
suonly logs time when user switched torootaccount- Disable
suwith using PAMsudo nano /etc/pam.d/su- Comment out
auth sufficient pam_rootok.sowith#- this disallows root to use
suwithout a password
- this disallows root to use
- Add
auth requisite pam_deny.so - Save and exit
- avoid using the same
rootpassword across systems - ensure only the
rootaccount has UID of 0- any account with UID of 0 is treated as a
rootaccount - check with
awk -F: '($3 == "0") {print}' /etc/passwd
- any account with UID of 0 is treated as a
- can disable root logins with
pam_securettymodule- common directive:
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so- can be found in default pam config on most distros
etc/securettyfile contains a list of devices whererootis allowed to log in- one per line
- common directive:
- disable root ssh logins
/etc/ssh/sshd_config- set
PermitRootLogin no systemctl reload sshd
- use one account per service
- e.g.,
httpd
- e.g.,
- keep system and service accounts locked
Deleting Accounts
- Determine UID
id ACCOUNT
- Delete account and home directory
userdel -r
- Find other files that belong to user
find / -user UIDfind / -nouser
Network Security
Secure Network Services
- use a dedicated user for each service
- disable unused services
- ports below
1024are privileged- use
rootto open them, then drop privileges
- use
- avoid unsecure services
- e.g.,
telnet,FTP
- e.g.,
- Managing services with
systemd:- to list running services:
systemctl - stop service:
systemctl stop SERVICE- will restart upon system reboot
- to disable service:
systemctl disable SERVICE
- to list running services:
- List listening services
netstat -nutlp0.0.0.0means all IP addresses
Secure SSH
- Enable key-based authentication
/etc/ssh/sshd_config- set
PubkeyAuthentication yes
- Generate SSH key with
ssh-keygen- optionally can use a passphrase
- Copy key to remote system:
ssh-copy-id [user@host]- adds public key to
~/.ssh/authorized_keys
- Disable password authentication
- set
PasswordAuthentication no
- set
- Disable
rootloginsPermitRootLogin no
- To only allow
rootlogin with keyPermitRootLogin without-password
- Only allow specific users SSH access
AllowUsers user1 user2 ...
- Only allow specific groups SSH access
AllowGroups group1 group2 ...
- Deny specific users and groups SSH access
DenyUsers user1 user2 ...DenyGroups group1 group2 ...
- Disable TCP port forwarding
AllowTcpForwarding noGatewayPorts no
Enable Firewall
- Linux Firewall
- comprised of two parts:
- Netfilter
- is a kernel framework
- IPTables
- is a packet selection system
- Netfilter
iptablescommand controls the firewall
- comprised of two parts:
- Basic structure of firewall:
- a table is comprised of chains which is comprised of rules
- can be multiple tables
- each table can contain multiple chains
- each chain can contain multiple rules
- 5 default tables:
- Filter
- most commonly used
- block incoming connections or deny outgoing connections
- NAT
- used for NAT
- used to allow a single IP address to be shared
- Mangle
- used to alter packets
- e.g. change the TTL
- used to alter packets
- Raw
- used to disable connection tracking
- rarely used
- Security
- used for mandatory access control
- used by SELinux
- Filter
- cannot create custom table
- Default chains
- INPUT
- OUTPUT
- FORWARD
- PREROUTING
- POSTROUTING
- Can create custom chains
- use for custom collection of rules
- a table is comprised of chains which is comprised of rules
- Rules
- comprised of match + target
- Match on:
- protocol
- source/dest IP or network
- source/dest port
- network interface
- Target determines what happens on a match
- common built-in targets
- ACCEPT
- DROP
- REJECT
- LOG
- RETURN
- common built-in targets
Configure Firewall
- View rules
iptables -Ldisplays the filter tableiptables -t nat -Ldisplay the nat tableiptables -nLdisplays using numeric outputiptables -vLdisplays using verbose outputiptables --line-numbers -Ldisplays using line numbers
- built-in chains have a default policy
- if a packet reaches the end of a chain, then the default policy is applied to the packet
- to set default policy:
iptables -P CHAIN TARGET
- Add and delete rules
- Append a rule to chain:
iptables -A CHAIN RULE- FILTER table is assumed unless
-t TABLEoption is given
- Insert a rule to beginning of chain:
iptables -I CHAIN [RULENUM] RULE
- Detele a rule:
iptables -D CHAIN RULE|RULENUM
- Flush rules (delete)
iptables [-t TABLE] -F [CHAIN]
- Append a rule to chain:
- Rule specification options:
- Specify a source:
-s SOURCE - Specify a destination:
-d DESTINATION - Specify a protocol:
-p PROTOCOL -mspecifies a module- Specify destination port:
-p PROTOCOL -m PROTOCOL --dport PORT - Specify a source port:
-p PROTOCOL -m PROTOCOL --sport PORT -m limit --limit rate[/second/minute/hour/day]specifies a rate limit
- Specify a source:
- Rule examples
iptables -A INPUT -s 216.58.219.174 -j DROP
- Create a custom chain
iptables [-t TABLE] -N CHAIN
- Delete a chain
iptables [-t TABLE] -X CHAIN
- Saving Rules
iptablescommand does not save the state of firewall for persistence- Debian/Ubuntu
apt-get install iptables-persistentnetfilter-persistent save
- CentOS/RedHat
yum install iptables-servicesservice iptables save
- IPTABLES front-ends
- Debian/Ubuntu:
UFW - CentOS/RHEL:
Firewalld
- Debian/Ubuntu:
File System Security
File Attributes
- some filesystems support file attributes
- aka extended attributes (xattr)
- e.g., ext2-4, XFS, Btrfs, ReiserFS, JFS, etc.
- Immutable (
i) attribute- file becomes immutable
- cannot be deleted, renamed, modified, linked to
- must remove attribute in order to modify file
- useful for
- file becomes immutable
- Append (
a) attribute- Allows append only
- existing content cannot be modified
- file cannot be deleted
- useful for log files
- not every attribute is support on all filesystems
- Viewing attributes
lsattr FILE
- Modify attributes
chattrcommand+adds attributes-removes attributes=sets exact attritbutes
File Access Control List
- provides additional control to file permissions
- e.g., can give one user access to a file
- the traditional solution is to create another group
- increases overhead of group management
- To use file ACLs, the filesystem needs to mount with ACL support
mount -o acl /path/to/dev /path/to/mount
- Types of ACL
- Access ACL
- controls access to a specific file or directory
- Default ACL
- used only on directories
- files without ACL used the default ACL rules
- Not retroactive
- Access ACL
- Creating ACLs
- use the
setfaclcommand - Create or modify:
setfacl -m ACL FILE
- use the
- ACL Format
- User
u:[UID|USER]:permsSet the access ACL for a user- e.g.,
setfacl -m u:jason:rwx start.sh
- Group
g:[GID|GROUP]:permssets the access ACL for a group- e.g.,
setfacl -m g:sales:rw sales.txt
- Effective rights mask
- is used to restrict permissions for all users and groups that are defined in the ACL
m:permssets the effective rights mask- e.g., prevent all users from writing to a file
setfacl -m m:rx sales.txt
- Other users
o:permssets the access ACL for others- e.g.,
setfacl -m o:r sales.txt
- User
- Create multiple ACLs at once
setfacl -m u:bob:r,g:sales:rw sales.txt
- Set default ACL
d:[ugo]:permssets the default ACL- preceded by
d:
- preceded by
- e.g.,
setfacl -m d:g:sales:rw sales
- Set ACLs recursively
setfacl -R -m g:sales:rw sales
- Remove ACL
setfacl -x ACL FILE- leave out permissions
- e.g.,
setfacl -x u:jason sales.txt - remove all ACL entries on a file
setfacl -b FILE- e.g.,
setfacl -b sales.txt
- View ACLs
getfacl sales.txt
Rootkits
A rootkit is a collection of software that allows a user to get unauthorized root access to a system and remained undetected.
- attempt to hide from admins and AVs
- use File Integrity Monitoring (FIM) tools to mitigate user space rootkits
- e.g., AIDE, tripwire, OSSEC
chrootkitis a shell script used to detect the presence of rootkits