October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

DB2 Database

Starting the DB2 control center on Linux

This procedure describes how to start the DB2® control center on Linux®.

To start the DB2 control center, perform the following steps:
  1. Login as root.
  2. At the command line, run the following command: xhost +localhost.
  3. Run the following command su – ctginst1.
  4. Run the following command db2cc.

Keeping multiple web servers in sync with rsync

People looking to create a load balanced web server solution often ask, how can they keep their web servers in sync with each other? There are many ways to go about this: NFS, lsync, rsync, etc. This guide will discuss a technique using rsync that runs from a cron job every 10 minutes.

There will be two different options presented, pulling the updates from the master web server, and pushing the updates from the master web server down to the slave web servers.

Our example will consist of the following servers:

web01.example.com (192.168.1.1) # Master Web Server
web02.example.com (192.168.1.2) # Slave Web Server
web03.example.com (192.168.1.3) # Slave Web Server

Our master web server is going to the single point of truth for the web content of our domain. Therefore, the web developers will only be modifying content from the master web server, and will let rsync handle keeping all the slave nodes in sync with each other.

There are a few prerequisites that must be in place:
1. Confirm that rsync is installed.
2. If pulling updates from the master web server, all slave servers must be able to SSH to the master server using a SSH key with no pass phrase.
3. If pushing updates from the master down to the slave servers, the master server must be able to SSH to the slave web servers using a SSH key with no passphrase.

To be proactive about monitoring the status of the rsync job, both scripts posted below allow you to perform a http content check against a status file to see if the string “SUCCESS” exists. If something other then SUCCESS is found, that means that the rsync script may have failed and should be investigated. An example of this URL to monitor would be is: 192.168.1.1/datasync.status

Please note that the assumption is being made that your web server will serve files that are placed in /var/www/html/. If not, please update the $status variable accordingly.

Using rsync to pull changes from the master web server:

This is especially useful if you are in a cloud environment and scale your environment by snapshotting an existing slave web server to provision a new one. When the new slave web server comes online, and assuming it already has the SSH key in place, it will automatically grab the latest content from the master server with no interaction needed by yourself except to test, then enable in your load balancer.

The disadvantage with using the pull method for your rsync updates comes into play when you have multiple slave web servers all running the rsync job at the same time. This can put a strain on the master web servers CPU, which can cause performance degradation. However if you have under 10 servers, or if your site does not have a lot of content, then the pull method should work fine.

Below will show the procedure for setting this up:

1. Create SSH keys on each slave web server:
ssh-keygen -t dsa

2. Now copy the public key generated on the slave web server (/root/.ssh/id_dsa.pub) and append it to the master web servers, /root/.ssh/authorized_keys2 file.

3. Test ssh’ing in as root from the slave web server to the master web server
# On web02
ssh root@192.168.1.1

4. Assuming you were able to log in to the master web server cleanly, then its time to create the rsync script on each slave web server. Please note that I am assuming your sites documentroot’s are stored in /var/www/vhosts. If not, please change the script accordingly and test!

mkdir -p /opt/scripts/
vi /opt/scripts/pull-datasync.sh

#!/bin/bash
# pull-datasync.sh : Pull site updates down from master to front end web servers via rsync

status=”/var/www/html/datasync.status”

if [ -d /tmp/.rsync.lock ]; then
echo “FAILURE : rsync lock exists : Perhaps there is a lot of new data to pull from the master server. Will retry shortly” > $status
exit 1
fi

/bin/mkdir /tmp/.rsync.lock

if [ $? = “1” ]; then
echo “FAILURE : can not create lock” > $status
exit 1
else
echo “SUCCESS : created lock” > $status
fi

echo “===== Beginning rsync =====”

nice -n 20 /usr/bin/rsync -axvz –delete -e ssh root@192.168.1.1:/var/www/vhosts/ /var/www/vhosts/

if [ $? = “1” ]; then
echo “FAILURE : rsync failed. Please refer to solution documentation” > $status
exit 1
fi

echo “===== Completed rsync =====”

/bin/rm -rf /tmp/.rsync.lock
echo "SUCCESS : rsync completed successfully" > $status

Be sure to set executable permissions on this script so cron can run it:
chmod 755 /opt/scripts/pull-datasync.sh

Using rsync to push changes from the master web server down to slave web servers:

Using rsync to push changes from the master down to the slaves also has some important advantages. First off, the slave web servers will not have SSH access to the master server. This could become critical if one of the slave servers is ever compromised and try’s to gain access to the master web server. The next advantage is the push method does not cause a serious CPU strain cause the master will run rsync against the slave servers, one at a time.

The disadvantage here would be if you have a lot of web servers syncing content that changes often. Its possible that your updates will not be pushed down to the web servers as quickly as expected since the master server is syncing the servers one at a time. So be sure to test this out to see if the results work for your solution. Also if you are cloning your servers to create additional web servers, you will need to update the rsync configuration accordingly to include the new node.

Below will show the procedure for setting this up:

1. To make administration easier, its recommended to setup your /etc/hosts file on the master web server to include a list of all the servers hostnames and internal IP’s.

vi /etc/hosts
192.168.1.1 web01 web01.example.com
192.168.1.2 web02 web02.example.com
192.168.1.3 web03 web03.example.com

2. Create SSH keys on the master web server:
ssh-keygen -t dsa

3. Now copy the public key generated on the master web server (/root/.ssh/id_dsa.pub) and append it to the slave web servers, /root/.ssh/authorized_keys2 file.

4. Test ssh’ing in as root from the master web server to each slave web server
# On web01
ssh root@web02

5. Assuming you were able to log in to the slave web servers cleanly, then its time to create the rsync script on the master web server. Please note that I am assuming your sites documentroot’s are stored in /var/www/vhosts. If not, please change the script accordingly and test!

mkdir -p /opt/scripts/
vi /opt/scripts/push-datasync.sh

#!/bin/bash
# push-datasync.sh – Push site updates from master server to front end web servers via rsync

webservers=(web01 web02 web03 web04 web05)
status=”/var/www/html/datasync.status”

if [ -d /tmp/.rsync.lock ]; then
echo “FAILURE : rsync lock exists : Perhaps there is a lot of new data to push to front end web servers. Will retry soon.” > $status
exit 1
fi

/bin/mkdir /tmp/.rsync.lock

if [ $? = “1” ]; then
echo “FAILURE : can not create lock” > $status
exit 1
else
echo “SUCCESS : created lock” > $status
fi

for i in ${webservers[@]}; do

echo “===== Beginning rsync of $i =====”

nice -n 20 /usr/bin/rsync -avzx –delete -e ssh /var/www/vhosts root@$i:/var/www/vhosts

if [ $? = “1” ]; then
echo “FAILURE : rsync failed. Please refer to the solution documentation ” > $status
exit 1
fi

echo “===== Completed rsync of $i =====”;
done

/bin/rm -rf /tmp/.rsync.lock
echo "SUCCESS : rsync completed successfully" > $status

Be sure to set executable permissions on this script so cron can run it:
chmod 755 /opt/scripts/push-datasync.sh

Now that you have the script in place and tested, its now time to set this up to run automatically via cron. For the example here, I am setting up cron to run this script every 10 minutes.

If using the push method, put the following into the master web servers crontab:

crontab -e
# Datasync script
*/10 * * * * /opt/scripts/push-datasync.sh

If using the pull method, put the following onto each slave web servers crontab:

crontab -e
# Datasync script
*/10 * * * * /opt/scripts/pull-datasync.sh

SQUID TIPS

How to install squid proxy on centos 6

Squid is a proxy server for caching and filtering web content . Squid proxy is used by various organisation and internet providers to reduce bandwidth and to increase response time .

Squid proxy service will cache the requested web-content and re-using it for the further request of the same content.

Steps to install and configure a perfect squid proxy server in Linux. This configuration Should work on all rpm based distributions(Redhat,CentOS,Fedora,etc.)
Linux Proxy server

Step1: Install squid packages first
[root@server ~#]yum install squid

Step2: Edit the squid’s configuration file “squid.conf” located in /etc/squid/
[root@server ~#]vi /etc/squid/squid.conf

#In 18th line add your proxy client network(if 192.168.10.1 to 255) and a name for network (here netusers is acl name)
acl your_network src 192.168.10.0/24

#In the 51st line, allow internet access to above specified network range
http_access allow your_network

# in the 64th line (remove # if present), and change port number if required
http_port 3128

#Add the below 3 lines to the bottom of file
request_header_access X-Forwarded-For deny all
request_header_access Via deny all
request_header_access Cache-Control deny all

#Add the below line to bottom  add (hide IP address)
forwarded_for off

#Add below line to bottom(add your visible hostname)
visible_hostname vjetnamnet

#(now save the squid.conf file)

Step3: start squid daemon
[root@server ~#]service squid start

Then verify the port 3128 is open
# netstat -tulpn | grep 3128

Configure firewall:
# iptables -A INPUT -i $INTERNET -m state –state ESTABLISHED,RELATED -j ACCEPT
 
# iptables -t nat -A PREROUTING -i $INTERNET -p tcp –dport 80 -j REDIRECT –to-port $SQUID_PORT

Step4: In the allowed clients(192.168.10.1 to 192.168.10.255) Configure web browser’s proxy settings to use the proxy server for internet access.

Configuring Squid as Transparent Proxy

squid is a caching proxy for the Web supporting HTTP, HTTPS, FTP, and more. It reduces bandwidth and improves response times by caching and reusing frequently-requested web pages. Squid has extensive access controls and makes a great server accelerator.

An intercepting proxy (also known as a “transparent proxy“) combines a proxy server with a gateway. Connections made by client browsers through the gateway are redirected through the proxy without client-side configuration (or often knowledge). So the client never realize and don’t have to configure the client machine to use the proxy, but they are using it.

You can configure squid as transparent proxy.
[root@server ~]# vi /etc/squid/squid.conf

Squid normally listens to port 3128
http_port 3128

and replace with
http_port 3128 intercept

The most important line is:

“http_port 3128 intercept” : This line means, Squid proxy run as transparent proxy at port 3128. Later you need to edit the iptables to bypass every request/response connection through this port.
Note: That setting is for Squid v3.1. For other version like Squid v2.6 or v2.7, “intercept” option is being deprecated, you need to use option “transparent” instead.

Redirect the all HTTP traffic.

If you would like to redirect the all HTTP traffic through the proxy without needing to set up a proxy manually in all your applications you will need to add some rules
[root@server ~]# iptables -t nat -A PREROUTING -i $LAN_IN -p tcp –dport 80 -j DNAT –to $SQUID_SERVER:$SQUID_PORT
 
[root@server ~]# iptables -t nat -A PREROUTING -i $INTERNET -p tcp –dport 80 -j REDIRECT –to-port $SQUID_PORT

Example:
[root@server ~]# iptables -t nat -A PREROUTING -i eth1 -p tcp -m tcp –dport 80 -j DNAT –to-destination 192.168.10.1:3128
 
[root@server ~]# iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp –dport 80 -j REDIRECT –to-ports 3128

Where eth1,eth0 are the LAN (eth1), WAN (eth0) devices and 192.168.10.1 (squid server IP)  is the IP address of your LAN device.

If you wish to monitor the performance of your proxy you can look as some log parser’s (sarg, calamaris, ect.)

How to change Squid server default listening port

Every network services has a particular port numbers. Same way the Squid proxy server will listen on port 3128/TCP by default. But you can change the listening port by editing the squid.conf file. And you should open the same port in squid servers firewall and in ip packet forwarding devices if required. Below is the way to change Squid listen port number.
Change Squid port number
[root@server ~]# vi /etc/squid/squid.conf

Go to 64th line if you are using squid version 3.0 or above.
Here changed the port from 3128 to 8080 (see below)
Squid normally listens to port 3128
http_port 8080

Now save the squid.conf file and restart squid server
Squid server listen on multiple ports
Squid server can listen on multiple ports at same time, use the below configuration
http_port 8080 9090
Now squid will listen on both 8080 and 9090 ports as well.
Restart Squid server to apply new configurations
[root@server ~]# service squid restart
Stopping squid: …………….                                [  OK  ]
 
Starting squid: .                                               [  OK  ]

 

How to open a port in squid server

y default the following TCP port numbers are opened in squid proxy server.
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
If a web server listening on custom port 81/TCP, squid server will not allow to browse to  that server due to the port 81/TCP is not listed as Safe_ports.
Follow the steps to enable a port in squid server
[root@server ~]# vi /etc/squid/squid.conf
acl Safe_ports port 81                          # Add this line with the default port acls
 
http_access allow Safe_ports                    # allow access
Add the above two lines to squid,conf
Restart or reload squid server with changes
[root@server ~]# service squid reload
                or
[root@server ~]# service squid restart

How to enable time based access restrictions in squid proxy server

Sometimes you may need to enable a time based access restrictions in your squid server. Squid proxy can do this with “time” access list(ACL). All you need to create a “time” ACL with required time and dates from the week and apply with access restriction ACLs.

Creating time ACL
[root@server ~]# vi /etc/squid/squid.conf

Configure the time based restrictions like below
acl danny src 192.168.10.66/32
acl officehours time MTWHFA 8:00-17:00
http_access allow danny officehours
Now save the squid.conf file
Where…..
MTWHFA is the days Monday to Saturday in a week
8:00-17:00 is restrict access in between 8:00 to 17:00 (24hr format)
Reload/restart the squid service
[root@server ~]# service squid reload
Now the user james with ip address 192.168.10.66 cannot access the internet from 8:00 to 17:00 Monday to Saturday.
You can use the time ACL with any other ACLs to restrict access within the time range.

How to enable ftp access through squid proxy server

Squid work as a http proxy with default configurations and will not process ftp requests from clients. You can configure squid as ftp proxy by editing the “squid.conf” configuration file in “/etc/squid/” directory.
Follow the steps below..
[root@server ~#]vi /etc/squid/squid.conf
acl SSL_ports port 443 21                 #(Edit add the ftp port 21 to SSL port acl)
acl Safe_ports port 21                    # ftp
acl ftp proto FTP                         #(Create a new acl for ftp protocol)
 
http_access allow ftp                     #(Allow browsing above created ftp acl)

Save the squid.conf file

Reload squid service with changes
[root@server ~#]service squid reload

Use Internet explorer or firefox for ftp upload and download

To access a ftp server use this way     ftp://username:password@ipaddress:port     (press enter)

Block https sites in squid proxy

here the post will show you how to block complete “http” and “https” facebook access in office times in your squid proxy server.

eg: block  https://www.facebook.com, https://twitter.com, and https://www.blogger.com. Create an acl with facebook domain (dstdomain) and deny both http and https access.

Step1: Create a new acl with facebook.com twitter.com and blogger.com (Dont forget to add a dot (“.”) before facebook.com)

Add the Configurations to squid.conf
[root@server ~#]vi /etc/squid/squid.conf

Create an acl for facebook domain  (any required sites)
acl badsites dstdomain .facebook.com .twitter.com .blogger.com

Step2: Deny the above domain to connect via ssl connection (https)
http_access deny CONNECT badsites

(save the squid.conf configuration file)
And finaly reload squid service to take effect changes
[root@server ~#]service squid reload

Tips: The way to include multiple sites in one ACL

How to block flash ads in squid proxy server

Configure your Squid proxy server to block flash ads (advertisements) in websites. So squid server filter flash ads contents.
Steps to block all flash ads in squid proxy server.
Edit squid configuration file and add the below configurations to squid.conf file.
[root@server ~]# vi /etc/squid/squid.conf
1: Create an acl for ads content type

acl flash_ads rep_mime_type application/x-shockwave-flash

#2: Deny flash ads by denying the above acl (against any ipaddress acl)
http_reply_access deny flash_ads

Now Save the squid.conf file

3: Reload squid service to take effect changes
[root@server ~]# service squid reload

Important: Sometimes clearing the client browser’s cache/cookie is required.)

Block Downloading File Types Like mp3, exe, zip, etc In Squid

Squid server can block/deny downloading particular file types like pictures, musics, videos, executable files etc. This file content filtering in squid is based on the file extension types like .exe, .mp3, .avi, .jpeg, .torrent, .zip etc.

Blocking file types in squid. First of all, create an ACL file includes all the file types to block downloading them.
[root@server ~]# vi /etc/squid/bad_files.acl

\.[Ee][Xx][Ee]$                                                       #Block downloading exe executable files
\.[Mm][Pp]3$                                                           #Block mp3 music files
\.[Zz][Ii][Pp]$                                                           #Block ZIP archive files
\.[Jj][Pp][Ee][Gg]$                                                #Block jpeg picture files
\.[Aa][Vv][Ii]$                                                         #Block avi video files
\.[Tt][Oo][Rr][Rr][Ee][Nn][Tt]$                #Block torrent files
(Add the above required file extensions types and save the file)

Then, edit the squid configuration file and add an ACL for above created acl file.
[root@server ~]# vi /etc/squid/squid.conf
acl lan src 192.168.10.0/24                                       (specify address range to deny downloading files)
acl badfiles urlpath_regex “/etc/squid/bad_files.acl”             (ACL for blocked file types)
http_access deny badfiles lan                                     (Deny the file types to lan)

(Add the above three lines and save the squid.conf file)

Restart or reload squid server
[root@server ~]# service squid reload

Verify the file type filtering/blocking by downloading any files from the Internet

How to block utorrent application and torrent large file downloading in squid

Utorrent application uses all the unregistered posts 1025-65535 with random selection method. So blocking all those port numbers will block the bulk file downloading with utorrent application.

Edit the Squid.conf configuration file
[root@server ~]# vi /etc/squid/squid.conf

By default all the port numbers from 1025-65535 are configured as “Safe_ports” and allowed for browsing.
So disable that ACL by adding a “#” infront of the line (see below)
#acl Safe_ports port 1025-65535          # unregistered ports

And create a new ACL for the same port range just below the above line (with different acl name, like below)
acl Denied_ports port 1025-65535

And deny browsing to the websites with denied port numbers (both normal and secure)
http_access deny Denied_ports
http_access deny CONNECT Denied_ports

# now save the squid.conf file

Reload Squid server with new configuration.
[root@server ~]# service squid reload

Verify Denying
Verify denying with squid access.log file
[root@server ~]# vi /var/log/squid/access.log

How to block a Web Browser in Squid proxy

Blocking  some web browsers is possible in squid proxy server. Squid can block all the requests from web browsers like Internet explorer, Chrome, Firefox, etc.

Create an “acl” with the bad web browser types and finaly deny the access. Add all the below configurations to the Squid server configuration file “/etc/squid/squid.conf”.
[root@server ~#]vim /etc/squid/squid.conf

#Block Chrome in squid proxy
acl bad_browser browser Chrome

#Deny the requests from chrome
http_access deny bad_browser all
#Block Mozilla Firefox in squid proxy
acl bad_browser browser Firefox

#Deny the requests from firefox
http_access deny bad_browser all
#Block Opera in squid proxy
acl bad_browser browser Opera

#Deny the requests from chrome
http_access deny bad_browser all

#Block Internet Explorer in squid proxy
acl bad_browser browser IE
#Deny the requests from Internet explorer
http_access deny bad_browser all

IPTables “Stealth” Scan Detection

Many of you probably know about port scanning. It’s a very simple process, where essentially you attempt to to make a connection on several ports of several machines. If the port is closed, a reset is returned. If the port is open, a SYN+ACK is returned.

Now, there are some other types of scans, such as a FIN scan, Xmas Tree scan, and a NULL scan. These basically work on the same principals of a SYN (normal) scan, but using some different TCP flags (ones that should never be seen in valid TCP connections).

If you’d like, read up on the different types of scans here, which is also a good site to determine what type of reply you want to give the scanning host. It also shows how to perform the scans using NMap.

So, most of the time, you want to just drop invalid packets, since the easiest way to deal with them is not to. However, you may wish to use REJECT here, since what the host does and does not return is part of the data collected. Being able to decide what to return could give you an edge over an attacker. If you return tcp-resets, then you can make an attacker (or more likely a bot) think that all the ports on the host are closed. Different operating systems also respond differently to the various stealth scans, so be mindful of that as well.

I wrote some simple firewall rules to detect, log, and block (either with a tcp-reset or just dropping the packet entirly. This script was made to run on top of an existng firewall.

## IPTables rules for detecting and blocking several different scans
## By Drew Tingen GlimpseIntoEntropy.Blogspot.com
## NOTE: Please understand the use of REJECT/DROP
## NOTE2: You may want to mirror the FORWARD rules to INPUT

## Note on Rule Order – since these are Inserts (designed to be easily plugged into
## an existing iptables config), the packet actions are above the logging action.
## If you put these at the top of a config, and change the -I to -A, reverse the order
## of the rules for logging to work properly

## TCP Null Scan
### Action for packets
### use REJECT option to make port look closed. Use drop for open/stealth
iptables -I FORWARD -p tcp –tcp-flags ALL NONE -j REJECT –reject-with tcp-reset
#iptables -I FORWARD -p tcp –tcp-flags ALL NONE -j DROP
### Detect and log
iptables -I FORWARD -p tcp –tcp-flags ALL NONE -j LOG –log-prefix “TCP Null Scan”

## TCP Fin Scan
### Action for packets
iptables -I FORWARD -p tcp –tcp-flags FIN,SYN FIN -m state –state NEW,INVALID -j REJECT –reject-with tcp-reset
#iptables -I FORWARD -p tcp –tcp-flags FIN,SYN FIN -m state –state NEW,INVALID -j DROP
### Detect and Log
iptables -I FORWARD -p tcp –tcp-flags FIN,SYN FIN -m state –state NEW,INVALID -j LOG –log-prefix “TCP FIN Scan”

## TCP Xmas Tree Scan
### Action for packets
iptables -I FORWARD -p tcp –tcp-flags ALL URG,PSH,FIN -j REJECT –reject-with tcp-reset
#iptables -I FORWARD -p tcp –tcp-flags ALL URG,PSH,FIN -j DROP
### Detect and Log
iptalbes -I FORWARD -p tcp –tcp-flags ALL URG,PSH,FIN -j LOG –log-prefix “Xmas Tree Scan”

#! / Bin / sh
# ————————————————- —————————–
#
# File: SIG-antiDDoS.sh
#
# ————————————————- —————————–
 
# For debugging use iptables-v.
IPTABLES = “/ sbin / iptables”  
IP6TABLES = “/ sbin/ip6tables”  
MODPROBE = “/ sbin / modprobe”  
RMMOD = “/ sbin / rmmod”  
ARP = “/ usr / sbin / arp”  
 
 
# Logging options.
# ————————————————- —————————–
LOG = “LOG – log-level debug – log-tcp-sequence – log-tcp-options”  
LOG = “$ LOG – log-ip-options”  
 
 
# Defaults for rate limiting
# ————————————————- —————————–
RLIMIT = “-m limit – limit 3 / s – limit-burst 8”  
 
 
# Unprivileged ports.
# ————————————————- —————————–
PHIGH = “1024:65535”  
PSSH = “1000:1023”  
 
 
# Load required kernel modules
# ————————————————- —————————–
$ MODPROBE ip_conntrack_ftp
$ MODPROBE ip_conntrack_irc
 
 
# Mitigate ARP spoofing / poisoning and similar attacks.
# ————————————————- —————————–
# Hardcode static ARP cache entries here
# $ ARP-s IP-ADDRESS MAC-ADDRESS
 
 
# Kernel configuration.
# ————————————————- —————————–
 
# Disable IP forwarding.
# On =>   Off = (reset)
echo 1> / proc/sys/net/ipv4/ip_forward
echo 0> / proc/sys/net/ipv4/ip_forward
 
# Enable IP spoofing protection
for i in / proc/sys/net/ipv4/conf / * / rp_filter; do echo 1> $ i; done
 
# Protect against SYN flood attacks
echo 1> / proc/sys/net/ipv4/tcp_syncookies
 
# Ignore all incoming ICMP echo requests
echo 0> / proc/sys/net/ipv4/icmp_echo_ignore_all
 
# Ignore ICMP echo requests to broadcast
echo 1> / proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
 
# Log packets with impossible addresses.
for i in / proc/sys/net/ipv4/conf / * / log_martians; do echo 1> $ i; done
 
# Don’t log invalid responses to broadcast
echo 1> / proc/sys/net/ipv4/icmp_ignore_bogus_error_responses
 
# Don’t accept or send ICMP redirects.
for i in / proc/sys/net/ipv4/conf / * / accept_redirects; do echo 0> $ i; done
for i in / proc/sys/net/ipv4/conf / * / send_redirects; do echo 0> $ i; done
 
# Don’t accept source routed packets.
for i in / proc/sys/net/ipv4/conf / * / accept_source_route; do echo 0> $ i; done
 
# Disable multicast routing
for i in / proc/sys/net/ipv4/conf / * / mc_forwarding; do echo 0> $ i; done
 
# Disable proxy_arp.
for i in / proc/sys/net/ipv4/conf / * / proxy_arp; do echo 0> $ i; done
 
# Enable secure redirects, ie only accept ICMP redirects for gateways
# Helps against MITM attacks.
for i in / proc/sys/net/ipv4/conf / * / secure_redirects; do echo 1> $ i; done
 
# Disable bootp_relay
for i in / proc/sys/net/ipv4/conf / * / bootp_relay; do echo 0> $ i; done
 
# Default policies.
# ————————————————- —————————–
 
# Drop everything by default.
$ IPTABLES-P INPUT DROP
$ IPTABLES-P FORWARD DROP
$ IPTABLES-P OUTPUT DROP
 
# Set the nat / mangle / raw tables’ chains to ACCEPT
$ IPTABLES-t nat-P PREROUTING ACCEPT
$ IPTABLES-t nat-P OUTPUT ACCEPT
$ IPTABLES-t nat-P POSTROUTING ACCEPT
 
$ IPTABLES-t mangle-P PREROUTING ACCEPT
$ IPTABLES-t mangle-P INPUT ACCEPT
$ IPTABLES-t mangle-P FORWARD ACCEPT
$ IPTABLES-t mangle-P OUTPUT ACCEPT
$ IPTABLES-t mangle-P POSTROUTING ACCEPT
 
# Cleanup.
# ————————————————- —————————–
 
# Delete all
$ IPTABLES-F
$ IPTABLES-t nat-F
$ IPTABLES-t mangle-F
 
# Delete all
$ IPTABLES-X
$ IPTABLES-t nat-X
$ IPTABLES-t mangle-X
 
# Zero all packets and counters.
$ IPTABLES-Z
$ IPTABLES-t nat-Z
$ IPTABLES-t mangle-Z
 
# Completely disable IPv6.
# ————————————————- —————————–
 
# Block all IPv6 traffic
# If the ip6tables command is available, try to block all IPv6 traffic.
if test-x $ IP6TABLES; then
# Set the default policies
# Drop everything
$ IP6TABLES-P INPUT DROP 2> / dev / null
$ IP6TABLES-P FORWARD DROP 2> / dev / null
$ IP6TABLES-P OUTPUT DROP 2> / dev / null
 
# The mangle table can pass everything
$ IP6TABLES-t mangle-P PREROUTING ACCEPT 2> / dev / null
$ IP6TABLES-t mangle-P INPUT ACCEPT 2> / dev / null
$ IP6TABLES-t mangle-P FORWARD ACCEPT 2> / dev / null
$ IP6TABLES-t mangle-P OUTPUT ACCEPT 2> / dev / null
$ IP6TABLES-t mangle-P POSTROUTING ACCEPT 2> / dev / null
 
# Delete all rules.
$ IP6TABLES-F 2> / dev / null
$ IP6TABLES-t mangle-F 2> / dev / null
 
# Delete all chains.
$ IP6TABLES-X 2> / dev / null
$ IP6TABLES-t mangle-X 2> / dev / null
 
# Zero all packets and counters.
$ IP6TABLES-Z 2> / dev / null
$ IP6TABLES-t mangle-Z 2> / dev / null
fi
 
# Custom user-defined chains.
# ————————————————- —————————–
 
# LOG packets, then ACCEPT.
$ IPTABLES-N ACCEPTLOG
$ IPTABLES-A ACCEPTLOG-j $ LOG $ RLIMIT – log-prefix “ACCEPT”
$ IPTABLES-A ACCEPTLOG-j ACCEPT
 
# LOG packets, then DROP.
$ IPTABLES-N DROPLOG
$ IPTABLES-A DROPLOG-j $ LOG $ RLIMIT – log-prefix “DROP”
$ IPTABLES-A DROPLOG-j DROP
 
# LOG packets, then REJECT.
# TCP packets are rejected with a TCP reset.
$ IPTABLES-N REJECTLOG
$ IPTABLES-A REJECTLOG-j $ LOG $ RLIMIT – log-prefix “REJECT”
$ IPTABLES-A REJECTLOG-p tcp-j REJECT – reject-with tcp-reset
$ IPTABLES-A REJECTLOG-j REJECT
 
# Only allows RELATED ICMP types
# (Destination-unreachable, time-exceeded, and parameter-problem).
# TODO: Rate-limit this traffic?
# TODO: Allow fragmentation-needed?
# TODO: Test.
$ IPTABLES-N RELATED_ICMP
$ IPTABLES-A RELATED_ICMP-p icmp – icmp-type destination-unreachable-j ACCEPT
$ IPTABLES-A RELATED_ICMP-p icmp – icmp-type time-exceeded-j ACCEPT
$ IPTABLES-A RELATED_ICMP-p icmp – icmp-type parameter-problem-j ACCEPT
$ IPTABLES-A RELATED_ICMP-j DROPLOG
 
# Make It Even Harder To Multi-PING
$ IPTABLES-A INPUT-p icmp-m limit – limit 1 / s – limit-burst 2-j ACCEPT
$ IPTABLES-A INPUT-p icmp-m limit – limit 1 / s – limit-burst 2-j LOG – log-prefix PING-DROP:
$ IPTABLES-A INPUT-p icmp-j DROP
$ IPTABLES-A OUTPUT-p icmp-j ACCEPT
 
# Only allow the minimally required / recommended parts of ICMP. Block the rest.
# ————————————————- —————————–
 
# TODO: This section needs a lot of testing!
 
# First, drop all fragmented ICMP packets (almost always malicious).
$ IPTABLES-A INPUT-p icmp – fragment-j DROPLOG
$ IPTABLES-A OUTPUT-p icmp – fragment-j DROPLOG
$ IPTABLES-A FORWARD-p icmp – fragment-j DROPLOG
 
# Allow all ESTABLISHED ICMP traffic.
$ IPTABLES-A INPUT-p icmp-m state – state ESTABLISHED-j ACCEPT $ RLIMIT
$ IPTABLES-A OUTPUT-p icmp-m state – state ESTABLISHED-j ACCEPT $ RLIMIT
 
# Allow some parts of the RELATED ICMP traffic, block the rest.
$ IPTABLES-A INPUT-p icmp-m state – state RELATED-j RELATED_ICMP $ RLIMIT
$ IPTABLES-A OUTPUT-p icmp-m state – state RELATED-j RELATED_ICMP $ RLIMIT
 
# Allow incoming ICMP echo requests (ping), but only rate-limited.
$ IPTABLES-A INPUT-p icmp – icmp-type echo-request-j ACCEPT $ RLIMIT
 
# Allow outgoing ICMP echo requests (ping), but only rate-limited.
$ IPTABLES-A OUTPUT-p icmp – icmp-type echo-request-j ACCEPT $ RLIMIT
 
# Drop any other ICMP traffic.
$ IPTABLES-A INPUT-p icmp-j DROPLOG
$ IPTABLES-A OUTPUT-p icmp-j DROPLOG
$ IPTABLES-A FORWARD-p icmp-j DROPLOG
 
# Selectively allow certain special types of traffic.
# ————————————————- —————————–
 
# Allow loopback interface to do anything.
$ IPTABLES-A INPUT-i lo-j ACCEPT
$ IPTABLES-A OUTPUT-o lo-j ACCEPT
 
# Allow incoming connections related to existing allowed connections.
$ IPTABLES-A INPUT-m state – state ESTABLISHED, RELATED-j ACCEPT
 
# Allow outgoing connections EXCEPT invalid
$ IPTABLES-A OUTPUT-m state – state NEW, ESTABLISHED, RELATED-j ACCEPT
 
# Miscellaneous.
# ————————————————- —————————–
 
# We don’t care about Milkosoft, Drop SMB / CIFS / etc ..
$ IPTABLES-A INPUT-p tcp-m multiport – dports 135,137,138,139,445,1433,1434-j DROP
$ IPTABLES-A INPUT-p udp-m multiport – dports 135,137,138,139,445,1433,1434-j DROP
 
# Explicitly drop invalid incoming traffic
$ IPTABLES-A INPUT-m state – state INVALID-j DROP
 
# Drop invalid outgoing traffic, too.
$ IPTABLES-A OUTPUT-m state – state INVALID-j DROP
 
# If we would use NAT, INVALID packets would pass – BLOCK them anyways
$ IPTABLES-A FORWARD-m state – state INVALID-j DROP
 
# PORT Scanners (stealth also)
$ IPTABLES-A INPUT-m state – state NEW-p tcp – tcp-flags ALL ALL-j DROP
$ IPTABLES-A INPUT-m state – state NEW-p tcp – tcp-flags ALL NONE-j DROP
 
# TODO: Some more anti-spoofing rules? For example:
# $ IPTABLES-A INPUT-p tcp – tcp-flags ALL FIN, URG, PSH-j DROP
# $ IPTABLES-A INPUT-p tcp – tcp-flags SYN, RST SYN, RST-j DROP
# $ IPTABLES-A INPUT-p tcp – tcp-flags SYN, FIN SYN, FIN-j DROP
$ IPTABLES-N SYN_FLOOD
$ IPTABLES-A INPUT-p tcp – syn-j SYN_FLOOD
$ IPTABLES-A SYN_FLOOD-m limit – limit 2 / s – limit-burst 6-j RETURN
$ IPTABLES-A SYN_FLOOD-j DROP
 
# TODO: Block known-bad IPs (see http://www.dshield.org/top10.php).
# $ IPTABLES-A INPUT-s INSERT-BAD-IP-HERE-j DROPLOG
 
# Drop any traffic from IANA-reserved IPs.
# ————————————————- —————————–
 
$ IPTABLES-A INPUT-s 0.0.0.0 / 7-j DROP
$ IPTABLES-A INPUT-s 2.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 5.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 7.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 10.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 23.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 27.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 31.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 36.0.0.0 / 7-j DROP
$ IPTABLES-A INPUT-s 39.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 42.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 49.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 50.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 77.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 78.0.0.0 / 7-j DROP
$ IPTABLES-A INPUT-s 92.0.0.0 / 6-j DROP
$ IPTABLES-A INPUT-s 96.0.0.0 / 4-j DROP
$ IPTABLES-A INPUT-s 112.0.0.0 / 5-j DROP
$ IPTABLES-A INPUT-s 120.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 169.254.0.0/16-j DROP
$ IPTABLES-A INPUT-s 172.16.0.0/12-j DROP
$ IPTABLES-A INPUT-s 173.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 174.0.0.0 / 7-j DROP
$ IPTABLES-A INPUT-s 176.0.0.0 / 5-j DROP
$ IPTABLES-A INPUT-s 184.0.0.0 / 6-j DROP
$ IPTABLES-A INPUT-s 192.0.2.0/24-j DROP
$ IPTABLES-A INPUT-s 197.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 198.18.0.0/15-j DROP
$ IPTABLES-A INPUT-s 223.0.0.0 / 8-j DROP
$ IPTABLES-A INPUT-s 224.0.0.0 / 3-j DROP
 
# Selectively allow certain outbound connections, block the rest.
# ————————————————- —————————–
 
# Allow outgoing DNS requests. Few things will work without this.
$ IPTABLES-A OUTPUT-m state – state NEW-p udp – dport 53-j ACCEPT
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 53-j ACCEPT
 
# Allow outgoing HTTP requests. Unencrypted, use with care.
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 80-j ACCEPT
 
# Allow outgoing HTTPS requests.
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 443-j ACCEPT
 
# Allow outgoing SMTPS requests. Do NOT allow unencrypted SMTP!
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 465-j ACCEPT
 
# Allow outgoing “submission” (RFC 2476) requests.
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 587-j ACCEPT
 
# Allow outgoing POP3S requests.
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 995-j ACCEPT
 
# Allow outgoing SSH requests.
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 22-j ACCEPT
 
# Allow outgoing FTP requests. Unencrypted, use with care.
$ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 21-j ACCEPT
 
# Allow outgoing NNTP requests. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 119-j ACCEPT
 
# Allow outgoing NTP requests. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p udp – dport 123-j ACCEPT
 
# Allow outgoing IRC requests. Unencrypted, use with care.
# Note: This usually needs the ip_conntrack_irc kernel module.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 6667-j ACCEPT
 
# Allow outgoing requests to various proxies. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 8080-j ACCEPT
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 8090-j ACCEPT
 
# Allow outgoing DHCP requests. Unencrypted, use with care.
# TODO: This is completely untested, I have no idea whether it works!
# TODO: I think this can be tightened a bit more.
$ IPTABLES-A OUTPUT-m state – state NEW-p udp – sport 67:68 – dport 67:68-j ACCEPT
 
# Allow outgoing CVS requests. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 2401-j ACCEPT
 
# Allow outgoing MySQL requests. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 3306-j ACCEPT
 
# Allow outgoing SVN requests. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 3690-j ACCEPT
 
# Allow outgoing PLESK requests. Unencrypted, use with care.
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 8443-j ACCEPT
 
# Allow outgoing Tor (http://tor.eff.org) requests.
# Note: Do _not_ use unencrypted protocols over Tor (sniffing is possible)!
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 9001-j ACCEPT
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 9002-j ACCEPT
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 9030-j ACCEPT
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 9031-j ACCEPT
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 9090-j ACCEPT
# $ IPTABLES-A OUTPUT-m state – state NEW-p tcp – dport 9091-j ACCEPT
 
# Allow outgoing OpenVPN requests.
$ IPTABLES-A OUTPUT-m state – state NEW-p udp – dport 1194-j ACCEPT
 
# TODO: ICQ, MSN, GTalk, Skype, Yahoo, etc …
 
# Selectively allow certain inbound connections, block the rest.
# ————————————————- —————————–
 
# Allow incoming DNS requests.
$ IPTABLES-A INPUT-m state – state NEW-p udp – dport 53-j ACCEPT
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 53-j ACCEPT
 
# Allow incoming HTTP requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 80-j ACCEPT
 
# Allow incoming HTTPS requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 443-j ACCEPT
 
# Allow incoming POP3 requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 110-j ACCEPT
 
# Allow incoming IMAP4 requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 143-j ACCEPT
 
# Allow incoming POP3S requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 995-j ACCEPT
 
# Allow incoming SMTP requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 25-j ACCEPT
 
# Allow incoming SSH requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 22-j ACCEPT
 
# Allow incoming FTP requests.
$ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 21-j ACCEPT
 
# Allow incoming NNTP requests.
# $ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 119-j ACCEPT
 
# Allow incoming MySQL requests.
# $ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 3306-j ACCEPT
 
# Allow incoming PLESK requests.
# $ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 8843-j ACCEPT
 
# Allow incoming BitTorrent requests.
# TODO: Are these already handled by ACCEPTing established / related traffic?
# $ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 6881-j ACCEPT
# $ IPTABLES-A INPUT-m state – state NEW-p udp – dport 6881-j ACCEPT
 
# Allow incoming nc requests.
# $ IPTABLES-A INPUT-m state – state NEW-p tcp – dport 2030-j ACCEPT
# $ IPTABLES-A INPUT-m state – state NEW-p udp – dport 2030-j ACCEPT
 
# Explicitly log and reject everything else.
# ————————————————- —————————–
# Use REJECT instead of REJECTLOG if you don’t need / want logging.
$ IPTABLES-A INPUT-j REJECTLOG
$ IPTABLES-A OUTPUT-j REJECTLOG
$ IPTABLES-A FORWARD-j REJECTLOG
 
 
# ————————————————- —————————–
# Testing the firewall.
# ————————————————- —————————–
 
# You should check / test that the firewall really works, using
# Iptables-vnL, nmap, ping, telnet, …
 
# Exit gracefully.
# ————————————————- —————————–
 
exit 0

Bridging, Transparent Firewalls and Intrusion Prevention

Contents

    What is Bridging?
    Installing a Bridge
    Configuring a Bridge
    What is a Bridging Firewall?
    Installing a Bridging Ebtables Firewall
    Configuring a Bridging Ebtables Firewall
    Installing a Bridging Iptables Firewall
    Configuring a Bridging Iptables Firewall
    What is an Intrusion Prevention System?
    Installing an Intrusion Prevention System
    Configuring an Intrusion Prevention System

What is Bridging?

A bridge is a network device, that connects two network segments of any network type (ethernet, token ring etc.) transparently to form one subnet. Transparency means, that you do not have to tell any component (computer, application etc.) that there is a new device between them. So, no configuration on them is needed. And your bridge is really stealthy, because it does not need any IP address.

You can easily build a bridge using a computer with at least two network interfaces. Here, in this section, I want to decribe howto setup a bridge using Linux (here wirth kernel 2.4.24), because based on the transparency characteristics of a bridge, you can build security enhancing network devices like bridging (transparent) firewalls and intrusion prevention systems.

Installing a Bridge

There are two things to do. First, you have to install the bridge-utils. Under gentoo you just type:

emerge bridge-utils

If your distribution is not shiped with bridge-utils, then you can download them from sourceforge. You can configure, compile and install bridge-utils the standard way.

The second thing to do is to prepare the kernel. Fortunately, you have to activate all drivers you need to run your box properly. In addition, you have to active (this depends on the development status of the kernel features):

    Code maturity level options –> Prompt development and/or incomplete code/drivers
    Networking options –> 802.1d Ethernet Bridging

Then simply recompile and install your new kernel. Reboot. If you are using modules, then load them!

Configuring a Bridge

Configuring a bridge a really straightforward. See table 1.

Table 1: Configuring the Bridge
$ ifconfig eth0 0.0.0.0 up
$ ifconfig eth1 0.0.0.0 up
$ brctl addbr br0
$ brctl addif br0 eth0
$ brctl addif br0 eth1
$ ifconfig br0 0.0.0.0 up

Now you have a network device, that forwards traffic between two network segments transparently. But what do the commands in table 1 do exactly? With the first two lines, you bring the two ethernet interfaces eth0 and eth1 up, without assigning an IP address to them. The 0.0.0.0 garantees, thet even if an IP address was assigned at startup, it will be overwritten. In the third line a new device, here a bridge, called br0 is created. Lines 4 and 5 add the two interfaces eth0 and eth1 to our bridge br0. In the last line, we bring our bridge br0 up. Again, we assign no IP address to it.

What is a Bridging Firewall?

A bridging firewall is also often called a transparent firewall and some benefits come with its’ design:

    Zero configuration. From a networking standpoint, there are virtually no changes. How can this be? Easy, the bridging firewall is plugged in-line with the network it is protecting. This means you can put it between two routers, or a router and a switch. You could even put it in front of a single machine. While it might be placed exactly where it should be if it were acting as a gateway or router, it’s not. Remember, it merely moves frames after inspecting them between interfaces. This means that there’s no need to make any changes to your existing network. It is completely transparent. No subnetting headaches or configuration updates are required with this device.
    Performance. Because they are simpler devices, there’s less processing overhead. This cost cutting either boosts the capabilities of the machines or allows for deeper examination of the data.
    Stealth. A key aspect of this device is the fact that it operates at layer 2 of the OSI model. This means the network interfaces have no IP addresses. Such a feature carries more weight than merely ease of configuration. Without an IP address, this device is unreachable and invisible to the outside world. If it cannot be reached, how can anyone attack it? No network probes, denial of service floods or firewalking on this machine. Your attackers won’t even know it’s in place, silently inspecting everything they send.

The are two possibilities to realize a bridging firewall: with ebtables or with iptables. In ebtables the focus is more on OSI layer 2-3, where in iptables it is more on ISO layer 3-4. Ebtables might be more suitable in scenarios, where the bridge connects two network segments within one subnet, where iptables might be more suitable where the bridge is placed before a router that connects the subnet to another net.

Installing a Bridging Ebtables Firewall?

First of all you need a bridge. Above I have decribed how to install and configure it. Secondly you have to install the ebtables packages. Under gentoo just do a

emerge ebtables

But keep in mind, that this package is masked. If this package is not shipped with your distribution, then download it from sourceforge. You can configure, compile and install ebtables the standard way. ebtables can be seen as a replacement for iptables. But it uses other tables within the kernel.

The next step is to enhance the kernel with the ebtables-brnf-patch (not necessary for kernel 2.6, because it is already in there). You can download it from sourceforge. Decompress it and the patch your kernel with the corresponding version of ebtables-brnf:

patch -p1 <patch_file

Within the kernel you have to activate:

    Networking options –> Network packet filtering (replaces ipchains)
    Networking options –> 802.1d Ethernet Bridging
    Networking options –> 802.1d Ethernet Bridging –> Bridge: ebtables (NEW)

Then a list of options for ebtables pops up. you can select, for simplicity, all of them. Then simply recompile, and install your new kernel. Reboot. If you are using modules, then load them!

Configuring a Bridging Ebtables Firewall?

The bridge is now running and the kernel already prepared for configuring a firewall via ebtables. The best is always to have a real life example to show how it works. My example will be based on the following environment:

    There is a NAT-Router with the IP address 192.168.1.1 playin the role of a gateway all clients within the subnet 192.168.1.0/24 and connection them to the internet
    On the NAT-Router runs an DNS forwarder, so that he is the DNS server for all clients in the subnet.
    The subnet 192.168.1.0/24 is divided into two parts. The clients within the first part of the subnet are directly connected to the NAT router via a switch. The clients of the second part of the subnet are connected with the first part of the subnet via our new bridge.
    There is a client in the second part of the subnet with the IP address 192.168.1.52. This client wants to surf the WWW. So it has to pass the bridge and the NAT router.

Table 2: Configuring the Bridging Ebtables Firewall
$ ebtables -P FORWARD DROP
$ ebtables -A FORWARD -p 0x806 -j ACCEPT
$ ebtables -A FORWARD -p 0x800 –ip-dst 192.168.1.52 –ip-proto tcp –ip-sport 80 -j ACCEPT
$ ebtables -A FORWARD -p 0x800 –ip-src 192.168.1.52 –ip-proto tcp –ip-dport 80 -j ACCEPT
$ ebtables -A FORWARD -p 0x800 –ip-src 192.168.1.52 –ip-dst 192.168.1.1 –ip-proto udp –ip-dport 53 -j ACCEPT
$ ebtables -A FORWARD -p 0x800 –ip-src 192.168.1.1 –ip-dst 192.168.1.52 –ip-proto udp –ip-sport 53 -j ACCEPT

The syntax of ebtables is quite similar to the one of iptables.Because we are using briding, that has in our case a lot of similarities to routing, we have to configure only our FORWARD chain. In the first line we set our default policy to DROP, meaning, that all packages not matching any other rule, are dropped by default. The second line says, that our bridging firewall will let ARP packages pass. The parameter -p is used to specify a protocol in hex. 0x806 is ARP (Address Resolution Protocol). This is needed, because the clients within a subnet communicate based on layer 2 of the OSI model. And so they have to find the MAC addresses based on the IP addresses they know.

In the third and fourth line we grant the client 192.168.1.52 to do surf the WWW. -p 0x800 is the well known Internet Protocol (IP). –ip-dst and –ip-src give the destination and source IP respectively. –ip-proto specifies the IP protocol, here TCP. With –ip-dport and –ip-sport we specify the destination and sourceport, here port 80 (the standard port for http traffic).

The last two lines eneble the client 192.168.1.52 to do dns requests. The NAT router 192.168.1.1 serves as a DNS forwarder. In this case the source and destination addresses are well known. The IP protocol used is UDP and the port on the NAT router serving DNS is 53.

Configured this way, our bridging firewall will only let one client through and will enable him to surf in the WWW.

Installing a Bridging Iptables Firewall?

First of all you need a bridge. Above I have decribed how to install and configure it. Secondly you have to install the iptables packages. Under gentoo just do a

emerge iptables

The software is shiped with really every distribution. So you do not need to download it.

Within the kernel you have to activate at least the following options:

    Networking options –> Network packet filtering (replaces ipchains)
    Networking options –> IP: Netfilter Configuration –> Connection Tracking (required for masq/NAT)
    Networking options –> IP: Netfilter Configuration –> IP tables support (required for filtering/masq/NAT)
    Networking options –> IP: Netfilter Configuration –> Connection state match support
    Networking options –> IP: Netfilter Configuration –> Connection tracking match support

Then simply recompile, and install your new kernel. Reboot. If you are using modules, then load them!

Configuring a Bridging Iptables Firewall?

Because iptables is well documented (and there is also a howto on linuxsecure) I will not go into detail here. I will only show a very small example here that uses connection tracking. The bridged iptables firewall will only let connections from client 192.168.1.52 out (willforward them) but no connections in. See table 3 for details.

Table 3: Configuring the Bridging Iptables Firewall
$ iptables -P FORWARD DROP
$ iptables -A FORWARD -m state –state ESTABLISHED,RELATED -j ACCEPT
$ iptables -A FORWARD -s 192.168.1.52 -m state –state NEW -j ACCEPT

The first line in table 3 configures the default policy. Any traffic, that is not matched by a rule is dropped. The next two lines tell iptables to let only packets in that belong to an existing connection or are related to it. As configured in line 3, new connections can only be established from client 192.168.1.52.

What is an Intrusion Prevention System?

I have already written a few lines about Intrusion Detection System (IDS) here One big point about flexible responses I have made there, is that despite the practicability of flexible responses, it is not fast/reliable enough. So If you want it, then you have to implement IDS with flexible response (or something similar) onto a router. A bridge is very similar to a router. It is a single entry or exit point to a network segment. So all traffic going in or out has to go through it. If you install an Intrusion Detection System on a bridge (or router) and if you configure it in a way, that it will not forward packages identified as containing an attack signature, then you have an Intrusion Prevention System (IPS).

Installing an Intrusion Prevention System

Here, I will show how to install an IPS on a bridge. Installing one on a router is quite the same. First, we have to set up the bridge, as shown above. Then we have to download snort_inline from sourceforge. Then just do

./configure –enable-inline
make
make install

Because snort_inline receives the network packages via iptables, we have to activate userspace queueing in the kernel:

    Networking options –> Network packet filtering (replaces ipchains)
    Networking options –> IP: Netfilter Configuration –> Userspace queueing via Netlink (EXPERIMENTAL) (NEW)

Then simply recompile, and install your new kernel. Reboot. If you are using modules, then load them!

Configuring an Intrusion Prevention System

The configuration of snort_inline is nearly the same as for snort, exept for the rule types. There are three new rule types, namely drop, reject, and sdrop:

    The drop rule will tell iptables to drop the packet and log it via usual snort means.
    The recet rule type will tell iptables to drop the packet, log it via usual snort means, and send a TCP reset if the protocol is TCP or an icmp port unreachable if the protocol is UDP.
    The sdrop rule type will tell iptables to drop the packet. Nothing is logged.

Now we have to tell iptables to sent all packages going through the bridge to the table QUEUE, so that snort_inline can get them from there. This can be archived with the commands in table 4.

Table 4: Preparing Iptables for Snort_Inline
$ IPTABLES -P FORWARD DROP
$ IPTABLES -A FORWARD -j QUEUE

The first line is not really necessary. The second line configures netfilter to push all packages in the FORWARD chain in to the table QUEUE.

What we have to do now is to change some of the rules in a way, that network packages matching attack signatures are not only detected, but also droped, so that they will never arrive at the target host. For example, we can prohibit packages matching the ICMP PING NMAP signature by simply changing the rule

alert icmp $EXTERNAL_NET any -> $HOME_NET any (msg:”ICMP PING NMAP”; dsize: 0; itype: 8; reference:arachnids,162; classtype:attempted-recon; sid:469; rev:1;)

to

drop icmp $EXTERNAL_NET any -> $HOME_NET any (msg:”ICMP PING NMAP”; dsize: 0; itype: 8; reference:arachnids,162; classtype:attempted-recon; sid:469; rev:1;)

Within snort_inline the rule application order has changed, in order to get intrusion prevention functionality. The new rule application order is now:

->activation->dynamic->drop->sdrop->reject->alert->pass->log

To start snort in inline mode, we have to use the new switch Q, meaning, that snort will not receive packages by sniffing on the wire, but via iptables:

snort_inline -QDc /etc/snort_inline/snort.conf -l /var/log/snort_inline

where /var/log/snort_inline is the directory, where snort logs the alerts/drops.

Stealth Firewalling with Linux

What Is Stealth Firewalling with Linux?
Simply put, a stealth firewall is an Ethernet bridge with filtering capabilities. This means that it’s a firewall that operates at Layer 2 of the OSI model, leveraging netfilter rules and chains (Linux’s firewall system) applied to the bridge. For those not familiar with what a bridge is: an Ethernet bridge is a means of connecting two or more networks/devices at the Data Link layer. The Data Link layer is the layer of the OSI model before the Network Layer (Layer 3). Layer 3 is where things like the IP in TCP/IP come into the picture. This means that a bridge operates before we get into things like protocols, so you can apply firewalling to protocols other than IP (IPX, DECnet, SNA, etc.) and you don’t have to worry about routing issues either. You’re moving raw frames from one interface to another, which lets you deploy your stealth firewall without anyone being the wiser. Another advantage of a stealth firewall is that if the hardware fails or malfunctions, you can bypass it with nothing more than a network cable.
How Does a Bridge Work?
A bridge operates in promiscuous mode, grabbing all the packets it sees on its interfaces, learns which MAC addresses apply to which interfaces, and moves packets between those interfaces. One example of a bridge that many are familiar with is the humble network switch, wherein all the interfaces on a switch comprise one bridge. With Linux, when you create a bridge you are combining two or more interfaces into one bridge. For instance, we’ll create a bridge, br0, that is made up of two interfaces, eth0 and eth1. Think of br0 as a set that contains two elements, eth0 and eth1. When the two interfaces are added to the bridge, the kernel will then move packets back and forth automatically between those two interfaces as if they were both part of the same physical network.

A Brief Explanation of Netfilter
Netfilter, if you’re not familiar with it, is Linux’s packet filtering system introduced in the 2.4 kernel and continued into 2.6. The netfilter system is manipulated by the userspace tool, iptables, and can also be manipulated by other tools. We only point this out because iptables is sometimes thought to be the only mechanism for controlling the kernel’s filtering capabilities, but it’s not.

Thanks to the flexibility of the netfilter subsystem and the way it handles packets, we can use it to apply firewall rules to network traffic, even if the device is not operating at the IP layer. The subsystem doesn’t actually care; it can apply firewall rules to whatever traffic passes through it. To help explain this, Figure 1 shows which netfilter rules are applied to the bridge interface, and the order in which they are applied for traffic flowing from eth0 to eth1 over the bridge.

Figure 1


What This Means in Practical Terms
You can put a firewall in place without anyone knowing it’s there or making any IP topology changes. For example, at the California Community Colocation Project (www.communitycolo.net), we used a bridging/stealth firewall to filter out worm traffic entering and exiting the network. This was done in such a way that there was no interruption for the users of the network, no need to change the routing tables or to even muck about with IP issues, and it required only some basic physical wiring changes. The use of a stealthy firewall such as this leads to all sorts of interesting alternative applications outside of just basic firewalling, such as stealth proxies, traffic-shaping devices, anti-spam/virus filtering, and stealth IDS/IPS systems. The key advantage for the firewall administrator is that you can deploy a fairly paranoid firewall setup without having to make any changes to your network, and failing over, as previously mentioned, is as simple as plugging in a patch cable.
How Do I Set One Up?
We’re using Fedora Core 3 for our demonstration environment, but the following should apply to nearly any modern Linux distribution running a 2.6 kernel. You can also do this with a 2.4 kernel, but for brevity’s sake we’re going to stick with the screaming edge. It’s more fun that way. First, we need to make sure our kernels support both bridging and Layer 2 filtering in netfilter. If you’re running FC3 with the default kernel, you can skip this next bit; this is for those of you running custom 2.6 kernels or other distributions that don’t include this functionality by default. To enable bridging and Layer 2 filtering, you’ll need to make sure the following settings are configured in your kernel to support ebtables.

Device Drivers
Networking Support
Networking Options —>
  <M> 802.1d Ethernet Bridging
  [*] Network packet filtering (replaces ipchains)  —>
    [*]   Bridged IP/ARP packets filtering
    Bridge: Netfilter Configuration  —>
      <M> Ethernet Bridge tables (ebtables) support
        <M>   ebt: broute table support (NEW)
        <M>   ebt: filter table support (NEW)
        <M>   ebt: nat table support (NEW)
        <M>   ebt: 802.3 filter support (NEW)
        <M>   ebt: among filter support (NEW)
        <M>   ebt: ARP filter support (NEW)
        <M>   ebt: IP filter support (NEW)
        <M>   ebt: limit match support (NEW)
        <M>   ebt:  mark filter support (NEW)
        <M>   ebt: packet type filter support (NEW)
        <M>   ebt: STP filter support (NEW)
        <M>   ebt: 802.1Q VLAN filter support (NEW)
        <M>   ebt: arp reply target support (NEW)
        <M>   ebt: dnat target support (NEW)
        <M>   ebt: mark target support (NEW)
        <M>   ebt: redirect target support (NEW)
        <M>   ebt: snat target support (NEW)
        <M>   ebt: log support (NEW)

You may also need to install ebtables for your distribution. The userspace ebtables utility and 2.4 kernel patches are available at http://sf.net/projects/ebtables and from our Web site – www.gotroot.com.

Next we need to set up our firewall, in this case it’s named Minimoose (kudos to those of you who get this reference), to bridge traffic between our network, 10.10.10.0/24, and our gateway, 10.10.10.1. The goal is to put Minimoose between the network and the gateway device. We start this process by first configuring Minimoose’s interfaces to act as a bridge. This is accomplished by using the userspace tool, brctl, to set up the bridged interfaces and to “capture” them. In this hypothetical example, Minimoose has two interfaces. One is pointing at the gateway router, which has an IP address 10.10.10.1 and is reached via ethernet interface eth0. Minimoose’s other interface, eth1, is facing the actual 10.10.10.0/24 network. Remember, the bridge does not need any IP addresses. It’s going to “bridge” the traffic between these two points, allowing traffic to move from the 10.10.10.0/24 network to the gateway router, 10.10.10.1, and vice versa as defined by the firewall rules on Minimoose. The first step, as already explained, is to set up the interfaces on Minimoose and to configure it as a bridge:

1. Create the logical interface in the kernel, which is called br0.

[root@minimoose root]# brctl addbr br0

2. Add the left interface, eth0, that connects to the 10.10.10.1 gateway.

[root@minimoose root]# brctl addif br0 eth0

3. Add the right interface, eth1, that connects to the 10.10.10.0/24 network.

[root@minimoose root]# brctl addif br0 eth1

4. Activate the bridged interfaces by bringing up the two real interfaces.

[root@minimoose root]# ifconfig eth0 0.0.0.0 promisc up
[root@minimoose root]# ifconfig eth1 0.0.0.0 promisc up

At this point your bridge is working.

As you have probably surmised, Minimoose doesn’t even have an IP address for itself. Although it’s probably a good idea to add an IP address to one of those interfaces for management reasons, you don’t have to in most instances. For example, you could just as easily connect this device to a serial console, or add another interface and run an “Out of Band” network just for admining your stealth firewall, or something like that if you’re über paranoid.

Figure 2 shows our network, 10.10.10.0/ 24, before we put our firewall in place.

Figure 2

Now we put our firewall, Minimoose, in place as shown in Figure 3.

Figure 3

With traffic passing from 10.10.10.0/24 to the gateway through Minimoose, it’s time to do something interesting with the firewall. Listing 1 provides a simple example script that sets up the firewall rules and configures them to stealthily drop all SMB traffic moving between the gateway and the hosts on the 10.10.10.0/24 network. These rules also allow traffic to move in both directions, not just from the 10.10.10.0/24 network outward, but also from the gateway back into the 10.10.10.0/24 network. This listing will help illustrate the stealthy nature of this configuration; neither the hosts on the 10.10.10/24 network nor the gateway will “see” any changes in the network, except that SMB traffic is not flowing between the two.

In the previous example you can see that applying firewall rules to Layer 3 (IP) traffic works exactly the same as it does with a normal firewall, that is we need to apply those rules to the FORWARD table, and of course make sure you enable ip_forwarding on our firewall for this example to work:

echo 1 > /proc/sys/net/ipv4/ip_forward

Another application of a stealth firewall would be to act as a transparent proxy server. We frequently add squid to our firewalls for performance reasons and this next example shows how to configure the squid Web proxy cache server for your stealth firewall. The good news is that setting this up is easy; the bad news is that it requires adding an IP address to the stealth firewall and, because of this, your firewall will not be as stealthy as you might like, as Web requests will be seen as if they were coming from the bridge’s IP address and, of course, your bridge will now have an IP address. Keep in mind, this doesn’t mean that other traffic will appear to come from the bridge’s IP address or that you need to change any default routes on your network. The stealth firewall will just be seen as another node on your network, not as a router. The steps to set this up are:

1. Install squid and configure squid.conf to allow connections from localhost. This is typically the default configuration for squid. The steps to do this are beyond the scope of this article, but if you are having problems, please visit our Web site for documentation: www.gotroot.com.

2. Add an IP address to your bridge interface, if you haven’t already done so. In the commands that follow, replace the variable $MANAGEMENTIP with the IP address you intend to assign to your bridge, and the $MANAGEMENTGATEWAY variable with the gateway address for your network.

ifconfig br0 $MANAGEMENTIP
route add default gw $MANAGEMENTGATEWAY

3. Finally, add the following two rules to your firewall:

iptables -A INPUT -i <internal interface on bridge, such as eth1> -p tcp -d $MANAGEMENTIP -s
10.10.10.0/24 –dport 3128 -m state –state NEW,ESTABLISHED -j ACCEPT

iptables -t nat -A PREROUTING -i <internal interface on bridge, such as eth1> -s 10.10.10.0/24 -p
tcp –dport 80 -j REDIRECT –to-port 3128

Click this link to download complete Source Code

Your stealth firewall is now configured to grab all the port 80 traffic coming from our hypothetical stealth firewall’s internal network, 10.10.10.0/24. Redirect it to squid, and then allow squid to request and cache the documents. Again, all Web requests will now come from the bridge’s IP address.

Hopefully this brief introduction to stealth firewalls has encouraged you to think up your own ways to use them in your environment. Stealth firewalls are a fantastic and reliable tool for any network or security administrator. They’re easy to set up, can be more secure than classic IP firewalls, and because they require no routing and don’t have to be integrated into the network’s routing scheme, they are actually less of a risk to a network, from a point-of-failure perspective, than a traditional IP firewall.

As we already mentioned, if the stealth firewall fails, just run a patch cable around it. Of course, this eliminates your firewall and we don’t want that. The good news is that there’s an easy solution to that problem as well, and it allows you to create a fully automatic failover between two or more stealth firewalls. The better news is that this is already built into Linux and is very robust, but that discussion is for another time.

open source software

Infrarecorder

Great application, it is a very good alternative to Nero. Add files and burn!
Infrarecorder home site http://infrarecorder.org/.

7-zip

Great application, it is a very good alternative to Winzip.
7-zip home site http://www.7-zip.org/.

Bulk rename utility

This is a very cool application, it will let you rename filenames in bulk. DO NOT get discouraged by its complex look, it is very easy to use once you understand it. And it is very powerfull.
Bulk rename utility home site http://www.bulkrenameutility.co.uk/.

Daemon tools

Mount ISO files to a virtual CD/DVD.
Daemon tools home site http://www.daemon-tools.cc/eng/downloads.

WinSCP

A must have application to connect to remote FTP, sFTP or SCP. Will give a system wide file access through SSH.
WinSCP download page http://winscp.net/eng/download.php.

Gimp

Must have application for picture manipulations. It is a very good alternative to Photoshop.
Gimp home site http://www.gimp.org/.

Open Office

It is a very good alternative to Microsoft Office.
Open Office home site http://www.openoffice.org/.

Firefox

A must have alternative to Internet Explorer!
Firefox home site http://www.firefox.com/.

Irfanview

The best picture viewer.
Irfanview home site http://www.irfanview.ca/.

Jalbum

Create web photo album. The best.
Jalbum home site http://jalbum.net/.

PDF Creator

Create PDF Files.
PDF Creator download page on Source Forge http://sourceforge.net/projects/pdfcreator/.

Bytecount

Great application by Hans Nelisse to find directory tree size. Very very usefull.
Bytecount home site http://www.xs4all.nl/~hneel/software.htm.

uvnc

Must have application to remote control a computer.
Ultra VNC home site http://www.uvnc.com/.

UBCD – Ultimate boot cd

Must have boot cd/dvd.
UBCD home site http://www.ultimatebootcd.com/.

LC ISO Creator

A 14 kb ISO creator. Easy, fast, great application. This is another must have.
UBCD home site http://www.lucersoft.com/freeware.php.

Linkchecker

An easy to use, great web site link checker for Windows.
http://linkchecker.sourceforge.net/.

Disabling Mod_Security

    1 Disabling Mod_Security Globally
    2 Disabling Mod_security per domain
    3 Disabling Mod_security per domain for an IP address
    4 Disable Mod_security on a global URL
    5 Disable Mod_security for an IP address
    6 Whitelist an IP
    7 Disable a rule for a single domain
    8 Disable Mod_security rule for a specific application in a single domain
    9 Disable Mod_security rule for all domains
    10 Disable Mod_security rules globally for a specific application
    11 Disable Mod_security rules by domain, for a specific application, for a list of IPs
    12 Customizing a rule
    13 Configuring and Setting up mod_security

[edit] Disabling Mod_Security Globally

Step 1) Disable config file

mv /etc/httpd/conf.d/00_mod_security.conf /etc/httpd/conf.d/00_mod_security.conf.disabled

Step 2) Restart Apache

service httpd restart

[edit] Disabling Mod_security per domain

For Plesk and similar systems you can also disable modsecurity in the Apache configuration.

Step 1) Edit the vhost/vhost_ssl.conf for the domain

 vim /var/www/vhosts/<DOMAINNAME>/conf/vhost.conf

Step 2) Add the following

<IfModule mod_security2.c>
  SecRuleEngine Off
</IfModule>

Then restart apache, if you are using Plesk then you will also need follow steps 3 and 4.

Step 3) Add vhost.conf to domain config

/usr/local/psa/admin/bin/websrvmng -a

Step 4) Restart Apache

service httpd restart

[edit] Disabling Mod_security per domain for an IP address

For Plesk and similar systems you can also disable modsecurity in the Apache configuration.

Step 1) Edit the vhost/vhost_ssl.conf for the domain

 vim /var/www/vhosts/<DOMAINNAME>/conf/vhost.conf

Step 2) Add the following

<IfModule mod_security2.c>
 SecRule REMOTE_ADDR “^1.2.3.4$ “phase:1,t:none,nolog,allow,ctl:ruleEngine=Off,ctl:auditEngine=Off”
</IfModule>

Then restart apache, if you are using Plesk then you will also need follow steps 3 and 4.

Step 3) Add vhost.conf to domain config

/usr/local/psa/admin/bin/websrvmng -a

Step 4) Restart Apache

service httpd restart

[edit] Disable Mod_security on a global URL

Step 1) Create a global exclude file

vim /etc/httpd/modsecurity.d/00_custom_exclude.conf

Step 2) Add the LocationMatch for the url to exclude. Example: /server.php

<LocationMatch /server.php>
  <IfModule mod_security2.c>
    SecRuleEngine Off
  </IfModule>
</LocationMatch>

Step 3) Restart apache

service httpd restart

[edit] Disable Mod_security for an IP address

In ASL, just click the “Whitelist” button.

If you are not using ASL, simply add your IP address to the file:

/etc/asl/whitelist

And restart Apache.

Note: For this rule to work, in ASL you must have the MODSEC_00_WHITELIST ruleset enabled.

If you are not using ASL, then you must have the 00_asl_whitelist.conf ruleset loaded.

[edit] Whitelist an IP

See above, “Disable Mod_security for an IP address”
[edit] Disable a rule for a single domain

If you have ASL installed:

Method 1:

Log into the ASL GUI, and click on the “Configuration” tab. Then click “Rule Management”, then click the “Rules” tab, then click the “WAF” tab. Type in the rule ID and the rule manager will pull up the rule. Click on the green down error which will pull up the options for this rule.

Type in the vhost name into the Text box on the left side of the options, then click “add”.

Keep in mind this is literal, so if you have a vhost with the name “example.com” that serves content for “ftp.example.com” and “www.example.com” you will need to add those FQDNs as well.

Method 2: Run this command as root:

 asl -dr RULE_ID –vhost www.example.com

Replace RULE_ID with the ID of the rule you want to disable for the vhost. Keep in mind this is literal, so if you have a vhost with the name “example.com” that serves content for “ftp.example.com” and “www.example.com” you will need to add those as well. For example:

 asl -dr RULE_ID –vhost www.example.com

 asl -dr RULE_ID –vhost ftp.example.com

 asl -dr RULE_ID –vhost example.com

If you do not have ASL installed you will have to do this manually:

Step 1) Edit the vhost/vhost_ssl.conf for the domain

vim /var/www/vhosts/<DOMAINNAME>/conf/vhost.conf

Step 2) Add the LocationMatch for the rule to exclude. Example, ruleid 950005

<LocationMatch .*>
  <IfModule mod_security2.c>
    SecRuleRemoveById 950005
  </IfModule>
</LocationMatch>

If you want to disable multiple rules:

Step 2) Add the LocationMatch for the rule to exclude. Example, ruleids 950005 and 950006

<LocationMatch .*>
  <IfModule mod_security2.c>
    SecRuleRemoveById 950005
    SecRuleRemoveById 950006
  </IfModule>
</LocationMatch>

[edit] Disable Mod_security rule for a specific application in a single domain

Step 1) Edit the vhost/vhost_ssl.conf for the domain

vim /var/www/vhosts/<DOMAINNAME>/conf/vhost.conf

Step 2) Add the LocationMatch for the rule to exclude. Example, ruleid 950005

<LocationMatch /URL/path/to/application.php>
  <IfModule mod_security2.c>
    SecRuleRemoveById 950005
  </IfModule>
</LocationMatch>

[edit] Disable Mod_security rule for all domains

Method 1:

Log into the ASL GUI, and click on the “Configuration” tab. Then click “Rule Management”, then click the “Rules” tab, then click the “WAF” tab. Type in the rule ID and the rule manager will pull up the rule. Click on the green down error which will pull up the options for this rule.

Set “disabled” to yes and click update.

Method 2:

Use ASL utility to disable rule by ID. Example: 950005

asl –disable-rule 950005

Note: This requires that Atomic Secured Linux be installed. If you do not have Atomic Secured Linux installed you can disable a rule globally manually by adding a rule to your own custom rules files that contains a line similar to this:

<LocationMatch .*>
  <IfModule mod_security2.c>
    SecRuleRemoveById 340000
  </IfModule>
</LocationMatch>

Custom rules should be loaded after atomicorp rules. A good place to add this, again only if you do not have ASL installed, is in the 999_user_exclude.conf file. If you don’t have this file, just create it. Then make sure your modsecurity configuration is setup to load this file.
[edit] Disable Mod_security rules globally for a specific application

Add this to either you vhost.conf file, or if your want to make this global make sure this exclusion is loaded after your rules are loaded. A good place to add this in the 999_user_exclude.conf file. If you don’t have this file, just create it. Then make sure your modsecurity configuration is setup to load this file.

<LocationMatch /url/to/your/application>
  <IfModule mod_security2.c>
    SecRuleRemoveById 1234567
    SecRuleRemoveById 9999999
  </IfModule>
</LocationMatch>

Whats important to remember is that the LocationMatch variable must match the URL, not the path on the system.
[edit] Disable Mod_security rules by domain, for a specific application, for a list of IPs

Step 1) Edit the vhost/vhost_ssl.conf for the domain

vim /var/www/vhosts/<DOMAINNAME>/conf/vhost.conf

Step 2) Add the LocationMatch for the rule to exclude.

<LocationMatch /foo/bar.php>
  <IfModule mod_security2.c>
    SecRule REMOTE_ADDR “@pmFromFile /etc/asl/whitelist” “nolog,phase:1,allow”
  </IfModule>
</LocationMatch>

Step 3) Add IP to /etc/asl/whitelist

echo “10.11.12.13” >> /etc/asl/whitelist

Or:

If you want to create a special whitelist for just that application:

Step 1) Edit the vhost/vhost_ssl.conf for the domain

vim /var/www/vhosts/<DOMAINNAME>/conf/vhost.conf

Step 2) Add the LocationMatch for the rule to exclude.

<LocationMatch /foo/bar.php>
  <IfModule mod_security2.c>
    SecRule REMOTE_ADDR “@pmFromFile /path/to/your/custom/whitelist_for_this_application” “nolog,phase:1,allow”
  </IfModule>
</LocationMatch>

Step 3) Create your custom whitelist and add IP to /etc/asl/whitelist

echo “10.11.12.13” >> /path/to/your/custom/whitelist_for_this_application

Keep in mind these custom lists are *not* managed by ASL, so if you want to add IPs to these lists you will need to do it from the command line.
[edit] Customizing a rule

If you need to customize a rule do not change the asl*conf files. These files will be overwritten by updates. If you need to change a rule because it is incorrectly blocking something we recommend you report it to use as a False Postive, using the Reporting_False_Positives procedure. If you simply want to modify a rule to perform different actions, then copy the entire rule into your own rule file, and make sure you tell mod_security not to enable the original ASL rule. You can do that by using the mod_security action SecRuleRemoveById. Here is a simple example:

If you had an original rule like this:

 SecRule REQUEST_URI “/foo” “t:normalisePath,id:9000000,rev:1,severity:2,msg:’Atomicorp.com WAF Rules: Block /foo'”

And you want it to block “bar” instead of “foo”, then you would copy the entire rule into your own custom rule file. If you are using our rules we recommend you use the filename 99_asl_zzz_custom.confm and change the id: field to an unused ID.

 SecRuleRemoveById 9000000
 SecRule REQUEST_URI “/bar” “t:normalisePath,id:9999999,rev:1,severity:2,msg:’Atomicorp.com WAF Rules: Block /foo'”

These are the reserved ranges:

   *     1-99,999; reserved for local (internal) use. Use as you see fit but do not use this range for rules that are distributed to others.
   *     100,000-199,999; reserved for internal use of the engine, to assign to rules that do not have explicit IDs.
   *     200,000-299,999; reserved for rules published at modsecurity.org.
   *     300,000-399,999; reserved for rules published at gotroot.com.
   *     400,000-419,999; unused (available for reservation).
   *     420,000-429,999; reserved for ScallyWhack.
   *     430,000-699,999; unused (available for reservation).
   *     700,000-799,999; reserved for Ivan Ristic.
   *     900,000-999,999; reserved for the Core Rules project.
   *     1,000,000 and above; unused (available for reservation).

 

Apache ModSecurity – IP Whitelist
Add this rule to ModSecurity rules:

SecRule REMOTE_ADDR “^192\.168\.2\.15$” phase:1,nolog,allow,ctl:ruleEngine=off

It means the IP 192.168.2.15 will be ignored by ModSecurity.

Don’t forget to restart Apache after adding new rule.

Apache Minimal to Learn

APACHE :-

Apache is an open source web server which guarantees availability of active websites online . The original version of apache was especially designed for unix-like operating system Nowadays, it can be implemented on variety of O.S. platforms. According to Apache Software Foundation and Net craft web server survey, 65% of websites on the internet uses Apache server.

 Features of Apache :-

1) Modularity

2)Uniformity

3)Portability

4)Powerful and Flexible webserver

5)Easily operable on wide variety of OS Platforms.

which made possible technologies like apache modules an API for apache module enabling features such as PHP, Mysql integration, URL Rewrite, PHP Handlers, Global variables and other features.

Apache Web Server Versions :-

Apache 1.3 :-

-Useful configuration files.
-Windows and Netware support
-DSO Support
-APXS tool (Basically APXS is located at /usr/local/apache/bin/apxs  and the APXS is a tool used for building and installing extension modules for Apache HTTP Server).

Apache 2.0 :-

-Most comprehensive configuration files.
-Efficiency
-Supports IPV6 version.
-Unix Threading
-Introduced new compilation system and multi-langauge error messaging.

Apache 2.2 :-

-Offers more and new flexible modules.
-User Authentication and Proxy caching features.
-SQL Support
-Support files exceeding 2Gb.

————————————————————————————————————————–

You may felt boredom while reading below concept,  But its the core and most important functional body of Apache.

 MPM  :-

MPM stands for Multiple Processing Modules.  The main purpose of MPM  is binding network ports on machine, accepting request and dispatching children to handle the requets.

Apache implements specialized MPM. MPM must be choosen while configuring and must be compiled in the server. MPM behaves like Apache module, the basic difference is only one MPM must be loaded into the server at any time.

List of Apache MPM modules are available. Refer the link for the same :-

http://httpd.apache.org/docs/2.0/mod/

Some of the well know and widely implemented MPM’s :-

1) Prefork :-

“The prefork MPM runs multiple processes with each child process handling one connection”.

Merits :-

-Stable and Secure
-Compatible with all implementations (cgi, fcgi, suPHP, DSO).
-Failure of one process wont affect other connections.

De-Merits :-

-Simultaneous execution of multiple processes >> indicates more memory usage.

A typical configuration of the process controls in the Preform MPM could look as follows:

StartServers 8
MinSpareServers 5
MaxSpareServers 20
MaxClients 256
MaxRequestsPerChild 1000

More Information

2) Worker :-

“The worker MPM has one control process that launches multi-threaded child processes which handles one connection per thread”.

Merits :-

-Multi-threaded design utilizes less memory usage irrespective of high connections.
-Fast performance.

De-Merits :-

-DSO Module Incompatible.

A typical configuration of the process-thread controls in the Worker MPM could look as follows:

ServerLimit 16
StartServers 2
MaxClients 150
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25

More Information

3) Event :-

“The Event MPM is similar to worker MPM but allows high performance by passing some of the listener thread work  to each work processes. Each process can act as worker or listener depending on need and activity in CPU for respective time”.

Merits :-

-Better optimization.

De-Merits :-

-DSO Module Incompatible.

 A typical configuration of the process-thread controls in the Event MPM could look as follows:

KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 20

More Information

Distinguish between Perform, Worker, Event MPM’s

Configurations Definitions :-

* StartServers :- The number of  child processes created  on startup.

*MinSpareServers : Minimum number of idle child processes. apache will continue to create new processes. This should be high enough, idle processes should be on hand.

*MaxSpaceServers : Max number of idle child process, parent process will kill idle process in excess of limit.

*MaxClients : Max number of simultaneous request i.e Max number of Apache requests.

*MaxRequestsPerChild : Max number of request a child process will handle before it dies. if set to 0 ; process will never die

*ServerLimit : Max number of child process, must be greater on equal to maxclient divided by thread per child.

*ThreadsPerChild : No. of threads per child process.

*MaxSpareThread : Min no.of idle thread.

*KeepAlive ; allows for persistent connection to improve latency for connections that require multiple requests.

*KeepAliveTimeout :  Length of time connection will be kept open for further request before closing.

*MaxKeepAliveRequests : Max no. of requests through a single keep alive connection.

Mod_Deflate
Mod_Deflate :-

mod_deflate is an module of an Apache HTTP Web Server. The basic purpose of mod_deflate is to speedup download web page access time. It provides DEFLATE output filter that allows output from webserver to webbrowser in the form of compression format.

It results in faster website access and decreases the amount of time in data transmission from web server to web browser.

mod_gzip or mod_gz modules are similar to mod_deflate which compresses the contents using different implementations like gzip implementations and external zlib library respectively.

You can check the gzip compression for website using below link :-

http://aruljohn.com/gziptest.php

How to Enable Mod_Deflate :-

1) # /scripts/easyapache

2) Adding the code under .htaccess file

<IfModule mod_deflate.c>
    AddOutPutFilterByType DEFLATE text/html text/plain text/xml
    <IfModule mod_setenvif.c>
        # Netscape 4.x has some problems…
        BrowserMatch ^Mozilla/4 gzip-only-text/html
        # Netscape 4.06-4.08 have some more problems
        BrowserMatch ^Mozilla/4\.0[678] no-gzip
        # MSIE masquerades as Netscape, but it is fine
        # BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
        # NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
        # the above regex won’t work. You can use the following
        # workaround to get the desired effect:
        BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
        # Don’t compress images
        SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
    </IfModule>
    <IfModule mod_headers.c>
        # Make sure proxies don’t deliver the wrong content
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
</IfModule>

3) Append below code under httpd.conf

LoadModule deflate_module modules/mod_deflate.so

Append following configuration <Location /> directive:

<Location />
AddOutputFilterByType DEFLATE text/html text/plain text/xml
….

<Location>

Above line only compress html and xml files. Here is the configuration from one of my production box:
<Location />


AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/atom_xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE application/x-httpd-eruby
AddOutputFilterByType DEFLATE text/html


<Location>
Close and save the file. Next restart apache web server. All of the above extension file should compressed by mod_deflate:

# /etc/init.d/httpd restart

More Information

Zip files corrupt when downloaded via IE but not via FF.
  Firefox would download the zip and it was fine, but the file was coming through corrupt when downloading via Internet Explorer. This is a result of IE not handling gzip encoded files properly.

RLimits

RLimits
Resource limits, or RLimits, are sometimes appropriate on older hardware, or if a customer requests them specifically. It can only be set on  VPS/Dedicated servers.

RLimits can be added to :-
 
# /usr/local/apache/conf/include/pre_main_global.conf

The most common entries are: Limits memory usage to 100MB. (note: will not work on VZ VPS)

RLimitMEM 104857600 104857600

Limits CPU usage.

RLimitCPU 150 200

Limits Number of processes per user (This is what regulates the process limits on shared servers).

RLimitNPROC 25 30

Mod_Expires/_Cache/_PageSpeed/_Bandwidth/_

Mod_Expires
The mod_expires module allows Cache-Control and expires headers to be added to a site without any changes to the existing site code. You can determine if a site is already providing cache headers by checking the current site headers: No caching headers:

~ $ curl -I http://www.hostgator.com
HTTP/1.1 200 OK
Date: Wed, 22 Sep 2010 20:30:25 GMT
Server: Apache/2.2.3 (CentOS)
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8

Cloudflare’s caching headers:
HTML:
HTTP/1.1 200 OK
Server: cloudflare-nginx
Date: Wed, 22 Sep 2010 20:19:51 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
ETag: “a568013-14dd2-490de3c42e8c0”
Accept-Ranges: bytes
Cache-Control: max-age=300, must-revalidate
Expires: Wed, 22 Sep 2010 20:24:48 GMT

Image:
HTTP/1.1 200 OK
Server: cloudflare-nginx
Date: Wed, 22 Sep 2010 20:19:56 GMT
Content-Type: image/jpeg
Connection: keep-alive
Last-Modified: Tue, 03 Aug 2010 03:10:53 GMT
ETag: “a5683b0-10558-48ce2aa35e940”
Accept-Ranges: bytes
Content-Length: 66904
Expires: Wed, 22 Sep 2010 22:19:56 GMT
Cache-Control: max-age=7200

Note how the image is being cached for 2 hours while the html is only being cached for 5 minutes. You can reproduce those settings with the following .htaccess rules.

<filesmatch “\.(flv|gif|ico|jpg|jpeg|png|swf)$”>
    header set Cache-Control “max-age=2592000”
</filesmatch>
<filesmatch “\.(css|js|pdf|txt)$”>
    header set Cache-Control “max-age=604800”
</filesmatch>
<filesmatch “\.(html|htm)$”>
    header set Cache-Control “max-age=43200”
</filesmatch>
<filesmatch “\.(cgi|fcgi|php|pl|scgi|spl)$”>
    header unset Cache-Control
    <ifmodule mod_expires.c>
        expiresactive off
    </ifmodule>
</filesmatch>
<ifmodule mod_expires.c>
    expiresdefault “access plus 1 year”
</ifmodule>

Mod_Cache and Mod_Pagespeed

mod_pagespeed
mod_pagespeed is an Apache module that adjusts html output to help the page render faster in the clients browser and performs some caching for the output as well. Some of the more common tasks would be removing whitespaces between html code, unifying CSS and java scripts into one file, gziping and rearranging the html on the page.

Install script:

GET http://hgfix.net/heckel/install-pagespeed | bash

Mod_Bandwidth :-

“Mod_bandwidth” is a module for the Apache HTTP webserver that enable the setting of server-wide or per connection bandwidth limits, based on the directory, size of files and remote IP/domain.

You can find the specific file types affected and other configuration settings in the “/usr/local/apache/conf/includes/mod_bandwidth.conf” file.

Mod Security
mod_sec is the important module of an Apache web Server which is concerned with security. Shared/reseller servers run mod_security. mod_security is a real-time, application layer, web-application firewall that runs as an apache module.

 The mod_security system watches each connection and looks for suspicious use/access based on defined rule sets. When a connection matches a rule set, the connection is blocked with an error (almost always a 403 (forbidden) error). Unfortunately, mod_security – by its very nature – has to be strict. This means that occasionally, a customer’s legitimate script use will be caught by mod_security. In those instances, we will have to white list the rules being hit in order for the script to continue to function.

Step 1: Determine which rule to whitelist. First, you must tail the apache error_log and determine which mod_security rule(s) need to be whitelisted. The easiest way to do this is with the command:

tail -f /usr/local/apache/logs/error_log | grep ‘216.110.94.228’

Once you have that running, reload the page. You will see something similar to the following appear:
[Mon Feb 15 20:59:28 2010] [error] [client 216.110.94.227] ModSecurity: Access denied with code 403 (phase 2). Pattern match “(?:http|https|ftp):/” at REQUEST_URI. [file “/opt/mod_security/98_asl_jitp.conf”] [line “881”] [id “1234234”] [rev “1”] [msg “JITP:1234234”] [severity “CRITICAL”] [hostname “www.hilili.com”] [uri “/tgp/st/st.php”] [unique_id “S3oKEK546YIAABcnxBAAAABK”]

Step 2: Determine the rule # being hit and white list Find the rule number, which would be the ID. In this case, the ID is highlighted, above. 1234234. Once you find the ID/rule, you will whitelist with the command: wlmodsec domain.tld rule# y/n In this case, you would use: wlmodsec hilili.com 1234234 y The y/n allows you to choose whether or not to automatically restart apache after the rule is whitelisted. This way, if you are whitelisting several domains (say a customer requests all of their domains be whitelisted against a specific rule), you can run it in a loop without having to restart after each whitelist. A loop would look similar to the following:

while read -r DOMS; do wlmodsec $DOMS 1234234 n; done < domain-list

After which, you would restart apache, manually.

Step 3: Repeat until all rules are found/whitelisted. You’ve found on rule. Where one rule is hit, invariably there are more. Go back to step 1, and repeat until you can reload the page (or repeat the process) without triggering an error. Whitelist each rule that you trigger. It is also possible to disable mod_security, completely, for a domain; however, we do not recommend this. If a customer is wishing to do this, it must be handled by an upper tier administrator It you need to manually edit the rules they are in

/opt/mod_security/whitelist.conf

Example (need to replace domain.com and ruleid):

SecRule SERVER_NAME “domain.com” phase:1,nolog,pass,ctl:ruleRemoveByID=ruleid
Example whitelisting a rule affecting a temporary url (replace username and ruleid):
SecRule REQUEST_URI “~username” phase:1,nolog,pass,ctl:ruleRemoveByID=ruleid Error
Message: ModSecurity: Unable to retrieve collection (name “global”, key “global”).
Use SecDataDir  to define data directory first. mkdir -p /var/asl

mkdir -p /var/asl/data/
mkdir -p /var/asl/data/msa
mkdir -p /var/asl/data/audit
mkdir -p /var/asl/data/suspicious
chown nobody.nobody /var/asl/data/msa
chown nobody.nobody /var/asl/data/audit
chown nobody.nobody /var/asl/data/suspicious
chmod o-rx -R /var/asl/data/*
chmod ug+rwx -R /var/asl/data/*

Then we need to add following lines to /usr/local/apache/conf/modsec2.user.conf

SecUploadDir /var/asl/data/suspicious
SecDataDir /var/asl/data/msa
SecTmpDir /tmp
SecAuditLogStorageDir /var/asl/data/audit Error Message: Rule execution error – PCRE limits exceeded (-8): (null). Add this to php.ini:
pcre.backtrack_limit = 50000
pcre.recursion_limit = 50000 Add this to modsec2.user.conf

SecPcreMatchLimit 50000
SecPcreMatchLimitRecursion 5000

 

htaccess-examples

I was testing authentication against Active Directory (LDAP) using Apache 2. The following worked for me in a .htaccess file but only after adding:

    LDAPVerifyServerCert Off

in the main httpd.conf file. I presume this is related to the server name in the SSL certificate on the Active Directory server.

    AuthBasicProvider ldap
    AuthzLDAPAuthoritative Off
    AuthLDAPURL ldaps://adserver.prefix.tld.co.uk:636/DC=prefix,DC=tld,DC=co,DC=uk?sAMAccountName?sub?(objectClass=user)
    AuthLDAPBindDN “CN=someuser,OU=some ou,OU=another unit,OU=department,OU=directorate,OU=Administration,OU=another big unit,DC=prefix,DC=tld,DC=co,DC=uk”
    AuthLDAPBindPassword secret
    AuthType Basic
    AuthName “Protected”
    require valid-user

Normal users should then be prompted for a username and password to access the directory and if correct credentials are supplied should be given access to the content.

redirecting-mobile-web-users

Apache Mod_Rewrite

    RewriteEngine On
    #redirect mobile browser using HTTP_ACCEPT header
    RewriteCond %{HTTP_ACCEPT} “text/vnd.wap.wml|application/vnd.wap.xhtml+xml” [NC]
    RewriteCond %{HTTP_HOST} “!m.yourmobileurl.com” [NC]
    RewriteRule (.*) http://m.yourmobileurl.com/$1 [L]
    #some high-end phone sometimes support HTML, only its sucks
    #add more browser user agent sig here
    RewriteCond %{HTTP_USER_AGENT} (nokia|symbian|iphone|blackberry) [NC]
    RewriteCond %{HTTP_HOST} “!m.yourmobileurl.com” [NC]
    RewriteRule (.*) http://m.yourmobileurl.com/$1 [L]

2. Wurfl and PHP API

3. Apache Mobile Filter

htaccess-examples

examples

Temporarily take site down for maintenance

    Options +FollowSymlinks
    RewriteEngine on
    RewriteCond %{REMOTE_ADDR} !^111\.111\.222\.111
    RewriteCond %{REQUEST_URI} !/index.html$
    RewriteRule $ /index.html [R=302,L

or

    Options +FollowSymlinks
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/oldsite/
    RewriteCond %{REMOTE_HOST} !^123\.111\.123\.111
    RewriteRule (.*) http://www.thedomain.com/oldsite/$1 [R=301,L]

 

Redirecting to a New Domain

    Options +FollowSymLinks
    RewriteEngine on
    RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

Force https use

    RewriteEngine On
    RewriteCond %{SERVER_PORT} !443
    RewriteRule (.*) https://www.thedomain.com/ [R]

or

    RewriteEngine On
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Use a Custom Error Document

    ErrorDocument 404 /mynotfound.html

Allowing access only from internal network

    order deny,allow
    allow from 123.123.
    deny from all

Password protecting a directory with htaccess and htpasswd
Enter the following into the .htaccess file:

    AuthUserFile /path/to/.htpasswd
    AuthName “Restricted Area”
    AuthType Basic
    Require valid-user

And then create the .htpasswd file with the following:

    /usr/local/apache/bin/htpasswd -c .htpasswd theusername

There are also online tools for creating the paswords e.g.:
http://www.htaccesstools.com/htpasswd-generator/
Redirect old address to new domain
Example http://www.domain.co.uk/mysite to http://www.mysite.com

    Options +FollowSymLinks
    RewriteEngine on
    RewriteBase /
    RewriteCond %{HTTP_HOST} ^www.domain.co.uk [NC]
    RewriteRule ^(.*)$ http://www.mysite.com/$1 [L,R=301]

Allowing Directory Browsing in single directories with .htaccess
Having a directory full of downloadable files can be useful and although it is generally accepted that allowing directory browsing from within the Apache configuration file might be a bit of a security issue, directory browsing for single directories can be useful and can be achieved using the following in a .htaccess file:

    Options +Indexes
    DirectoryIndex nonexistantfile.html nonexistantfile.htm

The reason why I have specified the DirectoryIndex as nonexistantfile.html is to ensure that if someone (or script) accidentally copies an index.html file into the directory that it won’t be used and instead the contents of the directory will be listed/browsable. Some Content Management Systems will copy new index.html files into directories even if you don’t want them 😉

.htaccess URL Rewriting
The following tool is useful for generating Rewrite Rules for SEO friendly URL’s in an Apache .htaccess file.
http://www.linkvendor.com/seo-tools/url-rewrite.html

.htaccess referers
I recently needed an intranet website to be protected so that only authorised users could get access to it. Since there is already a part of the website which requires a login and authentication to a directory I had a link placed on this page. The .htaccess file needed to accept referers only from the domain of the authenticated site. Since this new site was a single html page with hundreds of links to PDF files I also needed to add a referer for the HTML page that contained the links. Clear as mud? Yes. OK an example. The following code will not allow connections directly to www.theseconddomain.com .
www.theseconddomain.com can only be accessed by clicking a link on www.thefirstdomain.co.uk that points to www.theseconddomain.com

    SetEnvIfNoCase Referer www\.thefirstdomain\.co\.uk good_referer=1
    SetEnvIfNoCase Referer www\.theseconddomain\.com/index.html good_referer=1
    order allow,deny
    allow from env=good_referer
    ErrorDocument 403 http://www.thefirstdomain.co.uk/error.htm

Apache Authentication with Active Directory (LDAP)
Good article about this here.

A .htaccess file can be used to protect a directory on an Apache2 server. The code to use is:

    AuthType Basic
    AuthBasicProvider ldap
    AuthUserFile /dev/null
    AuthName “Test LDAP”
    AuthLDAPURL “ldap://xxxx.ads.tla.co.uk:389/OU=Staff,OU=ORG,dc=ads,dc=tla,dc=co,dc=uk?sAMAccountName?sub?(objectClass=*)”
    AuthLDAPBindDN CN=FullDNtoADuser,DC=tld,DC=co,DC=uk
    AuthLDAPBindPassword myADpassword
    AuthLDAPGroupAttributeIsDN on
    require valid-user

The values need to be changed to reflect the Active Directory structure. The most important line appears to be AuthLDAURL which is the LDAP search.

To use Exchange it may be possible to use:

    AuthLDAPURL “ldap://ldap.yourdomain.com:389/cn=Recipients,ou=ServerName,o=DomainName?uid?sub?(objectClass=*)“