1.initial setup
1.1 filesystem configuration
1. seprate partition for various mount points
2. disable unnecessary file systems
ls /usr/lib/modules/$(uname -r)/kernel/fs
kernel modules location
/etc/modprobe.d/*.conf
configure blacklist and install
/usr/lib/modprobe.d/
that this directory
should not be used for user defined module loading. Ensure that all such entries resides
in /etc/modprobe.d/*.conf files
use /bin/false as the command in disabling a particular module
load module with modprobe
3.Ensure mounting of filesystems is disabled
squashfs(snap needs it),cramfs,udf,
4. ensure /tmp is seprate partition
make it noexec,nosuid, and nodev
either make /tmp a tmpfs or separte partition
size={size} parameter in the relevant entry in /etc/fstab
/tmp tmpfs tmpfs rw,nosuid,nodev,noexec,inode6
5.configure /var
Since the /var directory may
contain world-writable files and directories, there is a risk of resource exhaustion. It will essentially have the whole disk available to fill up and impact the system as a whole.
ensure nodev and nosuid
6.configure /var/tmp
The /var/tmp directory is a world-writable directory used for temporary storage by all users and some applications. Temporary files residing in /var/tmp are to be preserved between reboots
ensure separate partition for /var/tmp
nosuid,nodev and noexec
7. Ensure separate partition exists for
/tmp
/var
/var/tmp
/var/log
/var/log/audit
/home nodev,nosuid
8. Ensure nodev,noexec,nosuid option set on /dev/shm partition\
9. Disable Automounting
autofs allows automatic mounting of devices, typically including CD/DVDs and USB
drives
systemctl is-enabled autofs
apt purge autofs
if dependencies on autofs
systemctl stop autofs
systemctl mask autofs
10. Disable USB Storage
sudo /sbin/modprobe -n -v usb-storage
insmod /lib/modules/6.1.0-10-amd64/kernel/drivers/usb/storage/usb-storage.ko
echo -e "install usb-storage /bin/false" >>/etc/modprobe.d/usb-storage.conf
modprobe -r usb-storage
echo -e "blacklist usb-storage" >> /etc/modprobe.d/usb-storage.conf
another way to block usb is using usbguard
1.2 Configure Software Updates
1. Ensure package manager repositories are configured
apt-cache policy
2. Ensure GPG keys are configured
sudo apt install gnupg2
apt-key list
1.3. Filesystem Integrity Checking
1.AIDE,
Ensure AIDE is installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' aide
aide-common
apt install aide aide-common
2.Ensure filesystem integrity is regularly checked
#systemctl is-enabled aidecheck.service
# systemctl is-enabled aidecheck.timer
# systemctl status aidecheck.timer
1.4.Secure Boot Setting
1.Ensure bootloader password is set
Requiring a boot password upon execution of the boot loader will prevent an
unauthorized user from entering boot parameters or changing the boot partition. This prevents users from weakening security (e.g. turning off AppArmor at boot time.
if password protection is enabled, only the designated superuser can edit a Grub 2
menu item by pressing "e" or access the GRUB 2 command line by pressing "c"
https://help.ubuntu.com/community/Grub2/Passwords
2. Ensure permissions on bootloader config are configured
stat /boot/grub/grub.cfg
Access: (0400/-r--------)
chown root:root /boot/grub/grub.cfg
chmod u-wx,go-rwx /boot/grub/grub.cfg
3.Ensure authentication required for single user mode
grep -Eq '^root:\$[0-9]' /etc/shadow || echo "root is locked"
passwd root
1.5.process hardening
1.Ensure address space layout randomization (ASLR) is enabled
Address space layout randomization (ASLR) is an exploit mitigation technique which randomly arranges the address space of key data areas of a process
/sbin/sysctl kernel.randomize_va_space
kernel.randomize_va_space = 2
if not 2 set it :
#printf "kernel.randomize_va_space = 2" >> /etc/sysctl.d/60-kernel_sysctl.conf
# sysctl -w kernel.randomize_va_space=2
default value is 2 nowdays.
Configuration files are read from directories in /etc/, /run/, /usr/local/lib/, and
/lib/, in order of precedence. Files must have the the ".conf" extension. Files in /etc/
override files with the same name in /run/, /usr/local/lib/, and /lib/. Files in /run/
override files with the same name under /usr/.
All configuration files are sorted by their filename in lexicographic order, regardless of which of the directories they reside in. If multiple files specify the same option, the entry in the file with the lexicographically latest name will take precedence. Thus, the configuration in a certain file may either be replaced completely (by placing a file with the same name in a directory with higher priority), or individual settings might be changed (by specifying additional settings in a file with a different name that is ordered later).
Packages should install their configuration files in /usr/lib/ (distribution packages) or /usr/local/lib/ (local installs). Files in /etc/ are reserved for the local administrator, who may use this logic to override the configuration files installed by vendor packages.
It is recommended to prefix all filenames with a two-digit number and a dash, to simplify the ordering of the files.
If the administrator wants to disable a configuration file supplied by the vendor, the
recommended way is to place a symlink to /dev/null in the configuration directory in /etc/, with the same filename as the vendor configuration file. If the vendor
configuration file is included in the initrd image, the image has to be regenerated.
2.Ensure prelink is not installed
prelink is a program that modifies ELF shared libraries and ELF dynamically linked
binaries in such a way that the time needed for the dynamic linker to perform relocations at startup significantly decreases
The prelinking feature can interfere with the operation of AIDE, because it changes
binaries. Prelinking can also increase the vulnerability of the system if a malicious user is able to compromise a common library such as libc.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' prelink
restore binaries
prelink -ua
apt purge prelink
3.Ensure Automatic Error Reporting is not enabled
dpkg-query -s apport > /dev/null 2>&1 && grep -Psi -- '^\h*enabled\h*=\h*[^0]\b' /etc/default/apport
systemctl is-active apport.service | grep '^active'
/etc/default/apport
enabled=0
systemctl stop apport.service
systemctl --now disable apport.service
or
apt purge apport
4.Ensure core dumps are restricted
grep -Es '^(\*|\s).*hard.*core.*(\s+#.*)?$' /etc/security/limits.conf
/etc/security/limits.d/*
* hard core 0
# /sbin/sysctl fs.suid_dumpable
fs.suid_dumpable = 0
# grep "fs.suid_dumpable" /etc/sysctl.conf /etc/sysctl.d/*
fs.suid_dumpable = 0
systemctl is-enabled coredump.service
If enabled, masked, or disabled is returned systemd-coredump is installed
Add the following line to /etc/security/limits.conf or a /etc/security/limits.d/*
file:
* hard core 0
fs.suid_dumpable = 0
#sysctl -w fs.suid_dumpable=0
for systemd-coredump
/etc/systemd/coredump.conf
Storage=none
ProcessSizeMax=0
systemctl daemon-reload
1.6. Mandatory Access Control
Mandatory Access Control (MAC) provides an additional layer of access restrictions to processes on top of the base Discretionary Access Controls. By restricting how
processes can access files and resources on a system the potential impact from
vulnerabilities in the processes can be reduced.
Impact: Mandatory Access Control limits the capabilities of applications and daemons on a system, while this can prevent unauthorized access the configuration of MAC can be complex and difficult to implement correctly preventing legitimate access from occurring.
Notes:
- Apparmor is the default MAC provided with Debian systems.
- Additional Mandatory Access Control systems to include SELinux exist.
Configure AppArmor
AppArmor provides a Mandatory Access Control (MAC) system that greatly augments the default Discretionary Access Control (DAC) model. Under AppArmor MAC rules are applied by file paths instead of by security contexts as in other MAC systems. As such it does not require support in the filesystem and can be applied to network mounted filesystems for example. AppArmor security policies define what system resources applications can access and what privileges they can do so with. This automatically limits the damage that the software can do to files accessible by the calling user. The user does not need to take any action to gain this benefit. For an action to occur, both the traditional DAC permissions must be satisfied as well as the AppArmor MAC rules.
The action will not be allowed if either one of these models does not permit the action. In this way, AppArmor rules can only make a system's permissions more restrictive and secure.
References:
1. AppArmor Documentation: http://wiki.apparmor.net/index.php/Documentation
2. Ubuntu AppArmor Documentation: https://help.ubuntu.com/community/AppArmor
3. SUSE AppArmor Documentation:
https://www.suse.com/documentation/apparmor/
1.Ensure AppArmor is installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
apparmor apparmor-utils
apt install apparmor apparmor-utils
2.Ensure AppArmor is enabled in the bootloader configuration
grep "^\s*linux" /boot/grub/grub.cfg | grep -v "apparmor=1"
grep "^\s*linux" /boot/grub/grub.cfg | grep -v "security=apparmor"
cat etc/default/grub
GRUB_CMDLINE_LINUX="apparmor=1 security=apparmor"
3.Ensure all AppArmor Profiles are in enforce or complain mode
apparmor_status | grep profiles
37 profiles are loaded.
35 profiles are in enforce mode.
2 profiles are in complain mode.
4 processes have profiles defined
apparmor_status | grep processes
4 processes have profiles defined.
4 processes are in enforce mode.
0 processes are in complain mode.
0 processes are unconfined but have a profile defined.
4.set all profile to enforce mode
#aa-enforce /etc/apparmor.d/*
set all profile to complain mode
#aa-complain /etc/apparmor.d/*
1.7.Command Line Warning Banners
Presenting a warning message prior to the normal user login may assist in the
prosecution of trespassers on the computer system. Changing some of these login
banners also has the side effect of hiding OS version information and other detailed
system information from attackers attempting to target specific exploits at a system.
The/etc/motd, /etc/issue, and /etc/issue.net files govern warning banners for standardvcommand line logins for both local and remote users.
Guidelines published by the US Department of Defense require that warning messagesvinclude at least the name of the organization that owns the system, the fact that thevsystem is subject to monitoring and that such monitoring is in compliance with localvstatutes, and that use of the system implies consent to such monitoring. It is importantvthat the organization's legal counsel review the content of all messages before anyvsystem modifications are made, as these warning messages are inherently site-specific.
More information (including citations of relevant case law) can be found at
http://www.justice.gov/criminal/cybercrime/
Note: The text provided in the remediation actions for these items is intended as an
example only. Please edit to include the specific text for your organization as approved by your legal department
1.Ensure message of the day is configured properly
The contents of the /etc/motd file are displayed to users after login and function as a message of the day for authenticated users.
grep -Eis "(\\\v|\\\r|\\\m|\\\s|$(grep '^ID=' /etc/os-release | cut -d= -f2
| sed -e 's/"//g'))" /etc/motd
Remediation:
Edit the /etc/motd file with the appropriate contents according to your site policy,
remove any instances of \m(machine arch) , \r(os release , \s(os name) , \v(os version) or references to the OS platform OR if the motd is not used, this file can be removed.
# rm /etc/motd
2.Ensure local login warning banner is configured properly
The contents of the /etc/issue file are displayed to users prior to login for local
terminals.
echo "Authorized uses only. All activity may be monitored and reported." >
/etc/issue
3.Ensure remote login warning banner is configured properly
The contents of the /etc/issue.net file are displayed to users prior to login for remote connections from configured services.
4.Ensure permissions on /etc/motd are configured
un the following command and verify: Uid and Gid are both 0/root and Access is 644,or the file doesn't exist
stat -L /etc/motd
# chown root:root $(readlink -e /etc/motd)
# chmod u-x,go-wx $(readlink -e /etc/motd)
or
# rm /etc/motd
5.Ensure permissions on /etc/issue are configured
stat -L /etc/issue
chown root:root $(readlink -e /etc/issue)
# chmod u-x,go-wx $(readlink -e /etc/issue)
6.Ensure permissions on /etc/issue.net are configured
stat -L /etc/issue.net
1.8. GNOME Display Manager
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' gdm3
apt purge gdm3
Ensure GDM login b
anner is configured
https://help.gnome.org/admin/system-admin-guide/stable/login-banner.html.en
/etc/dconf/db/gdm.d/01-banner-message
Ensure GDM disable-user-list option is enabled
/etc/dconf/profile/gdm
user-db:user\nsystem-db:gdm\nfile-db:/usr/share/gdm/greeter-dconf-defaults
/etc/dconf/db/gdm/00-login-screen
[org/gnome/login-screen]
disable-user-list=true
dconf update
Ensure GDM screen locks when the user is idle
idle-delay=uint32 {n}
lock-delay=uint32 {n}
[org/gnome/desktop/session]
idle-delay=uint32 900
[org/gnome/desktop/screensaver]
lock-delay=uint32 5
idle-delay=uint32 Should be 900 seconds (15 minutes) or less, not 0 (disabled)
and follow local site policy
lock-delay=uint32 should be 5 seconds or less and follow local site policy
/etc/dconf/profile/
user-db:user
system-db:{NAME_OF_DCONF_DATABASE}
echo -e '\nuser-db:user\nsystem-db:local' >> /etc/dconf/profile/user
mkdir /etc/dconf/db/local.d
Create the key file `/etc/dconf/db/{NAME_OF_DCONF_DATABASE}./{FILE_NAME} to provide information for the {NAME_OF_DCONF_DATABASE} database
/etc/dconf/db/local.d/00-screensaver
[org/gnome/desktop/session]
idle-delay=uint32 900
[org/gnome/desktop/screensaver]
lock-delay=uint32 5
dconf update
Users must log out and back in again before the system-wide settings take effect.
https://help.gnome.org/admin/system-admin-guide/stable/desktop-lockscreen.html.en
Ensure GDM screen locks cannot be overridden
to lock down a dconf key or subpath, create a locks subdirectory in the keyfile directory.
The files inside this directory contain a list of keys or subpaths to lock. Just as with the keyfiles, you may add any number of files to this directory.
/org/gnome/desktop/session/idle-delay
/org/gnome/desktop/screensaver/lock-delay
Setting a lock-out value reduces the window of opportunity for unauthorized user access
to another user's session that has been left unattended.
Without locking down the system settings, user settings take precedence over the
system settings.
https://help.gnome.org/admin/system-admin-guide/stable/dconf-lockdown.html.en
Ensure GDM automatic mounting of removable media is disabled
https://access.redhat.com/solutions/20107
gsettings set org.gnome.desktop.media-handling automount false
gsettings set org.gnome.desktop.media-handling automount-open false
systemctl restart gdm.service
cat
/etc/dconf/db/local.d/00-media-automount
org/gnome/desktop/media-handling] automount=false automount-open=false
dconf update
Ensure GDM disabling automatic mounting of removable media is not overridden
org/gnome/desktop/media-handling/automount
/org/gnome/desktop/media-handling/automount-open
Ensure GDM autorun-never is enabled
cat /etc/dconf/db/local.d/00-media-autorun
[org/gnome/desktop/media-handling]
autorun-never=true
dconf update
lock file
Lock desktop media-handling settings
/org/gnome/desktop/media-handling/autorun-never
/etc/dconf/db/local.d/locks/00-media-autorun
/org/gnome/desktop/media-handling/autorun-never
Ensure XDCMP is not enabled
X Display Manager Control Protocol (XDMCP) is designed to provide authenticated
access to display management services for remote displays
XDMCP is inherently insecure.
XDMCP is not a ciphered protocol. This may allow an attacker to capture
keystrokes entered by a user
XDMCP is vulnerable to man-in-the-middle attacks. This may allow an attacker to
steal the credentials of legitimate users by impersonating the XDMCP server.
grep -Eis '^\s*Enable\s*=\s*true' /etc/gdm3/custom.conf
remove line Enable=true from /etc/gdm3/custom.conf
9.Ensure updates, patches, and additional security software are installed
apt -s upgrade
apt upgrade
upgrade - is used to install the newest versions of all packages currently installed
on the system from the sources enumerated in /etc/apt/sources.list. Packages
currently installed with new versions available are retrieved and upgraded; under
no circumstances are currently installed packages removed, or packages not
already installed retrieved and installed. New versions of currently installed
packages that cannot be upgraded without changing the install status of another
package will be left at their current version. An update must be performed first so
that apt knows that new versions of packages are available.
apt dist-upgrade
dist-upgrade - in addition to performing the function of upgrade, also intelligently
handles changing dependencies with new versions of packages; apt has a
"smart" conflict resolution system, and it will attempt to upgrade the most
important packages at the expense of less important ones if necessary. So, dist-
upgrade command may remove some packages. The /etc/apt/sources.list file
contains a list of locations from which to retrieve desired package files. See also
apt_preferences(5) for a mechanism for overriding the general settings for
individual packages.
2. Services
2.1. Configure Time Synchronization
it is recommended that physical systems and virtual guests lacking direct access to the physical host's clock be configured to synchronize their time using a service such as systemd-timesyncd, chrony, or ntp
Time synchronization is important to support time sensitive security mechanisms and ensures log files have consistent time records across the enterprise, which aids in forensic investigations.
One of the three time synchronization daemons should be available; chrony, systemd-timesyncd, or ntp
apt purge ntp chrony
grep -Pr --include=*.{sources,conf} '^\h*(server|pool)\h+\H+' /etc/chrony/
pool time.nist.gov iburst maxsources 4 #The maxsources option is unique to
the pool directive
server time-a-g.nist.gov iburst
server 132.163.97.3 iburst
server time-d-b.nist.gov iburst
Edit /etc/chrony/chrony.conf or a file ending in .sources in /etc/chrony/sources.d/
systemctl restart chronyd
chronyc reload sources
https://tf.nist.gov/tf-cgi/servers.cgi
Ensure chrony is running as user _chrony
ps -ef | awk '(/[c]hronyd/ && $1!="_chrony") { print $1 }'
add or edit the user line to /etc/chrony/chrony.conf or a file ending in .conf in
/etc/chrony/conf.d/:
user _chrony
systemctl is-enabled chrony.service
systemctl is-active chrony.service
Configure systemd-timesyncd
/usr/lib/systemd/*.conf.d/, /usr/local/lib/systemd/*.conf.d/, and
/etc/systemd/*.conf.d/
The systemd-timesyncd service specifically implements only SNTP
find /etc/systemd -type f -name '*.conf' -exec grep -Ph '^\h*(NTP|FallbackNTP)=\H+' {} +
/etc/systemd/timesyncd.conf.d/time.conf
[Time]
NTP=time.nist.gov # Uses the generic name for NIST's time servers
-AND/OR-
FallbackNTP=time-a-g.nist.gov time-b-g.nist.gov time-c-g.nist.gov # Space
separated list of NIST time servers
systemctl try-reload-or-restart systemd-timesyncd
https://www.freedesktop.org/software/systemd/man/timesyncd.conf.html
systemctl is-enabled systemd-timesyncd.service
NTP
ntp Access Control Commands:
restrict address [mask mask] [ippeerlimit int] [flag ...]
The address argument expressed in dotted-quad form is the address of a host or
network. Alternatively, the address argument can be a valid host DNS name.
The mask argument expressed in dotted-quad form defaults to 255.255.255.255,
meaning that the address is treated as the address of an individual host. A default entry (address 0.0.0.0, mask 0.0.0.0) is always included and is always the first entry in the list.
Note: the text string default, with no mask option, may be used to indicate the
default entry.
The ippeerlimit directive limits the number of peer requests for each IP to int, where a value of -1 means "unlimited", the current default. A value of 0 means "none". There would usually be at most 1 peering request per IP, but if the remote peering requests are behind a proxy there could well be more than 1 per IP.
In the current implementation, flag always restricts access, i.e., an entry with no flags indicates that free access to the server is to be given. The flags are not orthogonal, in that more restrictive flags will often make less restrictive ones redundant. The flags can generally be classed into two categories, those which
restrict time service and those which restrict informational queries and attempts to do run-time reconfiguration of the server.
cat /etc/ntp.conf
restrict -4 default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
Ensure ntp is running as user ntp
grep -P -- '^\h*RUNASUSER=' /etc/init.d/ntp
RUNASUSER=ntp
ps -ef | awk '(/[n]tpd/ && $1!="ntp") { print $1 }'
2.2.Special Purpose Services
1. Ensure X Window System is not installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
xserver-xorg* | grep -Pi '\h+installed\b'
apt purge xserver-xorg*
2. Ensure Avahi Server is not installed
Avahi is a free zeroconf implementation, including a system for multicast DNS/DNS-SD service discovery. Avahi allows programs to publish and discover services and hosts running on a local network with no specific configuration.
For example, a user can plug a computer into a network and Avahi automatically finds printers to print to, files to look at and people to talk to, as well as network services running on the machine.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
avahi-daemon
# systemctl stop avahi-daaemon.service
# systemctl stop avahi-daemon.socket
# apt purge avahi-daemon
3. Ensure CUPS is not installed
The Common Unix Print System (CUPS) provides the ability to print to both local and network printers. A system running CUPS can also accept print jobs from remote systems and print them to local printers. It also provides a web based remote administration capability.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' cups
apt purge cups
4. Ensure DHCP Server is not installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' isc-
dhcp-server
apt purge isc-dhcp-server
5. Ensure LDAP server is not installed
The Lightweight Directory Access Protocol (LDAP) was introduced as a replacement for NIS/YP. It is a service that provides a method for looking up information from a central database.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
slapd
apt purge slapd
6. Ensure NFS is not installed
The Network File System (NFS) is one of the first and most widely distributed file
systems in the UNIX environment. It provides the ability for systems to mount file
systems of other servers through the network.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' nfs-
kernel-server
apt purge nfs-kernel-server
7. Ensure DNS Server is not installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
bind9
apt purge bind9
8. Ensure FTP Server is not installed
TP does not protect the confidentiality of data or authentication credentials. It is
recommended SFTP be used if file transfer is required. Unless there is a need to run the system as a FTP server (for example, to allow anonymous downloads), it is
recommended that the package be deleted to reduce the potential attack surface
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
vsftpd
apt purge vsftpd
9. Ensure HTTP server is not installed
HTTP or web servers provide the ability to host web site content.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
apache2
apt purge apache2 nginx
10. Ensure IMAP and POP3 server are not installed
dovecot-imapd and dovecot-pop3d are an open source IMAP and POP3 server for Linux based systems.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
dovecot-imapd dovecot-pop3d
courier-imap and cyrus-imap
11. Ensure Samba is not installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
samba
apt purge samba
12. Ensure HTTP Proxy Server is not installed
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n'
squid
13. Ensure SNMP Server is not installed
Simple Network Management Protocol (SNMP) is a widely used protocol for monitoring the health and welfare of network equipment, computer equipment and devices like UPSs.
Net-SNMP is a suite of applications used to implement SNMPv1 (RFC 1157), SNMPv2 (RFCs 1901-1908), and SNMPv3 (RFCs 3411-3418) using both IPv4 and IPv6. Support for SNMPv2 classic (a.k.a. "SNMPv2 historic" - RFCs 1441-1452) was dropped
with the 4.0 release of the UCD-snmp package. The Simple Network Management Protocol (SNMP) server is used to listen for SNMP commands from an SNMP management system, execute the commands or collect the information and then send results back to the requesting system.
SNMPv1, which transmits data in the clear and does not require authentication to execute commands.
SNMPv3 replaces the simple/clear text password sharing used in SNMPv2 with more securely encoded parameters.
If the the SNMP service is not required, the net-snmp package should be removed to reduce the attack surface of the system
Note: If SNMP is required:
The server should be configured for SNMP v3 only. User Authentication and
Message Encryption should be configured.
If SNMP v2 is absolutely necessary, modify the community strings' values.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' snmp
apt purge snmp
14. Ensure NIS Server is not installed
The Network Information Service (NIS) (formally known as Yellow Pages) is a client- server directory service protocol for distributing system configuration files. The NIS server is a collection of programs that allow for the distribution of configuration files.
The NIS service is inherently an insecure system that has been vulnerable to DOS
attacks, buffer overflows and has poor authentication for querying NIS maps. NIS
generally has been replaced by such protocols as Lightweight Directory Access
Protocol (LDAP). It is recommended that the service be removed and other, more
secure services be used
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' nis
apt purge nis
15. Ensure mail transfer agent is configured for local-only mode
Mail Transfer Agents (MTA), such as sendmail and Postfix, are used to listen for
incoming mail and transfer the messages to the appropriate user or mail server. If the system is not intended to be a mail server, it is recommended that the MTA be
configured to only process local mail.
ss -lntu | grep -E ':25\s' | grep -E -v '\s(127.0.0.1|::1):25\s'
/etc/postfix/main.cf
inet_interfaces = loopback-only
# systemctl restart postfix
16. Ensure rsync service is either not installed or masked
The rsync service can be used to synchronize files between systems over network
links.
The rsync service presents a security risk as it uses unencrypted protocols for
communication. The rsync package should be removed to reduce the attack area of the system.
dpkg-query -W -f='${binary:Package}\t${Status}\t${db:Status-Status}\n' rsync
apt purge rsync
systemctl stop rsync
systemctl mask rsync
2.3. Service Clients
Ensure NIS,rsh,talk,telnet,ldap,RPC client is not installed
rsh :
these legacy clients contain numerous security exposures and have been replaced withthe more secure SSH package. Even if the server is removed, it is best to ensure the clients are also removed to prevent users from inadvertently attempting to use these commands and therefore exposing their credentials. Note that removing the rsh package removes the clients for rsh , rcp and rlogin .
talk:
The talk software makes it possible for users to send and receive messages across
systems through a terminal session. The talk client, which allows initialization of talk sessions, is installed by default
telnet:
The telnet protocol is insecure and unencrypted. The use of an unencrypted
transmission medium could allow an unauthorized user to steal credentials. The ssh
package provides an encrypted session and stronger security and is included in most Linux distributions.
RPC:
Remote Procedure Call (RPC) is a method for creating low level client server
applications across different system architectures. It requires an RPC compliant client listening on a network port. The supporting package is rpcbind."
apt purge nis rsh-client talk telnet ldap-utils rpcbind
2.4. Ensure nonessential services are removed or masked
A listening port is a network port on which an application or process listens on, acting as a communication endpoint.
Each listening port can be open or closed (filtered) using a firewall. In general terms, an open port is a network port that accepts incoming packets from remote locations.
services should be reviewed, and if not required, the service should be stopped, and the package containing the service should be removed. If required packages have a dependency, the service should be stopped and masked to reduce the attack surface of the system.
# systemctl stop <service_name>.service
# systemctl mask <service_name>.socket
# systemctl mask <service_name>.service
3. Network Configuration
and /etc/sysctl.d/.
and put new settings there.
/etc/sysctl.d/ and put new settings there.
in /etc/ufw/sysctl.conf
/etc/sysctl.conf
/etc/default/ufw
3.1.Disable unused network protocols and devices
1. Ensure system is checked to determine if IPv6 is enabled
- Hierarchical addressing and routing infrastructure
- Stateful and Stateless configuration
- Support for quality of service (QoS)
- An ideal protocol for neighboring node interaction
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
" >> /etc/sysctl.d/60-disable_ipv6.conf
sysctl -w net.ipv6.conf.all.disable_ipv6=1
sysctl -w net.ipv6.conf.default.disable_ipv6=1
sysctl -w net.ipv6.route.flush=1
}
2. Ensure wireless interfaces are disabled
3. Ensure DCCP is disabled
insmod /lib/modules/6.1.0-10-amd64/kernel/net/dccp/dccp.ko
4. Ensure SCTP is disabled
3.2.Network Parameters (Host Only)
does not act as a router (in a host only configuration), there is no need to send
redirects.
router devices in an attempt to corrupt routing and have users access a system set up by the attacker as opposed to a valid system.
3.3. Network Parameters (Host and Router)
1.Ensure source routed packets are not accepted
packets take through a network. In contrast, non-source routed packets travel a path determined by routers in the network. In some cases, systems may not be routable or reachable from some locations (e.g. private addresses vs. Internet routable), and so source routed packets would need to be used.
capable of routing packets to Internet routable addresses on one interface and private addresses on another interface. Assume that the private addresses were not routable to the Internet routable addresses and vice versa. Under normal routing circumstances, an attacker from the Internet routable addresses could not use the system as a way to reach the private address systems. If, however, source routed packets were allowed, they could be used to gain access to the private address systems as the route could be specified, rather than rely on routing protocols that did not allow this routing.
2. Ensure ICMP redirects are not accepted
routing tables and get them to send packets to incorrect networks and allow your
system packets to be captured.
3. Ensure secure ICMP redirects are not accepted
gateways listed on the default gateway list. It is assumed that these gateways are
known to your system, and that they are likely to be secure.
4. Ensure suspicious packets are logged
kernel log.
5. Ensure broadcast ICMP requests are ignored
ICMP echo and timestamp requests to broadcast and multicast addresses.
Accepting ICMP echo and timestamp requests with broadcast or multicast destinations for your network could be used to trick your host into starting (or participating) in a Smurf attack. A Smurf attack relies on an attacker sending large amounts of ICMP broadcast messages with a spoofed source address. All hosts receiving this message and responding would send echo-reply messages back to the spoofed address, which is probably not routable. If many hosts respond to the packets, the amount of traffic on the network could be significantly multiplied.
6. Ensure bogus ICMP responses are ignored
bogus responses (RFC-1122 non-compliant) from broadcast reframes, keeping file
systems from filling up with useless log messages.
attempt to fill up a log file system with many useless error messages.
7.Ensure Reverse Path Filtering is enabled
forces the Linux kernel to utilize reverse path filtering on a received packet to determine if the packet was valid. Essentially, with reverse path filtering, if the return packet does not go out the same interface that the corresponding source packet came from, the packet is dropped (and logged if log_martians is set).
8. Ensure TCP SYN Cookies is enabled
9. Ensure IPv6 router advertisements are not accepted
3.5. Firewall Configuration
register callback functions with the network stack. A registered callback function
is then called back for every packet that traverses the respective hook within the
network stack. Includes the ip_tables, ip6_tables, arp_tables, and ebtables kernel
modules. These modules are some of the significant parts of the Netfilter hook
system.
network packets/datagrams/frames. nftables is supposed to replace certain parts
of Netfilter, while keeping and reusing most of it. nftables utilizes the building
blocks of the Netfilter infrastructure, such as the existing hooks into the
networking stack, connection tracking system, userspace queueing component,
and logging subsystem. Is available in Linux kernels 3.13 and newer.
In order to configure firewall rules for Netfilter or nftables, a firewall utility needs to be installed.
for the Linux kernel's netfilter framework via the iptables backend. ufw supports
both IPv4 and IPv6 networks
Linux kernel
configuration Netfilter and the ip_tables, ip6_tables, arp_tables, and ebtables
kernel modules.
1. Configure UncomplicatedFirewall
commands
applied.
# ufw allow out on lo
# ufw deny in from 127.0.0.0/8
# ufw deny in from ::1
ufw_out="$(ufw status verbose)"
ss -tuln | awk '($5!~/%lo:/ && $5!~/127.0.0.1:/ && $5!~/::1/) {split($5, a,
":"); print a[2]}' | sort | uniq | while read -r lpn; do
! grep -Pq "^\h*$lpn\b" <<< "$ufw_out" && echo "- Port: \"$lpn\" is
missing a firewall rule"
done
ufw allow in http
ufw allow out http <- required for apt to connect to repository
ufw allow in https
ufw allow out https
ufw allow out 53
ufw logging on
# ufw default deny outgoing
# ufw default deny routed
2. Configure nftables
# flush nftables rulesset
flush ruleset
# Load nftables ruleset
# nftables config with inet table named filter
To make these changes permanent:
Run the following command to create the nftables.rules file
would flow through those chains will not be touched by nftables.
<(input|forward|output)> priority 0 \; }
# nft add rule inet filter input ip protocol udp ct state established accept
# nft add rule inet filter input ip protocol icmp ct state established accept
# nft add rule inet filter output ip protocol tcp ct state
new,related,established accept
# nft add rule inet filter output ip protocol udp ct state
new,related,established accept
# nft add rule inet filter output ip protocol icmp ct state
new,related,established accept
# nft chain inet filter forward { policy drop \; }
# nft chain inet filter output { policy drop \; }
3. configure iptables
ebtables to Ethernet frames.
# iptables -P OUTPUT DROP
# iptables -P FORWARD DROP
# iptables -A OUTPUT -o lo -j ACCEPT
# iptables -A INPUT -s 127.0.0.0/8 -j DROP
# iptables -A OUTPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT
# iptables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT
# iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT
# iptables -A INPUT -p udp -m state --state ESTABLISHED -j ACCEPT
# iptables -A INPUT -p icmp -m state --state ESTABLISHED -j ACCEPT
ACCEPT
# ip6tables -P OUTPUT DROP
# ip6tables -P FORWARD DROP
# ip6tables -A OUTPUT -o lo -j ACCEPT
# ip6tables -A INPUT -s ::1 -j DROP
# ip6tables -A OUTPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT
# ip6tables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT
# ip6tables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT
# ip6tables -A INPUT -p udp -m state --state ESTABLISHED -j ACCEPT
# ip6tables -A INPUT -p icmp -m state --state ESTABLISHED -j ACCEPT
ACCEPT
4. Logging and Auditing
summarization) and auditd be used for auditing (with aureport providing
summarization) to automatically monitor logs for intrusion attempts and other suspicious system behavior.
4.1. Configure System Accounting (auditd)
system activity to facilitate incident investigation, detect unauthorized access or
modification of data. By default events will be logged to /var/log/audit/audit.log,
which can be configured in /etc/audit/auditd.conf.
The following types of audit rules can be specified:
makes.
across reboots.
they are active.
auditd audispd-plugins
max_log_file_action = keep_logs
action_mail_acct = root
-w /etc/sudoers -p wa -k scope
-w /etc/sudoers.d -p wa -k scope
" >> /etc/audit/rules.d/50-scope.rules
required to load rules\n"; fi
-a always,exit -F arch=b64 -C euid!=uid -F auid!=unset -S execve -k
user_emulation
-a always,exit -F arch=b32 -C euid!=uid -F auid!=unset -S execve -k
user_emulation
" >> /etc/audit/rules.d/50-user_emulation.rules
required to load rules\n"; fi
SUDO_LOG_FILE=$(grep -r logfile /etc/sudoers* | sed -e 's/.*logfile=//;s/,?
.*//' -e 's/"//g')
[ -n "${SUDO_LOG_FILE}" ] && printf "
-w ${SUDO_LOG_FILE} -p wa -k sudo_log_file
" >> /etc/audit/rules.d/50-sudo.rules || printf "ERROR: Variable
'SUDO_LOG_FILE_ESCAPED' is unset.\n"
}
-a always,exit -F arch=b64 -S adjtimex,settimeofday,clock_settime -k time-
change
-a always,exit -F arch=b32 -S adjtimex,settimeofday,clock_settime -k time-
change
-w /etc/localtime -p wa -k time-change
" >> /etc/audit/rules.d/50-time-change.rules
-a always,exit -F arch=b64 -S sethostname,setdomainname -k system-locale
-a always,exit -F arch=b32 -S sethostname,setdomainname -k system-locale
-w /etc/issue -p wa -k system-locale
-w /etc/issue.net -p wa -k system-locale
-w /etc/hosts -p wa -k system-locale
-w /etc/networks -p wa -k system-locale
-w /etc/network/ -p wa -k system-locale
" >> /etc/audit/rules.d/50-system_local.rules
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
AUDIT_RULE_FILE="/etc/audit/rules.d/50-privileged.rules"
NEW_DATA=()
for PARTITION in $(findmnt -n -l -k -it $(awk '/nodev/ { print $2 }'
/proc/filesystems | paste -sd,) | grep -Pv "noexec|nosuid" | awk '{print
$1}'); do
readarray -t DATA < <(find "${PARTITION}" -xdev -perm /6000 -type f | awk
-v UID_MIN=${UID_MIN} '{print "-a always,exit -F path=" $1 " -F perm=x -F
auid>="UID_MIN" -F auid!=unset -k privileged" }')
for ENTRY in "${DATA[@]}"; do
NEW_DATA+=("${ENTRY}")
done
done
readarray &> /dev/null -t OLD_DATA < "${AUDIT_RULE_FILE}"
COMBINED_DATA=( "${OLD_DATA[@]}" "${NEW_DATA[@]}" )
printf '%s\n' "${COMBINED_DATA[@]}" | sort -u > "${AUDIT_RULE_FILE}"
}
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F arch=b64 -S creat,open,openat,truncate,ftruncate -F exit=-
EACCES -F auid>=${UID_MIN} -F auid!=unset -k access
-a always,exit -F arch=b64 -S creat,open,openat,truncate,ftruncate -F exit=-
EPERM -F auid>=${UID_MIN} -F auid!=unset -k access
-a always,exit -F arch=b32 -S creat,open,openat,truncate,ftruncate -F exit=-
EACCES -F auid>=${UID_MIN} -F auid!=unset -k access
-a always,exit -F arch=b32 -S creat,open,openat,truncate,ftruncate -F exit=-
EPERM -F auid>=${UID_MIN} -F auid!=unset -k access
" >> /etc/audit/rules.d/50-access.rules || printf "ERROR: Variable 'UID_MIN'
is unset.\n"
}
-w /etc/group -p wa -k identity
-w /etc/passwd -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/security/opasswd -p wa -k identity
" >> /etc/audit/rules.d/50-identity.rules
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F arch=b64 -S chmod,fchmod,fchmodat -F auid>=${UID_MIN} -F
auid!=unset -F key=perm_mod
-a always,exit -F arch=b64 -S chown,fchown,lchown,fchownat -F
auid>=${UID_MIN} -F auid!=unset -F key=perm_mod
-a always,exit -F arch=b32 -S chmod,fchmod,fchmodat -F auid>=${UID_MIN} -F
auid!=unset -F key=perm_mod
-a always,exit -F arch=b32 -S lchown,fchown,chown,fchownat -F
auid>=${UID_MIN} -F auid!=unset -F key=perm_mod
-a always,exit -F arch=b64 -S
setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F
auid>=${UID_MIN} -F auid!=unset -F key=perm_mod
-a always,exit -F arch=b32 -S
setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F
auid>=${UID_MIN} -F auid!=unset -F key=perm_mod
" >> /etc/audit/rules.d/50-perm_mod.rules || printf "ERROR: Variable
'UID_MIN' is unset.\n"
}
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F arch=b32 -S mount -F auid>=$UID_MIN -F auid!=unset -k
mounts
-a always,exit -F arch=b64 -S mount -F auid>=$UID_MIN -F auid!=unset -k
mounts
" >> /etc/audit/rules.d/50-mounts.rules || printf "ERROR: Variable 'UID_MIN'
is unset.\n"
}
-w /var/run/utmp -p wa -k session
-w /var/log/wtmp -p wa -k session
-w /var/log/btmp -p wa -k session
" >> /etc/audit/rules.d/50-session.rules
-w /var/log/lastlog -p wa -k logins
-w /var/run/faillock -p wa -k logins
" >> /etc/audit/rules.d/50-login.rules
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F arch=b64 -S rename,unlink,unlinkat,renameat -F
auid>=${UID_MIN} -F auid!=unset -F key=delete
-a always,exit -F arch=b32 -S rename,unlink,unlinkat,renameat -F
auid>=${UID_MIN} -F auid!=unset -F key=delete
" >> /etc/audit/rules.d/50-delete.rules || printf "ERROR: Variable 'UID_MIN'
is unset.\n"
}
-w /etc/apparmor/ -p wa -k MAC-policy
-w /etc/apparmor.d/ -p wa -k MAC-policy
" >> /etc/audit/rules.d/50-MAC-policy.rules
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F path=/usr/bin/chcon -F perm=x -F auid>=${UID_MIN} -F
auid!=unset -k perm_chng
" >> /etc/audit/rules.d/50-perm_chng.rules || printf "ERROR: Variable
'UID_MIN' is unset.\n"
}
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F path=/usr/bin/setfacl -F perm=x -F auid>=${UID_MIN} -F
auid!=unset -k perm_chng
" >> /etc/audit/rules.d/50-perm_chng.rules || printf "ERROR: Variable
'UID_MIN' is unset.\n"
}
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F path=/usr/bin/chacl -F perm=x -F auid>=${UID_MIN} -F
auid!=unset -k perm_chng
" >> /etc/audit/rules.d/50-perm_chng.rules || printf "ERROR: Variable
'UID_MIN' is unset.\n"
}
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F path=/usr/sbin/usermod -F perm=x -F auid>=${UID_MIN} -F
auid!=unset -k usermod
" >> /etc/audit/rules.d/50-usermod.rules || printf "ERROR: Variable 'UID_MIN'
is unset.\n"
}
UID_MIN=$(awk '/^\s*UID_MIN/{print $2}' /etc/login.defs)
[ -n "${UID_MIN}" ] && printf "
-a always,exit -F arch=b64 -S
init_module,finit_module,delete_module,create_module,query_module -F
auid>=${UID_MIN} -F auid!=unset -k kernel_modules
-a always,exit -F path=/usr/bin/kmod -F perm=x -F auid>=${UID_MIN} -F
auid!=unset -k kernel_modules
" >> /etc/audit/rules.d/50-kernel_modules.rules || printf "ERROR: Variable
'UID_MIN' is unset.\n"
}
" >> /etc/audit/rules.d/99-finalize.rules
/usr/sbin/augenrules: No change
to load rules"; fi
'/^\s*log_file/ {print $2}' /etc/audit/auditd.conf | xargs))" -type f \( ! -
perm 600 -a ! -perm 0400 -a ! -perm 0200 -a ! -perm 0000 -a ! -perm 0640 -a !
-perm 0440 -a ! -perm 0040 \) -exec chmod u-x,g-wx,o-rwx {} +
'/^\s*log_file/ {print $2}' /etc/audit/auditd.conf | xargs))" -type f ! -user
root -exec chown root {} +
audit log files
/etc/audit/auditd.conf | xargs)) -type f \( ! -group adm -a ! -group root \)
-exec chgrp adm {} +
/etc/audit/auditd.conf
/etc/audit/auditd.conf))"
chmod u-x,g-wx,o-rwx {} +
root -exec chown root {} +
root -exec chgrp root {} +
/sbin/auditd /sbin/augenrules
/sbin/auditd /sbin/augenrules | grep -Pv -- '^\h*\H+\h+root\h*$'
/sbin/auditd /sbin/augenrules
/sbin/autrace /sbin/auditd /sbin/augenrules | grep -Pv -- '^\h*\H+\h+([0-
7][0,1,4,5][0,1,4,5])\h+root\h+root\h*$'
/sbin/auditd /sbin/augenrules
the integrity of audit tools
/etc/aide/aide.conf
/sbin/auditd p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/ausearch p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/aureport p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/autrace p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/augenrules p+i+n+u+g+s+b+acl+xattrs+sha512
tools:
/sbin/auditctl p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/auditd p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/ausearch p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/aureport p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/autrace p+i+n+u+g+s+b+acl+xattrs+sha512
/sbin/augenrules p+i+n+u+g+s+b+acl+xattrs+sha512
4.2.Configure Logging
logs on a remote server so that they can be reviewed in the event of a system
compromise. A centralized log server provides a single point of entry for further
analysis, monitoring and filtering.
Security principals for logging
server.
What is covered
This section will cover the minimum best practices for the usage of either rsyslog or journald. The recommendations are written such that each is wholly independent of each other and only one is implemented.
for the collection and storage of logging data. It creates and maintains structured,
indexed journals based on logging information that is received from a variety of sources such as:
- Classic RFC3164 BSD syslog via the /dev/log socket
- STDOUT/STDERR of programs via StandardOutput=journal +StandardError= journal in service files (both of which are default settings)
- Kernel log messages via the /dev/kmsg device node
- Audit records via the kernel’s audit subsystem
- Structured log messages via journald’s native protocol
systemd-journald
ServerKeyFile=/etc/ssl/private/journal-upload.pem
ServerCertificateFile=/etc/ssl/certs/journal-upload.pem
TrustedCertificateFile=/etc/ssl/ca/trusted.pem
remote client
disk
SystemKeepFree=
RuntimeMaxUse=
RuntimeKeepFree=
MaxFileSec=
override all default settings as defined in /usr/lib/tmpfiles.d/systemd.conf and
should be inspected.
If there is no override file, inspect the default /usr/lib/tmpfiles.d/systemd.conf
against the site specific requirements.
Ensure that file permissions are 0640.
Should a site policy dictate less restrictive permissions, ensure to follow said policy.
NOTE: More restrictive permissions such as 0600 is implicitly sufficient.
required. Requirements is either 0640 or site policy if that is less restrictive
$FileCreateMode to 0640 or more restrictive:
appropriate for your environment.
auth,authpriv.* /var/log/secure
mail.* -/var/log/mail
mail.info -/var/log/mail.info
mail.warning -/var/log/mail.warn
mail.err /var/log/mail.err
cron.* /var/log/cron
*.=warning;*.=err -/var/log/warn
*.crit /var/log/warn
*.*;mail.none;news.none -/var/log/messages
local0,local1.* -/var/log/localmessages
local2,local3.* -/var/log/localmessages
local4,local5.* -/var/log/localmessages
local6,local7.* -/var/log/localmessages
action.resumeRetryCount="100"
queue.type="LinkedList" queue.size="1000")
$ModLoad imtcp
$InputTCPServerRun
module(load="imtcp")
input(type="imtcp" port="514")
run periodically at fixed times, dates, or intervals.
at provides the ability to execute a command or shell script at a specified date and
hour, or after a given interval of time.
Notes:
method is used, it should be secured in accordance with local site policy
.service files or events
- Timers can be used as an alternative to cron and at
- Timers have built-in support for calendar time events, monotonic time
5.2 Configure SSH Server
# chmod og-rwx /etc/ssh/sshd_config
configured
configured
wx {} \;
# find /etc/ssh -xdev -type f -name 'ssh_host_*_key.pub' -exec chown
root:root {} \;
OR
AllowGroups <grouplist>
OR
DenyUsers <userlist>
OR
DenyGroups <grouplist>
OR
LogLevel INFO
[email protected],aes256-ctr,aes192-ctr,aes128-ctr
2. https://www.openssh.com/txt/cbc.adv
3. https://nvd.nist.gov/vuln/detail/CVE-2008-5161
4. https://www.openssh.com/txt/cbc.adv
5. SSHD_CONFIG(5)
communication.
Notes:
o ecdh-sha2-nistp256
o ecdh-sha2-nistp384
o ecdh-sha2-nistp521
o diffie-hellman-group-exchange-sha256
o diffie-hellman-group16-sha512
o diffie-hellman-group18-sha512
o diffie-hellman-group14-sha256
group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-
sha512,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-
hellman-group-exchange-sha256
unauthenticated connections to the SSH daemon
ClientAliveCountMax 3
5.3.Configure privilege escalation
Defaults use_pty
disabled globally
Defaults timestamp_timeout=15
Defaults env_reset
Add the following line to the /etc/pam.d/su file, specifying the empty group:
auth required pam_wheel.so use_uid group=sugroup
5.4. configure PAM
authentication modules on UNIX systems. PAM is implemented as a set of shared
objects that are loaded and executed when a program needs to authenticate a user.
Files for PAM are typically located in the /etc/pam.d directory. PAM must be carefully
configured to secure system authentication. While this section covers some of PAM,
please consult other PAM resources to fully understand the configuration capabilities.
Note: The usage of pam-auth-update:
the required functionality implemented by the benchmark. As such, the usage of
pam-auth-update is not recommended at present.
The following options are set in the /etc/security/pwquality.conf file:
the new password (digits, uppercase, lowercase, others)
ucredit = -1
ocredit = -1
lcredit = -1
fail_interval = 900
unlock time = 600
latest standards
for pam_unix.so is set:
try_first_pass remember=5
algorithm
5.5. User Accounts and Environment
configured
/etc/shadow
do change=$(date -d "$(chage --list $usr | grep '^Last password change' | cut
-d: -f2 | grep -v 'never$')" +%s); \
if [[ "$change" -gt "$(date +%s)" ]]; then \
echo "User: \"$usr\" last password change was \"$(chage --list $usr | grep
'^Last password change' | cut -d: -f2)\""; fi; done
'/^\s*UID_MIN/{print $2}' /etc/login.defs)"' &&
$7!~/((\/usr)?\/sbin\/nologin)/ && $7!~/(\/bin)?\/false/ {print}' /etc/passwd
# awk -F: '($1!~/(root|^\+)/ && $3<'"$(awk '/^\s*UID_MIN/{print $2}'
/etc/login.defs)"') {print $1}' /etc/passwd | xargs -I '{}' passwd -S '{}' |
awk '($2!~/LK?/) {print $1}'
'/^\s*UID_MIN/{print $2}' /etc/login.defs)"' &&
$7!~/((\/usr)?\/sbin\/nologin)/ && $7!~/(\/bin)?\/false/ {print $1}'
/etc/passwd | while read -r user; do usermod -s "$(which nologin)" "$user";
done
/etc/login.defs)"') {print $1}' /etc/passwd | xargs -I '{}' passwd -S '{}' |
awk '($2!~/LK?/) {print $1}' | while read -r user; do usermod -L "$user";
done
or umask 027. If a four digit umask is used, the first digit is ignored. The remaining
three digits effect the resulting permissions for user, group, and world/other
respectively.
and world/other o. The permissions listed are not masked by umask. ie a umask
set by umask u=rwx,g=rx,o= is the Symbolic equivalent of the Octal umask 027.
This umask would set a newly created directory with file mode drwxr-x--- and a
newly created file with file mode rw-r-----.
Setting the default umask:
o will set the umask according to the system default in /etc/login.defs and
user settings, solving the problem of different umask settings with different
shells, display managers, remote sessions etc.
o umask=<mask> value in the /etc/login.defs file is interpreted as Octal
o Setting USERGROUPS_ENAB to yes in /etc/login.defs (default):
bits. (examples: 022 -> 002, 077 -> 007) for non-root users, if the
uid is the same as gid, and username is the same as the primary
group name
members, and useradd will create by default a group with the name
of the user
o /etc/profile - used to set system wide environmental variables on users
shells. The variables are sometimes the same ones that are in the
.profile, however this file is used to set an initial PATH or PS1 for all
shell users of the system. is only executed for interactive login shells, or
shells executed with the --login parameter
o /etc/profile.d - /etc/profile will execute the scripts within
/etc/profile.d/*.sh. It is recommended to place your configuration in a
shell script within /etc/profile.d to set your own system wide
environmental variables.
o /etc/bash.bashrc - System wide version of .bashrc. etc/bashrc also
invokes /etc/profile.d/*.sh if non-login shell, but redirects output to
/dev/null if non-interactive. Is only executed for interactive shells or
if BASH_ENV is set to /etc/bash.bashrc
prompt. Is only read by login shells
interactive and non-login
choice about their file permissions. A default umask setting of 077 causes files and
directories created by users to not be readable by any other user on the system. A
umask of 027 would make files and directories readable by users in the same Unix group, while a umask of 022 would make files readable by every user on the system.
useradd and userdel.
Setting USERGROUPS_ENAB yes in /etc/login.defs
6]\b|[0-7][01][0-7]\b|[0-7][0-7][0-
6]\b|(u=[rwx]{0,3},)?(g=[rwx]{0,3},)?o=[rwx]+\b|(u=[rwx]{1,3},)?g=[^rx]{1,3}(
,o=[rwx]{0,3})?\b)' /etc/login.defs /etc/profile* /etc/bash.bashrc*
USERGROUPS_ENAB no
Example: /etc/profile.d/set_umask.sh
umask 027
system, it is recommended that their configuration files also are checked.
6. System Maintenance
# chown root:root /etc/passwd
# chown root:root /etc/passwd-
# chown root:root /etc/group
0/root and Gid is 0/root
-OR-
# chown root:root /etc/shadow
-OR-
# chown root:root /etc/gshadow
-type f -perm -0002
-nouser
-nogroup
-type f -perm -4000
-type f -perm -2000
/etc/passwd
for i in $(cut -s -d: -f4 /etc/passwd | sort -u ); do
grep -q -P "^.*?:[^:]*:$i:" /etc/group
if [ $? -ne 0 ]; then
echo "Group $i is referenced by /etc/passwd but does not exist in
/etc/group"
fi
done
# awk -F: -v GID="$(awk -F: '($1=="shadow") {print $3}' /etc/group)"
'($4==GID) {print $1}' /etc/passwd
RPCV="$(sudo -Hiu root env | grep '^PATH' | cut -d= -f2)"
echo "$RPCV" | grep -q "::" && echo "root's path contains a empty directory
(::)"
echo "$RPCV" | grep -q ":$" && echo "root's path contains a trailing (:)"
for x in $(echo "$RPCV" | tr ":" " "); do
if [ -d "$x" ]; then
ls -ldH "$x" | awk '$9 == "." {print "PATH contains current working
directory (.)"}
$3 != "root" {print $9, "is not owned by root"}
substr($1,6,1) != "-" {print $9, "is group writable"}
substr($1,9,1) != "-" {print $9, "is world writable"}'
else
echo "$x is not a directory"
fi
done
750 or more restrictive
{
perm_mask='0027'
maxperm="$( printf '%o' $(( 0777 & ~$perm_mask)) )"
valid_shells="^($( sed -rn '/^\//{s,/,\\\\/,g;p}' /etc/shells | paste -s -
d '|' - ))$"
awk -v pat="$valid_shells" -F: '$(NF) ~ pat { print $1 " " $(NF-1) }'
/etc/passwd | (while read -r user home; do
mode=$( stat -L -c '%#a' "$home" )
if [ $(( $mode & $perm_mask )) -gt 0 ]; then
echo -e "- modifying User $user home directory: \"$home\"\n-
removing excessive permissions from current mode of \"$mode\""
chmod g-w,o-rwx "$home"
fi
done
)
}
world writable
{
perm_mask='0022'
valid_shells="^($( sed -rn '/^\//{s,/,\\\\/,g;p}' /etc/shells | paste -s -
d '|' - ))$"
awk -v pat="$valid_shells" -F: '$(NF) ~ pat { print $1 " " $(NF-1) }'
/etc/passwd | while read -r user home; do
find "$home" -type f -name '.*' | while read -r dfile; do
mode=$( stat -L -c '%#a' "$dfile" )
if [ $(( $mode & $perm_mask )) -gt 0 ]; then
echo -e "\n- Modifying User \"$user\" file: \"$dfile\"\n-
removing group and other write permissions"
chmod go-w "$dfile"
fi
done
done
}
{
output=""
perm_mask='0022'
maxperm="$( printf '%o' $(( 0777 & ~$perm_mask)) )"
valid_shells="^($( sed -rn '/^\//{s,/,\\\\/,g;p}' /etc/shells | paste -s -
d '|' - ))$"
awk -v pat="$valid_shells" -F: '$(NF) ~ pat { print $1 " " $(NF-1) }'
/etc/passwd | (while read -r user home; do
for dfile in $(find "$home" -type f -name '.*'); do
mode=$( stat -L -c '%#a' "$dfile" )
[ $(( $mode & $perm_mask )) -gt 0 ] && output="$output\n- User $user
file: \"$dfile\" is too permissive: \"$mode\" (should be: \"$maxperm\" or
more restrictive)"
done
done
if [ -n "$output" ]; then
echo -e "\n- Failed:$output"
else
echo -e "\n- Passed:\n- All user home dot files are mode: \"$maxperm\"
or more restrictive"
fi
)
}
Comments
Post a Comment