Skip to content

Instantly share code, notes, and snippets.

@luckylittle
Last active December 16, 2023 00:56
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save luckylittle/890071cc01aa4187397bdb957c0bc76e to your computer and use it in GitHub Desktop.
Save luckylittle/890071cc01aa4187397bdb957c0bc76e 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

@luckylittle
Copy link
Author

SUMMARY:

#CH1

• Risk management is a continuous process of proactively discovering potential risk, assessing
facts, and taking action based on the facts to resolve those risks.
• Red Hat analyzes threats and vulnerabilities against all Red Hat products every day, and
provides relevant advice and updates through the Red Hat Customer Portal.
• Common Vulnerabilities and Exposures (CVE) entries provide a standardized format for
reporting and tracking security-related software issues.
• You should base your servers on a standard operating environment (SOE) that provides a
baseline of the minimum packages that all your systems require, and add only the additional
packages that the server applications require.
• Every daemon that provides a network service increases the risk of a successful remote attack,
so you should not run unnecessary services.
• You should not allow root to directly log in to the system using ssh. Instead, require initial login
to an unprivileged account that can use sudo or su to become root.
• You should consider turning off password-based SSH access and require either key-based
authentication or Kerberos for remote logins.

#CH2

• Effective automation tools help you manage security by ensuring all machines are correctly and
consistently configured and patched.
• Red Hat Ansible Automation is a good choice as an automation tool because it is simple to use,
its automation instructions are easy to read, and a number of security tools provide Ansible
Playbooks to help remediate issues.
• An Ansible Playbook consists of one or more plays. Each play targets a set of hosts with a list of
tasks, executed in order, and checks to see whether the system is in a certain state. If it is not, it
puts the system in that state.
• You use the ansible-playbook command to run an Ansible Playbook.
• An ad hoc command is a simple, one-task command that you can run using the ansible
command without writing a playbook.
• An inventory file lists the hosts and groups that you can use in your playbook and with ad hoc
commands.
• Red Hat Ansible Tower is a service that helps you control, secure, and centrally manage your
Ansible automation at scale.
• You can use Red Hat Ansible Tower to protect the authentication credentials of hosts from users
while still allowing them to use them to run playbooks.
• Red Hat Ansible Tower provides central logging and management so that you can track who
ran playbooks from the Ansible Tower server, at what time, affecting what hosts, and what the
results were of those runs.

#CH3

• Red Hat Enterprise Linux supports block device encryption with Linux Unified Key Setup (LUKS).
• A passphrase is required at boot time to decrypt a LUKS-encrypted block device.
• Network Bound Disk Encryption (NBDE) automates the decryption of LUKS-encrypted disks
without manually entering a passphrase at boot time.
• NBDE uses the Clevis framework on the client (decryption) side, and queries Tang servers to
determine if the client is running on a secure network.
• The Clevis framework provides binding policies which support the use of multiple Tang servers.
• The signature and exchange keys for a Tang server should be rotated periodically.

#CH4

• USBGuard protects your systems against rogue USB devices by implementing basic whitelisting
and blacklisting capabilities based on device attributes.
• The usbguard-daemon service determines whether or not to authorize a USB device based on
a policy defined by a set of rules.
• When a USB device is inserted into the system the daemon scans the existing rules sequentially,
and when a matching rule is found it either allows, blocks or rejects the device, based on the rule
target.
• The usbguard utility is used to manage the USB device authorization rules.

#CH5

• PAM stores most of its configuration files in /etc/pam.d/.
• A PAM-enabled application invokes the rules in each management group, auth, account,
password, and session, at different times during the user authentication and authorization
process.
• The authconfig command is the recommended way of updating the PAM configuration.
• Before any modification, back up the PAM configuration with authconfig --
savebackup=backupdir and open an extra root session to recover from errors.
• The pam_pwquality module uses the /etc/security/pwquality.conf configuration file
to enforce your organization password complexity requirements.
• The pam_faillock module locks accounts after too many consecutive failed attempts. You
use the authconfig --enablefaillock --faillockargs="parameters" command to
configure it.

#CH6

• Linux Audit is a system managed by the kernel to collect and log security-related events based
on a list of audit rules.
• The kernel sends the audit messages it collects to a user-space daemon, auditd, which is
responsible for recording them.
• auditd can save messages to a local log or relay them to a remote auditd or syslog service.
• You can use the ausearch and aureport commands to analyze the audit log.
• You can define audit rules persistently by editing files in /etc/audit/rules.d that have a
.rules suffix.
• There are three types of rules: file system rules (watches), system call rules, and control rules.
• The auditctl command may be used to edit Audit rules temporarily.
• The audit package includes some prepackaged Audit rule files that can be used to help
implement common security requirements.
• If a control rule has been set to make the audit rules immutable, they cannot be changed until
the system is rebooted.

#CH7

• AIDE allows you to detect changes made to a machine's file systems.
• An AIDE check can be run manually or by scheduling it with a tool such as crontab, and detect
changes using a database of baseline information.
• You use the /etc/aide.conf file to configure checks that AIDE performs against specific files
and directories using group definitions, selection lines, and macros.
• You need to rebuild the AIDE database file to accept authorized changes to files and to apply
new settings from the configuration file.
• You can use Audit in conjunction with AIDE to help you determine what process or user caused a
change that AIDE is reporting.

#CH8

• To migrate a system that has SELinux disabled to enforcing mode, switch to permissive
mode, review the audit log, relabel files and resolve issues, and then switch to enforcing mode.
• Confined SELinux users can allow you to restrict users from using sudo or su to switch user, log
in using ssh, or run some commands on the system.
• You can use the sesearch command to look up the access rules and transition rules that
SELinux enforces.
• You can use the sepolicy transition command to analyze whether or not a process
running in one domain can potentially use one or more domain transitions to run a process in
another domain.
• You can use the matchpathcon command to determine the expected context of a file created in
a particular location even if the file does not exist.

#CH9

• The openscap-scanner and scap-security-guide packages must be installed on the system to scan
for compliance.
• You use SCAP Workbench to explore and customize the policies provided by the SCAP Security
Guide.
• The oscap xccdf eval command is used to scan systems for compliance, using a data stream
file, a profile, and optionally a tailoring file containing local customizations.
• The oscap generate fix command can be used to generate an Ansible Playbook from a
profile or a scan result XML file, which can be used to apply remediations.

#CH10

• Red Hat Satellite 6 compliance policies can be used to centrally manage and review the results of
OpenSCAP scans on its registered clients.
• A Red Hat Satellite 6 compliance policy is a named, scheduled task that scans specific hosts for
compliance with an OpenSCAP XCCDF profile.
• OpenSCAP content must be uploaded to the Red Hat Satellite Server before it can be used in a
compliance policy.
• Clients update their compliance policy configuration using Puppet, run OpenSCAP scans locally,
and upload the results to Red Hat Satellite.
• The compliance policy dashboard in the Satellite Server's web UI provides an overview of
compliant and noncompliant hosts, and links to detailed OpenSCAP compliance reports for each
host.
• A compliance policy can be customized with an OpenSCAP tailoring file, which may be created in
SCAP Workbench.

#CH11

• Red Hat Insights is designed to help you identify and remediate threats to the security,
performance, availability, and stability of systems running Red Hat products.
• Red Hat Insights is provided as Software-as-a-service (SaaS) through the Red Hat Customer
Portal.
• You can directly register clients for Red Hat Insights analysis through the Customer Portal, or
indirectly by using your Red Hat Satellite Server as a proxy.
• You can configure the Insights client on each of your hosts to restrict or obscure the data sent to
Red Hat Insights for analysis, although this may make its analysis less comprehensive.
• You can review Red Hat Insights reports on the Customer Portal or through your Red Hat
Satellite Server.
• The risk and impact of issues are graded by Likelihood, Impact, Total Risk, and
Risk of change to help you understand and prioritize the actions to take to address detected
issues.
• You can create Ansible Playbooks to address issues with your systems by configuring a
maintenance plan in Red Hat Insights.
• Integrating Red Hat Ansible Tower with Red Hat Insights allows you to automate the remediation
of issues reported by Red Hat Insights on your registered systems.

@luckylittle
Copy link
Author

luckylittle commented Aug 15, 2019

@luckylittle
Copy link
Author

PDF version:
RH415_20191119.pdf

@AungAungMyoMyint
Copy link

where can i get this book
RH415-RHEL7.5-en-1-20180830

@luckylittle
Copy link
Author

where can i get this book
RH415-RHEL7.5-en-1-20180830

You need to have an active Red Hat Learning subscription and when you open the course, click on the DOWNLOAD EBOOK and chose the language.

@yanjunding
Copy link

yanjunding commented Aug 3, 2020

more useful commands

$ udisksctl status      # list disk drivers and block devices
$ lsblk

$ ssh-kengen
$ ssh-copy-id user@remote

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