Интересное

Сообщение об ошибке

Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in drupal_environment_initialize() (line 684 of /home/www/nixtalk.com/includes/bootstrap.inc).

Почтовый сервер Exim+Dovecot

Опубликовано вс, 12/15/2013 - 18:26 пользователем Demontager

Почтовый сервер Exim+Dovecot
Заметка о том как можно настроить самый простой почтовый сервер на базе Exim и Dovecot. Этот конфиг я использовал на FreeBSD сервере и только модифицировал его чтобы он работал на Debian/Ubuntu Linux. Используется простая SMTP авторизация с хранением аккаунтов и паролей в базе данных MySQL. Так как мне не нужно защищенное соединение, SSL/TLS авторизация не используется.
Пошагово разберем установку

1. Начнем с установки пакетов

  1. #apt-get install dovecot-imapd dovecot-pop3d dovecot-common dovecot-mysql exim4-daemon-heavy

2. Ставим mysql сервер и задаем пароль рута

  1. apt-get install mysql-server
  2. mysqladmin -u root password NEWPASSWORD

3. Заранее подготовил структуру таблиц в базе mysql. Сохраните ее в формате base.sql в любом текстовом редакторе и подготовьте для иморта.

  1. -- phpMyAdmin SQL Dump
  2. -- version 4.0.4-rc1
  3. -- http://www.phpmyadmin.net
  4. --
  5. -- Host: localhost
  6. -- Generation Time: Dec 15, 2013 at 03:08 PM
  7. -- Server version: 5.5.29-0ubuntu1
  8. -- PHP Version: 5.4.9-4ubuntu2
  9.  
  10. SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
  11. SET time_zone = "+00:00";
  12.  
  13.  
  14. /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
  15. /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
  16. /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
  17. /*!40101 SET NAMES utf8 */;
  18.  
  19. --
  20. -- Database: `exim_db`
  21. --
  22.  
  23. -- --------------------------------------------------------
  24.  
  25. --
  26. -- Table structure for table `accounts`
  27. --
  28.  
  29. CREATE TABLE IF NOT EXISTS `accounts` (
  30. `login` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
  31. `password` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
  32. `uid` int(11) NOT NULL DEFAULT '118',
  33. `gid` int(11) NOT NULL DEFAULT '8',
  34. `domain` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT 'nixtalk.com',
  35. `quota` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '250M',
  36. `status` int(11) NOT NULL DEFAULT '1',
  37. PRIMARY KEY (`login`,`domain`)
  38. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  39.  
  40. --
  41. -- Dumping data for table `accounts`
  42. --
  43.  
  44. INSERT INTO `accounts` (`login`, `password`, `uid`, `gid`, `domain`, `quota`, `status`) VALUES
  45. ('support', 'secretPassword', 118, 8, 'nixtalk.com', '250M', 1);
  46.  
  47. -- --------------------------------------------------------
  48.  
  49. --
  50. -- Table structure for table `aliases`
  51. --
  52.  
  53. CREATE TABLE IF NOT EXISTS `aliases` (
  54. `address` varchar(128) COLLATE utf8_bin DEFAULT NULL,
  55. `goto` varchar(128) COLLATE utf8_bin DEFAULT NULL,
  56. `domain` varchar(128) COLLATE utf8_bin DEFAULT 'nixtalk.com'
  57. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  58.  
  59. -- --------------------------------------------------------
  60.  
  61. --
  62. -- Table structure for table `domains`
  63. --
  64.  
  65. CREATE TABLE IF NOT EXISTS `domains` (
  66. `domain` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
  67. `status` int(11) NOT NULL DEFAULT '1',
  68. PRIMARY KEY (`domain`)
  69. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  70.  
  71. --
  72. -- Dumping data for table `domains`
  73. --
  74.  
  75. INSERT INTO `domains` (`domain`, `status`) VALUES
  76. ('nixtalk.com', 1);
  77.  
  78. -- --------------------------------------------------------
  79.  
  80. --
  81. -- Table structure for table `whitelist`
  82. --
  83.  
  84. CREATE TABLE IF NOT EXISTS `whitelist` (
  85. `senders` varchar(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'support@nixtalk.com'
  86. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  87.  
  88. /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
  89. /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
  90. /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Пояснения к cтруктуре базы:
для примера уже вставлен один аккаунт support@nixtalk.com c квотой 250M. Если нужно добавить другой аккаунт, предпочтительно делать это в phpmyadmin, выбрав таблицу и нажав Insert.
по дефолту доступ к почте имеет пользователь с uid 118, входящий в группу с gid 8

Импортируем базу через phpmyadmin или с терминала

  1. mysql -uroot -pMySQLpass exim_db < base.sql

4. Редактируем основной конфиг exim-а

  1. nano /etc/exim4/update-exim4.conf.conf
  2. #почта будет ходить через Internet
  3. dc_eximconfig_configtype='internet'
  4. dc_other_hostnames='nixtalk.com'
  5. dc_local_interfaces='127.0.0.1'
  6. dc_readhost=''
  7. dc_relay_domains='nixtalk.com'
  8. dc_minimaldns='false'
  9. #через эти сети разрешен relay
  10. dc_relay_nets='127.0.0.1:77.124.5.76'
  11. dc_smarthost=''
  12. CFILEMODE='644'
  13. dc_use_split_config='false'
  14. dc_hide_mailname=''
  15. dc_mailname_in_oh='true'
  16. dc_localdelivery='mail_spool'

dc_use_split_config='false' - очень важный момент, этим мы указывает что хотим использовать только один конфигурационный файл для exim. Это сделано в целях удобства, так как общая конфигурация довольна простая и не требует указания большого количества директив.
После внесения изменений не забываем выполнить

  1. update-exim4.conf

Все файлы и папки кроме update-exim4.conf.conf и exim4.conf.template можно удалить. Теперь редактируем exim4.conf.template

  1. nano /etc/exim4/exim4.conf.template

и приводим к такому виду, заменяя на свои данные

  1. primary_hostname = mail.nixtalk.com
  2. # имя базы и пароль
  3. hide mysql_servers = localhost/exim_db/exim/eximPassword
  4. domainlist local_domains = ${lookup mysql{select domain from domains where domain='${domain}'}}
  5. domainlist relay_to_domains = ${lookup mysql{select domain from domains where domain='${domain}'}}
  6. hostlist relay_from_hosts = localhost : 127.0.0.1
  7. acl_smtp_rcpt = acl_check_rcpt
  8. acl_smtp_data = acl_check_data
  9. #tls_certificate = /etc/ssl/certs/favmail.pem
  10. #tls_privatekey = /etc/ssl/certs/favmail.pem
  11. #порт smtp
  12. daemon_smtp_ports = 25
  13. #tls_on_connect_ports = 465
  14. qualify_domain = mail.nixtalk.com
  15. allow_domain_literals = false
  16. exim_user = Debian-exim
  17. exim_group = mail
  18. never_users = root
  19. host_lookup = *
  20. rfc1413_hosts = *
  21. rfc1413_query_timeout = 5s
  22. ignore_bounce_errors_after = 2h
  23. timeout_frozen_after = 7d
  24. return_size_limit = 10K
  25. split_spool_directory = true
  26. syslog_timestamp = no
  27. begin acl
  28.  
  29.  
  30. acl_check_rcpt:
  31. accept hosts = :
  32.  
  33. deny domains = +local_domains
  34. local_parts = ^[.] : ^.*[@%!/|]
  35.  
  36. deny domains = !+local_domains
  37. local_parts = ^[./|] : ^.*[@%!] : ^.*/\\.\\./
  38.  
  39. accept senders=${lookup mysql{SELECT senders FROM whitelist \
  40. WHERE senders='${quote_mysql:$sender_address}'}}
  41.  
  42. deny message = HELO/EHLO required by SMTP RFC
  43. condition = ${if eq{$sender_helo_name}{}{yes}{no}}
  44.  
  45. deny message = Go Away! You are spammer.
  46. condition = ${if match{$sender_host_name} \
  47. {bezeqint\\.net|net\\.il|pool|peer|dhcp} \
  48. {yes}{no}}
  49.  
  50. deny message = rejected because $sender_host_address \
  51. is in a black list at $dnslist_domain\n$dnslist_text
  52. hosts = !+relay_from_hosts
  53. !authenticated = *
  54. log_message = found in $dnslist_domain
  55. dnslists = bl.spamcop.net : \
  56. cbl.abuseat.org : \
  57. dnsbl.njabl.org : \
  58. pbl.spamhaus.org
  59. warn
  60. set acl_m0 = 25s
  61. warn
  62. hosts = +relay_from_hosts
  63. set acl_m0 = 0s
  64. warn
  65. authenticated = *
  66. set acl_m0 = 0s
  67.  
  68. warn
  69. logwrite = Delay $acl_m0 for $sender_host_name \
  70. [$sender_host_address] with HELO=$sender_helo_name. Mail \
  71. from $sender_address to $local_part@$domain.
  72. delay = $acl_m0
  73.  
  74. drop message = Rejected - Sender Verify Failed
  75. log_message = Rejected - Sender Verify Failed
  76. hosts = *
  77. !verify = sender/no_details/callout=2m,defer_ok
  78. !condition = ${if eq{$sender_verify_failure}{}}
  79.  
  80.  
  81. accept domains = +local_domains
  82. endpass
  83. message = unknown user
  84. verify = recipient
  85.  
  86. accept domains = +relay_to_domains
  87. endpass
  88. message = unrouteable address
  89. verify = recipient
  90.  
  91. accept hosts = +relay_from_hosts
  92. accept authenticated = *
  93. deny message = relay not permitted
  94.  
  95. acl_check_data:
  96.  
  97. # China symbols
  98. deny message = This is spam - denied
  99. !senders = :
  100. condition = ${if match{$message_body}{105[-_]*51[-_]*86|778[-_]*98[-_]*94}{yes}{no}}
  101.  
  102. #Extensions
  103. deny message = contains $found_extension file (blacklisted).
  104. !senders = :
  105. demime = com:vbs:bat:pif:scr:exe
  106. #Check MIME
  107. deny message = This message contains a MIME error ($demime_reason)
  108. !senders = :
  109. demime = *
  110. condition = ${if >{$demime_errorlevel}{2}{1}{0}}
  111.  
  112. #Messages with NUL- symbols
  113. deny message = This message contains NUL characters
  114. !senders = :
  115. log_message = NUL characters!
  116. condition = ${if >{$body_zerocount}{0}{1}{0}}
  117.  
  118. # Headers
  119. deny message = Incorrect headers syntax
  120. hosts = !+relay_from_hosts:*
  121. !senders = :
  122. !verify = header_syntax
  123. accept
  124.  
  125. begin routers
  126. dnslookup:
  127. driver = dnslookup
  128. domains = ! +local_domains
  129. transport = remote_smtp
  130. ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
  131. no_more
  132.  
  133. system_aliases:
  134. driver = redirect
  135. allow_fail
  136. allow_defer
  137. data = ${lookup mysql{select goto from aliases where address='${quote_mysql:$local_part}' and domain='${quote_mysql:$domain}'}}
  138. user = Debian-exim
  139. group = mail
  140. file_transport = address_file
  141. pipe_transport = address_pipe
  142.  
  143. userforward:
  144. driver = redirect
  145. check_local_user
  146. no_verify
  147. no_expn
  148. check_ancestor
  149. file_transport = address_file
  150. pipe_transport = address_pipe
  151. reply_transport = address_reply
  152. data = ${lookup mysql{select goto from aliases where address='${quote_mysql:$local_part}' and domain='${quote_mysql:$domain}'}}
  153.  
  154. localuser:
  155. driver = accept
  156. domains = ${lookup mysql{select domain from domains where domain='${domain}'}}
  157. local_parts = ${lookup mysql{select login from accounts where login='${local_part}' and domain='${domain}'}}
  158. transport = local_delivery
  159. cannot_route_message = Unknown user
  160.  
  161. begin transports
  162.  
  163. remote_smtp:
  164. driver = smtp
  165.  
  166. local_delivery:
  167. driver = appendfile
  168. maildir_format
  169. maildir_tag = ,S=$message_size
  170. directory = /home/mail/$domain/$local_part
  171. create_directory
  172. delivery_date_add
  173. envelope_to_add
  174. return_path_add
  175. group = mail
  176. mode = 0660
  177. no_mode_fail_narrower
  178.  
  179. address_pipe:
  180. driver = pipe
  181. return_output
  182.  
  183. address_file:
  184. driver = appendfile
  185. delivery_date_add
  186. envelope_to_add
  187. return_path_add
  188.  
  189. address_reply:
  190. driver = autoreply
  191.  
  192. begin retry
  193.  
  194. * * F,2h,15m; G,16h,1h,1.5; F,4d,6h
  195.  
  196. begin rewrite
  197.  
  198. begin authenticators
  199.  
  200. auth_plain:
  201. driver = plaintext
  202. server_set_id = $2
  203. server_prompts = :
  204. public_name = PLAIN
  205. server_condition = ${lookup mysql{select login from accounts where login='${quote_mysql:${local_part:$2}}' and password='${quote_mysql:$3}'}{yes}{no}}
  206.  
  207. auth_login:
  208. driver = plaintext
  209. public_name = LOGIN
  210. server_set_id = $1
  211. server_prompts = Username:: : Password::
  212. server_condition = ${lookup mysql{select login from accounts where login='${quote_mysql:${local_part:$1}}' and password='${quote_mysql:$2}'}{yes}{no}}
  213.  
  214. auth_cram_md5:
  215. driver = cram_md5
  216. public_name = CRAM-MD5
  217. server_secret = ${lookup mysql{select password from accounts where login='${quote_mysql:${local_part:$1}}'}{$value}fail}
  218. server_set_id = $1

5. Теперь настроим dovecot, редактируем
nano /etc/dovecot/dovecot.conf

  1. auth_default_realm = mail.nixtalk.com
  2. auth_verbose = yes
  3. base_dir = /var/run/dovecot/
  4. disable_plaintext_auth = no
  5. first_valid_gid = 8
  6. first_valid_uid = 118
  7. login_greeting = Dovecot ready
  8. log_path = /var/log/dovecot.log
  9. login_log_format_elements = user=<%u> method=%m rip=%r lip=%l %c
  10. mail_access_groups = mail
  11. mail_debug = yes
  12. mail_location = maildir:/home/mail/%d/%n
  13. passdb {
  14. args = /etc/dovecot/dovecot-sql.conf
  15. driver = sql
  16. }
  17. protocols = pop3 imap
  18. service auth {
  19. unix_listener auth-master {
  20. mode = 0600
  21. user = Debian-exim
  22. }
  23. user = root
  24. }
  25. service imap-login {
  26. chroot = login
  27. inet_listener imap {
  28. address = *
  29. port = 143
  30. }
  31. process_limit = 3
  32. process_min_avail = 3
  33. service_count = 1
  34. user = dovecot
  35. vsz_limit = 64 M
  36. }
  37. service pop3-login {
  38. chroot = login
  39. inet_listener pop3 {
  40. address = *
  41. port = 110
  42. }
  43. process_limit = 3
  44. process_min_avail = 3
  45. service_count = 1
  46. user = dovecot
  47. vsz_limit = 64 M
  48. }
  49. ssl = no
  50. #ssl_cert = </etc/ssl/certs/favmail.pem
  51. #ssl_key = </etc/ssl/certs/favmail.pem
  52. userdb {
  53. args = /etc/dovecot/dovecot-sql.conf
  54. driver = sql
  55. }
  56. verbose_proctitle = yes
  57.  
  58. #protocol imap {
  59. # imap_client_workarounds = delay-newmail tb-extra-mailbox-sep
  60. #}
  61.  
  62. protocol pop3 {
  63. pop3_client_workarounds = outlook-no-nuls oe-ns-eoh
  64. pop3_uidl_format = %08Xu%08Xv
  65. }
  66. protocol lda {
  67. auth_socket_path = /var/run/dovecot/auth-master
  68. postmaster_address = support@nixtalk.com
  69. }

6. Редактируем конфиг dovecot для доступа к mysql базе
nano /etc/dovecot/dovecot-sql.conf

  1. driver=mysql
  2. connect=host=127.0.0.1 dbname=exim_db user=exim password=eximPassword
  3. default_pass_scheme=PLAIN
  4. password_query=select password from accounts where login='%n' and domain='%d'
  5. user_query=select uid, gid from accounts where login='%n' and domain='%d'

7. Создаем директорию для писем и даем ей права

  1. mkdir /home/mail
  2. chown Debian-exim:exim /home/mail

8. Прописываем в /etc/hosts IP нашего почтового сервера

  1. 77.124.5.76 nixtalk.com
  2. 77.124.5.76 mail.nixtalk.com

На этом настройка закончена и в конце даю короткие команды где смотреть логи

  1. tailf /var/log/dovecot.log
  2. tailf /var/log/exim4/mainlog
  3. tailf /var/log/exim4/rejectlog
  4. tailf /var/log/exim4/paniclog # Появляется при фатальных ошибках

Перезапуск сервисов

  1. serviсe dovecot restart
  2. service exim4 restart
category_index: 
Поделится: 

2 комментария

Аватар пользователя Hectorsigo

автор Hectorsigo вкл пт, 05/13/2016 - 02:36

There is certainly noticeably a bundle to understand this. I presume you've produced specific nice points in characteristics also.
I'd like to uslysht somewhat much more on this subject
I'm a lengthy time ago I read your weblog and has extended been expressing that you’re an excellent author
Find out to publish himself, the article from an additional source
I’m a long time watcher and I just believed I’d drop by and say hello there there for the really 1st time.

Аватар пользователя Alexey

автор Alexey вкл вс, 01/28/2018 - 04:41

Похоже у вас опечатка: в п.7 :
chown Debian-exim:exim /home/mail

а в конфигурации nano /etc/exim4/exim4.conf.template п.4
exim_user = Debian-exim
exim_group = mail

Т.е в п.7 должно быть: chown Debian-exim:mail, верно?

Добавить комментарий