Dịch vụ sửa máy tính pc laptop máy in - Nạp mực máy in Trường Tín Tphcm
Dịch vụ sửa máy tính pc laptop máy in - Nạp mực máy in Trường Tín Tphcm

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

--
Web Tin Học Trường Tín có bài: Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail Postfix là một MTA (Mail Transport Agent), được viết bởi Wietse Venema khi ông đang làm việc ở trung tâm nghiên cứu T. J. Watson của IBM. Đặc điểm của Postfix: dễ quản lý, nhanh, an toàn…

Quản Trị Mạng – Postfix là một MTA (Mail Transport Agent), được viết bởi Wietse Venema khi ông đang làm việc ở trung tâm nghiên cứu T. J. Watson của IBM. Đặc điểm của Postfix: dễ quản lý, nhanh, an toàn. Chỉ cần một server với hardware thông thường, Postfix có thể chuyển ship hàng triệu email một ngày. Trong bài viết sau chúng tôi sẽ hướng dẫn các bạn cách cài đặt một mail server Postfix cơ bản trên user và domain ảo (tức là user và domain được lưu trong cơ sở dữ liệu MySQL).

> > > Chạy SquirrelMail trên Nginx (LEMP) trong Debian Squeeze/Ubuntu 11.04

Ngoài ra, bài viết sẽ thể hiện qui trình cài đặt và cấu hình Courier (Courier-POP3, Courier-IMAP), từ đấy Courier có thân xác thực cơ sở dữ liệu MySQL mà Postfix sử dụng. Kết quả là máy chủ Postfix có khả năng xác thực SMTP-AUTH , TLS quota (quota không được thành lập trong Postfix theo mặc định, chúng ta sẽ vá Postfix một cách thích hợp). Những mật khẩu sẽ được lưu giữ trong form encrypted của database. Đồng thời chúng tôi sẽ trình bày tới các bạn cách cài đặt Amavisd, SpamAssassin và ClamAV để các email này được quét và kiểm tra spam, virus. Cuối cùng chúng ta sẽ tiến hành cài đặt giao diện webmail SquirrelMail để các user cũng đều có thể đọc và gửi mail, thay đổi password.

Tổng quan

Ưu điểm của một thiết lập “ ảo ” (user và domain ảo trong MySQL database) là nó làm tăng biết bao công suất so với một thiết lập cơ bản dựa theo user hệ thống “ real ”. Với thiết lập ảo, mail server của bạn có thể giải quyết hàng ngàn domain và user. Bên cạnh đó, việc quản trị cũng trở nên dễ dàng hơn bởi bạn chỉ cần xử lý với MySQL database khi thêm user/domain mới hoặc chỉnh sửa những tài khoảng hiện có. Không cần những lệnh postmap để tạo file db, chẳng cần tải lại Postfix… việc quản lý MySQL database cũng có thể thông qua công cụ web như phpMyAdmin (sẽ được cài đặt trong hướng dẫn này). Ưu điểm thứ ba là người sử dụng sẽ được một địa điểm email chính là tên user thay vì một username và một email gây phiền phức.

1. Một số lưu ý

Ở đây chúng tôi sử dụng hệ thống Fedora 15 x86_64, có địa điểm IP tĩnh 192.168.0.100 và hostname server1.example.com . Bạn cần chắc chắn rằng tường lửa và SELinux đều được vô hiệu hóa.

2. Một số ứng dụng cần phải có

Trước tiên chúng ta cần cập nhập các gói có sẵn trên hệ thống:

yum update

Sau đó cài đặt một số ứng dụng cần thiết:

yum groupinstall 'Development Tools'

yum groupinstall 'Development Libraries'

3. Cài đặt Apache, MySQL, phpMyAdmin

Bộ ứng dụng này có thể được cài đồng thời qua một dòng lệnh sau (bao gồm các gói cần thành lập cho Courier-IMAP):

yum install ntp httpd mysql-server php php-mysql php-mbstring rpm-build gcc mysql-devel openssl-devel cyrus-sasl-devel pkgconfig zlib-devel phpMyAdmin pcre-devel openldap-devel postgresql-devel expect libtool-ltdl-devel openldap-servers libtool gdbm-devel pam-devel gamin-devel libidn-devel

4. Cài đặt Courier-IMAP, Courier-Authlib, And Maildrop

Thật không may vì gói rpm chưa được tích hợp sẵn cho Courier-IMAP, Courier-Authlib, và Maildrop. Do đó chúng ta cần thành lập nó để sử dụng. Các gói rpm không nên thành lập với quyền là root , courier-imap sẽ từ chối biên dịch nếu phát giác gói này chạy ở root. Vì vậy chúng tôi sẽ tạo một tài khoản bình thường (ví dụ truongtin ) và gán cho nó một mật khẩu:

useradd -m -s /bin/bash truongtin
passwd truongtin

Sau đó chúng ta sử dụng lệnh sudo để truongtin cũng có thể biên dịch và cài đặt các gói rpm. Nhưng trước tiên cần cấp phép truongtin chạy tất cả những lệnh sử dụng sudo:

visudo

Trong tập tin được mở, tại dòng root ALL=(ALL) ALL thêm 1 dòng tương tự dành cho truongtin bên dưới:

 [...] ## Allow root to run any commands anywhere root ALL=(ALL) ALL truongtin ALL=(ALL) ALL [...] 

Bây giờ là lúc thành lập gói rpm. Đầu tiên trở thành truongtin :

su truongtin

Tiếp theo tạo môi trường xây dựng:

mkdir $HOME/rpm
mkdir $HOME/rpm/SOURCES
mkdir $HOME/rpm/SPECS
mkdir $HOME/rpm/BUILD
mkdir $HOME/rpm/BUILDROOT
mkdir $HOME/rpm/SRPMS
mkdir $HOME/rpm/RPMS
mkdir $HOME/rpm/RPMS/i386
mkdir $HOME/rpm/RPMS/x86_64

echo “%_topdir $HOME/rpm” > > $HOME/.rpmmacros

Tạo thư mục downloads và tải về tập tin nguồn ở đây :

mkdir $HOME/downloads
cd $HOME/downloads

wget https://sourceforge.net/projects/courier/files/authlib/0.63.0/courier-authlib-0.63.0.tar.bz2/download
wget https://sourceforge.net/projects/courier/files/imap/4.9.3/courier-imap-4.9.3.tar.bz2/download
wget https://sourceforge.net/projects/courier/files/maildrop/2.5.4/maildrop-2.5.4.tar.bz2/download

Vẫn ở trong $HOME/downloads , chúng ta thành lập courier-authlib:

sudo rpmbuild -ta courier-authlib-0.63.0.tar.bz2

Sau khi hoàn thành, gói rpm có thể được tìm thấy trong /root/rpmbuild/RPMS/x86_64 ( /root/rpmbuild/RPMS/i386 nếu bạn đang chạy hệ thống i386):

sudo ls -l /root/rpmbuild/RPMS/x86_64

Các gói có sẵn của rpm hiển thị như sau:

 [truongtin@server1 downloads]$ sudo ls -l /root/rpmbuild/RPMS/x86_64 total 520 -rw-r--r-- 1 root root 123448 May 25 18:06 courier-authlib-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 265144 May 25 18:06 courier-authlib-debuginfo-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 34876 May 25 18:06 courier-authlib-devel-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 17448 May 25 18:06 courier-authlib-ldap-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 13808 May 25 18:06 courier-authlib-mysql-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 13020 May 25 18:06 courier-authlib-pgsql-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 8276 May 25 18:06 courier-authlib-pipe-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 34108 May 25 18:06 courier-authlib-userdb-0.63.0-1.fc15.x86_64.rpm [truongtin@server1 downloads]$ 

Chọn một gói bạn muốn, sau đó cài đặt chúng tương tự dưới đây:

sudo rpm -ivh /root/rpmbuild/RPMS/x86_64/courier-authlib-0.63.0-1.fc15.x86_64.rpm /root/rpmbuild/RPMS/x86_64/courier-authlib-mysql-0.63.0-1.fc15.x86_64.rpm /root/rpmbuild/RPMS/x86_64/courier-authlib-devel-0.63.0-1.fc15.x86_64.rpm

Quay trở lại thư mục downloads :

cd $HOME/downloads

Chạy các lệnh sau đây để tạo các thư mục thu nhận yêu cầu/cho phép thay đổi (nếu không vượt qui trình thành lập Courier-Imap sẽ thất bại):

sudo mkdir /var/cache/ccache/tmp
sudo chmod o+rwx /var/cache/ccache/
sudo chmod 777 /var/cache/ccache/tmp

Bây giờ chạy lệnh rpmbuild lần nữa, lưu ý rằng không thông qua sudo bởi trình biên dịch không cấp phép nó chạy như là root.

rpmbuild -ta courier-imap-4.9.3.tar.bz2

Sau đó gói rpm sẽ có tìm thấy trong $HOME/rpm/RPMS/x86_64 ( $HOME/rpm/RPMS/i386 nếu là hệ thống i386):

cd $HOME/rpm/RPMS/x86_64

Chạy lệnh sau:

ls -l

Bạn sẽ nhận được các gói rpm có sẵn:

[truongtin@server1 x86_64]$ ls -l
total 1040
-rw-rw-r– 1 truongtin truongtin 315872 May 25 18:33 courier-imap-4.9.3-1.15.x86_64.rpm
-rw-rw-r– 1 truongtin truongtin 743200 May 25 18:33 courier-imap-debuginfo-4.9.3-1.15.x86_64.rpm
[truongtin@server1 x86_64]$

Cài đặt courier-imap bằng lệnh sau:

sudo rpm -ivh courier-imap-4.9.3-1.15.x86_64.rpm

Quay trở lại thư mục downloads :

cd $HOME/downloads

Chạy lệnh rpmbuild để xây dựng gói maildrop:

sudo rpmbuild -ta maildrop-2.5.4.tar.bz2

Sau đó gói rpm cũng có thể có thể tìm thấy tại /root/rpmbuild/RPMS/x86_64 ( /root/rpmbuild/RPMS/i386 với hệ thống i386).

sudo ls -l /root/rpmbuild/RPMS/x86_64

Các gói rpm có sẵn được liệt kê:

 [truongtin@server1 downloads]$ sudo ls -l /root/rpmbuild/RPMS/x86_64 total 1628 -rw-r--r-- 1 root root 123448 May 25 18:06 courier-authlib-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 265144 May 25 18:06 courier-authlib-debuginfo-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 34876 May 25 18:06 courier-authlib-devel-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 17448 May 25 18:06 courier-authlib-ldap-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 13808 May 25 18:06 courier-authlib-mysql-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 13020 May 25 18:06 courier-authlib-pgsql-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 8276 May 25 18:06 courier-authlib-pipe-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 34108 May 25 18:06 courier-authlib-userdb-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 278520 May 25 18:50 maildrop-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 685672 May 25 18:50 maildrop-debuginfo-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 99924 May 25 18:50 maildrop-devel-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 63968 May 25 18:50 maildrop-man-2.5.4-1.15.x86_64.rpm [truongtin@server1 downloads]$ 

Cài đặt maildrop bằng lệnh sau:

sudo rpm -ivh /root/rpmbuild/RPMS/x86_64/maildrop-2.5.4-1.15.x86_64.rpm

Sau khi biên dịch và cài đặt thành công các gói cần thiết, bạn có thể trở lại root bằng lệnh:

exit

5. Áp dụng bản vá Quota Patch cho Postfix

Chúng ta phải lấy các nguồn Postfix rpm, vá nó với bản vá quota, thành lập một gói Postfix rpm mới và cài đặt nó:

cd /usr/src
wget http://ftp-stud.fht-esslingen.de/pub/Mirrors/fedora/linux/releases/15/Everything/source/SRPMS/postfix-2.8.2-2.fc15.src.rpm
rpm -ivh postfix-2.8.2-2.fc15.src.rpm

Các cảnh báo sau hiện ra, bạn cũng có thể có thể bỏ lỡ nó:

warning: user mockbuild does not exist – using root
warning: group mockbuild does not exist – using root

cd /root/rpmbuild/SOURCES
wget http://vda.sourceforge.net/VDA/postfix-vda-v10-2.8.2.patch
cd /root/rpmbuild/SPECS/

Chúng ta cần sửa lại tập tin postfix.spec:

vi postfix.spec

Và thêm Patch0: po stfix-vda-v10-2.8.2.patch vào đoạn # Patches , thêm %patch0 -p1 -b. vda-v10 vào đoạn %setup -q như sau:

 [...] # Patches Patch0: postfix-vda-v10-2.8.2.patch Patch1: postfix-2.7.0-config.patch Patch2: postfix-2.6.1-files.patch Patch3: postfix-alternatives.patch Patch8: postfix-large-fs.patch Patch9: pflogsumm-1.1.3-datecalc.patch [...] %prep %setup -q # Apply obligatory patches %patch0 -p1 -b. vda-v10 %patch1 -p1 -b. config %patch2 -p1 -b. files %patch3 -p1 -b. alternatives %patch8 -p1 -b. large-fs [...] 

Sau đó thành lập gói Postfix rpm mới với quota và hỗ trợ MySQL:

rpmbuild -ba postfix.spec

Vào thư mục chứa postfix rpm trong /root/rpmbuild/RPMS/x86_64 ( /root/rpmbuild/RPMS/i386 nếu là hệ thống i386):

cd /root/rpmbuild/RPMS/x86_64

Chạy lệnh:

ls -l

Bạn sẽ nhận được những gói có sẵn:

 [root@server1 x86_64]# ls -l total 8308 -rw-r--r-- 1 root root 123528 Jun 20 16:33 courier-authlib-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 265100 Jun 20 16:33 courier-authlib-debuginfo-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 34876 Jun 20 16:33 courier-authlib-devel-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 17452 Jun 20 16:33 courier-authlib-ldap-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 13812 Jun 20 16:33 courier-authlib-mysql-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 13040 Jun 20 16:33 courier-authlib-pgsql-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 8280 Jun 20 16:33 courier-authlib-pipe-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 34144 Jun 20 16:33 courier-authlib-userdb-0.63.0-1.fc15.x86_64.rpm -rw-r--r-- 1 root root 278628 Jun 20 18:29 maildrop-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 685320 Jun 20 18:29 maildrop-debuginfo-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 99920 Jun 20 18:29 maildrop-devel-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 63964 Jun 20 18:29 maildrop-man-2.5.4-1.15.x86_64.rpm -rw-r--r-- 1 root root 2170848 Jun 20 18:40 postfix-2.8.2-2.fc15.x86_64.rpm -rw-r--r-- 1 root root 4599208 Jun 20 18:40 postfix-debuginfo-2.8.2-2.fc15.x86_64.rpm -rw-r--r-- 1 root root 63536 Jun 20 18:40 postfix-perl-scripts-2.8.2-2.fc15.x86_64.rpm [root@server1 x86_64]# 

Chọn một gói bạn muốn và cài đặt như dưới đây:

rpm -ivh postfix-2.8.2-2.fc15.x86_64.rpm


6. Cài đặt password cho MySQL và cấu hình phpMyAdmin

Trước tiên chúng ta khởi động MySQL:

chkconfig –levels 235 mysqld on
/etc/init.d/mysqld start

Sau đó thiết lập passwords MySQL cho tài khoản root:

mysql_secure_installation

 [root@server1 ~]# mysql_secure_installation NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY! In order to log into MySQL to secure it, we'll need the current password for the root user. If you've just installed MySQL, and you haven't set the root password yet, the password will be blank, so you should just press enter here. Enter current password for root (enter for none):   <-- ENTER    OK, successfully used password, moving on... 
Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.
Set root password? [Y/n]
<-- ENTER New password: <-- yourrootsqlpassword Re-enter new password: <-- yourrootsqlpassword Password updated successfully!
Reloading privilege tables..
. .. Success!
By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n]
<-- ENTER . .. Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n]
<-- ENTER . .. Success!
By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed before moving into a production environment.
Remove test database and access to it? [Y/n]
<-- ENTER - Dropping test database...
. .. Success!
- Removing privileges on test database...
. .. Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n]
<-- ENTER . .. Success!
Cleaning up...
All done! If you've completed all of the above steps, your MySQL
installation should now be secure.
Thanks for using MySQL!
[root@server1 ~]#

Tiếp theo chúng ta cấu hình cho phpMyAdmin. Thay đổi Apache để phpMyAdmin cấp phép các kết nối khác (không chỉ từ localhost ) bằng phương pháp tạo chú thích ở đoạn .

 # phpMyAdmin - Web based MySQL browser written in php # # Allows only localhost by default # # But allowing phpMyAdmin to anyone other than localhost should be considered # dangerous unless properly secured by SSL Alias /phpMyAdmin /usr/share/phpMyAdmin Alias /phpmyadmin /usr/share/phpMyAdmin # # Order Deny,Allow # Deny from All # Allow from 127.0.0.1 # Allow from ::1 # Order Deny,Allow Deny from All Allow from 127.0.0.1 Allow from ::1 # These directories do not require access over HTTP - taken from the original # phpMyAdmin upstream tarball # Order Deny,Allow Deny from All Allow from None Order Deny,Allow Deny from All Allow from None Order Deny,Allow Deny from All Allow from None # This configuration prevents mod_security at phpMyAdmin directories from # filtering SQL etc. This may break your mod_security implementation. # # # # SecRuleInheritance Off # # 

Tạo đường dẫn khởi động cho Apache và kích hoạt nó:

chkconfig –levels 235 httpd on
/etc/init.d/httpd start

Bây giờ bạn cũng có thể truy cập vào liên kết http://server1.example.com/phpMyAdmin/ hoặc http://192.168.0.100/phpMyAdmin/ trên trình duyệt cùa mình, sau đó đăng nhập vào với username root và mật khẩu root MySQL.

7. Tạo cơ sở dữ liệu MySQL cho Postfix/Courier

Đầu tiên chúng ta tạo một db có tên mail:

mysqladmin -u root -p create mail

Tiếp theo vào MySQL shell:

mysql -u root -p

Trên MySQL shell, chúng ta tạo user mail_admin với password mail_admin_password (hãy thay thế bằng password riêng của bạn) có những quyền cơ bản như SELECT, INSERT, UPDATE, DELETE trên cơ sở dữ liệu mail. User này sẽ có sử dụng bởi Postfix và Courier để kết nối tới cơ sở dữ liệu mail:

GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO 'mail_admin'@'localhost' IDENTIFIED BY 'mail_admin_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO 'mail_admin'@'localhost.localdomain' IDENTIFIED BY 'mail_admin_password';
FLUSH PRIVILEGES;

Vẫn ở MySQL shell, chúng ta tạo các bảng mà Postfix và Courier cần:

USE mail;
CREATE TABLE domains (
domain varchar(50) NOT NULL,
PRIMARY KEY (domain) )
ENGINE=MyISAM;
CREATE TABLE forwardings (
source varchar(80) NOT NULL,
destination TEXT NOT NULL,
PRIMARY KEY (source) )
ENGINE=MyISAM;
CREATE TABLE users (
email varchar(80) NOT NULL,
password varchar(20) NOT NULL,
quota bigint(20) DEFAULT '10485760',
PRIMARY KEY (email)
) ENGINE=MyISAM;
CREATE TABLE transport (
domain varchar(128) NOT NULL default '',
transport varchar(128) NOT NULL default '',
UNIQUE KEY domain (domain)
) ENGINE=MyISAM;
quit;

Bằng cách sử dụng lệnh quit; chúng ta sẽ rời khỏi MySQL shell và trở về Linux shell.

Bảng domains sẽ lưu giữ từng domain ảo để Postfix nhận các email (ví dụ example.com ).

domain
example.com

Bảng forwardings dành cho những email trỏ tới email khác, ví dụ trỏ từ info@example.com tới sales@example.com .

source destination
info@example.com sales@example.com

Bảng users lưu giữ mọi thứ tin tức tài khoản ảo và mật khẩu cùng giá trị quota dành riêng cho mail box (trong tỉ dụ đây là giá trị mặc định 10485760 bytes tương đương với 10MB ).

email password quota
sales@example.com No9.E4skNvGa. (“secret” in encrypted form) 10485760

Bảng transport là chọn lựa thêm không bắt buộc, dành riêng cho các người dùng nâng cao, cho phép chuyển tiếp mail đối với mỗi người dùng đơn lẻ, hoặc toàn bộ domain cũng giống mọi thứ mail tới server khác. Ví dụ:

domain transport
example.com smtp:[1.2.3.4]

Ở đây toàn bộ email sẽ chuyển tiếp cho example.com thông qua giao thức smtp tới máy server với địa điểm IP 1.2.3.4 , dấu ngoặc vuông [] có nghĩa là “ không thi hành một tra cứu của bản ghi MX DNS ” (cho các địa điểm IP). Nếu bạn sử dụng một tên miền đầy đủ (FQDN) thì không cần dùng dấu [] này.

8. Cấu hình Postfix

Bây giờ chúng ta cần cho Postfix biết nơi nó có thể tìm thấy toàn bộ thông tin trong cơ sở dữ liệu. Đầu tiên cần tạo ra 6 file văn bản, sau đó thông báo cho Postfix kết nối tới MySQL trên địa điểm IP 127.0.0.1 thay vì localhost . Chúng ta nên làm điều đó bởi Postfix đang chạy trên một chroot jail và không có quyền truy cập tới socket MySQL, do đấy nếu không được điều tiết nó sẽ cố kết nối thông qua localhost . Còn khi dùng 127.0.0.1 , Postfix sẽ thông qua TCP để kết nối tới MySQL mà không gặp vấn đề nào trong một chroot jail.

Tạo 6 file văn bản:

vi /etc/postfix/mysql-virtual_domains.cf

 user = mail_admin password = mail_admin_password dbname = mail query = SELECT domain AS virtual FROM domains WHERE domain='%s' hosts = 127.0.0.1 

vi /etc/postfix/mysql-virtual_forwardings.cf

 user = mail_admin password = mail_admin_password dbname = mail query = SELECT destination FROM forwardings WHERE source='%s' hosts = 127.0.0.1 

vi /etc/postfix/mysql-virtual_mailboxes.cf

 user = mail_admin password = mail_admin_password dbname = mail query = SELECT CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/') FROM users WHERE email='%s' hosts = 127.0.0.1 

vi /etc/postfix/mysql-virtual_email2email.cf

 user = mail_admin password = mail_admin_password dbname = mail query = SELECT email FROM users WHERE email='%s' hosts = 127.0.0.1 

vi /etc/postfix/mysql-virtual_transports.cf

 user = mail_admin password = mail_admin_password dbname = mail query = SELECT transport FROM transport WHERE domain='%s' hosts = 127.0.0.1 

vi /etc/postfix/mysql-virtual_mailbox_limit_maps.cf

 user = mail_admin password = mail_admin_password dbname = mail query = SELECT quota FROM users WHERE email='%s' hosts = 127.0.0.1 

chmod o= /etc/postfix/mysql-virtual_*.cf
chgrp postfix /etc/postfix/mysql-virtual_*.cf

Bây giờ ta tạo một user và group mang tên vmail với thư mục home là /home/vmail . Điều này sẽ lưu giữ toàn bộ hòm thư đến.

groupadd -g 5000 vmail
useradd -g vmail -u 5000 vmail -d /home/vmail -m

Tiếp theo là qui trình cấu hình Postfix. Hãy chắc chắn rằng bạn đã thay thế server1.example.com với một FQDN hợp lệ, nếu không Postfix cũng có thể không làm việc đúng cách.

 postconf -e 'myhostname = server1.example.com' postconf -e 'mydestination = server1.example.com, localhost, localhost.localdomain' postconf -e 'mynetworks = 127.0.0.0/8' postconf -e 'virtual_alias_domains =' postconf -e ' virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, mysql:/etc/postfix/mysql-virtual_email2email.cf' postconf -e 'virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf' postconf -e 'virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf' postconf -e 'virtual_mailbox_base = /home/vmail' postconf -e 'virtual_uid_maps = static:5000' postconf -e 'virtual_gid_maps = static:5000' postconf -e 'smtpd_sasl_auth_enable = yes' postconf -e 'broken_sasl_auth_clients = yes' postconf -e 'smtpd_sasl_authenticated_header = yes' postconf -e 'smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination' postconf -e 'smtpd_use_tls = yes' postconf -e 'smtpd_tls_cert_file = /etc/postfix/smtpd.cert' postconf -e 'smtpd_tls_key_file = /etc/postfix/smtpd.key' postconf -e 'transport_maps = proxy:mysql:/etc/postfix/mysql-virtual_transports.cf' postconf -e 'virtual_create_maildirsize = yes' postconf -e 'virtual_maildir_extended = yes' postconf -e 'virtual_mailbox_limit_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_limit_maps.cf' postconf -e 'virtual_mailbox_limit_override = yes' postconf -e 'virtual_maildir_limit_message = "The user you are trying to reach is over quota."' postconf -e 'virtual_overquota_bounce = yes' postconf -e 'proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps' postconf -e 'inet_interfaces = all' 

Sau đó tạo chứng nhận SSL cần có cho TLS:

cd /etc/postfix
openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509

Country Name (2 letter code) [XX]: <– Enter your Country Name (e.g., "DE").
State or Province Name (full name) []: <– Enter your State or Province Name.
Locality Name (eg, city) [Default City]: <– Enter your City.
Organization Name (eg, company) [Default Company Ltd]: <– Enter your Organization Name (e.g., the name of your company).
Organizational Unit Name (eg, section) []: <– Enter your Organizational Unit Name (e.g. "IT Department").
Common Name (eg, your name or your server's hostname) []: <– Enter the Fully Qualified Domain Name of the system (e.g. “server1.example.com”).
Email Address []: <– Enter your Email Address.

Thay đổi quyền cho smtpd.key:

chmod o= /etc/postfix/smtpd.key


9. Cấu hình Saslauthd

Chỉnh sửa tập tin /etc/sasl2/smtpd.conf như sau:

vi /etc/sasl2/smtpd.conf

 pwcheck_method: authdaemond log_level: 3 mech_list: PLAIN LOGIN authdaemond_path:/var/spool/authdaemon/socket 

Sau đó tắt Sendmail và khởi động Postfix, saslauthd, courier-authlib:

chmod 755 /var/spool/authdaemon
chkconfig –levels 235 courier-authlib on
/etc/init.d/courier-authlib start
chkconfig –levels 235 sendmail off
chkconfig –levels 235 postfix on
chkconfig –levels 235 saslauthd on
/etc/init.d/sendmail stop
/etc/init.d/postfix start
/etc/init.d/saslauthd start

10. Cấu hình Courier

Bây giờ chúng ta sẽ báo cho Courier biết cần xác thực lại MySQL database. Đầu tiên, sửa /etc/authlib/authdaemonrc và thay đổi giá trị của authmodulelist :

vi /etc/authlib/authdaemonrc

 [...] authmodulelist="authmysql" #authmodulelist="authuserdb authpam authpgsql authldap authmysql authcustom authpipe" [...] 

Sau đó sửa lại /etc/authlib/authmysqlrc . Đảm bảo tính chính xác cho các gì nhập vào.

cp /etc/authlib/authmysqlrc /etc/authlib/authmysqlrc_orig
cat /dev/null > /etc/authlib/authmysqlrc
vi /etc/authlib/authmysqlrc
 MYSQL_SERVER localhost MYSQL_USERNAME mail_admin MYSQL_PASSWORD mail_admin_password MYSQL_PORT 0 MYSQL_DATABASE mail MYSQL_USER_TABLE users MYSQL_CRYPT_PWFIELD password #MYSQL_CLEAR_PWFIELD password MYSQL_UID_FIELD 5000 MYSQL_GID_FIELD 5000 MYSQL_LOGIN_FIELD email MYSQL_HOME_FIELD "/home/vmail" MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/') #MYSQL_NAME_FIELD MYSQL_QUOTA_FIELD quota 

Khởi động lại Courier:

chkconfig –levels 235 courier-imap on
/etc/init.d/courier-authlib restart
/etc/init.d/courier-imap restart

Lần đầu khởi chạy courier-imap, nó sẽ tự động tạo ra những tập tin chứng thực /usr/lib/courier-imap/share/imapd.pem /usr/lib/courier-imap/share/pop3d.pem từ file /usr/lib/courier-imap/etc/imapd.cnf /usr/lib/courier-imap/etc/pop3d.cnf . Bởi vì nội dung của những file . cnf đều chứa dòng CN=localhost , nhưng server của chúng ta lại mang tên server1.example.com do đó các chứng nhận có thể gặp sự cố khi sử dụng kết nối TLS. Để giải quyết vấn đề này, chúng ta hãy xóa bỏ các chứng thực…

cd /usr/lib/courier-imap/share
rm -f imapd.pem
rm -f pop3d.pem

… và thay thế dòng CN=localhost trong /usr/lib/courier-imap/etc/imapd.cnf /usr/lib/courier-imap/etc/pop3d.cnf bởi CN=server1.example.com :

vi /usr/lib/courier-imap/etc/imapd.cnf

 [...] CN=server1.example.com [...] 

vi /usr/lib/courier-imap/etc/pop3d.cnf

 [...] CN=server1.example.com [...] 

Sau đó khởi tạo lại hai chứng thư này…

. /mkimapdcert
. /mkpop3dcert

… và khởi động lại courier-authlib, courier-imap:

/etc/init.d/courier-authlib restart
/etc/init.d/courier-imap restart

Chạy lệnh:

telnet localhost pop3

để xem máy server POP3 của bạn làm việc chính xác hay là không bằng phương pháp hiện thông báo +OK Hello there . (gõ quit để quay trở lại Linux shell):

[root@server1 share]# telnet localhost pop3
Trying ::1…
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
<– quit
+OK Better luck next time.
Connection closed by foreign host.
[root@server1 share]#

11. Chỉnh sửa /etc/aliases

Bước tiếp theo bạn mở /etc/aliases . Đảm nói rằng postmaster trỏ tới root root tới username của bạn hoặc email, chẳng hạn:

vi /etc/aliases

 [...] postmaster: root root: postmaster@yourdomain.tld [...] 

Hoặc như thế này (nếu administrator thuộc quyền sở hữu của bạn):

 [...] postmaster: root root: administrator [...] 

Bất cứ khi nào bạn sửa đổi /etc/aliases, đều phải chạy lệnh:

newaliases

Sau đó restart Postfix:

/etc/init.d/postfix restart


12. Cài đặt Amavisd-new, SpamAssassin và ClamAV

Để cài đặt cùng theo đó Amavisd-new, SpamAssassin và ClamAV, bạn chạy dòng lệnh sau:

yum install amavisd-new spamassassin clamav clamav-data clamav-server clamav-update unzip bzip2

Bây giờ bạn cần làm là sửa file /etc/amavisd/amavisd.conf .

vi /etc/amavisd/amavisd.conf

Trong tập tin này chúng ta cần thay đổi 5 địa điểm:

12.1: Đổi

 $mydomain = 'example.com'; # a convenient default for other settings 

Thành

 $mydomain = 'localhost'; #$mydomain = 'example.com'; # a convenient default for other settings 

12.2: Đổi

 $sa_tag_level_deflt = 2.0; # add spam info headers if at, or above that level $sa_tag2_level_deflt = 6.2; # add 'spam detected' headers at that level $sa_kill_level_deflt = 6.9; # triggers spam evasive actions (e.g. blocks mail) $sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent 

Thành

 $sa_tag_level_deflt = 2.0; # add spam info headers if at, or above that level $sa_tag2_level_deflt = 4.0; # add 'spam detected' headers at that level $sa_kill_level_deflt = $sa_tag2_level_deflt; # triggers spam evasive actions (e.g. blocks mail) $sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent #$sa_tag_level_deflt = 2.0; # add spam info headers if at, or above that level #$sa_tag2_level_deflt = 6.2; # add 'spam detected' headers at that level #$sa_kill_level_deflt = 6.9; # triggers spam evasive actions (e.g. blocks mail) #$sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent 

Ở đây bạn có thể điều chỉnh số điểm spam theo ý mình.

12.3: Đổi

 # @lookup_sql_dsn = # ( ['DBI:mysql:database=mail;host=127.0.0.1;port=3306', 'user1', 'passwd1'], # ['DBI:mysql:database=mail;host=host2', 'username2', 'password2'], # ["DBI:SQLite:dbname=$MYHOME/sql/mail_prefs.sqlite", '', ''] ); # @storage_sql_dsn = @lookup_sql_dsn; # none, same, or separate database 

Thành

 # @lookup_sql_dsn = # ( ['DBI:mysql:database=mail;host=127.0.0.1;port=3306', 'user1', 'passwd1'], # ['DBI:mysql:database=mail;host=host2', 'username2', 'password2'], # ["DBI:SQLite:dbname=$MYHOME/sql/mail_prefs.sqlite", '', ''] ); # @storage_sql_dsn = @lookup_sql_dsn; # none, same, or separate database @lookup_sql_dsn = ( ['DBI:mysql:database=mail;host=127.0.0.1;port=3306', 'mail_admin', 'mail_admin_password'] ); $sql_select_policy = 'SELECT "Y" as local FROM domains WHERE CONCAT("@",domain) IN (%k)'; $sql_select_white_black_list = undef; # undef disables SQL white/blacklisting $recipient_delimiter = '+'; # (default is '+') $replace_existing_extension = 1; # (default is false) $localpart_is_case_sensitive = 0; # (default is false) 

12.4: Đổi

 # $recipient_delimiter = '+'; # undef disables address extensions altogether # when enabling addr extensions do also Postfix/main.cf: recipient_delimiter=+ 

Thành

 $recipient_delimiter = undef; # undef disables address extensions altogether # $recipient_delimiter = '+'; # undef disables address extensions altogether # when enabling addr extensions do also Postfix/main.cf: recipient_delimiter=+ 

12.5: Đổi

 $final_virus_destiny = D_DISCARD; $final_banned_destiny = D_BOUNCE; $final_spam_destiny = D_DISCARD; $final_bad_header_destiny = D_BOUNCE; 

Thành

 $final_virus_destiny = D_REJECT; $final_banned_destiny = D_REJECT; $final_spam_destiny = D_PASS; $final_bad_header_destiny = D_PASS; #$final_virus_destiny = D_DISCARD; #$final_banned_destiny = D_BOUNCE; #$final_spam_destiny = D_DISCARD; #$final_bad_header_destiny = D_BOUNCE; 

Sau khi thay đổi xong các phần này, file /etc/amavisd/amavisd.conf sẽ trông như sau:

 use strict; # a minimalistic configuration file for amavisd-new with all necessary settings # # see amavisd.conf-default for a list of all variables with their defaults; # see amavisd.conf-sample for a traditional-style commented file; # for more details see documentation in INSTALL, README_FILES/* # and at http://www.ijs.si/software/amavisd/amavisd-new-docs.html # COMMONLY ADJUSTED SETTINGS: # @bypass_virus_checks_maps = (1); # controls running of anti-virus code # @bypass_spam_checks_maps = (1); # controls running of anti-spam code # $bypass_decode_parts = 1; # controls running of decoders&dearchivers $max_servers = 2; # num of pre-forked children (2..30 is common), -m $daemon_user = 'amavis'; # (no default; customary: vscan or amavis), -u $daemon_group = 'amavis'; # (no default; customary: vscan or amavis), -g $mydomain = 'localhost'; #$mydomain = 'example.com'; # a convenient default for other settings $MYHOME = '/var/spool/amavisd'; # a convenient default for other settings, -H $TEMPBASE = "$MYHOME/tmp"; # working directory, needs to exist, -T $ENV{TMPDIR} = $TEMPBASE; # environment variable TMPDIR, used by SA, etc. $QUARANTINEDIR = undef; # -Q # $quarantine_subdir_levels = 1; # add level of subdirs to disperse quarantine # $release_format = 'resend'; # 'attach', 'plain', 'resend' # $report_format = 'arf'; # 'attach', 'plain', 'resend', 'arf' # $daemon_chroot_dir = $MYHOME; # chroot directory or undef, -R $db_home = "$MYHOME/db"; # dir for bdb nanny/cache/snmp databases, -D # $helpers_home = "$MYHOME/var"; # working directory for SpamAssassin, -S $lock_file = "/var/run/amavisd/amavisd.lock"; # -L $pid_file = "/var/run/amavisd/amavisd.pid"; # -P #NOTE: create directories $MYHOME/tmp, $MYHOME/var, $MYHOME/db manually $log_level = 0; # verbosity 0..5, -d $log_recip_templ = undef; # disable by-recipient level-0 log entries $DO_SYSLOG = 1; # log via syslogd (preferred) $syslog_facility = 'mail'; # Syslog facility as a string # e.g.: mail, daemon, user, local0,. .. local7 $syslog_priority = 'debug'; # Syslog base (minimal) priority as a string, # choose from: emerg, alert, crit, err, warning, notice, info, debug $enable_db = 1; # enable use of BerkeleyDB/libdb (SNMP and nanny) $enable_global_cache = 1; # enable use of libdb-based cache if $enable_db=1 $nanny_details_level = 2; # nanny verbosity: 1: traditional, 2: detailed $enable_dkim_verification = 1; # enable DKIM signatures verification $enable_dkim_signing = 1; # load DKIM signing code, keys defined by dkim_key @local_domains_maps = ( [".$mydomain"] ); # list of all local domains @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 ); $unix_socketname = "$MYHOME/amavisd.sock"; # amavisd-release or amavis-milter # option(s) -p overrides $inet_socket_port and $unix_socketname $inet_socket_port = 10024; # listen on this local TCP port(s) # $inet_socket_port = [10024,10026]; # listen on multiple TCP ports $policy_bank{'MYNETS'} = { # mail originating from @mynetworks originating => 1, # is true in MYNETS by default, but let's make it explicit os_fingerprint_method => undef, # don't query p0f for internal clients }; # it is up to MTA to re-route mail from authenticated roaming users or # from internal hosts to a dedicated TCP port (such as 10026) for filtering $interface_policy{'10026'} = 'ORIGINATING'; $policy_bank{'ORIGINATING'} = { # mail supposedly originating from our users originating => 1, # declare that mail was submitted by our smtp client allow_disclaimers => 1, # enables disclaimer insertion if available # notify administrator of locally originating malware virus_admin_maps => ["virusalert@$mydomain"], spam_admin_maps => ["virusalert@$mydomain"], warnbadhsender => 1, # forward to a smtpd service providing DKIM signing service forward_method => 'smtp:[127.0.0.1]:10027', # force MTA conversion to 7-bit (e.g. before DKIM signing) smtpd_discard_ehlo_keywords => ['8BITMIME'], bypass_banned_checks_maps => [1], # allow sending any file names and types terminate_dsn_on_notify_success => 0, # don't remove NOTIFY=SUCCESS option }; $interface_policy{'SOCK'} = 'AM.PDP-SOCK'; # only applies with $unix_socketname # Use with amavis-release over a socket or with Petr Rehor's amavis-milter.c # (with amavis-milter.c from this package or old amavis.c client use 'AM.CL'): $policy_bank{'AM.PDP-SOCK'} = { protocol => 'AM.PDP', auth_required_release => 0, # do not require secret_id for amavisd-release }; $sa_tag_level_deflt = 2.0; # add spam info headers if at, or above that level $sa_tag2_level_deflt = 4.0; # add 'spam detected' headers at that level $sa_kill_level_deflt = $sa_tag2_level_deflt; # triggers spam evasive actions (e.g. blocks mail) $sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent #$sa_tag_level_deflt = 2.0; # add spam info headers if at, or above that level #$sa_tag2_level_deflt = 6.2; # add 'spam detected' headers at that level #$sa_kill_level_deflt = 6.9; # triggers spam evasive actions (e.g. blocks mail) #$sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent $sa_crediblefrom_dsn_cutoff_level = 18; # likewise, but for a likely valid From # $sa_quarantine_cutoff_level = 25; # spam level beyond which quarantine is off $penpals_bonus_score = 8; # (no effect without a @storage_sql_dsn database) $penpals_threshold_high = $sa_kill_level_deflt; # don't waste time on hi spam $bounce_killer_score = 100; # spam score points to add for joe-jobbed bounces $sa_mail_body_size_limit = 400*1024; # don't waste time on SA if mail is larger $sa_local_tests_only = 0; # only tests which do not require internet access? # @lookup_sql_dsn = # ( ['DBI:mysql:database=mail;host=127.0.0.1;port=3306', 'user1', 'passwd1'], # ['DBI:mysql:database=mail;host=host2', 'username2', 'password2'], # ["DBI:SQLite:dbname=$MYHOME/sql/mail_prefs.sqlite", '', ''] ); # @storage_sql_dsn = @lookup_sql_dsn; # none, same, or separate database @lookup_sql_dsn = ( ['DBI:mysql:database=mail;host=127.0.0.1;port=3306', 'mail_admin', 'mail_admin_password'] ); $sql_select_policy = 'SELECT "Y" as local FROM domains WHERE CONCAT("@",domain) IN (%k)'; $sql_select_white_black_list = undef; # undef disables SQL white/blacklisting $recipient_delimiter = '+'; # (default is '+') $replace_existing_extension = 1; # (default is false) $localpart_is_case_sensitive = 0; # (default is false) # $timestamp_fmt_mysql = 1; # if using MySQL *and* msgs.time_iso is TIMESTAMP; # defaults to 0, which is good for non-MySQL or if msgs.time_iso is CHAR(16) $virus_admin = undef; # notifications recip. $mailfrom_notify_admin = undef; # notifications sender $mailfrom_notify_recip = undef; # notifications sender $mailfrom_notify_spamadmin = undef; # notifications sender $mailfrom_to_quarantine = ''; # null return path; uses original sender if undef @addr_extension_virus_maps = ('virus'); @addr_extension_banned_maps = ('banned'); @addr_extension_spam_maps = ('spam'); @addr_extension_bad_header_maps = ('badh'); $recipient_delimiter = undef; # undef disables address extensions altogether # $recipient_delimiter = '+'; # undef disables address extensions altogether # when enabling addr extensions do also Postfix/main.cf: recipient_delimiter=+ $path = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/usr/bin:/bin'; # $dspam = 'dspam'; $MAXLEVELS = 14; $MAXFILES = 1500; $MIN_EXPANSION_QUOTA = 100*1024; # bytes (default undef, not enforced) $MAX_EXPANSION_QUOTA = 300*1024*1024; # bytes (default undef, not enforced) $sa_spam_subject_tag = '***SPAM*** '; $defang_virus = 1; # MIME-wrap passed infected mail $defang_banned = 1; # MIME-wrap passed mail containing banned name # for defanging bad headers only turn on certain minor contents categories: $defang_by_ccat{+CC_BADH.",3"} = 1; # NUL or CR character in header $defang_by_ccat{+CC_BADH.",5"} = 1; # header line longer than 998 characters $defang_by_ccat{+CC_BADH.",6"} = 1; # header field syntax error # OTHER MORE COMMON SETTINGS (defaults may suffice): # $myhostname = 'host.example.com'; # must be a fully-qualified domain name! # $notify_method = 'smtp:[127.0.0.1]:10025'; # $forward_method = 'smtp:[127.0.0.1]:10025'; # set to undef with milter! $final_virus_destiny = D_REJECT; $final_banned_destiny = D_REJECT; $final_spam_destiny = D_PASS; $final_bad_header_destiny = D_PASS; #$final_virus_destiny = D_DISCARD; #$final_banned_destiny = D_BOUNCE; #$final_spam_destiny = D_DISCARD; #$final_bad_header_destiny = D_BOUNCE; # $bad_header_quarantine_method = undef; # $os_fingerprint_method = 'p0f:*:2345'; # to query p0f-analyzer.pl ## hierarchy by which a final setting is chosen: ## policy bank (based on port or IP address) -> *_by_ccat ## *_by_ccat (based on mail contents) -> *_maps ## *_maps (based on recipient address) -> final configuration value # SOME OTHER VARIABLES WORTH CONSIDERING (see amavisd.conf-default for all) # $warnbadhsender, # $warnvirusrecip, $warnbannedrecip, $warnbadhrecip, (or @warn*recip_maps) # # @bypass_virus_checks_maps, @bypass_spam_checks_maps, # @bypass_banned_checks_maps, @bypass_header_checks_maps, # # @virus_lovers_maps, @spam_lovers_maps, # @banned_files_lovers_maps, @bad_header_lovers_maps, # # @blacklist_sender_maps, @score_sender_maps, # # $clean_quarantine_method, $virus_quarantine_to, $banned_quarantine_to, # $bad_header_quarantine_to, $spam_quarantine_to, # # $defang_bad_header, $defang_undecipherable, $defang_spam # REMAINING IMPORTANT VARIABLES ARE LISTED HERE BECAUSE OF LONGER ASSIGNMENTS @keep_decoded_original_maps = (new_RE( qr'^MAIL$', # retain full original message for virus checking qr'^MAIL-UNDECIPHERABLE$', # recheck full mail if it contains undecipherables qr'^(ASCII(?! cpio)|text|uuencoded|xxencoded|binhex)'i, # qr'^Zip archive data', # don't trust Archive::Zip )); # for $banned_namepath_re (a new-style of banned table) see amavisd.conf-sample $banned_filename_re = new_RE( ### BLOCKED ANYWHERE # qr'^UNDECIPHERABLE$', # is or contains any undecipherable components qr'^.(exe-ms|dll)$', # banned file(1) types, rudimentary # qr'^.(exe|lha|tnef|cab|dll)$', # banned file(1) types ### BLOCK THE FOLLOWING, EXCEPT WITHIN UNIX ARCHIVES: # [ qr'^.(gz|bz2)$' => 0 ], # allow any in gzip or bzip2 [ qr'^.(rpm|cpio|tar)$' => 0 ], # allow any in Unix-type archives qr'..(pif|scr)$'i, # banned extensions - rudimentary # qr'^.zip$', # block zip type ### BLOCK THE FOLLOWING, EXCEPT WITHIN ARCHIVES: # [ qr'^.(zip|rar|arc|arj|zoo)$'=> 0 ], # allow any within these archives qr'^application/x-msdownload$'i, # block these MIME types qr'^application/x-msdos-program$'i, qr'^application/hta$'i, # qr'^message/partial$'i, # rfc2046 MIME type # qr'^message/external-body$'i, # rfc2046 MIME type # qr'^(application/x-msmetafile|image/x-wmf)$'i, # Windows Metafile MIME type # qr'^.wmf$', # Windows Metafile file(1) type # block certain double extensions in filenames qr'.[^./]*[A-Za-z][^./]*.s*(exe|vbs|pif|scr|bat|cmd|com|cpl|dll)[.s]*$'i, # qr'{[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}}?'i, # Class ID CLSID, strict # qr'{[0-9a-z]{4,}(-[0-9a-z]{4,}){0,7}}?'i, # Class ID extension CLSID, loose qr'..(exe|vbs|pif|scr|cpl)$'i, # banned extension - basic # qr'..(exe|vbs|pif|scr|cpl|bat|cmd|com)$'i, # banned extension - basic+cmd # qr'..(ade|adp|app|bas|bat|chm|cmd|com|cpl|crt|emf|exe|fxp|grp|hlp|hta| # inf|ins|isp|js|jse|lnk|mda|mdb|mde|mdw|mdt|mdz|msc|msi|msp|mst| # ops|pcd|pif|prg|reg|scr|sct|shb|shs|vb|vbe|vbs| # wmf|wsc|wsf|wsh)$'ix, # banned ext - long # qr'..(ani|cur|ico)$'i, # banned cursors and icons filename # qr'^.ani$', # banned animated cursor file(1) type # qr'..(mim|b64|bhx|hqx|xxe|uu|uue)$'i, # banned extension - WinZip vulnerab. ); # See http://support.microsoft.com/default.aspx?sc> [{'bla-mobile.press@example.com' => 10.0}], # 'user3@example.com' => [{'.ebay.com' => -3.0}], # 'user4@example.com' => [{'cleargreen@cleargreen.com' => -7.0, # '.cleargreen.com' => -5.0}], ## site-wide opinions about senders (the '.' matches any recipient) '.' => [ # the _first_ matching sender determines the score boost new_RE( # regexp-type lookup table, just happens to be all soft-blacklist [qr'^(bulkmail|offers|cheapbenefits|earnmoney|foryou)@'i => 5.0], [qr'^(greatcasino|investments|lose_weight_today|market.alert)@'i=> 5.0], [qr'^(money2you|MyGreenCard|new.tld.registry|opt-out|opt-in)@'i=> 5.0], [qr'^(optin|saveonlsmoking2002k|specialoffer|specialoffers)@'i => 5.0], [qr'^(stockalert|stopsnoring|wantsome|workathome|yesitsfree)@'i => 5.0], [qr'^(your_friend|greatoffers)@'i => 5.0], [qr'^(inkjetplanet|marketopt|MakeMoney)d*@'i => 5.0], ), # read_hash("/var/amavis/sender_scores_sitewide"), { # a hash-type lookup table (associative array) 'nobody@cert.org' => -3.0, 'cert-advisory@us-cert.gov' => -3.0, 'owner-alert@iss.net' => -3.0, 'slashdot@slashdot.org' => -3.0, 'securityfocus.com' => -3.0, 'ntbugtraq@listserv.ntbugtraq.com' => -3.0, 'security-alerts@linuxsecurity.com' => -3.0, 'mailman-announce-admin@python.org' => -3.0, 'amavis-user-admin@lists.sourceforge.net'=> -3.0, 'amavis-user-bounces@lists.sourceforge.net' => -3.0, 'spamassassin.apache.org' => -3.0, 'notification-return@lists.sophos.com' => -3.0, 'owner-postfix-users@postfix.org' => -3.0, 'owner-postfix-announce@postfix.org' => -3.0, 'owner-sendmail-announce@lists.sendmail.org' => -3.0, 'sendmail-announce-request@lists.sendmail.org' => -3.0, 'donotreply@sendmail.org' => -3.0, 'ca+envelope@sendmail.org' => -3.0, 'noreply@freshmeat.net' => -3.0, 'owner-technews@postel.acm.org' => -3.0, 'ietf-123-owner@loki.ietf.org' => -3.0, 'cvs-commits-list-admin@gnome.org' => -3.0, 'rt-users-admin@lists.fsck.com' => -3.0, 'clp-request@comp.nus.edu.sg' => -3.0, 'surveys-errors@lists.nua.ie' => -3.0, 'emailnews@genomeweb.com' => -5.0, 'yahoo-dev-null@yahoo-inc.com' => -3.0, 'returns.groups.yahoo.com' => -3.0, 'clusternews@linuxnetworx.com' => -3.0, lc('lvs-users-admin@LinuxVirtualServer.org') => -3.0, lc('owner-textbreakingnews@CNNIMAIL12.CNN.COM') => -5.0, # soft-blacklisting (positive score) 'sender@example.net' => 3.0, '.example.net' => 1.0, }, ], # end of site-wide tables }); @decoders = ( ['mail', &do_mime_decode], ['asc', &do_ascii], ['uue', &do_ascii], ['hqx', &do_ascii], ['ync', &do_ascii], ['F', &do_uncompress, ['unfreeze','freeze -d','melt','fcat'] ], ['Z', &do_uncompress, ['uncompress','gzip -d','zcat'] ], ['gz', &do_uncompress, 'gzip -d'], ['gz', &do_gunzip], ['bz2', &do_uncompress, 'bzip2 -d'], ['lzo', &do_uncompress, 'lzop -d'], ['rpm', &do_uncompress, ['rpm2cpio.pl','rpm2cpio'] ], ['cpio', &do_pax_cpio, ['pax','gcpio','cpio'] ], ['tar', &do_pax_cpio, ['pax','gcpio','cpio'] ], ['deb', &do_ar, 'ar'], # ['a', &do_ar, 'ar'], # unpacking. a seems an overkill ['zip', &do_unzip], ['7z', &do_7zip, ['7zr','7za','7z'] ], ['rar', &do_unrar, ['rar','unrar'] ], ['arj', &do_unarj, ['arj','unarj'] ], ['arc', &do_arc, ['nomarch','arc'] ], ['zoo', &do_zoo, ['zoo','unzoo'] ], ['lha', &do_lha, 'lha'], # ['doc', &do_ole, 'ripole'], ['cab', &do_cabextract, 'cabextract'], ['tnef', &do_tnef_ext, 'tnef'], ['tnef', &do_tnef], # ['sit', &do_unstuff, 'unstuff'], # broken/unsafe decoder ['exe', &do_executable, ['rar','unrar'], 'lha', ['arj','unarj'] ], ); @av_scanners = ( # ### http://www.clanfield.info/sophie/ (http://www.vanja.com/tools/sophie/) # ['Sophie', # &ask_daemon, ["{}/n", '/var/run/sophie'], # qr/(?x)^ 0+ ( : | [00rn]* $)/m, qr/(?x)^ 1 ( : | [00rn]* $)/m, # qr/(?x)^ [-+]? d+ : (.*?) [00rn]* $/m ], # ### http://www.csupomona.edu/~henson/www/projects/SAVI-Perl/ # ['Sophos SAVI', &sophos_savi ], # ### http://www.clamav.net/ ['ClamAV-clamd', &ask_daemon, ["CONTSCAN {}n", "/var/spool/amavisd/clamd.sock"], qr/bOK$/m, qr/bFOUND$/m, qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ], # # NOTE: run clamd under the same user as amavisd, or run it under its own # # uid such as clamav, add user clamav to the amavis group, and then add # # AllowSupplementaryGroups to clamd.conf; # # NOTE: match socket name (LocalSocket) in clamav.conf to the socket name in # # this entry; when running chrooted one may prefer socket "$MYHOME/clamd". # ### http://www.clamav.net/ and CPAN (memory-hungry! clamd is preferred) # # note that Mail::ClamAV requires perl to be build with threading! # ['Mail::ClamAV', &ask_clamav, "*", [0], [1], qr/^INFECTED: (.+)/m ], # ### http://www.openantivirus.org/ # ['OpenAntiVirus ScannerDaemon (OAV)', # &ask_daemon, ["SCAN {}n", '127.0.0.1:8127'], # qr/^OK/m, qr/^FOUND: /m, qr/^FOUND: (.+)/m ], # ### http://www.vanja.com/tools/trophie/ # ['Trophie', # &ask_daemon, ["{}/n", '/var/run/trophie'], # qr/(?x)^ 0+ ( : | [00rn]* $)/m, qr/(?x)^ 1 ( : | [00rn]* $)/m, # qr/(?x)^ [-+]? d+ : (.*?) [00rn]* $/m ], # ### http://www.grisoft.com/ # ['AVG Anti-Virus', # &ask_daemon, ["SCAN {}n", '127.0.0.1:55555'], # qr/^200/m, qr/^403/m, qr/^403. *?: ([^rn]+)/m ], # ### http://www.f-prot.com/ # ['F-Prot fpscand', # F-PROT Antivirus for BSD/Linux/Solaris, version 6 # &ask_daemon, # ["SCAN FILE {}/*n", '127.0.0.1:10200'], # qr/^(0|8|64) /m, # qr/^([1235679]|1[01345]) | :]*(?i)(infected|suspicious|unwanted)/m, # qr/(?i) :]*(?:infected|suspicious|unwanted)[^> :]*: ([^> ]*)> /m ], # ### http://www.f-prot.com/ # ['F-Prot f-protd', # old version # &ask_daemon, # ["GET {}/*?-dumb%20-archive%20-packed HTTP/1.0rnrn", # ['127.0.0.1:10200', '127.0.0.1:10201', '127.0.0.1:10202', # '127.0.0.1:10203', '127.0.0.1:10204'] ], # qr/(?i)  ]*> clean  /m, # qr/(?i)  ]*> infected  /m, # qr/(?i) (.+) /m ], # ### http://www.sald.com/, http://www.dials.ru/english/, http://www.drweb.ru/ # ['DrWebD', &ask_daemon, # DrWebD 4.31 or later # [pack('N',1). # DRWEBD_SCAN_CMD # pack('N',0x00280001). # DONT_CHANGEMAIL, IS_MAIL, RETURN_VIRUSES # pack('N', # path length # length("$TEMPBASE/amavis-yyyymmddTHHMMSS-xxxxx/parts/pxxx")). # '{}/*'. # path # pack('N',0). # content size # pack('N',0), # '/var/drweb/run/drwebd.sock', # # '/var/amavis/var/run/drwebd.sock', # suitable for chroot # # '/usr/local/drweb/run/drwebd.sock', # FreeBSD drweb ports default # # '127.0.0.1:3000', # or over an inet socket # ], # qr/Ax00[x10x11][x00x10]x00/sm, # IS_CLEAN,EVAL_KEY; SKIPPED # qr/Ax00[x00x01][x00x10][x20x40x80]/sm,# KNOWN_V,UNKNOWN_V,V._MODIF # qr/A.{12}(?:infected with )?([^x00]+)x00/sm, # ], # # NOTE: If using amavis-milter, change length to: # # length("$TEMPBASE/amavis-milter-xxxxxxxxxxxxxx/parts/pxxx"). ### http://www.kaspersky.com/ (kav4mailservers) ['KasperskyLab AVP - aveclient', ['/usr/local/kav/bin/aveclient','/usr/local/share/kav/bin/aveclient', '/opt/kav/5.5/kav4mailservers/bin/aveclient','aveclient'], '-p /var/run/aveserver -s {}/*', [0,3,6,8], qr/b(INFECTED|SUSPICION|SUSPICIOUS)b/m, qr/(?:INFECTED|WARNING|SUSPICION|SUSPICIOUS) (.+)/m, ], # NOTE: one may prefer [0],[2,3,4,5], depending on how suspicious, # currupted or protected archives are to be handled ### http://www.kaspersky.com/ ['KasperskyLab AntiViral Toolkit Pro (AVP)', ['avp'], '-* -P -B -Y -O- {}', [0,3,6,8], [2,4], # any use for -A -K ? qr/infected: (.+)/m, sub {chdir('/opt/AVP') or die "Can't chdir to AVP: $!"}, sub {chdir($TEMPBASE) or die "Can't chdir back to $TEMPBASE $!"}, ], ### The kavdaemon and AVPDaemonClient have been removed from Kasperky ### products and replaced by aveserver and aveclient ['KasperskyLab AVPDaemonClient', [ '/opt/AVP/kavdaemon', 'kavdaemon', '/opt/AVP/AvpDaemonClient', 'AvpDaemonClient', '/opt/AVP/AvpTeamDream', 'AvpTeamDream', '/opt/AVP/avpdc', 'avpdc' ], "-f=$TEMPBASE {}", [0,8], [3,4,5,6], qr/infected: ([^rn]+)/m ], # change the startup-script in /etc/init.d/kavd to: # DPARMS="-* -Y -dl -f=/var/amavis /var/amavis" # (or perhaps: DPARMS="-I0 -Y -* /var/amavis" ) # adjusting /var/amavis above to match your $TEMPBASE. # The '-f=/var/amavis' is needed if not running it as root, so it # can find, read, and write its pid file, etc., see 'man kavdaemon'. # defUnix.prf: there must be an entry "*/var/amavis" (or whatever # directory $TEMPBASE specifies) in the 'Names=' section. # cd /opt/AVP/DaemonClients; configure; cd Sample; make # cp AvpDaemonClient /opt/AVP/ # su - vscan -c "${PREFIX}/kavdaemon ${DPARMS}" ### http://www.centralcommand.com/ ['CentralCommand Vexira (new) vascan', ['vascan','/usr/lib/Vexira/vascan'], "-a s --timeout=60 --temp=$TEMPBASE -y $QUARANTINEDIR ". "--log=/var/log/vascan.log {}", [0,3], [1,2,5], qr/(?x)^s* (?:virus|iworm|macro|mutant|sequence|trojan) found: ( [^]s']+ ). .. /m ], # Adjust the path of the binary and the virus database as needed. # 'vascan' does not allow to have the temp directory to be the same as # the quarantine directory, and the quarantine option can not be disabled. # If $QUARANTINEDIR is not used, then another directory must be specified # to appease 'vascan'. Move status 3 to the second list if password # protected files are to be considered infected. ### http://www.avira.com/ ### Avira AntiVir (formerly H+BEDV) or (old) CentralCommand Vexira Antivirus ['Avira AntiVir', ['antivir','vexira'], '--allfiles -noboot -nombr -rs -s -z {}', [0], qr/ALERT:|VIRUS:/m, qr/(?x)^s* (?: ALERT: s* (?: [ | [^']* ' ) | (?i) VIRUS:. *? virus '?) ( [^]s']+ )/m ], # NOTE: if you only have a demo version, remove -z and add 214, as in: # '--allfiles -noboot -nombr -rs -s {}', [0,214], qr/ALERT:|VIRUS:/, ### http://www.commandsoftware.com/ ['Command AntiVirus for Linux', 'csav', '-all -archive -packed {}', [50], [51,52,53], qr/Infection: (.+)/m ], ### http://www.symantec.com/ ['Symantec CarrierScan via Symantec CommandLineScanner', 'cscmdline', '-a scan -i 1 -v -s 127.0.0.1:7777 {}', qr/^Files Infected:s+0$/m, qr/^Infectedb/m, qr/^(?:Info|Virus Name):s+(.+)/m ], ### http://www.symantec.com/ ['Symantec AntiVirus Scan Engine', 'savsecls', '-server 127.0.0.1:7777 -mode scanrepair -details -verbose {}', [0], qr/^Infectedb/m, qr/^(?:Info|Virus Name):s+(.+)/m ], # NOTE: check options and patterns to see which entry better applies # ### http://www.f-secure.com/products/anti-virus/ version 4.65 # ['F-Secure Antivirus for Linux servers', # ['/opt/f-secure/fsav/bin/fsav', 'fsav'], # '--delete=no --disinf=no --rename=no --archive=yes --auto=yes '. # '--dumb=yes --list=no --mime=yes {}', [0], [3,6,8], # qr/(?:infection|Infected|Suspected): (.+)/m ], ### http://www.f-secure.com/products/anti-virus/ version 5.52 ['F-Secure Antivirus for Linux servers', ['/opt/f-secure/fsav/bin/fsav', 'fsav'], '--virus-action1=report --archive=yes --auto=yes '. '--dumb=yes --list=no --mime=yes {}', [0], [3,4,6,8], qr/(?:infection|Infected|Suspected|Riskware): (.+)/m ], # NOTE: internal archive handling may be switched off by '--archive=no' # to prevent fsav from exiting with status 9 on broken archives # ### http://www.avast.com/ # ['avast! Antivirus daemon', # &ask_daemon, # greets with 220, terminate with QUIT # ["SCAN {}1512QUIT1512", '/var/run/avast4/mailscanner.sock'], # qr/t[+]/m, qr/t[L]t/m, qr/t[L]t([^[ t1512]+)/m ], # ### http://www.avast.com/ # ['avast! Antivirus - Client/Server Version', 'avastlite', # '-a /var/run/avast4/mailscanner.sock -n {}', [0], [1], # qr/t[L]t([^[ t1512]+)/m ], ['CAI InoculateIT', 'inocucmd', # retired product '-sec -nex {}', [0], [100], qr/was infected by virus (.+)/m ], # see: http://www.flatmtn.com/computer/Linux-Antivirus_CAI.html ### http://www3.ca.com/Solutions/Product.asp?ID=156 (ex InoculateIT) ['CAI eTrust Antivirus', 'etrust-wrapper', '-arc -nex -spm h {}', [0], [101], qr/is infected by virus: (.+)/m ], # NOTE: requires suid wrapper around inocmd32; consider flag: -mod reviewer # see http://marc.theaimsgroup.com/?l=amavis-user&m=109229779912783 ### http://mks.com.pl/english.html ['MkS_Vir for Linux (beta)', ['mks32','mks'], '-s {}/*', [0], [1,2], qr/--[ t]*(.+)/m ], ### http://mks.com.pl/english.html ['MkS_Vir daemon', 'mksscan', '-s -q {}', [0], [1..7], qr/^... (S+)/m ], # ### http://www.nod32.com/, version v2.52 (old) # ['ESET NOD32 for Linux Mail servers', # ['/opt/eset/nod32/bin/nod32cli', 'nod32cli'], # '--subdir --files -z --sfx --rtp --adware --unsafe --pattern --heur '. # '-w -a --action-on-infected=accept --action-on-uncleanable=accept '. # '--action-on-notscanned=accept {}', # [0,3], [1,2], qr/virus="([^"]+)"/m ], # ### http://www.eset.com/, version v2.7 (old) # ['ESET NOD32 Linux Mail Server - command line interface', # ['/usr/bin/nod32cli', '/opt/eset/nod32/bin/nod32cli', 'nod32cli'], # '--subdir {}', [0,3], [1,2], qr/virus="([^"]+)"/m ], # ### http://www.eset.com/, version 2.71.12 # ['ESET Software ESETS Command Line Interface', # ['/usr/bin/esets_cli', 'esets_cli'], # '--subdir {}', [0], [1,2,3], qr/virus="([^"]+)"/m ], ### http://www.eset.com/, version 3.0 ['ESET Software ESETS Command Line Interface', ['/usr/bin/esets_cli', 'esets_cli'], '--subdir {}', [0], [1,2,3], qr/:s*action="(?!accepted)[^"]*"n.*:s*virus="([^"]*)"/m ], ## http://www.nod32.com/, NOD32LFS version 2.5 and above ['ESET NOD32 for Linux File servers', ['/opt/eset/nod32/sbin/nod32','nod32'], '--files -z --mail --sfx --rtp --adware --unsafe --pattern --heur '. '-w -a --action=1 -b {}', [0], [1,10], qr/^object=.*, virus="(.*?)",/m ], # Experimental, based on posting from Rado Dibarbora (Dibo) on 2002-05-31 # ['ESET Software NOD32 Client/Server (NOD32SS)', # &ask_daemon2, # greets with 200, persistent, terminate with QUIT # ["SCAN {}/*rn", '127.0.0.1:8448' ], # qr/^200 File OK/m, qr/^201 /m, qr/^201 (.+)/m ], ### http://www.norman.com/products_nvc.shtml ['Norman Virus Control v5 / Linux', 'nvcc', '-c -l:0 -s -u -temp:$TEMPBASE {}', [0,10,11], [1,2,14], qr/(?i).* virus in. * -> '(.+)'/m ], ### http://www.pandasoftware.com/ ['Panda CommandLineSecure 9 for Linux', ['/opt/pavcl/usr/bin/pavcl','pavcl'], '-auto -aex -heu -cmp -nbr -nor -nos -eng -nob {}', qr/Number of files infected[. ]*: 0+(?!d)/m, qr/Number of files infected[. ]*: 0*[1-9]/m, qr/Found virus :s*(S+)/m ], # NOTE: for efficiency, start the Panda in resident mode with 'pavcl -tsr' # before starting amavisd - the bases are then loaded only once at startup. # To reload bases in a signature update script: # /opt/pavcl/usr/bin/pavcl -tsr -ulr; /opt/pavcl/usr/bin/pavcl -tsr # Please review other options of pavcl, for example: # -nomalw, -nojoke, -nodial, -nohackt, -nospyw, -nocookies # ### http://www.pandasoftware.com/ # ['Panda Antivirus for Linux', ['pavcl'], # '-TSR -aut -aex -heu -cmp -nbr -nor -nso -eng {}', # [0], [0x10, 0x30, 0x50, 0x70, 0x90, 0xB0, 0xD0, 0xF0], # qr/Found virus :s*(S+)/m ], # GeCAD AV technology is acquired by Microsoft; RAV has been discontinued. # Check your RAV license terms before fiddling with the following two lines! # ['GeCAD RAV AntiVirus 8', 'ravav', # '--all --archive --mail {}', [1], [2,3,4,5], qr/Infected: (.+)/m ], # # NOTE: the command line switches changed with scan engine 8.5 ! # # (btw, assigning stdin to /dev/null causes RAV to fail) ### http://www.nai.com/ ['NAI McAfee AntiVirus (uvscan)', 'uvscan', '--secure -rv --mime --summary --noboot - {}', [0], [13], qr/(?x) Found (?: the (.+) (?:virus|trojan) | (?:virus|trojan) or variant ([^ ]+) | : (.+) NOT a virus)/m, # sub {$ENV{LD_PRELOAD}='/lib/libc.so.6'}, # sub {delete $ENV{LD_PRELOAD}}, ], # NOTE1: with RH9: force the dynamic linker to look at /lib/libc.so.6 before # anything else by setting environment variable LD_PRELOAD=/lib/libc.so.6 # and then clear it when finished to avoid confusing anything else. # NOTE2: to treat encrypted files as viruses replace the [13] with: # qr/^s{5,}(Found|is password-protected|.*(virus|trojan))/ ### http://www.virusbuster.hu/en/ ['VirusBuster', ['vbuster', 'vbengcl'], "{} -ss -i '*' -log=$MYHOME/vbuster.log", [0], [1], qr/: '(.*)' - Virus/m ], # VirusBuster Ltd. does not support the daemon version for the workstation # engine (vbuster-eng-1.12-linux-i386-libc6.tgz) any longer. The names of # binaries, some parameters AND return codes have changed (from 3 to 1). # See also the new Vexira entry 'vascan' which is possibly related. # ### http://www.virusbuster.hu/en/ # ['VirusBuster (Client + Daemon)', 'vbengd', # '-f -log scandir {}', [0], [3], # qr/Virus found = (.*);/m ], # # HINT: for an infected file it always returns 3, # # although the man-page tells a different story ### http://www.cyber.com/ ['CyberSoft VFind', 'vfind', '--vexit {}/*', [0], [23], qr/##==> > > > VIRUS ID: CVDL (.+)/m, # sub {$ENV{VSTK_HOME}='/usr/lib/vstk'}, ], ### http://www.avast.com/ ['avast! Antivirus', ['/usr/bin/avastcmd','avastcmd'], '-a -i -n -t=A {}', [0], [1], qr/binfected by:s+([^ tn[]]+)/m ], ### http://www.ikarus-software.com/ ['Ikarus AntiVirus for Linux', 'ikarus', '{}', [0], [40], qr/Signature (.+) found/m ], ### http://www.bitdefender.com/ ['BitDefender', 'bdscan', # new version '--action=ignore --no-list {}', qr/^Infected filess*:s*0+(?!d)/m, qr/^(?:Infected files|Identified viruses|Suspect files)s*:s*0*[1-9]/m, qr/(?:suspected|infected)s*:s*(.*)(?:33|$)/m ], ### http://www.bitdefender.com/ ['BitDefender', 'bdc', # old version '--arc --mail {}', qr/^Infected files *:0+(?!d)/m, qr/^(?:Infected files|Identified viruses|Suspect files) *:0*[1-9]/m, qr/(?:suspected|infected): (.*)(?:33|$)/m ], # consider also: --all --nowarn --alev=15 --flev=15. The --all argument may # not apply to your version of bdc, check documentation and see 'bdc --help' ### ArcaVir for Linux and Unix http://www.arcabit.pl/ ['ArcaVir for Linux', ['arcacmd','arcacmd.static'], '-v 1 -summary 0 -s {}', [0], [1,2], qr/(?:VIR|WIR):[ t]*(.+)/m ], # ### a generic SMTP-client interface to a SMTP-based virus scanner # ['av_smtp', &ask_av_smtp, # ['{}', 'smtp:[127.0.0.1]:5525', 'dummy@localhost'], # qr/^2/, qr/^5/, qr/^s*(.*?)s*$/m ], # ['File::Scan', sub {Amavis::AV::ask_av(sub{ # use File::Scan; my($fn)=@_; # my($f)=File::Scan-> new(max_txt_size=> 0, max_bin_size=> 0); # my($vname) = $f-> scan($fn); # $f-> error ? (2,"Error: ".$f-> error) # : ($vname ne '') ? (1,"$vname FOUND") : (0,"Clean")}, @_) }, # ["{}/*"], [0], [1], qr/^(.*) FOUND$/m ], # ### fully-fledged checker for JPEG marker segments of invalid length # ['check-jpeg', # sub { use JpegTester (); Amavis::AV::ask_av(&JpegTester::test_jpeg, @_) }, # ["{}/*"], undef, [1], qr/^(bad jpeg:. *)$/m ], # # NOTE: place file JpegTester.pm somewhere where Perl can find it, # # for example in /usr/local/lib/perl5/site_perl ); @av_scanners_backup = ( ### http://www.clamav.net/ - backs up clamd or Mail::ClamAV ['ClamAV-clamscan', 'clamscan', "--stdout --no-summary -r --tempdir=$TEMPBASE {}", [0], qr/:.*sFOUND$/m, qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ], ### http://www.f-prot.com/ - backs up F-Prot Daemon, V6 ['F-PROT Antivirus for UNIX', ['fpscan'], '--report --mount --adware {}', # consider: --applications -s 4 -u 3 -z 10 [0,8,64], [1,2,3, 4+1,4+2,4+3, 8+1,8+2,8+3, 12+1,12+2,12+3], qr/^[Founds+[^]]*]s+ ]*)/m ], ### http://www.f-prot.com/ - backs up F-Prot Daemon (old) ['FRISK F-Prot Antivirus', ['f-prot','f-prot.sh'], '-dumb -archive -packed {}', [0,8], [3,6], # or: [0], [3,6,8], qr/(?:Infection:|security risk named) (.+)|s+containss+(.+)$/m ], ### http://www.trendmicro.com/ - backs up Trophie ['Trend Micro FileScanner', ['/etc/iscan/vscan','vscan'], '-za -a {}', [0], qr/Found virus/m, qr/Found virus (.+) in/m ], ### http://www.sald.com/, http://drweb.imshop.de/ - backs up DrWebD ['drweb - DrWeb Antivirus', # security LHA hole in Dr.Web 4.33 and earlier ['/usr/local/drweb/drweb', '/opt/drweb/drweb', 'drweb'], '-path={} -al -go -ot -cn -upn -ok-', [0,32], [1,9,33], qr' infected (?:with|by)(?: virus)? (.*)$'m ], ### http://www.kaspersky.com/ ['Kaspersky Antivirus v5.5', ['/opt/kaspersky/kav4fs/bin/kav4fs-kavscanner', '/opt/kav/5.5/kav4unix/bin/kavscanner', '/opt/kav/5.5/kav4mailservers/bin/kavscanner', 'kavscanner'], '-i0 -xn -xp -mn -R -ePASBME {}/*', [0,10,15], [5,20,21,25], qr/(?:INFECTED|WARNING|SUSPICION|SUSPICIOUS) (.*)/m, # sub {chdir('/opt/kav/bin') or die "Can't chdir to kav: $!"}, # sub {chdir($TEMPBASE) or die "Can't chdir back to $TEMPBASE $!"}, ], # Commented out because the name 'sweep' clashes with Debian and FreeBSD # package/port of an audio editor. Make sure the correct 'sweep' is found # in the path when enabling. # # ### http://www.sophos.com/ - backs up Sophie or SAVI-Perl # ['Sophos Anti Virus (sweep)', 'sweep', # '-nb -f -all -rec -ss -sc -archive -cab -mime -oe -tnef '. # '--no-reset-atime {}', # [0,2], qr/Virus. *? found/m, # qr/^> > > Virus(?: fragment)? '?(.*?)'? found/m, # ], # # other options to consider: -idedir=/usr/local/sav # Always succeeds and considers mail clean. # Potentially useful when all other scanners fail and it is desirable # to let mail continue to flow with no virus checking (when uncommented). # ['always-clean', sub {0}], ); 1; # insure a defined return value 

amavisd-new là chương trình gắn kết Postfix và SpamAssassin/ClamAV lại với nhau. Postfix sẽ đi qua các mail tới amavisd-new sau đó gọi SpamAssassin và ClamAV để quét các mail này. Bạn cũng có thể có thể tùy chỉnh trong tập tin /etc/amavisd/amavisd.conf theo ý thích.

Khi cài đặt ClamAV, 1 trình tự công việc đã được thiết lập để cập nhật cơ sở dữ liệu nhận dạng virus cho ClamAV 3 giờ 1 lần. Nhưng tính năng chỉ hoạt động khi ta kích hoạt bên trong /etc/sysconfig/freshclam /etc/freshclam.conf :

vi /etc/sysconfig/freshclam

Chú thích bên phía ngoài dòng FRESHCLAM_DELAY ở phía cuối như sau:

 ## When changing the periodicity of freshclam runs in the crontab, ## this value must be adjusted also. Its value is the timespan between ## two subsequent freshclam runs in minutes. E.g. for the default ## ## | 0 */3 * * *. .. ## ## crontab line, the value is 180 (minutes). # FRESHCLAM_MOD= ## A predefined value for the delay in seconds. By default, the value is ## calculated by the 'hostdisabled-warn'. .. disables the automatic freshclam update and ## gives out a warning ## 'disabled'. .. disables the automatic freshclam silently # FRESHCLAM_DELAY= ### !!!!! REMOVE ME !!!!!! ### REMOVE ME: By default, the freshclam update is disabled to avoid ### REMOVE ME: network access without prior activation #FRESHCLAM_DELAY=disabled-warn # REMOVE ME 

vi /etc/freshclam.conf

Chú thích cho dòng Example :

 [...] # Comment or remove the line below. #Example [...] 

Tạo liên kết khởi động cho ClamAV và amavisd-new, cập nhật ClamAV và khởi động cả hai dịch vụ đó:

chkconfig –levels 235 amavisd on
chkconfig –levels 235 clamd.amavisd on
/usr/bin/freshclam
/etc/init.d/amavisd start
/etc/init.d/clamd.amavisd start

Cấu hình Postfix để tạo ra thể gửi mail thông qua amavisd-new:

postconf -e 'content_filter = amavis:[127.0.0.1]:10024'
postconf -e 'receive_override_options = no_address_mappings'

Sau đó thêm các dòng sau vào /etc/postfix/master.cf :

vi /etc/postfix/master.cf

 [...] amavis unix - - - - 2 smtp -o smtp_data_done_timeout=1200 -o smtp_send_xforward_command=yes 127.0.0.1:10025 inet n - - - - smtpd -o content_filter= -o local_recipient_maps= -o relay_recipient_maps= -o smtpd_restriction_classes= -o smtpd_client_restrictions= -o smtpd_helo_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o mynetworks=127.0.0.0/8 -o strict_rfc821_envelopes=yes -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks -o smtpd_bind_address=127.0.0.1 

Cuối cùng restart Postfix:

/etc/init.d/postfix restart


13. Cài đặt Razor, Pyzor, DCC và cấu hình SpamAssassin

Razor, Pyzor và DCC là các bộ lọc spam email sử dụng một bộ lọc hệ thống mạng tương tác với nhau. Để cài đặt Razor và Pyzor, gõ lệnh sau:

yum install perl-Razor-Agent pyzor

Sau đó tái tạo cùng theo đó hai dịch vụ:

chmod -R a+rX /usr/share/doc/pyzor-0.5.0 /usr/bin/pyzor /usr/bin/pyzord
chmod -R a+rX /usr/lib/python2.7/site-packages/pyzor
su -m amavis -c 'pyzor –homedir /var/spool/amavisd discover'
su -m amavis -c 'razor-admin -home=/var/spool/amavisd -create'
su -m amavis -c 'razor-admin -home=/var/spool/amavisd -register'

Tiếp theo chúng ta cài đặt DCC:

cd /tmp
wget http://www.dcc-servers.net/dcc/source/dcc-dccproc.tar.Z
tar xzvf dcc-dccproc.tar.Z
cd dcc-dccproc-1.3.140
. /configure –with-u> make
make install
chown -R amavis:amavis /var/dcc
ln -s /var/dcc/libexec/dccifd /usr/local/bin/dccifd

Sau đó chúng ta cần báo cho SpamAssassin để sử dụng 3 chương trình này. Chỉnh sửa file /etc/mail/spamassassin/local.cf như sau:

vi /etc/mail/spamassassin/local.cf

 # These values can be overridden by editing ~/.spamassassin/user_prefs.cf # (see spamassassin(1) for details) # These should be safe assumptions and allow for simple visual sifting # without risking lost emails. #required_hits 5 #report_safe 0 #rewrite_header Subject [SPAM] # dcc use_dcc 1 dcc_path /usr/local/bin/dccproc #pyzor use_pyzor 1 pyzor_path /usr/bin/pyzor #razor use_razor2 1 razor_config /var/spool/amavisd/razor-agent.conf #bayes use_bayes 1 use_bayes_rules 1 bayes_auto_learn 1 

Kích hoạt plugin DCC trong SpamAssassin. Mở /etc/mail/spamassassin/v310.pre và bỏ chú thích ở dòng loadplugin Mail::SpamAssassin::Plugin::DCC :

vi /etc/mail/spamassassin/v310.pre

 [...] # DCC - perform DCC message checks. # # DCC is disabled here because it is not open source. See the DCC # license for more details. # loadplugin Mail::SpamAssassin::Plugin::DCC [...] 

Bạn cũng đều có thể kiểm tra cấu hình SpamAssassin bằng phương pháp thực thi lệnh:

spamassassin –lint

Nếu không có bất kỳ lỗi nào xảy ra, chạy tiếp lệnh:

/etc/init.d/amavisd restart

Cập nhật các ruleset cho SpamAssassin:

sa-update –no-gpg

Tạo một công việc có chu kỳ để các ruleset được cập nhật thường xuyên.

crontab -e

Mở trình soạn thảo và tạo công việc định kỳ như sau:

 23 4 */2 * * /usr/bin/sa-update --no-gpg &> /dev/null 

Như vậy ruleset sẽ được cập nhật hai ngày một lần vào hồi 4.23h.

14. Cảnh báo Quota Exceedance

Nếu bạn muốn nhận được thông báo về toàn bộ tài khoản email vượt quá quota, sau đó tạo tập tin /usr/local/sbin/quota_notify :

cd /usr/local/sbin/
vi quota_notify

 #!/usr/bin/perl -w # Author # # This script assumes that virtual_mailbox_base in defined # in postfix's main.cf file. This directory is assumed to contain # directories which themselves contain your virtual user's maildirs. # For example: # # -----------/ # | # | # home/vmail/domains/ # | | # | | # example.com/ foo.com/ # | # | # ----------------- # | | | # | | | # user1/ user2/ user3/ # | # | # maildirsize # use strict; my $POSTFIX_CF = "/etc/postfix/main.cf"; my $MAILPROG = "/usr/sbin/sendmail -t"; my $WARNPERCENT = 80; my @POSTMASTERS = ('postmaster@domain.tld'); my $CONAME = 'My Company'; my $COADDR = 'postmaster@domain.tld'; my $SUADDR = 'postmaster@domain.tld'; my $MAIL_REPORT = 1; my $MAIL_WARNING = 1; #get virtual mailbox base from postfix config open(PCF, " < $POSTFIX_CF") or die $!; my $mboxBase; while ( ) { next unless /virtual_mailbox_bases*=s*(.*)s*/; $mboxBase = $1; } close(PCF); #assume one level of subdirectories for domain names my @domains; opendir(DIR, $mboxBase) or die $!; while (defined(my $name = readdir(DIR))) { next if $name =~ /^..?$/; #skip '.' and '..' next unless (-d "$mboxBase/$name"); push(@domains, $name); } closedir(DIR); #iterate through domains for username/maildirsize files my @users; chdir($mboxBase); foreach my $domain (@domains) { opendir(DIR, $domain) or die $!; while (defined(my $name = readdir(DIR))) { next if $name =~ /^..?$/; #skip '.' and '..' next unless (-d "$domain/$name"); push(@users, {"$name@$domain" => "$mboxBase/$domain/$name"}); } } closedir(DIR); #get user quotas and percent used my (%lusers, $report); foreach my $href (@users) { foreach my $user (keys %$href) { my $quotafile = "$href-> {$user}/maildirsize"; next unless (-f $quotafile); open(QF, " < $quotafile") or die $!; my ($firstln, $quota, $used); while ( ) { my $line = $_; if (! $firstln) { $firstln = 1; die "Error: corrupt quotafile $quotafile" unless ($line =~ /^(d+)S/); $quota = $1; last if (! $quota); next; } die "Error: corrupt quotafile $quotafile" unless ($line =~ /s*(-?d+)/); $used += $1; } close(QF); next if (! $used); my $percent = int($used / $quota * 100); $lusers{$user} = $percent unless not $percent; } } #send a report to the postmasters if ($MAIL_REPORT) { open(MAIL, "| $MAILPROG"); select(MAIL); map {print "To: $_n"} @POSTMASTERS; print "From: $COADDRn"; print "Subject: Daily Quota Report.n"; print "DAILY QUOTA REPORT:nn"; print "----------------------------------------------n"; print "| % USAGE | ACCOUNT NAME |n"; print "----------------------------------------------n"; foreach my $luser ( sort { $lusers{$b} $lusers{$a} } keys %lusers ) { printf("| %3d | %32s |n", $lusers{$luser}, $luser); print "---------------------------------------------n"; } print "n--n"; print "$CONAMEn"; close(MAIL); } #email a warning to people over quota if ($MAIL_WARNING) { foreach my $luser (keys (%lusers)) { next unless $lusers{$luser} > = $WARNPERCENT; # skip those under quota open(MAIL, "| $MAILPROG"); select(MAIL); print "To: $lusern"; map {print "BCC: $_n"} @POSTMASTERS; print "From: $SUADDRn"; print "Subject: WARNING: Your mailbox is $lusers{$luser}% full.n"; print "Reply-to: $SUADDRn"; print "Your mailbox: $luser is $lusers{$luser}% full.nn"; print "Once your e-mail box has exceeded your monthly storage quotan"; print "your monthly billing will be automatically adjusted.n"; print "Please consider deleting e-mail and emptying your trash folder to clear some space.nn"; print "Contact for further assistance.nn"; print "Thank You.nn"; print "--n"; print "$CONAMEn"; close(MAIL); } } 

Hãy chắc chắn rằng các biến trên được điều chỉnh sao cho phù hợp (đặc biệt là địa chỉ email postmaster@domain.tld ):

Chúng ta cần thực thi file này:

chmod 755 quota_notify

Chạy lệnh

crontab -e

để tạo một script cho công việc định kỳ:

 0 0 * * * /usr/local/sbin/quota_notify &> /dev/null 

15. Thử nghiệm Postfix

Để kiểm tra xem Postfix đã sẵn sàng cho SMTP-AUTH TLS hay không, chạy lệnh:

telnet localhost 25

Sau khi đã thiết lập một kết nối với Postfix mail server của mình, nhập vào:

ehlo localhost

Nếu bạn nhìn thấy dòng:

250-STARTTLS

250-AUTH LOGIN PLAIN

Vậy là mọi thứ đều tốt đẹp.

[root@server1 sbin]# telnet localhost 25
Trying ::1…
Connected to localhost.
Escape character is '^]'.
220 server1.example.com ESMTP Postfix
<– ehlo localhost
250-server1.example.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
<– quit
221 2.0.0 Bye
Connection closed by foreign host.
[root@server1 sbin]#

Bạn gõ:

quit

16. Hợp nhất các cơ sở dữ liệu và thí nghiệm

Để hợp nhất các cơ sở dữ liệu bạn cũng có thể có thể sử dụng MySQL shell:

mysql -u root -p

USE mail;

Ít nhất bạn cần tạo những phần tử sau trong bảng domains users :

INSERT INTO `domains` (`domain`) VALUES ('example.com');
INSERT INTO `users` (`email`, `password`, `quota`) VALUES ('sales@example.com', ENCRYPT('secret'), 10485760);

(Hãy cẩn thận khi dùng cú pháp ENCRYPT trong lệnh INSERT thứ hai để mã hóa mật khẩu.)

Nếu bạn muốn ghi dữ liệu vào hai bảng khác, tiếp tục làm như sau:

INSERT INTO `forwardings` (`source`, `destination`) VALUES ('info@example.com', 'sales@example.com');
INSERT INTO `transport` (`domain`, `transport`) VALUES ('example.com', 'smtp:mail.example.com');

Để ra khỏi MySQL shell, nhập:

quit;

Đối với đa số mọi người việc quản lý MySQL trên giao diện đồ họa sẽ dễ dàng hơn rất nhiều. Do đó bạn có thể sử dụng phpMyAdmin (trong tỉ dụ này có địa chỉ http://192.168.0.100/phpMyAdmin/ hoặc http://server1.example.com/phpMyAdmin/ ) để quản trị cơ sở dữ liệu mail. Một lần nữa, thận trọng khi sử dụng cú pháp ENCRYPT trong lệnh INSERT thứ 2 để mã hóa mật khẩu.

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

Tương tự, bảng forwardings có thể có các mục như sau:

source destination
info@example.com sales@example.com Redirects emails for info@example.com to sales@example.com
@example.com thomas@example.com Creates a Catch-All account for thomas@example.com. All emails to example.com will arrive at thomas@example.com, except those that exist in the users table (i.e., if sales@example.com exists in the users table, mails to sales@example.com will still arrive at sales@example.com).
@example.com @anotherdomain.tld This redirects all emails to example.com to the same user at anotherdomain.tld. E.g., emails to thomas@example.com will be forwarded to thomas@anotherdomain.tld.
info@example.com sales@example.com, billing@anotherdomain.tld Forward emails for info@example.com to two or more email addresses. All listed email addresses under destination receive a copy of the email.

Bảng transport kể cả các mục:

domain transport
example.com : Delivers emails for example.com locally. This is as if this record would not exist in this table at all.
example.com smtp:mail.anotherdomain.tld Delivers all emails for example.com via smtp to the server mail.anotherdomain.com.
example.com smtp:mail.anotherdomain.tld:2025 Delivers all emails for example.com via smtp to the server mail.anotherdomain.com, but on port 2025, not 25 which is the default port for smtp.
example.com

smtp:[1.2.3.4]
smtp:[1.2.3.4]:2025
smtp:[mail.anotherdomain.tld]

The square brackets prevent Postfix from doing lookups of the MX DNS record for the address in square brackets. Makes sense for IP addresses.
. example.com smtp:mail.anotherdomain.tld Mail for any subdomain of example.com is delivered to mail.anotherdomain.tld.
* smtp:mail.anotherdomain.tld All emails are delivered to mail.anotherdomain.tld.
joe@example.com smtp:mail.anotherdomain.tld Emails for joe@example.com are delivered to mail.anotherdomain.tld.

Bạn có thể dùng lệnh:

man transport

Để hiểu thêm chi tiết.

Lưu ý: Thứ tự các mục trong bảng transport rất quan trọng. Chúng sẽ có theo sau từ trên xuống dưới. Postfix sử dụng cơ chế bộ nhớ đệm cho chuyện vận chuyển, do đấy sẽ mất 1 khoảng thời gian để những thay đổi của bạn trong bảng transport có hiệu lực. Nếu muốn chúng có hiệu quả ngay lập tức, chạy lệnh:

postfix reload

sau khi bạn đã thực hiện các thay đổi trong bảng transport.

17. Gửi một Email Welcome để tạo Maildir

Khi bạn tạo 1 tài khoản email mới, và thử lấy email từ đó (với chuẩn POP3/IMAP), thường thì sẽ nhận được thông báo lỗi rằng Maildir không tồn tại. Maildir sẽ tự động được tạo nên khi email trước mắt gửi tới tài khoản mới tương ứng. Do đó một ý tưởng tốt là bạn gửi một email welcome tới tài khoản này.

Trước tiên, cài đặt gói mailx:

yum install mailx

Gửi email welcome tới sales@example.com , chẳng hạn:

mailx sales@example.com

Bạn sẽ được yêu cầu nhập tiêu đề, gõ bất kỳ nội dung nào (ví dụ Welcome ), sau đó nhấn Enter . Trong dòng tiếp theo, gõ nội dung thông báo. Khi hoàn tất phần nội dung, nhấn Enter để bắt đầu 1 dòng mới, ở đây nhấn CTRL+D :

[root@server1 ~]# mailx sales@example.com
Subject: Welcome <– ENTER
Welcome! Have fun with your new mail account. <– ENTER
<– CTRL+D
EOT
[root@server1 ~]#

18. Cài đặt SquirrelMail

SquirrelMail là hệ thống quản lý webmail qua giao diện web, cho phép người dùng gửi và nhận email thông qua trình duyệt. Để cài đặt SquirrelMail, gõ lệnh sau:

yum install squirrelmail php-pear-DB

Sau đó, khởi động lại Apache:

/etc/init.d/httpd restart

SquirrelMail có kèm theo với 1 số plugin có sẵn, nhưng thật không may, không có plugin nào hỗ trợ người dùng thay đổi mật khẩu email trong cơ sở dữ liệu MySQL. Nhưng thay vào đó, các bạn có thể sử dụng plugin thay thế sau:

cd /usr/share/squirrelmail/plugins
wget http://www.squirrelmail.org/plugins/change_sqlpass-3.3-1.2.tar.gz
tar xvfz change_sqlpass-3.3-1.2.tar.gz
cd change_sqlpass
cp config.php.sample config.php

Tiếp theo, chúng ta phải điều tiết config.php , thay đổi các biến: $csp_dsn, $lookup_password_query, $password_update_queries, $password_encryption, $csp_salt_static, và $csp_delimiter như sau và chú giải bên phía ngoài $csp_salt_query :

vi config.php

 [...] $csp_dsn = 'mysql://mail_admin:mail_admin_password@localhost/mail'; [...] $lookup_password_query = 'SELECT count(*) FROM users WHERE email = "%1" AND password = %4'; [...] $password_update_queries = array('UPDATE users SET password = %4 WHERE email = "%1"'); [...] $password_encryption = 'MYSQLENCRYPT'; [...] $csp_salt_static = 'LEFT(password, 2)'; [...] //$csp_salt_query = 'SELECT salt FROM users WHERE username = "%1"'; [...] $csp_delimiter = '@'; [...] 

File sau khi chỉnh sửa sẽ trông giống thế này:

 <?php /** * SquirrelMail Change SQL Password Plugin * Copyright (C) 2001-2002 Tyler Akins * 2002 Thijs Kinkhorst * 2002-2005 Paul Lesneiwski * This program is licensed under GPL. See COPYING for details * * @package plugins * @subpackage Change SQL Password * */ // Global Variables, don't touch these unless you want to break the plugin // global $csp_dsn, $password_update_queries, $lookup_password_query, $force_change_password_check_query, $password_encryption, $csp_salt_query, $csp_salt_static, $csp_secure_port, $csp_non_standard_http_port, $csp_delimiter, $csp_debug, $min_password_length, $max_password_length, $include_digit_in_password, $include_uppercase_letter_in_password, $include_lowercase_letter_in_password, $include_nonalphanumeric_in_password; // csp_dsn // // Theoretically, any SQL database supported by Pear should be supported // here. The DSN (data source name) must contain the information needed // to connect to your database backend. A MySQL example is included below. // For more details about DSN syntax and list of supported database types, // please see: // http://pear.php.net/manual/en/package.database.db.intro-dsn.php // //$csp_dsn = 'mysql://user:password@localhost/email_users'; $csp_dsn = 'mysql://mail_admin:mail_admin_password@localhost/mail'; // lookup_password_query // // This plugin will always verify the user's old password // against their login password, but an extra check can also // be done against the database for more security if you // desire. If you do not need the extra password check, // make sure this setting is empty. // // This is a query that returns a positive value if a user // and password pair are found in the database. // // This query should return one value (one row, one column), the // value being ideally a one or a zero, simply indicating that // the user/password pair does in fact exist in the database. // // %1 in this query will be replaced with the full username // (including domain), such as "jose@example.com" // %2 in this query will be replaced with the username (without // any domain portion), such as "jose" // %3 in this query will be replaced with the domain name, // such as "example.com" // %4 in this query will be replaced with the current (old) // password in whatever encryption format is needed per other // plugin configuration settings (Note that the syntax of // the password will be provided depending on your encryption // choices, so you NEVER need to provide quotes around this // value in the query here.) // %5 in this query will be replaced with the current (old) // password in unencrypted plain text. If you do not use any // password encryption, %4 and %5 will be the same values, // except %4 will have double quotes around it and %5 will not. // //$lookup_password_query = ''; // TERRIBLE SECURITY: $lookup_password_query = 'SELECT count(*) FROM users WHERE username = "%1" AND plain_password = "%5"'; //$lookup_password_query = 'SELECT count(*) FROM users WHERE username = "%1" AND crypt_password = %4'; $lookup_password_query = 'SELECT count(*) FROM users WHERE email = "%1" AND password = %4'; // password_update_queries // // An array of SQL queries that will all be executed // whenever a password change attempt is made. // // Any number of queries may be included here. // The queries will be executed in the order given here. // // %1 in all queries will be replaced with the full username // (including domain), such as "jose@example.com" // %2 in all queries will be replaced with the username (without // any domain portion), such as "jose" // %3 in all queries will be replaced with the domain name, // such as "example.com" // %4 in all queries will be replaced with the new password // in whatever encryption format is needed per other // plugin configuration settings (Note that the syntax of // the password will be provided depending on your // encryption choices, so you NEVER need to provide quotes // around this value in the queries here.) // %5 in all queries will be replaced with the new password // in unencrypted plain text - BEWARE! If you do not use // any password encryption, %4 and %5 will be the same // values, except %4 will have double quotes around it // and %5 will not. // // $password_update_queries = array( // 'UPDATE users SET crypt_password = %4 WHERE username = "%1"', // 'UPDATE user_flags SET force_change_pwd = 0 WHERE username = "%1"', // 'UPDATE users SET crypt_password = %4, force_change_pwd = 0 WHERE username = "%1"', // ); $password_update_queries = array('UPDATE users SET password = %4 WHERE email = "%1"'); // force_change_password_check_query // // A query that checks for a flag that indicates if a user // should be forced to change their password. This query // should return one value (one row, one column) which is // zero if the user does NOT need to change their password, // or one if the user should be forced to change it now. // // This setting should be an empty string if you do not wish // to enable this functionality. // // %1 in this query will be replaced with the full username // (including domain), such as "jose@example.com" // %2 in this query will be replaced with the username (without // any domain portion), such as "jose" // %3 in this query will be replaced with the domain name, // such as "example.com" // //$force_change_password_check_query = 'SELECT IF(force_change_pwd = "yes", 1, 0) FROM users WHERE username = "%1"'; //$force_change_password_check_query = 'SELECT force_change_pwd FROM users WHERE username = "%1"'; $force_change_password_check_query = ''; // password_encryption // // What encryption method do you use to store passwords // in your database? Please use one of the following, // exactly as you see it: // // NONE Passwords are stored as plain text only // MYSQLPWD Passwords are stored using the MySQL password() function // MYSQLENCRYPT Passwords are stored using the MySQL encrypt() function // PHPCRYPT Passwords are stored using the PHP crypt() function // MD5CRYPT Passwords are stored using encrypted MD5 algorithm // MD5 Passwords are stored as MD5 hash // //$password_encryption = 'MYSQLPWD'; $password_encryption = 'MYSQLENCRYPT'; // csp_salt_query // csp_salt_static // // Encryption types that need a salt need to know where to get // that salt. If you have a constant, known salt value, you // should define it in $csp_salt_static. Otherwise, leave that // value empty and define a value for the $csp_salt_query. // // Leave both values empty if you do not need (or use) salts // to encrypt your passwords. // // The query should return one value (one row, one column) which // is the salt value for the current user's password. This // query is ignored if $csp_salt_static is anything but empty. // // %1 in this query will be replaced with the full username // (including domain), such as "jose@example.com" // %2 in this query will be replaced with the username (without // any domain portion), such as "jose" // %3 in this query will be replaced with the domain name, // such as "example.com" // //$csp_salt_static = 'LEFT(crypt_password, 2)'; //$csp_salt_static = '"a4"'; // use this format with MYSQLENCRYPT //$csp_salt_static = '$2$blowsomefish$'; // use this format with PHPCRYPT //$csp_salt_static = ''; $csp_salt_static = 'LEFT(password, 2)'; //$csp_salt_query = 'SELECT SUBSTRING_INDEX(crypt_password, '$', 1) FROM users WHERE username = "%1"'; //$csp_salt_query = 'SELECT SUBSTRING(crypt_password, (LENGTH(SUBSTRING_INDEX(crypt_password, '$', 2)) + 2)) FROM users WHERE username = "%1"'; //$csp_salt_query = 'SELECT salt FROM users WHERE username = "%1"'; //$csp_salt_query = ''; // csp_secure_port // // You may ensure that SSL encryption is used during password // change by setting this to the port that your HTTPS is served // on (443 is typical). Set to zero if you do not wish to force // an HTTPS connection when users are changing their passwords. // // You may override this value for certain domains, users, or // service levels through the Virtual Host Login (vlogin) plugin // by setting a value(s) for $vlogin_csp_secure_port in the vlogin // configuration. // $csp_secure_port = 0; //$csp_secure_port = 443; // csp_non_standard_http_port // // If you serve standard HTTP web requests on a non-standard // port (anything other than port 80), you should specify that // port number here. Set to zero otherwise. // // You may override this value for certain domains, users, or // service levels through the Virtual Host Login (vlogin) plugin // by setting a value(s) for $vlogin_csp_non_standard_http_port // in the vlogin configuration. // //$csp_non_standard_http_port = 8080; $csp_non_standard_http_port = 0; // min_password_length // max_password_length // include_digit_in_password // include_uppercase_letter_in_password // include_lowercase_letter_in_password // include_nonalphanumeric_in_password // // You can set the minimum and maximum password lengths that // you accept or leave those settings as zero to indicate that // no limit should be applied. // // Turn on any of the other settings here to check that the // new password contains at least one digit, upper case letter, // lower case letter and/or one non-alphanumeric character. // $min_password_length = 6; $max_password_length = 0; $include_digit_in_password = 0; $include_uppercase_letter_in_password = 0; $include_lowercase_letter_in_password = 0; $include_nonalphanumeric_in_password = 0; // csp_delimiter // // if your system has usernames with something other than // an "@" sign separating the user and domain portion, // specify that character here // //$csp_delimiter = '|'; $csp_delimiter = '@'; // debug mode // $csp_debug = 0; ?> 

Mặt khác, plugin Change SQL Password cũng lệ thuộc phần lớn vào khả năng tương thích của các hệ thống plugin như sau:

cd /usr/share/squirrelmail/plugins
wget http://www.squirrelmail.org/countdl.php?fileurl=http%3A%2F%2Fwww.squirrelmail.org%2Fplugins%2Fcompatibility-2.0.16-1.0.tar.gz
tar xvfz compatibility-2.0.16-1.0.tar.gz

Bây giờ sẽ cấu hình SquirrelMail và “ thông báo ” tới SquirrelMail rằng chúng ta sẽ sử dụng Courier như chuẩn POP3 và IMAP server, đồng thời kích hoạt 2 plugin Change SQL Password và Compatibility:

/usr/share/squirrelmail/config/conf.pl

Menu điều khiển sẽ hiển thị:

 SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Main Menu -- 1. Organization Preferences 2. Server Settings 3. Folder Defaults 4. General Options 5. Themes 6. Address Books 7. Message of the Day (MOTD) 8. Plugins 9. Database 10. Languages D. Set pre-defined settings for specific IMAP servers C Turn color off S Save data Q Quit Command > >  <-- D  SquirrelMail Configuration : Read: config.php --------------------------------------------------------- While we have been building SquirrelMail, we have discovered some preferences that work better with some servers that don't work so well with others. If you select your IMAP server, this option will set some pre-defined settings for that server. Please note that you will still need to go through and make sure everything is correct. This does not change everything. There are only a few settings that this will change. Please select your IMAP server: bincimap = Binc IMAP server courier = Courier IMAP server cyrus = Cyrus IMAP server dovecot = Dovecot Secure IMAP server exchange = Microsoft Exchange IMAP server hmailserver = hMailServer macosx = Mac OS X Mailserver mercury32 = Mercury/32 uw = University of Washington's IMAP server gmail = IMAP access to Google mail (Gmail) accounts quit = Do not change anything Command > >  <-- courier  imap_server_type = courier default_folder_prefix = INBOX. trash_folder = Trash sent_folder = Sent draft_folder = Drafts show_prefix_option = false default_sub_of_inbox = false show_contain_subfolders_option = false optional_delimiter =. delete_folder = true Press any key to continue...  <-- press some key  SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Main Menu -- 1. Organization Preferences 2. Server Settings 3. Folder Defaults 4. General Options 5. Themes 6. Address Books 7. Message of the Day (MOTD) 8. Plugins 9. Database 10. Languages D. Set pre-defined settings for specific IMAP servers C Turn color off S Save data Q Quit Command > >  <-- 8  SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Plugins Installed Plugins 1. delete_move_next 2. squirrelspell 3. newmail Available Plugins: 4. administrator 5. bug_report 6. calendar 7. change_sqlpass 8. compatibility 9. filters 10. fortune 11. info 12. listcommands 13. mail_fetch 14. message_details 15. sent_subfolders 16. spamcop 17. test 18. translate R Return to Main Menu C Turn color off S Save data Q Quit Command > >  <-- 8 (or whatever number the compatibility plugin has - it's needed by the change_sqlpass plugin)  SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Plugins Installed Plugins 1. delete_move_next 2. squirrelspell 3. newmail 4. compatibility Available Plugins: 5. administrator 6. bug_report 7. calendar 8. change_sqlpass 9. filters 10. fortune 11. info 12. listcommands 13. mail_fetch 14. message_details 15. sent_subfolders 16. spamcop 17. test 18. translate R Return to Main Menu C Turn color off S Save data Q Quit Command > >  <-- 8 (the number of the change_sqlpass plugin)  SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Plugins Installed Plugins 1. delete_move_next 2. squirrelspell 3. newmail 4. compatibility 5. change_sqlpass Available Plugins: 6. administrator 7. bug_report 8. calendar 9. filters 10. fortune 11. info 12. listcommands 13. mail_fetch 14. message_details 15. sent_subfolders 16. spamcop 17. test 18. translate R Return to Main Menu C Turn color off S Save data Q Quit Command > >  <-- S  SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Plugins Installed Plugins 1. delete_move_next 2. squirrelspell 3. newmail 4. compatibility 5. change_sqlpass Available Plugins: 6. administrator 7. bug_report 8. calendar 9. filters 10. fortune 11. info 12. listcommands 13. mail_fetch 14. message_details 15. sent_subfolders 16. spamcop 17. test 18. translate R Return to Main Menu C Turn color off S Save data Q Quit Command > > S Data saved in config.php Press enter to continue...  <-- ENTER  SquirrelMail Configuration : Read: config.php (1.4.0) --------------------------------------------------------- Plugins Installed Plugins 1. delete_move_next 2. squirrelspell 3. newmail 4. compatibility 5. change_sqlpass Available Plugins: 6. administrator 7. bug_report 8. calendar 9. filters 10. fortune 11. info 12. listcommands 13. mail_fetch 14. message_details 15. sent_subfolders 16. spamcop 17. test 18. translate R Return to Main Menu C Turn color off S Save data Q Quit Command > >  <-- Q  

Cuối cùng cần chỉnh sửa file /etc/squirrelmail/config_local.php và chú giải bên phía ngoài biến $default_folder_prefix – nếu không thực hành bước này, bạn sẽ thu được thông báo lỗi trong SquirrelMail sau khi đăng nhập: Query: CREATE “Sent” Reason Given: Invalid mailbox name .

vi /etc/squirrelmail/config_local.php

 

Mở trình duyệt và gõ địa điểm http://server1.example.com/webmail hoặc http://192.168.0.100/webmail để truy cập SquirrelMail, sử dụng tài khoản email (ở đây là sales@example.com ) và mật khẩu khai báo bên trên để đăng nhập:

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

Bạn sẽ thấy email welcome trong mục inbox:

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

Để thay đổi mật khẩu, chọn Options > Change Password :

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

Gõ mật khẩu ngày nay và mật khẩu mới 2 lần:

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

Ngay sau khi đổi mật khẩu, bạn sẽ bị “ văng ” ra khỏi cửa sổ làm việc ngày nay và phải tiến hành đăng nhập lại:

Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail

19. Các link tham khảo

  • Postfix MTA: http://www.postfix.org/
  • Postfix Quota Patch: http://web.onda.com.br/nadal/
  • phpMyAdmin: http://www.phpmyadmin.net/
  • SquirrelMail: http://www.squirrelmail.org/
  • Fedora: http://fedoraproject.org/

Postfix, MTA, cài đặt mail server, cài đặt Courier, máy chủ Postfix, webmail, SquirrelMail, ảo hóa, ảo hóa người dùng, ảo hóa user, ảo hóa domain

Nội dung Ảo hóa người dùng và tên miền với Postfix, Courier, MySQL và SquirrelMail được tổng hợp sưu tầm biên tập bởi: Tin Học Trường Tín. Mọi ý kiến vui lòng gửi Liên Hệ cho truongtin.top để điều chỉnh. truongtin.top tks.

Bài Viết Liên Quan


Xếp Hạng post

Bài Viết Khác

--