Friday, July 22, 2022

LINUX COMMANDS - III


DISPLAYING DATE IN VARIOUS FORMATS
date +%a,%_2d-%b-%4Y,%_H:%M%_P
Tue, 7-Dec-2021, 1:41-AM
date +%a,%_2d-%b-%Y,%_H:%M%_p 

date +%a," "%d" "%b" "%Y" - "%r
Wed, 19 Jan 2022 - 05:36:48 PM IST


COPY COMMANDS
cp -a //run/media/bhishma/WD-II/IP-1/. /mnt/data/win1/
cp -a -v //run/media/bhishma/WD-II/IP-2/. /mnt/data/win2/
cp -a -v //mnt/data/win1/. /run/media/bhishma/WD-II/IP-1/
/usr/bin/rsync -vuza /mnt/data/win1/. /run/media/bhishma/WD-II/IP-1/
/usr/bin/rsync -vuza /mnt/data/win2/. /run/media/bhishma/WD-II/IP-2/
/usr/bin/rsync -vuza /mnt/data/kdebkp/. /run/media/bhishma/kdebkp/

IPTABLE COMMANDS
iptables -p icmp -h ### IPTABLES COMMAND COMPLETE OPTIONS
systemctl enable iptables ### sets iptables to start on boot
systemctl disable iptables ### stops iptables from start on boot
systemctl start iptables.service
systemctl start ip6tables.service
systemctl stop iptables.service
systemctl --type=service
iptables --list-rules
ip6tables --list-rules
iptables -F ### delete all rules
iptables -X ### DELETE A USER DEFINED CHAIN
iptables -E LOGGING LOGS ### RENAME chain named LOGGING TO LOGS
iptables-save -f /etc/iptables/iptables.rules
iptables-save -f /etc/iptables/ip6tables.rules
journalctl -k | grep "IN=.*OUT=.*" ### LIST LOGS FOR IPTABLES

iptables -P INPUT ACCEPT
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -L -n -v --line-numbers ### List ruleset, numeric format, verbose, display rule line numbers
iptables -F ### delete all rules
iptables -D OUTPUT 2 ### delete input rule number 5
iptables -L INPUT -n --line-numbers
iptables -I INPUT 1 -s ipaddress -j DROP ### inserts new INPUT rule 5
iptables -A INPUT -j DROP ### DROP ALL INCOMING PACKETS
iptables -A OUTPUT -j DROP ### DROP ALL OUTGOING PACKETS

MOVE NON WORKING IPTABLES APP TO TEMP DIR &
COPY WORKING LEGACY APP TO DEFAULT FOLDER

sudo touch /run/xtables.lock
sudo chmod a+r /run/xtables.lock

#!/bin/bash
mv /usr/sbin/iptables /usr/sbin/iptables-broken
cp /usr/sbin/iptables-legacy /usr/sbin/iptables
mv /usr/sbin/iptables-restore /usr/sbin/iptables-restore-broken
mv /usr/sbin/ip6tables-restore /usr/sbin/ip6tables-restore-broken
mv /usr/sbin/iptables-save /usr/sbin/iptables-save-broken
mv /usr/sbin/ip6tables-save /usr/sbin/ip6tables-save-broken
cp /usr/sbin/iptables-legacy-restore /usr/sbin/iptables-restore
cp /usr/sbin/ip6tables-legacy-restore /usr/sbin/ip6tables-restore
cp /usr/sbin/iptables-legacy-save /usr/sbin/iptables-save
cp /usr/sbin/ip6tables-legacy-save /usr/sbin/ip6tables-save

IPTABLES RULE TO LOG BOTH INCOMING & OUTGOING PACKETS
iptables -N LOGS1
iptables -I INPUT 4 -j LOGS1
iptables -I OUTPUT 4 -j LOGS1
iptables -A LOGS1 -m limit --limit 2/min -j LOG --log-prefix "IPTbmv-Dropped1: " --log-level 4
iptables -A LOGS1 -j DROP

DROP OR ACCEPT TRAFFIC FROM MAC ADDRESS EXAMPLE
iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP
iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT ### ACCEPT TCP PORT 8080 FROM MAC source

NETWORK COMMANDS
ip address show
which tcpdump ### FIND IF TCPDUMP IS INSTALLED IN SYSTEM
pacman -S tcpdump ### INSTALL TCPDUMP
tcpdump -D ### PRINT LIST OF NETWORK INTERFACES THAT TCPDUMP CAN USE
ss -lntu ### LIST OPEN TCP & UDP NETWORK PORTS
ip neigh ### LIST NEIGHBOUR DEVICES AND ITS MAC ADDRESSES
pacman -S net-tools ### INSTALLS NETSTAT & OTHER COMMANDS
pacman -Sy dnsutils ### INSTALLS NSLOOKUP & DIG & OTHER COMMANDS
ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
ip -4 addr show dev wlp2s0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
ip -4 addr show | grep -v '127.0.0.1'
ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1'
ip addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1'
ip addr show | grep -oP 'inet \K[^/]+' | grep -v '127.0.0.1' ### BEST COMMAND SHOWS IP ONLY
ip route get 8.8.8.8 | grep -oP 'src \K[^ ]+'
ip route | grep -oP 'src \K[^ ]+'
ip route get 8.8.8.8 | grep -oP 'dev \K[^ ]+'
ip addr | grep "scope global" | sed 's:^[^0-9]*::' | sed 's:/.*$::'
ip addr | grep "scope global" | grep -oP 'inet \K[^/]+'
ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'
ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet )[^ /]+"
nmcli device show | awk '/4.A/ {print $2}' | grep -v '127.*' | cut -d / -f1

DISK | DIRECTORY | FILE COMMANDS
blkid ### lists UUID of all disk resources
ls -al /dev/disk/by-uuid/ ### lists UUID of all disk resources
find . -type f -name "*dillo*" ### FIND FILE WITH NAME dillo (START FROM \ DIRECTORY)
rm -rf folder-name ### deletes all subfolders & files recursively
find . -type f -name pycharm.svg -exec rm {} \; ### FIND & DELETE ALL FILES WITH NAME "pycharm.svg"
df -h
df -hT
fdisk -l
parted -l
findmnt ### POWERFUL TOOL TO FIND MOUNTED FILESYSTEMS.
chown bhishma:bhishma . ### CHANGE OWNERSHIP FROM ROOT TO BHISHMA FOR CURRENT DIRECTORY
chown owner_name file_name
chown -c master file1.txt ### CHANGES OWNER TO MASTER | -C: REPORTS AFTER OWNER CHANGE IS DONE.
chown :group1 file1.txt ### TO CHANGE OWNERSHIP OF A GROUP
chmod +rwx . ### CHANGE PERMISSIONS OF CURRENT DIRECTORY
chmod [class][operator][permission] file_name
chmod [ugoa][+or-][rwx] file_name
ls -al /dev/disk/by-uuid/ ### lists UUID of all disk resources
UUID=6cce8255-bf46-4b4a-a071-019472c7cc75 /mnt/data ext4 defaults 0 2 ### EDIT /etc/fstab FILE TO AUTO MOUNT DISK AT BOOT
sudo dd bs=4M if=/mnt/data/downloads/archbang-autumn-0412-x86_64.iso of=/dev/sdb conv=fdatasync status=progress ### CREATE USB BOOTABLE FROM ISO
dd bs=4M if=/mnt/data/downloads/iso/manjaro-xfce-21.1.6-minimal-211017-linux513.iso of=/dev/sdb conv=fdatasync status=progress

AUTO MOUNT A DATA DISK
blkid ### lists UUID of all disk resources
ls -al /dev/disk/by-uuid/ ### lists UUID of all disk resources
mkdir /mnt/data ### CREATE NEW MOUNT POINT FOLDER
groupadd grpdata ### CREATE NEW GROUP
usermod -aG grpdata kalki (KALKI IS NAME OF USER TO BE ADDED) ### ADD USER KALKI TO GROUP grpdata
chown -R :grpdata data ### CHANGE OWNERSHIP OF MOUNT POINT
vi /etc/fstab ### OPEN FSTAB CONFIG FILE
UUID=6cce8255-bf46-4b4a-a071-019472c7cc75 /mnt/data ext4 defaults 0 2 ### ADD LINE TO FSTAB FILE END
findmnt --verify ### TEST THE FSTAB BEFORE REBOOTING

PACMAN INSTALL/UNINSTALL COMMANDS
pacman -Syyu ### DOWNLOAD & INSTALL SYSTEM UPDATE FOR ARCH LINUX
pacman -S epiphany ### DOWNLOADS & INSTALLS OTTER BROWSER & DEPENDENT PACKAGES
pacman -Rns dillo ### UNINSTALL DILLO WEB BROWSER WITH INSTALLED PACKAGES

SYSTEM CONFIG COMMANDS
systemctl --type=service
systemctl --type=service --state=running
sudo -i
systemctl daemon-reload
lsblk -a ### LISTS ALL STORAGE DEVICES ON SYSTEM
lsusb ### LISTS ALL USB DEVICES
dmidecode -t bios ### LIST BIOS INFORMATION
pacman -Syu ### UPDATES ALL INSTALLED PACKAGES
pacman -S opera ### INSTALL OPERA BROWSER
dmidecode -t memory ### MEMORY HARDWARE INFORMATION
dmidecode -t memory | grep -i size ### MEMORY HARDWARE INFORMATION - SIZE
dd if=/dev/zero of=1G.test bs=1 count=0 seek=1G ### CREATE 1GB FILE FOR TESTING
rm ./path/to/the/file/file_1.txt ### DELETE A FILE
rm -d directory ### DELETE A DIRECTORY
ps aux | grep midori
ps aux | grep firefox
ps aux --sort -pcpu | grep firefox
ps aux --sort -pmem | head -n 16 ### DISPLAY TOP 16 MEMORY CONSUMING PROCESSES
ps aux --sort -pcpu | head -n 10 ### DISPLAY TOP 10 CPU CONSUMING PROCESSES
ps auxk -pcpu | head -n 10 ### DISPLAY TOP 10 CPU CONSUMING PROCESSES
ps -eo user,pid,%cpu,%mem,command --sort -pcpu | grep midori | head -20 ### SORTS OUTPUT DESCENDING
ps -eo user,pid,%cpu,%mem,command --sort=%mem ### SORTS OUTPUT ASCENDING
ps aux --sort -pcpu | grep webkitwebprocess | head -n 10
ps aux --sort -pcpu | grep webkit2gtk | head -n 10
kill [SIGNAL name/number] [PID/process name]
kill -9 3124
killall -9 firefox


BASH SCRIPTING COMMANDS
chmod u+x deploy.sh to make BASH script executable
echo -e "--------------CPU/Memory Usage----------------"
echo -e "Memory Usage:\t"`free | awk '/Mem/{printf("%.2f%"), $3/$2*100}'`
echo -e "Swap Usage:\t"`free | awk '/Swap/{printf("%.2f%"), $3/$2*100}'`
echo -e "CPU Usage:\t"`cat /proc/stat | awk '/cpu/{printf("%.2f%\n"), ($2+$4)*100/($2+$4+$5)}' | awk '{print $0}' | head -1`
echo ""

AWK SCRIPTING COMMANDS
awk -F':' '{printf "%s%s", $2, (/^Grade/)?"\n":"\t|"}' input.txt ### converts rows to columns
pacman -Qi | grep -E -w -i "name|description|licenses|depends|reason|date"
pacman -Qi | grep -E -w -i "name|description|URL|licenses|Depends|Required|Replaces|Reason" | awk '{ print $1, $2, $3, $4, $5, $6, $7,
$8 }' | awk -F':' '{printf "%-s %s", $2, (/^Install Reason/)?"\n":"\t|"}' | head -n 10
pacman -Qi | grep -E -w -i "name|description|URL|licenses" | awk '{ print $1, $2, $3, $4 }' | awk -F':' '{printf "%-s %s", $2, (/^Licenses/)?"\n":"\t|"}' | head -n 10

CRON JOBS IN LINUX
journalctl -xb -u cronie
systemctl list-timers --all

BASH SCRIPTING - VARIABLES IN LINUX
myname='Terry Clark'
echo $myname
unset myname
export myname=Terry ### CREATES GLOBAL VARIABLES AVAILABLE ACROSS SCRIPTS

TERMINAL CONSOLE KEYBOARD SHORTCUTS
Ctrl + A Go to the beginning of the line you are currently typing on
Ctrl + E Go to the end of the line you are currently typing on
Ctrl + L Clears the Screen, similar to the clear command
Ctrl + U Clears the line before the cursor position. If you are at the end of the line, clears the entire line.
Ctrl + H Same as backspace
Ctrl + R Lets you search through previously used commands
Ctrl + C Kill whatever you are running or start a new prompt
Ctrl + D Exit the current shell
Ctrl + Z Puts whatever you are running into a suspended background process. fg restores it.
Ctrl + W Delete the word before the cursor
Ctrl + K Clear the line after the cursor
Ctrl + T Swap the last two characters before the cursor
Esc + T Swap the last two words before the cursor
Alt + F Move cursor forward one word on the current line
Alt + B Move cursor backward one word on the current line
Tab Auto-complete files and folder names

MAC ADDRESS
wlp2s0 cc:b0:da:a7:39:2f LAPTOP WIFI
enp3s0 c8:5b:76:68:de:25 LAPTOP LAN
redmi 4a:0b:1d:eb:8f:74 REDMI PHONE


systemd is the newest Linux service manager(System V & Upstart are older ones)
mount command mounts a storage device or filesystem
/usr/local/SOFTNAME = software you compile from source (.tar.gz)
/usr/bin/ = Usually programs get installed to
/opt = can be used for trying software install which can be later removed

Windows Server Hardening

Windows Server Hardening Checklist

Sourced from : https://www.netwrix.com/windows_server_hardening_checklist.html

Deploying servers in their default state is the quickest way to get the job done. But the server will almost certainly be optimized for ease of use, often at the expense of cyber security.  By investing a little time in WindowsServer hardening — identifying and remediating security vulnerabilities that threat actors could exploit — you can dramatically reduce your risk of costly breaches and business disruptions from attacks, malware (including ransomware), and other cyber threats. 

This guide provides a comprehensive checklist of Windows Server hardening best practices for strengthening your security and compliance posture and protecting your vital systems and data. Your goal should be to establish security baselines tailored for your environment that reduce your attack surface and improve information security. You can get additional guidance from the Center for Internet Security (CIS) and the US Department of Defense Security Technical Implementation Guide (STIG).

Keep in mind that although server hardening is vital to cybersecurity, you also need to implement appropriate controls and processes, increase security awareness across the enterprise and follow other critical data security best practices.

Configuration Management 

Before diving into detailed secure configuration guidance, it’s worth reviewing some broader security best practices for developing, documenting and managing your configurations:

  • Maintain an inventory record for each server that clearly documents its baseline configuration and records every change to the server.
  • Review and minimize the applications installed on each server to reduce risk.
  • Thoroughly test and validate every proposed change to server hardware or software before making the change in the production environment.
  • Regularly perform a risk assessment. Use the results to update your risk management plan and maintain a prioritized list of all servers to ensure that security vulnerabilities are fixed in a timely manner.
  • Keep all servers at the same revision level to simplify configuration management.

Windows Server Preparation 

  • Protect new servers from potentially hostile network traffic until the operating system is fully hardened. Harden new servers in a network that is not open to the internet.
  • Set a strong BIOS/firmware password to prevent unauthorized changes to the server’s settings.
  • Disable automatic administrative logon to the recovery console.
  • Configure the device boot order to prevent unauthorized booting from alternate media.

Windows Server Installation 

  • Ensure that the system does not shut down during installation.
  • Create a system configuration based on the specific role that is needed. You can use the Security Configuration Wizard for this purpose.
  • When you install Windows Server, immediately update it with the latest patches using WSUS or SCCM. Security patches resolve known vulnerabilities that attackers could otherwise exploit to compromise a system.
  • Enable automatic notification of patch availability and make sure that all appropriate patches, hotfixes and service packs are reviewed, tested and applied in a timely manner.

User Account Security Hardening 

  • Disable and rename the guest account on each server.
  • Disable and rename the local Administrator account on any machine that is part of a domain where uniquely named domain admin accounts will be used.
  • Minimize access to privileged functions. Pay special attention to rights granted to built-in accounts and groups such as:
  • Local System (NT AUTHORITY\System)
  • Network Service (NT AUTHORITY\NetworkService)
  • Administrators group
  • Backup Operators group
  • Users group
  • Everyone group

For example, by default, the ‘Access this computer from the network’ right is granted to the Everyone group, essentially giving all users unrestricted remote access to shared folders.

  • Ensure that passwords of system and administrator accounts meet password best practices. In particular, verify that these privileged account passwords are not based on a dictionary word and are at least 15 characters long, with letters, numbers, special characters and invisible (CTRL ˆ ) characters interspersed throughout. Ensure that your strong password policy requires passwords to be changed every 90 days.
  • Configure account lockout Group Policy according to account lockout best practices.
  • Disallow users from creating and logging in with Microsoft accounts.
  • Do not allow “everyone” permissions to apply to anonymous users.
  • Disallow anonymous enumeration of SAM accounts and shares.
  • Disable anonymous SID/Name translation.
  • Promptly disable or delete unused user accounts

Network Security Configuration and Access Management 

  • Enable the Windows firewall and make sure the Firewall is enabled for each of the Domain, Private and Public firewall Profiles. Configure the default behaviour of the Firewall for each Profile to block inbound traffic by default.
  • Where inbound access is required to a server, restrict it to necessary protocols, ports and IP addresses.
  • Perform port blocking at the network setting level. Perform an analysis to determine which network ports need to be open and restrict access to all other ports.
  • Allow only Authenticated Users to access any computer from the network.
  • Do not grant any users the 'act as part of the operating system' right.
  • Deny guest accounts the ability to log on as a service, as a batch job, locally or via RDP.
  • If RDP is used, set the RDP connection encryption level to high.
  • Remove Enable LMhosts lookup.
  • Disable NetBIOS over TCP/IP.
  • Remove ncacn_ip_tcp.
  • Configure both the Microsoft Network Client and the Microsoft Network Server to always digitally sign communications.
  • Disable the sending of unencrypted passwords to third-party Server Message Block (SMB) servers.
  • Do not allow any shares to be accessed anonymously.
  • Set up the LAN Manager to refuse LM and NTLMv1 authentication.
  • Allow Local System to use computer identity for NTLMv2 authentication.
  • Disable Local System NULL session fallback.
  • Configure allowable encryption types for Kerberos authentication.
  • Do not store LAN Manager hash values.
  • Remove file and print sharing from network settings. File and print sharing could allow anyone to connect to a server and access critical data without requiring a user ID or password.

Registry Security Configuration 

Ensure that all administrators take the time to thoroughly understand how the registry functions and the purpose of each of its keys. Many of the vulnerabilities in the Windows operating system can be mitigated by changing the following keys: 

  • Protect the registry from anonymous access.
  • Disallow remote registry access if not required.
  • Set MaxCachedSockets (REG_DWORD) to 0.
  • Set SmbDeviceEnabled (REG_DWORD) to 0.
  • Set AutoShareServer to 0.
  • Set AutoShareWks to 0.
  • Delete all values in the NullSessionPipes key.
  • Delete all values in the NullSessionShares key.

General Security Settings

  • Disable any unneeded services included in the default installation to reduce the server’s vulnerability. See the Netwrix Hardened Services guide for specific guidance.
  • Remove unnecessary Windows Server roles and features.
  • Enable the built-in Encrypting File System (EFS) with NTFS or BitLocker.
  • If the server has significant random access memory (RAM), disable the Windows swapfile. This will improve performance and make the machine more secure because no sensitive data can be written to the hard drive.
  • Do not use AUTORUN. Otherwise, untrusted code can be run without the direct knowledge of the user; for example, attackers might put a CD into the machine and cause their own script to run.
  • Display a legal notice like the following before the user logs in: “Unauthorized use of this computer and networking resources is prohibited…”
  • Require Ctrl+Alt+Del for interactive logins,  and configure an inactivity limit to terminate idle interactive sessions.
  • Ensure all volumes are using the NTFS file system.
  • Configure Local file and folder permissions. By default, Windows does not apply specific restrictions on any local files or folders; the Everyone group is given full permissions to most of the machine. Remove this group and instead grant access to files and folders using role-based groups based on the least-privilege principle. Every attempt should be made to remove Guest, Everyone and ANONYMOUS LOGON from user rights.
  • Set the system date/time and configure it to synchronize against domain time servers.
  • Configure a timeout that locks the console's screen automatically if it is left unattended.

Audit Policy and Advanced Audit Policy Configuration

  • Create an audit policy according to audit policy best practices  to define which events are written to the security logs to gain visibility into critical activity.
  • Configure the event log retention method to overwrite as needed and make sure up to 4GB of storage is reserved.
  • Configure security log shipping to your security information and event management (SIEM) tool, if you have one, to improve threat detection and response.

Brief Guide to Additional Hardening 

The settings below can be defined locally using the Windows Local Security Policy editor or the Local Group Policy editor. Alternatively, in a domain environment, use the Active Directory GPO (Group Policy Object) Management features on your domain controller to create centralized configuration policies to deploy to all member computers.

  • Rigorously enforce the least privilege principle to limit user rights. The User Rights Assignment settings control the permissions and access to privileged functions on a per user and per group basis. Windows has a number of built in user accounts and groups, otherwise known as Special Identities, with relevant privileges aligned to them; they include:
  • Local System, or NT AUTHORITY\System
  • Network Service, or NT AUTHORITY\NetworkService,
  • Administrators
  • Backup Operators
  • Users
  • Everyone

It is vital to minimize the assignment of built-in groups and accounts to these user rights. For example, the ‘Access this computer from the network’ setting is set by default to ‘Administrators, Backup Operators, Everyone, Users’ on Windows 10 — essentially granting unrestricted remote access to shared folders for all users. To reduce this security risk, the recommended setting is to restrict these rights to just the Administrators and Remote Desktop User groups to improve access control.

  • Install and enable anti-virus software. Configure it to scan all downloads and attachments and to provide real-time protection. Set to update daily.
  • Install and enable anti-spyware software. Configure it to update daily.
  • Install and enable data loss prevention (DLP) software.
  • Promptly review, test and install recommended updates and patches for all operating system and applications to promptly patch vulnerabilities and improve application security.
  • Follow  security best practices, as well as database hardening and application hardening guidance, for all your systems.

How Netwrix Can Help

Netwrix Change Tracker simplifies Windows Server hardening and configuration management. It uses system and file integrity monitoring technology to analyze configuration settings and pinpoint vulnerabilities and errors, and provides detailed guidance for establishing a hardened baseline configuration. Then it help you maintain those secure configurations by monitoring and alerting on suspicious changes to:

  • Filesystem
  • Registry
  • Windows Security and Audit policy
  • Installed software
  • Local user groups and accounts
  • Open network ports
  • Service states and running processes

Any drift from the hardened configuration can be corrected immediately, while any unexpected change can be promptly investigated to prevent security breaches and downtime. Integration with your overall security system can be provided, either as a component of a 3rd party managed security service or for an in-house approach.

Linux Server Hardening and Security Best Practices

 

Linux Server Hardening and Security Best Practices

Sourced from: https://www.netwrix.com/linux_hardening_security_best_practices.html

Introduction

Implementing secure configurations across your computing environment, including your Unix and Linux systems, is a key security best practice because it reduces your attack surface area and limits the damage that cyberattacks can do. Indeed, system hardening is a core control in many compliance directives.

This guide explains how what configuration hardening is and how to establish hardened build standards for your Linux and Unix systems. 

The Basics of System Hardening

The most secure Linux server or other computer is the one that is powered off and disconnected from the network. But if we want to actually use the machine to provide IT services, we need to maximize its security defenses when it is booted up and attached to the network or even the internet. 

This is where hardening comes into play.  Hardening a system means optimizing its configuration for secure operations and data protection. The range of exploitable vulnerabilities is vast, so there are three main rules to follow:

  • Remove functionality that isn’t needed for the role of the computer. For example, operating systems and other applications are typically delivered in a “quick start” state, helpfully pre-loaded with utilities and features that users might want. However, the more functions that are provided, the greater the attack surface presented by the host. Therefore, be sure to disable functions you don’t need and avoid adding unnecessary functions wherever possible.
  • Patch and update promptly. Flaws in software design create vulnerabilities that attackers can exploit. Software vendors provide patches or updated versions of the software to remediate these issues, so make sure all software, including operating systems, is fully updated at all times.
  • Maintain secure configuration settings. It’s crucial that secure settings be enabled and maintained.

Linux System Hardening

Unsurprisingly, Linux security hardening is a specialized procedure in its own right, given the wide-range of subtly different Linux distributions. While there is no shortage of guides, checklists and tips for best practices in Linux server hardening — including the Center for Internet Security (CIS) benchmarks and the DISA STIGs — this guide will provide the key config options to adopt. 

Important: Make sure you back up your systems before applying hardened settings and test after a restart. It’s easy to get locked out!

Remove Unneeded Functionality 

Start by stripping out any features, utilities and services that are not required for running the server. Uninstall unnecessary software and disable system services that are not needed. Since the hardware in your infrastructure also presents exploitable vulnerabilities, make sure any accessible interfaces, such as USB ports, are disabled or even physically removed from the machine.

The workflow here is to log in and get a report of installed packages and services, and review it to identify any that can be removed or disabled. For the essential items that remain, check for available patches to remediate known vulnerabilities against exploits.

How to List Software on Linux/Unix Systems

SystemCommands to Use
Linux (e.g., RedHat or CentOS)rpm -qa --qf '%{NAME} %{VERSION} %{VENDOR}\n'
Debian Linux (e.g., Ubuntu)dpkg -l
Fedora Linux

To list software from a terminal or putty session: 

service --status-all 

chkconfig --list 

systemctl -a

 

To stop a service: 

Service <Service-Name> stop

Chkconfig <Service-Name>

Systemctl stop <Service-Name>

 

To disable a service:

Systemctl disable <Service-Name>

Chkconfig <Service-Name> off

 

Also inspect the /etc/init.d/ path for any service control scripts and run ls /etc/init.d/ to expose all startup scripts; then rename or remove any that are to be disabled.

 

Minimize Open Ports and Other Network Vulnerabilities

Network-based attacks are among the most common threats. To reduce your risk, identify open network-accessible ports and remove any corresponding processes that are not needed. To list open ports on Linux, use the following command: 

ss -tulpn | egrep “LISTEN” | awk ‘{print “IP-Port “ $4 “ PID/Name “ $7}’

In addition:

  • Ensure that the TCP Wrappers service is active.
  • Define both an etc/hosts.allow whitelist and an etc/hosts.deny blacklist.
  • Use the iptables or Firewalld services with a Deny All policy for both IP V4 and V6 traffic, even if you are using on-network third-party WAFs and firewall protection.
  • Block ICMP traffic to thwart ping scans used by hacker tools for device discovery.

Review User Accounts and Authentication

Review local user accounts and remove any that are not needed. For local user accounts that remain, a strong password policy should be configured that covers password complexity, length, expiration, re-use and change frequency. Also be sure to use strong hashing algorithms for stored passwords.

User accounts and authentication should be governed using a centralized control system such as Active Directory or, even better, a modern privileged access management (PAM) solution that allows a Zero Standing Privilege strategy, which negates many of the problems with traditional user accounts and permanently assigned privilege. Of course, never use root and always make sure that sudo elevation is used only on an as-needed basis.

How to Configure a Password Policy for Local Accounts 

Locate and edit the following configuration file: /etc/security/pwquality.conf

To enforce a 14-character password: 

minlen = 14

To enforce complexity for all passwords: 

minclass = 4 

OR 

dcredit = -1 

ucredit = -1 

ocredit = -1 

lcredit = -1

To enforce a strong password lockout policy:

Update the /etc/pam.d/system-auth and /etc/pam.d/password-auth files to set the following options: 

auth required pam_faillock.so preauth silent deny=5 unlock_time=900

auth required pam_faillock.so authfail deny=5 unlock_time=900

 

To enforce a password history policy of 5 or more passwords:

Add the remember=5 option to the pam_pwhistory.so and pam_unix.so lines in /etc/pam.d/password-auth:

password requisite pam_pwhistory.so try_first_pass local_users_only enforce-for-root retry=3 remember=5 

password sufficient pam_unix.so sha512 shadow try_first_pass use_authtok remember=5

 

To enforce strong password hashing:

Update the /etc/pam.d/system-auth and /etc/pam.d/password-auth files as follows:

/etc/pam.d/password-auth:

password sufficient pam_unix.so sha512 shadow try_first_pass use_authtok

/etc/pam.d/system-auth:

password sufficient pam_unix.so sha512 shadow try_first_pass use_authtok remember=5

Review Service Accounts

System and service accounts should be reviewed and any that are no longer required should be removed.

Service accounts are “hardened” in that they only support the operation of a locally run process and do not provide a user shell, so these accounts cannot ever be used to access the server by a user logon. However, a core hardening mantra is to minimize functionality, so unused service accounts should still be removed.

SSH Hardening for Linux and Unix

As the primary route for remotely administering your Linux systems, SSH requires particular attention. There are a number of default settings in the /etc/ssh/sshd_config file that need to be enabled in order to harden the SSH server operation. 

SSH is used for all Linux and Unix access, so the following guidelines apply for Unix hardening, too.

Enable v2 of the SSH protocol

For example, the default configuration enables the outdated and less secure version 1 of the SSH protocol. CIS hardening guidance recommends enabling version 2 to enhance security. To do so, simply uncomment the Protocol 2 setting in the configuration file (/etc/ssh/sshd_config) by removing the #, as follows:

Default entry in /etc/ssh/sshd_config:

# The default requires explicit activation of protocol 1

# Protocol 2

A more secure configuration:

# The default requires explicit activation of protocol 1

Protocol 2

Additional hardening

In addition, apply the following recommended CIS hardened settings to the config file: 

LogLevel INFO

IgnoreRhosts yes

PermitEmptyPasswords no

LoginGraceTime 60

PermitRootLogin no

MaxAuthTries 4

HostbasedAuthentication no

X11Forwarding no…

PermitUserEnvironment no

ClientAliveInterval 300

ClientAliveCountMax 0

Banner /etc/issue.net

 …

AllowUsers <Specify user names, separated by spaces, e.g. user1 user2>

Additional Notes:

/etc/issue.net will need to be created/edited to include an appropriate Banner, e.g.

Warning! Unauthorized access to this system is forbidden and will be prosecuted by law. By accessing this system, you agree that your actions may be monitored if unauthorized usage is suspected.

Together with AllowUsers, AllowGroups is also supported as a config switch/keyword.

 

Apache Web Server Hardening

Linux is the platform of choice for hosting internet-based web applications, and Apache Tomcat and Apache HTTP Server (often referred to as Apache HTTPD) are two of the most popular options for delivering web content. 

The approach to Apache configuration hardening is the same: minimize functionality and implement secure configuration settings where available.

Verify that only essential Apache modules are enabled:

httpd -M 

For example, mod_dav and  mod_dav_fs should always be disabled, while the  log_config module should always be loaded and enabled.

Confirm the package.access definition only includes the following allowed packages:

package.access = sun.,org.apache.catalina.,org.apache.coyote.,

org.apache.tomcat.,org.apache.jasper.

Configure the server.xml file:

The server.xml file on the CATALINA_HOME/conf path is the core configuration store for the web server. The recommended settings to include in server.xml are as follows:

  • Disable the shutdown port:

<Server port="-1" shutdown="SHUTDOWN">

  • Remove unused connectors, including the default HTTPConnector and the AJPConnector. To remove the HTTPConnector, delete or comment out this tag:

<Connector className="org.apache.catalina.connector.http.HttpConnector"

...

connectionTimeout="60000"/>

Remove the default presence-advertising settings:

For Tomcat:

Set the xpoweredBy attributes to false:

xpoweredBy="false" />

For HTTP Server:

  • Remove the default index.html and comment out the below from the /etc/httpd/conf.d/welcome.conf using a # or ## for each line:

##<LocationMatch "^/+$">

## Options -Indexes

## ErrorDocument 403 /error/noindex.html

##</LocationMatch>

  • Comment out the Server-Status section:

##<Location /server-status>

## SetHandler server-status

## Order deny,allow

## Deny from all

## Allow from .example.com

##</Location>

  • Comment out the server-info section:

##<Location /server-info>

## SetHandler server-info

## Order deny,allow

## Deny from all

## Allow from .example.com

##</Location>

Disable diagnostic trace facilities: 

Set the allowTrace attribute for each Connector to false

Disable auto deployment of applications, and disable deployment on startup:

autoDeploy="false"

deployOnStartup="false"

Additional hardening:

  • Ensure that file and folder permissions are restrictive and that Apache services run using non-shell service accounts (i.e., accounts that cannot be used to log on to the system). Disable Directory Listing and browsing.

$CATALINA_HOME

$CATALINA_BASE

Kernel Hardening for Linux

SELinux modifies the Linux kernel to enforce mandatory access controls, restricting how Linux processes can access files and programs. This additional layer of restriction provides a fundamental protection mechanism against root kit malware. AppArmor provides an equivalent level of MAC for Debian distributions. 

SELinux Settings

Install SELinux on CentOS/RHEL:

dnf install libselinux

Enable SELinux:

By default, SELinux will be disabled. To enable SELinux at boot, edit/etc/default/grub and remove these default settings: 

selinux=0

enforcing=0

Set SELinux config to enforcing

Edit the /etc/selinux/config file to include the following:

SELINUX=enforcing

SELINUXTYPE=default

Check that all services are being run with a security context controlled by SELinux:

The following command will list any services being launched from the init process, which may require a non-default security context assigned to them: 

ps -eZ | egrep "initrc" | egrep -vw "tr|ps|egrep|bash|awk" | tr ':' ' ' | awk '{ print $NF }'

Restart the computer to make sure all settings have been loaded.

AppArmor Settings

Install AppArmor on Ubuntu/Debian:

apt-get install apparmor apparmor-profiles apparmor-utils

Enable AppArmor at boot: 

Edit /etc/default/grub and add the following settings: 

GRUB_CMDLINE_LINUX="apparmor=1 security=apparmor"

Ensure all AppArmor profiles are in enforce mode: 

aa-enforce /etc/apparmor.d/*

Embedded Linux Hardening

Embedded Linux provides a stripped-down operating system for embedded devices or embedded systems, such as smart phones, smart TVs, set-top boxes and broadband internet routers.

A simplified operating system with a reduced footprint is attractive when the full range of function usually provided by server-grade Linux devices is not required and hardware resources such as storage, memory and CPU have been minimized to save manufacturing costs. For example, the open-source Android platform developed by Google is optimized for smart phones and TVs, and the OpenWrt router firmware is used for a wide range of broadband routers.

The functionality included in the operating system varies widely depending upon the intended application. For example, Android includes screen lock, face recognition, PIN entry support and location services; these are not needed in operating systems for home routers, but VPN, guest Wi-Fi and bandwidth throttling features are included. As a result, hardening guidance is specifically linked to the particular device and platform in use.

Android Hardening Highlights

Ensure device firmware is up to date:

Go to Settings | System | System Updates; select Check for Update and install any updates that are available.

Install Google Play and security updates:

Go to Settings | Security:

  • Select Google Security Check-Up and apply any updates available.
  • Select Google Play system update and apply any updates  available.

Enable general device security: 

  1. Go to Settings | Security | Device Security and do the following:
  • Set ‘Screen Lock’ to ‘Enabled’.
  • Set ‘Pattern Visible’ to ‘Disabled’.
  • Set ‘Automatically Lock’ to ‘Immediately’.
  • Set ‘Power Button Instantly Locks’ to ‘On’.
  • Set Device Admin Apps ‘Find My Device’ to ‘Enabled’.
  • Set ‘Allow remote lock and erase’ to ‘Enabled’.

2. Go to Settings | System | Advanced and do the following:

  • Set ‘Developer Options’ to ‘Off’.

3. Go to Settings | Apps & Notifications | Advanced | Special App Access and do the following:

  • Set ‘Install Unknown Apps’ to ‘Not Allowed’.

4. Launch Play Store | Menu and do the following:

  • Select ‘My Apps & Games’ and click ‘Update All’.

OpenWrt Hardening Highlights

  • Change the admin password from the default.
  • Ensure the firmware is always updated to the latest version.

Kali Linux Hardening

Kali Linux has been optimized to be the pen testers’ platform of choice, so it has a wide range of security auditing and pen testing utilities. 

Since Kali Linux is a Debian-based Linux distribution, you can use the Linux hardening tips above to address the security weaknesses in Kali Linux systems.

Linux Mint Security Hardening

Similarly for Linux Mint, as an Ubuntu-derived Desktop Linux platform, the same hardening procedures used for Debian-Linux should be adopted. Work through the earlier Linux Hardening Checklist steps and apply these to your Linux Mint systems.

Hardening Arch Linux

As an independent Linux distribution not directly derived from Debian or Fedora, Arch Linux is an individual case when it comes to hardening measures, although the concepts of how and what to harden are similar. Arch code is intentionally built as a streamlined ‘no filler’ Linux distribution and as such will require less hardening work when it comes to removing/disabling unnecessary services 

Final Word

Even a hardened system can still be compromised, especially by the following: 

  • Zero-day threats — exploits we had no knowledge of and therefore did not protect against
  • Ransomware and other malware
  • Insider threats, including both hackers using hijacked credentials and users abusing their access

Therefore, in addition to hardening your systems, you need additional defenses. In particular, it’s vital to monitor system and file integrity. Any unexpected change could lead to a breach or other security incident. Netwrix Change Tracker provides real-time alerts on all unplanned changes, and it supports all Linux and Unix platforms. 

 

void auto config

.backups/ .bh .p/ .pcbankdetail/ .profig.os .tmpb/ Alarms/ Android/ DCIM/.thumbnails/ DCIM/100ANDRO/ DemoContent.txt Notifications/ Podcasts...

/* BMV WEB CSS STYLE ENDS */