Step by step instructions for setting up fail2ban for sendmail.

Create the filter

First, create a filter file for sendmail, typically filter.d/sendmail.conf, with the following content:

# Fail2Ban configuration file
# Source:
# Contibutors: Gutza, the SASL regex
# $Revision: 0 $


# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>\S+)
# Values:  TEXT

failregex = \[<HOST>\] .*to MTA
#            \[<HOST>\] \(may be forged\)
            \[<HOST>\], reject.*\.\.\. Relaying denied
            (User unknown)\n* \[<HOST>\]
            badlogin: .* \[<HOST>\] plaintext .* SASL

# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
ignoreregex =

You may enable the “(may be forged)” line by uncommenting it (remove the hash symbol at the beginning of the line). Observe caution about that particular regular expression, because it might cause bans on legitimate users.

Define the jail

Now you need to tell fail2ban what to do with this filter. Edit jail.conf and add the following section:

enabled  = true
filter   = sendmail
action   = iptables-multiport[name=sendmail, port="pop3,imap,smtp,pop3s,imaps,smtps", protocol=tcp]
logpath  = /var/log/maillog

Don’t forget to change with your e-mail address.

Posted in Linux How-To | Leave a comment

Netstat: Linux network information

If you use Linux (especially on a server) it is important to be able to have plenty of information at the tips of your fingers. This includes all types of information. One of the first places to look for for information is /var/log, however that can be cumbersome and doesn’t always give you the specific networking information you need.

There is one tool that is ready to hand you much of the networking information you will need from your server. That tool? Netstat. The netstat tool prints out (on the command line) information about the Linux networking subsystem. With this tool you can get valuable information about: Open sockets, routing tables,  multicast group membership, network interfaces, masqueraded connections, and protocol statistics. Each type of information can also be narrowed with the help of options.

In this article you will learn how to be able to make use of the netstat tool, so you can have as much networking information as you need at your fingertips.

Basic structure

The basic netstat command looks like:


Where ARGUMENT is the type of address family you want information about and OPTIONS is the optional option(s) that will specify the type of information you get returned.

Now let’s break this command down into address families.

Open Sockets

This is the easiest way to use netstat. If you issue the command without any arguments you will get a list of all sockets that are currently listening on a system. The output would look something like:

Proto RefCnt Flags Type       State         I-Node   Path
unix  3      [ ]   STREAM     CONNECTED     205824   /tmp/.X11-unix/X0
unix  3      [ ]   STREAM     CONNECTED     205823
unix  3      [ ]   STREAM     CONNECTED     203856   /tmp/.X11-unix/X0
unix  3      [ ]   STREAM     CONNECTED     203855

As you can see, from the output above, the information isn’t terribly useful. We can make it much more useful with a few options. What we want to do is tell netstat to give us output for specific applications that are listening for tcp connections. To do this we issue the command:

netstat –tcp –listening –programs

The output for this command would look something like:

Proto Recv-Q Send-Q Local Address Foreign Address Stat    PID/Program
tcp   0      0      *:ssh         *:*             LISTEN  25469/sshd
tcp   0      0      *:httpd       *:*             LISTEN  26754/httpd
tcp   0      0      localhost:ipp *:*             LISTEN  -

Now you can actually see some useful information. In the above output you can see that both sshd and httpd are listening for incoming connections. The above is just a snippet of what the output can look like. What is very handy about this command is it will show you if there is a command or local address listening for incoming connections that shouldn’t be listening. If you find an application that shouldn’t be listening, kill it to be safe.

Netstat is able to quickly print your machines’ kernel routing table with the command:

netstat -r

The output of this command will look like:

Kernel IP routing table
Destination  Gateway     Genmask         Flags   MSS Window  irtt Iface  *    U       0 0         0    eth0
default         UG      0 0         0    eth0


This is one of the handier of the netstat tools. With this you can find out exactly the statics for each protocol. The basic command structure is:

netstat –statistics

which will give you far more information than you want. Say, you only want to see statistics on the TCP protocol. For this you can issue the command:

netstat -t –statistics

The output to the above command will include information such as:

4343 active connections openings
8 passive connection openings
5 failed connection attempts
178 connection resets received
6 connections established
59075 segments received
60033 segments send out
76 segments retransmited
0 bad segments received.
303 resets sent

Or you could get information on UDP as well with the command:

netstat -u –statistics

Which would give you similar output for the UDP protocol.

Get creative

What if you wanted to see all unique IP addresses connected to a server? You can do that with netstat (and the help of a few other tools) like so:

netstat -nat | awk '{ print $5}' | cut -d: -f1 | sed -e '/^$/d' | uniq

The output of the above command would depend upon how much traffic your machine/server is getting. But it will include all unique IP addresses attempting to connect to your server.

What about checking to see if your server is under a DOS attack? You can do that with netstat like this:
netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

The above command will list out the IP addresses requesting the highest amount of connections to your server. If you see a number that is far higher than it should be, you most likely are under a Denial of Service attack.



Posted in Linux How-To | Leave a comment

Fail2Ban setup


Fail2Ban is an intrusion prevention framework written in the Python programming language. It works by reading SSH, ProFTP, Apache logs etc.. and uses iptables profiles to block brute-force attempts.


To install fail2ban, type the following in the terminal:

sudo apt-get install fail2ban


To configure fail2ban, make a ‘local’ copy the jail.conf file in /etc/fail2ban

cd /etc/fail2ban
sudo cp jail.conf jail.local

Now edit the file:

sudo nano jail.local

Set the IPs you want fail2ban to ignore, the ban time (in seconds) and maximum number of user attempts to your liking:

# "ignoreip" can be an IP address, a CIDR mask or a DNS host
ignoreip =
bantime  = 3600
maxretry = 3

Email Notification

Note: You will need sendmail or any other MTA to do this.

If you wish to be notified of bans by email, modify this line with your email address:

destemail =

Then find the line:

action = %(action_)s

and change it to

action = %(action_mw)s

Jail Configuration

Jails are the rules which fail2ban apply to a given application/log:


enabled = true
port    = ssh
filter  = sshd
logpath  = /var/log/auth.log
maxretry = 3

To enable the other profiles, such as [ssh-ddos], make sure the first line beneath it reads:

enabled = true

Once done, restart fail2ban to put those settings into effect

sudo /etc/init.d/fail2ban restart

Advanced: Filters

If you wish to tweak or add log filters, you can find them in



To test fail2ban, look at iptable rules:

sudo iptables -L

Attempt to login to a service that fail2ban is monitoring (preferably from another machine) and look at the iptable rules again to see if that IP source gets added.

Posted in Linux How-To | Leave a comment

Replacing smart quotes, em-dashes, and ellipses with MySQL or PHP

The “Smart quotes” feature in Microsoft Office transforms straight quotes into curly quotes.  It also transforms hyphens into em-dashes and three periods into ellipses.  While one might think, “How lovely!  My document looks almost as if I’m educated!” readers of said document may not.  Microsoft, in its infinite wisdom, decided to assign special characters such as the ones we just mentioned to a range of codes above 128.  Problem: these codes aren’t compatible with other character sets such as ISO-8859-1 or UTF-8, resulting in frustrating issues with non-Microsoft systems.

Keep reading for some PHP and MySQL code to help out with this issue.

Our introduction to this was in a situation where we had people using many different systems submitting articles to one of our programs.  We decided that we wanted all our articles to use straight quotes, hyphens, and periods.  This was partly for consistency, and partly because these characters are common to many character sets and won’t cause incompatibilities.  Should your requirements be different, it should be trivial to modify the code below to fit your specific situation.

Here are some MySQL and PHP techniques for replacing all instances of smart quotes, plus the en dash, em dash, and ellipsis with straight quotes, one or two dashes, or three dots.  This code should operate with both the Windows-1252 charset, and also UTF-8, an extended character set that is in many situations the “best” character set to use for email and websites.


# FIRST, REPLACE UTF-8 characters.
UPDATE `t` SET `c` = REPLACE(`c`, 0xE28098, "'");
UPDATE `t` SET `c` = REPLACE(`c`, 0xE28099, "'");
UPDATE `t` SET `c` = REPLACE(`c`, 0xE2809C, '"');
UPDATE `t` SET `c` = REPLACE(`c`, 0xE2809D, '"');
UPDATE `t` SET `c` = REPLACE(`c`, 0xE28093, '-');
UPDATE `t` SET `c` = REPLACE(`c`, 0xE28094, '--');
UPDATE `t` SET `c` = REPLACE(`c`, 0xE280A6, '...');
# NEXT, REPLACE their Windows-1252 equivalents.
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(145), "'");
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(146), "'");
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(147), '"');
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(148), '"');
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(150), '-');
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(151), '--');
UPDATE `t` SET `c` = REPLACE(`c`, CHAR(133), '...');


// First, replace UTF-8 characters.
$text = str_replace(
 array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6"),
 array("'", "'", '"', '"', '-', '--', '...'),
// Next, replace their Windows-1252 equivalents.
 $text = str_replace(
 array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
 array("'", "'", '"', '"', '-', '--', '...'),

Additionally, here’s a table of character codes that you may find useful:
Windows-1252 characters not present in ISO-8859-1

Further reading from Wikipedia:

ISO/IEC 8859-1


Maybe you need a greater range of characters than is available in ISO/IEC 8859-1?  You should use UTF-8 instead:
PHP UTF-8 Cheatsheet

Posted in Linux How-To | Leave a comment

Find out What Perl Modules Already Installed On My System

What command I need to type to list all installed Perl modules on my Linux / UNIX system?

You need to use instmodsh (interactive inventory for installed Perl modules) command to find out what modules already installed on my system. instmodsh command provides an interactive shell type interface to query details of locally installed Perl modules. It is a little interface to ExtUtils::Installed to examine locally* installed modules, validate your packlists and even create a tarball from an installed module.

Task: List installed perl module

To display the list enter the following command:
$ instmodsh
Sample outputs:

Available commands are:
l            - List all installed modules
m    - Select a module
q            - Quit the program

At cmd? prompt type l to list all installed modules:
cmd? l
Sample outputs:

Installed modules are:

This command itself is a perl script that use ExtUtils::Installed module. Try following command to see its source code:
$ vi $(which instmodsh)

Posted in Linux How-To | Leave a comment

Setting Up a FreeBSD Router, Step-by-Step

rl0 – NIC facing the network
xl0 – NIC facing the network
xl1 – NIC facing the modem
tun0 – The virtual NIC used by PPP, facing the outside


  1. Install FreeBSD
  2. Enable the rl0 network card and give it an address by adding the following line to /etc/rc.conf
    this is a temporary address, and we’re doing this so we can log into the computer via SSH for convenience.

    ifconifg_rl0="inet netmask"
  3. Enable the xl0 network card and give it an address by adding the following line to /etc/rc.conf
    ifconifg_xl0="inet netmask"
  4. Set the defaultrouter in /etc/rc.conf to the address of the existing router:
  5. Set the nameserver in resolv.conf to the address of the exisitng name server:
  6. In /etc/rc.conf enable the gateway function of FreeBSD by adding this line:


  1. Making FreeBSD load the IPNAT kernel module on bootup is easy, simply add this line to rc.conf:
  2. Create the IPNAT configuration file /etc/ipnat.rules
  3. Add the two lines in /etc/ipnat.rules that are for outgoing connections:
    map tun0 -> portmap tcp/udp 40000:65000
    map tun0 ->
  4. Add any redirection lines you may want. They take the following form:

    An example, used for a webserver:

    rdr tun0 port 80 -> port 80
  5. After every time you alter the /etc/ipnat.rules file and want the changes to take effect, use the following commands:

    To clear the current settings:

    #ipnat -C

    To load the new settings:

    #ipnat -f /etc/ipnat.rules

    To view the current settings:

    #ipnat -l


  1. Grab and decompress the ports tree:
    #cd /usr
    #tar xvfz ports.tar.gz
  2. rc.subr capability is needed for ISC DCHP server, so install it from the ports:
    #cd /usr/ports/sysutils/rc_subr
    #make install clean
  3. Install ISC DHCPD from the ports:
    #cd /usr/ports/net/isc-dhcp3-server
    #make install clean
  4. Configure DHCPD:
    edit /usr/local/etc/dhcpd.conf so it looks like the following:

    #ee /usr/local/etc/dhcpd.conf
    option domain-name "";
    option domain-name-servers;	#a valid DNS server, given by your ISP
    option subnet-mask;
    default-lease-time 86400;
    max-lease-time 86400;
    ddns-update-style none;
    subnet netmask {
      range;	#the range of IPs you want it to give out
      option routers;
  5. To make DHCPD start on boot add the following line to /etc/rc.conf:


  1. Configure DNS forwarding:
    edit the file /etc/namedb/named.conf:

    #ee /etc/namedb/named.conf

    uncomment where it says “forward only” and “forwarders” and place one of your ISP’s DNS servers between the forwarders brackets.

  2. To make the name server start at boot add the following line to /etc/rc.conf:


  1. PPPoE’s configuration file is /etc/ppp/ppp.conf, edit it:
    #ee /etc/ppp/ppp.conf
     set device PPPoE:xl1  #xl1 is the NIC the modem is connected to
     set speed sync
     set mru 1492
     set mtu 1492
     set ctsrts off
     enable lqr
     set log phase tun
     add default HISADDR #grabs the ISP's gateway's address and makes it your defaultrouter
     nat enable no
     set authname USERNAME  #Replace USERNAME with your ISP login name
     set authkey PASSWORD   #Replace PASSWORD with your ISP login password
  2. Run PPP manually if you want to test it out:

    the commands form is /usr/sbin/ppp -MODE -PROFILE, in our case, we want it to run in the background and use the profile ‘att’, which we defined in the config file.

    #/usr/sbin/ppp -background att
  3. Making it so that PPP runs on boot:
    add the following lines to /etc/rc.conf:

    ppp_enable="YES"	#so that PPP starts
    ppp_nat="NO"		#IPNAT does our NAT, so we don't want this
    ppp_profile="att"	#use the 'att' profile
    ppp_mode="ddial"	#this mode makes ppp reconnect when disconnected


  1. Change the address of the interface facing the internal network
    #ifconfig rl0 inet netmask
    #ee /etc/rc.conf
    ifconifg_rl0="inet netmask"
  2. Comment out or delete the defaultrouter”″ line in /etc/rc.conf
  3. Put the address of your ISP’s DNS server(s) in /etc/resolv.conf
  4. Hook it up!
Posted in Linux How-To, Networking | Leave a comment

Darwin Boot Options

When you boot your hackintosh you can press “F8” before you see the gray apple boot screen. then you should see a menu with all the partitions you have, at this time you may choose between the partitions using up/down arrows (it defines what partition to load from). Another thing you can do at this boot prompt is to specify boot options.

note that the last line says: “boot:” this is your prompt, you may write one of the next options:
[Kernel Name]
[Kernel Flags]
[Boot Flags]
  “Graphics Mode”=
[UnKnown flags]

Kernel Name this boot option state what kernel to use in order to load the system, for instance you may use mach_kernel or any other kernel you downloaded and want to try (new EFI supporting kernel or new version of kernel), the kernel must be in folder “/”
Kernel Flags you can enter kernel flags that should be used during this boot time, kernel flags examples: debug=0x144 io=0xffffffff (not so sure what these guys do, but read more on kernel)
-s mean you would like to enter “Single User” mode which doesn’t load GUI and doesn’t mount partitions but gives you a prompt so you can make system maintenance and recovery procedures.
-v loads the system in Verbose mode which display allot of log lines during boot time and does not display the apple gray boot screen, it is good to use this option if things go wrong, or if you get an error screen and you want to know the reason.
-f tells the hackintosh to reload all kext (Kernel Extensions = drivers) and dump the cache, not rely on it (kext cache found in: /System/Library/Extensions.mkext, you can delete it manually and the system will recreate it)
the kext cache is built of the necessary kext that needs to be loaded and it will be created whenever it does not exist.
you can use a command line utility (from terminal) named: “mkextunpack” to extract the content and see what kext are cached for example the command:
mkextunpack -d /111 /System/Library/Extensions.mkext
will extract the content to a folder (that must exist before runing this command) /111
you can also use the command line utility “kextcache” to create or update kextcache.
-x this option boot the system into safe mode ignoring kext cache and loads only necessary kext
cpus= this parameter tells the hackintosh how many cpus to use, for instance if you have dual CPU or dual Core then you can state cpus=2, so the system will use both cpus, and if you get reboot without loading GUI or boot screen then you may use cpus=1 to allow use of one cpu and avoid reboot
“Graphics Mode”= this parameter tells the hackintosh to use stated graphics resolution and color depth, the pattern to use is: WidthxHeightxDepth@RefreshRate for instance a resolution of 640×480 with 32 bit color depth and 60 hertz frequancy refresh rate will look like this:
“Graphics Mode”=”640x480x32@60″
rd= this parameter state what is the boot disk to use (instead of using the boot menu appearing before the prompt) you state the drive and partition in the pattern: diskXsY where X stands for the disk number (first disk (usually primary master in IDE) 0 second disk is 1 etc.) and Y stands for the partition on that disk starting with 1 as the first partition, so if you have one disk and one partition the parameter will look like this: rd=disk0s1
config= this parameter tells the system to load using different copy of the boot config file, the default copy used is kept in:
the content of this file state boot options such as:
timeout (how much time to wait for user selection in boot prompt)
kernel (what kernel to use)
kernel flags (what kernel flags to use in each and every boot)
quiet boot (weather to display boot menu or not)
boot graphics (if to boot with apple spinning circle)
platform= this parameter sets the platform to use at this boot time, you may use:
platform=ACPI (ACPI support)
platform=X86PC (non ACPI support)
platform=ACPI|86PC (try to support ACPI if fails do not support it)
idlehalt gets two values ether 1 or 0 stating true or false, if set to true then at idle time the cpu will halt causing power saving and cooling of CPU, if set to 0 then the cpu will allways run even in idle time.
-legacy causes the system to load in 32 bit mode while running on 64 bit systems
?memory this info screen display information about the memory on the machine
?video this info screen display information about the video card supported graphic modes
Posted in OSx86 | Leave a comment

Nagios NRPE example setup


#> apt-get install nagios-nrpe-server nagios-nrpe-plugin

CentOS and Fedora

#> yum install nrpe nagios-plugins-load nagios-plugins-users nagios-plugins-swap nagios-plugins-disk

#> chkconfig –add nrpe


#> cd /usr/ports/net-mgmt/nrpe*

#> make

#> make install clean

#> In /etc/nagios/nrpe.cfg

Set the following

dont_blame_nrpe=1 (default set is 0)

Edit the local config file to only allow the nagios servers and set the check commands

This is in /etc/nagios/nrpe_local.cfg on Ubuntu boxes


command[check_users]=/usr/lib/nagios/plugins/check_users -w 5 -c 10

command[check_load]=/usr/lib/nagios/plugins/check_load -w 15,10,5 -c 30,25,20

command[check_disk]=/usr/lib/nagios/plugins/check_disk -w 20 -c 10

command[check_zombie_procs]=/usr/lib/nagios/plugins/check_procs -w 5 -c 10 -s Z

command[check_procs]=/usr/lib/nagios/plugins/check_procs -w 150 -c 200

command[check_swap]=/usr/lib/nagios/plugins/check_swap -w 20 -c 10

On CentOS it puts the hard coded commands into /etc/nagios/nrpe.cfg there is no local file

Also add this line as it is not there by default

command[check_swap]=/usr/lib64/nagios/plugins/check_swap -w 20 -c 10

This may bee needed on 64bit machines

mkdir /usr/lib/nagios

mkdir /usr/lib/nagios/plugins

ln -s /usr/lib64/nagios/plugins/check_nrpe /usr/lib/nagios/plugins/check_nrpe

If you are running a custom firewall or standard IP tables you may need to add an allow for the port (Fedora or CentOS)

Firewall (I added under the SSH section)


$IPTABLES -A INPUT -p tcp -s $ANY –destination-port 5666 -j ACCEPT

Standard IP Tables

-A INPUT -p tcp -s $ANY –destination-port 5666 -j ACCEPT

Restart the firewall

Restart the nrpe server


/etc/init.d/nagios-nrpe-server restart


/etc/init.d/nrpe restart

On the monitoring server you can run this to check for a response and make sure things are talking. This can also be ran on the local machine just use as the server IP. If you get a response on the local machine but not the nagios server you likely have a firewall rule blocking you.

/usr/lib/nagios/plugins/check_nrpe -H <SERVER IP>
Posted in Linux How-To, Networking | Leave a comment

Postifix only allow localhost

This is how to allow only mail from localhost preventing an open relay on your postfix server in the file usually in /etc/postfix/

mynetworks =, [::1]/128

Posted in Linux How-To, Mail | Leave a comment

Block Port 25 with IPTables

Block all port 25 except from localhost

-A INPUT -p tcp -s localhost –dport 25 -j ACCEPT

-A INPUT -p tcp –dport 25 -j DROP

Posted in Linux How-To, Networking | Leave a comment