Security Fundamentals

Security Principles in Linux
Linux is secure by design but often unsecure by configuration
three core principles

The Principle of Least Privilege
no user, program or service should carry more permissions than necessary
every extra permission you grant is a potential weapon for an attacker

Attack Surface Reduction
attack surface is the sum of all different points where an attacker can enter the system
every open port is a door
every app is a potential window
remove vulnerabilities
  • if a printing service is not needed by a web server, uninstall it
  • if port 8080 doesn't need to be open, close it
  • if software isn't being used remove it

Defense in Depth
assume every layer will fail
  • do not rely solely on the firewall
  • do not rely solely on passwords
  • do not rely solely on file permissions

User Account Security: Strong Passwords, Account Policies
policies which mitigate risk
Enforcing Strong Passwords with PAM
PAM (Pluggable Authentication Modules) framework
sits between login/SSH and the authentication mechanism
can plugin a module into PAM which checks password strength
Install on Ubunutu and Debian
use module libpam-pwquality
sudo apt install libpam-pwquality
once installed config the file
/etc/pam.d/common-password
open file with a text editor
sudo nano /etc/pam.d/common-password
find the line referring to pam_pwQuality.so
password requisite pam_pwquality.so retry=3
can add options to the command
  • minlen=12 - 12 char minimum length password
  • difok=3 - new password has to have at least 3 different chars than old password
  • ucredit=-1 - must contain at least 1 uppercase char
  • lcredit=-1 - must contain at least 1 lowercase char
  • dcredit=-1 - must contain at least 1 digit
  • ocredit=-1 - must contain at least 1 special char

example using flags
password requisite pam_pwquality.so retry=3 minlen=12 difok=3 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1
Password Aging and Expiration
forcing users to periodically change their passwords can lead to weak passwords
can manage passwords with the Chnage Age chage command
to see current setting for use bob
sudo chage -l bob
to force bob to change his password every 90 days
sudo chage -M 90 bob
to warn bob 7 days before his password expires
sudo chage -W 7 bob
Locking Accounts
if user leaves the company or an account is suspect it can be disbaled
delting the user can delete files needed for later audits
two ways to lock an account
  1. passwd - command locks the password
    sudo passwd -l bob
  2. usermod - command modifies by adding or removing a ! (bang) to or from the encrypted password string in /etc/shadow
    sudo usermod <flag> bob
    • -L - lock the account
    • -U - unlock the account

Auditing for Empty Passwords
an account with an empty password is a major security hole
inspect /etc/shadow
if the second field is empty there is no password
to find those accounts run the command
sudo awk -F:'($22 == ""){print $1}' /etc/shadow
if command return any accounts either disable them or create a password for them

Using UFW (Uncomplicated Firewall) for Beginners
firewall Netfilter is built into the kernel
difficult to use
easier to use userspace tools

The Classic: iptables
iptables ws along time standard tool
uses a system of 'Tables' and 'Chains'
  • INPUT Chain - traffic coming into the server
  • OUTPUT Chain - traffic leaving the server
  • FORWARD Chain - traffic passing through the server (acting as a router)

an iptables command looks like
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
translates to
Append a rule to the INPUT chain. 
If the protocol is TCP and the destination port is 22 (SSH), then Jump to ACCEPT (allow it).
iptables is
  • powerful
  • complex
  • has uforgiving syntax
  • rules are not persistent by default

The Modern Red Hat Way: firewalld
default tool is firewalld
uses concept of Zones
can assign network interfaces to zones like "Public", "Work" etc.
then apply rules to zones

The Modern Ubuntu Way: UFW
UFW is a simplified interface for iptables
set up an Ubuntu firewall from scratch
  1. check if running
    sudo ufw status
    likely inactive
  2. set the defaults
    want a Default Deny policy
    firewall blocks everything unless there is a specific rule
    usually allow all outgoing traffic from the server so it can download updates
    sudo ufw default deny incoming
    sudo ufw default allow outgoing
  3. allow SSH (Do Not Lock Yourself Out)
    allow SSH before enabling firewall
    sudo ufw allow ssh
    if running on a customport
    sudo ufw allow ssh <port number>
  4. allow other services
    if box is a web server need to allow standard web traffic
    sudo ufw allow http
    sudo ufw allow https
    opens ports 80 and 443

  5. enable the firewall
    check step 3 before enabling
    sudo ufw enable
  6. verify the rules
    sudo ufw status verbose
    output
    Status: active Logging: on (low) 
    Default: deny (incoming), allow (outgoing), disabled (routed) 
    New profiles: skip 
    To Action From 
    22/tcp ALLOW IN Anywhere 
    80/tcp ALLOW IN Anywhere 
    443/tcp ALLOW IN Anywhere
    

Deleting Rules
have UFW number the rules
sudo ufw status numbered
output will be a numbered list
to delete a rule
sudo ufw delete <rule number>
Advanced UFW: Rate Limiting
can limit a port
prevents brute force attacks
denies connections from an IP address from an IP address which has attempted to initiate 6 or more connections in 30 seconds
sudo ufw limit ssh
Understanding SELinux and AppArmor
Discretionary Access Control (DAC) is the standard user/group/other permission system
owner of file makes decision
Mandatory Access Control (MAC) system makes policy-based decisions
two main MAC systems in Linux

AppArmor (Applcation Armor)
default with Ubuntu and Debian
assigns profiles to executables
profile is a text file listing what files an app can read, write or excute
  • Enforce Mode - policy is enforced
    violations are blocked and logged
  • Complain Mode - policy is monitored
    violations are allowed but logged
    used for testing new profiles

to check AppArmor status
sudo aa-status
generally no need to manually config
packages come with their own profiles which are enabled automatically

SELinux (Security Enhanced Linux)
system developed by the NSA
used in Red Hat, CentOS and Fedora
more complex and powerful than AppArmor
labels every file, process and port witha context
a policy defines which contexts can interact
to check its status
sestatus
The SELinux "Disable It" Myth
CentOS permission errors are sometimes blamed on SELinux
do not disable SELinux
error usually means labels are incorrect
to fix labels
resorecon -R /var/www/html
command looks up what labels should be for the directory and corrects them
to troubleshoot install settroubleshoot tools
when a error occurs run
sudo audi2why < /var/log/audit/audit.log
tool reads log
explains why the action was blocked
often suggests command to resolve problem

Automatic Security Updates
use unattended-upgrades tool for automatic security updates
  1. Install
    sudo apt install unattended-upgrades
  2. Configure
    sudo dpkg-reconfigure -plow unattended-upgrades
  3. Verification - config file is at
    at /etc/apt/apt.conf.d/50unattended-upgrades
    open and ensure this line is uncommented
    Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}-security";
    }; 
Kernel Live Patching
normally updating the kernel requires a reboot
Canonical offers livepatch service
allows kernel to be patched in memory
free for personal use fot up to 3 machines

Securing SSH: Disabling Root Login, Changing Ports, Fail2Ban
Disable Password Authentication
once SSH keys are working turn off password authentication
edit /etc/ssh/sshd_config
PasswordAuthentication no
ChallengeResponseAuthentication no
restart SSH
sudo systemctl restart ssh
Disable Root Login
never allow root to log in directly
edit /etc/ssh/sshd_config
PermitRootLogin no
Change Default Port (optional)
bots blindly attack port 22
configure SSH to run on port 2222
security thru obscurity

install fail2ban

Use Fail2Ban
service watches the logs
if someone fails to log in 5 times in a row, it bans theirIP address using the firewall
sudo apt install fail2ban
The default config is in /etc/fail2ban/jail.conf
should not edit it
create a local copy called jail.local
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
scroll down to the [sshd] section
customize the settings
[sshd] 
enabled = true 
port = ssh 
filter = sshd
logpath = /var/log/auth.log 
maxretry = 3 
bantime = 3600
enables SSH
sets max retires to 3
bands IP for 1 hour

Starting Fail2Ban
sudo systemctl enable --now fail2ban
Checking Status
see who is in jail
sudo fail2ban-client status sshd
list currently band IPs and list of IP addresses

Unbanning an IP
sudo fail2ban-client set sshd unbanip <dotted quad>
File Integrity Monitoring Basics
File Integrity Monitoring (FIM) tool calculates a cryptographic checksum for critical files
run a check daily
FIM tool alerts to any changes

AIDE (Advanced Intrusion Detection Environment)
popualr open source tool
sudo apt install aide
must create an initial database with clean snapshot of system
sudo aideinit
install new db as the active master database
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
to run a check
sudo aide --check
when installing new software or change config files aide will report the changes
update the database
sudo aide --update
Security Best Practices and Hardening Checklists
check list for new server
  1. Update the System
    sudo apt update && sudo apt upgrade -y
  2. Create a User - a standard user
  3. SSH Keys - copy public keys to server
  4. SSH Config - edit /etc/ssh/sshd_config
    disable PermitRootLogin and PasswordAuthentication
    restart SSH
  5. Firewall - configure UFW, allow SSH, enable UFW
  6. Fail2Ban - install and enable Fail2Ban
  7. Auto-Updates - install and enable unattended-upgrades
  8. Check Ports - run
    sudo ss -tulpn
    look at Listening ports
    disable or uninstall any unneeded ones
  9. Backups - ensure there's a backup strategy
Summary
covers
  • Mindset - importance of Least Privilege and Defense in Depth
  • Firewalls - how to use UFW to white list only necessary traffic
  • Access Control - DAC and MAC differences, never disable SELinux/AppArmor
  • SSH Hardening - banish passwords and root logins
  • Automation - use Fail2Ban for protection
    stay patched using unattended-upgrade
  • Integrity - use AIDE to detect tampered system files

key points
  • Least Privilege - never give user or service more power than necessary
  • UFW - most important firewll rule Default Deny Incoming
  • SSH Keys - always use keys for remote servers, never passwords
  • Fail2Ban - essential tool
  • Unattended Upgrades - auto-install security patches
  • SELinux/AppArmor - provides safety net if service is compromised
    fix contexts and not disable service
  • Audit - regularly check logs and listening ports
index