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:
      1. Restart system
      2. interrupt boot process to get to boot menu
      3. In Grub boot loader: press e to edit the configuration
        • may differ on other OS
      4. Find line that starts with linux
        • this line tells the boot loader where kernel is
      5. give an argument of s to boot into single user mode
        • can also use S or 1
      6. boot with CTRL+x
    • Some newer OS require a root password
    • To require a root password for single user mode on init systems:
      1. login as root
      2. edit the /etc/sysconfig/init
      3. Change SINGLE=/sbin/sushell to SINGLE=/sbin/sulogin
      4. Reboot system
    • To require a root password for single user mode on systemd systems:
      1. login as root
      2. go to /lib/systemd/system
      3. edit emergency.service and rescue.service
      4. change ExecStart line from using /usr/sbin/sushell to /usr/sbin/sulogin
    • 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/bash to the linux kernel line
  • To protect against this, need to require a password on the GRUB bootloader before making any changes
    1. create a config file in /etc/grub.d
      • name to 40_custom
    2. add set superusers="root" and password root <password>
      • can use any user here
    3. can encrypt password with grub2-mkpasswd-pbkdf2
      • then can set password_pbkdf2 root <output of previous command>
        • e.g., grub.pbkdf2.sha512.HASH
    4. Rebuild grub.cfg file
      • grub2-mkconfig -o /boot/grub2/grub.cfg
      • command may vary
        • on Ubuntu: update-grub
      • refer to doc for your distribution
  • 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-crypt encrypted 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
  1. install cryptsetup
  2. sudo fdisk -l to find the device file associated with device
  3. 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
  4. Initialize device
    • sudo cryptsetup format /dev/sdb
  5. Open device
    • sudo cryptsetup luksOpen /dev/sdb <name of device to use>
    • block device created in /dev/mapper/<name>
  6. Format device
    • sudo mkfs -t ext4 /dev/mapper/<name>
  7. Mount filesystem
    • sudo mount /dev/mapper/<name> <dir-to-mount>
  8. 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 systemd systems:
    • 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/passwd file will show x for passwords
    • stored in /etc/shadow
    • enable shadow passwords: pwconv
    • disable: pwunconv
  • can set default password aging options in /etc/login.defs
    • PASS_MAX_DAYS
    • PASS_MIN_DAYS
    • PASS_MIN_LEN
    • PASS_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
    • To lock, can use the chsh (change shell) command
      • syntax: chsh -s SHELL ACCOUNT
      • e.g., chsh -s /sbin/nologin jason
  • Can disable logins for a user for a period of time with the pam_nologin module
    • enabled in pam config file
    • looks for /etc/nologin or /var/run/nologin
    • disables logins and displays contents of nologin file

Intrusion Prevention System with fail2ban

  • fail2ban monitors 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
  • DuoSecurity’s pam_duo module
  • RSA SecurID PAM module
  • these use TOTP codes

Root Account Security

  • don’t use root account for normal daily activity
  • avoid logging in as root
    • escalate privileges from normal account as needed
  • use sudo instead of su
    • sudo has better audit logging of activity
      • who ran what and when
    • su only logs time when user switched to root account
    • Disable su with using PAM
      • sudo nano /etc/pam.d/su
      • Comment out auth sufficient pam_rootok.so with #
        • this disallows root to use su without a password
      • Add auth requisite pam_deny.so
      • Save and exit
  • avoid using the same root password across systems
  • ensure only the root account has UID of 0
    • any account with UID of 0 is treated as a root account
    • check with awk -F: '($3 == "0") {print}' /etc/passwd
  • can disable root logins with pam_securetty module
    • 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/securetty file contains a list of devices where root is allowed to log in
      • one per line
  • disable root ssh logins
    • /etc/ssh/sshd_config
    • set PermitRootLogin no
    • systemctl reload sshd
  • use one account per service
    • e.g., httpd
  • keep system and service accounts locked

Deleting Accounts

  1. Determine UID
    • id ACCOUNT
  2. Delete account and home directory
    • userdel -r
  3. Find other files that belong to user
    • find / -user UID
    • find / -nouser

Network Security

Secure Network Services

  • use a dedicated user for each service
  • disable unused services
  • ports below 1024 are privileged
    • use root to open them, then drop privileges
  • avoid unsecure services
    • e.g., telnet, FTP
  • 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
  • List listening services
    • netstat -nutlp
    • 0.0.0.0 means 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
  • Disable root logins
    • PermitRootLogin no
  • To only allow root login with key
    • PermitRootLogin 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 no
    • GatewayPorts no

Enable Firewall

  • Linux Firewall
    • comprised of two parts:
      • Netfilter
        • is a kernel framework
      • IPTables
        • is a packet selection system
    • iptables command controls the firewall
  • 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
      • Raw
        • used to disable connection tracking
        • rarely used
      • Security
        • used for mandatory access control
        • used by SELinux
    • cannot create custom table
    • Default chains
      • INPUT
      • OUTPUT
      • FORWARD
      • PREROUTING
      • POSTROUTING
    • Can create custom chains
      • use for custom collection 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

Configure Firewall

  • View rules
    • iptables -L displays the filter table
    • iptables -t nat -L display the nat table
    • iptables -nL displays using numeric output
    • iptables -vL displays using verbose output
    • iptables --line-numbers -L displays 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 TABLE option 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]
  • Rule specification options:
    • Specify a source: -s SOURCE
    • Specify a destination: -d DESTINATION
    • Specify a protocol: -p PROTOCOL
    • -m specifies 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
  • 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
    • iptables command does not save the state of firewall for persistence
    • Debian/Ubuntu
      • apt-get install iptables-persistent
      • netfilter-persistent save
    • CentOS/RedHat
      • yum install iptables-services
      • service iptables save
  • IPTABLES front-ends
    • Debian/Ubuntu: UFW
    • CentOS/RHEL: Firewalld

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
  • 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
    • chattr command
      • + 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
  • Creating ACLs
    • use the setfacl command
    • Create or modify: setfacl -m ACL FILE
  • ACL Format
    • User
      • u:[UID|USER]:perms Set the access ACL for a user
      • e.g., setfacl -m u:jason:rwx start.sh
    • Group
      • g:[GID|GROUP]:perms sets 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:perms sets the effective rights mask
      • e.g., prevent all users from writing to a file
        • setfacl -m m:rx sales.txt
    • Other users
      • o:perms sets the access ACL for others
      • e.g., setfacl -m o:r sales.txt
  • Create multiple ACLs at once
    • setfacl -m u:bob:r,g:sales:rw sales.txt
  • Set default ACL
    • d:[ugo]:perms sets the default ACL
      • preceded by d:
    • 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
  • chrootkit is a shell script used to detect the presence of rootkits