Linux Security: Structure, Permissions and Access

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Muhammed Dardir LinkedIn : https://www.linkedin.

com/in/muhammed-dardir

Make a list of the most critical data to your organization


Determine what the most critical processes that access
Criticality of linux Systems
that data are
Map back to what servers that data resides on
It is important to remember that although Windows has a
much larger install base, Linux is usually installed on the
most important, mission-critical systems
If you sort by price, the most expensive systems are often
UNIX or Linux-based
Linux VS Windows Most security appliances also run Linux
For security analysis, assessment, and penetration testing,
many security teams use Linux in addition to other
operating systems

Windows started as a desktop OS, but is now a respected Old: Single-user platform
server platform New; Multiple processes for multiple users at the same
time
Old: Installed on servers with many simultaneous users
UNIX took the opposite route
New: Used as a desktop OS
Ubuntu (Debian) Ubuntu is a Linux distribution
Main Linux Distributions
Fedora (Red Hat) The Fedora project is based on Red Hat Linux

type of linux operating system Main Linux Distributions Cygwin for Windows
macOS (BSD)
NOTE: Kali is based on Debian Linux
Open-source operating system with many variants
Originally developed for personal computers, but has been
ported to other platforms
Many security tools are freely available and often only run
on Linux
Linux
Linux and Windows: Desktops and Servers
Runs the Linux kernel as the "brains" of the operating
system

The Cygwin project is a fantastic solution for aiding the


transition to Microsoft Windows for those who grew up in
the Linux computer world.
Many Linux commands and utilities
Cygwin is not Linux
Is not a Linux emulator
You can compile server software for Windows
Not a replacement for running Linux on a physical hardware
Operating System comparison or a virtual machine
Cygwin
Powerful scripting within Windows
Windows can easily interact with Linux services
Cygwin installs and is supported on all versions of
Windows except Windows CE.
The Cygwin interface enables you to access all the ported
libraries and programs from Linux that you configure
Cygwin to install at setup time
Apple moved to using BSD as its underlying operating
Uses BSD as its underlying system system platform
Built on top of XNU kernel
Designed to have security built in
Many features cannot be disabled
Most network services disabled by default
Automatic updates
Gatekeeper to protect apps: Adversaries are constantly
trying to infect a computer by tricking the user into
downloading malicious software that infects a computer
MacOS system
FileVault: Computers often contain sensitive information
Privacy controls
Built-in security features Strong passwords
iCloud key chain
Sandboxing
Runtime protection
Antiphishing
macOS security Download protection
iCloud device location
Turn on firewall to control access to services
Turn off unneeded services
Limit service sharing
Securing mac'OS
Set up secure file sharing
Carefully monitor access lists
Use password assistant for stronger authentication
The short answer is all three: Windows, Linux, and MacOS
To be proficient in security, it is recommended that you
have both a Windows and a Linux system
Many security tools only run on Linux
Which Operating System Is Best for Security? Most of the popular security distros are all based on Linux
Several critical security tools are only available for Linux
Microsoft has developed the Windows subsystem for Linux
The power of virtual machines is that you can have multiple
operating systems running simultaneously
Although iOS does have a large install base, Android has
the largest install base from a mobile operating system
perspective·
Open standard with the ability for modifications and
changes to be made
Less locked down and more configurable
Recently more focused on security and integrated features
Often viewed as an operating system that is more
functionality and less security
Android Oreo significantly focused on security
More built-in security and trying to be similar to iOS
Android security
Still open operating system but more embedded security
Android features
Mobile security Now focused on "multiple layers of security, right out of the
box
Application security: Applications are rigorously tested
for security before they are available for download
Active scanning: When applications run, they are
monitored to look for suspicious activity
Android Pay: Secure payment options do not expose
credit card data
Android's security features: Virtual Sandbox: Critical data is sandboxed or isolated
from applications to minimize exposure
Device Manager: Allows for locating and securely wiping
remote devices
Android VS iOS
Built-in encryption: Cryptographic functionality is built in
to protect data at rest and in transit
Closed software that cannotbe modified or changed by
third parties
Locked down with fewer options to configure
Always had integrated security and focused on security
Designed with security at its core
Closed model unless someone jailbreaks the phone
Security is integrated into the entire architecture
Apple IOS Security
Most security is transparent to the user
Key security (that is, encryption) cannot be disabled or
IOS turned off
System security: Both hardware and security features
that support the architecture and applications that run on
the system
Encryption and data protection: Protect critical data if
the device is stolen or unauthorized access is attempted,
protecting data at rest
Network security: Complements data protection and
provides security for data in transit
Application security: Creates a platform to enable third-
features that are in IOS party applications to run in a secure environment
Apple Pay: Enables you to make secure payments
Internet services: Provide cloud-based services for
backup and capability for communication
Device control: Enables management of device to
include secure wipe
Privacy controls: Enables you to remotely access device
information such as with location services

Linux Operating System

Kernel: The core component of the operating system that The memory-resident part of an operating system that
is often referred to as the "brains" of the operating system directly interfaces with the hardware is called the kernel
Shell: The portion of the operating system with which users
and the process interact directly
operating system overview Hardware: A collection of physical components such as
the actual CPU and memory chips

Linux shells

Shell is the command-line interpreter used to run User


programs on the computer
Provides the user with an interface to the system
Shell listens to the terminal
Shell translates requests into action by the kernel and
programs
Bourne Shell "sh"
C Shell "csh"
For UNIX Bourne-Again Shell "bash"
Korn Shell "ksh"
Shell
Examples of Shells exTended C Shell "tcsh"
For DOS Command.com
Cmd.exe
For Windows
Powershell.exe
Administrators can display the currently mounted partitions
df Command with the df command

The kernel manages the hardware and the executing


processes
/ (root filesystem; top of directory hierarchy)
/dev, /devices (directory containing files used to talk to
system devices)
/usr (primary OS directory; read-only)
Logical Filesystem
/var (contains log files, queues, and so on)
/bin, /usr/bin, /usr/local, /opt (executable programs; some
SUID/SGID)
/home, /export/home (user home directories)
Linux Security: Structure,· Permissions and Access Logical Linux filesystem is made up of multiple physical
disk partitions
Disk partitions are mounted at various points in the
filesystem
Physical Filesystem
Different security options can be set on each mount point
NOTE: This is a key component of Linux: Security can be
integrated into the installation process
Protect OS binaries in /usr
Linux kernel
Prevent introduction of SUID programs and unauthorized
Filesystem Security Goals devices
Allow other software to be installed
Discourage DoS attacks
Filesystem
ro: Filesystem is mounted read-only (files and directories
cannot be modified)
nosuid: SUID/SGID bits are ignored on all programs in the SUID: File executes with. privileges of file's owner
Filesystem Security options filesystem
SGID: Temporarily grant user file group permissions
nodev: UNIX device files don't work
Allfilesystems should either be mounted read-only or
nosuid
/usr and /usr/local contain SUID/SGID programs but can be
readonly
Goal of Security Most other filesystems must be writeable but have no
SUID/SGID programs
/ filesystem contains / dev, but all other filesystems can be
Kernel services include mounted nodev
LUKS is the standard for Linux hard disk encryption
Compatibilityvia standardization
Secure against low entropy attacks
 Linux Unified Key Setup (LUKS) 
Support formultiple keys
Effective passphrase revocation
Free
Low-level network protocol support (for example, IP)
Memory and process management

Symbolic uses letters to represent the permission such as


RWX

Symbolic

Two general ways to represent permissions

Linux Fie permissions Absolute Absolute represents the permission as a number


To change permission on a Linux system, you would use
the chmod command

File Attributes

The idea was that any program which had the sticky bit set
was supposed to "stick around11 in the memory of the
operating system after the program had finished executing

sticky This was a win on programs that needed to be executed


frequently because they did not need to be read back into
memory constantly

Other Permission Bits

Other Bits in Absolute Mode

Permissions

Files Versus Directories

World-writable directories, such as /tmp, are used by


programs to hold intermediate results
What if an attacker clobbers your program's temporary file
World-writable directories and substitutes his or her own
Avoid world-writable directories if possible
Golden rules
Always set the sticky bit for world-writable directories
You can't run UNIX without SUID/SGID programs
Double-edged sword However, rogue SUID/SGID programs can easily
compromise a machine

SUID/SGID Programs Keep track of the SUID /SGID programs provided with your
operating system
Raise an alarm if new or unexpected SUID /SGID
programs appear
Umask sets default newly created file permissions umask u-x,g=r,o-w
Umask and chmod Umask reads existing umask setting chmod u=rwx,g=rx,o=r filename
Chmod changes existing file permissions chmod 754:filename
Chown changes file ownership chown user1 /home/user1
Chgrp changes group ownership chgrp support /home/user1
permissions : Chown and Chgrp Both user and group ownership can be changed at the
same time withchown
Chown will use both user and group IDs or their names
Usernames and passwords are case sensitive
User and group names are for the convenience of humans
User Account and Groups
Linux systems store ownership information with user IDs
and group IDs
Normal users
Superusers control all files, processes, and devices
Superuser A two-class security model:
Superuser is usually called root
Superusers Superuser accounts always have a UID of 0
Multiple UID 0 accounts can exist besides the root account
UID 0 account creation or access is any attacker's goal
You should never log in as root or UID 0
Anonymous login is very dangerous
Logging in as UID O provides no accountability if there are
PrivEsc
multiple accounts
Always log in as a normal user
Utilize su or sudo to escalate privileges
Linux operating systems tend to come with many service
accounts for various apps
Typically, these accounts have low UID numbers (UID <
100?, 500?, 1,000?)
UNIX systems Accounts Attackers sometimes activate these accounts as
"backdoors" into the system
If you're not using a particular service or app, remove (or
block) the account

Passwd File

Username: Name matching the entry in the /etc/passwd


file
Password: Encrypted password along with the salt and
type of encryption
Last: Number of days since the last password change
based on 1 Jan 1970
May: Number of days before the password may be
username:passwd:last:may:must:warn:expire:disable:reser changed again
ved
Must: Number of days before the password must be
changed
Warn: Number of days before the password must be
changed, so the user gets a warning message
Shadow File
Expire: Number of days before the password expires
Disable: Number of days before the account gets disabled
Reserved: Not used at this time
username:Npgeo8pfz4wuk:9479:o:10000: : : :
On most UNIX OSs, the password-expiring and password-
rotation features are disabled
PASS_MAX_DAYS: Maximum number of days a password
is valid. The default is 99,999 days
P ASS_MIN_DAYS: Minimum number of days before a
user can change.the password since the last chaµge. The
To enable, you must simply apply values to configuration default is 0 days.
files in /etc/login.defs.
Enabling Password Aging PASS_MIN_LEN: Minimum length of password (in Linux,
this valu.e is controlled by the PAM). The default is 0,
User accounts
PASS_ WARN_AGE: Number of days when the password
change reminder starts. The default is 7 days
INACTIVE: Number of days after password expiration that
accountis disabled.Value of-1 feature disabled (default).
/etc/default/useradd EXPIRE: Account expiration date in theformatYYYY-MM0
DD. Default is None
PAM stands for Pluggable Authentication Modules
System libraries handle Linux authentication
Authentication
Passwords
Four management groups
Sessions
Accounts
Configuration files are in /etc/pam.d
Edit the file /etc/pam.d/system-auth by adding the following
The pam_cracklib module checks the password against
dictionary words and other constraints
minlen= $: Minimum length of password must be$.
lcredit=-$: Minimum number oflowercase letters must be$.

Enforce Stronger Passwords ucredit=-$: Minimum number of uppercase letters must be


$.
dcredit=-$: Minimum number of digits must be$.

PAM ocredit=-$: Minimum number of other characters must be$.


Edit the /etc/pam.d/system-auth file and add/change the
difok =$:Number of characters that must be different from
Restricting Use of previous password the old password$.
pam_pwhistory: Modules remember old password uses.
remember=$: This value is the number of old passwords
remembered

Edit the /etc/pam.d/system-auth file and add/change the


following
The pam_tally module locks individual user accounts after
too many failed su or login attempts.
onerr=fail tells the system what to do when reaching a set
number of fail=lock accounts.
No _magic _root tells the system not to lock the root
account. This prevents a DoS against the root account.
per_ user keeps an account of each individual use.
Locking User Accounts AfterToo Many Login F ailures Deny=$ is the number of attempts made before account
401.6_linuxEssentials locks$.
faillog -u <user> lists the current number of bad logins
faillog-u <user> -r unlocks the account
faillog -u <user> -m -1 turns off locking on lockout of a
pmticular user
passwd -1 <user>
usermod -L <user>
You can also unlock accounts by using these commands
passwd -u <user>
usermod -U <user>

init is the first process to start init was the original boottime service starter
It is responsible for the setup of the entire user
environment
Also known as System-VStyle init
The init process starts as a process PID 1
it checks and mounts filesystems and starts necessary
services
Init is the parent process to all other processes and adopts
all orphaned processes in the user space
Tracks services only during sudden changes to the system
Unable to detect and handle sudden changes to the
Classic init system
Run level 0 means shut down the systems
Runlevel 1 means single-user mode

All init-based solutions use runlevels, which tell services Runlevel 2 means multiuser mode
how a process will start as the init process starts Run level 3 means multiuser mode with networking
Runlevel 5 means starting the system with appropriate
display manager and graphics.
Runlevel 6 means system reboot

Follows a linear process

Classic init was too rigid a solution and lacked important


features that system administrators needed
Several solutions were developed
One solution is upstart
Upstart supports parallel booting of services
It supports live system changes
It monitors the status of a service
It is an optional add-on
Upstart waiting: Indicates the initial state of processing
starting: Indicates the place where a job is about to start
pre-start: Specifies the place where the pre-start section
is loaded
Starting services at boot time
spawned: Indicates the place where a script section is
about to run
post-start: Specifies the place where post-start operations
take place
Upstart supports the following actions: running: Indicates the place where the job is fully
operational
pre-stop: Indicates the place where pre-stop operations
take place
stopping: Specifies the place where the job is being
stopped
killed: Indicates the place where the job is stopped
post-stop: Indicates the place where post-stop operations
take place; to clean up
Systemd is the name of the init daemon and also the entire
software bundle around it
Full System and Service Manager
A software platform
Systemd major functions
Provides interfaces that give functionality provided by the
Systemd kernel
Supports parallel processing
Monitors services after boot
Supports device hotplugging
Common Commands systemctl

Pros and Cons Scheduling daemon


Starts an action (in the background) at preset time
Can also be employed by users
Cons
Uses crontab file to store the jobs that are going to run
Cron daemon (crond) works in sync with the system clock

Reducing the number of packages in a system is a


common practice
Minimizing the storage requirements to run in smaller
environments
Important for security to reduce attack surface
Minimizing Packages
Use XFCE instead of gnome
Reducing package count
Drop unnecessary packages
HINT: The. entire X11 subsystem is an optional package
and can be removed ifit is not needed.
Configuration managementtools are an important aspectfor
increasing the overall security of your Linux environment
Keeps systems configured the same
Many different players in the market
Package control Both open_source and commercial options
Originally a development operations tool
Open-source and commercial version
Limited prebuilt support
Puppet Commercial version inostfeature rich
Written in Ruby
Requiressomeskill to configure
Has some support for Windows systems
Configuration Management tools
Oldest configuration management tool
Both open-source and commercial version
Easytouse
CFEngine
Moved from focusing on a local data center to being more
cloud~based
Automation frameworkthat is paired with a monitoring and
modeling compliance engine
Free software platform for configuring and managing
computers
Performs software deployment, task execution, and
configuration management
Ansible Manages nodes over SSH
EX :Tools
Controlling machine performs orchestration and
management
Uses controlling macliines and nodes Nodes are systems that are being managed
Communication occurs through a JSON protocol
Open-source software
Software agent that automates the infrastructure
Allows for quick provisioning, managing, and adaption of
Chef the infrastructure
Turns the infrastructure into code
Chef Development Kit
Key components: Chef Server
ChefClient
Allows for configuration and management of data centers,
infrastructure, and applications
Built for speed, scale, and the complexity of the cloud
SaltStack Utilizes fasfremote execution engine
Provides a flexible but scalable approach to systems
management
If a service is managed by inetd, you can close the port by
finding the line in the /etc/inetd.conf file for the service and
/etc/inetd.conf comment it out by adding # to the beginning of the line
control and close down unneeded ports /etc/xinetd.d Locate the service file name; set disable optionto yes in file
/etc/rc.conf Comment out lines or change the value from YES fo NO
Passwords can be stolen or cracked
Multifactor authentication adds another layer of
authentication
For critical services such as SSH, multifactor authentication
must be used
SSHKeys
Google Authenticator
Several options are available for multifactor authentication
for SSH FreeOTP
SSH MultiFactor Authentication Authy
Duo
Some are free, and others are commercial but are minimal
in cost

Port control and port restriction SSH key management is generally ad hoc
Private keys for your SSH are generally stored on your
local computer with minimal, if any, security to protect them
Solutions exist to centrally manage SSH keys
SSH/TLS Key Management Manages user roles
Manages keys
KeyBox web-based SSH manager
Manages simultaneous SSH sessions across multiple
systems
Puppet also can manage SSH keys
Logs the switch of the user to the other user
su (switch user) is often used to elevate to root No other control; the user has all root privileges
All users know the root user's password
Users only know their own password
sudo gives granular control of execution Allowed to execute only the commands specified in
Sudo and Sudoers sudoers file
effective user ID
effective group ID
environment list
Security policy that can be set with sudo working directory
umask
SELinux role
scheduling priority
The sysctl utility audits and can dynamically change
settings within a Linux system while the system is running
Sysctl is used to modify kernel settings at runtime
Running sysctl -a shows you all the variables for the system
1Pv4 and 1Pv6 settings
Hardening and Securing Linux Services
Execshield
Sysctl configures network and system settings Network attack preventions
Logging attacks
Address Space Layout Randomization
Recommended way to edit the variables is to edit the / etc/
sysctl.conf file
To see all the variables for the system, run sysctl -a. To
write to a variable using the sysctl command, enter sysctl -
w variable=value. The -w option tells sysctl to write
the value to the variable
Allows a packets' sender to partially or completely specify
the route the packet takes through the network
The danger is it allows for two-way spoofed communication
It is possible for a Linux system to be part of a source
SysctI Hardening : Source routing
routing path
SysctI Hardening Set the net.ipv4.conf.default.accept_source_route to 0
sysctl ·a I grep source_route
net.ipv6.conf.all.accept_ra=0
Disable router advertisement
net.ipv6.conf.default.accept_ra=0

Settings for hardening IPv6 include : net.ipv6.conf.all.use_tempaddr=2


Enable IPv6 privacy extensions
net.ipv6.conf.default.use_tempaddr=2
Rate limiting net.ipv6.icmp.ratelimit- limit in time (ms), default 1000
The purpose is to assist in the prevention of exploits that
require the use of known address locations for particular
process functions such as the return function
Randomizes process memory address space
Address Space Layout Randomization (ASLR) Makes successful exploits and the resulting control of
execution much harder
Effectiveness of ASLR is limited by the amount of available
Address Space Layout Randomization (ASLR) entropy, which varies from platform to platform
For ASLR to be useful, all segments of a process's
memory space must be randomized
ASLR can be disabled per application with setarch
Recommended to remove setarch utility from hardened
Sysctl Hardening- IPv6 systems
Modprobe is used to add loadable kernel modules (LKM)
to the kernel or remove them from the kernel
Modprobe exists in /etc/modprobe.d directory
Reduces exposure to exploits
Disable or blacklist unneeded kernel modules
Disabling Unneeded Kernel Modules with Modprobe Reduces code complexity
This gives information on other dependent modules to
Modinfo enables you to see what modules do assist in determining which module to disable or blacklist
find /lib/modules/'uname -r' -name *modulename*
Linux kernel can have built-in modules or loadable dynamic
modules
Gives flexibility to the kernel
Don't have to recompile the kernel for everything that is
encountered
Disabling Dynamic loading After Boot The risks of having dynamic loading after boot is that a
rootkit with any functionality can be inserted into the kernel
with root privileges
Disabling loadable kernel modules severely limits the
vector of a malicious actor injecting a malicious kernel
module
SELinux is a robust solution for hardening the Linux system
with Mandatory Access Control (MAC) mechanisms
Separation between policy and enforcement
Security Enhanced Linux is a loadable kernel module
Controls over process initialization, inheritance, and
specific to security
Linux Hardening execution
SELinux
Many more controls available
Most modern Linux releases support SELinux kernel
module
Operating System Enhancements Overall controls what programs can do
Deny access Will not use SELinux access on object
Discretionary Access Control (DAC)
Allow or default SELinux access policy applies

SELinux Policy
When using categories, the level is written as
Each level is a sensitivity-category pair, with categories sensitivity:category-set.
MLS/MCS being optional: When not using categories, the level is written as
sensitivity.

Grsecurity is a set of patches for the UNIX kernel that


enhance security
MAC tool with role-based access control support Gradm utility to manage RBAC
PaX memory protection Paxctld to manage PaX
File System Hardening
Kernel Auditing
Trusted Path Execution (TPE)
PaX protects against cormption of memory by containing
many of the grsecurity mitigations
Prevents memory from being overwritten
Grsecurity also includes PaX Provides memory corruption defenses
Provides NOEXEC and runtime code check
Places flags in the executable header
Download grsecurity for your distribution
Customize with the menuconfig
Install
Compile and then install
Install gradm and paxctld
Set passwords for admin and shutdown
Start learning mode gradm -F-L /etc/grsec/learning.logs
Start
Apply output file as policy gradm -F -L /etc/grsec/
learning.logs -0 / etc/ grsec/policy
PAX: Control and mark binaries that are to be used by the
system
Address Space Protection: Manage how to protect
memory on this system; this includes control for buffer
overflows and variable storage.
Role-Based Access Control (RBAC) options: Control
the configuration of the roles and ways to manage access
Grsecurity control requests
File System Protection: Configure options for protection
of the file system and restrictions around what changes
In grsecurity, you can customize the following general
users can make to the file system.
areas
Kernel Auditing: Control what is audited on the system
and what level of detail is stored
Execution Protections: Control what binaries can be
created and what changes can be made to existing binaries
Network Protections: Manage changes to the TCP/IP
protocol stack and how it works
Sysctl Support: Allow modification of settings at runtime
Logging Options: Control the volume and level of logging
that is perfotmed
gradm -S check status
gradm -E to enable
gradm -D to disable
gradm commands gradm -C policy control
gradm -a login to a role
gradm -u logout
gradm -F -L learning mode

App Armor is a Linux kernel module that you can use to


restrict the capabilities of programs.
Behavior-based protection and dynamic protection
AppArmor Restricts program'sresource access and privilegelevel Controls are per application
Includes manydefault poHcies
Combines static analysis and learning-based tools
Muhammed Dardir LinkedIn : https://www.linkedin.com/in/muhammed-dardir

utmp: Gives a complete picture of users' logins at which


terminals, logouts, system events, current status of the
system, system boot time
wtmp: Provides historical data of utmp
btmp: Records only failed login attempts
dmesg: Is a display or driver message
Log files of interest
messages: Contains global system messages
maillog: Contains the messages from mail server
secure: Contains all security-related messages on the
system
last -f /var/\og/wtmp
last
Key Log files utmp ,wtmp,btmp last -f /var/\og/mp
utmpdump utmpdump /run/utmp
Utmp and wtmp are the two main log files; they cannot be
read with any text editor utility or text-reading program such
as cat. They must be read with the who, last, or utmpdump
Configuring and monitoring logs
command.
dmesg does have some data that is similar to the
messages log file, but the drnesg log contains strictly the
information about the boot process of the system from the
Dmesg is both the special log file and the command to point of initial startup all the way through the loading of the
read the log file itself entire OS and kernel.
They do serve different purposes: dmesg captures only
the kernel's messages of any log level, whereas the
messages log stores valuable, nondebug, and noncritical
messages. The messages log should be considered the
general system activity log, which is a fantastic resource for
Dmesg and messages often are thought to contain the troubleshooting and anomaly hunting
same logging information The messages log file is generally located in /var/log/
messages
Standard for message logging
Any part of the system, including applications, drivers, and
other daemons, can make log entries
A facility code is used to specify the type of program that is
logging the message
Messages with different facilities may be handled
differently
The workhorse of the Linux logging system is the system
logging daemon, or syslogd. This daemon is normally
started from the system startup (re) scripts when the
system goes into run level 1
Once it is running, almost any part of the system, including
applications, drivers, and other daemons, can make log
entries

Syslog facility codes A facility code is used to specify the type of program that is
logging the message
The most common facility codes used are kern, user,
daemon, auth, syslog, and auth priv

Syslog severity levels

Sender authentication
Message confidentiality
Message delivery and replays
Syslog doesuot, by default, encrypt the traffic, so syslog
traffic is inherently not confidential, and all traffic is sent in
cleartext

Syslog security considerations Denial of service


Unreliable delivery
Message prioritization and differentiation
Syslog does not have any authentication orverification; it
Syslog security wiU simply acceptthe logs from anysource. Any source
qould send a tremendous amount of noise, causing the
server to have to drop legitimate syslog traffic destined for
Logging with syslog and alternatives Syslog it,
Syslog configuration Configuration file is syslog.conf
Syslog Next Generation (syslog-NG) was developed to add
additional security to remote system logging and provide
for additional filtering options for the log files
Replacement to syslog
Developed to add additional security to remote system
Syslog-NG
logging
Additional filtering
Sends data with TCP
An alternative to syslog for both local and remote logging is
the rsyslog daemon.
Rsyslogd is a system utility providing support for message
logging.
Supports syslog.conf
Rsyslog Supports regex for advanced filtering
Uses configuration file /etc/rsyslog.conf or /etc/rsyslog.d/
*.conf
The main configuration file /etc/rsyslog.conf or an
alternative file, given with the -f option, is read at startup
Logrotate is configured in the aptly named /etc/
logrotate.conf.
Logrotate.conf starts with definitions of some global
options. These options are used as defaults for later entries.
Monitoring and Attack Detection
daily, weekly, monthly, size
missingok
Directives include
logrotate rotate <n>
create <perms> <owner> <group>
postrotate ... endscript
Closing and reopening the logfile
sharedscripts
Remove /etc/cron.daily/ syslogd
Additional directives for compression and emailing files
Protects against log wiping
Denial of service possibility
centralized logging Needs a lot of disks for large environments
One machine holds a lot of sensitive information
Easy to search and scan
The auditd subsystem is an access monitoring and
accounting solution for Linux that is developed and
maintained by Red Hat.
Command execution logging
File access logging
Directory access logging
Network connection logging

auditd Lots of documentation for rules especially with CIS (Center


for Internet Security)
Rules controlled by audit.rules and/ or the use of the
auditctl command
Has a suite of tools to review the generated logs
ausearch, aureport, and autrace
auditctl -I: Lists all the currently running rules within auditd
auditctl -s: Shows the current status of the auditd daemon.
auditctl -b: Sets maximum number of outstanding audit
buffers allowed. If all buffers are full, the kernel consults
the failure flag for action
auditctl -f: Sets the failure flag as 0, 1, or 2. This option
enables you to determine how you want the kernel to
handle critical errors. If set to 0, audit messages that could
not be logged will be silently discarded. If set to I,
messages are sent to the kernel log subsystem. If set to 2,
auditd rules file example
it will trigger a kernel panic.
auditctl -R: Enables you to read audit rules from the file
specified. This capability is useful when you are testing
some temporary rules and want to use the old rules again
from the audit.rules file
Monitoring and accounting with Auditd Auditd
auditctl-a: Is used in conjunction with -S for system call
auditing. The options for -a are action and filter, which are
set to specify when a certain event is logged.
auditctl -D: Deletes all the rules running in the auditd
daemon
ausearch -k
ausearch -m LOGIN --start today-i
ausearch -a 7618
ausearch ausearch -f /etc/ssh/sshd_config -i
autrace autrace /usr/bin/find
aureport -x -summary
aureport aureport --failed
aureport --failed
Message type, -m
When the logs occurred, -start
If you want to look through these logs you need tvvo main Key phrases that mark logs by the rule, -k
tools: ausearch and aureport. Ausearch enables you to look
through the logs based on the following The audit event Id, -a
The filename, -f
The -i switch tells ausearch to interpret numeric entities as
text because some field will only be numeric and not text at
all.
auditctl -w /etc/sysconfig/ -p rwa -k sysaccess
auditctl -w /sbin/modprobe -p x -k kernel_modules
Auditd examples
auditctl -W /sbin/modprobe -p x -k kernel_modules
auditctl -W /sbin/modprobe -p x -k kernel_modules

Many utilities have been built for Linux


Better visibility
Reducing the attack surface
Goals for enhancing OS security
Controlling the damage
Early detection

Enhancing the Overall Security Always identify the overall risk that is going to be reduced
Determine if the solution is the most cost-effective way of
reducing the risk
WARNING- WARNING - WARNING
Often, security professionals criticize a tool because it is
either old or does not solve all security problems

understanding of security Instead of trying to find fault, ask yourself whether the utility
helps or hurts your overall security
The ultimate question to always ask is based on the cost
that is required to implement the solution, whether the
reduction in risk is worth the overall effort
Security is about visibility, baselining, and automation; all
three are very powerful components of Linux
It is important to understand what is running on a system
and what is happening on the system
There is no such thing as an invisible adversary
Many people always look for third-party tools when Linux
has a vast area of built-in capabilities
ls
Shows network connectionson a system
Network connections
Routing tables
Used to printout
Intetface statistics
Connections
netstat
Command-line tool to understand what's happening from a
Using built-in commands and security features network perspective
-a Show all ports
-l Show all listening ports
help -at Show all TCP ports
-au Show all UDP ports
-s Show the statistics for each protocol
Shows active processes thafare running onthesystem
Basic but essential process .. management tool
Shows running-processes
Displays process information to include CPU usage,
ps memory usage,. command name
ps -ef Show all running processes
help ps -C apache2 Shows process by name
Four powerful built-in commands
ps --sort=pcpu Sort by CPU utilization
ps -ef lgrep syslog
Provides a dynamic, real-time view of a running Linux
system
401.6_linuxEssentials
While top is running, press z to allow for color coding of
top different processes
While top is running, press c to allow for the full path of the
file to be displayed
some tricks with top.
While top is running, press Shift-p to sort by CPU utilization
Start top using the -u option followed by a username to see
all process details associated with that user
Displays the1ast10 lines of a file by default and is . useful
for log files
tail tail -f-s 5 /var/log/messages
tail -c 500 /var/log/messages
the power of I and grep
Two versions : Open source and commercial version
Focused on file integrity checking
Writes alertsto logs
Tripwire
Intrusion detection through integrity checking
Creates a "secure" database of file and directory attributes
Can include SHA signatures for verification
Open source
File integrity checking plus other features
Can be centralized managed and controlled
Checks ports and executable files
A-host-based intrusion detection system-(HIDS)
Contains various features to both prevent and, detect host-
Samhain
based attacks

When it comes to file integrity checking on Linux, you have Can monitor multiple operating systems
Configuring integrity checkers many options Open~source multiplatform application
Features
Detection of rogue executables
Features Rootkit detection
Port monitoring
Log file analysis and correlation
Open source
Runs on several different operating systems
Breadth offeatures and capabilities
Integrates host-based intrusion detection
Comprehensive protection
OSSEe File integrity checking
Log monitoring
Rootcheck
Process monitoring
Send emailalerts and alert logs
Integrates with SIEM
Firewalls are critical to manage and filter traffic
Network firewalls provide a boundary defense
Host-based firewalls are needed to complement network
firewalls
With Linux, the same software can provide both network
and host-based firewalls
Using the same software allows for better control,
manageability, and scalability across the enterprise
In Windows, there are host-based and network-based
firewallsoften made by different vendors with minimal
relationships
Built-infirewall (host or network) for Linux ·Powerful and customizable
Many free scripts and GUis available for simplifying
The Linux kernel includes IP Tables
configuration . and maintenance
Firewalls Stateful firewall with NAT capability
Flush any existing rules iptables -F
iptables -P INPUT DROP
Set our default policy to drop all packets iptables -P OUTPUT DROP

help iptables -P FORWARD DROP


Append this rule to the input chain (-A INPUT), so we look
at incoming traffic
Check to see whether it is TCP (-p tcp)
iptables -AINPlJT -,p tcp --dport ssh ·-J ACCEPT If so, check to see whether the input goes to the SSH port
(--dport ssh)
If so, accept the input (-j ACCEPT)
Another option for firewalls in Linux is firewalld

Linux Firewalls Dynamically managed firewall


Supports zones to define trust level for each interface
Eirewalld
Changes can be made in theruntime environment
Firewalld D.,.Bus allows applications to adapt firewall.
settings

firewall features

Subsystem of the Linux kernel to provide classification and


filtering of network packets
Replaces netfilter
Less code duplication and higher throughput
nftables
Configured with nft
Sample command to drop outbound packets with a
destination address of l0.10.10.10: nft add rule ip filteroutputip daddr 10.10;10.10 drop
A default install of a Linux system is not necessarily secure
Additional services and components that are installed can
often be compromised
Default configuration options often contain vulnerabilities
Individuals who use Linux do not necessarily understand
how to secure a system
Manual configuration can be very time consuming
Scalable way to secure a system
Security can be defined once and scaled across the
PROS enterprise
Automation of the hardening process
Can be used as a validation method in auditing
Hardening scripts PROS and CONS
Blindly applying security can be dangerous
Security with no clear metrics makesvalidation difficult

PROS Person applying the script does not necessarily learn or


understand security
Oifferent systems require different security, so a one-size-
fits-all approach does not always work
Bastille is a program that runs a series of~criptstochange
the configuration of your _ Linux system to harden itto
industry best practices
Audits and sets the security settings of a Linux system
Bastille
Also educates aboutsecurity as you go through it
Allows for user - decided customized security
The Center for Internet Security (CIS) is a volunteer project
that does exactly that
Censensus guide with steps to make system secure
Hardening tools
Center for Internet Security (CIS)
Security Utilities Using hardening scripts Scoring tools
Free for your use
Provides details on how to properly secure a system
Audits for many comp Hance frameworks Basel II, GLBA, HIPAA, PCIDSS, and SOX
Available authentication methods
Lynis Expired SSL certificates
Outdated software
ltems that Lynis audits
User accounts without passwords
Incorrect file permissions
Firewall auditing
One of the methods adversaries use to maintain
persistence on a system is by installing a rootkit onto the
computer
Contrary to its name, a rootkit does not provide root
access, but once adversaries obtain root access, they
install a rootkit to cover their tracks and allow access in a
covert manner
The main premise behind a rootkit is to not get caught;
therefore, it can be tricky to detect
Often used for kernel-level rootkits
Will work with file-level rootkits but often most effective with
file integrity checking
Have been known to generate false alarms, so useful as an
initial indicator but not a conclusive decision
rkhunter (Rootkit Hunter)
Rkhunter (Rootkit Hunter) is a UNIX-based tool that scans
for rootkits, backdoors, and possible local exploits.
Compares hashes of important files to online databases of
known good hashes
Rootkit Detectors
Capable ofwhitelisting
Mails you if an alert is found
rkhunter rkhunter --update
Advisable to set up with crontab or timers for scheduled rkhunter --propupd
checks
rkhunter -c --enable all --disable none
/var/log/rkhunter.log
Run the rkhunter with rkhunter -c --enable all --disable none
command to complete a check of the system
When the check is complete, review the log within /var/log/
rkhunter.conf
Chkrootkit (Check Rootkit) is a classic UNIX-based utility to
assist system administrators in checking their system for
known rootkits.
Chkrootkit (Check Rootkit)
Checks system for suspicious processes and known bad
Chkrootkit
files
The command to run a scan is chkrootkit
Common false positive on a mail server is Bindshell infected on port 465
The UNIX chroot() restriction is an application-isolation
feature that must be enabled on an application-
byapplication basis.
Applications may call chroot() to isolate themselves to a
particular directory
If attackers compromise an application, they have only
limited access to the system
Some apps have built-in chroot(): TFTP, (anonymous) FTP,
BIND, and SSH
For other apps, such as Apache, use the chroot wrapper
chroot() program
Helper programs and shared libraries
Have to discover and copy all application dependencies
into chroot() directory Application and system configuration files
Device files (tricky)
Look for preconfigured directories provided with OS
(BIND, FTP)
Applications with complex dependencies may be
impossible to chroot()
LXC interface for the Linux containment system
Allows for creation and distribution of containers
Middle ground between chroot and virtualized
environments
Creates an isolated environment running on a single kernel
Operating system level containers
Kernel namespaces (ipc, uts, mount, pid, network,ahd
user)
Apparmor and SELinux profiles
Seccomp policies
Uses the following Kernel features
Chroots (using pivot_root)
Kernel capabilities
CGroups
Cgroups and namespaces are the core of the kernel that
allows for the isolation of different applications
Developed by Google
ControLthe isolation of system resources
Cgroups Govern the system resources
The Core of Containers Cgroups and namespaces Key resources are CPU and memory
Control resources for a group of proce,sses
Developed by IBM
Obtain system resources that are needed

Linux LXC / Containers namespaces Presentthe resources to the application


Appear to be dedicated to the application
Chroot, Containers, and Virtualization Isolation for a single process
Original Linux containers
Operating system level virtualization
Lxc Allows for multiple operating system virtualizations· ona
single host
Keyfeatures cgroups and namespace

Comparison of Container Single application LXC containers


More portable arid flexible containers
Easy to deploy, replicate, and move application workloads

docker Single process and stateless


Based on open standards
One of the leaders in containers
Creates filesystem that contains the application and all
docker
components needed to run it
Application will run the same in all environments
Applications are isolated to achieve a level of security
Containers and virtual machines are similar in being able
isolate and perform resource allocation
They use a different architectural approach
Containers are more compact and portable

Container VS VM Virtual machines contain the entire OS


Containers contain the application and associated files

Virtualization is a key aspect of both running a data center


and utilizing a security lab
Virtualization allows for more scalable use of hardware in a
data center
Provides virtualization capability to Linux
Utilizes kernel-level isolation
Virtualization -V-Server
Can run multiple virtualized environments simultaneously
Provides security controls to properly isolate each virtual
machine
Uses segmented routing, chroot, extended quotas, and
some other standard tools
Before package managem:enttools, softwarehad to be
compiled and manually track all dependencies
Software is distributed in precompiled packages

Overviwe Packages contain binaries and dependencies that are


required for the software to run
Package management tools monitor updates and changes
so that software upgrades can automatically happen
Download validation: Verify the download is valid and
from a trusted source
Installation of dependencies: Determine dependencies
and make sure they are installed
Binary format: Install precompiled applications to
minimize dealing with source code

Linux package management Features Key features of Linux package management tools Standard locations for installations: Use standards to
install files in common locations to enable reuse of code
Deploying package management strategies such as libraries
User experience components: Add features to make it
easier and enhance the user experience
Verification of installation: Verify the install was done
correctly and make sure it is a stable install
Debian package management is based on the tool dpkg
Thecommon package management solution is "APT"
Packages often have the extension .deb
Often cqmpatible with Ubuntu (be careful with declared
dependencies)

advanced package tool "apt" Easy-to-use syntax and commands


apt-get
apt-get install package-name: Installs the specified
software with all associated dependencies
apt-get remove package-name: Removes the specified
software but does not remove dependencies
common options for APT apt-get update: Updates the system database of software
updates that are available
apt-get upgrade: Upgrades all the software with the
available updates