프리이미지
사이트 내 전체검색

우분투 메일서버 설치

페이지 정보

작성일11-09-15 10:50

본문

 
1.1 준비
대상 OS: Ubuntu 8.04, 8.10
host name(FQDN): aaaaaaaa.org
host ip address: 192.168.0.1
 
루트 사용자로 작업을 진행한다.
sudo su
sudo bash
 
#----------------------------------------
 
disable AppArmor:
sudo /etc/init.d/apparmor stop
sudo update-rc.d -f apparmor remove
sudo apt-get remove apparmor apparmor-utils
 
#----------------------------------------
# Install Postfix, Courier, Saslauthd, MySQL, phpMyAdmin
# To install Postfix, Courier, Saslauthd, MySQL, and phpMyAdmin, we simply run
sudo apt-get install postfix postfix-mysql postfix-doc mysql-client mysql-server courier-authdaemon courier-authlib-mysql courier-pop courier-pop-ssl courier-imap courier-imap-ssl libsasl2-2 libsasl2-modules libsasl2-modules-sql sasl2-bin libpam-mysql openssl apache2 apache2.2-common apache2-utils phpmyadmin libapache2-mod-php5 php5 php5-mysql libpam-smbpass
 
apt-get install sasl2-bin

MySQL, Courier 등의 설정 질문에 아래와 같이 비밀번호 등을 입력한다.
New password for the MySQL "root" user: <-- root sql password
Repeat password for the MySQL "root" user: <-- root sql password
Create directories for web-based administration? <-- No
General type of mail configuration: <-- Internet Site
System mail name: <-- mail.aaaaaaaa.org
SSL certificate required <-- Ok
Web server to reconfigure automatically: <-- apache2
 
 
#----------------------------------------
Postfix reconfigure
postfix 재설정을 할 경우 도메인 이름과 포스트마스터에 대한 alias 설정을 꼭 한다.
sudo dpkg-reconfigure postfix
domain name
postmaster
 
 
4 Create The MySQL Database For Postfix/Courier
 
Now we create a database called mail:
mysqladmin -u root -p create mail
 
Next, we go to the MySQL shell:
mysql -u root -p
 
select, insert, update, delete 권한을 mail_admin에 준다.
mysql> grant select, insert, update, delete on mail.* to 'mail_admin'@'localhost' identified by 'password';
mysql> grant select, insert, update, delete on mail.* to 'mail_admin'@'192.168.1.%' identified by 'password';
mysql> flush privileges;
 
'mail_admin'@'localhost' 은 localhost 에서 db 접근을 허용
'mail_admin'@'192.168.1.%' 은 192.168.1 네트워크에서 db 접근을 허용
 
table 생성
mysql> USE mail;
 
CREATE TABLE mail_domains (
domain varchar(50) NOT NULL,
PRIMARY KEY (domain) )
TYPE=MyISAM;
 
CREATE TABLE mail_forwardings (
source varchar(80) NOT NULL,
destination TEXT NOT NULL,
PRIMARY KEY (source) )
TYPE=MyISAM;
 
CREATE TABLE mail_users (
email varchar(80) NOT NULL,
password varchar(20) NOT NULL,
quota INT(10) DEFAULT '10485760',
PRIMARY KEY (email)
) TYPE=MyISAM;
 
CREATE TABLE mail_transport (
domain varchar(128) NOT NULL default '',
transport varchar(128) NOT NULL default '',
UNIQUE KEY domain (domain)
) TYPE=MyISAM;
 
quit;
 
domain 테이블 : 가상 도메인 이름
domain
aaaaaaaa.org
 
forwarding 테이블: 포워딩으로 설정된 이메일 alias
source destination
info@aaaaaaaa.org sales@aaaaaaaa.org
 
user 테이블: 사용자 이메일과 암호화된 패스워드, quota의 기본 값은 10485760로 10Mb이다.
email password quota
sales@aaaaaaaa.org No9.E4skNvGa. ("secret" in encrypted form) 10485760
 
transport 테이블: 옵션으로 It allows to forward mails for single users, whole domains or all mails to another server. 
domain transport
aaaaaaaa.org smtp:[1.2.3.4]
위 사례는 도메인 aaaaaaaa.org으로 오는 모든 메일이 smtp를 이용해 1.2.3.4로 전달한다.
the square brackets [] mean "do not make a lookup of the MX DNS record"
도메일 명을 이용하면 []를 사용하지 말라.
 
예제
mysql> INSERT INTO 'mail_domains' ('domain') VALUES ('aaaaaaaa.org');
mysql> INSERT INTO mail_users('email', 'password', 'quota') VALUES ('xxxxxxxxxx@aaaaaaaa.org', ENCRYPT('1234'), 104857600);
 

5 Configure Postfix
postfix와 mysql의 통신은 127.0.0.1을 통해 이루어지고, mysqld 데몬에서 127.0.0.1주소와 바인딩을 해야한다.
 
 
vi /etc/mysql/my.cnf
bind-address = 127.0.0.1
/etc/init.d/mysql restart
 
 
sudo dpkg-reconfigure postfix ;
postconf -e 'home_mailbox = Maildir/'

Postfix와 mysql 설정을 위한 여섯개의 파일을 만든다.
혹은 첨부된 자료를 이용: postfix-mysq-cf.tar.bz2

#----------------------------------------

vi /etc/postfix/mysql-virtual_domains.cf
user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT domain AS virtual FROM mail_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 mail_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 mail_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 mail_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 mail_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 mail_users WHERE email='%s' 
hosts = 127.0.0.1

sudo chmod o= /etc/postfix/mysql-virtual_*.cf
sudo chgrp postfix /etc/postfix/mysql-virtual_*.cf
sudo groupadd -g 5000 vmail
sudo useradd -g vmail -u 5000 vmail -d /data/vmail -m

#----------------------------------------


vmail 의 홈디렉토리는 메일이 저장되는 홈 디렉토리 이므로 적절한 공간에 위치해야 한다.
Postfix configuration
aaaaaaaa.org으로 해당 도메인으로 변경해서 설정을 진행한다.
mailbox_base를 변경하고자 하면 앞서 vmail 사용자 추가시 vmail의 홈디렉토리를 변경후 해당 디렉토리를 사용한다.
첨부 파일 참조: main.cf
아래 postconf 명령을 수행하거나, /etc/postfix/main.cf 를 수정해 넣는다.
postconf -e 'myhostname = mail.aaaaaaaa.org'
postconf -e 'mydestination = $mydomain, $myhostname'
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 = /data/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 'virtual_mailbox_extended = yes'


Maildir 사용: 
postconf -e 'virtual_mailbox_extended = yes'

#----------------------------------------

TLS에서 사용하게 되는 ssl 인증서를 생성한다.
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) [AU]:KO
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:SEOUL
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bukwang Pharm. Inc.,LTD.
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:bukwang
Email Address []:it_contact@bukwang.kr
Then change the permissions of the smtpd.key:


sudo chmod o= /etc/postfix/smtpd.key

#----------------------------------------

6 Configure Saslauthd

sudo mkdir -p /var/spool/postfix/var/run/saslauthd

vi /etc/default/saslauthd

Set START to yes 그리고, OPTIONS="-c -m /var/run/saslauthd" 을 아래와 같이 변경

START=yes
PWDIR="/var/spool/postfix/var/run/saslauthd"
PARAMS="-m ${PWDIR} -r"

START=yes
OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"

vi /etc/pam.d/smtp
auth required pam_mysql.so user=mail_admin passwd=mail_admin_password host=127.0.0.1 db=mail table=users usercolumn=email passwdcolumn=password crypt=1
account sufficient pam_mysql.so user=mail_admin passwd=mail_admin_password host=127.0.0.1 db=mail table=users usercolumn=email passwdcolumn=password crypt=1

vi /etc/postfix/sasl/smtpd.conf
pwcheck_method: saslauthd
mech_list: plain login
allow_plaintext: true
auxprop_plugin: mysql
sql_hostnames: 127.0.0.1
sql_user: mail_admin
sql_passwd: mail_admin_passwordsql_database: mail
sql_select: select password from mail_users where email = '%u'

postfix 사용자를 sasl 그룹에 속하게 만들어 Postfix가 saslauthd를 접근하게 한다.
adduser postfix sasl

#----------------------------------------

restart
sudo /etc/init.d/postfix restart
sudo /etc/init.d/saslauthd restart


#----------------------------------------

7 Configure Courier
Courier를 MySql을 이용해 인증하게 설정한다.
vi /etc/courier/authdaemonrc
[...]
authmodulelist="authmysql"

DEBUG_LOGIN=2  <-- 디버그 용

[...]

vi /etc/syslog.conf

vi /etc/courier/authmysqlrc
cp /etc/courier/authmysqlrc /etc/courier/authmysqlrc_orig
cat /dev/null > /etc/courier/authmysqlrc
vi /etc/courier/authmysqlrc


MYSQL_HOME 필드는 앞서 vmail의 홈 디렉토리, 즉 mail base의 디렉토리이다.





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

DEFAULT_DOMAIN aaaaaaaa.org
MYSQL_LOGIN_FIELD email 

## 아니면 
# 이것을 이렇게 바꾸어라. .2011-09-15 김성대
# MYSQL_LOGIN_FIELD       substring_index(email,'@',1)


MYSQL_HOME_FIELD "/data/vmail"
MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/')


#----------------------------------------
#MYSQL_NAME_FIELD  name  <-- 막을것
MYSQL_QUOTA_FIELD quota


Then restart Courier:
sudo /etc/init.d/courier-authdaemon restart
sudo /etc/init.d/courier-imap restart
sudo /etc/init.d/courier-imap-ssl restart
sudo /etc/init.d/courier-pop restart
sudo /etc/init.d/courier-pop-ssl restart

#----------------------------------------
Pop3 연결 테스트
telnet localhost pop3
Trying 127.0.0.1...
Connected to localhost.localdomain.
Escape character is '^]'.
+OK Hello there.
quit
+OK Better luck next time.
Connection closed by foreign host.
vi /etc/aliases
postmaster가 root를 가르키게 한다.
[...] postmaster: root



 root: user_id@aaaaaaaa.org [...]
우분투, 데비안의 경우 sudo 사용자로 root가 지정되어 있다.
혹은 root: administrator 형식도 괜잖다.
$sudo newaliases
sudo /etc/init.d/postfix restart


#----------------------------------------

12 Test Postfix
 
Postfix 가 SMTP-AUTH 와 TLS로 준비되었는지 점거.
 
telnet localhost 25
...
ehlo localhost
250-gtko-ubuntu.bukwang
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH CRAM-MD5 NTLM DIGEST-MD5 LOGIN PLAIN
250-AUTH=CRAM-MD5 NTLM DIGEST-MD5 LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
...
quit
 
 
pop3 확인
$ telnet localhost pop3
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
user xxxxxxxxxx
+OK Password required.
pass 1234
+OK logged in.


imap 확인
$ telnet localhost imap
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION] Courier-IMAP ready. Copyright 1998-2005 Double Precision, Inc. See COPYING for distribution information.
imap login
imap OK LOGIN Ok.
 
 
 
13 Populate The Database And Test
사용자를 DB에 추가해 테스트 한다.
 
 
domains and users:
INSERT INTO `domains` (`domain`) VALUES ('bukwang');
INSERT INTO users(`email`, `password`, `quota`) VALUES ('gtko@bukwang', ENCRYPT('012345'), 10485760);
forwarding and transport 에 대한 설정이 필요하면
INSERT INTO `forwardings` (`source`, `destination`) VALUES ('info@aaaaaaaa.org', 'sales@aaaaaaaa.org');
INSERT INTO `transport` (`domain`, `transport`) VALUES ('aaaaaaaa.org', 'smtp:mail.aaaaaaaa.org');
 
The forwardings table can have entries like the following:
source destination  
info@aaaaaaaa.org sales@aaaaaaaa.org Redirects emails for info@aaaaaaaa.org to sales@aaaaaaaa.org
@aaaaaaaa.org thomas@aaaaaaaa.org Creates a Catch-All account for thomas@aaaaaaaa.org. All emails to aaaaaaaa.org will arrive at thomas@aaaaaaaa.org, except those that exist in the users table (i.e., if sales@aaaaaaaa.org exists in the users table, mails to sales@aaaaaaaa.org will still arrive at sales@aaaaaaaa.org).
@aaaaaaaa.org @anotherdomain.tld This redirects all emails to aaaaaaaa.org to the same user at anotherdomain.tld. E.g., emails to thomas@aaaaaaaa.org will be forwarded to thomas@anotherdomain.tld.
info@aaaaaaaa.org sales@aaaaaaaa.org, billing@anotherdomain.tld Forward emails for info@aaaaaaaa.org to two or more email addresses. All listed email addresses under destination receive a copy of the email.
 
The transport table can have entries like these:
domain transport  
aaaaaaaa.org : Delivers emails for aaaaaaaa.org locally. This is as if this record would not exist in this table at all.
aaaaaaaa.org smtp:mail.anotherdomain.tld Delivers all emails for aaaaaaaa.org via smtp to the server mail.anotherdomain.com.
aaaaaaaa.org smtp:mail.anotherdomain.tld:2025 Delivers all emails for aaaaaaaa.org via smtp to the server mail.anotherdomain.com, but on port 2025, not 25 which is the default port for smtp.
aaaaaaaa.org
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.
.aaaaaaaa.org smtp:mail.anotherdomain.tld Mail for any subdomain of aaaaaaaa.org is delivered to mail.anotherdomain.tld.
* smtp:mail.anotherdomain.tld All emails are delivered to mail.anotherdomain.tld.
joe@aaaaaaaa.org smtp:mail.anotherdomain.tld Emails for joe@aaaaaaaa.org are delivered to mail.anotherdomain.tld.
Please keep in mind that the order of entries in the transport table is important! The entries will be followed from the top to the bottom.
Important: Postfix uses a caching mechanism for the transports, therefore it might take a while until you changes in the transport table take effect. If you want them to take effect immediately, run
postfix reload
after you have made your changes in the transport table.
 
 
 
14 Send A Welcome Email For Creating Maildir
When you create a new email account and try to fetch emails from it (with POP3/IMAP) you will probably get error messages saying that the Maildir doesn't exist. The Maildir is created automatically when the first email arrives for the new account. Therefore it's a good idea to send a welcome email to a new account.
First, we install the mailx package:
 
apt-get install mailx
 
To send a welcome email to sales@aaaaaaaa.org, we do this:
 
mailx sales@aaaaaaaa.org
You will be prompted for the subject. Type in the subject (e.g. Welcome), then press ENTER, and in the next line type your message. When the message is finished, press ENTER again so that you are in a new line, then press CTRL+D; if you don't want to cc the mail, press ENTER again:
root@server1:/usr/local/sbin# mailx sales@aaaaaaaa.org
Subject: Welcome <-- ENTER
Welcome! Have fun with your new mail account. <-- ENTER
<-- CTRL+D
Cc: <-- ENTER
 
세팅이 다 끝난 후에 썬더버드등 을 통하여 메일을 보낼 때 보내고 받는 것에는 이상이 없지만 인증서와 관련하여 창이 계속 뜬다.
 
그것을 해결 하기 위해서는 먼저  /etc/courier/ 밑에 있는 imapd.cnf 파일을 알맞게 수정하여 준다.]
(작업 과정 중에 혹시 있을 일을 대비하여 복사본을 만들어 놓은 후 작업을 한다.)
cd /etc/courier
cp imapd.cnf imapd.cnf.orig
cp impad.pem imapd.pem.orig
vi imapd.cnf
 
[ req_dn ]
C=US    ex) KO
ST=NY     ex) SE ,SEOUL , KYUNGKIDO...
L=New York     ex) SEOUL ,POCHUN , DONGJAKGU ....O=Courier Mail Server     ex) Embedin CO.
OU=Automatically-generated IMAP SSL key   삭제하여도 무방.CN=localhost   ex) embedin.co.kr  *가장 중요한 부분. 자신이 설정한 도메인명과 동일 하여야함.*emailAddress = postmaster@exampl.com ex) it_contact@embedin.co.kr
 
수정이 끝났으면 폴더내에 imapd.pem 파일이 있는지 확인 후. 있다면 삭제.
게시물 검색