«Java Script» и «Почтовый сервер на Debian 9 полная установка: dbmail & postgresql & postfix & stunnel & postgrey& spamassassin»: разница между страницами

Материал из support.qbpro.ru
(Различия между страницами)
imported>Supportadmin
 
imported>Vix
Нет описания правки
 
Строка 1: Строка 1:
==Как бы учебник==
'''Руководство для быстрого развертывания собственного сервера почты.'''<br>
*[[Операторы JavaScript]]
* ''Данная статья появилась тут в связи с тем, что я столкнулся с проблемой переноса почтового сервера на обычной файловой системе.''
*[[Массивы JavaScript]]
''В первую очередь с тем, что почта была организована на уже устаревшем ПО и перенос ее на новую платформу без потерь стал практически не возможен.
*[[Объекты JavaScript]]
А вот хранение почты в базе данных, дает огромные преимущества при обновлении или доступе к информации, а так же восстановлении. В частности у меня база данных находится на другом хосте, что сильно облегчает ее обслуживание, при этом все конфигурационные файлы самой почты можно легко повторить если понадобится на новом хосте для создания почтового сервера заново.''<br>
*[[Особенности функций в JavaScript]]
**[[Возвратные функции]]
*[[ООП JavaScript - наследование]]
*[[Область видимости переменной в Javascript]]
*[[Клиентский (браузерный) JavaScript]]
**[[Javascript синхронный и асинхронный запрос]]
*[[JavaScript Strict Mode]]


----
=='''1. Порядок установки dbmail'''==
*[[Масштабируемые JavaScript приложения]]
* '''''Система Debian Stretch {9}'''''
*[[10 несуразностей и секретов JavaScript]]
* Используемый source.list
*[[Используем console на полную]]
#
deb http://mirror.mephi.ru/debian/ stretch main
deb-src http://mirror.mephi.ru/debian/ stretch main
deb http://security.debian.org/debian-security stretch/updates main
deb-src http://security.debian.org/debian-security stretch/updates main
# stretch-updates, previously known as 'volatile'
deb http://mirror.mephi.ru/debian/ stretch-updates main
deb-src http://mirror.mephi.ru/debian/ stretch-updates main
###### Debian Main Repos
deb http://deb.debian.org/debian/ stable main contrib non-free
deb-src http://deb.debian.org/debian/ stable main contrib non-free
deb http://deb.debian.org/debian/ stable-updates main contrib non-free
deb-src http://deb.debian.org/debian/ stable-updates main contrib non-free
deb http://deb.debian.org/debian-security stable/updates main contrib non-free
deb-src http://deb.debian.org/debian-security stable/updates main contrib non-free
deb http://ftp.debian.org/debian stretch-backports main contrib non-free
deb-src http://ftp.debian.org/debian stretch-backports main contrib non-free
1.1 ''Устанавливаем необходимые пакеты:''
apt-get install pkg-config libglib2.0-dev libgmime-2.6-dev libmhash-dev libevent-dev libssl-dev libzdb-dev\
autoconf automake libtool autotools-dev dpkg-dev fakeroot debhelper dh-make libldap2-dev libsieve2-dev ascidoc\
libcrypto++6 libcrypto++-utils libcrypto++-dev xmlto xmltoman libarchive-tools lrzip binutils-multiarch\
arch-test libpgf-dev libsasl2-modules-db libsasl2-modules curl libcroco3 libsasl2-2 procmail libsasl2-modules-sql\
libpcre32-3 zlib1g-dev libmhash-dev libpcrecpp0v5


==Крайне полезная информация==
1.2 ''Скачиваем с [http://www.dbmail.org/index.php?page=download dbmail.org] исходники:''
wget -c -t 0 -T 8 http://www.dbmail.org/download/3.1/dbmail-3.1.17.tar.gz


Это надо обработать
1.3 ''Распаковываем и компилируем:''
*[http://jsperf.com/array-prototype-push-apply-vs-concat/20 Тесты производительности циклов, работы с массивами и т.д.]
cp dbmail-3.1.17.tar.gz /usr/local/src
*'''[http://bonsaiden.github.com/JavaScript-Garden/ru/ JavaScript Гарден]'''
tar -xf dbmail-3.1.17.tar.gz /usr/local/src.dbmail-3.1.7
*[http://habrahabr.ru/post/117069/ Модульный подход в JavaScript]
cp dbmail-3.1.17.tar.gz /usr/local/src/dbmail_3.1.7.orig.tar.gz
*[http://canegor.urc.ac.ru/gui_for_script/articles/random_sort.htm Случайное перемешивание массива]
* '''[!]''' - ''не знаю, может так у меня получилось, но когда применяешь комменты, версия которая высвечивается именно'' '''3.1.7'''!!
*[http://habrahabr.ru/post/131714/ Javascript наследование для чайников]
* '''[!]''' - ''именно поэтому все, что тут распаковываем и создаем имеет версию'' - 3.1.7 ...
*[http://javascript.ru/basic/operators Операторы, их особенности в JS]
*[http://www.w3schools.com/js/js_comparisons.asp JavaScript Comparison and Logical Operators]
*'''[http://habrahabr.ru/post/138773/  Путь асинхронного самурая]'''
*[http://habrahabr.ru/post/137818/ «Лапша» из callback-ов — будьте проще]
*[http://habrahabr.ru/post/97042/ Как избавиться от пристрастия к синхронности]
*[http://habrahabr.ru/post/137778/ Спагетти в последовательном вызове асинхронных функций. Теория и практика]
*'''[http://hashcode.ru/questions/87809/javascript-xmlhttprequest-%D0%B2-%D1%86%D0%B8%D0%BA%D0%BB%D0%B5 javascript - XMLHttpRequest в цикле]'''  
*[[javascript - XMLHttpRequest подробный анализ примера]]
*[http://javascript.ru/blog/tenshi/mnogopotochnyi-yavaskript Многопоточный яваскрипт]
* [http://javascript.ru/tutorial/object/inheritance работаем с объектами в примерах]
* '''[http://javascript.ru/unsorted/top-10-functions 10 лучших функций на JavaScript]''' - в комментах тьма полезностей
* [http://webo.in/articles/habrahabr/28-chain-javascript-calls-optimization/ ОПТИМИЗИРУЕМ JS]
* http://pyramidin.narod.ru/clientref13/ -очень хорошо описаны функции, их стандартные методы, свойства и использование
* [http://wiki.dieg.info/doku.php/pobitovye_ili_porazrjadnye_operacii Побитовые или поразрядные операции] в конце для js
* [http://ruseller.com/lessons.php?rub=28&id=1445 Прототипы в JavaScript]
* [http://habrahabr.ru/post/49245/ Стыкуем компоненты в JavaScript]
* [http://webo.in/articles/habrahabr/77-coupling-async-scripts/ Стыкуем асинхронные скрипты]
* [http://learn.javascript.ru/gcc-closure-library GCC: интеграция с Google Closure Library]
* [http://creativejs.com/resources/requestanimationframe/ 3d -javascipt]
* [http://stepansuvorov.com/blog/2012/07/%D0%BF%D0%B8%D1%88%D0%B5%D0%BC-%D1%81%D0%B2%D0%BE%D0%B9-uploader-%D1%81-%D0%BD%D1%83%D0%BB%D1%8F-%D0%BD%D0%B0-javascript-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D1%83%D1%8F-fileapi-%D1%87%D0%B0-3/ свой Uploader с нуля]
* [http://alljs.ru/articles/document-write document-write]
* [http://www.jaguar-developers.com/category/articles/javascript_dom/ создаем элементы DOM]
* [http://www.jstoolbox.com/skripty/rabota-s-massivami/zapolnenie-massiva-odinakovymi-znacheniyami/ Заполнение массива одинаковыми значениями]
* [http://webo.in/articles/habrahabr/78-javascript-constructions-performance/ Производительность простых и сложных конструкций в JavaScript]


==обработка событий в примерах==
''Готовим пакет к сборке:''
*[http://on-line-teaching.com/js/js.events.keyboard.htm События клавиатуры и мыши]
cd /usr/local/src/dbmail-3.1.7
*[http://javascript.ru/tutorial/events/properties  Свойства объекта событие]
./configure --prefix=/usr
*[http://www.tigir.com/javascript.htm разные примеры...]
 
*[https://developer.mozilla.org/ru/docs/JavaScript/Guide/Regular_Expressions регулярные выражения - шаблоны]
dpkg-source --commit
==Контекст==
даем имя, что-то: '''pgsql.commit'''<br>
*[http://habrahabr.ru/post/149516/ Ключевое слово this в javascript — учимся определять контекст на практике]
выходим по '''ESC'''<br>
*[http://habrahabr.ru/post/149581/ Привязка контекста (this) к функции в javascript и частичное применение функций]
должно быть так:<br>
*[http://habrahabr.ru/post/103760/ Правильный захват контекста в Javascript]
...
*[http://habrahabr.ru/qa/5846/ JavaScript: что делает Function.call.apply(…)?]
dpkg-source: инфо: локальные изменения были записаны в новую заплату: dbmail-3.1.7/debian/patches/pgsql.commit
*[http://ru.wikipedia.org/wiki/%D0%A1%D1%82%D1%80%D0%B0%D1%82%D0%B5%D0%B3%D0%B8%D1%8F_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F) Стратегия (шаблон проектирования)]
[http://javascript.ru/ecma/part10 Контексты исполнения]
*[http://habrahabr.ru/post/112069/ предсказание элемента формы]


==Библиотеки==
далее:
*[http://qooxdoo.org/ JavaScript-фреймворк qooxdoo 1.6] - новое слово в вебинтерфейсах
cd /usr/local/src/
:*[http://www.opennet.ru/opennews/art.shtml?num=32573 Новость про qooxdoo 1.6]
dpkg-source -b dbmail-3.1.7
*[http://www.leemon.com/crypto/BigInt.js JS библиотека для работы с большими числами][http://www.leemon.com/crypto/BigInt.html Демо]


cd /usr/local/src/dbmail-3.1.7
dpkg-buildpackage -d


*[http://learn.javascript.ru/lib Мини-библиотека функций]
* '''[!]''' - если у вас появилось сообщение типа:
===Несколько интересных проектов с помощью которых можно динамически создавать векторные рисунки.===
...
* [http://y3x.ru/2010/12/artisanjs/]http://y3x.ru/2010/12/artisanjs/ Статья - Пробуем ремесло рисования с помощью ArtisanJS]
debian/rules:138: *** missing separator (did you mean TAB instead of 8 spaces?). Останов.
*Страница разработчика ArtisanJS
dpkg-buildpackage: ошибка: debian/rules clean возвратил код ошибки 2
[http://artisanjs.com/]http://artisanjs.com/
*Высокопроизводительная библиотека динамического рисования Html5 - полностью самодостаточная
[http://jcscript.com/]http://jcscript.com/
*Кросс-браузерное решение
[http://raphaeljs.com/]http://raphaeljs.com/
*Поддерживается как свободное рисование так и работа с векторными формами
[http://kangax.github.com/fabric.js/kitchensink/]http://kangax.github.com/fabric.js/kitchensink/


==Полезные трюки==
* '''[!]''' - то необходимо исправить ошибку в файле '''dbmail-3.1.7/debian/rules'''
http://habrahabr.ru/post/155093/
строка 138:  
'''''........make -f debian/rules binary-common $* DH_OPTIONS=-p$*'''''
      ^^^
    здесь 8 пробелов!! - а должно быть 2 табуляции, что и вызывает ошибку...


==Как работает Array.prototype.slice.call==
* после того как соберется пакет, дожно быть так:
Для того, чтобы из аргументов JavaScript функции "отрезать" первые Х значений, используется метод:
# ls -n /usr/local/src
итого 3668
drwxrwxr-x 13 0  0    4096 ноя  2 00:19 dbmail-3.1.7
-rw-r--r--  1 0 50    7597 ноя  2 00:19 dbmail_3.1.7-1_amd64.buildinfo
-rw-r--r--  1 0 50    1957 ноя  2 00:19 dbmail_3.1.7-1_amd64.changes
-rw-r--r--  1 0 50  349256 ноя  2 00:19 dbmail_3.1.7-1_amd64.deb
-rw-r--r--  1 0 50  148008 ноя  2 00:14 dbmail_3.1.7-1.debian.tar.xz
-rw-r--r--  1 0 50    1045 ноя  2 00:14 dbmail_3.1.7-1.dsc
-rw-r--r--  1 0  0 2391054 июл 27  2014 dbmail_3.1.7.orig.tar.gz
-rw-r--r--  1 0 50  838508 ноя  2 00:19 dbmail-dbgsym_3.1.7-1_amd64.deb


Array.prototype.slice.call(arguments, X);
* копируем себе в архив и ставим пакет.
dpkg -i dbmail_3.1.7-1_amd64.deb


Например такая функция вернет "3,4":
* правим файл конфигурации:
editor /etc/dbmail/dbmail.conf


<nowiki>(function(){
* пример рабочего конфигурационного файла:
  var args = Array.prototype.slice.call(arguments, 2);
  alert(args); // Returns: 3,4
})(1, 2, 3, 4);</nowiki>


# (c) 2000-2006 IC&S, The Netherlands
#
# Configuration file for DBMAIL
[DBMAIL]
#
# Database settings
#
# database connection URI
'''#dburi                = sqlite:///var/tmp/dbmail.db'''
'''dburi                = postgresql://dbmail:dbmailpass@10.0.5.2:5432/mailbasename'''
#
# Supported drivers are sql, ldap.
#
'''authdriver          = sql'''
#
#
# following fields are now DEPRECATED!
'''driver              = postgresql'''
'''host                = 10.0.5.2'''
'''sqlport              = 5432'''
'''#sqlsocket            ='''             
'''user                = dbmail'''
'''pass                = dbmailpass'''
'''db                  = mailbasename'''
#
# Number of database connections per threaded daemon
# This also determines the size of the worker threadpool
#
# Do NOT increase this without proper consideration. A
# very large database/worker pool will not only increase
# the connection pressure on the database, but will more
# significantly cause unnecessary context-switching in
# your CPUs.
#
#max_db_connections  = 10
#
# Table prefix. Defaults to "dbmail_" if not specified.
#
'''table_prefix        = dbmail_''' 
#
# encoding must match the database/table encoding.
# i.e. latin1, utf8
encoding            = utf8
#
# messages with unknown encoding will be assumed to have
# default_msg_encoding
# i.e. iso8859-1, utf8
default_msg_encoding = utf8
#
# Postmaster's email address for use in bounce messages.
#
#postmaster          = DBMAIL-MAILER     
#
# Sendmail executable for forwards, replies, notifies, vacations.
# You may use pipes (|) in this command, for example:
# dos2unix|/usr/sbin/sendmail  works well with Qmail.
# You may use quotes (") for executables with unusual names.
#
sendmail              = /usr/sbin/sendmail   
#
#
# The following items can be overridden in the service-specific sections.
#
#
#
# Logging via stderr/log file and syslog
#
# Logging is broken up into 8 logging levels and each level can be indivually turned on or off.
# The Stderr/log file logs all entries to stderr or the log file.
# Syslog logging uses the facility mail and the logging level of the event for logging.
# Syslog can then be configured to log data according to the levels.
#
# Set the log level to the sum of the values next to the levels you want to record.
#  1 = Emergency
#  2 = Alert
#  4 = Critical
#  8 = Error
#  16 = Warning
#  32 = Notice
#  64 = Info
# 128 = Debug
# 256 = Database -> Logs at debug level
#
# Examples:  0 = Nothing
#            31 = Emergency + Alert + Critical + Error + Warning
#          511 = Everything
#
file_logging_levels      = 7
#
syslog_logging_levels    = 31
#
# Generate a log entry for database queries for the log level at number of seconds of query execution time.
#
query_time_info      = 10
query_time_notice    = 20
query_time_warning    = 30
#
# Throw an exception is the query takes longer than query_timeout seconds
query_timeout        = 300
#
# Root privs are used to open a port, then privs
# are dropped down to the user/group specified here.
#
'''effective_user        = dbmail'''
'''effective_group      = mail'''
#
# The IPv4 and/or IPv6 addresses the services will bind to.
# Use * for all local interfaces.
# Use 127.0.0.1 for localhost only.
# Separate multiple entries with spaces ( ) or commas (,).
#
'''bindip                = 0.0.0.0        # IPv4 only - all IP's'''
#bindip                = ::            # IPv4 and IPv6 - all IP's (linux)
#bindip                = ::            # IPv6 only - all IP's (BSD)
#bindip                = 0.0.0.0,::    # IPv4 and IPv6 - all IP's (BSD)
#
# The maximum length of the queue of pending connections. See
# listen(2) for more information
#
# backlog              = 128
#
# Idle time allowed before a connection is shut off.
#
timeout              = 300           
#
# Idle time allowed before a connection is shut off if you have not logged in yet.
#
login_timeout        = 60
#
# If yes, resolves IP addresses to DNS names when logging.
#
resolve_ip            = yes
#
# If yes, keep statistics in the authlog table for connecting users
#
authlog              = no
#
# logfile for stdout messages
#
logfile              = /var/log/dbmail.log       
#
# logfile for stderr messages
#
errorlog              = /var/log/dbmail.err       
#
# directory for storing PID files
#
pid_directory        = /var/run/dbmail
#
# directory for locating libraries (normally has a sane default compiled-in)
#
library_directory      = /usr/lib/dbmail
#
# SSL/TLS certificates
#
# A file containing a list of CAs in PEM format
tls_cafile            =
# A file containing a PEM format certificate
tls_cert              =
# A file containing a PEM format RSA or DSA key
tls_key              =
# A cipher list string in the format given in ciphers(1)
tls_ciphers          =
# hashing algorithm. You can select your favorite hash type
# for generating unique ids for message parts.
#
# for valid values check mhash(3) but minus the MHASH_ prefix.
# if you ever change this value run 'dbmail-util --rehash' to
# update the hash for all mimeparts.
#
# examples: MD5, SHA1, SHA256, SHA512, TIGER, WHIRLPOOL
#
# hash_algorithm = SHA1
# header_cache tuning
#
# set header_cache_readonly to 'yes' to prevent new
# unknown header-names from being cached.
#
# header_cache_readonly = yes
[LMTP]
'''bindip = 127.0.0.1'''
port                  = 24               
#tls_port              =
[POP]
port                  = 110
#tls_port              = 995
# You can set an alternate banner to display when connecting to the service
# banner = DBMAIL pop3 server ready to rock
#
# If yes, allows SMTP access from the host IP connecting by POP3.
# This requires addition configuration of your MTA
#
pop_before_smtp      = no     
[HTTP]
port                  = 41380
#
# the httpd daemon provides full access to all users, mailboxes
# and messages. Be very careful with this one!
'''bindip                = 127.0.0.1'''
admin                = admin:secret
[IMAP]
# You can set an alternate banner to display when connecting to the service
# banner = imap 4r1 server (dbmail 2.3.x)
#
# Port to bind to.
#
port                  = 143               
##tls_port              = 993
#
# IMAP prefers a longer timeout than other services.
#
timeout              = 4000           
#
# If yes, allows SMTP access from the host IP connecting by IMAP.
# This requires addition configuration of your MTA
#
imap_before_smtp      = no
#
# during IDLE, how many seconds between checking the mailbox
# status (default: 30)
#
# idle_timeout          = 30
# during IDLE, how often should the server send an '* OK' still
# here message (default: 10)
#
# the time between such a message is idle_timeout * idle_interval
# seconds
#
# idle_interval        = 10
#
# If TLS is enabled, login before starttls is normally
# not allowed. Use login_disabled=no to change this
#
# login_disabled        = yes
#
# Provide a CAPABILITY to override the default
#
# capability  = IMAP4 IMAP4rev1 AUTH=LOGIN ACL RIGHTS=texk NAMESPACE CHILDREN SORT QUOTA THREAD=ORDEREDSUBJECT UNSELECT IDLE
# max message size. You can specify the maximum message size
# accepted by the IMAP daemon during APPEND commands.
#
# Supported formats:
#  decimal: 1000000   
#  octal:  03777777
#  hex:    0xfffff
#
# max_message_size      =
[SIEVE]
#
# Port to bind to.
#
port                  = 2000             
tls_port              =
[LDAP]
port                  = 389
version              = 3
hostname              = ldap
base_dn              = ou=People,dc=mydomain,dc=com
#
# If your LDAP library supports ldap_initialize(), then you can use the
# alternative LDAP server DSN like following.
#
# URI                = ldap://127.0.0.1:389
# URI                = ldapi://%2fvar%2frun%2fopenldap%2fldapi/
#
# Leave blank for anonymous bind.
# example: cn=admin,dc=mydomain,dc=com   
#
bind_dn              =
#
# Leave blank for anonymous bind.
#
bind_pw              =
scope                = SubTree
# AD users may want to set this to 'no' to disable
# ldap referrals if you are seeing 'Operations errors'
# in your logs
#
referrals            = yes
user_objectclass      = top,account,dbmailUser
forw_objectclass      = top,account,dbmailForwardingAddress
cn_string            = uid
field_passwd          = userPassword
field_uid            = uid
field_nid            = uidNumber
min_nid              = 10000
max_nid              = 15000
field_cid            = gidNumber
min_cid              = 10000
max_cid              = 15000
# a comma-separated list of attributes to match when searching
# for users or forwards that match a delivery address. A match
# on any of them is a hit.
field_mail            = mail
# field that holds the mail-quota size for a user.
field_quota          = mailQuota
# field that holds the forwarding address.
field_fwdtarget      = mailForwardingAddress
# override the query string used to search for users
# or forwards with a delivery address.
# query_string          = (mail=%s)
[DELIVERY]
#
# Run Sieve scripts as messages are delivered.
#
SIEVE                = yes             
#
# Use 'user+mailbox@domain' format to deliver to a mailbox.
#
SUBADDRESS            = yes         
#
# Turn on/off the Sieve Vacation extension.
#
SIEVE_VACATION        = yes     
#
# Turn on/off the Sieve Notify extension
#
SIEVE_NOTIFY          = yes
#
# Turn on/off additional Sieve debugging.
#
SIEVE_DEBUG          = no         
# Use the auto_notify table to send email notifications.
#
AUTO_NOTIFY          = no
 
#
# Use the auto_reply table to send away messages.
#
AUTO_REPLY            = no
#
# Defaults to "NEW MAIL NOTIFICATION"
#
#AUTO_NOTIFY_SUBJECT        =   
#
# Defaults to POSTMASTER from the DBMAIL section.
#
#AUTO_NOTIFY_SENDER        = 
# If you set this to 'yes' dbmail will check for duplicate
# messages in the relevant mailbox during delivery using
# the Message-ID header
#
suppress_duplicates    = no
#
# Soft or hard bounce on over-quota delivery
#
quota_failure          = hard
# end of configuration file


Таким образом, такой подход используется когда нужно срезать входящие параметры функции JavaScript.
* правим default конфигурационный файл - /etc/default/dbmail
==Array.prototype.concat.apply==
Для объединения более двух массивов используется concat().


  <nowiki>var a = [1, 2], b = ["x", "y"], c = [true, false];
  # debian specific configuration for dbmail
var d = a.concat(b, c);
console.log(d); // [1, 2, "x", "y", true, false];</nowiki>
# work-around for linux/epoll bug in libevent
export EVENT_NOEPOLL=yes
# comment out to disable the pop3 server
'''START_POP3D=true'''
# comment out to disable the imapd server
'''START_IMAPD=true'''
# uncomment to enable the lmtpd server
'''START_LMTPD=true'''
# uncomment to enable the timsieved server
#START_SIEVE=true
# comment out to enable the stunnel SSL wrapper
'''START_SSL=true'''
# specify the filename for the pem file as
# it resides in /etc/ssl/certs
'''PEMFILE="/etc/ssl/serts/dbmail.pem"'''


For concatenating just two arrays, using push.apply() can be used instead for the case of adding elements from one array to the end of another without producing a new array. With slice() it can also be used instead of concat() but there appears to be no performance advantage from doing this.
* создаем сертификат для dbmail:
cd /etc/ssl/certs
openssl req -new -x509 -nodes -out dbmail.pem -keyout smtpd.pem -days 3650
* перезапуск службы:
systemctl restart dbmail


  <nowiki>var a = [1, 2], b = ["x", "y"];
* Краткое пояснение:
a.push.apply(a, b);
  1. Предназначенные для доставки сообщений от MTA в хранилище.<br>
console.log(a); // [1, 2, "x", "y"];</nowiki>
2. Предназначенные для доставки MUA из хранилища.<br>


==Современный метод bind==
* К первым относятся:<br>
'''dbmail-lmtpd''' – UNIX-демон, принимающий клиентские подключения через UNIX-сокет или TCP-сокет. Для приема почтовых сообщений используется протокол LMTP. На каждое входящее сообщение MTA создает только клиентский сокет, необходимое количество процессов и подключений к БД создается заранее.<br>
Таким образом, этот вариант обеспечивает лучшую производительность при высокой нагрузке, но при низкой он потребляет больше системных ресурсов, чем необходимо.<br>


В современном JavaScript для привязки функций есть метод bind. Он поддерживается большинством современных браузеров, за исключением IE<9, но легко эмулируется.
* Ко вторым относятся:<br>
'''dbmail-pop3d''' – демон для доступа по протоколу POP3.<br>
'''dbmail-imapd''' – демон для доступа по протоколу IMAP.<br>


Этот метод позволяет привязать функцию к нужному контексту, и даже к аргументам.
* Кроме того, в состав DBMail входят следующие вспомогательные утилиты:<br>
'''dbmail-users''' – инструмент для управления пользователями и их псевдонимами (возможно, многим из вас будет привычнее термин alias).<br>
'''dbmail-util''' – инструмент для очистки, оптимизации и проверки корректности БД.<br>


Синтаксис bind:
* С установкой '''dbmail''' пока окончено, следующий этап установка '''postgesql''' и настройка для будущей работы.


<nowiki>var wrapper = func.bind(context[, arg1, arg2...])</nowiki>
*'''func''' Произвольная функция
*'''wrapper''' Функция-обёртка, которую возвращает вызов bind. Она вызывает func, фиксируя контекст и, если указаны, первые аргументы.
*'''context''' Обертка wrapper будет вызывать функцию с контекстом this = context.
*'''arg1, arg2, …''' Если указаны аргументы arg1, arg2... — они будут прибавлены к каждому вызову новой функции, причем встанут перед теми, которые указаны при вызове.


Простейший пример, фиксируем только this:
=='''2. [[Настройка PostgreSQL]]'''==


<nowiki>function f() {
2.1. После того как мы настроили базу данных '''postgresql''', создаем пользователя '''dbmail''' и базу '''dbmail'''<br>
  alert(this.name);
* Создаем пользователя для работы с почтовой базой
}
createuser -U postgres -P dbmail


var user = { name: "Вася" };
* '''[!]''' - Ни в коем случае не используйте спецсимволы в пароле, кроме #! (авторизация может не проходить)


var f2 = f.bind(user);
* Создаем базу
createdb -U postgres --owner dbmail dbmail


f2(); // выполнит f с this = user
* Вместе с '''dbmail''' идут заготовки базы, распаковываем и заливаем:
</nowiki>
  bunzip2 /usr/share/doc/dbmail-2.2.10/create_tables.pgsql.bz2
Использование для привязки метода sayHi к новому объекту User:
psql -U dbmail -d dbmail < /usr/share/doc/dbmail-2.2.10/create_tables.pgsql
  <nowiki>
function User() {
  this.id = 1;
  this.sayHi = function() {
    alert(this.id);
  }.bind(this);
}
var user = new User();
setTimeout(user.sayHi, 1000); // выведет "1"</nowiki>


==Object.defineProperty или как сделать код капельку лучше==
или так:
[http://habrahabr.ru/post/150571/ оригинал статьи] [http://msdn.microsoft.com/ru-ru/library/ie/dd548687(v=vs.94).aspx тоже ребята старались]
zcat /usr/share/doc/dbmail/examples/create_tables.pgsql.gz|psql -h 127.0.0.1 dbmail dbmailadmin


Этот краткий пост-заметку или температурный бред (в Одессе похолодало, да) хочу посвятить такой прекрасной функции, как Object.defineProperty (и Object.defineProperties). Активно использую её уже около двух месяцев, так как поддержка старых браузеров (в том числе и IE8) в проекте, который я сейчас реализую, не требуется (завидуйте).
или так:
psql -U dbmail -h localhost maildb < create_tables.pgsql


Как положено статье на хабре, приведу краткое описание того, что она делает. Object.defineProperty добавляет новое свойство, обладающее неким нестандартным для обычного свойства поведением, и принимает три аргумента:
*Объект, который мы модифицируем, добавляя новое свойство
*Свойство (строка), которое, собственно, хотим добавить
*Дескриптор: объект, содержащий «настройки» нового свойства, например аццессоры (геттер, сеттер)
Дескриптор может содержать следующие свойства:
*value (любое значение: строка, функция...) — значение, которое получит определяемое свойство объекта (геттер и сеттер в данном случае определить нельзя)
*writable (true/false) — можно ли перезаписать значение свойства (аццессоры тоже не доступны)
*get (функция) — геттер (value и writable определить нельзя)
*set (функция) — сеттер (value и writable определить нельзя)
*configurable (true/false) — можно ли переопределить дескриптор (использовать Object.defineProperty над тем же свойством)
*enumerable (true/false) — будет ли свойство перечисляться через for..in и доступно в Object.keys (плохая формулировка)
<nowiki>var o = {};
Object.defineProperty(o, "a", {value : 37,
                              writable : true,
                              enumerable : true,
                              configurable : true});


* В этом дампе нет таблицы для работы с виртуальными доменами, создадим ее:
  CREATE TYPE dtype AS ENUM (
  'LOCAL',
  'VIRTUAL',
  'RELAY'
);
ALTER TYPE public.dtype OWNER TO dbmail;
SET default_with_oids = true;
CREATE TABLE dbmail_domains (
  uid integer NOT NULL,
  domain character varying(128) NOT NULL,
  type dtype NOT NULL
);
   
   
var bValue;
INSERT INTO dbmail_domains (uid, domain, type) VALUES (1, 'example.com', 'LOCAL');
Object.defineProperty(o, "b", {get : function(){ return bValue; },
                              set : function(newValue){ bValue = newValue; },
                              enumerable : true,
                              configurable : true});</nowiki>


Лучше меня объяснит MDN [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty Object/defineProperty]. Благо, даже английский знать не надо, и так всё понятно.
'''База готова.'''


Если нужно определить сразу несколько свойств, можно использовать Object.defineProperties, который принимает два аргумента: объект, требующий изменений и объект с определяемыми ключами.
* добавляем обработку базы в /etc/crontab
MDN: [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperties Object/defineProperties].
...
0 3 * * * root /usr/sbin/dbmail-util -cturpd -l 24h -qq
...


<nowiki>
* проверяем работу '''dbmail''' c базой:
// Код сперт с MDN
Object.defineProperties(obj, {
  "property1": {
    value: true,
    writable: true
  },
  "property2": {
    value: "Hello",
    writable: false
  }
  // etc. etc.
});</nowiki>


dbmail-util -av


если есть ошибки, исправляем не забывая проверить файл конфигурации...<br>
.. если все ок, приступаем к настройке '''postfix'''


Теперь соль. Чего я вообще решил это запостить?
=='''3. Настройка Postfix'''==


Так как в упомянутом выше проекте мне приходится использовать defineProperty не просто активно, а очень активно, код стал, мягко говоря, некрасивым. Пришла в голову простейшая идея (как я до этого раньше-то не додумался?), расширить прототип Object, сделав код сильно компактнее. Плохой тон, скажете вы, засерать прототип Object новыми методами.
apt-get install postfix postfix-pgsql postfix-sqlite procmail libsasl2-2 libsasl2-modules libsasl2-modules-db\
libsasl2-modules-sql sqlite3 mutt postfix-pcre postfix-ldap postfix-lmdb sasl2-bin ufw


Откуда вообще взялось это мнение? Потому что все объекты унаследуют это свойство, которое, при обычной модификации прототипа, становится перечисляемым в for..in. На душе становится тепло, когда вспоминаешь о том, что я описал выше, а именно, о свойстве дескриптора enumerable. Действительно, расширив прототип таким образом:  
* вносим необходимые изменения в файлы конфигурации - пример рабочей версии '''main.cf''':


  <nowiki>Object.defineProperty( Object.prototype, 'logOk' {
  # See /usr/share/postfix/main.cf.dist for a commented, more complete version
    value: function() { console.log('ok') },
    enumerable: false
});</nowiki>
# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no
# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2
# TLS parameters
'''#smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem'''
'''#smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key'''
'''smtpd_tls_cert_file=/etc/postfix/ssl/smtpd.pem'''
'''smtpd_tls_key_file=/etc/postfix/ssl/smtpd.key'''
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
'''smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination'''
'''myhostname = mymail.home.local'''
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
'''mydestination = $myhostname, mymail.ru, mymail.home.local, localhost.home.local, localhost'''
relayhost =
'''#mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128'''
'''######################### вторым ip указываем хост где база данных postgresql'''
'''mynetworks = 127.0.0.0/8 10.0.5.2'''
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
'''############################## - указываем способ использования postgresql'''
'''local_recipient_maps = pgsql:/etc/postfix/dbmail-mailboxes.cf $alias_maps'''
'''mailbox_transport = dbmail-lmtp:127.0.0.1:24'''
'''#################### - подключаем авторизацию через sasl, установка ниже в статье.'''
'''broken_sasl_auth_clients = yes'''
'''smtpd_sasl_auth_enable = yes'''
'''smtpd_sasl_local_domain ='''
'''############################### - подключаем наш сертификат созданный как описано ниже.'''
'''smtpd_tls_auth_only = no'''
'''smtpd_tls_loglevel = 1'''
'''smtpd_tls_received_header = yes'''
'''smtpd_tls_session_cache_timeout = 3600s'''
'''tls_random_source = dev:/dev/urandom'''


все объекты получат этот метод, но, при этом, он будет неперечисляемым (не нужно каждый раз использовать hasOwnProperty для проверки, есть ли такое свойство):
 
* вносим необходимые изменения в файлы конфигурации - пример рабочей версии '''master.cf''':
#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#              (yes)  (yes)  (no)    (never) (100)
# ==========================================================================
smtp      inet  n      -      y      -      -      smtpd
#smtp      inet  n      -      y      -      1      postscreen
#smtpd    pass  -      -      y      -      -      smtpd
#dnsblog  unix  -      -      y      -      0      dnsblog
#tlsproxy  unix  -      -      y      -      0      tlsproxy
#submission inet n      -      y      -      -      smtpd
#  -o syslog_name=postfix/submission
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps    inet  n      -      y      -      -      smtpd
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628      inet  n      -      y      -      -      qmqpd
pickup    unix  n      -      y      60      1      pickup
cleanup  unix  n      -      y      -      0      cleanup
qmgr      unix  n      -      n      300    1      qmgr
#qmgr    unix  n      -      n      300    1      oqmgr
tlsmgr    unix  -      -      y      1000?  1      tlsmgr
rewrite  unix  -      -      y      -      -      trivial-rewrite
bounce    unix  -      -      y      -      0      bounce
defer    unix  -      -      y      -      0      bounce
trace    unix  -      -      y      -      0      bounce
verify    unix  -      -      y      -      1      verify
flush    unix  n      -      y      1000?  0      flush
proxymap  unix  -      -      n      -      -      proxymap
proxywrite unix -      -      n      -      1      proxymap
smtp      unix  -      -      y      -      -      smtp
relay    unix  -      -      y      -      -      smtp
#      -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq    unix  n      -      y      -      -      showq
error    unix  -      -      y      -      -      error
retry    unix  -      -      y      -      -      error
discard  unix  -      -      y      -      -      discard
local    unix  -      n      n      -      -      local
virtual  unix  -      n      n      -      -      virtual
lmtp      unix  -      -      y      -      -      lmtp
anvil    unix  -      -      y      -      1      anvil
scache    unix  -      -      y      -      1      scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -      n      n      -      -      pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#  lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus    unix  -      n      n      -      -      pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -      n      n      -      -      pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -      n      n      -      -      pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -      n      n      -      -      pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp    unix  -      n      n      -      -      pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -      n      n      -      2      pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman  unix  -      n      n      -      -      pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
'''######'''
'''dbmail-lmtp    unix    -      -      n      -      -      lmtp'''
        '''-o disable_dns_lookups=yes'''
* создаем файл настройки подключения к базе postgresql - '''dbmail-mailboxes.cf''':


  <nowiki>var o = {a: 1, b: 2}
  user = dbmail
for( var i in o ) console.log( i, o[ i ] );
password = userpass
> a 1
hosts = 10.0.5.2
> b 2
dbname = mailbasename
o.logOk();
table = dbmail_aliases
> ok</nowiki>
select_field = alias
where_field = alias


* Так как почтовый сервер изначально не рассматсривается как релей, то доступ к '''SMTP''' только по авторизации и для этого используем '''SASL'''.
* в каталоге настроек postfix создаем файл настроек для '''sasl''':
mkdir -p /etc/postfix/sasl


Собственно то, ради чего я тут графоманю.
* создаем файл конфигурации - '''smtpd.conf''':
echo > /etc/postfix/sasl/smtpd.conf
* вносим содержимое файла:
edit /etc/postfix/sasl/smtpd.conf


Во-первых определим метод define, чтоб каждый раз не вызывать перегруженную, на мой взгляд, конструкцию. Во-вторых определим метод extendNotEnum, который расширяет объект неперечисляемыми свойствами.
pwcheck_method: auxprop
auxprop_plugin: sql
mech_list: digest-md5 cram-md5 login plain
sql_engine: pgsql
sql_user: dbmail
sql_passwd: userpass
sql_hostnames: 10.0.5.2
sql_database: mailbasename
sql_statement: select passwd from dbmail_users where userid='%u@%r'
sql_verbose: yes


  <nowiki>Object.defineProperties( Object.prototype, {
* создаем свой recipient_bcc
    define: {
  *@mainhost.local admin@mailbox.ru
        value: function( key, descriptor ) {
*@slavehost.local admin@mailbox.ru
            if( descriptor ) {
*@otherhost.local admin@mailbox.ru
                Object.defineProperty( this, key, descriptor );
            } else {
                Object.defineProperties( this, key );
            }
            return this;
        },
        enumerable: false
    },
    extendNotEnum: {
        value: function( key, property ) {
            if( property ) {
                this.define( key, {
                    value: property,
                    enumerable: false,
                    configurable: true
                });
            } else {
                for( var prop in key ) if( key.hasOwnProperty( prop ) ){
                    this.extendNotEnum( prop, key[ prop ] );
                }
            }
        },
        enumerable: false
    }
});
</nowiki>


Использование:
* генерируем базу
  <nowiki>var o = { a: 1 };
  postmap recipient_bcc
o.define( 'randomInt', {
    get: function() {
        return 42;
    }
});


o.extendNotEnum({
* генерируем свой сертификат tls:
    b: 2;
mkdir -p /etc/postfix/ssl
});
cd /etc/postfix/ssl
openssl req -new -x509 -days 3650 -nodes -out smtpd.pem -keyout smtpd.key


for( var i in o ) console.log( i, o[ i ] );
* перезапускаем '''postfix''':
> a 1
systemctl  restart postfix
> randomInt 42
или
/etc/init.d/postfix restart


console.log( o.b );
* проверяем работу '''postfix''':
> 2
# telnet mymail.ru 25
</nowiki>
Trying mymail.ru...
Connected to mymail.ru.
Escape character is '^]'.
220 mx.kscom.ru ESMTP Postfix
EHLO example.com
250-mx.kscom.ru
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
QUIT
221 2.0.0 Bye
Connection closed by foreign host.
- должно быть - 250-STARTTLS
- все работает..


И пошла… Еще два удобных метода:
=='''4. Настройка Stunnel'''==
* Данный пакет позволяет организовать защищенное соединение как для почты так и для других программ.<br>
* Далее будет описание, как создать защищенный вход на почтовый сервер.<br>


<nowiki>Object.prototype.extendNotEnum({
* Устанавливаем пакет:
    extend: function() {
apt-get install stunnel4
        var args = Array.prototype.slice.call( arguments );
        args.unshift( this );
        return $.extend.apply( null, args ); // если jQuery надоест, можно просто переписать под себя
    },
   
    each: function( callback ) {
        return $.each( this, callback ); // аналогично
    }
});


* в каталоге /etc/stunnel - сразу создаем себе скрипт для генерации сертификата, чтобы если понадобится снова не вспоминать как это...
echo > /etc/stunnel/create-sert
editor /etc/stunnel/create-sert


o.extend({c: 3}); // тупо добавляет новые свойства в объект
* вносим содержимое:
o.each(function( key, value ) {
#!/bin/sh
    // просто повторяет механизм $.each, перебирая все ключи и свойства
# каталог сертификатов SSL в системе
});</nowiki>
cd /etc/ssl/certs
# имя сертификата на свое усмотрение...
PEMFILE="servername.mymail.ru.pem"
# генерация сертификата
openssl req -new -x509 -nodes -days 3650 -out $PEMFILE -keyout $PEMFILE
chmod 600 $PEMFILE
[ -e temp_file ] && rm -f temp_file
dd if=/dev/urandom of=temp_file count=2
openssl dhparam -rand temp_file 512 >> $PEMFILE
ln -sf $PEMFILE `openssl x509 -noout -hash < $PEMFILE`.0
 
* даем права на исполнение - только для root:
chmod 0700 /etc/stunnel/create-sert


* запускаем скрипт и отвечаем на вопросы..
/etc/stunnel/create-sert


Добавлять новые свойства можно до бесконечности, никто вам за это руку не откусит.
* создаем каталог в котором будет файл запуска .pid
mkdir -p /var/run/stunnel4/


Вывод
* копируем из примера будущий конфигурационный файл для stunnel4
cp /usr/share/doc/stunnel4/examples/stunnel.conf-sample /etc/stunnel/stunnel.conf


Играйте в Денди, пишите на Javascript, который становится всё лучше и лучше.
* приводим его в такой вариант (рабочий пример):
; Sample stunnel configuration file for Unix by Michal Trojnara 2002-2015
; Some options used here may be inadequate for your particular configuration
; This sample file does *not* represent stunnel.conf defaults
; Please consult the manual for detailed description of available options
; **************************************************************************
; * Global options                                                        *
; **************************************************************************
; It is recommended to drop root privileges if stunnel is started by root
;setuid = stunnel4
;setgid = stunnel4
; PID file is created inside the chroot jail (if enabled)
pid = /var/run/stunnel4/stunnel.pid
; Debugging stuff (may be useful for troubleshooting)
;foreground = yes
;debug = info
output = /var/log/stunnel.log
; Enable FIPS 140-2 mode if needed for compliance
;fips = yes
fips = no
; **************************************************************************
; * Service defaults may also be specified in individual service sections  *
; **************************************************************************
; Enable support for the insecure SSLv3 protocol
options = -NO_SSLv3
sslVersion = TLSv1.2
; These options provide additional security at some performance degradation
;options = SINGLE_ECDH_USE
;options = SINGLE_DH_USE
; **************************************************************************
; * Include all configuration file fragments from the specified folder    *
; **************************************************************************
;include = /etc/stunnel/conf.d
; **************************************************************************
; * Service definitions (remove all services for inetd mode)              *
; **************************************************************************
; ***************************************** Example TLS client mode services
; The following examples use /etc/ssl/certs, which is the common location
; of a hashed directory containing trusted CA certificates.  This is not
; a hardcoded path of the stunnel package, as it is not related to the
; stunnel configuration in /etc/stunnel/.
;[mymail-pop3]
;client = yes
;accept = 127.0.0.1:110
;connect = pop3.mymail.ru:995
;verifyChain = yes
;CApath = @sysconfdir/ssl/certs
;checkHost = pop3s.mymail.ru
;OCSPaia = yes
;[mymail-imap]
;client = yes
;accept = 127.0.0.1:143
;connect = imap.mymail.ru:993
;verifyChain = yes
;CApath = @sysconfdir/ssl/certs
;checkHost = imaps.mymail.ru
;OCSPaia = yes
;[mymail-smtp]
;client = yes
;accept = 127.0.0.1:25
;connect = smtp.mymail.ru:465
;verifyChain = yes
;CApath = @sysconfdir/ssl/certs
;checkHost = smtps.mymail.ru
;OCSPaia = yes
; ***************************************** Example TLS server mode services
[pop3s]
accept  = 995
connect = 110
cert = /etc/ssl/certs/servername.mymail.ru.pem
[imaps]
accept  = 993
connect = 143
cert = /etc/ssl/certs/servername.mymail.ru.pem
[smtps]
accept  = 465
connect = 25
cert = /etc/ssl/certs/servername.mymail.ru.pem
; TLS front-end to a web server
;[https]
;accept  = 443
;connect = 80
;cert = /etc/stunnel/stunnel.pem
; "TIMEOUTclose = 0" is a workaround for a design flaw in Microsoft SChannel
; Microsoft implementations do not use TLS close-notify alert and thus they
; are vulnerable to truncation attacks
;TIMEOUTclose = 0
; Remote shell protected with PSK-authenticated TLS
; Create "/etc/stunnel/secrets.txt" containing IDENTITY:KEY pairs
;[shell]
;accept = 1337
;exec = /bin/sh
;execArgs = sh -i
;ciphers = PSK
;PSKsecrets = /etc/stunnel/secrets.txt
; Non-standard MySQL-over-TLS encapsulation connecting the Unix socket
;[mysql]
;cert = /etc/stunnel/stunnel.pem
;accept = 3307
;connect = /run/mysqld/mysqld.sock
; vim:ft=dosini


комментарии
* корректируем конфигурационный файл запуска по умолчанию:
# /etc/default/stunnel
# Julien LEMOINE <speedblue@debian.org>
# September 2003
# Change to one to enable stunnel automatic startup
ENABLED=1
FILES="/etc/stunnel/*.conf"
OPTIONS=""
# Change to one to enable ppp restart scripts
PPP_RESTART=0
# Change to enable the setting of limits on the stunnel instances
# For example, to set a large limit on file descriptors (to enable
# more simultaneous client connections), set RLIMITS="-n 4096"
# More than one resource limit may be modified at the same time,
# e.g. RLIMITS="-n 4096 -d unlimited"
RLIMITS=""


* перезапуск stunnel
/etc/init.d/stunnel4 restart


Еще один финт ушами для тех, кто определяет свойства прототипа только однажды, после определения функции-конструктора:
* после этого проверяем наличие нужных нам портов:
<nowiki>// запускается в консоли
nmap -v mymail.ru
Object.defineProperty( Object.prototype, 'awesomeprototype', {
...
    set: function( object ) {
PORT    STATE SERVICE
        for( var prop in object ) {
22/tcp  open  ssh
            Object.defineProperty( this.prototype, prop, {
25/tcp  open  smtp
                value: object[ prop ],
110/tcp open  pop3
                enumerable: false
143/tcp open  imap
            });
465/tcp open  smtps
        }
993/tcp open  imaps
    }
995/tcp open  pop3s
});


var X = function() {}
* проверяем работу с почтой по '''SSL\TLS''' - зашифрованный пароль на портах '''465,993,995'''
X.awesomeprototype = {
* если все в порядке, рекомендую закрыть обычные порты через '''iptables''' ('''110,143'''),
    method: function() { alert( 'ok' ) }
* а оставить только '''25''' (некоторые серверы для доставки вам почты требуют именно его)
};


var x = new X
=='''5. Установка антиспама Spamassassin'''==


x.method()
* установка пакета:
</nowiki>
aptitude install spamassassin


'''Стоит отметить что в литералах объектов свойства можно задавать через геттер и сеттер:'''
* запуск по умолчанию в /etc/default/spamassassin
  <nowiki>var o = {
  ...
    __someProperty : 42,
ENABLED=1
    get someProperty() { return this.__someProperty; },
...
    set someProperty(v) { this.__someProperty = v; }
};


o.someProperty; // 42
* Приводим файл конфигурации антиспама /etc/spamassassin/local.cf  к такому:
o.someProperty = 56;
o.someProperty; // 56
</nowiki>


Ну это так, к слову :)
# This is the right place to customize your installation of SpamAssassin.
 
#
==deferred==
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
*[http://habrahabr.ru/post/175947/ Асинхронные API и объект Deferred в деталях][https://github.com/StreetStrider/utils/tree/master/doc GitHub]
# tweaked.
*[http://javascript.ru/unsorted/async/deferred Объект Deferred.]
#
*[http://www.smira.ru/2009/02/10/deferred-async-programming/ Асинхронное программирование: концепция Deferred]
# Only a small subset of options are listed below
*[http://www.smira.ru/2009/02/24/more-about-deferred/ Deferred: все подробности]
#
==Шаблонизация в JavaScript==
###########################################################################
*[http://learn.javascript.ru/templates Шаблонизация в JavaScript]
==DOM==
#  Add *****SPAM***** to the Subject header of spam e-mails
===dom2json===
#
http://coderepos.org/share/browser/lang/javascript/dom2json/dom2json.js?rev=30780
rewrite_header Subject *****SPAM*****
skips empty attributes that IE implicitly adds
  <nowiki>/*
  #  Save spam messages as a message/rfc822 MIME attachment instead of
  * $Id: dom2json.js,v 0.2 2008/06/15 07:04:10 dankogai Exp dankogai $
  #  modifying the original message (0: off, 2: use text/plain instead)
  */
  #
(function(){
report_safe 0
 
dom2json = function(dom){
    var type = dom.nodeType;
#  Set which networks or hosts are considered 'trusted' by your mail
    if (type == 3) return dom.nodeValue;
#  server (i.e. not spammers)
    if (type == 1){
#
        var json = [];
# trusted_networks 212.17.35.
        json.push(dom.nodeName);
trusted_networks 10.0.5.
        var attrs = dom.attributes;
        if (attrs.length){
            var attr = {};
#  Set file-locking method (flock is not safe over NFS, but is faster)
            for (var i = 0, l = attrs.length; i < l; i++){
#
                attr[attrs[i].name] = attrs[i].value;
# lock_method flock
            }
            if (0 /*@cc_on +1@*/){
                attr['style'] = dom.style;
#  Set the threshold at which a message is considered spam (default: 5.0)
            }
#
            json.push(attr);
required_score 5.0
        }
        if (! dom.hasChildNodes()) return json;
        var kids = dom.childNodes;
#  Use Bayesian classifier (default: 1)
        for (var i = 0, l = kids.length; i < l; i++){
#
            var kjson = arguments.callee(kids[i]);
use_bayes 1
            if (kjson) json.push(kjson);
        }
        return json;
#  Bayesian classifier auto-learning (default: 1)
    }
#
};
bayes_auto_learn 1
json2dom = function(json){
    var i = 0;
#  Set headers which may provide inappropriate cues to the Bayesian
    var tag = json[i++]
#  classifier
    var dom = document.createElement(tag);
#
    if (json[i].constructor == Object){
bayes_ignore_header X-Bogosity
        var attr = json[i++];
bayes_ignore_header X-Spam-Flag
        for (var name in attr){
bayes_ignore_header X-Spam-Status
            dom.setAttribute(name, attr[name]);
        }
    }
#  Whether to decode non- UTF-8 and non-ASCII textual parts and recode
    for (var l = json.length; i < l; i++){
#  them to UTF-8 before the text is given over to rules processing.
        dom.appendChild(
#
            json[i].constructor == Array
# normalize_charset 1
                ? arguments.callee(json[i])
                : document.createTextNode(json[i])
#  Some shortcircuiting, if the plugin is enabled
            );           
#
    }
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
    return dom;
#
}
#   default: strongly-whitelisted mails are *really* whitelisted now, if the
#  shortcircuiting plugin is active, causing early exit to save CPU load.
})();</nowiki>
  #  Uncomment to turn this on
===обход дерева DOM===
#
   <nowiki>/**
# shortcircuit USER_IN_WHITELIST      on
  * Рекурсивное перечисление дочерних элементов
  # shortcircuit USER_IN_DEF_WHITELIST  on
  *
  # shortcircuit USER_IN_ALL_SPAM_TO    on
  * @param DomNode node
  # shortcircuit SUBJECT_IN_WHITELIST    on
  * Родительский элемент, чьи дочерние узлы нужно перечислять.
   
  *
  #  the opposite; blacklisted mails can also save CPU
  * @return void
  #
  */
# shortcircuit USER_IN_BLACKLIST      on
function enumChildNodes(node) {
# shortcircuit USER_IN_BLACKLIST_TO    on
    // если нам передали элемент
# shortcircuit SUBJECT_IN_BLACKLIST    on
    if (node && 1 == node.nodeType) {
        // берем его первый дочерний узел
#  if you have taken the time to correctly specify your "trusted_networks",
        var child = node.firstChild;
#  this is another good way to save CPU
        // пока узлы не закончились
#
        while (child) {
# shortcircuit ALL_TRUSTED             on
             // если этот узел является элементом
            if (1 == child.nodeType) {
#  and a well-trained bayes DB can save running rules, too
                // что-то делаем с найденным элементом
#
                alert('элемент ' + child.tagName);
# shortcircuit BAYES_99                spam
                // рекурсивно перечисляем дочерние узлы
# shortcircuit BAYES_00                ham
                enumChildNodes(child);
whitelist_from @mymail.ru
            };
            // переходим к следующему узлу
endif # Mail::SpamAssassin::Plugin::Shortcircuit
            child = child.nextSibling;
        };
    };
};
   
   
// перечисляем содержимое body
* Стартуем spamassasin:
enumChildNodes(document.body);</nowiki>


===Обход child nodes (потомков) определнного элемента в Javascript===
/etc/init.d/spamassassin start
JavaScript на заметку Комментировать
Речь о том как корректно обойти элементы потомки DOM для данного элемента,
простите за тафтологию


  var object = document.getElementById('el');
* Редактируем файл постфикса /etc/postfix/master.cf
  for (var childItem in object.childNodes) {
- Строку:
  if (object.childNodes[childItem].nodeType == 1)
  ..
  object.childNodes[childItem].style.color = '#FF0000';
smtp      inet  n      -      -      -      -      smtpd
  ..
- Заменяем на:
  ..
smtp      inet  n      -      -      -      -      smtpd -o content_filter=spamassassin
  ..


В данном примере мы берем некоторый элемент с id = 'el' и проходим по массиву
- Перед:
его потомков (childNodes), при этом проверяем nodeType потомка, чтобы он был
..
элементом страницы и если так, то окрашиваем его в КРАСНЫЙ цвет.
dbmail-lmtp    unix    -      -      n      -      -      lmtp
        -o disable_dns_lookups=yes
..


В принципе на базе этой конструкции можно организовать рекурсивный обход дерева
- Добавляем:
всех потомков заданного элемента, если конечно возникнет такая необходимость, но
..
пока я представляю только упрощенный вариант.
spamassassin unix  -  n  n  -  -  pipe  user=debian-spamd argv=/usr/bin/spamc -s 5120000 -f -e /usr/sbin/sendmail -oi -f
${sender}${recipient}
..


Здесь следует обратить внимание на проверку свойства nodeType == 1, дело в том
* Перезапускаем '''postfix''':
что без этой проверки в обработку попадут и разрывы строк, т.е. символы "\n",
которые тоже воспинимаются как ноды. Т.е. например конструкция вида:
/etc/init.d/postfix restart


так быстрее и меньше кода
* Проверяем работу почты, все должно работать...  
var object = document.getElementById(‘el’).getElementsByTagName(‘*’);
for(var i=0;object[i];i++){
object[i].style.color = ‘#FF0000′;




Sun, getElementsByTagName не поддерживает ИЕ, смысл его использовать?
<hr>


К сожалению заметил, что данная конструкция в Opera выполняется некорректно
Источники:
(цикл for проходится два раза), никто с таким не встречался? Где-то всё же
<hr>
закралась моя ошибка или это ошибка браузера (проверял в 9.20, 9.50, 10.20),
* [https://www.opennet.ru/docs/RUS/dbmail_postfix/ Почтовый сервер на основе реляционной СУБД.]
замечу, что в остальных браузерах всё выполняется верно.
* [http://library.mobrien.com/dbmailadministrator/ GUI-конфигуратора DbMail Administrator (DBMA), написанного на Perl]
 
* [https://habrahabr.ru/post/37195/ Настройка exim+postgresql+dbmail+spamassassin...]
  var object = document.getElementById(‘el’);
* [https://www.opennet.ru/docs/RUS/dbmail/#dbmail_fs Создание почтовой системы на базе exim, dbmail, amavisd-new и postgresql]
for (var childItem in object.childNodes) {
* [https://www.opennet.ru/docs/RUS/dbmail_postfix/ Почтовый сервер на основе реляционной СУБД]
* [https://habrahabr.ru/post/211078/ Почтовый сервер с хранением данных в PostgreSQL]
}
* [https://www.opennet.ru/base/net/exim_intro.txt.html Exim (exim mail mta virtual spam virus clamav freebsd imap postgresql)]
* [http://www.linuxcenter.ru/lib/articles/soft/ezh_mailsystem.phtml?style=print Создание почтовой системы на базе exim, dbmail, amavisd-new и postgresql]
var object=document.getElementById(‘el’);
* [https://www.lissyara.su/archive/exim+dbmail/ Exim и dbmail]
for(var i=0;i<object.childNodes.length;i++) {
* [https://vovanys.com/linux/pochtovyj-server-pod-ubuntu-server-svyazka-dbmail-postfix-sasl-spamassassin-clamav/ Почтовый сервер под Ubuntu Server: связка DBmail + Postfix + sasl + spamassassin + clamav]
if (object.childNodes[i].nodeType == 1) {
* [http://samag.ru/archive/article/608 Почтовый сервер на основе реляционной СУБД - переработанное]
// тут что-либо делаем
* [http://www.wertup.ru/ubuntu/mail-server Почтовый сервер cвязка DBmail + Postfix + sasl + spamassassin + clamav + DBMA + Roundcube webmail]
}
* [https://www.lissyara.su/articles/freebsd/mail/postfix+dbmail/ Почтовая система Postfix + DBMail + SASL2 + TLS + DSpam + ClamAV + RoundCubeWebMail]
}
* [http://www.dbmail.org/dokuwiki/doku.php/stunnel How to set up and use encrypted connections with DBmail]
* [https://notessysadmin.com/postfix-perenapravlenie-pochty Postfix. Перенаправление почты]
* [https://toster.ru/q/53106 Postfix пересылка всей входящей почты на другой ящик]
* [https://code.google.com/archive/p/simple-dbmail-admin/downloads web admin dbmail]

Версия от 15:53, 2 мая 2018

Руководство для быстрого развертывания собственного сервера почты.

  • Данная статья появилась тут в связи с тем, что я столкнулся с проблемой переноса почтового сервера на обычной файловой системе.

В первую очередь с тем, что почта была организована на уже устаревшем ПО и перенос ее на новую платформу без потерь стал практически не возможен. А вот хранение почты в базе данных, дает огромные преимущества при обновлении или доступе к информации, а так же восстановлении. В частности у меня база данных находится на другом хосте, что сильно облегчает ее обслуживание, при этом все конфигурационные файлы самой почты можно легко повторить если понадобится на новом хосте для создания почтового сервера заново.

1. Порядок установки dbmail

  • Система Debian Stretch {9}
  • Используемый source.list
# 
deb http://mirror.mephi.ru/debian/ stretch main
deb-src http://mirror.mephi.ru/debian/ stretch main

deb http://security.debian.org/debian-security stretch/updates main
deb-src http://security.debian.org/debian-security stretch/updates main 

# stretch-updates, previously known as 'volatile'
deb http://mirror.mephi.ru/debian/ stretch-updates main
deb-src http://mirror.mephi.ru/debian/ stretch-updates main

###### Debian Main Repos
deb http://deb.debian.org/debian/ stable main contrib non-free
deb-src http://deb.debian.org/debian/ stable main contrib non-free

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

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

deb http://ftp.debian.org/debian stretch-backports main contrib non-free
deb-src http://ftp.debian.org/debian stretch-backports main contrib non-free

1.1 Устанавливаем необходимые пакеты:

apt-get install pkg-config libglib2.0-dev libgmime-2.6-dev libmhash-dev libevent-dev libssl-dev libzdb-dev\
autoconf automake libtool autotools-dev dpkg-dev fakeroot debhelper dh-make libldap2-dev libsieve2-dev ascidoc\
libcrypto++6 libcrypto++-utils libcrypto++-dev xmlto xmltoman libarchive-tools lrzip binutils-multiarch\
arch-test libpgf-dev libsasl2-modules-db libsasl2-modules curl libcroco3 libsasl2-2 procmail libsasl2-modules-sql\
libpcre32-3 zlib1g-dev libmhash-dev libpcrecpp0v5 

1.2 Скачиваем с dbmail.org исходники:

wget -c -t 0 -T 8 http://www.dbmail.org/download/3.1/dbmail-3.1.17.tar.gz

1.3 Распаковываем и компилируем:

cp dbmail-3.1.17.tar.gz /usr/local/src
tar -xf dbmail-3.1.17.tar.gz /usr/local/src.dbmail-3.1.7
cp dbmail-3.1.17.tar.gz /usr/local/src/dbmail_3.1.7.orig.tar.gz
  • [!] - не знаю, может так у меня получилось, но когда применяешь комменты, версия которая высвечивается именно 3.1.7!!
  • [!] - именно поэтому все, что тут распаковываем и создаем имеет версию - 3.1.7 ...

Готовим пакет к сборке:

cd /usr/local/src/dbmail-3.1.7
./configure --prefix=/usr
 
dpkg-source --commit

даем имя, что-то: pgsql.commit
выходим по ESC
должно быть так:

...
dpkg-source: инфо: локальные изменения были записаны в новую заплату: dbmail-3.1.7/debian/patches/pgsql.commit

далее:

cd /usr/local/src/
dpkg-source -b dbmail-3.1.7
cd /usr/local/src/dbmail-3.1.7
dpkg-buildpackage -d
  • [!] - если у вас появилось сообщение типа:
...
debian/rules:138: *** missing separator (did you mean TAB instead of 8 spaces?).  Останов.
dpkg-buildpackage: ошибка: debian/rules clean возвратил код ошибки 2
  • [!] - то необходимо исправить ошибку в файле dbmail-3.1.7/debian/rules
строка 138: 
........make -f debian/rules binary-common $* DH_OPTIONS=-p$*
     ^^^
   здесь 8 пробелов!! - а должно быть 2 табуляции, что и вызывает ошибку...
  • после того как соберется пакет, дожно быть так:
# ls -n /usr/local/src
итого 3668
drwxrwxr-x 13 0  0    4096 ноя  2 00:19 dbmail-3.1.7
-rw-r--r--  1 0 50    7597 ноя  2 00:19 dbmail_3.1.7-1_amd64.buildinfo
-rw-r--r--  1 0 50    1957 ноя  2 00:19 dbmail_3.1.7-1_amd64.changes
-rw-r--r--  1 0 50  349256 ноя  2 00:19 dbmail_3.1.7-1_amd64.deb
-rw-r--r--  1 0 50  148008 ноя  2 00:14 dbmail_3.1.7-1.debian.tar.xz
-rw-r--r--  1 0 50    1045 ноя  2 00:14 dbmail_3.1.7-1.dsc
-rw-r--r--  1 0  0 2391054 июл 27  2014 dbmail_3.1.7.orig.tar.gz
-rw-r--r--  1 0 50  838508 ноя  2 00:19 dbmail-dbgsym_3.1.7-1_amd64.deb
  • копируем себе в архив и ставим пакет.
dpkg -i dbmail_3.1.7-1_amd64.deb
  • правим файл конфигурации:
editor /etc/dbmail/dbmail.conf
  • пример рабочего конфигурационного файла:
# (c) 2000-2006 IC&S, The Netherlands 
#
# Configuration file for DBMAIL 

[DBMAIL] 
# 
# Database settings
#
# database connection URI

#dburi                = sqlite:///var/tmp/dbmail.db
dburi                = postgresql://dbmail:dbmailpass@10.0.5.2:5432/mailbasename
# 
# Supported drivers are sql, ldap.
#
authdriver           = sql

# 
# 
# following fields are now DEPRECATED!
driver               = postgresql
host                 = 10.0.5.2
sqlport              = 5432
#sqlsocket            =              
user                 = dbmail
pass                 = dbmailpass
db                   = mailbasename

#
# Number of database connections per threaded daemon
# This also determines the size of the worker threadpool
#
# Do NOT increase this without proper consideration. A
# very large database/worker pool will not only increase
# the connection pressure on the database, but will more
# significantly cause unnecessary context-switching in 
# your CPUs.
#
#max_db_connections   = 10

# 
# Table prefix. Defaults to "dbmail_" if not specified.
#
table_prefix         = dbmail_   

# 
# encoding must match the database/table encoding.
# i.e. latin1, utf8
encoding             = utf8

#
# messages with unknown encoding will be assumed to have 
# default_msg_encoding
# i.e. iso8859-1, utf8
default_msg_encoding = utf8

# 
# Postmaster's email address for use in bounce messages.
#
#postmaster           = DBMAIL-MAILER       

# 
# Sendmail executable for forwards, replies, notifies, vacations.
# You may use pipes (|) in this command, for example:
# dos2unix|/usr/sbin/sendmail  works well with Qmail.
# You may use quotes (") for executables with unusual names.
#
sendmail              = /usr/sbin/sendmail     

#
#
# The following items can be overridden in the service-specific sections.
#
#

#
# Logging via stderr/log file and syslog
#
# Logging is broken up into 8 logging levels and each level can be indivually turned on or off.
# The Stderr/log file logs all entries to stderr or the log file.
# Syslog logging uses the facility mail and the logging level of the event for logging.
# Syslog can then be configured to log data according to the levels.
#
# Set the log level to the sum of the values next to the levels you want to record.
#   1 = Emergency 
#   2 = Alert
#   4 = Critical
#   8 = Error
#  16 = Warning
#  32 = Notice
#  64 = Info
# 128 = Debug
# 256 = Database -> Logs at debug level
#
# Examples:   0 = Nothing
#            31 = Emergency + Alert + Critical + Error + Warning
#           511 = Everything
#
file_logging_levels       = 7
#
syslog_logging_levels     = 31

#
# Generate a log entry for database queries for the log level at number of seconds of query execution time.
#
query_time_info       = 10
query_time_notice     = 20
query_time_warning    = 30

#
# Throw an exception is the query takes longer than query_timeout seconds
query_timeout         = 300 

# 
# Root privs are used to open a port, then privs
# are dropped down to the user/group specified here.
#
effective_user        = dbmail
effective_group       = mail

# 
# The IPv4 and/or IPv6 addresses the services will bind to.
# Use * for all local interfaces.
# Use 127.0.0.1 for localhost only.
# Separate multiple entries with spaces ( ) or commas (,).
#
bindip                = 0.0.0.0         # IPv4 only - all IP's
#bindip                = ::             # IPv4 and IPv6 - all IP's (linux)
#bindip                = ::             # IPv6 only - all IP's (BSD)
#bindip                = 0.0.0.0,::     # IPv4 and IPv6 - all IP's (BSD)


#
# The maximum length of the queue of pending connections. See
# listen(2) for more information
#
# backlog              = 128

# 
# Idle time allowed before a connection is shut off.
#
timeout               = 300             

# 
# Idle time allowed before a connection is shut off if you have not logged in yet.
#
login_timeout         = 60

# 
# If yes, resolves IP addresses to DNS names when logging.
#
resolve_ip            = yes

#
# If yes, keep statistics in the authlog table for connecting users
#
authlog               = no

# 
# logfile for stdout messages
#
logfile               = /var/log/dbmail.log        

# 
# logfile for stderr messages
#
errorlog              = /var/log/dbmail.err        

# 
# directory for storing PID files
#
pid_directory         = /var/run/dbmail

#
# directory for locating libraries (normally has a sane default compiled-in)
#
library_directory       = /usr/lib/dbmail

#
# SSL/TLS certificates
#
# A file containing a list of CAs in PEM format
tls_cafile            =

# A file containing a PEM format certificate
tls_cert              =

# A file containing a PEM format RSA or DSA key
tls_key               =

# A cipher list string in the format given in ciphers(1)
tls_ciphers           =


# hashing algorithm. You can select your favorite hash type
# for generating unique ids for message parts. 
#
# for valid values check mhash(3) but minus the MHASH_ prefix.
#  
# if you ever change this value run 'dbmail-util --rehash' to 
# update the hash for all mimeparts.
#
# examples: MD5, SHA1, SHA256, SHA512, TIGER, WHIRLPOOL
#
# hash_algorithm = SHA1


# header_cache tuning
#
# set header_cache_readonly to 'yes' to prevent new
# unknown header-names from being cached.
#
# header_cache_readonly = yes



[LMTP]
bindip = 127.0.0.1
port                  = 24                 
#tls_port              =


[POP]
port                  = 110
#tls_port              = 995

# You can set an alternate banner to display when connecting to the service
# banner = DBMAIL pop3 server ready to rock

# 
# If yes, allows SMTP access from the host IP connecting by POP3.
# This requires addition configuration of your MTA
#
pop_before_smtp       = no      

[HTTP]
port                  = 41380
#
# the httpd daemon provides full access to all users, mailboxes
# and messages. Be very careful with this one!
bindip                = 127.0.0.1
admin                 = admin:secret

[IMAP]
# You can set an alternate banner to display when connecting to the service
# banner = imap 4r1 server (dbmail 2.3.x)

# 
# Port to bind to.
#
port                  = 143                
##tls_port              = 993

# 
# IMAP prefers a longer timeout than other services.
#
timeout               = 4000            

# 
# If yes, allows SMTP access from the host IP connecting by IMAP.
# This requires addition configuration of your MTA
#
imap_before_smtp      = no

#
# during IDLE, how many seconds between checking the mailbox
# status (default: 30)
#
# idle_timeout          = 30

# during IDLE, how often should the server send an '* OK' still
# here message (default: 10)
#
# the time between such a message is idle_timeout * idle_interval
# seconds
#
# idle_interval         = 10

#
# If TLS is enabled, login before starttls is normally
# not allowed. Use login_disabled=no to change this
#
# login_disabled        = yes

#
# Provide a CAPABILITY to override the default
#
# capability   = IMAP4 IMAP4rev1 AUTH=LOGIN ACL RIGHTS=texk NAMESPACE CHILDREN SORT QUOTA THREAD=ORDEREDSUBJECT UNSELECT IDLE

# max message size. You can specify the maximum message size
# accepted by the IMAP daemon during APPEND commands.
#
# Supported formats:
#  decimal: 1000000    
#  octal:   03777777
#  hex:     0xfffff
#
# max_message_size      =


[SIEVE]
# 
# Port to bind to.
#
port                  = 2000               
tls_port              =


[LDAP]
port                  = 389
version               = 3
hostname              = ldap
base_dn               = ou=People,dc=mydomain,dc=com

# 
# If your LDAP library supports ldap_initialize(), then you can use the
# alternative LDAP server DSN like following.
#
# URI                = ldap://127.0.0.1:389
# URI                = ldapi://%2fvar%2frun%2fopenldap%2fldapi/

# 
# Leave blank for anonymous bind.
# example: cn=admin,dc=mydomain,dc=com     
#
bind_dn               = 

# 
# Leave blank for anonymous bind.
#
bind_pw               = 
scope                 = SubTree

# AD users may want to set this to 'no' to disable
# ldap referrals if you are seeing 'Operations errors' 
# in your logs
#
referrals             = yes

user_objectclass      = top,account,dbmailUser
forw_objectclass      = top,account,dbmailForwardingAddress
cn_string             = uid
field_passwd          = userPassword
field_uid             = uid
field_nid             = uidNumber
min_nid               = 10000
max_nid               = 15000
field_cid             = gidNumber
min_cid               = 10000
max_cid               = 15000

# a comma-separated list of attributes to match when searching
# for users or forwards that match a delivery address. A match
# on any of them is a hit.
field_mail            = mail

# field that holds the mail-quota size for a user.
field_quota           = mailQuota

# field that holds the forwarding address. 
field_fwdtarget       = mailForwardingAddress

# override the query string used to search for users 
# or forwards with a delivery address.
# query_string          = (mail=%s)

[DELIVERY]
# 
# Run Sieve scripts as messages are delivered.
#
SIEVE                 = yes               

# 
# Use 'user+mailbox@domain' format to deliver to a mailbox.
#
SUBADDRESS            = yes          

# 
# Turn on/off the Sieve Vacation extension.
#
SIEVE_VACATION        = yes      

# 
# Turn on/off the Sieve Notify extension
#
SIEVE_NOTIFY          = yes

# 
# Turn on/off additional Sieve debugging.
#
SIEVE_DEBUG           = no          


# Use the auto_notify table to send email notifications.
#
AUTO_NOTIFY           = no
 
# 
# Use the auto_reply table to send away messages.
#
AUTO_REPLY            = no

# 
# Defaults to "NEW MAIL NOTIFICATION"
#
#AUTO_NOTIFY_SUBJECT        =    

# 
# Defaults to POSTMASTER from the DBMAIL section.
#
#AUTO_NOTIFY_SENDER        =   


# If you set this to 'yes' dbmail will check for duplicate
# messages in the relevant mailbox during delivery using 
# the Message-ID header
#
suppress_duplicates     = no

#
# Soft or hard bounce on over-quota delivery
#
quota_failure           = hard


# end of configuration file

  • правим default конфигурационный файл - /etc/default/dbmail
# debian specific configuration for dbmail

# work-around for linux/epoll bug in libevent
export EVENT_NOEPOLL=yes

# comment out to disable the pop3 server
START_POP3D=true

# comment out to disable the imapd server
START_IMAPD=true

# uncomment to enable the lmtpd server
START_LMTPD=true

# uncomment to enable the timsieved server
#START_SIEVE=true

# comment out to enable the stunnel SSL wrapper
START_SSL=true

# specify the filename for the pem file as 
# it resides in /etc/ssl/certs
PEMFILE="/etc/ssl/serts/dbmail.pem"
  • создаем сертификат для dbmail:
cd /etc/ssl/certs
openssl req -new -x509 -nodes -out dbmail.pem -keyout smtpd.pem -days 3650
  • перезапуск службы:
systemctl restart dbmail
  • Краткое пояснение:
1. Предназначенные для доставки сообщений от MTA в хранилище.
2. Предназначенные для доставки MUA из хранилища.
  • К первым относятся:

dbmail-lmtpd – UNIX-демон, принимающий клиентские подключения через UNIX-сокет или TCP-сокет. Для приема почтовых сообщений используется протокол LMTP. На каждое входящее сообщение MTA создает только клиентский сокет, необходимое количество процессов и подключений к БД создается заранее.
Таким образом, этот вариант обеспечивает лучшую производительность при высокой нагрузке, но при низкой он потребляет больше системных ресурсов, чем необходимо.

  • Ко вторым относятся:

dbmail-pop3d – демон для доступа по протоколу POP3.
dbmail-imapd – демон для доступа по протоколу IMAP.

  • Кроме того, в состав DBMail входят следующие вспомогательные утилиты:

dbmail-users – инструмент для управления пользователями и их псевдонимами (возможно, многим из вас будет привычнее термин alias).
dbmail-util – инструмент для очистки, оптимизации и проверки корректности БД.

  • С установкой dbmail пока окончено, следующий этап установка postgesql и настройка для будущей работы.


2. Настройка PostgreSQL

2.1. После того как мы настроили базу данных postgresql, создаем пользователя dbmail и базу dbmail

  • Создаем пользователя для работы с почтовой базой
createuser -U postgres -P dbmail
  • [!] - Ни в коем случае не используйте спецсимволы в пароле, кроме #! (авторизация может не проходить)
  • Создаем базу
createdb -U postgres --owner dbmail dbmail
  • Вместе с dbmail идут заготовки базы, распаковываем и заливаем:
bunzip2 /usr/share/doc/dbmail-2.2.10/create_tables.pgsql.bz2
psql -U dbmail -d dbmail < /usr/share/doc/dbmail-2.2.10/create_tables.pgsql

или так:

zcat /usr/share/doc/dbmail/examples/create_tables.pgsql.gz|psql -h 127.0.0.1 dbmail dbmailadmin

или так:

psql -U dbmail -h localhost maildb < create_tables.pgsql


  • В этом дампе нет таблицы для работы с виртуальными доменами, создадим ее:
 CREATE TYPE dtype AS ENUM ( 
 'LOCAL', 
 'VIRTUAL', 
 'RELAY' 
); 

ALTER TYPE public.dtype OWNER TO dbmail; 

SET default_with_oids = true; 

CREATE TABLE dbmail_domains ( 
 uid integer NOT NULL, 
 domain character varying(128) NOT NULL, 
 type dtype NOT NULL 
);

INSERT INTO dbmail_domains (uid, domain, type) VALUES (1, 'example.com', 'LOCAL');

База готова.

  • добавляем обработку базы в /etc/crontab
...
0 3 * * * root /usr/sbin/dbmail-util -cturpd -l 24h -qq
...
  • проверяем работу dbmail c базой:
dbmail-util -av

если есть ошибки, исправляем не забывая проверить файл конфигурации...
.. если все ок, приступаем к настройке postfix

3. Настройка Postfix

apt-get install postfix postfix-pgsql postfix-sqlite procmail libsasl2-2 libsasl2-modules libsasl2-modules-db\ 
libsasl2-modules-sql sqlite3 mutt postfix-pcre postfix-ldap postfix-lmdb sasl2-bin ufw 
  • вносим необходимые изменения в файлы конфигурации - пример рабочей версии main.cf:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2

# TLS parameters
#smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
#smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_cert_file=/etc/postfix/ssl/smtpd.pem
smtpd_tls_key_file=/etc/postfix/ssl/smtpd.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mymail.home.local
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, mymail.ru, mymail.home.local, localhost.home.local, localhost
relayhost = 
#mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
######################### вторым ip указываем хост где база данных postgresql
mynetworks = 127.0.0.0/8 10.0.5.2
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
############################## - указываем способ использования postgresql
local_recipient_maps = pgsql:/etc/postfix/dbmail-mailboxes.cf $alias_maps
mailbox_transport = dbmail-lmtp:127.0.0.1:24

#################### - подключаем авторизацию через sasl, установка ниже в статье.
broken_sasl_auth_clients = yes
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = 
############################### - подключаем наш сертификат созданный как описано ниже.
smtpd_tls_auth_only = no
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom


  • вносим необходимые изменения в файлы конфигурации - пример рабочей версии master.cf:
#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
#submission inet n       -       y       -       -       smtpd
#  -o syslog_name=postfix/submission
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps     inet  n       -       y       -       -       smtpd
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
pickup    unix  n       -       y       60      1       pickup
cleanup   unix  n       -       y       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
######
dbmail-lmtp     unix    -       -       n       -       -       lmtp
        -o disable_dns_lookups=yes

  • создаем файл настройки подключения к базе postgresql - dbmail-mailboxes.cf:
user = dbmail
password = userpass
hosts = 10.0.5.2
dbname = mailbasename
table = dbmail_aliases
select_field = alias
where_field = alias
  • Так как почтовый сервер изначально не рассматсривается как релей, то доступ к SMTP только по авторизации и для этого используем SASL.
  • в каталоге настроек postfix создаем файл настроек для sasl:
mkdir -p /etc/postfix/sasl
  • создаем файл конфигурации - smtpd.conf:
echo > /etc/postfix/sasl/smtpd.conf
  • вносим содержимое файла:
edit /etc/postfix/sasl/smtpd.conf
pwcheck_method: auxprop
auxprop_plugin: sql
mech_list: digest-md5 cram-md5 login plain
sql_engine: pgsql
sql_user: dbmail
sql_passwd: userpass
sql_hostnames: 10.0.5.2
sql_database: mailbasename
sql_statement: select passwd from dbmail_users where userid='%u@%r'
sql_verbose: yes
  • создаем свой recipient_bcc
*@mainhost.local admin@mailbox.ru
*@slavehost.local admin@mailbox.ru
*@otherhost.local admin@mailbox.ru
  • генерируем базу
postmap recipient_bcc
  • генерируем свой сертификат tls:
mkdir -p /etc/postfix/ssl
cd /etc/postfix/ssl
openssl req -new -x509 -days 3650 -nodes -out smtpd.pem -keyout smtpd.key
  • перезапускаем postfix:
systemctl  restart postfix

или

/etc/init.d/postfix restart
  • проверяем работу postfix:
# telnet mymail.ru 25
Trying mymail.ru...
Connected to mymail.ru.
Escape character is '^]'.
220 mx.kscom.ru ESMTP Postfix
EHLO example.com
250-mx.kscom.ru
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
QUIT
221 2.0.0 Bye
Connection closed by foreign host.

- должно быть - 250-STARTTLS - все работает..

4. Настройка Stunnel

  • Данный пакет позволяет организовать защищенное соединение как для почты так и для других программ.
  • Далее будет описание, как создать защищенный вход на почтовый сервер.
  • Устанавливаем пакет:
apt-get install stunnel4
  • в каталоге /etc/stunnel - сразу создаем себе скрипт для генерации сертификата, чтобы если понадобится снова не вспоминать как это...
echo > /etc/stunnel/create-sert
editor /etc/stunnel/create-sert
  • вносим содержимое:
#!/bin/sh
# каталог сертификатов SSL в системе
cd /etc/ssl/certs
# имя сертификата на свое усмотрение...
PEMFILE="servername.mymail.ru.pem"
# генерация сертификата
openssl req -new -x509 -nodes -days 3650 -out $PEMFILE -keyout $PEMFILE
chmod 600 $PEMFILE
[ -e temp_file ] && rm -f temp_file
dd if=/dev/urandom of=temp_file count=2
openssl dhparam -rand temp_file 512 >> $PEMFILE
ln -sf $PEMFILE `openssl x509 -noout -hash < $PEMFILE`.0
 
  • даем права на исполнение - только для root:
chmod 0700 /etc/stunnel/create-sert
  • запускаем скрипт и отвечаем на вопросы..
/etc/stunnel/create-sert
  • создаем каталог в котором будет файл запуска .pid
mkdir -p /var/run/stunnel4/
  • копируем из примера будущий конфигурационный файл для stunnel4
cp /usr/share/doc/stunnel4/examples/stunnel.conf-sample /etc/stunnel/stunnel.conf
  • приводим его в такой вариант (рабочий пример):
; Sample stunnel configuration file for Unix by Michal Trojnara 2002-2015
; Some options used here may be inadequate for your particular configuration
; This sample file does *not* represent stunnel.conf defaults
; Please consult the manual for detailed description of available options

; **************************************************************************
; * Global options                                                         *
; **************************************************************************

; It is recommended to drop root privileges if stunnel is started by root
;setuid = stunnel4
;setgid = stunnel4

; PID file is created inside the chroot jail (if enabled)
pid = /var/run/stunnel4/stunnel.pid

; Debugging stuff (may be useful for troubleshooting)
;foreground = yes
;debug = info
output = /var/log/stunnel.log

; Enable FIPS 140-2 mode if needed for compliance
;fips = yes
fips = no
; **************************************************************************
; * Service defaults may also be specified in individual service sections  *
; **************************************************************************

; Enable support for the insecure SSLv3 protocol
options = -NO_SSLv3
sslVersion = TLSv1.2

; These options provide additional security at some performance degradation
;options = SINGLE_ECDH_USE
;options = SINGLE_DH_USE

; **************************************************************************
; * Include all configuration file fragments from the specified folder     *
; **************************************************************************

;include = /etc/stunnel/conf.d

; **************************************************************************
; * Service definitions (remove all services for inetd mode)               *
; **************************************************************************

; ***************************************** Example TLS client mode services

; The following examples use /etc/ssl/certs, which is the common location
; of a hashed directory containing trusted CA certificates.  This is not
; a hardcoded path of the stunnel package, as it is not related to the
; stunnel configuration in /etc/stunnel/.

;[mymail-pop3]
;client = yes
;accept = 127.0.0.1:110
;connect = pop3.mymail.ru:995
;verifyChain = yes
;CApath = @sysconfdir/ssl/certs
;checkHost = pop3s.mymail.ru
;OCSPaia = yes

;[mymail-imap]
;client = yes
;accept = 127.0.0.1:143
;connect = imap.mymail.ru:993
;verifyChain = yes
;CApath = @sysconfdir/ssl/certs
;checkHost = imaps.mymail.ru
;OCSPaia = yes

;[mymail-smtp]
;client = yes
;accept = 127.0.0.1:25
;connect = smtp.mymail.ru:465
;verifyChain = yes
;CApath = @sysconfdir/ssl/certs
;checkHost = smtps.mymail.ru
;OCSPaia = yes

; ***************************************** Example TLS server mode services

[pop3s]
accept  = 995
connect = 110
cert = /etc/ssl/certs/servername.mymail.ru.pem

[imaps]
accept  = 993
connect = 143
cert = /etc/ssl/certs/servername.mymail.ru.pem

[smtps]
accept  = 465
connect = 25
cert = /etc/ssl/certs/servername.mymail.ru.pem

; TLS front-end to a web server
;[https]
;accept  = 443
;connect = 80
;cert = /etc/stunnel/stunnel.pem
; "TIMEOUTclose = 0" is a workaround for a design flaw in Microsoft SChannel
; Microsoft implementations do not use TLS close-notify alert and thus they
; are vulnerable to truncation attacks
;TIMEOUTclose = 0

; Remote shell protected with PSK-authenticated TLS
; Create "/etc/stunnel/secrets.txt" containing IDENTITY:KEY pairs
;[shell]
;accept = 1337
;exec = /bin/sh
;execArgs = sh -i
;ciphers = PSK
;PSKsecrets = /etc/stunnel/secrets.txt

; Non-standard MySQL-over-TLS encapsulation connecting the Unix socket
;[mysql]
;cert = /etc/stunnel/stunnel.pem
;accept = 3307
;connect = /run/mysqld/mysqld.sock

; vim:ft=dosini
  • корректируем конфигурационный файл запуска по умолчанию:
# /etc/default/stunnel
# Julien LEMOINE <speedblue@debian.org>
# September 2003

# Change to one to enable stunnel automatic startup
ENABLED=1
FILES="/etc/stunnel/*.conf"
OPTIONS=""

# Change to one to enable ppp restart scripts
PPP_RESTART=0

# Change to enable the setting of limits on the stunnel instances
# For example, to set a large limit on file descriptors (to enable
# more simultaneous client connections), set RLIMITS="-n 4096"
# More than one resource limit may be modified at the same time,
# e.g. RLIMITS="-n 4096 -d unlimited"
RLIMITS=""
  • перезапуск stunnel
/etc/init.d/stunnel4 restart
  • после этого проверяем наличие нужных нам портов:
nmap -v mymail.ru
...
PORT    STATE SERVICE
22/tcp  open  ssh
25/tcp  open  smtp
110/tcp open  pop3
143/tcp open  imap
465/tcp open  smtps
993/tcp open  imaps
995/tcp open  pop3s 
  • проверяем работу с почтой по SSL\TLS - зашифрованный пароль на портах 465,993,995
  • если все в порядке, рекомендую закрыть обычные порты через iptables (110,143),
  • а оставить только 25 (некоторые серверы для доставки вам почты требуют именно его)

5. Установка антиспама Spamassassin

  • установка пакета:
aptitude install spamassassin
  • запуск по умолчанию в /etc/default/spamassassin
...
ENABLED=1
...
  • Приводим файл конфигурации антиспама /etc/spamassassin/local.cf к такому:
# This is the right place to customize your installation of SpamAssassin.
#
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
# tweaked.
#
# Only a small subset of options are listed below
#
###########################################################################

#   Add *****SPAM***** to the Subject header of spam e-mails
#
rewrite_header Subject *****SPAM*****


#   Save spam messages as a message/rfc822 MIME attachment instead of
#   modifying the original message (0: off, 2: use text/plain instead)
#
report_safe 0


#   Set which networks or hosts are considered 'trusted' by your mail
#   server (i.e. not spammers)
#
# trusted_networks 212.17.35.
trusted_networks 10.0.5.


#   Set file-locking method (flock is not safe over NFS, but is faster)
#
# lock_method flock


#   Set the threshold at which a message is considered spam (default: 5.0)
#
required_score 5.0


#   Use Bayesian classifier (default: 1)
#
use_bayes 1


#   Bayesian classifier auto-learning (default: 1)
#
bayes_auto_learn 1


#   Set headers which may provide inappropriate cues to the Bayesian
#   classifier
#
bayes_ignore_header X-Bogosity
bayes_ignore_header X-Spam-Flag
bayes_ignore_header X-Spam-Status


#   Whether to decode non- UTF-8 and non-ASCII textual parts and recode
#   them to UTF-8 before the text is given over to rules processing.
#
# normalize_charset 1

#   Some shortcircuiting, if the plugin is enabled
# 
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
#
#   default: strongly-whitelisted mails are *really* whitelisted now, if the
#   shortcircuiting plugin is active, causing early exit to save CPU load.
#   Uncomment to turn this on
#
# shortcircuit USER_IN_WHITELIST       on
# shortcircuit USER_IN_DEF_WHITELIST   on
# shortcircuit USER_IN_ALL_SPAM_TO     on
# shortcircuit SUBJECT_IN_WHITELIST    on

#   the opposite; blacklisted mails can also save CPU
#
# shortcircuit USER_IN_BLACKLIST       on
# shortcircuit USER_IN_BLACKLIST_TO    on
# shortcircuit SUBJECT_IN_BLACKLIST    on

#   if you have taken the time to correctly specify your "trusted_networks",
#   this is another good way to save CPU
#
# shortcircuit ALL_TRUSTED             on

#   and a well-trained bayes DB can save running rules, too
#
# shortcircuit BAYES_99                spam
# shortcircuit BAYES_00                ham
whitelist_from @mymail.ru

endif # Mail::SpamAssassin::Plugin::Shortcircuit

  • Стартуем spamassasin:
/etc/init.d/spamassassin start 
  • Редактируем файл постфикса /etc/postfix/master.cf

- Строку:

..
smtp      inet  n       -       -       -       -       smtpd
..

- Заменяем на:

..
smtp      inet  n       -       -       -       -       smtpd -o content_filter=spamassassin
..

- Перед:

..
dbmail-lmtp     unix    -       -       n       -       -       lmtp
        -o disable_dns_lookups=yes
..

- Добавляем:

..
spamassassin unix   -   n   n   -   -   pipe  user=debian-spamd argv=/usr/bin/spamc -s 5120000 -f -e /usr/sbin/sendmail -oi -f
${sender}${recipient}
..
  • Перезапускаем postfix:
/etc/init.d/postfix restart
  • Проверяем работу почты, все должно работать...



Источники: