Skip to content

Instantly share code, notes, and snippets.

@dmi3mis
Forked from luckylittle/RH415.md
Created July 11, 2025 13:46
Show Gist options
  • Save dmi3mis/067762908f910f7b30fb0d7c0b2c60e3 to your computer and use it in GitHub Desktop.
Save dmi3mis/067762908f910f7b30fb0d7c0b2c60e3 to your computer and use it in GitHub Desktop.

Revisions

  1. @luckylittle luckylittle revised this gist Nov 18, 2019. 1 changed file with 7 additions and 2 deletions.
    9 changes: 7 additions & 2 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Mon Nov 18 03:26:03 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Mon Nov 18 05:32:46 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -24,10 +24,11 @@ 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
    # 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 [email protected].* # this would need PermitRootLogin yes
    AllowUsers [email protected]
    AllowUsers [email protected]/24 [email protected]
    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
    @@ -447,6 +448,10 @@ aureport --tty # convert the data l

    # 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
  2. @luckylittle luckylittle revised this gist Nov 18, 2019. 1 changed file with 13 additions and 1 deletion.
    14 changes: 13 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Tue Nov 12 04:04:25 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Mon Nov 18 03:26:03 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -437,6 +437,18 @@ vi /etc/pam.d/password-auth
    aureport --tty # convert the data logged in the Audit system to a more readable format
    ```
    ```bash
    # 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
    ```
    ## 7. Monitoring File System Changes
    ```bash
  3. @luckylittle luckylittle revised this gist Nov 18, 2019. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -313,7 +313,7 @@ vi /etc/pam.d/password-auth-local
    # 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, beware of defaults (commented out)
    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]
    @@ -544,7 +544,6 @@ 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
    ```
    ```bash
    # Three policies: targeted, MLS (Multi-Level Security), minimum
    yum install setools-console
  4. @luckylittle luckylittle revised this gist Nov 17, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -615,7 +615,7 @@ oscap xccdf generate fix --profile xccdf_org.ssgproject.content_profile_pci-dss
    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
    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
  5. @luckylittle luckylittle revised this gist Nov 12, 2019. 1 changed file with 7 additions and 3 deletions.
    10 changes: 7 additions & 3 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -172,8 +172,11 @@ clevis luks bind -d /dev/vdb1 sss "$cfg"
    # 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 enable usbguard --now
    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
    @@ -189,9 +192,10 @@ hash "CsKOZ6IY8v3eojsc1fqKDW84V+MMhD6HsjjojcZBjSg=" parent-hash
    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
    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
    ```
    @@ -420,7 +424,7 @@ auditctl -e 2 # set the currently
    ```
    ```bash
    # PREPACKAGED AUDIT RULE SETS:
    # 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
  6. @luckylittle luckylittle revised this gist Nov 12, 2019. 1 changed file with 12 additions and 3 deletions.
    15 changes: 12 additions & 3 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -171,7 +171,7 @@ clevis luks bind -d /dev/vdb1 sss "$cfg"
    ```bash
    # USBGUARD:
    yum -y install usbguard
    yum -y install usbutils udisks2 # provides lsusb, udisksctl
    yum -y install usbutils udisks2 # provides lsusb, udisksctl (shows serial num + blk device)
    usbguard <list-devices|allow-device id|block-device id|reject-device id|list-rules|append-rule rule|remove-rule id|generate-policy>
    systemctl enable usbguard --now

    @@ -340,11 +340,20 @@ authconfig --help | grep faillock
    authconfig --enablefaillock --faillockargs="deny=3 fail_interval=60 unlock_time=600" --update
    faillock # list failed login attempts
    faillock --user user1 # restricts the output to a specific account
    faillock --user user1 --reset # removes the failure records for a user, as a side effect516298
    this also unlocks the account if it was locked
    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
    ```
    ```bash
    # 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
    ```bash
  7. @luckylittle luckylittle revised this gist Nov 12, 2019. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Fri Sep 27 05:17:25 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Tue Nov 12 04:04:25 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -78,7 +78,7 @@ become_ask_pass = false
    ```

    ```bash
    # Ansible role for SELinux remediation:
    # Ansible role for SELinux remediation (yum install rhel-system-roles):
    linux-system-roles.selinux
    ```

    @@ -502,9 +502,9 @@ setsebool -P httpd_enable_homedirs on # permanently turn t
    ```bash
    # ENABLING SELINUX FROM DISABLED MODE:
    touch /.autorelabel ; systemctl reboot
    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
    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
  8. @luckylittle luckylittle revised this gist Sep 27, 2019. 1 changed file with 54 additions and 42 deletions.
    96 changes: 54 additions & 42 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,18 +1,19 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Thu Aug 15 05:19:13 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Fri Sep 27 05:17:25 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    ## 1. Managing Security & Risk

    ```bash
    # USING YUM TO MANAGE SECURITY ERRATA:
    yum updateinfo --security # security related updates
    yum updateinfo --security # security related updates/summary
    yum updateinfo list updates | grep Critical # identify critical RHSAs
    yum updateinfo RHSA-2018:1453 # view RHSA details
    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?
    ```

    ```bash
    @@ -31,6 +32,11 @@ vi /etc/ssh/sshd_config
    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
    ```

    ```bash
    @@ -88,7 +94,7 @@ part pv.01 --size=10000 --encrypted --passphrase=PASSPHRASE # encrypting an LVM
    ```bash
    # ENCRYPTING DEVICES WITH LUKS AFTER INSTALLATION:
    parted -l # lists partition layout on all block devices
    parted /dev/vdb mklabel msdos mkpart primary xfs 1M 1G # msdos label type, primary xfs type partition from 1M to 1G
    parted /dev/vdb 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
    @@ -102,17 +108,9 @@ cryptsetup luksAddKey --key-slot 1 /dev/vdb1 # enter original pas
    cryptsetup luksChangeKey /dev/vdb1 # change passphrase
    ```

    ```bash
    # 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
    ```

    ```bash
    # 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
    @@ -122,12 +120,24 @@ jose jwk gen -i '{"alg":"ECMR"}' -o exchange.jwk # creating new keys
    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
    systemctl enable clevis-luks-askpass.path # when decrypting non-root file system
    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
    ```

    ```bash
    # 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
    ```

    ```bash
    # 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
    @@ -137,7 +147,7 @@ clevis luks bind -d /dev/vdb1 sss "$cfg"
    ```

    ```json
    # JSON format of the above cfg example:
    # JSON format of the above cfg example, do not forget HTTP and quotes:
    {
    "t": 2,
    "pins": {
    @@ -191,16 +201,16 @@ usbguard watch # watch terminal for
    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 \
    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
    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
    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:
    # 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
    @@ -228,6 +238,7 @@ reject via-port "1-2" # allow Yubikey on a

    # 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:*:* }
    @@ -254,7 +265,7 @@ man -k pam_ | grep <QUERY> # e.g.: man pam_fail

    # USING SSSD AND PAM:
    yum -y install sssd
    authconfig --enablesssd --enablesssdauth --update
    authconfig --enablesssd --enablesssdauth --update # don't forget to put both here (sssd & sssd auth)
    ```
    ```bash
    @@ -298,12 +309,12 @@ vi /etc/pam.d/password-auth-local
    # DESCRIBING THE PAM_PWQUALITY MODULE: # man pwquality.conf
    authconfig --passminlen=12 --update
    grep pam_pwquality /etc/pam.d/system-auth /etc/pam.d/password-auth # these can be only specified in /etc/pam.d/ files: try_first_pass local_users_only retry authtok_type
    vi /etc/security/pwquality.conf # negative values indicate/enforce the minimum number of characters required for each class
    minlen = 8 # passwords must be a minimum of eight characters in length
    lcredit = 0 # policy does not specify anything regarding lowercase characters
    ucredit = -1 # passwords must contain at least one uppercase character
    dcredit = -2 # passwords must contain at least two digits
    ocredit = -1 # passwords must contain at least one other/special character
    vi /etc/security/pwquality.conf # negative values indicate/enforce the minimum number of characters required for each class, 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]
    ```
    ```bash
    @@ -427,7 +438,7 @@ PERMS = p+u+g+acl+selinux+xattrs # group named PERMS
    CONTENT_EX = sha256+ftype+p+u+g+n+acl+selinux+xattrs # content, filetype, access etc.

    # SELECTION LINES:
    /etc PERMS # regular, regular expression recursively
    /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

    @@ -500,13 +511,13 @@ semanage permissive -d httpd_t # switch a domain ba
    ```
    ```bash
    # DEFINING SELINUX USERS: # user_u cannot use 'su' or 'sudo', sysadm_u allows to use 'su', 'sudo', staff_u can use 'sudo' but not 'su'
    # 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
    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
    @@ -578,7 +589,7 @@ 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
    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
    @@ -590,6 +601,8 @@ 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

    # APPLYING PROFILES DURING INSTALLATION: # Kickstart file
    %addon org_fedora_oscap
    @@ -603,8 +616,8 @@ profile = pci-dss
    ```bash
    # 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
    hammer scap-content list # list the SCAP contents in Satellite server (*-ds.xml files)
    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
    @@ -625,21 +638,20 @@ vi /etc/foreman_scap_client/config.yaml # contains policy in
    :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
    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):
    # Upload a tailoring file to Satellite
    # Assigning a tailoring file to a compliance policy
    # This will add ':tailoring_path:' and ':tailoring_download_path:' to the /etc/foreman_scap_client/config.yaml
    ```
    ## 11. Analyzing and Remediating Issues with Red Hat Insights
    ### 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'
    ```bash
    ```
    ## 11. Analyzing and Remediating Issues with Red Hat Insights
    ---
  9. @luckylittle luckylittle revised this gist Aug 15, 2019. 1 changed file with 34 additions and 1 deletion.
    35 changes: 34 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Thu Aug 15 02:20:55 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Thu Aug 15 05:19:13 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -601,6 +601,39 @@ profile = pci-dss
    ## 10. Automating Compliance with Red Hat Satellite
    ```bash
    # 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
    hammer scap-content list # list the SCAP contents in Satellite server (*-ds.xml files)

    # 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

    # 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):
    # Upload a tailoring file to Satellite
    # Assigning a tailoring file to a compliance policy
    # This will add ':tailoring_path:' and ':tailoring_download_path:' to the /etc/foreman_scap_client/config.yaml
    ```
    ## 11. Analyzing and Remediating Issues with Red Hat Insights
  10. @luckylittle luckylittle revised this gist Aug 15, 2019. 1 changed file with 37 additions and 1 deletion.
    38 changes: 37 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Tue Aug 13 06:25:49 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Thu Aug 15 02:20:55 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -560,6 +560,42 @@ sesearch -T -s crond_t -t var_log_t -c file # list the file tran
    ## 9. Managing Compliance with OpenSCAP
    ```bash
    # 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

    # 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

    # 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
  11. @luckylittle luckylittle revised this gist Aug 15, 2019. 1 changed file with 20 additions and 1 deletion.
    21 changes: 20 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -535,7 +535,26 @@ 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 #
    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
  12. @luckylittle luckylittle revised this gist Aug 13, 2019. 1 changed file with 78 additions and 1 deletion.
    79 changes: 78 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Tue Aug 13 04:26:49 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Tue Aug 13 06:25:49 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -71,6 +71,11 @@ become_user = root
    become_ask_pass = false
    ```

    ```bash
    # Ansible role for SELinux remediation:
    linux-system-roles.selinux
    ```

    ## 3. Protecting Data with LUKS & NBDE

    ```bash
    @@ -459,6 +464,78 @@ ausearch -i -f /etc/group -ts "08/07/2018" "09:00:00" # search for events
    ## 8. Mitigating Risk with SELinux
    ```bash
    # 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'
    ```
    ```bash
    # ENABLING SELINUX FROM DISABLED MODE:
    touch /.autorelabel ; systemctl reboot
    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
    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
    ```
    ```bash
    # DEFINING SELINUX USERS: # user_u cannot use 'su' or 'sudo', sysadm_u allows to use 'su', 'sudo', staff_u can use 'sudo' but not 'su'
    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
    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
    ```
    ```bash
    # 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 #
    ```
    ## 9. Managing Compliance with OpenSCAP
  13. @luckylittle luckylittle revised this gist Aug 13, 2019. 1 changed file with 44 additions and 1 deletion.
    45 changes: 44 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Mon Aug 12 13:38:11 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Tue Aug 13 04:26:49 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -411,6 +411,49 @@ aureport --tty # convert the data l
    ## 7. Monitoring File System Changes
    ```bash
    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
    =/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
    ```
    ```bash
    # 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
  14. @luckylittle luckylittle revised this gist Aug 12, 2019. 1 changed file with 82 additions and 34 deletions.
    116 changes: 82 additions & 34 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Fri Aug 9 09:33:36 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Mon Aug 12 13:38:11 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -27,7 +27,7 @@ vi /etc/ssh/sshd_config
    AllowUsers [email protected].* # this would need PermitRootLogin yes
    AllowUsers [email protected]
    AllowUsers [email protected]/24 [email protected]
    # If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. The available criteria are User, Group, Host, LocalAddress, LocalPort, and Address:
    # 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
    @@ -57,11 +57,13 @@ sudo -i # changes to the roo
    ## 2. Automating Configuration & Remediation with Ansible

    ```bash
    # 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
    @@ -108,7 +110,7 @@ cat /etc/fstab
    # NBDE - UNATTENDED DEVICE DECRYPTION AT BOOT TIME:
    yum -y install tang # Tang servers validate the keys
    systemctl enable tangd.socket --now # tangd service binds to the 80/TCP port
    firewall-cmd --zone=public --add-service=http --permanent
    firewall-cmd --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
    @@ -127,7 +129,9 @@ cfg=$'{"t":2,"pins":{"tang":[\n
    > {"url":"http://demotang2.lab.example.com"},\n
    > {"url":"http://demotang3.lab.example.com"}]}}'
    clevis luks bind -d /dev/vdb1 sss "$cfg"
    ```

    ```json
    # JSON format of the above cfg example:
    {
    "t": 2,
    @@ -241,7 +245,7 @@ type control module [module arguments]
    # '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_ # e.g.: man pam_faildelay
    man -k pam_ | grep <QUERY> # e.g.: man pam_faildelay

    # USING SSSD AND PAM:
    yum -y install sssd
    @@ -273,7 +277,7 @@ cp password-auth-ac password-auth-local # ...and password-au
    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 you custom files, include the *-ac files
    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
    @@ -286,7 +290,7 @@ vi /etc/pam.d/password-auth-local
    ```
    ```bash
    # DESCRIBING THE PAM_PWQUALITY MODULE:
    # 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
    @@ -298,23 +302,25 @@ vi /etc/security/pwquality.conf # negative values in
    ```
    ```bash
    # PAM_TIME MODULE:
    vi /etc/security/time.conf # configure the pam_time module
    # 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:
    # 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
    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
    ```
    ```bash
    # LOCKING ACCOUNTS WITH MULTIPLE FAILED LOGINS:
    # LOCKING ACCOUNTS WITH MULTIPLE FAILED LOGINS: # man pam_faillock
    authconfig --help | grep faillock
    man pam_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
    @@ -330,34 +336,76 @@ authconfig --disablefaillock --update
    /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 or KEEP_FILES
    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 #
    space_left_action #
    admin_space_left #
    admin_space_left_action #
    disk_full_action #
    disk_error_action #
    flush = INCREMENTAL_ASYNC #
    freq = 50 #
    log_format = ENRICHED #
    name_format #
    /etc/audisp/plugins.d/syslog.conf #
    active = yes #
    yum install audispd-plugins
    /etc/audisp/plugins.d/au-remote.conf #
    active = yes #
    /etc/audisp/audisp-remote.conf #
    remote_server #
    port #
    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 #
    /etc/audit/auditd.conf #
    tcp_listen_port = 60
    /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
    ```
    ```bash
    # 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
    ```
    ```bash
    # 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
    ```
    ```bash
    # PREPACKAGED AUDIT RULE SETS:
    ls /usr/share/doc/audit-*/rules/
    cp -v /usr/share/doc/audit-*/rules/30-stig.rules /etc/audit/rules.d/
    augenrules --load

    # FULL TERMINAL KEYSTROKE LOGGING: # man pam_tty_audit
    vi /etc/pam.d/system-auth
    session required pam_tty_audit.so disable=* enable=demo # enables keystroke logging for the demo user, and disables it for all other users
    vi /etc/pam.d/password-auth
    session required pam_tty_audit.so disable=* enable=demo # enables keystroke logging for the demo user, and disables it for all other users
    aureport --tty # convert the data logged in the Audit system to a more readable format
    ```
    ## 7. Monitoring File System Changes
  15. @luckylittle luckylittle revised this gist Aug 9, 2019. 1 changed file with 8 additions and 8 deletions.
    16 changes: 8 additions & 8 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Wed Aug 7 12:01:03 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Fri Aug 9 09:33:36 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -327,10 +327,11 @@ authconfig --disablefaillock --update
    ```bash
    # CONFIGURE CLIENT:
    /etc/audit/auditd.conf #
    log_file #
    max_log_file #
    max_log_file_action #
    /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 or KEEP_FILES
    num_logs # keep number of X old logs
    space_left #
    space_left_action #
    admin_space_left #
    @@ -349,9 +350,8 @@ authconfig --disablefaillock --update
    /etc/audisp/audisp-remote.conf #
    remote_server #
    port #
    /etc/audit/audit.rules #
    /etc/audit/rules.d # augenrules
    /etc/audit/rules.d/audit.rules #
    /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:
  16. @luckylittle luckylittle revised this gist Aug 7, 2019. 1 changed file with 120 additions and 1 deletion.
    121 changes: 120 additions & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Sun Aug 4 12:58:33 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Wed Aug 7 12:01:03 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -234,11 +234,130 @@ install -m 0600 -o root -g root ~/rules.conf /etc/usbguard/rules.conf ; systemct
    ## 5. Controlling Authentication with PAM
    ```bash
    # 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_ # e.g.: man pam_faildelay

    # USING SSSD AND PAM:
    yum -y install sssd
    authconfig --enablesssd --enablesssdauth --update
    ```
    ```bash
    # 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
    ```
    ```bash
    # 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 you 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
    ```
    ```bash
    # DESCRIBING THE PAM_PWQUALITY MODULE:
    authconfig --passminlen=12 --update
    grep pam_pwquality /etc/pam.d/system-auth /etc/pam.d/password-auth # these can be only specified in /etc/pam.d/ files: try_first_pass local_users_only retry authtok_type
    vi /etc/security/pwquality.conf # negative values indicate/enforce the minimum number of characters required for each class
    minlen = 8 # passwords must be a minimum of eight characters in length
    lcredit = 0 # policy does not specify anything regarding lowercase characters
    ucredit = -1 # passwords must contain at least one uppercase character
    dcredit = -2 # passwords must contain at least two digits
    ocredit = -1 # passwords must contain at least one other/special character
    ```
    ```bash
    # PAM_TIME MODULE:
    vi /etc/security/time.conf # configure the pam_time module
    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

    # PAM_ACCESS MODULE:
    authconfig --help | grep access
    authconfig --enablepamaccess --update # enables pam_access (check /etc/security/access.conf during account authorization)
    vi /etc/security/access.conf
    +: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:ALL # other users are not allowed to log in
    ```
    ```bash
    # LOCKING ACCOUNTS WITH MULTIPLE FAILED LOGINS:
    authconfig --help | grep faillock
    man pam_faillock
    authconfig --enablefaillock --faillockargs="deny=3 fail_interval=60 unlock_time=600" --update
    faillock # list failed login attempts
    faillock --user user1 # restricts the output to a specific account
    faillock --user user1 --reset # removes the failure records for a user, as a side effect516298
    this also unlocks the account if it was locked
    authconfig --disablefaillock --update
    ```
    ## 6. Recording System Events with Audit
    ```bash
    # CONFIGURE CLIENT:
    /etc/audit/auditd.conf #
    log_file #
    max_log_file #
    max_log_file_action #
    space_left #
    space_left_action #
    admin_space_left #
    admin_space_left_action #
    disk_full_action #
    disk_error_action #
    flush = INCREMENTAL_ASYNC #
    freq = 50 #
    log_format = ENRICHED #
    name_format #
    /etc/audisp/plugins.d/syslog.conf #
    active = yes #
    yum install audispd-plugins
    /etc/audisp/plugins.d/au-remote.conf #
    active = yes #
    /etc/audisp/audisp-remote.conf #
    remote_server #
    port #
    /etc/audit/audit.rules #
    /etc/audit/rules.d # augenrules
    /etc/audit/rules.d/audit.rules #
    systemctl status auditd; systemctl is-enabled auditd

    # CONFIGURE SERVER COLLECTING AUDITD EVENTS:
    /etc/rsyslog.conf #
    /etc/audit/auditd.conf #
    tcp_listen_port = 60
    ```
    ## 7. Monitoring File System Changes
  17. @luckylittle luckylittle revised this gist Aug 4, 2019. 1 changed file with 67 additions and 19 deletions.
    86 changes: 67 additions & 19 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: Sun Aug 4 05:42:02 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Sun Aug 4 12:58:33 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    @@ -21,7 +21,15 @@ ss -tlw # open ports in the
    # CUSTOMIZING YOUR SSH SERVICE CONFIGURATION:
    vi /etc/ssh/sshd_config
    PermitRootLogin no # do not allow root to SSH to this machine
    PasswordAuthentication no # only key-based authentication
    PasswordAuthentication no # force only key-based authentication
    # ALLOW/DENY USERS & GROUPS:
    # The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups
    AllowUsers [email protected].* # this would need PermitRootLogin yes
    AllowUsers [email protected]
    AllowUsers [email protected]/24 [email protected]
    # If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. The available criteria are User, Group, Host, LocalAddress, LocalPort, and Address:
    Match Address 192.168.0.? # 192.168.0.[0-9] network range
    PermitRootLogin yes
    systemctl reload sshd
    ```

    @@ -31,8 +39,19 @@ su # switches to the ta
    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
    @@ -64,14 +83,16 @@ part pv.01 --size=10000 --encrypted --passphrase=PASSPHRASE # encrypting an LVM
    parted -l # lists partition layout on all block devices
    parted /dev/vdb mklabel msdos mkpart primary xfs 1M 1G # msdos label type, primary xfs type partition from 1M to 1G
    parted /dev/vdb print
    cryptsetup luksFormat /dev/vdb1
    cryptsetup luksFormat /dev/vdb1 [--key-file /path/to/file] # this will encrypt the drive
    cryptsetup luksDump /dev/vdb1
    cryptsetup luksOpen /dev/vdb1 example
    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
    ```

    ```bash
    @@ -85,17 +106,19 @@ cat /etc/fstab

    ```bash
    # NBDE - UNATTENDED DEVICE DECRYPTION AT BOOT TIME:
    yum -y install tang
    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
    cd /var/db/tang
    jose jwk gen -i '{"alg":"ES512"}' -o signature.jwk # creating new keys
    jose jwk gen -i '{"alg":"ECMR"}' -o exchange.jwk # creating new keys
    mv -v gxB7oqYiEu3zrLayhymtD10sV9E.jwk .gxB7oqYiEu3zrLayhymtD10sV9E.jwk
    mv -v k25k6PbmgUu-pWWUb210xgBelhfQ.jwk .k25k6PbmgUu-pWWUb210xgBelhfQ.jwk
    cd /var/db/tang # cryptographic keys are generated at first start
    jose jwk gen -i '{"alg":"ES512"}' -o signature.jwk # creating new keys manually
    jose jwk gen -i '{"alg":"ECMR"}' -o exchange.jwk # creating new keys manually
    mv -v gxB7oqYiEu3zrLay.jwk .gxB7oqYiEu3zrLay.jwk # rename both old keys to have leading period
    mv -v k25k6PbmgUu-pWWUb210x.jwk .k25k6PbmgUu-pWWUb210x.jwk

    yum install clevis clevis-luks clevis-dracut
    yum install clevis clevis-luks clevis-dracut # Clevis clients reach out to tang servers
    clevis luks bind -d /dev/vda1 tang '{"url":"http://demotang.lab.example.com"}'
    luksmeta show -d /dev/vda1 # verify that Clevis key was placed in LUKS header
    dracut -f # enable Dracut to unlock encrypted partitions using NBDS
    systemctl enable clevis-luks-askpass.path # when decrypting non-root file system

    # SSS policy which defines three Tang servers, and requires at least two of them to be available for automatic decryption to occur
    @@ -136,7 +159,7 @@ systemctl enable usbguard --now
    usbguard generate-policy > /etc/usbguard/rules.conf # authorizes the currently connected USB devices
    systemctl restart usbguard
    usbguard list-rules
    # Rule example:
    # 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
    @@ -151,6 +174,7 @@ systemctl restart usbguard

    usbguard list-devices
    usbguard list-rules
    usbguard watch # watch terminal for IPC activity
    ```

    ```bash
    @@ -159,28 +183,52 @@ usbguard block-device <ID> # set its rule targe
    usbguard list-devices --blocked
    usbguard reject-device <ID> # set its rule target to reject
    usbguard generate-policy -X -t reject \
    > /etc/usbguard/rules.conf # generate a new base policy with a reject rule target that will ignore any additional USB devices that try to interact with the system
    > /etc/usbguard/rules.conf # generate a new base policy with a reject rule target that will ignore any additional USB devices that'll try to interact with the system
    grep usbguard /etc/group # 'groupadd usbguard' & 'usermod -aG usbguard richard' if needed
    vi /etc/usbguard/usbguard-daemon.conf
    RuleFile=/etc/usbguard/rules.conf
    RuleFile=/etc/usbguard/rules.conf # do not edit this file directly, but rather elsewhere and then move it here
    IPCAccessControlFiles=/etc/usbguard/IPCAccessControl.d/
    IPCAllowedGroups=usbguard
    usbguard add-user -g usbguard --devices=modify,list,listen --policy=list --exceptions=listen

    # RULE OPTIONS:
    allow/reject name <DEVICE_NAME> serial <SER_NUM> via-port <PORT_ID> hash <HASH> with-interface <INTERFACE_TYPE>
    # RULE OPERATORS (via-port <OPERATOR> {...}, with-interface <OPERATOR> {...}):
    all-of # must contain all specified values to match
    one-of # must contain at least one
    none-of # must not contain any
    equals # must contain exactly the same
    equals-ordered # must contain exactly the same also in the same order
    # RULE CONDITIONS:
    localtime(time_range) # true if local time is in the range
    allowed-matches(query) # true if device matches query
    rule-applied # true if rule currently being evaluated ever matched device before
    rule-applied(past_duration) # same as above, but if it matched devce in the past duration of time
    rule-evaluated # true if was ever evaluated before
    rule-evaluated(past_duration) # same as above, but if it was evaluated in the past duration of time
    random # probability is 0.5 by default, can be changed by p_true
    true
    false
    ```

    ```bash
    # 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"
    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 with-interface equals { 08:*:* } # allow USB mass storage devices (class 08), deny all other via implicit rule

    # REJECT DEVICES WITH SUSPICIOUS COMBINATION OF INTERFACES:
    allow with-interface equals { 08:*:* }
    reject with-interface all-of { 08:*:* 03:00:* }
    reject with-interface all-of { 08:*:* 03:01:* }
    reject with-interface all-of { 08:*:* e0:*:* }
    reject with-interface all-of { 08:*:* 02:*:* }
    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
    @@ -208,12 +256,12 @@ reject with-interface all-of { 08:*:* 02:*:* }
    ```bash
    ```
    ## 10. Automating Compliance with Red4Hat Satellite
    ## 10. Automating Compliance with Red Hat Satellite
    ```bash
    ```
    ## 11. Analyzing and Remediating Issues with Red4Hat Insights
    ## 11. Analyzing and Remediating Issues with Red Hat Insights
    ```bash
    ```
  18. @luckylittle luckylittle revised this gist Aug 4, 2019. 1 changed file with 161 additions and 2 deletions.
    163 changes: 161 additions & 2 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,27 +1,186 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: xxx xxx x xx:xx:xx AEST xxxx by [@luckylittle](https://github.com/luckylittle)_
    _Last update: Sun Aug 4 05:42:02 UTC 2019 by [@luckylittle](https://github.com/luckylittle)_

    ---

    ## 1. Managing Security & Risk

    ```bash
    # USING YUM TO MANAGE SECURITY ERRATA:
    yum updateinfo --security # security related updates
    yum updateinfo list updates | grep Critical # identify critical RHSAs
    yum updateinfo RHSA-2018:1453 # view RHSA details
    yum updateinfo list --cve CVE-2018-1111 # what needs to be updated to fix CVE
    yum update --cve CVE-2018-1111 # resolve CVE
    ```

    ```bash
    # 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 # only key-based authentication
    systemctl reload sshd
    ```

    ```bash
    # 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
    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

    ```bash
    # 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
    ```

    ## 3. Protecting Data with LUKS & NBDE

    ```bash
    # 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
    ```

    ```bash
    # ENCRYPTING DEVICES WITH LUKS AFTER INSTALLATION:
    parted -l # lists partition layout on all block devices
    parted /dev/vdb mklabel msdos mkpart primary xfs 1M 1G # msdos label type, primary xfs type partition from 1M to 1G
    parted /dev/vdb print
    cryptsetup luksFormat /dev/vdb1
    cryptsetup luksDump /dev/vdb1
    cryptsetup luksOpen /dev/vdb1 example
    ls /dev/mapper/example
    mkfs.xfs /dev/mapper/example
    mount -t xfs /dev/mapper/example /encrypted
    umount /encrypted
    cryptsetup luksClose example
    ```

    ```bash
    # 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
    ```

    ```bash
    # NBDE - UNATTENDED DEVICE DECRYPTION AT BOOT TIME:
    yum -y install tang
    systemctl enable tangd.socket --now # tangd service binds to the 80/TCP port
    firewall-cmd --zone=public --add-service=http --permanent
    cd /var/db/tang
    jose jwk gen -i '{"alg":"ES512"}' -o signature.jwk # creating new keys
    jose jwk gen -i '{"alg":"ECMR"}' -o exchange.jwk # creating new keys
    mv -v gxB7oqYiEu3zrLayhymtD10sV9E.jwk .gxB7oqYiEu3zrLayhymtD10sV9E.jwk
    mv -v k25k6PbmgUu-pWWUb210xgBelhfQ.jwk .k25k6PbmgUu-pWWUb210xgBelhfQ.jwk

    yum install clevis clevis-luks clevis-dracut
    clevis luks bind -d /dev/vda1 tang '{"url":"http://demotang.lab.example.com"}'
    systemctl enable clevis-luks-askpass.path # when decrypting non-root file system

    # SSS policy which defines three Tang servers, and requires at least two of them to be available for automatic decryption to occur
    cfg=$'{"t":2,"pins":{"tang":[\n
    > {"url":"http://demotang1.lab.example.com"},\n
    > {"url":"http://demotang2.lab.example.com"},\n
    > {"url":"http://demotang3.lab.example.com"}]}}'
    clevis luks bind -d /dev/vdb1 sss "$cfg"

    # JSON format of the above cfg example:
    {
    "t": 2,
    "pins": {
    "tang": [
    {
    "url": "http://demotang1.lab.example.com"
    },
    {
    "url": "http://demotang2.lab.example.com"
    },
    {
    "url": "http://demotang3.lab.example.com"
    }
    ]
    }
    }
    ```

    ## 4. Restricting USB Device Access

    ```bash
    # USBGUARD:
    yum -y install usbguard
    yum -y install usbutils udisks2 # provides lsusb, udisksctl
    usbguard <list-devices|allow-device id|block-device id|reject-device id|list-rules|append-rule rule|remove-rule id|generate-policy>
    systemctl enable usbguard --now

    usbguard generate-policy > /etc/usbguard/rules.conf # authorizes the currently connected USB devices
    systemctl restart usbguard
    usbguard list-rules
    # Rule 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
    ```

    ```bash
    # AUTHORIZING A DEVICE TO PERSISTENTLY INTERACT WITH THE SYSTEM:
    usbguard list-devices # if a new USB device is attached to the system after the default policy is generated it is not authorized to access the system and is assigned a block rule target
    usbguard allow-device 6 # will not persist across reboots
    usbguard allow-device -p 6 # will add it to /etc/usbguard/rules.conf and persist
    systemctl restart usbguard

    usbguard list-devices
    usbguard list-rules
    ```

    ```bash
    # PREVENTING A DEVICE FROM INTERACTING WITH THE SYSTEM, WHITE/BLACKLISTING:
    usbguard block-device <ID> # set its rule target to block
    usbguard list-devices --blocked
    usbguard reject-device <ID> # set its rule target to reject
    usbguard generate-policy -X -t reject \
    > /etc/usbguard/rules.conf # generate a new base policy with a reject rule target that will ignore any additional USB devices that try to interact with the system
    vi /etc/usbguard/usbguard-daemon.conf
    RuleFile=/etc/usbguard/rules.conf
    IPCAccessControlFiles=/etc/usbguard/IPCAccessControl.d/
    usbguard add-user -g usbguard --devices=modify,list,listen --policy=list --exceptions=listen
    ```

    ```bash
    # 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"

    # CREATING POLICIES THAT MATCH MULTIPLE DEVICES `{ interface class:subclass:protocol }`:
    allow with-interface equals { 08:*:* }

    # 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:*:* }
    ```
    ## 5. Controlling Authentication with PAM
    @@ -68,4 +227,4 @@ _And then use `pandoc` v`1.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](https://gist.github.com/luckylittle/32a90c2024c4183bf01ebc752cbaae51#file-listings-setup-tex):_
    `pandoc -f markdown_github --listings -H listings-setup.tex -V geometry:margin=0.3in -o RH415.pdf RH415.md`
    `pandoc -f markdown_github --listings -H listings-setup.tex -V geometry:margin=0.3in -o RH415.pdf RH415.md`
  19. @luckylittle luckylittle revised this gist Jul 4, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion RH415.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud
    # Red Hat Security: Linux in Physical, Virtual and Cloud (RH415)

    _Last update: xxx xxx x xx:xx:xx AEST xxxx by [@luckylittle](https://github.com/luckylittle)_

  20. @luckylittle luckylittle created this gist Jul 3, 2019.
    71 changes: 71 additions & 0 deletions RH415.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    # Red Hat Security: Linux in Physical, Virtual and Cloud

    _Last update: xxx xxx x xx:xx:xx AEST xxxx by [@luckylittle](https://github.com/luckylittle)_

    ---

    ## 1. Managing Security & Risk

    ```bash
    ```

    ## 2. Automating Configuration & Remediation with Ansible

    ```bash
    ```

    ## 3. Protecting Data with LUKS & NBDE

    ```bash
    ```

    ## 4. Restricting USB Device Access

    ```bash
    ```

    ## 5. Controlling Authentication with PAM

    ```bash
    ```

    ## 6. Recording System Events with Audit

    ```bash
    ```

    ## 7. Monitoring File System Changes

    ```bash
    ```

    ## 8. Mitigating Risk with SELinux

    ```bash
    ```

    ## 9. Managing Compliance with OpenSCAP

    ```bash
    ```

    ## 10. Automating Compliance with Red4Hat Satellite

    ```bash
    ```

    ## 11. Analyzing and Remediating Issues with Red4Hat Insights

    ```bash
    ```

    ---

    _Note: To generate beautiful PDF file, install `latex` and `pandoc`:_
    `sudo yum install pandoc pandoc-citeproc texlive`

    _And then use `pandoc` v`1.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](https://gist.github.com/luckylittle/32a90c2024c4183bf01ebc752cbaae51#file-listings-setup-tex):_
    `pandoc -f markdown_github --listings -H listings-setup.tex -V geometry:margin=0.3in -o RH415.pdf RH415.md`