Index  Page 1  Page 2
Create Debian Installer CD
Debian Installation
PuTTY, additional programs and apt
Create Firewall Rules
Install MySQL
Install programs that use SSL certificates
Create and install SSL Certificates
Enable php in apache-ssl
Install and configure phpMyAdmin
Perform some preliminary Postfix configuration
Install SquirrelMail software
Install and configure PostfixAdmin and maildrop
Configure SASL and TLS
Install and configure amavisd-new
Create Bayes and AWL tables in MySQL
Configure and customize SquirrelMail
Configure Razor
Install pflogsumm
Install BIND
Additional Postfix configuration
Set up PostfixAdmin Vacation
Install postfixadmin SquirrelMail plugin
Install MailZu
Quota
Install Mailgraph - Optional
Install mysql-zrm
The alias issue
Acting as a relay server
You don't want to loose mail due to a failed hard drive. I suggest using software or hardware RAID1 (I provide a separate software RAID1 howto). I am not going to install a GUI when I install Debian, so during installation "Standard system" will be the only package group I select. In other words, I will not select "Desktop environment". This is a copy and paste document. You need to save all three pages of this document to your computer then edit this page and do a search and replace of certain items in order to customize it for your server. Open this saved document in WordPad, a plain text HTML editor or other similar text editor that will not modify the HTML code and read the instructions at the top of the document. The instructions will point you to some items that should be changed. Note that once this document is edited to match your preferences, there will be passwords in this document. Please take steps to secure your copy of this document. Once edited, make backup copies of all three pages to a CD or floppies or at least to a different directory. Don't make the same mistake I have made a couple times by editing this page and then downloading another fresh copy and overwriting it. I personally find that when selecting a block of text it is easier to start at the bottom and work up rather than starting at the top and working down.

Without going into much detail about hardware requirements I can tell you that the biggest problem you will face is how long it takes to scan a message for spam and viruses. On a powerful computer on a wide Internet pipe it typically takes around 5 seconds. On a lower powered machine (like an older P4 2.0Ghz single processor) on a narrower pipe (like a T1), it can take 20 or 30 seconds. However, you control the number of concurrent spam scanning processes. Theoretically you add more processes for greater throughput. The problem is, each process takes a considerable amount of CPU power and RAM. If you incrementally add processes, at some point your server will grind to a halt - most likely due to swap thrashing. That said, your server should have a minimum of 1GB RAM. Mark Martinec wrote a paper that illustrates the capacity of a single moderately powerful dual processor machine http://www.ijs.si/software/amavisd/amavisd-new-magdeburg-20050519.pdf. Mailscanner is a product similar to amavisd-new. Here are some samples of servers used with Mailscanner: http://wiki.mailscanner.info/doku.php?id=maq:index#setup_examples. Note that these examples are using older (less CPU intensive) versions of SpamAssassin. Also note that on this server you will have the significant additional overhead of Apache, MySQL and Courier. If you want to install intrusion detection (I use an older version of AIDE) you will need a floppy drive. I have to warn you, the company I work for only has about 50 mail users, so this has not been tested on a large scale. This setup has only been tested using the en_US locale.

Create Debian Installer CD:

Index Top Bottom

Make a new directory on your Windows computer and call it 'debian' or something. Then download the latest version of the Debian installer for 'etch' and save it there. Go to: http://www.debian.org/releases/etch/debian-installer/. Read the errata while you are on that page. One interesting errata is http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=401435.

Note that there are etch 4.0r3 i386 or etch 4.0r3 ia64 or etch 4.0r3 amd64 CDs available from this location but unfortunately I have only tested this setup using the i386 CD (32bit). By default it installs the Linux kernel version 2.6.18.

Debian Installation:

Index Top Bottom

Information on the Debian Installer is located at http://d-i.alioth.debian.org/manual/en.i386/apa.html

If using RAID1, you should have both drives installed. We are going to erase the hard drive so make sure you don't have any data on it you might need. You may have to change the order of boot devices in your BIOS before we begin. Boot up the computer using the Installer CD or the Installer floppy #1. If you use the floppy to boot up, it will prompt you for remaining floppies. I recommend the CD-ROM. The instructions below pertain to the CD-ROM method in the default "ask as few questions as possible" mode. Set the correct date and (local) time in the BIOS before you start. When the system boots up to the Debian screen, simply press [Enter] at the boot: prompt.

[ !! Choose Language]
This determines the language of the installer and picks a keyboard.
This installation has only been tested with English - English
[Choose country, territory or area]
Choose what is appropriate

Unplug the ethernet cable.

[! Select a keyboard layout]
American English selects a standard qwerty keyboard.

There will be a few screens of activity, then this will come up:
[Configuring the network with DHCP]
Hit [Cancel] because we want DHCP configuration to fail.

Plug the ethernet cable back in.

[!! Configure the network]
Network autoconfiguration failed

We wanted that to happen, simply press:
[Continue]

On the next screen, choose the default of:
[Configure network manually]

[!! Configure the network]
Make sure Num Lock is on!
[IP address:]
111.111.111.111
[Netmask:]
255.255.255.x
[Gateway:]
333.333.333.333
[Name server addresses:]
444.444.444.444 555.555.555.555
[Hostname:]
msa
[Domain name:]
example.com

For partitioning hard drives, I am going to use software RAID1. I suggest using a pair of 320GB or larger hard drives. Another possibility is using four drives and allocating an entire pair of drives to the mail store: /var/vmail. See: http://www200.pair.com/mecham/raid/raid1.html

[! Configure time zone]
[Select your time zone:]
Simply choose what is appropriate.

[!! Set up users and passwords]
This will ask for root's password and allow you to create a "normal" user and a password for that user. Watch your [Num Lock] status. Use really good passwords and don't forget them. Please add one, and just one, normal user here. If you plan on storing mail locally on this machine (not documented here), or even if you don't, create a user who's main purpose in life might be to hold root's mail. I suggest calling the user myroot or something similar.
Keep in mind that all the best hacker tools run on Linux. If a hacker gains root access to this box, your entire network is history.

[Installing the base system]
Wait....

[! Configure the package manager]
[Use a network mirror?]
Choose [Yes]
[Debian archive mirror country:]
Choose your country
[Debian archive mirror:]
Choose a mirror near you (mirrors.kernel.org works very well in the US)
[HTTP proxy information]
(configure if needed, otherwise leave unconfigured)
Scanning the mirror...

[! Configuring popularity contest]
You decide if you would like participate.

[Debian software selection]
[Choose software to install:]
You only want to select 'Standard system' here (nothing else). Use the space bar to deselect 'Desktop environment' then simply [Tab] over and select [Continue].
Software will download now. I hope you have a fast Internet connection. What software we don't have now, we can easily get later. We are trying to keep this system somewhat clean. We will use apt-get to install most software after the fact. Some software may also be upgraded, and as a result, you may be asked some questions. When asked a question, usually the default answer will be the correct answer.

This section should not show up, but just in case it ever does:
[Configuring console data]
IMPORTANT! choose "Don't touch keymap"

This should not come up either, but in case it does:
[Configuring Exim v4 (exim4-config)]

[General type of mail configuration:]
choose [no configuration at this time]
[Really leave the mail system unconfigured?] [Yes]

[Root and postmaster mail recipient:]
The "normal" user we added earlier will display here. This is fine, so simply accept this. All of root's mail will be redirected to this "normal" user's mailbox. This is necessary because you typically cannot access root's mailbox remotely.

[! Install the GRUB boot loader on a hard disk]
[Install the GRUB boot loader to the master boot record?]
If you would like the install the (recommended) GRUB boot loader choose [Yes]
If you would like the install the LILO boot loader [Tab] over and select [Go Back]
Then select the 'Install the LILO boot loader...'
[Finish the installation]
Remove the CD or floppy when prompted, then hit [Continue] This will reboot.

Once the system is installed, login as root and issue the following command:
apt-get install ntpdate ssh vim

It may ask you to insert the installation CD; do so, then please remove it afterwards.

PuTTY, additional programs and apt:

Index Top Bottom

I will now turn off the monitor and head on over to my trusty old Windows computer. I am going to configure every thing else from there.

You should have this document open in a window on your Windows computer because we are going to use the Windows SSH client PuTTY to operate our server remotely. We are going to save a lot of typing because you are going to select text with the mouse, copy it to the clipboard with [Ctrl]+c and then paste it into the PuTTY window with a right-click of the mouse. Also, simply highlighting text in the PuTTY window copies that text to the clipboard.

Place putty.exe on your desktop, open it up, select SSH, input the IP address of the server then enter a name for your session in the Saved Sessions box. In the Category window, expand Terminal and click on Features. Check the box "Disable application keypad mode". Just below this in the Category window, click on Window, and increase "Lines of scrollback" from 200 to 800. click on Session (at the top), then Save. The "Disable application keypad mode" enables us to use the numeric keypad when using vi.

When you use PuTTY again, simply double click on the saved session. Make sure you are at a command (shell) prompt before exiting PuTTY. You can log out of the bash shell (and hence close the the PuTTY window) by issuing the command 'logout' or 'exit' or [Ctrl]+d.

Note.
Your [Home] and [End] keys will work when editing a file using vi, but will not work at the command prompt (you can use [Ctrl]+a and [Ctrl]+e for this).

Open up a PuTTY session now and log in as root.

This would be a good time to also download and install WinSCP. WinSCP is a great GUI file browser that lets you transfer files between your Windows machine and your new Debian box. You can also edit files on your Debian box from your Windows machine using WinSCP's editor. I suggest when you save sessions you leave the password blank so you are prompted for it each time you log in.

We are going to use vi (vim actually) to do most of our editing. Fortunately we only need to learn a few commands to be able to accomplish our tasks. There are 3 operating modes in vi. There is the "Command" mode, the "Write" mode and the "Command line" mode. When you first open a file for editing, you are in Command mode. You change to Write mode by entering the letter "i", (short for "insert"). You can edit text pretty much as you would expect in Write mode. You exit out of Write mode and return to Command mode by hitting the [Esc] key. There are many commands that can be learned in Command mode but we only need to learn two more in addition to "i". Those commands are ":" (a colon) and "/" (a forward slash). The colon is used to enter the third mode, the Command line mode and the slash enables the Search command. When you are in Command line mode, you will see a colon at the bottom of the screen. Here is a list of commands we will use while in Command line mode:

:q    quit (provided you have not made any changes) By the way, the lower case q is used often in *nix as a way to exit a screen.
:q!   exits vi and discards changes (great when you trashed the file and just want to start over!)
:wq   saves the changes and exits vi (write and quit)
:w    saves the current changes but does not exit vi (write)
And in command mode:
G    The capital "G" Goes to the bottom of the page (very handy)

And here is how the Search command works:
/text_to_search_for   moves the cursor to the first occurrence of     text_to_search_for

Once the first occurrence of the text we searched for is found, use a lower case 'n' to find the next occurrence.

That's all we need to know for now! The biggest mistake you will make at first is you will forget to hit "i" (to enter insert mode) before you paste stuff into a document.
If you would like a cheat sheet for additional commands: http://www.fprintf.net/vimCheatSheet.html and http://amath.colorado.edu/computing/unix/vi/

Set the system clock:
ntpdate clock.fmt.he.net
ntpdate ntp1.tummy.com



Enter the following command:
dpkg-reconfigure locales

[Configuring locales]
You use [PgUp] [PgDn] [up-arrow] [down-arrow] [tab] and [spacebar] to navigate and select.
The etch installer software installed en_US.UTF-8 UTF-8 on my system. I suggest you install the en_US ISO-8859-1 locale (in addition to any other ISO-8859-x locales you may require). If you need to change the locale, or add additional locales, use the [arrow] [spacebar] and [tab] keys. An UTF-8 locale should not be used as the default system LANG (set in /etc/environment or /etc/default/locale), SpamAssassin and amavisd-new may have problems if you do. However, you should keep the UTF-8 locale in addition to the ISO-8859-x file or Perl may complain.

[Which locale should be the default in the system environment?]
I suggest you do NOT choose [None], I suggest you choose [en_US] or other non UTF-8 locale (an ISO-8859-x locale).

Our default language is currently an UTF-8 locale. We want our system wide language to be an ISO-8859-x (non UTF-8) locale. You can set the language in /etc/environment (if it exists, otherwise it is set in /etc/default/locale). This file is read when we log in. We need to use a non UTF-8 locale so characters will appear as we expect them to and to avoid other problems. It is best to run amavisd-new in a non-UTF8 locale environment. The 'dpgk-reconfigure locales' program previously automatically updated /etc/environment, but it no longer does when using the etch version so we are going edit it manually (it now updates /etc/default/locale). Make sure you have installed a corresponding ISO-8859-x locale for the UTF-8 locale we are going to change:
cat /etc/environment

If the above returns "No such file or directory", then the setting is in /etc/default/locale and you can skip editing this file, otherwise please continue.
vim /etc/environment

Change LANG from a UTF-8 setting:
LANG="en_US.UTF-8"

to a non UTF-8 setting:
LANG="en_US"

Save and exit the file: [Esc]:wq to 'write and quit' or [Esc]:q to quit without saving (so you can give it another try). Note: you can run the command locale to see the current settings. It is best to reboot after changing the /etc/environment file. Changes are not recognized until you at least log out, then back in.

There is an errata dealing with tcp_window_scaling on Linux kernel 2.6.17 (and newer).
http://kerneltrap.org/node/6723 http://marc.info/?l=postfix-users&m=117457942431349 You may want to consider what may happen (large files fail to transfer between systems) when there is a buggy router between you and someone else, and may wish to make this change to the system (you decide):
echo "net.ipv4.tcp_wmem = 4096 65536 65536" >>/etc/sysctl.conf
echo "net.ipv4.tcp_rmem = 4096 65536 65536" >>/etc/sysctl.conf
sysctl -p


I am going to assume this may slow down communications between systems under certain circumstances.

Our default system editor will be nano, and not vim. I will change my default system editor to vim:
vim /root/.profile

and just below the line "fi" insert this entry:
export EDITOR=/usr/bin/vim.basic

Save and exit the file: [ESC]:wq

vim /etc/apt/sources.list

At this point, the contents of the file may look something like this:
#
# deb cdrom:[Debian GNU/Linux testing _Etch_ - Official Snapshot i386 Binary-1 (20061111)]/ etch main

deb cdrom:[Debian GNU/Linux testing _Etch_ - Official Snapshot i386 Binary-1 (20061111)]/ etch main

deb http://mirrors.kernel.org/debian/ etch main
deb-src http://mirrors.kernel.org/debian/ etch main

deb http://security.debian.org/ etch/updates main
deb-src http://security.debian.org/ etch/updates main
We need to modify this file so the result will look something like this:
(with only the http server unique to your particular system)
deb http://mirrors.kernel.org/debian/ etch main non-free contrib
deb-src http://mirrors.kernel.org/debian/ etch main

deb http://security.debian.org/ etch/updates main non-free contrib
deb-src http://security.debian.org/ etch/updates main

deb http://volatile.debian.org/debian-volatile etch/volatile main
Note what I have done here. Any lines that use the cdrom
#deb cdrom:[Debian GNU/Linux testing _etch_
have been erased and the words "non-free" and "contrib" have been added. Debian Volatile has also been added.

You will have to add the current Volatile gpg key. Note that if you are unable to retrieve the key from subkeys.pgp.net it might be an indication of some sort of firewall or proxy issue. I personally have a proxy that gives me problems so I work around it by using another gateway (see /etc/network/interfaces). I have a feeling my proxy does not proxy this protocol properly. If that is also the case with you, you may end up having problems with other programs such as the DCC client:
gpg --keyserver subkeys.pgp.net --recv-key BBE55AB3
gpg --armor --export BBE55AB3 | apt-key add -



You must run apt-get update next.
apt-get update


You should also make sure the system is up to date.
apt-get upgrade


If the kernel is upgraded:
reboot


For security reasons I remove some programs. My server will not need the pident service or provide shared disk space.
apt-get remove nfs-common pidentd portmap


If you are using a multi-processor machine, then use a multi-processor kernel. To locate available smp kernels for etch, you could run:
apt-cache search linux-image | grep smp | grep linux-image

If you are running a 2.6.18 (etch) kernel, and have a dual core Intel system, you could for example use the 'linux-image-2.6-686-smp' kernel. You would pick the kernel that most closely matches your system (and your current kernel). To install it, you would simply run (for example):
apt-get install linux-image-2.6-686-smp

If you installed a new kernel, please  reboot  afterwards.

There is a problem I describe here. Here I attempt to fix it:
apt-get install yaird

apt-get remove initramfs-tools

KERNEL=`uname -r`
cp /boot/initrd.img-$KERNEL /boot/initrd.img-$KERNEL-backup
mv /boot/initrd.img-$KERNEL /boot/initrd.img-$KERNEL-backup2
yaird --output=/boot/initrd.img-$KERNEL $KERNEL
ls -l /boot

Make sure it shows you have a good initrd.img that matches the other stuff:
-rw-r--r-- 1 root root   70781 2007-05-09 16:14 config-2.6.18-4-686
drwxr-xr-x 2 root root    4096 2007-06-10 09:25 grub
-rw------- 1 root root 1135592 2007-06-19 20:15 initrd.img-2.6.18-4-686
-rw-r--r-- 1 root root 4490534 2007-06-19 20:14 initrd.img-2.6.18-4-686-backup
-rw-r--r-- 1 root root 4490534 2007-06-10 09:25 initrd.img-2.6.18-4-686-backup2
-rw-r--r-- 1 root root  722037 2007-05-09 22:14 System.map-2.6.18-4-686
-rw-r--r-- 1 root root 1261213 2007-05-09 22:14 vmlinuz-2.6.18-4-686
Then reboot:
reboot
exit



Create Firewall Rules:

Index Top Bottom

On my system I try to keep as much traffic as possible between this machine and my users encrypted, so I don't open port 80. I will configure my clients to use 443 (apache-ssl), 993 (courier-imap-ssl) and 995 (courier-pop-ssl) whenever possible. I also limit access to ssh to my local network.

DO NOT USE AS IS, CHANGE NETWORK ADDRESS FIRST IF YOU HAVE NOT ALREADY DONE SO:
You can copy and paste this whole section to the shell prompt:
iptables -F
iptables -N FIREWALL
iptables -F FIREWALL
iptables -A INPUT -j FIREWALL
iptables -A FORWARD -j FIREWALL
iptables -A FIREWALL -p tcp -m tcp --dport 25 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 110 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 143 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 443 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 465 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 587 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 993 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 995 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --dport 4650 --syn -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp -s 222.222.222.222/24 --dport 22 --syn -j ACCEPT
iptables -A FIREWALL -i lo -j ACCEPT
iptables -A FIREWALL -p udp -m udp --sport 53 -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --sport 53 -j ACCEPT
iptables -A FIREWALL -p udp -m udp --dport 123 -j ACCEPT
iptables -A FIREWALL -p udp -m udp --sport 6277 -j ACCEPT
iptables -A FIREWALL -p udp -m udp --sport 24441 -j ACCEPT
iptables -A FIREWALL -p tcp -m tcp --syn -j REJECT
iptables -A FIREWALL -p udp -m udp -j REJECT
iptables-save > /etc/firewall-rules
iptables-restore < /etc/firewall-rules

This will write the firewall rules to a file on this server, but iptables starts with an empty rule set each time the computer restarts. The rule set I saved to /etc/firewall-rules must be "loaded" into iptables every time the system starts up.

I am going to insert the command to configure iptables into a file that starts up the network interfaces when the system boots up:
vi /etc/network/interfaces

And insert the following text in the blank line just below "iface lo inet loopback":
pre-up iptables-restore < /etc/firewall-rules

While you are at it, 2 lines down, change allow-hotplug eth0 to:
auto eth0

Save and exit the file, then reboot:
reboot
exit


If you have problems accessing the system after it boots up, enter the command  iptables -F   from the console to clear out iptables. This will allow you another shot at it.

Install ntp, a c compiler, logcheck and some other stuff:
apt-get install ntp make gcc bison flex libc6-dev logcheck logcheck-database flip psmisc dpkg-dev

For more information about logcheck rules and patterns to include or ignore:
vi -R /usr/share/doc/logcheck-database/README.logcheck-database.gz

and to debug logcheck:
su -s /bin/bash -c "/usr/sbin/logcheck -otd" logcheck

Install MySQL

Index Top Bottom
apt-get install mysql-server

Out of the box MySQL is tuned for a system with very little memory. We need to allocate more memory for caching items. This will make a huge difference in performance. We are going to change all tables to InnoDB so we will adjust some InnoDB settings. If you currently have data in MySQL or you have made changes to /etc/mysql/my.cnf you should not perform these steps to replace your my.cnf file with mine! Also, I am assuming you have at the very least 1GB of physical memory installed (2GB recommended - 3GB even better):
cp /etc/mysql/my.cnf /etc/mysql/my.cnf-original
zcat /usr/share/doc/mysql-server-5.0/examples/my-medium.cnf.gz > /etc/mysql/my.cnf
cd /etc/mysql/
wget http://www200.pair.com/mecham/spam/my-medium.cnf.patch.txt
patch my.cnf < my-medium.cnf.patch.txt
/etc/init.d/mysql restart


Add a password for user 'root' (make sure the hostname is correct):
mysql -u root

From the mysql> prompt, create the two passwords required for root (bold text items need to be replaced with your personal settings - you should have edited this document already):
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('roots_password');
SET PASSWORD FOR 'root'@'msa' = PASSWORD('roots_password');
FLUSH PRIVILEGES;
SHOW VARIABLES LIKE 'innodb_fast_shutdown';


Make a mental note of the innodb_fast_shutdown setting. The default is "1". Quit mysql:
QUIT

Since my patch changed the size of innodb_log_file_size, we will have to create new logs. If innodb_fast_shutdown was something other than "1", edit /etc/mysql/my.cnf and add an entry "innodb_fast_shutdown = 1" and then restart mysql with "/etc/init.d/mysql restart". Once innodb_fast_shutdown = 1 then:
/etc/init.d/mysql stop

Make sure that it shuts down without errors (to ensure that there is no information for outstanding transactions in the logs). Then:
mv /var/lib/mysql/ib_logfile0 /var/lib/mysql/iblogfile0-old
mv /var/lib/mysql/ib_logfile1 /var/lib/mysql/iblogfile1-old
/etc/init.d/mysql start
ls -l /var/lib/mysql/ib_*


It should show our two log files are now 48MB in size (50331648). I have set "innodb_buffer_pool_size = 192M" which will give much better performance than the default of 8M, and "innodb_log_file_size = 48M" which is 25% of the innodb_buffer_pool_size. If you have plenty of RAM, you can increase innodb_buffer_pool_size even more, but personally I would not set it to more than 25% of physical RAM. You may need the extra space for a polar bear or dung beetle.

Install programs that use SSL certificates

Index Top Bottom
The next command goes on one line. Before you issue this command, read the paragraph following it.
apt-get install apache-ssl libapache-mod-php4 php4 php4-common php4-mysql php4-gd php4-mcrypt mcrypt ca-certificates openssl

You will be asked questions. Sample answers follow. Be sure to use the full name for your state or province name and the host name must be the FQDN host name of this machine (however, the certificate created here will soon be replaced):
Country Name US
State or Province Name Utah
Locality Name Salt Lake City
Organisation Name Widgits Inc.
Organisational Unit Name WebMail Server
Host Name msa.example.com
Email Address postmaster@example.com

Actually, that was just practice. We are not going to use the certificate we just created. Do not browse to the web server yet. At least, DO NOT install the certificate. Now install Postfix:
apt-get install postfix postfix-pcre postfix-mysql libsasl2-modules-sql libsasl2-modules

Answer the questions:
General type of configuration? Internet Site
Mail name? example.com (edit this so only the domain name is used here)


apt-get install courier-imap-ssl courier-pop-ssl courier-authlib-mysql

Create directories for web-based administration ? [No]

Create and install SSL Certificates

Index Top Bottom
Every client that connects to this server will need to be able to resolve the hostname of the server. Add an entry to your hosts file or add an A record to your DNS server so we can properly interact with the server. We are going to be our own Certificate Authority and sign our own certificates. These commands are dependent on /etc/ssl/openssl.cnf as supplied by Debian. We start by making a small change to /etc/ssl/openssl.cnf. We make it so by default our certificates are good for 10 years instead of 1:
sed -i 's/= 365\t/= 3653\t/' /etc/ssl/openssl.cnf
grep 365 /etc/ssl/openssl.cnf


We will set up a common place to put our certificates:
cd /root
mkdir CA
cd CA
mkdir demoCA
cd demoCA
mkdir newcerts
mkdir private
echo '01' > serial
touch index.txt
cd ..


Create a Root Certificate:
openssl req -new -x509 -extensions v3_ca -keyout demoCA/private/cakey.pem -out cacert.pem -days 3653

Enter a passphrase when prompted. You will need this passphrase in the future. What I mean is: make it unique and don't ever loose it. You will be asked questions. Sample answers follow. Be sure to use the full name for your state or province name and the Common Name should be something that describes you as an authority (like Widgits Inc. RootCA):
Country Name US
State or Province Name Utah
Locality Name Salt Lake City
Organisation Name Widgits Inc.
Organisational Unit Name WebMail Server
Common Name (eg, YOUR name) Widgits Inc. RootCA
Email Address postmaster@example.com


This process produces two files as output: a private key in demoCA/private/cakey.pem and a root CA certificate in cacert.pem. Any and all key files we produce will need to be protected from unauthorized persons reading them, and must not be lost for the next 10 years. Also realize that the CA you created can sign any number of certificates (until it expires 10 years from now) so you only need to (or want to) create the CA once. We will copy our cert and our key to something more descriptive:
cp -i demoCA/private/cakey.pem demoCA/private/cakey.example.com.pem
chmod 600 demoCA/private/*
cp -i cacert.pem cacert.example.com.pem
cp -i cacert.pem cacert.example.com.crt


The cacert.example.com.pem and cacert.example.com.crt are copies of our certificate and are the files that can be distributed and installed on the client's machines. Windows clients would use the .crt file. On my Windows 2000 system, double clicking this file would install it in Internet Explorer (which is exactly what want). Simply browsing to our server will give us the opportunity to install the web server certificate we will create (this will be the Common Name msa.example.com) but this is not the same as installing the CA certificate in the Trusted Root Certification Authorities store (seen as the Common Name you entered above). Just in case you are not familiar, in IE6 it's Tools->Internet Options->Content->Certificates->Trusted Root Certification Authorities. Outlook and Outlook Express use the same certificate store as Internet Explorer. In Mozilla Thunderbird it's Tools->Options->Privacy->Security->View Certificates->Authorities. In Firefox it's Tools->Options->Advanced->Encryption->View Certificates->Authorities->Import. If you go through this process more than once while testing, don't install duplicate certificates. Delete any old 'test' certificate you previously installed before adding your new one that replaces it. In my old version of The Bat! I add a new contact in the "Trusted Root CA" section of the address book and import the certificate from there. I suggest using WinSCP to transfer the cacert.example.com.crt certificate to your machine. I think the worst part of getting this server set up is getting the CA certificates installed on the clients. Sometimes it's worth it to buy a certificate from a well known commercial CA that is already in the Trusted Root Certification Authorities store.

We are now going to create a request for a certificate from the CA (which is us - but could be a commercial CA if you like). Everyone that connects to us will connect to the hostname of this machine. The Secure Web server, Secure IMAP server, Secure POP server and Postfix Secure SMTP server will all be msa.example.com, so the Common Name MUST BE our FQDN hostname when we create the request. The Organization name needs to be the same as the one in the CA cert. Do not enter your email address, challenge password or an optional company name when generating the CSR:
openssl req -new -nodes -out req.pem

Country Name US
State or Province Name Utah
Locality Name Salt Lake City
Organisation Name Widgits Inc.
Organisational Unit Name WebMail Server
Common Name (eg, YOUR name) msa.example.com
Email Address


This process produces two files as output, a private key in privkey.pem and a certificate signing request in req.pem. These files should be kept. The private key is of course necessary for SSL encryption. We will make backup copies of these files with more descriptive names:
cp -i privkey.pem privkey.msa.example.com.pem
chmod 600 privkey.*
cp -i req.pem req.msa.example.com.pem


Sign the Certificate (you will be asked for the pass phrase):
openssl ca -out cert.pem -cert cacert.pem -infiles req.pem

This process updates the CA database and produces two files as output, a certificate in cert.pem and a copy of the certificate in demoCA/newcerts/ named xx.pem, where xx is the serial number. We will copy the cert to a more descriptive name. The certificate has both the encoded version and a human-readable version in the same file. We want to strip off the human-readable portion as follows:
mv -i cert.pem temp.cert.msa.example.com.pem
openssl x509 -in temp.cert.msa.example.com.pem -out cert.pem
cp -i cert.pem cert.msa.example.com.pem


Postfix will want the cert and the key in two separate files, apache-ssl will want the two combined (but can use two separate files if configured to do so). Courier will want the two combined, with a Diffie-Hellman code block added. Sheesh, why can't we all just get along?
cat privkey.msa.example.com.pem cert.msa.example.com.pem >key-cert.pem
cp -i key-cert.pem key-cert.msa.example.com.pem
cp -i key-cert.pem key-cert-dh.msa.example.com.pem

openssl gendh >> key-cert-dh.msa.example.com.pem
chmod -R 600 /root/CA


After those steps, you have four installable components (and some more descriptive backup copies):
A private key in privkey.pem (with a copy in privkey.msa.example.com.pem)
A certificate in cert.pem (with a copy in cert.msa.example.com.pem)
A combined private key and certificate in key-cert.pem (with a copy in key-cert.msa.example.com.pem)
A combined private key, certificate and DH code in key-cert-dh.msa.example.com.pem

Now give a copy of the combined certificate to apache-ssl. Apache-ssl is currently using the /etc/apache-ssl/apache.pem certificate (the SSLCertificateFile setting in /etc/apache-ssl/httpd.conf). We will reconfigure it to use /etc/apache-ssl/key-cert.msa.example.com.pem:
/etc/init.d/apache-ssl stop
/etc/init.d/apache-ssl start

cd /root/CA/
cp key-cert.msa.example.com.pem /etc/apache-ssl/
chmod 600 /etc/apache-ssl/key-cert.msa.example.com.pem
sed -i 's/apache.pem/key-cert.msa.example.com.pem/' /etc/apache-ssl/httpd.conf
/etc/init.d/apache-ssl stop
/etc/init.d/apache-ssl start


Give Postfix the files it needs and tell it where they are (and set a couple other TLS parameters). We also make a backup of main.cf before we modify it for the first time:
cp -i /etc/postfix/main.cf /etc/postfix/main.cf-24jul2007

mkdir -p /etc/postfix/ssl
cp privkey.msa.example.com.pem /etc/postfix/ssl
cp cert.msa.example.com.pem /etc/postfix/ssl
cp cacert.example.com.pem /etc/postfix/ssl
postconf -e "smtpd_tls_key_file = /etc/postfix/ssl/privkey.msa.example.com.pem"
postconf -e "smtpd_tls_cert_file = /etc/postfix/ssl/cert.msa.example.com.pem"
postconf -e "smtpd_tls_CAfile = /etc/postfix/ssl/cacert.example.com.pem"
postconf -e "smtpd_tls_received_header = yes"
postconf -e "smtpd_use_tls = yes"
chmod 600 /etc/postfix/ssl/*
postfix reload


Install certificates in Courier IMAP and configure imapd-ssl to use them (this changes the TLS_CERTFILE setting):
cp -i key-cert-dh.msa.example.com.pem /etc/courier/

chmod 600 /etc/courier/key-cert-dh.msa.example.com.pem
chown daemon /etc/courier/key-cert-dh.msa.example.com.pem
sed -i 's/imapd.pem/key-cert-dh.msa.example.com.pem/' /etc/courier/imapd-ssl
/etc/init.d/courier-imap-ssl stop
/etc/init.d/courier-imap-ssl start


And configure Courier POP3 to use the same certificates:
sed -i 's/pop3d.pem/key-cert-dh.msa.example.com.pem/' /etc/courier/pop3d-ssl
/etc/init.d/courier-pop-ssl stop
/etc/init.d/courier-pop-ssl start


Running some of these commands again will result in overwriting keys and certificates. That may not be good. Some files will necessarily be overwritten if additional certificates are requested, signed and created. That is expected, and is the reason we make host-specific copies of everything as we go along. Just be careful not to overwrite any host-specific files we have created. And remember, only one Root Certificate Authority needs creation. Make a backup of the session, both on and off the system (transfer the directory via WinSCP).
cp -r /root/CA /root/CA-24jul2007



Note that if you create certificates for additional hosts and want to provide SSL for multiple hosts via the VirtualHost directive, it is my understanding you will need a separate IP address for each host: http://httpd.apache.org/docs/trunk/ssl/ssl_faq.html#vhosts. For example, I created a request for a new cert for mailzu.domain.tld. Then I signed it using our CA cert, stripped off the human readable portion, combined the key and certificate into a single file called key-cert.mailzu.domain.tld.pem and copied this certificate to the /etc/apache-ssl directory. Later we will install MailZu, which has a home directory of /var/www/mailzu. If you wanted to access /var/www/mailzu using a virtual host (using SSL) via https://mailzu.domain.tld, you would have to add another IP address. Here I show adding one to an existing interface that has the IP address 192.168.1.222 - (this is in /etc/network/interfaces):
auto eth0
iface eth0 inet static
        address 192.168.1.222
        netmask 255.255.255.0
        network 192.168.1.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
		
auto eth0:0
iface eth0:0 inet static
        address 192.168.1.223
        netmask 255.255.255.0
        network 192.168.1.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
Then I created a file called /etc/apache-ssl/vhosts.conf with the contents:
<VirtualHost 192.168.1.223:443>
DocumentRoot /var/www/mailzu
ServerName mailzu.domain.tld
SSLCertificateFile /etc/apache-ssl/key-cert.mailzu.domain.tld.pem
</VirtualHost>
I personally do not go this route (who has IP addresses to spare?), so I do not do this. I choose to access MailZu via https://msa.example.com/mailzu. This means I only have to deal with one host certificate (and one IP address). BTW, I reboot after making changes to /etc/network/interfaces.


Enable php in apache-ssl

Index Top Bottom
The next command is on one line. We will use sed to edit a file that will enable php in apache-ssl.
sed -i 's|#AddType application/x-httpd-php .php|AddType application/x-httpd-php .php|' /etc/apache-ssl/httpd.conf

grep php4_module /etc/apache-ssl/modules.conf

If you do not get:
LoadModule php4_module /usr/lib/apache/1.3/libphp4.so

Then you need perform the next step:
apache-modconf apache-ssl enable mod_php4

Regardless, restart apache-ssl:
/etc/init.d/apache-ssl restart

Download a home page. This page describes some of the features of the mail system to new users. Those features are not yet installed but we can install this page. One it is in place, edit it (you may prefer the WinSCP editor) and do a search and replace on the items listed at the top of the page. No doubt once this entire system is installed you will do a lot more editing of this page:
cd /var/www
wget http://www200.pair.com/mecham/spam/virtual.index.html
cp index.html index.html-apache-original
cp virtual.index.html index.html
sed -i 's/Our Organization/Widgits Inc./' index.html
sed -i 's/somehost.domain.tld/msa.example.com/' index.html
sed -i 's/domain.tld/example.com/' index.html
chown root:www-data index.html


Browse to the server (first add the address to DNS or your hosts file):
https://msa.example.com


Install and configure phpMyAdmin

Index Top Bottom
apt-get install phpmyadmin

At this point our https://msa.example.com/phpmyadmin program is open for abuse. We will secure it by making the URL obscure, by setting a user name and password and by optionally (but highly recommended) only allowing chosen IP addresses to access the URL. Obscure the URL by changing its name (which should have already been done by editing this page):
mv /var/www/phpmyadmin /var/www/phpmyadmiNx

With the current settings in /etc/apache-ssl/httpd.conf, our files used for access control (files like .htpasswd) will not be used unless we tell apache-ssl to use them. We will modify the provided access control file, then change /etc/apache-ssl/httpd.conf so it uses it. The current user name is 'admin'. Let's begin by obscuring the user name:
sed -i 's/admin/myadmin_username/' /etc/phpmyadmin/htpasswd.setup

Then, create a password for that user:
htpasswd -c /etc/phpmyadmin/htpasswd.setup myadmin_username

New password: myadmin_password
Re-type new password: myadmin_password

Now we direct apache-ssl to use this access file by placing directives in a configuration file we create. Once this is in place, attempts to browse to the /phpmyadmiNx directory will be met with a login dialog box. Note that our version of /etc/apache-ssl/http.conf contains the command "Include /etc/apache-ssl/conf.d" so that any config files we place in this directory will be read. I am also going to illustrate limiting access to one single workstation (yours of course). This is optional, but recommended. If you need to allow access to a network of machines, see http://httpd.apache.org/docs/1.3/mod/mod_access.html:

vi /etc/apache-ssl/conf.d/phpmyadmin.conf

and insert the following, making sure the IP address is the IP address of your workstation (as the mailserver sees it).
Also make sure any comments start at the leftmost column.
<Directory /var/www/phpmyadmiNx/>

 order deny,allow
 deny from all
 allow from 666.666.666.666
#allow from 666.666.666.666 allow from 192.168   

 AuthUserFile /etc/phpmyadmin/htpasswd.setup
 AuthGroupFile /dev/null
 AuthName "phpMyAdmin"
 AuthType Basic
 require valid-user
   
</Directory>
Restart apache-ssl:
/etc/init.d/apache-ssl restart

and browse to phpMyAdmin:
https://msa.example.com/phpmyadmiNx

The first login is the phpMyAdmin user name and password: myadmin_username myadmin_password
The second login is your mysql login (probably root and roots_password). You can close the phpMyAdmin web page.

Perform some preliminary Postfix configuration

Index Top Bottom
We want to explicitly set our domain name and host name in Postfix so there is no possibility Postfix finds something else:
postconf -e "mydomain = example.com"
postconf -e "myorigin = example.com"
postconf -e "myhostname = msa.example.com"


At this point, if you issue this command:
postconf -n

Postfix should show main.cf is configured something like this:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
inet_interfaces = all
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
mydestination = example.com, msa.example.com, localhost.example.com, localhost
mydomain = example.com
myhostname = msa.example.com
mynetworks = 127.0.0.0/8
myorigin = example.com
recipient_delimiter = +
relayhost =
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.example.com.pem
smtpd_tls_cert_file = /etc/postfix/ssl/cert.msa.example.com.pem
smtpd_tls_key_file = /etc/postfix/ssl/privkey.msa.example.com.pem
smtpd_tls_received_header = yes
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtpd_use_tls = yes
Please note that 'postconf -n' does not show every setting we have in main.cf. Postfix should accept mail for the addresses listed in /etc/aliases and deliver it to a mailbox in /var/mail. You should test this. Configure a MUA to use this mail server as its outgoing SMTP server. I like to designate a MUA I'm not using at the moment for testing purposes. For test purposes I typically I have several different MUAs (Outlook, Outlook Express, Thunderbird, The Bat!) set up on the system I am sending mail from. Do not send mail from the command line (using sendmail or other means) when testing this system. In all tests we perform I expect you to send test messages from an external client (unless of course we are testing something like SquirrelMail). Now send a message to postmaster@example.com. See what /var/log/mail.log said about the transaction (look for errors). It should also show you the user the message was delivered to:
tail -50 /var/log/mail.log

ls -l /var/mail


In the /var/mail directory you should see the mbox of the user the message was delivered to. You can ' more /var/mail/user ' to read the contents of the mbox.

Grab the Postfix source code (we need a few samples from it):
cd /usr/local/src
wget http://ftp.debian.org/debian/pool/main/p/postfix/postfix_2.3.8.orig.tar.gz
tar xzf postfix_2.3.8.orig.tar.gz


Make sure you answer "n" to "Overwrite?". Do the first command separately:
cp -i /usr/local/src/postfix-2.3.8/conf/* /etc/postfix

cp -i /etc/postfix/header_checks /etc/postfix/body_checks
cp -i /etc/postfix/access /etc/postfix/sender_access
cp -i /etc/postfix/access /etc/postfix/rbl_client_exceptions
cp -i /etc/postfix/access /etc/postfix/rbl_sender_exceptions
cp -i /etc/postfix/access /etc/postfix/rbl_recipient_exceptions
cp -i /etc/postfix/access /etc/postfix/reject_over_quota

cp /usr/local/src/postfix-2.3.8/examples/chroot-setup/LINUX2 /usr/sbin
chmod +x /usr/sbin/LINUX2
LINUX2


On Debian, Postfix runs chrooted. The LINUX2 script is used to copy files to the chroot jail.

Install SquirrelMail software

and a few other things
Index Top Bottom
We just need the software in place at this time.
apt-get install squirrelmail squirrelmail-locales maildrop

apt-get install sudo php-pear php5-mysql php5-gd php5-cli php5-common php5-mcrypt

apt-get install php-db php-net-socket php-log php-net-smtp



Install and configure PostfixAdmin and maildrop

Index Top Bottom
Add our virtual user and group:
groupadd vmail -g 6060
useradd vmail -u 6060 -g 6060


And create the directory where our mail will be stored:
mkdir /var/vmail
chown -R vmail:vmail /var/vmail
chmod -R 700 /var/vmail


Install subversion:
apt-get install subversion

Download revision 1 of the source code (from the SVN repository):
cd /var/www
svn -r 1 co https://postfixadmin.svn.sourceforge.net/svnroot/postfixadmin/trunk postfixadmin


Just like phpMyAdmin, we obscure the postfixadmin URL. Run these commands in sections - but don't manually change to a different directory during the process. I hope you have saved this document to your computer and have done a search and replace on the bold items. This document is for you to customize to your particular system. Read the instructions at the top of the page once you have opened it in a plain text editor (like WordPad):
mv postfixadmin postFixadminx
cd /var/www/postFixadminx
cp -i DATABASE_MYSQL.TXT DATABASE_MYSQL.TXT~
sed -i "s/password('postfix')/password('pfix_password')/" DATABASE_MYSQL.TXT sed -i "s/password('postfixadmin')/password('pfixadm_password')/" DATABASE_MYSQL.TXT wget http://www200.pair.com/mecham/spam/database_mysql.patch.txt patch DATABASE_MYSQL.TXT < database_mysql.patch.txt mysql -u root -p < DATABASE_MYSQL.TXT
(you will need to enter roots_password in order to complete the last command) chmod 600 DATABASE_MYSQL.TXT cp config.inc.php.sample config.inc.php sed -i "s|admin_url'] = ''|admin_url'] = 'https://msa.example.com/postFixadminx'|" config.inc.php sed -i "s|admin_path'] = ''|admin_path'] = '/var/www/postFixadminx'|" config.inc.php sed -i "s/password'] = 'postfixadmin'/password'] = 'pfixadm_password'/" config.inc.php sed -i 's/postmaster@change-this-to-your.domain.tld/postmaster@example.com/' config.inc.php sed -i 's/abuse@change-this-to-your.domain.tld/abuse@example.com/' config.inc.php sed -i 's/hostmaster@change-this-to-your.domain.tld/hostmaster@example.com/' config.inc.php sed -i 's/postmaster@change-this-to-your.domain.tld/postmaster@example.com/' config.inc.php sed -i 's/webmaster@change-this-to-your.domain.tld/webmaster@example.com/' config.inc.php sed -i 's/autoreply.change-this-to-your.domain.tld/autoreply.example.com/' config.inc.php sed -i 's|to change-this-to-your.domain.tld|to https://msa.example.com/postFixadminx|' config.inc.php sed -i 's|http://change-this-to-your.domain.tld|https://msa.example.com/postFixadminx|' config.inc.php sed -i "s/domain_path'] = 'NO/domain_path'] = 'YES/" config.inc.php sed -i "s/domain_in_mailbox'] = 'YES/domain_in_mailbox'] = 'NO/" config.inc.php sed -i "s/mailboxes'] = '10'/mailboxes'] = '300'/" config.inc.php sed -i "s/maxquota'] = '10'/maxquota'] = '500'/" config.inc.php sed -i "s/quota'] = 'NO/quota'] = 'YES/" config.inc.php sed -i 's/EHLO/HELO/' functions.inc.php
You should vi config.inc.php and browse through it to familiarize yourself with all the possible settings and to make sure your domain name was properly updated. Create a .htaccess password for the admin url (user name will be pfadmin_username). Assign the password pfadmin_password
cd /var/www/postFixadminx/admin
htpasswd -c .htpasswd pfadmin_username


Now tell apache-ssl to use the file. We also limit access to our own workstation, but you can add more IP addresses (or networks) if needed. Access to https://msa.example.com/postFixadminx/admin/ is controlled by the IP address(es) of the client and the .htaccess user name and password. The super user is the only one who should have access to this URL.

vi /etc/apache-ssl/conf.d/postfixadmin.conf

and insert this phrase. Don't forget to edit the ip address if you have not already done so and remember that comments must left justified:
<Directory /var/www/postFixadminx/admin/>

 order deny,allow
 deny from all
 allow from 666.666.666.666   
#allow from 666.666.666.666 allow from 192.168    

 AuthUserFile /var/www/postFixadminx/admin/.htpasswd
 AuthGroupFile /dev/null
 AuthName "Postfix Admin"
 AuthType Basic
 require valid-user
   
</Directory>
Restart apache-ssl:
/etc/init.d/apache-ssl restart

When we add a user to postfixadmin it creates records in the MySQL database but it does not create a Maildir for that user. We can make that happen with a patch to postfixadmin and a couple bash scripts. We also apply a patch to create new MySQL data in lower case rather than mixed case. Another patch is a group of patches others have submitted to the project:
cd /var/www/postFixadminx/
wget http://www200.pair.com/mecham/spam/postfixadmin.autocreate.patch.txt
wget http://www200.pair.com/mecham/spam/postfixadmin.lowercase.patch.txt
wget http://www200.pair.com/mecham/spam/postfixadmin.multipatch.txt
wget http://www200.pair.com/mecham/spam/admin-edit-mailbox.patch.txt
wget http://www200.pair.com/mecham/spam/edit-mailbox.patch.txt

cp create-alias.php create-alias.php~
cp create-mailbox.php create-mailbox.php~
cp edit-mailbox.php edit-mailbox.php~
cp admin/create-alias.php admin/create-alias.php~
cp admin/create-admin.php admin/create-admin.php~
cp admin/create-domain.php admin/create-domain.php~
cp admin/create-mailbox.php admin/create-mailbox.php~
cp admin/edit-mailbox.php admin/edit-mailbox.php~
cp users/vacation.php users/vacation.php~
cp stylesheet.css stylesheet.css~
cp admin/list-virtual.php admin/list-virtual.php~
cp templates/overview.tpl templates/overview.tpl~
cp templates/admin_list-virtual.tpl templates/admin_list-virtual.tpl~
cp templates/login.tpl templates/login.tpl~
cp templates/header.tpl templates/header.tpl~
cp templates/admin_list-domain.tpl templates/admin_list-domain.tpl~
cp languages/de.lang languages/de.lang~
cp search.php search.php~

patch -p0 < postfixadmin.lowercase.patch.txt

patch -p0 < postfixadmin.multipatch.txt

patch -p0 < postfixadmin.autocreate.patch.txt

patch -p0 < edit-mailbox.patch.txt

patch admin/edit-mailbox.php <admin-edit-mailbox.patch.txt

cd /usr/sbin
wget http://www200.pair.com/mecham/spam/maildirmake.sh.txt
mv maildirmake.sh.txt maildirmake.sh
chmod +x maildirmake.sh
wget http://www200.pair.com/mecham/spam/quotachange.sh.txt
mv quotachange.sh.txt quotachange.sh
chmod +x quotachange.sh


In order to allow the www-data user to run the scripts, you must run:
visudo

and on the bottom of the page add this stuff (notice our hostname):
www-data msa=NOPASSWD: /usr/sbin/maildirmake.sh
www-data msa=NOPASSWD: /usr/sbin/quotachange.sh


Set permissions:
cd /var/www/postFixadminx
chown -R root:www-data ../postFixadminx
chmod 640 *.php *.txt *~
chmod 600 *.TXT
chmod 640 admin/*.php admin/*~
chmod 640 images/*.png
chmod 640 languages/*.lang languages/*~
chmod 640 templates/*.tpl templates/*~
chmod 640 users/*.php users/*~


Now you can browse to postfixadmin and run the setup script:
https://msa.example.com/postFixadminx/setup.php

Assuming everything is OK, click on the link to the admin section and get past the apache security with pfadmin_username and pfadmin_password . You will need to log into the /admin page with a user name of admin@domain.tld and a password of admin (note: domain.tld is literally domain.tld). All 'Super admins' are directed to the /admin page. Click on "New Domain" and add the primary domain (example.com). Leave the optional "Add default mail aliases:" and "Mail server is backup MX:" boxes unchecked. All domains you add should have either an A record or MX record in DNS in order for PostfixAdmin to consider them valid. Add any other domains you need. Only add domains that will store mail locally (we will talk about relay domains later). Now click on "New Admin" and add your email address and a strong password. You are not adding a mailbox here, you are adding yourself as an administrator. Once you are added, you need to promote yourself to a Super admin. To do so, click "Admin List", edit your login and check the "Super admin" checkbox. You do not need to select any domains when you are a Super admin. Only select a domain (or domains) when adding a normal admin. Now Logout and log back in using your user name.

Please delete admin@domain.tld otherwise the whole world knows your Super admin login. Only Super admins have access to the /admin page. You can add one or more 'normal' admins at this time if you like. You actually need to add an additional normal admin login for yourself that you will use on a day to day basis. Normal admins get a different screen. The https://msa.example.com/postFixadminx/ will be used by normal administrators and access to this URL will be controlled by IP address of the client and the user name and password that is assigned to the administrator by us (using the tools at https://msa.example.com/postFixadminx/admin). Users can change their forwarding information and password at https://msa.example.com/postFixadminx/users; however, they will not need to once we add a SquirrelMail plugin. That's all we'll do here for the moment, but leave the current page open. Return to the PuTTY screen and rename setup.php:
cd /var/www/postFixadminx
mv setup.php setup.php.txt


Back at the browser window you will notice a link to Return to https://msa.example.com/postFixadminx. Clicking on this should bring you to the normal admin page where you (and possibly other domain admins) would log in to manage your domain(s). The first thing you should do is Add Mailbox for yourself. The "Active:" and "Create mailbox:" check boxes should of course be checked. Notice that Username: is only the local part; you choose the @domain from the drop down box. Create the username in lower case. This is your IMAP account. It is imperative that our maildirmake.sh script runs correctly when a mailbox is created in postfixadmin, otherwise Postfix will accept the message but will not be able to deliver it to a mailbox. Check that a mailbox exists, and a squirrelmail profile was created:
ls -l /var/vmail/example.com
ls -l /var/lib/squirrelmail/data


Note that if you delete a mailbox from postfixadmin, as a safety precaution we will not automatically delete the user's maildir (or mail). You will have to manually remove it. You should add another regular user "test@example.com" to use when you need to test sending and receiving messages as a normal user (not related to any administrator accounts). At this point we still need to configure Postfix to send mail to our virtual mailboxes using the information stored in the postfixadmin databases. Begin by downloading and modifying Postfix data access configuration files:
cd /etc/postfix
wget http://www200.pair.com/mecham/spam/mysql_virtual_alias_maps.cf
wget http://www200.pair.com/mecham/spam/mysql_virtual_domains_maps.cf
wget http://www200.pair.com/mecham/spam/mysql_virtual_mailbox_maps.cf
sed -i 's/password = postfix/password = pfix_password/' mysql_virtual_alias_maps.cf
sed -i 's/password = postfix/password = pfix_password/' mysql_virtual_domains_maps.cf
sed -i 's/password = postfix/password = pfix_password/' mysql_virtual_mailbox_maps.cf
chmod 640 mysql_*
chown root:postfix mysql_*


We need to remove our domain name from $mydestination because our domain will soon be listed as a virtual mailbox domain - and you cannot have a domain in more than one address class:
cp /etc/postfix/main.cf /etc/postfix/main.cf-domain
postconf -e "mydestination = msa.example.com, localhost.example.com, localhost"


Now tell Postfix to use our MySQL data files (and maildrop - which still needs configuration):
touch /etc/postfix/virtual
postmap /etc/postfix/virtual
postconf -e "virtual_minimum_uid = 6060"
postconf -e "virtual_gid_maps = static:6060"
postconf -e "virtual_uid_maps = static:6060"
postconf -e "virtual_alias_maps = proxy:mysql:/etc/postfix/mysql_virtual_alias_maps.cf, hash:/etc/postfix/virtual"
postconf -e "virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql_virtual_domains_maps.cf"
postconf -e "virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf"
postconf -e "virtual_transport = maildrop"
postconf -e "virtual_mailbox_base = /var/vmail/"
postconf -e "maildrop_destination_concurrency_limit = 2"
postconf -e "maildrop_destination_recipient_limit = 1"


Note that I use proxy:mysql: here (proxymap(8)). When proxymap(8) is used, changes to the MySQL tables may not be recognized immediately. During testing you may want to remove proxy: because it may cause frustration and confusion. Alternately, reload Postfix so changes are recognized sooner.

To configure maildrop, first get a new maildroprc file from me that contains instructions to deliver spam to the user's Spam folder:
cd /etc
mv maildroprc maildroprc-old
wget http://www200.pair.com/mecham/spam/maildroprc.txt
cp maildroprc.txt maildroprc
touch /var/log/maildroprc.log
chown vmail:vmail /var/log/maildroprc.log
cd /etc/logrotate.d/
wget http://www200.pair.com/mecham/spam/maildrop.logrotate.txt
mv maildrop.logrotate.txt maildrop


Now we need to edit the maildrop entry in master.cf. We will also make a backup of the original master.cf:
cp -i /etc/postfix/master.cf /etc/postfix/master.cf-24jul2007
vi /etc/postfix/master.cf


Locate the current maildrop transport and comment it out (as shown) then insert the new maildrop transport as shown:
#maildrop  unix  -       n       n       -       -       pipe
#  flags=ODRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
  
maildrop  unix  -       n       n       -       -       pipe
  flags=ODRhu user=vmail:daemon argv=/usr/bin/maildrop -w 90 -d ${user}@${nexthop}
  ${extension} ${recipient} ${user} ${nexthop}
Then reload Postfix:
postfix stop
postfix start


You should get a message that files differ; run LINUX2 to correct that. At this point, since we are sending mail to maildrop, maildrop also needs to read the MySQL data in order to determine the relationship between user@example.com and the maildir where mail is supposed to go for that user. Fortunately, both Courier and maildrop can use the same configuration file to store the settings. This file is /etc/courier/authmysqlrc. We need to make quite a few changes to this file to get it to work in our current environment, so rather than edit it, get a new one from me. Note that tabs must be used to separate the variable and the value. Also, read through this file to get an idea of what it contains:
cd /etc/courier
mv authmysqlrc authmysqlrc~
wget http://www200.pair.com/mecham/spam/authmysqlrc.txt
mv authmysqlrc.txt authmysqlrc
sed -i "s/MYSQL_PASSWORD\tpostfix/MYSQL_PASSWORD\tpfix_password/" authmysqlrc
chown daemon:daemon authmysqlrc
chmod 660 authmysqlrc


You also need to tell authdaemond to use the authmysqlrc file we just modified. We will use data in our MySQL postfix database to authenticate users for IMAP, POP and SASL. For remote clients to send mail we will use SASL with TLS. We can optionally use CRAM-MD5 for those clients (like my old version of The Bat!) that seem to have a broken TLS implementation. At least the password will be encrypted during its trip across the wire:
sed -i 's/authmodulelist="authpam"/authmodulelist="authmysql"/' authdaemonrc
/etc/init.d/courier-authdaemon restart


We will enable CRAM-MD5 login mechanism for imapd (port 143):
cp -ip /etc/courier/imapd /etc/courier/imapd~
sed -i 's/SORT QUOTA IDLE/SORT QUOTA AUTH=CRAM-MD5 IDLE/' /etc/courier/imapd


Let's simply start off clean, we need to make certain stuff works after a reboot anyway:
reboot
exit


Once the system comes back up:
tail -f /var/log/mail.log

Now we will send a message through the system to see if it lands in our maildir. You should already have a MUA set up to use this server as its outgoing server. You should also now be able to configure it to connect to the IMAP server using your username (full email address) and password. Assuming you have successfully created a maildir for yourself, send a message to yourself and see if you get it. Tail the mail.log file as the message goes through. Also: grep fatal /var/log/mail.log
Success should look like:

Jun 10 11:21:06 msa postfix/pipe[11513]: 0FBC5240C2: to=<garyv@example.com>, relay=maildrop, delay=0.13, delays=0.07/0.02/0/0.04, dsn=2.0.0, status=sent (delivered via maildrop service)

If you have an error, you must fix it before you continue. We have made a lot of changes to a lot of files. It is certainly possible something happened along the way that would prevent proper delivery of a message. You should have an understanding of the files involved. You just have to find the incorrect setting(s). Some familiarity with Postfix would really be handy. Basic stuff like familiarity with the mailq, postsuper, qshape and postqueue commands. Also remember that you have phpMyAdmin to browse the database (and possibly make manual changes). You should browse the postfix database to get familiar with the structure of the data. You will also want to set up the IMAP account for the test@example.com user and send a message to that address.
ls -al /var/vmail/example.com/test/new

cat /var/log/maildroprc.log


If you can deliver mail to users, it would be a good idea to familiarize yourself with PostfixAdmin at this time. Add some aliases, add some domains. Play with the software. Postfix will no longer use /etc/aliases for our virtual domains so you will need to make aliases (or mailboxes) for root, abuse, postmaster, webmaster and logcheck @example.com. If you fail to make aliases or mailboxes for recipients of system generated mail, maildrop will bounce the messages and complain with an 'Invalid user specified.' error. Set up your MUA to retrieve mail from the mailserver via IMAP SSL on port 993. If you must use POP3, use POP3 SSL on port 995. POP3 clients will only be able to retrieve mail from the /new folder which means they will never see their Spam folder unless they also use SquirrelMail. If you must use standard POP (110) or IMAP (143), configure the client to use TLS (if it's an option - some clients use it automatically). Some clients may wish to use CRAM-MD5 to authenticate to port 110 or 143. If so, you will have to fire up phpMyAdmin and place a cleartext password in the 'clear' field for those users. Hopefully you are using my database schema with the 'clear' field added. If not, it's likely maildrop will think every user is invalid. Install the CA certificate we created earlier on the test client if you have not already done so. Not having the root certificate properly installed will cause all kinds of grief.

If you need to debug pop3d/imapd/pop3d-ssl/imapd-ssl, edit those files in the /etc/courier directory and add DEBUG_LOGIN=2. Then of course restart any of those services as needed. This will give more details in mail.log. Also check /var/log/auth.log:
/etc/init.d/courier-pop restart
/etc/init.d/courier-pop-ssl restart
/etc/init.d/courier-imap restart
/etc/init.d/courier-imap-ssl restart

There are three (contributed) scripts that come with PostfixAdmin in the ADDITIONS directory that are used to delete orphaned maildirs. These are mailboxes you deleted in PostfixAdmin but the files remain on the system. As mentioned earlier, I do not automatically delete maildirs when a user is removed. I would leave orphaned files alone for some length of time. One of the provided scripts would delete all your mail if you let it. That can't be good. Of the other two, cleanupdirs.pl appears to be Ok but I'm still not going to allow it do delete maildirs; I'm only going to use it to report orphaned ones. I'm also going to rename it maildircheck.
cp -i /var/www/postFixadminx/ADDITIONS/cleanupdirs.pl /usr/sbin/maildircheck

touch /var/log/maildircheck.log
sed -i "s|/home/vmail|/var/vmail|" /usr/sbin/maildircheck
sed -i "s/removed_maildirs.log/maildircheck.log/" /usr/sbin/maildircheck
sed -i "s/someuser/postfix/" /usr/sbin/maildircheck
sed -i "s/somepass/pfix_password/" /usr/sbin/maildircheck
sed -i "s/      rmtree/#     rmtree/" /usr/sbin/maildircheck
sed -i "s/'\$to_delete'/\$to_delete/" /usr/sbin/maildircheck
sed -i "s/Need to delete/Orphaned/" /usr/sbin/maildircheck
chmod 700 /usr/sbin/maildircheck

cd /etc/logrotate.d
wget http://www200.pair.com/mecham/spam/maildircheck.txt
mv maildircheck.txt maildircheck


To test, you need to delete a test user via the PostfixAdmin interface. Then run:
maildircheck

If we deleted test@example.com, look and see (and make sure) that the mail directory was NOT deleted, for example, run ls -l /var/vmail/example.com/test . Then add the user back in. If you actually wanted to use this script to delete the directories, you would have to uncomment the 'rmtree' line. I hope the script works and you don't end up deleting every mailbox on the system.

Now I have an optional script that will automatically delete messages left in each user's Spam folder that is older than 24 days. You could test it (at some point in the future) by temporarily modifying the number of days (-mtime 0 = 1 day).
cd /etc/cron.daily
wget http://www200.pair.com/mecham/spam/rmmailboxspam.txt
mv rmmailboxspam.txt rmmailboxspam
chmod +x rmmailboxspam



Configure SASL and TLS

Index Top Bottom
vi /etc/postfix/sasl/smtpd.conf

and insert the following:
pwcheck_method: authdaemond
log_level: 3
mech_list: PLAIN LOGIN CRAM-MD5
authdaemond_path: /var/run/courier/authdaemon/socket
auxprop_plugin: sql
sql_hostnames: 127.0.0.1
sql_user: postfix
sql_passwd: pfix_password
sql_database: postfix
sql_select: select clear from mailbox where username = '%u@%r'


The first three lines will authenticate against encrypted passwords in the 'password' field of the mailbox table in the postfix database (when a client and the server use PLAIN or LOGIN). The remaining lines are for CRAM-MD5 logins that will instead look up the cleartext password from the 'clear' field. Look in /var/log/auth.log for error messages. I reduce the log_level: to 0 when done testing. Passwords you enter in PostfixAdmin are encrypted but you will have to manually add any cleartext passwords. This can be done with an SQL statement or via the phpMyAdmin interface. The cleartext passwords do not have the be the same as the encrypted passwords - the client simply has to use the correct password for the chosen mechanism.

Make sure we are not using saslauthd (don't worry if /etc/init.d/saslauthd does not exist):
sed -i 's/START=yes/START=no/' /etc/default/saslauthd
/etc/init.d/saslauthd stop


Since Debian runs Postfix chrooted, Postfix will need to find /var/run/courier/authdaemon/socket in the chroot jail. We will do this by making a hard link to the existing file:
mkdir -p /var/spool/postfix/var/run/courier/authdaemon
ln /var/run/courier/authdaemon/socket /var/spool/postfix/var/run/courier/authdaemon/socket
chown -R daemon:daemon /var/spool/postfix/var/run/courier
chmod 755 /var/run/courier/authdaemon


We have to recreate this link to 'socket' prior to Postfix starting up so we will modify the init script:
vi /etc/init.d/postfix

and just after   # Make sure that the chroot environment is set up correctly. (around line 45) insert the following:
ln -f /var/run/courier/authdaemon/socket /var/spool/postfix/var/run/courier/authdaemon/socket

Now tell Postfix to use SASL (we make a backup copy of main.cf should you need to refer to it):
cp -i /etc/postfix/main.cf /etc/postfix/main.cf-before-sasl
postconf -e "broken_sasl_auth_clients = yes"
postconf -e "smtpd_sasl_auth_enable = yes"
postconf -e "smtpd_sasl_local_domain = \$myhostname"
postconf -e "smtpd_sasl_security_options = noanonymous"
postconf -e "smtpd_sasl_authenticated_header = yes"
postconf -e "smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination"
/etc/init.d/postfix restart


If SASL auth stops working with "warning: SASL authentication failure: cannot connect to Courier authdaemond: Connection refused", a likely cause is Postfix can no longer write to the socket (due to running chrooted). Restarting postfix with the modified init script may solve the problem.
/etc/init.d/postfix restart

Once our SASL/TLS configuration is complete (we still have to modify master.cf before it is), you should experiment with SASL and TLS. To help debug (if necessary) you can place "debug_peer_list=666.666.666.666" (the IP of the client sending the messages) and/or "smtpd_tls_loglevel=3" (read this) in main.cf. Remove those settings when you are satisfied. Configure an Outlook Express IMAP account to require authentication and use SMTPS (AKA SSMTP) port 465 for outgoing, and IMAPS (secure IMAP) port 993 for incoming. Similar to this. Most other clients will use 465 also. Clients that can't use a dedicated TLS port (Postfix offers this via smtpd_tls_wrappermode=yes) may use port 4650 and instead use STARTTLS. Port 587 will be used for clients unable to get TLS working and will instead use CRAM-MD5 to encrypt the cleartext password. There is an issue with Mozilla Thunderbird. It tries to use CRAM-MD5 before it tries PLAIN. This will result in a "SASL authentication failure: empty secret" warning unless you enter a cleartext password for these clients. If you don't wish to do that, you can either fix Thunderbird, or not use CRAM-MD5. To fix Thunderbird, go to Tools->Options->Advanced->General->Config Editor and then double click on mail.smtpserver.default.trySecAuth (which is set to true by default) in order to set it to false.

While we are editing master.cf we will also disable address rewriting on the three ports. We will wait until after amavisd-new has processed a message before any address rewriting takes place. You may want to use the WinSCP editor for this. You want to replace everything between the two grayed out lines:
vi /etc/postfix/master.cf
smtp      inet  n       -       -       -       -       smtpd
  -o smtpd_use_tls=no
  -o smtpd_sasl_auth_enable=no
# -o receive_override_options=no_address_mappings
# If they want to relay, make them use port 587 (submission) or port 465 (smtps)
# If using submission port, configure client to use CRAM-MD5
submission inet n       -       -       -       -       smtpd
  -o smtpd_use_tls=no
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o receive_override_options=no_address_mappings  
# Outlook and OE (and many others) expect smtpd_tls_wrappermode,
# so have them submit here (port 465):
smtps     inet  n       -       -       -       -       smtpd
  -o smtpd_enforce_tls=yes
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o receive_override_options=no_address_mappings
# We will use port 4650 for clients that use STARTTLS:
4650     inet  n       -       -       -       -       smtpd
  -o smtpd_enforce_tls=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o receive_override_options=no_address_mappings
#628      inet  n       -       -       -       -       qmqpd
Then of course:
/etc/init.d/postfix restart

FYI, at this point output from 'postconf -n' looks like:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
inet_interfaces = all
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
mydestination = msa.example.com, localhost.example.com, localhost
mydomain = example.com
myhostname = msa.example.com
mynetworks = 127.0.0.0/8
myorigin = example.com
recipient_delimiter = +
relayhost =
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_authenticated_header = yes
smtpd_sasl_local_domain = $myhostname
smtpd_sasl_security_options = noanonymous
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.example.com.pem
smtpd_tls_cert_file = /etc/postfix/ssl/cert.msa.example.com.pem
smtpd_tls_key_file = /etc/postfix/ssl/privkey.msa.example.com.pem
smtpd_tls_received_header = yes
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtpd_use_tls = yes
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf, hash:/etc/postfix/virtual
virtual_gid_maps = static:6060
virtual_mailbox_base = /var/vmail/
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_minimum_uid = 6060
virtual_transport = maildrop
virtual_uid_maps = static:6060
Please note that 'postconf -n' does not show every setting we have in main.cf.


Install and configure amavisd-new

Index Top Bottom
Here we install amavisd-new, SpamAssassin and ClamAV, then add the clamav user to the amavis group. We update SpamAssassin's rules. Then we enable spam and virus scanning in amavisd-new:
apt-get update

apt-get install amavisd-new spamassassin razor pyzor lha apt-listchanges nomarch cabextract pax p7zip

apt-get install clamav clamav-daemon clamav-freshclam

apt-get install arj libio-string-perl libhtml-format-perl libmail-spf-query-perl libnet-dns-perl unrar

unrar (rar) is not free. See http://www.rarsoft.com/index.htm

gpasswd -a clamav amavis
/etc/init.d/clamav-daemon stop
freshclam
/etc/init.d/clamav-daemon start

sa-update

cd /etc/amavis/conf.d/
sed -i 's/#@bypass_virus_/@bypass_virus_/' 15-content_filter_mode
sed -i 's/#   \\%bypass_vi/   \\%bypass_vi/' 15-content_filter_mode
sed -i 's/#@bypass_spam_/@bypass_spam_/' 15-content_filter_mode
sed -i 's/#   \\%bypass_s/   \\%bypass_s/' 15-content_filter_mode
cat 15-content_filter_mode
amavisd-new reload


Note: during the time amavisd-new is restarting, mail cannot be delivered to it. Also note that amavisd-new may not be able to use the UNIX socket at /var/run/clamav/clamd.ctl until clamd has fully loaded the virus definition database - which can take minutes. Once this server has mail flowing through it, during the time amavisd-new is reloading Postfix may complain "connect to localhost[127.0.0.1]: Connection refused". Postfix will defer this mail (for about 15 minutes). To speed things up, an impatient person may run 'postfix flush' to flush the deferred queue, but I would not.

We will install a script that runs sa-update daily:
cd /usr/sbin
wget http://www200.pair.com/mecham/spam/sa-update1.sh.txt
mv sa-update1.sh.txt sa-update.sh
chmod +x sa-update.sh
sa-update.sh


And apply a couple small patches to amavisd-new:
cd /usr/sbin
wget http://www200.pair.com/mecham/spam/amavisd-new-trim-whitespace.patch.txt
patch amavisd-new <amavisd-new-trim-whitespace.patch.txt
rm amavisd-new-trim-whitespace.patch.txt
wget http://www200.pair.com/mecham/spam/amavisd-new-trim-whitespace.patch2.txt
patch amavisd-new <amavisd-new-trim-whitespace.patch2.txt
rm amavisd-new-trim-whitespace.patch2.txt


You only need to run this script once a day. Place an entry in your crontab (on the first available blank line):
crontab -e

Replace MM with a number between 0 and 59 and HH with a number between 0 and 23:
MM HH * * * /usr/sbin/sa-update.sh

Now we reinstall clamav from Volatile (you would use this to upgrade to new versions):
apt-get -t etch install clamav clamav-daemon clamav-freshclam

Now vi /etc/amavis/conf.d/50-user and insert the text below in the middle of the file (must be between "use strict;" and "1;"). You may prefer the WinSCP editor since vim will tend to comment out this text when you paste it in. If you are still in the editor since the last edit, you may need to hit the refresh icon in order to see the /etc/amavis directory. Edit @local_domains_maps and include all your domains there. Also take a look at @mynetworks to see if you need to modify it. You will probably want to temporarily leave your network out of @mynetworks during testing (so you can send spam to test recipients):

# nice to have $log_level (1-5) available:
$log_level = 0;

# If sender matches ACL, turn debugging fully up, just for this one message
#@debug_sender_maps = ( ["test\@$mydomain"] );

# explicitly set $mydomain and $myhostname:
$mydomain = 'example.com';
$myhostname = 'msa.example.com';

# Set number of processes. Rough guide for dual processor, 1GB = 6, 2GB = 12, 4GB = 24
# you MUST also change maxproc for the smtp-amavis transport to match this number, e.g:
# smtp-amavis unix -      -       n       -       6  smtp
$max_servers = 6;

# We discard (and quarantine) viruses, discard (and quarantine) spam (>= kill_level), 
# bounce (and quarantine) banned files and pass bad headers:
$final_virus_destiny      = D_DISCARD;
$final_banned_destiny     = D_BOUNCE;
$final_spam_destiny       = D_DISCARD;
$final_bad_header_destiny = D_PASS;

# don't quarantine bad headers (no need since we pass them all):
$bad_header_quarantine_to = undef;

# We use plus addressing to place spam in user's Spam folder:
$recipient_delimiter = '+';

# Spam gets the Subject line prepended with:
$sa_spam_subject_tag = 'Spam> ';

# We tag all headers (for 'local' domains) with X-Spam info:
$sa_tag_level_deflt = undef;

# This is the system default spam tag level that will be overridden by user's preferences in MySQL
$sa_tag2_level_deflt = 6.31;

## For relay domains not set up in MySQL you can create a static domain wide (or individual) map: 
#@spam_tag2_level_maps = (
#  { 'postmaster@example.net' => 99.0,
#    '.example.net' => 8.0,
#    '.example.org' => 6.0 },
#  \$sa_tag2_level_deflt,   # catchall default
#);

# The default is to not quarantine any spam (outside of what users get in their Spam folder), 
# so set default kill_level high. Users can choose their own kill_level however. kill_level
# will trigger quarantining (to MailZu).
$sa_kill_level_deflt = 9999;

## Once again, relay domains may want something different:
#@spam_kill_level_maps = (
#  { 'postmaster@example.net' => 99.0,
#    '.example.net' => 8.0,
#    '.example.org' => 10.0 },
#  \$sa_kill_level_deflt,   # catchall default
#);

## And some relay domains may wish to quarantine up to a certain level, then discard:
#@spam_quarantine_cutoff_level_maps = (
#  { '.example.net' => 20.5,   
#    '.example.org' => 25 },
#  \$sa_quarantine_cutoff_level,   # catchall default (currently undef)
#);

# We will quarantine viruses to /var/lib/amavis/virusmails (the default).
# We will use a cron job to automatically delete these files older than 14 days from the quarantine.
# We can use amavisd-release or MailZu to release quarantined messages. We warn the recipients
# and expect them to contact us (via the MailZu interface) if they need a banned file released.
# Each domain can have their own administrators.
@virus_admin_maps = ({
    '.example.com' => 'postmaster@example.com',
    '.example.net' => 'postmaster@example.net',
    '.' => 'postmaster@example.com',
    });
@banned_admin_maps = ({
    '.example.com' => 'postmaster@example.com',
    '.example.net' => 'postmaster@example.net',
    '.' => 'postmaster@example.com',
    });
$warnbannedrecip = 1;
$defang_banned = 1;

# recipient's local address(es) will be rewritten to user+spam when spam exceeds tag2_level
# and as a result will be delivered to their Spam folder (thanks to maildrop)
@addr_extension_spam_maps = ('spam');

# list domains in an external file (created by local_domains.sh script):
@local_domains_maps = ( read_hash("$MYHOME/local_domains") );

# Since we configured SQL, we can use penpals feature:
$penpals_bonus_score = 5;
$penpals_threshold_low = 1;
$penpals_threshold_high = 18;

# We are going to create policy banks that will notify us of internally created spam
# but also let banned files out (provided they are compressed).

@mynetworks = qw( 127.0.0.0/8 [::1] [FE80::]/10 [FEC0::]/10
                   10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 );

$inet_socket_port = [10024, 10026]; 
## If using Mailzu, use this instead:
#$inet_socket_port = [10024, 10026, 9998]; 

$inet_socket_bind = '127.0.0.1';
## If using Mailzu, use this instead:
#$inet_socket_bind = undef;

## Interface to MailZu
#$interface_policy{'9998'} = 'MAILZU';
#$policy_bank{'MAILZU'} = {
#    protocol => 'AM.PDP',
#    inet_acl => [qw( 127.0.0.1 [::1] 111.111.111.111 )],
#};

# We create a custom set of banned rules for the MYNETS and TRUSTED policy
# banks. See also the 'DEFAULT' $banned_filename_re settings in 20-debian_defaults
%banned_rules = (
 'BLOCK_EXE' =>  new_RE(
    # block double extensions in names:
      qr'\.[^./]*\.(exe|vbs|pif|scr|bat|cmd|com|cpl|dll)\.?$'i,
    # allow any name or type (except viruses) within an archive:
      [ qr'^\.(Z|gz|bz2|rpm|cpio|tar|zip|rar|arc|arj|zoo)$' => 0],
    # blocks MS executable file(1) types, unless allowed above:
      qr'^\.(exe|exe-ms)$',
    ),
 'DEFAULT' => $banned_filename_re,
);				   

$policy_bank{'MYNETS'} = {  # mail originating from @mynetworks
  spam_admin_maps  => ["postmaster\@$mydomain"], # alert of internal spam
  final_spam_destiny => D_BOUNCE, # so the sender knows they are a spammer  
  spam_kill_level_maps => [10.0],
  spam_dsn_cutoff_level_maps => [9999],
  banned_filename_maps => ['BLOCK_EXE'],
};

$interface_policy{'10026'} = 'TRUSTED';
$policy_bank{'TRUSTED'} = {  # mail originating from trusted senders
  spam_admin_maps  => ["postmaster\@$mydomain"], # alert of internal spam
  final_spam_destiny => D_BOUNCE, # so the sender knows they are a spammer
  spam_kill_level_maps => [10.0],
  spam_dsn_cutoff_level_maps => [9999],
  banned_filename_maps => ['BLOCK_EXE'],
};

# Here we set up access to MySQL data:
@lookup_sql_dsn = ( ['DBI:mysql:amavis:localhost', 'amavis', 'amavis_password'] );
@storage_sql_dsn = @lookup_sql_dsn;

# If using MailZu, store banned files and spam to MySQL if you want to give users the
# ability to read those messages in the MailZu interface:
#$banned_files_quarantine_method = 'sql:';
#$spam_quarantine_method         = 'sql:';

# If using MailZu and you do not wish to quarantine spam to MySQL but instead want to
# quarantine to /var/lib/amavis/virusmails, MailZu cannot have spam messages
# compressed (which is the default), so you would have to change from the default to this:
#$spam_quarantine_method         = 'local:spam-%m';

# Note: If you quarantine items locally, you would also need to create a script delete
# old quarantined items. Look to /etc/cron.daily/rmvirusquar for an example

# required because we set msgs.time_iso to type TIMESTAMP (required by MailZu)
$timestamp_fmt_mysql = 1;

# specific to the amavisnewsql SquirrelMail plugin
$sql_select_white_black_list = 'SELECT wb FROM wblist'.
  ' WHERE (rid=?) AND (wblist.email IN (%k))'.
  ' ORDER BY wblist.priority DESC';

#----------------------------------------------------------
Now we will create the MySQL schema for amavisd-new. This schema is a combination of the recommended amavisd-new schema, and the schema provided with the amavisnewsql SquirrelMail Plugin:
cd
wget http://www200.pair.com/mecham/spam/amavis-sqmail.sql.txt
sed -i "s/BY 'password'/BY 'amavis_password'/" amavis-sqmail.sql.txt
chmod 600 amavis-sqmail.sql.txt
mysql -u root -p < amavis-sqmail.sql.txt


You would have been prompted for roots_password. Secure 50-user from prying eyes (to protect the MySQL password):
chmod 640 /etc/amavis/conf.d/50-user

We are going to create a script that will pull a list of our domains from a PostfixAdmin table:
vi /usr/sbin/local_domains.sh

Insert the following (this is two lines - line 2 may wrap)
#!/bin/bash
mysql -upostfix -ppfix_password postfix -B -N -e "select concat('.',domain) from domain" >/var/lib/amavis/local_domains


Save the file. Then:
chmod 700 /usr/sbin/local_domains.sh
local_domains.sh
cat /var/lib/amavis/local_domains


Our domains should be listed in the file. We will add this script to PostfixAdmin so it's updated every time we add or remove domains. We need to add another entry to /etc/sudoers so www-data can run this script:
visudo

and insert at the bottom (noting once again the hostname of the server):
www-data msa=NOPASSWD: /usr/sbin/local_domains.sh

Now patch PostfixAdmin so it uses this script:
cd /var/www/postFixadminx/admin
cp edit-domain.php edit-domain.php~
wget http://www200.pair.com/mecham/spam/domain.patch.txt
patch -p0 < domain.patch.txt
chown root:www-data *


You should spend a minute to convince yourself this works. Remove /var/lib/amavis/local_domains and log into PostfixAdmin and edit a domain (you have to log in as the super-user in order to edit domains). Insure /var/lib/amavis/local_domains was created as expected, then:
amavisd-new reload

Install a couple maintenance scripts to prevent the amavis database from growing forever (messages over 24 days are deleted). If it grows forever, you or I made a mistake here:
cd /usr/sbin
wget http://www200.pair.com/mecham/spam/trim-amavis-msgs.txt
mv trim-amavis-msgs.txt trim-amavis-msgs
sed -i 's/Passw0rd/amavis_password/' trim-amavis-msgs
chmod 750 trim-amavis-msgs
cd /etc
wget http://www200.pair.com/mecham/spam/trim-amavis.sql.txt
mv trim-amavis.sql.txt trim-amavis.sql
cd /etc/cron.daily/
wget http://www200.pair.com/mecham/spam/trim-amavis.txt
mv trim-amavis.txt ztrim-amavis
sed -i 's/password/amavis_password/' ztrim-amavis
chmod 750 ztrim-amavis
./ztrim-amavis


Now configure postfix to use amavisd-new. I will show NEW changes to master.cf in red. Don't forget to match maxproc for the smtp-amavis transport to $max_servers. Also notice there are different port number involved for the content_filter overrides. You may also want to use the WinSCP editor here:
vi /etc/postfix/master.cf
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
  -o smtpd_use_tls=no
  -o smtpd_sasl_auth_enable=no
  -o content_filter=smtp-amavis:[127.0.0.1]:10024
# -o receive_override_options=no_address_mappings
# If they want to relay, make them use port 587 (submission) or port 465 (smtps)
# If using submission port, configure client to use CRAM-MD5
submission inet n       -       -       -       -       smtpd
  -o smtpd_use_tls=no
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o content_filter=smtp-amavis:[127.0.0.1]:10026
# -o receive_override_options=no_address_mappings
# Outlook and OE (and many others) expect smtpd_tls_wrappermode,
# so have them submit here (PORT 465):
smtps     inet  n       -       -       -       -       smtpd
  -o smtpd_enforce_tls=yes
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o content_filter=smtp-amavis:[127.0.0.1]:10026
# -o receive_override_options=no_address_mappings
# We will use port 4650 for clients that use STARTTLS:
4650     inet  n       -       -       -       -       smtpd
  -o smtpd_enforce_tls=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o content_filter=smtp-amavis:[127.0.0.1]:10026
# -o receive_override_options=no_address_mappings
#628      inet  n       -       -       -       -       qmqpd
pickup    fifo  n       -       -       60      1       pickup
  -o content_filter=

[... other stuff is here, but does not need editing ...]

# Insert at the bottom and adjust maxproc from 6 if needed:
#
smtp-amavis unix -    -    n    -    6    smtp
    -o smtp_data_done_timeout=1200
    -o smtp_send_xforward_command=yes
    -o disable_dns_lookups=yes

127.0.0.1:10025 inet n    -    n    -    -    smtpd
    -o content_filter=
    -o local_recipient_maps=
    -o relay_recipient_maps=
    -o smtpd_restriction_classes=
    -o smtpd_delay_reject=no
    -o smtpd_client_restrictions=permit_mynetworks,reject
    -o smtpd_helo_restrictions=
    -o smtpd_sender_restrictions=
    -o smtpd_recipient_restrictions=permit_mynetworks,reject
    -o smtpd_data_restrictions=reject_unauth_pipelining
    -o smtpd_end_of_data_restrictions=
    -o mynetworks=127.0.0.0/8
    -o smtpd_error_sleep_time=0
    -o smtpd_soft_error_limit=1001
    -o smtpd_hard_error_limit=1000
    -o smtpd_client_connection_count_limit=0
    -o smtpd_client_connection_rate_limit=0
    -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks
When finished editing:
postconf -e "recipient_delimiter = +"
/etc/init.d/postfix restart


Configure pyzor (to use a mirror):
pyzor discover
su amavis -c 'pyzor discover'
echo "82.94.255.100:24441" > /var/lib/amavis/.pyzor/servers
echo "82.94.255.100:24441" > /root/.pyzor/servers
su amavis -c 'pyzor ping'


Pyzor Ping should show 'OK'. If not, then it's possible your firewall is blocking udp replies from 82.94.255.100. We need amavisd-nanny which can be used as a diagnostic program and amavisd-release (for amavisd-new version 2.4.2) which can be used to release quarantined messages:
cd /usr/local/src
wget http://www.ijs.si/software/amavisd/amavisd-new-2.4.2.tar.gz
tar xzf amavisd-new-2.4.2.tar.gz
cp amavisd-new-2.4.2/amavisd-release /usr/sbin
cp amavisd-new-2.4.2/amavisd-nanny /usr/sbin
sed -i 's|/var/amavis/amavisd.sock|/var/run/amavis/amavisd.sock|' /usr/sbin/amavisd-release
sed -i 's|/var/amavis/db|/var/lib/amavis/db|' /usr/sbin/amavisd-nanny


SpamAssassin, by default, will automatically attempt to figure out which Received: headers were inserted by mail servers in your network, and which were not. However, to be safe it's best to manually configure the trust path. The IP addresses listed in internal_networks and trusted_networks should be the IP addresses (or network addresses) of hosts on you network. If you are behind a NAT box, this would include your internal network, your public network and the loopback interface. If mail is relayed to you from a trusted 3rd party (maybe you use something like Postini to filter your mail), then those servers would be added to trusted_networks (but not internal_networks).
vi /etc/spamassassin/local.cf

Here is an example of what should be inserted:
# explicitly set our internal_networks (might be the same or similar to mynetworks)
clear_internal_networks
internal_networks 127/8
internal_networks 222.222.222.222/24
internal_networks 10.10.10.10/24
# add the same to trusted_networks, and possibly other computers/networks whose mail we trust
clear_trusted_networks
trusted_networks 127/8
trusted_networks 222.222.222.222/24
trusted_networks 10.10.10.10/24


Always lint SpamAssassin after modifying or adding files:
spamassassin --lint

Once you have correctly configured these settings:
amavisd-new stop
amavisd-new start
tail -f /var/log/mail.log


Test by sending a message through and observing output from mail.log. It can take between 1 second and 30 seconds (or even longer) to process a message.
If you get clamd errors, /etc/init.d/clamav-daemon stop , wait a moment, /etc/init.d/clamav-daemon start , and wait a minute before continuing.

I quarantine viruses locally for 14 days, then delete them. If you would like to accomplish this task, grab the script from me:
cd /etc/cron.daily
wget http://www200.pair.com/mecham/spam/rmvirusquar.txt
mv rmvirusquar.txt rmvirusquar
chmod +x rmvirusquar
./rmvirusquar



Create Bayes and AWL tables in MySQL

Index Top Bottom
Placing Bayes and AWL data in MySQL will put some load on the MySQL server, but as long as you have been reasonably generous with innodb_buffer_pool_size and innodb_log_file_size you will greatly improve Bayes performance (do these in sections):
cd /etc/spamassassin/
wget http://www200.pair.com/mecham/spam/gv-bayes-awl.sql.txt
sed -i 's/paSSw0rd/amavis_password/' gv-bayes-awl.sql.txt
mysql -u root -p < gv-bayes-awl.sql.txt

Enter roots_password to complete the process.

rm gv-bayes-awl.sql.txt
wget http://www200.pair.com/mecham/spam/local.cf-bayes-awl.txt
cp local.cf local.cf-before-mysql
cat local.cf-bayes-awl.txt local.cf-before-mysql > local.cf
sed -i 's/paSSw0rd/amavis_password/' local.cf
spamassassin --lint
amavisd-new reload

cd
wget http://www200.pair.com/mecham/spam/sample-spam.txt
sa-learn --spam sample-spam.txt
sa-learn --dump magic
spamassassin --lint


It should show our nspam (number of spam) count is 1, and --lint should be clean. We should also create our .spamassassin directory and user_prefs file:
su amavis -c 'spamassassin <sample-spam.txt'

We continue by adding an AWL and bayes_seen maintenance script (watch for errors):
cd /etc
wget http://www200.pair.com/mecham/spam/trim-awl.sql.txt
mv trim-awl.sql.txt trim-awl.sql
cd /usr/sbin
wget http://www200.pair.com/mecham/spam/trim-awl.txt
mv trim-awl.txt trim-awl
chmod +x trim-awl
sed -i 's/paSSw0rd/amavis_password/' trim-awl
cd /etc/cron.weekly/
wget http://www200.pair.com/mecham/spam/trim-sql-awl-weekly.txt
mv trim-sql-awl-weekly.txt trim-sql-awl-weekly
chmod +x trim-sql-awl-weekly
su - amavis /usr/sbin/trim-awl
./trim-sql-awl-weekly


Once again make sure amavisd-new is processing messages. Send at least one test message and then read the headers of the message. It should show X-Spam headers and such. It will not show any BAYES hits yet - it is required that Bayes learns at least 200 ham messages first. I use autolearn (with an occasional manual feeding to sa-learn). I do not cover using other means of feeding spam and ham to SpamAssassin in this HOWTO - see man sa-learn . The SquirrelMail Spam Buttons plugin allows users to mark messages as 'Spam' or 'Not Spam' and feed them to sa-learn as such, but in a site wide database one has to remember that "one man's garbage is another man's treasure" and "too many cooks spoil the pot". Plus, there is the addition server load to consider - sa-learn is CPU intensive.

It would be a good idea to test clamd. After temporarily disabling your desktop AV program I would send a test message through with ONLY the eicar string in the body of the message (absolutely no whitespace before or after the string - it must start and end on the very first line). You can stop amavisd-new and debug it with 'amavisd-new debug' or 'amavisd-new sa-debug' or you can raise $log_level or temporarily set @debug_sender_maps.


Configure and customize SquirrelMail

Index Top Bottom
Tell apache-ssl to use squirrelmail:
echo "Include /etc/squirrelmail/apache.conf" >> /etc/apache-ssl/httpd.conf

I am going to set the SquirrelMail URL to https://msa.example.com/mail/, so:
cd /etc/squirrelmail/
sed -i "s|Alias /squirrelmail|Alias /mail|" apache.conf
sed -i "s|allow from 127.0.0.1|allow from 666.666.666.666|" apache.conf

/etc/init.d/apache-ssl restart


The 'allow from' IP address above is the IP address of your computer (as the mailserver sees it). Download some plugins:
cd /usr/share/squirrelmail/plugins/
wget http://www.squirrelmail.org/plugins/quota_usage-1.3.1-1.2.7.tar.gz
tar xzf quota_usage-1.3.1-1.2.7.tar.gz
cp quota_usage/config.php.sample quota_usage/config.php
wget http://www.squirrelmail.org/plugins/timeout_user-1.1.1-0.5.tar.gz
tar xzf timeout_user-1.1.1-0.5.tar.gz
wget http://www.squirrelmail.org/plugins/compatibility-2.0.7-1.0.tar.gz
tar xzf compatibility-2.0.7-1.0.tar.gz
wget http://www.squirrelmail.org/plugins/amavisnewsql-0.8.0-1.4.tar.gz
tar xzf amavisnewsql-0.8.0-1.4.tar.gz
mkdir /var/lib/amavis/.notstored
chown -R amavis:amavis /var/lib/amavis
sed -i 's/minutes = 120;/minutes = 20;/' timeout_user/config.php
cd amavisnewsql
cp config.php.dist config.php

sed -i 's|pgsql://postgres:@localhost|mysql://amavis:amavis_password@localhost|' config.php
sed -i 's|"yourdomain.com"|"example.com"|' config.php
sed -i 's|use_quarantine"] = true|use_quarantine"] = false|' config.php
sed -i 's|http://webmail.yourdomain.com|https://msa.example.com/mail|' config.php
sed -i 's|noreply@yourdomain.com|noreply@example.com|' config.php
sed -i 's|/htdocs/squirrel/|/usr/share/squirrelmail/|' utils/cleanquarantine.php
sed -i 's|/htdocs/squirrel/|/usr/share/squirrelmail/|' utils/generatedigest.php
sed -i 's|/htdocs/squirrel/|/usr/share/squirrelmail/|' utils/process_bsmtp.php
sed -i 's|/var/virusmails|/var/lib/amavis/virusmails|' utils/process_bsmtp.php
chown -R root:root /usr/share/squirrelmail/plugins/amavisnewsql
chmod 644 *
chmod 755 contrib htmlMimeMail-2.5.1 locale po utils
chmod 640 contrib/*
chmod 640 htmlMimeMail-2.5.1/*
chmod 640 utils/soap/*
chmod 640 utils/*php
chmod 640 utils/*sql
chmod 640 config.php
chown root:www-data config.php


We did some configuration of amavisnewsql. We turned off its (broken) quarantine function (and because it is broken we send spam to either a folder or MailZu). Now we put some sanity constraints on what users can enter for tag2_level and kill_level and modify some of the text that users see. I also add the ability for the users to set spam_quarantine_cutoff_level which gives them the option to discard high scoring spam. New users are added to the database when they log into SquirrelMail and go to Options->SpamAssassin Configuration.
wget http://www200.pair.com/mecham/spam/amavisnewsql.patch1.txt
sed -i 's/host.domain.tld/msa.example.com/' amavisnewsql.patch1.txt
cp -p functions.php functions.php~
cp -p amavisnewsql.class.php amavisnewsql.class.php~
cp -p amavisnewsql.php amavisnewsql.php~
patch -p0 < amavisnewsql.patch1.txt


Now start configuration (hint: enter squ[Tab]). Navigate to the items below from the main menu:
squirrelmail-configure

1. Organization preferences.
 1. Organization Name Widgits Inc.
 7. Provider link https://msa.example.com/mail/

4. General Options
 5. Usernames in Lowercase true
 7. Hide SM attributions true
 10. Allow server thread sort