Web server securing guide

1   OS Hardening

1.1          Kernel hardening

Update kernel parameter on /etc/sysctl.conf

# Turn on exec shield

kernel.exec-shield=1

kernel.randomize_va_space=1

# Enable IP spoofing protection

net.ipv4.conf.all.rp_filter=1

# Disable IP source routing

net.ipv4.conf.all.accept_source_route=0

# Ignoring broadcasts request

net.ipv4.icmp_echo_ignore_broadcasts=1

net.ipv4.icmp_ignore_bogus_error_messages=1

# Make sure spoofed packets get logged

net.ipv4.conf.all.log_martians = 1

1.2          Banner

This line should be present Banner /etc/issue.net In above file below entries should be present.

/etc/issue.net

WARNING!!

This system is the property of the ITQuery Solutions Ltd. and should be accessed only by authorized users. Unauthorized use of this system is strictly prohibited and will be subject to disciplinary action and prosecution. Systems and Technology Department may monitor any activity or communication on this system and retrieve any information stored within the system.

1.3          Password Policy

/etc/login.defs

Below 4 Values should be present.

PASS_MAX_DAYS   30

(Maximum number of days a password may be used. If the          password is older than this, a password change will be forced.)

PASS_MIN_DAYS   0                 

(Minimum number of days allowed between password changes. Any password changes attempted sooner than this will be rejected)

PASS_MIN_LEN    8                    

(Minimum Password Length)

PASS_WARN_AGE   15   

(Number of days warning given before a password expires. A zero means warning is given only upon the day of expiration, a negative value means no warning is given. If not specified, no warning will be provided.)

1.4          Disable     rsh service status

/etc/xinetd.d/rsh

Disable = yes

Check for # chkconfig --list rsh

rsh             off

1.5          Telnet service status

/etc/xinetd.d/telnet

disable= yes

Check for # chkconfig --list telnet

telnet=off

1.6          Disable CTRL+ALT+DEL

cat /etc/inittab |grep ctrl

#ca::ctrlaltdel:/sbin/shutdown -t3 -r now

Comment out above line in inittab to disable ctrl+alt+del key sequence which can reboot the system

1.7          iptables Rules

The following example will drop incoming connections which make more than 5 connection attempts upon port 22 within 60 seconds:

#!/bin/bash

inet_if=eth1

ssh_port=22

$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --set

$IPT -I INPUT -p tcp --dport ${ssh_port} -i ${inet_if} -m state --state NEW -m recent  --update --seconds 60 --hitcount 5 -j DROP

 

Call above script from your iptables scripts. Another config option:

 


$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT

$IPT -A INPUT  -i ${inet_if} -p tcp --dport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT

$IPT -A OUTPUT -o ${inet_if} -p tcp --sport ${ssh_port} -m state --state ESTABLISHED -j ACCEPT

# Another one line example


$IPT -A INPUT -i ${inet_if} -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 22 -m limit --limit 5/minute --limit-burst 5-j ACCEPT

1.8   Thwart SSH Crackers (Brute Force Attack)

Download and install “DenyHosts” from http://denyhosts.sourceforge.net

DenyHosts is a Python based security tool for SSH servers.

It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.

 

1.9   Audit

Install audit package if not present and enable in init


$chkconfig auditd on

1.9.1   Set a watch on a file for auditing

$ auditctl -w /etc/passwd -p war -k password-file

$ auditctl -w /etc/shadow -k shadow-file -p rwxa

$ auditctl -a exit,never -S mount

$ auditctl -a entry,always -S all -F pid=1005

1.9.2   Enabled audit rules

vi /etc/audit/audit.rules

Add below lines, more can also be customized as per requirement

-a exit,always -F path=/bin/rm -k rmcommand

-a exit,always -F path=/bin/mv -k mvcommand

-a exit,always -F path=/bin/kill -k killcommand

-a exit,always -F path=/usr/bin/passwd -k passwdcommand

-a exit,always -F path=/bin/chown -k chowncommand

-a exit,always -F path=/bin/chmod -k chmodcommand

-a exit,always -F path=/bin/vi -k vicommand

-a exit,always -F path=/usr/bin/vim -k vimcommand

-a exit,always -F path=/usr/bin/crontab -k crontabcommand

 

vi  /etc/audit/auditd.conf

num_logs = 8

max_log_file = 50

# service auditd restart

 

1.10      PAM

vi /etc/pam.d/system-auth

Enter this entry in password section:

 

auth        required      pam_env.so

auth        required      pam_tally2.so deny=5 onerr=fail unlock_time=1800

auth        sufficient    pam_unix.so nullok try_first_pass

 

 

password    requisite     pam_cracklib.so retry=5 minlen=8 lcredit=1 ucredit=1 dcredit=1 ocredit=1 difok=3

password    sufficient     pam_unix.so nullok use_authtok md5 shadow remember=5

 

vi /etc/ssh/sshd_config

 

 

# Change to no to disable s/key passwords

ChallengeResponseAuthentication yes

ChallengeResponseAuthentication no

 

 

1.11   Below Services should be disabled on newly installed server.


bluetooth
cups
avahi-daemon
hplip
hidd
ip6tables
iptables
isdn
mcstrans
pcscd
tog-pegasus

 

1.12   Other system wide sanity check

1.12.1Check Current Status of Startup Services

chkconfig –list | grep ‘3:on’

 

1.12.2Remove not required packages from system

yum erase inetd xinetd ypserv tftp-server telnet-server rsh-serve

1.12.3Enable SELinux

/etc/sysconfig/selinux

SELINUX= enforcing

1.12.4Check system wide guest rwx

systemwide directory having write rwx access for guest/other user

find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print

 

1.12.5 Non existing owner file check

find / -xdev \( -nouser -o -nogroup \) -print

 

1.12.6Write Protect Apache, PHP, and, MySQL Configuration Files

chattr +i /etc/php.ini

chattr +i /etc/php.d/*

chattr +i /etc/my.ini

chattr +i /etc/httpd/conf/httpd.conf

chattr +i /etc/

2      VSFTP configuration

 

/etc/vsftpd/vsftpd.conf

# You may fully customize the login banner string:

ftpd_banner=Welcome to ITQueryt Solutions’s FTP Server.

pam_service_name=vsftpd

userlist_enable=YES

tcp_wrappers=YES

use_localtime=YES

pasv_enable=YES

anonymous_enable=NO

chmod_enable = NO

chroot_list_enable = NO

guest_enable= NO

 

 

/etc/vsftpd/user_list

# vsftpd userlist

# If userlist_deny=NO, only allow users in this file

# If userlist_deny=YES (default), never allow users in this file, and

# do not even prompt for a password.

# Note that the default vsftpd pam config also checks /etc/vsftpd/ftpusers

# for users that are denied.

root

bin

daemon

adm

lp

sync

shutdown

halt

mail

news

uucp

operator

games

nobody

 

cat /etc/vsftpd/ftpusers

# Users that are not allowed to login via ftp

root

bin

daemon

adm

lp

sync

shutdown

halt

mail

news

uucp

operator

games

nobody

 

 

 

 

3      SSH Hardening

3.1 Secure OpenSSH Server (/etc/ssh/sshd_config)

No Remote root Login

Allow Users xyz abc etc

Configure Idle Log out Timeout Interval

Disable .rhosts Files

Disable Empty Passwords

ClientAliveInterval 300

ClientAliveCountMax 0

PermitRootLogin no

IgnoreRhosts yes

PermitEmptyPasswords no

 

3.2 Use TCP Wrappers to enable ssh login from given ip address only (/etc/hosts.allow)

sshd : 192.xx.xx.xx 172.xx.xx.xx etc..

(/etc/hosts.deny)

sshd: ALL

 

3.3  Hide openssh version

#  Turn on privilege separation

UsePrivilegeSeparation yes

# Prevent the use of insecure home directory and key file permissions

StrictModes yes

# Turn on reverse name checking

VerifyReverseMapping yes

# Do you need port forwarding?

AllowTcpForwarding no

X11Forwarding no

#  Specifies whether password authentication is allowed.  The default is yes.

#  Use this only when you have key base authentication

PasswordAuthentication no 

 

 

 

 

4      Send mail Hardening

4.1          Configure Mail Submission

Edit /etc/sysconfig/sendmail modify the line:

DAEMON=no

machine should forward it’s all outgoing mail.

# Edit /etc/mail/submit.cf

D{MTAHost}mail.itquery.com

 

4.2          Mail server masquerading

Sendmail config file /etc/mail/sendmail.mc:

Append/add/modify the lines as follows:

 

MASQUERADE_AS(itquery.com)dnl

FEATURE(masquerade_envelope)dnl

FEATURE(masquerade_entire_domain)dnl

MASQUERADE_DOMAIN(itquery.com)dnl

 

Update and restart sendmail server:

$ m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf

$ /etc/init.d/sendmail restart

 

5      Apache Hardening

Create separate partitions for Apache and FTP server roots (/opt/www/).

Edit /etc/fstab file and make sure you add the following configuration options:

noexec - Do not set execution of any binaries on this partition (prevents execution of binaries but allows scripts).

nodev - Do not allow character or special devices on this partition (prevents use of device files such as zero, sda etc).

nosuid - Do not set SUID/SGID access on this partition (prevent the setuid bit).

Sample /etc/fstab entry to to limit user access on /dev/sda5 (ftp server root directory):

5.1   Suggestion for apache installations –

It is highly recommended to have web server (apache) installation to have a separate instance in DMZ environment, application and database should reside on separate instance behind the DMZ server.

5.2   Suggestive apache configuration

Directive and configuration setting

Description

ServerSignature Off

Prevents server from giving version info on error pages.

ServerTokens Prod

Prevents server from giving version info in HTTP headers

User apache

Ensure that the child processes run as unprivileged user

Group apache

Ensure that the child processes run as unprivileged group

ErrorDocument 404 errors/404.html
ErrorDocument 500 errors/500.html
etc…

To further obfuscate the web server and version, this will redirect to a page that you should create, rather than using the default Apache pages.

ServerAdmin webmaster@itquery.com

Use a mail alias – never use a person’s email address here.

UserDir disabled root

Remove the UserDir line, since we disabled this module.  If you do enable user directories, you’ll need this line to protect root’s files.


 

 

<Directory />
Order Deny, Allow
Deny from all
</Directory>

Deny access to the root file system.

<Directory /opt/www ">
<LimitExcept GET POST>
Deny from all</LimitExcept>

Options -FollowSymLinks -Includes -Indexes  -MultiViews  AllowOverride None

Order allow,deny
Allow from all
</Directory>

LimitExcept prevents TRACE from allowing attackers to find a path through cache or proxy servers.

The “-“ before any directive disables that option.

FollowSymLinks allows a user to navigate outside the doc tree, and Indexes will reveal the contents of any directory in your doc tree.

Includes allows .shtml pages, which use server-side includes (potentially allowing access to the host).  If you really need SSI, use IncludesNoExec instead.

AllowOverride None will prevent developers from overriding these specifications in other parts of the doc tree.

AddIcon
IndexOptions
AddDescription
ReadmeName
HeaderName
IndexIgnore

Remove all references to these directives, since we disabled the fancy indexing module.

Alias /manual

Don’t provide any accessible references to the Apache manual, it gives attackers too much info about your server. (remove)

 

 

 

5.3   Apache module “mod_security“

 

ModSecurity™is an open source, free web application firewall (WAF) Apache module. With over 70% of all attacks now carried out over the web application level, organizations need all the help they can get in making their systems secure. WAFs are deployed to establish an external security layer that increases security, detects and prevents attacks before they reach web applications. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.

It is recommended to Install and configure mod_secutiry a plugin for apache’ httpd server to secure and filter the request received and served.

This can be downloaded from http://www.modsecurity.org/

6      PHP Hardening

 

PHP perform better with a reduced modules and security, hence would recommend to remove these item –

SQLITE -

mv /etc/php.d/sqlite3.ini /etc/php.d/sqlite3.disable

Modify/update php configuration with suggested parameter -

/etc/php.ini

file_uploads=On

# user can only upload upto 1MB via php

upload_max_filesize=1M

allow_url_include=Off

open_basedir="/opt/www"

disable_functions =exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

Update modify security configuration -

/etc/php.d/security.ini

expose_php=Off

log_errors=On

error_log=/var/log/httpd/php_scripts_error.log

This entry was posted in Apache, Shell script, Unix/Linux. Bookmark the permalink.

Leave a Reply