Last update: Tue Aug 13 04:26:49 UTC 2019 by @luckylittle
# USING YUM TO MANAGE SECURITY ERRATA:
yum updateinfo --security # security related updates
yum updateinfo list updates | grep Critical # identify critical RHSAs
yum updateinfo RHSA-2018:1453 # view RHSA details
yum updateinfo list --cve CVE-2018-1111 # what needs to be updated to fix CVE
yum update --cve CVE-2018-1111 # resolve CVE# SECURING SERVICES:
ss -tlw # open ports in the listening state
# CUSTOMIZING YOUR SSH SERVICE CONFIGURATION:
vi /etc/ssh/sshd_config
PermitRootLogin no # do not allow root to SSH to this machine
PasswordAuthentication no # force only key-based authentication
# ALLOW/DENY USERS & GROUPS:
# The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups
AllowUsers [email protected].* # this would need PermitRootLogin yes
AllowUsers [email protected]
AllowUsers [email protected]/24 [email protected]
# If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. The available criteria are User, Group, Host, LocalAddress, LocalPort, and Address:
Match Address 192.168.0.? # 192.168.0.[0-9] network range
PermitRootLogin yes
systemctl reload sshd# SUDO:
su # switches to the target user (which is root by default), but provides a normal shell with the same environment as the user who invoked the su command
su - # switches to the target user and invokes a login shell based on the target user's environment. A login shell resets most environment variables, including the target user's PATH
visudo
vi /etc/sudoers
Defaults timestamp_timeout = 1 # require password every minute (0 = every time it's used)
User_Alias FULLTIMERS = millert, mikef, dowdy
Runas_Alias OP = root, operator
Host_Alias SERVERS = master, mail, www, ns
Cmnd_Alias REBOOT = /usr/sbin/reboot
root ALL = (ALL) ALL # who where = (as_whom) what
%wheel ALL = (ALL) ALL # we let any user in group wheel run any command on any host as any user
FULLTIMERS ALL = NOPASSWD: ALL
lisa SERVERS = ALL
bob SERVERS = (OP) ALL : 128.138.242.0 = (OP) REBOOT # the user bob may run anything on the SERVERS and can run reboot on 128.138.242.0 machines as any user listed in the OP Runas_Alias (root and operator)
sudo # resets the PATH variable based on the 'secure_path' directive in the /etc/sudoers file
sudo -i # changes to the root user's home directory and opens an interactive login shell based on the root user's environment variables
# This chapter is not covered in large detail as it is part of a different document
# An example of a typical 'ansible.cfg' file:
[defaults]
inventory = ./inventory
remote_user = user
ask_pass = false
[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false# CREATION OF ENCRYPTED DEVICES AT INSTALLATION USING KICKSTART:
autopart --type=lvm --encrypted --passphrase=PASSPHRASE # use automated partitioning
part /home --fstype=ext4 --size=10000 --onpart=vda2 --encrypted --passphrase=PASSPHRASE
part pv.01 --size=10000 --encrypted --passphrase=PASSPHRASE # encrypting an LVM physical volume# ENCRYPTING DEVICES WITH LUKS AFTER INSTALLATION:
parted -l # lists partition layout on all block devices
parted /dev/vdb mklabel msdos mkpart primary xfs 1M 1G # msdos label type, primary xfs type partition from 1M to 1G
parted /dev/vdb print
cryptsetup luksFormat /dev/vdb1 [--key-file /path/to/file] # this will encrypt the drive
cryptsetup luksDump /dev/vdb1
cryptsetup luksOpen /dev/vdb1 example # this will decrypt the drive
ls /dev/mapper/example
mkfs.xfs /dev/mapper/example
mount -t xfs /dev/mapper/example /encrypted
umount /encrypted
cryptsetup luksClose example
cryptsetup luksAddKey --key-slot 1 /dev/vdb1 # enter original passhphrase (or key-file) and the new passphrase
cryptsetup luksChangeKey /dev/vdb1 # change passphrase# PERSISTENTLY MOUNTING LUKS FILE SYSTEMS:
cat /etc/crypttab
decrypted1 /dev/vdb1 none _netdev
decrypted2 UUID=43d8995e-b876-4385-b124-7e402446d6c7 none _netdev
cat /etc/fstab
/dev/mapper/decrypted1 /encrypted xfs _netdev 1 2# NBDE - UNATTENDED DEVICE DECRYPTION AT BOOT TIME:
yum -y install tang # Tang servers validate the keys
systemctl enable tangd.socket --now # tangd service binds to the 80/TCP port
firewall-cmd --zone=public --add-service=http --permanent ; firewall-cmd --reload
cd /var/db/tang # cryptographic keys are generated at first start
jose jwk gen -i '{"alg":"ES512"}' -o signature.jwk # creating new keys manually
jose jwk gen -i '{"alg":"ECMR"}' -o exchange.jwk # creating new keys manually
mv -v gxB7oqYiEu3zrLay.jwk .gxB7oqYiEu3zrLay.jwk # rename both old keys to have leading period
mv -v k25k6PbmgUu-pWWUb210x.jwk .k25k6PbmgUu-pWWUb210x.jwk
yum install clevis clevis-luks clevis-dracut # Clevis clients reach out to tang servers
clevis luks bind -d /dev/vda1 tang '{"url":"http://demotang.lab.example.com"}'
luksmeta show -d /dev/vda1 # verify that Clevis key was placed in LUKS header
dracut -f # enable Dracut to unlock encrypted partitions using NBDS
systemctl enable clevis-luks-askpass.path # when decrypting non-root file system
# SSS policy which defines three Tang servers, and requires at least two of them to be available for automatic decryption to occur
cfg=$'{"t":2,"pins":{"tang":[\n
> {"url":"http://demotang1.lab.example.com"},\n
> {"url":"http://demotang2.lab.example.com"},\n
> {"url":"http://demotang3.lab.example.com"}]}}'
clevis luks bind -d /dev/vdb1 sss "$cfg"# JSON format of the above cfg example:
{
"t": 2,
"pins": {
"tang": [
{
"url": "http://demotang1.lab.example.com"
},
{
"url": "http://demotang2.lab.example.com"
},
{
"url": "http://demotang3.lab.example.com"
}
]
}
}# USBGUARD:
yum -y install usbguard
yum -y install usbutils udisks2 # provides lsusb, udisksctl
usbguard <list-devices|allow-device id|block-device id|reject-device id|list-rules|append-rule rule|remove-rule id|generate-policy>
systemctl enable usbguard --now
usbguard generate-policy > /etc/usbguard/rules.conf # authorizes the currently connected USB devices
systemctl restart usbguard
usbguard list-rules
# Rule output example:
1: allow id 1d6b:0002 serial "0000:00:04.7" name "EHCI Host Controller"
hash "CsKOZ6IY8v3eojsc1fqKDW84V+MMhD6HsjjojcZBjSg=" parent-hash
"qiR4Ubbd7AIXLCz201hJYzaO9KIrOvqqRgqs2vM2NOY=" with-interface 09:00:00# AUTHORIZING A DEVICE TO PERSISTENTLY INTERACT WITH THE SYSTEM:
usbguard list-devices # if a new USB device is attached to the system after the default policy is generated it is not authorized to access the system and is assigned a block rule target
usbguard allow-device 6 # will not persist across reboots
usbguard allow-device -p 6 # will add it to /etc/usbguard/rules.conf and persist
systemctl restart usbguard
usbguard list-devices
usbguard list-rules
usbguard watch # watch terminal for IPC activity# PREVENTING A DEVICE FROM INTERACTING WITH THE SYSTEM, WHITE/BLACKLISTING:
usbguard block-device <ID> # set its rule target to block
usbguard list-devices --blocked
usbguard reject-device <ID> # set its rule target to reject
usbguard generate-policy -X -t reject \
> /etc/usbguard/rules.conf # generate a new base policy with a reject rule target that will ignore any additional USB devices that'll try to interact with the system
grep usbguard /etc/group # 'groupadd usbguard' & 'usermod -aG usbguard richard' if needed
vi /etc/usbguard/usbguard-daemon.conf
RuleFile=/etc/usbguard/rules.conf # do not edit this file directly, but rather elsewhere and then move it here
IPCAccessControlFiles=/etc/usbguard/IPCAccessControl.d/
IPCAllowedGroups=usbguard
usbguard add-user -g usbguard --devices=modify,list,listen --policy=list --exceptions=listen
# RULE OPTIONS:
allow/reject name <DEVICE_NAME> serial <SER_NUM> via-port <PORT_ID> hash <HASH> with-interface <INTERFACE_TYPE>
# RULE OPERATORS (via-port <OPERATOR> {...}, with-interface <OPERATOR> {...}):
all-of # must contain all specified values to match
one-of # must contain at least one
none-of # must not contain any
equals # must contain exactly the same
equals-ordered # must contain exactly the same also in the same order
# RULE CONDITIONS:
localtime(time_range) # true if local time is in the range
allowed-matches(query) # true if device matches query
rule-applied # true if rule currently being evaluated ever matched device before
rule-applied(past_duration) # same as above, but if it matched devce in the past duration of time
rule-evaluated # true if was ever evaluated before
rule-evaluated(past_duration) # same as above, but if it was evaluated in the past duration of time
random # probability is 0.5 by default, can be changed by p_true
true
false# CREATING POLICIES THAT MATCH A SPECIFIC DEVICE:
allow 1050:0011 name "Yubico Yubikey II" serial "0001234567" via-port "1-2" hash
"044b5e168d40ee0245478416caf3d998"
reject via-port "1-2" # allow Yubikey on a specific port, reject all other devices on that port
# CREATING POLICIES THAT MATCH MULTIPLE DEVICES `{ interface class:subclass:protocol }`:
allow with-interface equals { 08:*:* } # allow USB mass storage devices (class 08), deny all other via implicit rule
# REJECT DEVICES WITH SUSPICIOUS COMBINATION OF INTERFACES:
allow with-interface equals { 08:*:* }
reject with-interface all-of { 08:*:* 03:00:* }
reject with-interface all-of { 08:*:* 03:01:* }
reject with-interface all-of { 08:*:* e0:*:* }
reject with-interface all-of { 08:*:* 02:*:* } # this whole block allows keyboard-only USB if there's not one already plugged
# APPLY THE POLICY CHANGES:
install -m 0600 -o root -g root ~/rules.conf /etc/usbguard/rules.conf ; systemctl restart usbguard# DESCRIBING THE PAM CONFIGURATION FILE SYNTAX:
# Application configuration files in /etc/pam.d/ follow a standard format for their rules - parsed and executed top to bottom:
type control module [module arguments]
# 'type' can only be auth, account, password, session - in this order
# 'control' is usually just required, requisite, sufficient, optional, include, substack
# A dash (-) character in front of a type (such as "-session" near the end of the /etc/pam.d/system-auth file) indicates to silently skip the rule if the module file is missing.
# PAM looks for the modules in the /usr/lib64/security/ directory.
man -k pam_ | grep <QUERY> # e.g.: man pam_faildelay
# USING SSSD AND PAM:
yum -y install sssd
authconfig --enablesssd --enablesssdauth --update# PREPARING FOR CONFIGURATION UPDATE:
authconfig --savebackup=/root/pambackup
authconfig --restorebackup=/root/pambackup # restore process doesn't remove the links to your *-local files. It only restored the *-ac files and preserved your custom modifications.
# authconfig modifies only the *-ac files (/etc/pam.d/system-auth-ac and /etc/pam.d/password-auth-ac)
# most of the PAM service configuration files include the system-auth and password-auth files, which are symlinks to *-ac files
# ensure that a secondary root shell is open at all times to recover from potential errors# ONLY ALLOWING MANUAL CONFIGURATION:
cd /etc/pam.d
cp system-auth-ac system-auth-local # Make a copy of the existing system-auth-ac
cp password-auth-ac password-auth-local # ...and password-auth-ac files to use for manual configuration
rm system-auth password-auth # Remove the symbolic links
ln -s system-auth-local system-auth # Recreate the links to point to your custom system-auth-local and password-auth-local files
ln -s password-auth-local password-auth # now you can edit the custom system-auth-local and password-auth-local files without risking an overwrite by authconfig
# ALLOWING BOTH MANUAL AND AUTHCONFIG CONFIGURATION:
cd /etc/pam.d
cp system-auth-ac system-auth-local # Make a copy of the of the existing system-auth-ac
cp password-auth-ac password-auth-local # ...and password-auth-ac files to use for manual configuration
rm system-auth password-auth # Remove the symbolic links
ln -s system-auth-local system-auth # Recreate the links to point to your custom system-auth-local and password-auth-local files
ln -s password-auth-local password-auth
vi /etc/pam.d/system-auth-local # In your custom files, include the *-ac files
auth include system-auth-ac
account inlcude system-auth-ac
password inlcude system-auth-ac
session include system-auth-ac
vi /etc/pam.d/password-auth-local
auth include password-auth-ac
account inlcude password-auth-ac
password inlcude password-auth-ac
session include password-auth-ac # you can now use the custom *-local files for manual configuration, but include the *-ac files for the configuration you do through authconfig# DESCRIBING THE PAM_PWQUALITY MODULE: # man pwquality.conf
authconfig --passminlen=12 --update
grep pam_pwquality /etc/pam.d/system-auth /etc/pam.d/password-auth # these can be only specified in /etc/pam.d/ files: try_first_pass local_users_only retry authtok_type
vi /etc/security/pwquality.conf # negative values indicate/enforce the minimum number of characters required for each class
minlen = 8 # passwords must be a minimum of eight characters in length
lcredit = 0 # policy does not specify anything regarding lowercase characters
ucredit = -1 # passwords must contain at least one uppercase character
dcredit = -2 # passwords must contain at least two digits
ocredit = -1 # passwords must contain at least one other/special character# PAM_TIME MODULE: # man time.conf
vi /etc/security/time.conf # configure the pam_time module, syntax: services;ttys;users;times
sshd|login;*;!root&student;Al1800-2300 # users can only log in using SSH or the console between 6PM and 11PM on any given day. This restriction does not apply to root and student - they will be able to log in at any time
login;tty*&!ttyp*;!root;!Al0000-2400 # all users except for root are denied access to console-login at all times
games;*;!waster;Wd0000-2400|Wk1800-0800 # games (configured to use PAM) are only to be accessed out of working hours. This rule does not apply to the user waster
# PAM_ACCESS MODULE: # man access.conf
authconfig --help | grep access
authconfig --enablepamaccess --update # enables pam_access (check /etc/security/access.conf during account authorization)
vi /etc/security/access.conf # syntax: permission:users/groups:origins
+:root student: ALL # root and student users can log in from anywhere
+:(operators):172.25.250.254 # members of the operators group can only log in if they attempt access from workstation (172.25.250.254)
-:ALL EXCEPT (wheel) shutdown sync:LOCAL # disallow console logins to all but the shutdown, sync and all other accounts, which are a member of the wheel group
-:ALL:ALL # other users are not allowed to log in# LOCKING ACCOUNTS WITH MULTIPLE FAILED LOGINS: # man pam_faillock
authconfig --help | grep faillock
authconfig --enablefaillock --faillockargs="deny=3 fail_interval=60 unlock_time=600" --update
faillock # list failed login attempts
faillock --user user1 # restricts the output to a specific account
faillock --user user1 --reset # removes the failure records for a user, as a side effect516298
this also unlocks the account if it was locked
authconfig --disablefaillock --update# CONFIGURE CLIENT:
/etc/audit/auditd.conf # main config file
log_file # location of the log file, /var/log/audit/audit.log by default
max_log_file # trigger max_log_file_action when file reaches X MB
max_log_file_action # ROTATE (based on num_logs) or KEEP_FILES (ignore num_logs)
num_logs # keep number of X old logs
space_left # when X MB is remaining, space_left_action is triggered
space_left_action # SYSLOG, EMAIL (see action_mail_acct), EXEC /path/to/script
admin_space_left # when the file system containing the log file has this much free space (in MB) remaining
admin_space_left_action # SUSPEND (auditd to stop writing audit records to the file system), SINGLE, HALT
disk_full_action # SUSPEND, SINGLE (putting the system in single-user mode, allowing the admin to recover), HALT
disk_error_action # SUSPEND, SINGLE, HALT (complete system shutdown)
flush = INCREMENTAL_ASYNC # enable asynchronous flushing of records to storage after the number of writes specified by freq, DATA, SYNC
freq = 50 # set the freq parameter to 50 to flush the Audit log after every 50 records
log_format = ENRICHED # resolve UID, GID, system call number, architecture, and socket address information to names before transmitting each event
name_format = HOSTNAME # include the machine's host name in each message
/etc/audisp/plugins.d/syslog.conf # if you are sending messages to rsyslog
active = yes # + you also need to configure /etc/rsyslog.conf
yum install audispd-plugins # if you are sending messages to a remote auditd service
/etc/audisp/plugins.d/au-remote.conf # needed for remote auditd
active = yes
/etc/audisp/audisp-remote.conf # needed for remote auditd, see man audisp-remote.conf for encryption
remote_server # directive set to the IP address or host name of the remote auditd server
port # if your remote server is not listening on the default 60/TCP port
/etc/audit/audit.rules # do not edit this, it is automatically generated from the /etc/audit/rules.d/
/etc/audit/rules.d # all files ending in *.rules are combined into /etc/audit/audit.rules by augenrules
systemctl status auditd; systemctl is-enabled auditd
# CONFIGURE SERVER COLLECTING AUDITD EVENTS:
/etc/rsyslog.conf # imudp or imtcp
/etc/audit/auditd.conf
tcp_listen_port = 60 # uncomment this line
firewall-cmd --add-port=60/tcp --permanent ; firewall-cmd --reload
systemctl restart auditd ; reboot# INTERPRETING AUDIT MESSAGES:
ausearch -i -a 28708 # show all records for the event that has 28708 as its event ID, interpret the log records - translate numeric values into names
ausearch -f /path/to/file # search for all events related to a specific filename
ausearch -m LOGIN --format csv > results.csv # search for all audit events of the LOGIN type, and export them in CSV format
aureport -l # report logins
aureport --summary # number of failed logins, authentications, failed authentications, users, AVCs etc.
aureport -x # executable name report
aureport -if /some/other/audit.log --executable --summary # show executable summary for the different auditd log file
# TRACING A PROGRAM: # autrace command removes any active audit rules or requires you to remove any active rules before you run it
autrace /bin/date # investigate the system calls performed by a process /bin/date, you can locate the records with PID
ausearch --raw -p 26472 | aureport --file -i # PID from the previous autrace command# SETTING SYSTEM CALL RULES: # when Audit starts, it assigns an Audit UID of 4294967295 to any existing process (-F auid!=4294967295)
auditctl -l # list the current rules
auditctl -s # current status of audit
auditctl -a exit,always -F arch=b32 -F auid>=500 -S rename\ # audit the 32-bit version of both the rename and renameat system call for all users whose original Audit user ID is equal to or greater than 500
-S renameat -F subj_type!=mysqld_t -k rename # do not trigger the Audit rule if the process is under the mysqld_t SELinux domain, and add the rename key to the logs
auditctl -a exit,always -F dir=/home/ -F uid=0\ # recursively audit every file system access by the root user under the /home directory to files or directories not owned by the original user that is now working as root
-C auid!=obj_uid
auditctl -e 2 # set the currently loaded rules to be immutable, the rules cannot be changed again until the system is rebooted, must be last rule# PREPACKAGED AUDIT RULE SETS:
ls /usr/share/doc/audit-*/rules/
cp -v /usr/share/doc/audit-*/rules/30-stig.rules /etc/audit/rules.d/
augenrules --load
# FULL TERMINAL KEYSTROKE LOGGING: # man pam_tty_audit
vi /etc/pam.d/system-auth
session required pam_tty_audit.so disable=* enable=demo # enables keystroke logging for the demo user, and disables it for all other users
vi /etc/pam.d/password-auth
session required pam_tty_audit.so disable=* enable=demo # enables keystroke logging for the demo user, and disables it for all other users
aureport --tty # convert the data logged in the Audit system to a more readable formatyum install aide
# CONFIGURATION LINES: # man aide.conf
database # location where it reads db when running checks
database_out # location where it writes db when it is updated
gzip_dbout # new compressed (gzip) db when set to yes
# Group definitions:
PERMS = p+u+g+acl+selinux+xattrs # group named PERMS monitors permissions, user, group, acl, selinux, extended attributes
CONTENT_EX = sha256+ftype+p+u+g+n+acl+selinux+xattrs # content, filetype, access etc.
# SELECTION LINES:
/etc PERMS # regular, regular expression recursively
=/testidr PERMS # equals, regular expression non-recursively
!/etc/mtab # negative, regular expression of what files or directories not to monitor
# MACRO LINES:
@@define DBDIR /var/lib/aide # variable definition
database=file:@@{DBDIR}/aide.db.gz # variable expansion, sets the database parameter to the value file:/var/lib/aide/aide.db.gz# CONFIGURING AIDE AND AUDIT: # it is a good idea to configure both
aide --init # initializing the aide database
aide --check # manually verifying integrity with aide
vi /etc/cron.d/aide # in production, you should periodically run AIDE checks
00 17 * * * root /usr/sbin/aide --check
aide --update # update the db when EXPECTED changes occur
mv -v /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz # do not forget to replace the old database file with the updated file
# INVESTIGATING FILE SYSTEM CHANGES:
ausearch -i -f /etc/group # select events relevant to the file that you are investigating
ausearch -i -f /etc/group -ts "08/07/2018" "09:00:00" # search for events since e.g. date and time of the last AIDE report
CWD # current working directory
PATH # path to a file involved in the event
PROCTITLE # complete command line that triggered the event
SYSCALL # system call made to the kernel that trigerred the event
a0 # first argument of the system call
a1 # second argument of the system call (e.g. O_WRONLY,O_RDWR,O_RDONLY...)
auid # a.k.a. audit ID # user ID that was used to log in to the system initially (even when su)
euid # a.k.a. effective ID # user ID that the process has for permission checks
egid # a.k.a. effective GID # group ID that the process has for permission checks
success # yes or no
uid # a.k.a. real UID # user ID that started the process (overwritten by su, setuid, setgid)Note: To generate beautiful PDF file, install latex and pandoc:
sudo yum install pandoc pandoc-citeproc texlive
And then use pandoc v1.12.3.1 to output Github Markdown to the PDF:
pandoc -f markdown_github -t latex -V geometry:margin=0.3in -o RH415.pdf R415.md
For better result (pandoc text-wrap code blocks), you may want to try my listings-setup.tex:
pandoc -f markdown_github --listings -H listings-setup.tex -V geometry:margin=0.3in -o RH415.pdf RH415.md