Skip to content

Instantly share code, notes, and snippets.

@DevSecOpsGuy
Forked from luckylittle/RH415.md
Created September 15, 2021 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevSecOpsGuy/851dfb1060805c93e765fc3e570798c8 to your computer and use it in GitHub Desktop.
Save DevSecOpsGuy/851dfb1060805c93e765fc3e570798c8 to your computer and use it in GitHub Desktop.
Red Hat RH415 Notes

Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

Last update: Mon Nov 18 05:32:46 UTC 2019 by @luckylittle


1. Managing Security & Risk

# USING YUM TO MANAGE SECURITY ERRATA:
yum updateinfo --security                                   # security related updates/summary
yum updateinfo list updates | grep Critical                 # identify critical RHSAs
yum updateinfo RHSA-2018:1453                               # view RHSA details and corresponding CVEs
yum updateinfo list --cve CVE-2018-1111                     # what needs to be updated to fix CVE
yum update --cve CVE-2018-1111                              # resolve CVE
yum list updates --security                                 # how many security updates are there?
# 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. If specified, login is allowed ONLY for usernames that match one of the patterns!
  AllowUsers root@192.168.22.*                              # this would need PermitRootLogin yes
  AllowUsers James@host1.example.com
  AllowUsers root@192.168.22.0/24 James@host1.example.com
  AllowGroups wheel
  #  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

# SSH key filesystem permissions:
~/.ssh/                                                     # 0700
~/.ssh/id_rsa.pub                                           # 0644
~/.ssh/id_rsa                                               # 0600
# 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

2. Automating Configuration & Remediation with Ansible

# 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
# Ansible role for SELinux remediation (yum install rhel-system-roles):
linux-system-roles.selinux

3. Protecting Data with LUKS & NBDE

# 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 (or use fdisk)
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
# NBDE - UNATTENDED DEVICE DECRYPTION AT BOOT TIME:
# Servers:
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

# Clients:
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, takse a while
systemctl enable clevis-luks-askpass.path                   # when decrypting non-root file system, needs clevis-dracut
# 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
# 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, do not forget HTTP and quotes:
{
  "t": 2,
  "pins": {
    "tang": [
      {
        "url": "http://demotang1.lab.example.com"
      },
      {
        "url": "http://demotang2.lab.example.com"
      },
      {
        "url": "http://demotang3.lab.example.com"
      }
    ]
  }
}

4. Restricting USB Device Access

# USBGUARD:
yum -y install usbguard
yum -y install usbutils udisks2                             # provides lsusb, udisksctl (shows serial num + blk device)
rpm -qd usbguard                                            # document files for a package
rpm -qc usbguard                                            # shows all config files for a package
usbguard <list-devices|allow-device id|block-device id|reject-device id|list-rules|append-rule rule|remove-rule id|generate-policy>
systemctl start usbguard
^start^enable                                               # this will run the previous command and replace the string

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                                  # when rule is added, either reboot the machine or this

usbguard list-devices
usbguard list-devices --blocked                             # only show blocked
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 \                     # -X = don't generate hash attribute for devices
  > /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 (who can modify policy)
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 (sudo install -m 0600 -o root -g root modified_rules.conf /etc/usbguard/rules.conf ; systemctl restart usbguard)
  IPCAccessControlFiles=/etc/usbguard/IPCAccessControl.d/
  IPCAllowedGroups=usbguard
usbguard add-user -g usbguard --devices=modify,list,listen --policy=list --exceptions=listen

# RULE OPTIONS:                                             # man usbguard-rules.conf
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                                                      # this at the end will block everything (catch-all)

# 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

5. Controlling Authentication with PAM

# 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           # don't forget to put both here (sssd & sssd auth)
# 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, zero means zero extra credit - but one credit still applies! Beware of defaults (commented out)
  minlen = 8                                                # passwords must be a minimum of eight characters in length [default=9]
  lcredit = 0                                               # policy does not specify anything regarding lowercase characters [default=1]
  ucredit = -1                                              # passwords must contain at least one uppercase character [default=1]
  dcredit = -2                                              # passwords must contain at least two digits [default=1]
  ocredit = -1                                              # passwords must contain at least one other/special character [default=1]
# 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 effect this also unlocks the account if it was locked
authconfig --disablefaillock --update
# The 'pam_sepermit' module allows or denies login depending on SELinux enforcement state. When the user which is logging in matches an entry in the config file he is allowed access only when the SELinux is in enforcing mode:
vim /etc/security/sepermit.conf
  lmaly:ignore
  @wheel:exclusive
  %guest_u:exclusive
  %staff_u:ignore
  %user_u:ignore

6. Recording System Events with Audit

# 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:                              # note that watchers (-w) do not cross filesystem boundaries
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 format
# HOW TO EXCLUDE SPECIFIC USERS, GROUPS, OR SERVICES IN AUDITD?

# 1. When watching files:
-w /opt/application -p wa                                   # audits all writes & attribute-changes to /opt/application and everything beneath it
-a always,exit -F dir=/opt/application -F perm=wa           # same, converted to the more expressive format, conditions can now be added: -F uid!=USER, -F uid>=1000, -F success=1 (USER, or system users, or unsuccesfull event will prevent triggering the rule)
-a always,exit -F dir=/opt/application -F perm=w -F uid!=bob -F uid!=alice -F auid!=root -F uid>=1000 -F gid!=admins -F success=1                                                   # effectively audit all successful writes to /opt/application, except those executed by processes which are owned by bob & alice, user who originally logged in as root, user with a UID less than 1000, process where the primary group is "admins"

# 2. When watching syscalls:
-a always,exit -F arch=b64 -S clock_settime -F subj_type!=ntpd_t -F auid!=timekeeper # whitelists the use of clock_settime() by any processes running under the ntpd_t SELinux domain and by any processes owned by a user (probably root) who originally logged in as the "timekeeper" user

# 3. Do not audit cron, with help of SELinux
-a never,user -F subj_type=crond_t
-a exit,never -F subj_type=crond_t

7. Monitoring File System Changes

yum 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 (don't put trailing "/" at the end)
=/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)

8. Mitigating Risk with SELinux

# MANUAL PAGES:
yum install selinux-policy-doc policycoreutils-devel
sepolicy manpage -d httpd_t                                 # build the manual page for a specific domain, man /tmp/httpd_selinux.8
sepolicy manpage -a -p /usr/share/man/man8                  # by default the sepolicy manpage command generates the manual pages in /tmp
# PERSISTENTLY SET THE SELINUX MODE:
vi /etc/selinux/config
  SELINUX=enforcing                                         # check the mode with getenforce
# SELINUX REFRESHER:                                        # syntax: user:role:type(domain):level (e.g. system_u:system_r:httpd_t:s0)
# PROCESS:
ps -Z -C httpd                                              # every process
# DIRECTORY/FILE:
ls -Z -d /var/www/html                                      # ...directory, file
# PORT:
semanage port -l | grep "80,"                               # ...and port has a particular security label called the SELinux context
semanage port -a -t mysqld_port_t -p tcp 13306
# FILE CONTEXT:
semanage fcontext -l                                        # list default file context rules
semanage fcontext -a -t httpd_sys_content_t '/virtual(/.*)?'
restorecon -Rv /var/www/html/                               # although newly created file inherits the context of its parent directory
# BOOLEAN:
getsebool -a                                                # display all SELinux booleans
getsebool httpd_enable_homedirs                             # default is 'off'
setsebool -P httpd_enable_homedirs on                       # permanently turn the previous boolean to 'on'
# ENABLING SELINUX FROM DISABLED MODE:
touch /.autorelabel ; systemctl reboot                      # start with 'permissive' mode first
grep denied /var/log/audit/audit.log                        # extract the SELinux denials from the log file
ausearch -m AVC -ts boot                                    # only display messages from SELinux, and since the last system boot; use restorecon to fix all issues & switch to 'enforcing' mode
semanage permissive -a httpd_t                              # set a specific domain in permissive mode
semanage permissive -l                                      # list the domains in permissive mode
semanage permissive -d httpd_t                              # switch a domain back to enforcing
# DEFINING SELINUX USERS:                                   # sysadm_u allows to use 'su', 'sudo'; staff_u can use 'sudo' but not 'su'; user_u cannot use 'su' or 'sudo'
semanage user -l                                            # list the SELinux users and their SELinux roles
semanage login -l                                           # displays the table that SELinux uses for mapping Linux users to SELinux users
id -Z                                                       # logged in Linux users can retrieve their associated SELinux user
semanage login -a -s sysadm_u operator1                     # map existing Linux user 'operator1' to SELinux user 'sysadm_u'
semanage login -d -s sysadm_u operator1                     # remove the previous mapping
semanage login -m -s user_u -r s0 __default__               # modify the default mapping of SELinux user 'user_u' to '__default__' login name - confines all your Linux users to an SELinux user with minimal privileges by default, SELinux range for SELinux user defaults to s0
useradd -Z staff_u developer1                               # map a new Linux user operator1 at creation time
useradd -G wheel -Z sysadm_u operator2                      # map a new Linux user operator2 to SELinux user sysadm_u and add him to Linux group wheel to benefit from existing sudo rule
userdel -Z operator2                                        # remove the mapping at the same time you delete the user
# COMMON SELINUX USER BOOLEANS:
ssh_sysadm_login                                            # off=users mapped to sysadm_u cannot use SSH to log in
user_exec_content                                           # off=prevent users in user_u from executing programs in their home directories and /tmp
sysadm_exec_content                                         #
staff_exec_content                                          # off=prevent the staff_u SELinux users from executing programs in their home directories and /tmp
# SUDO RULES FOR SELINUX:
vi /etc/sudoers.d/developers
  developer ALL= ROLE=sysadm_r /bin/systemctl restart httpd # configure sudo to perform the SELinux role change before running the command
# Three policies: targeted, MLS (Multi-Level Security), minimum
yum install setools-console
seinfo                                                      # list all the objects in the policy
seinfo --type                                               # list all the types
seinfo --attribute                                          # list all attributes
seinfo --attribute=exec_type -x                             # list the types in an exec_type attribute
sesearch -A                                                 # list all the rules
sesearch -A -s httpd_t -t httpd_config_t -c file            # only display rule that allows the httpd_t source type to access files with the httpd_config_t target type
seinfo -c                                                   # list all classes of the target objects
sesearch -A -s httpd_t -t httpd_sys_script_exec_t \
  -c file -p execute -C                                     # identify boolean that enables(E)/disables(D) specific rule

# DISABLING AND ENABLING "DONTAUDIT" RULES:
semodule -DB                                                # disable the dontaudit rules to record all SELinux denials in the log
semodule -B                                                 # re-enable the dontaudit rules
sesearch -D -s postfix_master_t -d                          # list the dontaudit rules, searches direct rules direct with source of postfix_master_t

# CREATING CUSTOM POLICY MODULES:                           # before using audit2allow, and to collect all the denials in one operation, put SELinux in permissive mode
audit2allow -a                                              # generate a policy module for you by analyzing the denials in the audit.log file, print the rules to allow the access
audit2allow -a -M mymodule                                  # generate a new SELinux policy module, add the -M modulename option to the previous command
semodule -i mymodule.pp                                     # persistently load the new module in SELinux

# ANALYZING DOMAIN TRANSITIONS:
pstree -Z 1446                                              # new processes inherit the context type of their parent
pstree -Z | grep -e ^systemd -e httpd                       # when systemd (domain init_t) starts httpd, httpd transitions to the httpd_t domain
sesearch -T -s init_t -t httpd_exec_t                       # list the transition rules with source of init_t and target httpd_exec_t

yum install policycoreutils-devel                           # provides sepolicy transition
sepolicy transition -s httpd_t -t unconfined_t              # lists all the paths of sequential transitions that can get from the httpd_t domain to the unconfined_t domain

# ANALYZING FILE TRANSITIONS:
matchpathcon /var/www/html/myimage.png                      # get the expected context of an object
sesearch -T -s crond_t -t var_log_t -c file                 # list the file transition rules (crond_t -> var_log_t)

9. Managing Compliance with OpenSCAP

# THE SCAP SECURITY GUIDE:
yum install scap-security-guide                             # it install openscap-scanner as well (scap command)
ls -l /usr/share/xml/scap/ssg/content/                      # predefined profiles
oscap info /usr/share/xml/scap/ssg/content/ssg-firefox-ds.xml     # inspect the security content (parse XCCDF XML and display profiles + ids)
oscap xccdf generate guide --profile xccdf_org.ssgproject.content_profile_stig-firefox-upstream \
  /usr/share/xml/scap/ssg/content/ssg-firefox-ds.xml > guide.html # generate the HTML security guide for the Upstream Firefox STIG profile

# SCAP WORKBENCH:
yum install scap-workbench                                  # GUI tool, it also installs scap-security-guide

# LOCAL SYSTEM OPENSCAP SCAN:
yum install scap-security-guide
man scap-security-guide                                     # same as "grep '<Profile' /usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml"
ls /usr/share/xml/scap/ssg/content/*-ds.xml                 # list XCCDF data stream files
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_pci-dss \
  --results /root/results.xml /usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml # scan the local system
oscap xccdf eval --fetch-remote-resources --profile xccdf_org.ssgproject.content_profile_pci-dss \
  --results /root/results.xml /usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml # download list of up-to-date patches
oscap xccdf generate report results.xml > results.html      # generate a complete report in HTML format from XML (or use --report <results.html> while running eval)

# CUSTOMIZE A SCAP SECURITY GUIDE PROFILE:
# create a Tailoring File in scap-workbench first, define custom profile identifier in the process
oscap xccdf eval --profile custom_profile_ID --tailoring-file tailoring_file.xml \
  --results results.xml /usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml

# GENERATE A REMEDIATION ANSIBLE PLAYBOOK:                  # it only includes the tasks to remediate the failed checks
oscap xccdf generate fix --profile xccdf_org.ssgproject.content_profile_pci-dss \
  --fix-type ansible /usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml > pci-dss.yml # remediation from profile
oscap xccdf generate fix --profile xccdf_org.ssgproject.content_profile_pci-dss \
  --fix-type ansible --result-id "" /root/results.xml > remediation-playbook.yml    # remediation from results
oscap xccdf generate fix --profile xccdf_com.example_profile --tailoring-file \
  lab-tailor.xml --fix-type ansible --result-id "" lab-results.xml --output fix.yml # Ansible remediation with tailoring file. We have to specify the empty result-id, because oscap supports generation of fixes from a result file, that can have results from multiple scans.

# APPLYING PROFILES DURING INSTALLATION:                    # Kickstart file
%addon org_fedora_oscap
content-type = scap-security-guide
profile = pci-dss
%end

10. Automating Compliance with Red Hat Satellite

# UPLOADING OPENSCAP CONTENT TO THE SATELLITE SERVER:
yum install scap-security-guide                             # ensure the package is installed on the Satellite server
foreman-rake foreman_openscap:bulk_upload:default           # upload the default OpenSCAP content to your Satellite server, run this on the Satellite server
hammer scap-content list                                    # list the SCAP contents in Satellite server (*-ds.xml files, or in the Satellite console - SCAP Contents)

# PREPARING SATELLITE CLIENTS FOR OPENSCAP SCANS:
# "puppet-foreman_scap_client" package provides the Puppet modules required to set up clients to perform compliance scans
# add the "foreman_scap_client" Puppet class listed under the "foreman_scap_client" Puppet module

# INITIATING A PUPPET AGENT RUN ON A HOST:
# The 'foreman_scap_client' Puppet module installs the 'rubygem-foreman_scap_client' package and its dependencies
# Puppet module also configures the '/etc/foreman_scap_client/config.yaml' file on the host with parameters that are needed to run scans and upload results to the Satellite Server

# The 'bootstrap.py' script provided by the Satellite Server is used to register a system as both a host and a content host
wget https://satellite.lab.example.com/pub/bootstrap.py --no-check-certificate
chmod a+x bootstrap.py
./bootstrap.py -l admin -s satellite.lab.example.com -o 'org-example' -L 'Default Location' -a serverkey -g org-hostgroup1 --force
vi /etc/foreman_scap_client/config.yaml                     # contains policy information to be applied on the host
  :server: 'satellite.lab.example.com'
  :port: 9090
  1:
  :profile: 'xccdf_org.ssgproject.content_profile_common'
rpm -qa | grep -E 'foreman_scap|openscap'
vi /etc/cron.d/foreman_scap_client_cron
puppet agent --test --verbose                               # Puppet agent ensures that the compliance policy is correctly configured on the host. You can manually fetch the latest compliance policy this way, or wair for another run

# RUNNING AN OPENSCAP SCAN ON A CLIENT:                     # assumes the Puppet is configured with the above module
foreman_scap_client 1                                       # scan, archives the scan results, and uploads the results to the Satellite Server

EXECUTING A COMPLIANCE SCAN USING A CUSTOMIZED COMPLIANCE POLICY (TAILORING FILE) IN SATELLITE:

  • Upload a tailoring file to Satellite: 'Hosts' -> 'Tailoring Files'
  • Assigning a tailoring file to a compliance policy: 'Hosts' -> 'Policies' This will add ':tailoring_path:' and ':tailoring_download_path:' to the /etc/foreman_scap_client/config.yaml
  • 'Hosts' -> 'All hosts' -> [Select] -> 'Select Action' -> 'Assign Compliance Policy'
  • 'Hosts' -> 'All hosts' -> [Select] -> 'Select Action' -> 'Schedule Remote Job' -> 'OpenSCAP'

11. Analyzing and Remediating Issues with Red Hat Insights


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment