Postfix+cyrus-saslauthd+dovecot+openldap

Обсуждение настройки и работы сервисов, резервирования, сетевых настроек и вопросов безопасности ОС.

Модераторы: SLEDopit, Модераторы разделов

Аватара пользователя
strah
Сообщения: 283
ОС: Freebsd, linux, Solaris.

Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение strah »

Настройка связки postfix + dovecot + cyrus-saslauthd + openldap

1)Введение:
Итак, нам необходимо настроить почтовый сервер, который будет хранить инфу о пользователях/алиасах/etc в LDAP. В нашем примере мы будем использовать openldap, хотя можно взять любой другой LDAP-сервер. Кроме того, нам надо обеспечить smtp-аутентентификацию пользвательей, чтобы абы кто не мог отправлять с нашего сервера сообщения. Кроме того, надо будет настроить imaps-аутентификацию для того, чтобы анонимус не мог читать чужие письма. И smtp, и imaps аутентификация будет проводиться с использованием сертификатов – для повышения безопасности. В качестве smtp-сервера мы будем юзать postfix, как один из наиболее безопасных, в качестве сервера аутентификации для postfix'а будет использоваться cyrus-authd, а в качестве imaps-сервера – dovecot (аутентификацию через LDAP он умеет проводить сам).

2)Установка ПО:
В качестве openldap-сервера в нашем случае будет использоваться Redhat Enterprise Linux 5.0, а в качестве smtp/imaps сервера – FreeBSD 7.1. На машину с FreeBSD кроме самих пакетов postfix, cyrus-authd и dovecot надо будет установить openssl, но обо всем по порядку.

2.1)Настройка LDAP-сервера.
Для начала устанавливаем пакет openldap-2.3.27-8.el5_1.3.x86_64.rpm (или openldap-2.3.27-8.el5_1.3.i386.rpm – зависит от архитектуры). Далее открываем в своем любимом текстовом редакторе файл /etc/openldap/slapd.conf, и приводим его к следующему виду:

Код:

# # See slapd.conf(5) for details on configuration options. # This file should NOT be world readable. # include /etc/openldap/schema/core.schema include /etc/openldap/schema/cosine.schema include /etc/openldap/schema/inetorgperson.schema include /etc/openldap/schema/nis.schema include /etc/openldap/schema/mail.schema #содержимое схемы приведено ниже # Allow LDAPv2 client connections. This is NOT the default. #allow bind_v2 # Do not enable referrals until AFTER you have a working directory # service AND an understanding of referrals. #referral ldap://root.openldap.org pidfile /var/run/openldap/slapd.pid argsfile /var/run/openldap/slapd.args # Load dynamic backend modules: # modulepath /usr/lib64/openldap # moduleload back_bdb.la # moduleload back_ldap.la # moduleload back_ldbm.la # moduleload back_passwd.la # moduleload back_shell.la # The next three lines allow use of TLS for encrypting connections using a # dummy test certificate which you can generate by changing to # /etc/pki/tls/certs, running "make slapd.pem", and fixing permissions on # slapd.pem so that the ldap user or group can read it. Your client software # may balk at self-signed certificates, however. # TLSCACertificateFile /etc/pki/tls/certs/ca-bundle.crt # TLSCertificateFile /etc/pki/tls/certs/slapd.pem # TLSCertificateKeyFile /etc/pki/tls/certs/slapd.pem # Sample security restrictions # Require integrity protection (prevent hijacking) # Require 112-bit (3DES or better) encryption for updates # Require 63-bit encryption for simple bind # security ssf=1 update_ssf=112 simple_bind=64 # Sample access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # Directives needed to implement policy: # access to dn.base="" by * read # access to dn.base="cn=Subschema" by * read # access to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! ####################################################################### # ldbm and/or bdb database definitions ####################################################################### database bdb suffix "dc=local,dc=net" #суффикс нашей БД rootdn "cn=God,dc=local,dc=net" #описание «админского» объекта, имеющего права на запись куда угодно в нашем дереве. # Cleartext passwords, especially for the rootdn, should # be avoided. See slappasswd(8) and slapd.conf(5) for details. # Use of strong authentication encouraged. # rootpw secret rootpw {MD5}X03MO1qnZdYdgyfeuILPmQ== #MD5-хеш пароля, генерируется программой slappasswd # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. directory /var/ldap #папка, где хранятся данные дерева. # Indices to maintain for this database #описания индексов. index objectClass eq,pres index mail eq index maildrop eq index ou,cn,surname,givenname eq,pres,sub index uidNumber,gidNumber,loginShell eq,pres index uid,memberUid eq,pres,sub index nisMapName,nisMapEntry eq,pres,sub #разрешаем анонимусу аутентифицироваться access to attrs=userPassword by self write by anonymous auth by * none access to * by self read by * none


Далее, нам необходимо создать схему mail.schema с описанием нужных нам объектов:

/etc/openldap/schema/mail.schema:

Код:

######### # old postfix mail address attribute from postfix-courier.schema #attributetype ( 0.9.2342.19200300.100.5.3 # NAME ( 'postfix-alias' 'postfix-email' ) # DESC 'Postfix virtual mailbox' # EQUALITY caseIgnoreIA5Match # SUBSTR caseIgnoreIA5SubstringsMatch # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) # standart mail address attribute from core.schema included at OpenLDAP 2.1.x version #attributetype ( 0.9.2342.19200300.100.1.3 # NAME ( 'mail' 'rfc822Mailbox' ) # DESC 'RFC1274: RFC822 Mailbox' # EQUALITY caseIgnoreIA5Match # SUBSTR caseIgnoreIA5SubstringsMatch # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) # standart (from) mail address (for routing forwarding ) attribute from # misc.schema included at OpenLDAP 2.1.x version #attributetype ( 2.16.840.1.113730.3.1.13 # NAME 'mailLocalAddress' # DESC 'RFC822 email address of this recipient' # EQUALITY caseIgnoreIA5Match # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) # standart mail host attribute. see description. # new unique attribute i'm not used this older howto. #attributetype ( 2.16.840.1.113730.3.1.18 # NAME 'mailHost' # DESC 'FQDN of the SMTP/MTA of this recipient' # EQUALITY caseIgnoreIA5Match # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} # SINGLE-VALUE ) # old postfix mail forwarding attribute from postfix-courier.schema #attributetype ( 0.9.2342.19200300.100.5.5 # NAME ( 'postfix-forward' 'postfix-remote-alias') # DESC 'Postfix forwarding maps' # EQUALITY caseIgnoreIA5Match # SUBSTR caseIgnoreIA5SubstringsMatch # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) # standart mail routing attribute. may be used for forwarding (to) #attributetype ( 2.16.840.1.113730.3.1.47 # NAME 'mailRoutingAddress' # DESC 'RFC822 routing address of this recipient' # EQUALITY caseIgnoreIA5Match # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} # SINGLE-VALUE ) # very intresting attribute. This it can used in mail subscribe by members. # You know any MTA support this ? #attributetype ( 1.3.6.1.4.1.42.2.27.2.1.15 # NAME 'rfc822MailMember' # DESC 'rfc822 mail address of group member(s)' # EQUALITY caseIgnoreIA5Match # SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) ########## courier schema ############### # Remember ! if you use this schema exclude authldap.schema. attributetype ( 1.3.6.1.4.1.10018.1.1.454 NAME 'mailAlias' DESC 'A mail alias' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) attributetype ( 1.3.6.1.4.1.10018.1.1.2 NAME 'quota' DESC 'A string that represents the quota on a mailbox' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) attributetype ( 1.3.6.1.4.1.10018.1.1.3 NAME 'maildrop' DESC 'The absolute path to the mailbox for a mail account in a non-default location' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} ) # use mailHost ? attributetype ( 1.3.6.1.4.1.10018.1.1.4 NAME 'mailDomain' DESC 'A virtual mail domain' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) attributetype ( 1.3.6.1.4.1.10018.1.1.5 NAME 'mailTransport' DESC 'transport for domain' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) attributetype ( 1.3.6.1.4.1.10018.1.1.6 NAME 'mailAccess' DESC 'Access string' EQUALITY caseIgnoreIA5Match SUBSTR caseIgnoreIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) ############################ # object class ############################ # old postfix object for mail forwarding. #objectclass (0.9.2342.19200300.100.5.13 # NAME 'postfix-forward-map' # DESC 'Postfix forward map' # SUP top STRUCTURAL # MUST ( postfix-alias $ postfix-forward ) ) # # standart object for mail forward. # object class for routing & forwarding. # additional information mailHost. # Can help routing in multi MTA & LDAP server configuration and saves timein search. # objectclass ( 2.16.840.1.113730.3.2.147 # NAME 'inetLocalMailRecipient' # DESC 'Internet local mail recipient' # SUP top STRUCTURAL # MAY ( mailLocalAddress $ mailHost $ mailRoutingAddress ) ) # warning !!! change AUXILIARY to STRUCTURAL ! #objectclass (0.9.2342.19200300.100.5.12 # NAME 'postfix-alias-map' # DESC 'Postfix virtual account map' # SUP top STRUCTURAL # MUST ( postfix-alias $ postfix-uid $ postfix-gid $ postfix-maildir ) # MAY ( userPassword $ courier-clearPassword $ courier-home $ courier-quota ) ) objectclass ( 1.3.6.1.4.1.10018.1.2.1235 NAME 'mailPerson' DESC 'RFC2256: a person' SUP top AUXILIARY MUST ( sn $ cn ) MAY ( telephoneNumber ) ) objectclass ( 1.3.6.1.4.1.10018.1.2.1234 NAME 'aliasObject' SUP TOP STRUCTURAL DESC 'Mail alias object' MUST ( mail $ mailAlias ) ) # object class for full mail account objectclass ( 1.3.6.1.4.1.10018.1.2.1 NAME 'fullMailAccount' SUP top STRUCTURAL DESC 'Full mail account object as used by the mail for server recive &storage messages' MUST ( mail $ maildrop ) MAY ( uid $ cn $ description $ quota $ userPassword ) ) # object class for mail account # others attributes contains in additonal posixAccount. objectclass ( 1.3.6.1.4.1.10018.1.2.2 NAME 'mailAccount' SUP organizationalPerson STRUCTURAL DESC 'mail account object as used by the mail for server recive & storage messages' MUST ( mail $ maildrop ) MAY ( quota ) ) #objectclass (0.9.2342.19200300.100.5.11 # NAME 'postfix-transport-map' # DESC 'Postfix virtual domain-transport map' # SUP top STRUCTURAL # MUST ( postfix-domain $ postfix-transport ) ) # object class for virtual mail domain # & additional transport table objectclass ( 1.3.6.1.4.1.10018.1.2.3 NAME 'mailDomainTransport' SUP top STRUCTURAL DESC 'Domain mail aliasing/transporting entry' MUST ( mailDomain ) MAY ( mailTransport $ description ) ) # alternate object class #objectclass ( 1.3.6.1.4.1.10018.1.2.3 NAME 'mailDomainTransport' SUP top STRUCTURAL # DESC 'Domain mail aliasing/transporting entry' # MUST ( mailHost ) # MAY ( mailTransport $ description ) ) # additional class object for access network & ip we can got in nis.schema # ipHost & ipNetwork # blacklist object class objectclass ( 1.3.6.1.4.1.10018.1.2.4 NAME 'mailAccess' SUP top STRUCTURAL DESC 'mail & domain access entry' MUST ( mail ) MAY ( mailAccess $ description ) )



Теперь, запускаем наш LDAP-сервер, для чего выполняем

Код: Выделить всё

/etc/init.d/ldap start

Добавляем slapd в автозагрузку:

Код: Выделить всё

ln -s /etc/init.d/ldap /etc/rc5.d/S73ldap


Все, теперь переходим к настройке непосредственно почты.

2.2)Настройка postfix.
Для начала, кроме самого постфикса нам понадобятся пакеты openssl и openldap-clients.
Итак, после утановки всех пакетов (не забываем, что при установке постфикса из портов надо включить поддержку SSL, OpenLDAP и cyrus) открываем файл /usr/local/etc/openldap/ldap.conf, и приводим его к следующему виду:

Код: Выделить всё

BASE    dc=local,dc=net  #Корневой DN базы
URI     ldap://192.168.100.95 #ip адрес LDAP-сервера


Теперь заполняем дерево новыми объектами:

new.ldif:

Код:

# local.net dn: dc=local,dc=net objectClass: organization objectClass: dcObject dc: local o: Hell state university street: Level 4 of hell # telecommunications, local.net dn: ou=telecommunications,dc=local,dc=net objectClass: organizationalUnit ou: telecommunications telephoneNumber: 02-01-03 # kenny, telecommunications, local.net dn: uid=kenny,ou=telecommunications,dc=local,dc=net objectClass: fullMailAccount objectClass: mailPerson mail: kenny@mail.local.net maildrop: kenny/ uid: kenny cn: Alexander userPassword: {CRYPT}password1 sn: Vasa.Pupkins # tom, telecommunications, local.net dn: uid=tom,ou=telecommunications,dc=local,dc=net objectClass: fullMailAccount objectClass: mailPerson mail: tom@mail.local.net maildrop: tom/ uid: tom cn: Keiti cn: Denis userPassword: {CRYPT}ppp sn: Repkov.Denis # sysobjects, local.net dn: ou=sysobjects,dc=local,dc=net objectClass: organizationalUnit ou: sysobjects description: System objects # mailAliases, sysobjects, local.net dn: ou=mailAliases,ou=sysobjects,dc=local,dc=net objectClass: organizationalUnit ou: mailAliases # terminal@mail.local.net, mailAliases, sysobjects, local.net dn: mail=terminal@mail.local.net,ou=mailAliases,ou=sysobjects,dc=local,dc=net objectClass: aliasObject mail: terminal@mail.local.net mailAlias: tom@mail.local.net # Repkov.Denis@mail.local.net, mailAliases, sysobjects, local.net dn: mail=Repkov.Denis@mail.local.net,ou=mailAliases,ou=sysobjects,dc=local,dc= net objectClass: aliasObject mail: Repkov.Denis@mail.local.net mailAlias: tom@mail.local.net # Vasa.Pupkins@mail.local.net, mailAliases, sysobjects, local.net dn: mail=Vasa.Pupkins@mail.local.net,ou=mailAliases,ou=sysobjects,dc=local,dc=net objectClass: aliasObject mail: Vasa.Pupkins@mail.local.net mailAlias: kenny@mail.local.net

Теперь добавляем содержимое файла к дереву:

Код: Выделить всё

ldapadd -D "cn=God,dc=local,dc=net" -w password -f new.ldif


Проверяем, насколько все успешно прошло:

Код: Выделить всё

ldapsearch -D "cn=God,dc=local,dc=net" -b "dc=local,dc=net" -w password


Теперь приступим к постфиксу. Открываем в текстовом редакторе файл "${POSTFIX_BASEDIR}/etc/postfix/main.cf", и приводим его к виду:

Код:

#имя папки очереди queue_directory = /var/mail/pspool command_directory = /usr/sbin daemon_directory = /usr/libexec/postfix #директория для chroot data_directory = /var/mail/postfix #владелец папок $queue_directory и $data_directory mail_owner = postfix inet_interfaces = 192.168.100.61, 127.0.0.1 #для кого юзать транспорт local mydestination = localhost unknown_local_recipient_reject_code = 550 relay_domains = debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5 newaliases_path = /usr/bin/newaliases mailq_path = /usr/bin/mailq setgid_group = postdrop html_directory = /usr/share/doc/postfix manpage_directory = /usr/local/man sample_directory = /etc/postfix readme_directory = /usr/share/doc/postfix #максимальный размер сообщения message_size_limit = 1048576 virtual_mailbox_base = /var/mail virtual_mailbox_domains = mail.local.net #для кого юзать транспорт virtual virtual_mailbox_maps = ldap:/etc/postfix/virtual.mbox.ldap #файл, где описывается схема маппинга пользователей для транспорта virtual, файл приведен ниже. virtual_alias_maps = ldap:/etc/postfix/virtual.aliases.ldap #файл, где описывается схема маппинга алиасов для транспорта virtual, файл приведен ниже. virtual_uid_maps = static:1001 #владелец почты virtual_gid_maps = static:1001 virtual_mailbox_limit = 5242880 #максимальный размер ящика remote_header_rewrite_domain = mail.local.net canonical_maps = ldap:/etc/postfix/cannonical.ldap #схема маппинга канонических имен smtpd_reject_unlisted_sender = yes smtpd_delay_reject = yes smtpd_client_restrictions = permit_sasl_authenticated, reject #настройки acl smtpd_sasl_auth_enable = yes smtpd_sasl_security_options = noanonymous #никаких анонимусов! smtpd_sasl_path = smtpd smtpd_tls_cert_file = /etc/ssl/certs/dovecot.pem smtpd_tls_key_file = /etc/ssl/private/dovecot.pem smtpd_tls_security_level = encrypt #никаких нешифрованных соединений! smtpd_tls_CA_file = /etc/ssl/certs/cacert.pem


/etc/postfix/virtual.mbox.ldap

Код: Выделить всё

version = 3      #По умоляанию юзается 2-я версия протокола
server_host = 192.168.100.95     #адрес ldap-сервера
search_base = dc=local,dc=net
bind_dn = cn=God,dc=local,dc=net
bind_pw = password
query_filter = (&(mail=%s)(objectClass=fullMailAccount))  #фильтр поиска, для просветления курить "man ldapsearch"
result_attribute = maildrop


/etc/postfix/cannonical.ldap

Код: Выделить всё

version = 3
server_host = 192.168.100.95
search_base = dc=local,dc=net
bind_dn = cn=God,dc=local,dc=net
bind_pw = password
query_filter = (&(uid=%s)(objectClass=fullMailAccount))
result_attribute = sn


/etc/postfix/virtual.aliases.ldap

Код: Выделить всё

version = 3
server_host = 192.168.100.95
search_base = ou=mailAliases,ou=sysobjects,dc=local,dc=net
bind_dn = cn=God,dc=local,dc=net
bind_pw = password
query_filter= (&(mail=%s)(objectClass=aliasObject))
result_attribute = mailAlias



Настраиваем openssl:

/etc/ssl/openssl.cnf

Код:

HOME = . RANDFILE = $ENV::HOME/.rnd oid_section = new_oids [ new_oids ] [ ca ] default_ca = CA_default # The default ca section [ CA_default ] dir = ./demoCA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of # several ctificates with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = $dir/cacert.pem # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number # must be commented out to leave a V1 CRL crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem# The private key RANDFILE = $dir/private/.rand # private random number file x509_extensions = usr_cert # The extentions to add to the cert name_opt = ca_default # Subject Name options cert_opt = ca_default # Certificate field options default_days = 365 # how long to certify for default_crl_days= 365 # how long before next CRL default_md = sha1 # which md to use. preserve = no # keep passed DN ordering policy = policy_match [ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional [ req ] default_bits = 1024 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes x509_extensions = v3_ca # The extentions to add to the self signed cert string_mask = nombstr [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = RU countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = Ulyanovsk localityName = Locality Name (eg, city) localityName_default = Big Ass 0.organizationName = Organization Name (eg, company) 0.organizationName_default = Bell labs organizationalUnitName = Organizational Unit Name (eg, section) #organizationalUnitName_default = commonName = Common Name (eg, YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 64 # SET-ex3 = SET extension number 3 [ req_attributes ] challengePassword = A challenge password challengePassword_min = 4 challengePassword_max = 20 unstructuredName = An optional company name [ usr_cert ] basicConstraints=CA:FALSE nsComment = "OpenSSL Generated Certificate" subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment [ v3_ca ] subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer:always basicConstraints = CA:true [ crl_ext ] authorityKeyIdentifier=keyid:always,issuer:always [ proxy_cert_ext ] basicConstraints=CA:FALSE nsComment = "OpenSSL Generated Certificate" subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer:always proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo


Теперь генерим все нужные сертификаты:

Код: Выделить всё

openssl req -x509 -nodes -keyout /etc/ssl/private/dovecot.pem -out /etc/ssl/certs/dovecot.pem
openssl req -x509 -keyout /etc/ssl/private/cakey.pem -out /etc/ssl/certs/cacert.pem
openssl crl -in /etc/ssl/certs/cacert.pem -out crl.pem
cat crl.pem >> /etc/ssl/certs/cacert.pem


А вот пример создания пользовательских сертификатов:

Код: Выделить всё

openssl req -keyout newkey.pem -out req.pem


Подписывание клиентских сертификатов:

Код: Выделить всё

openssl ca -in req.pem -keyfile newkey.pem -out newcert.pem -cert /etc/ssl/certs/cacert.pem
cat crl.pem >> newcert.pem


Генерация PKCS#12 файла, нужно для импортирования сертификата во многие почтовые клиенты.

Код: Выделить всё

openssl pkcs12 -export -in newcert.pem -inkey newkey.pem -out newcert.p12


Несмотря на то, что настройка постфикса закончена, запускать его еще рано, ибо пока еще не настроен cyrus.

2.3)Настройка cyrus-saslauthd
Устанавливаем cyrus-saslauthd, далее приводим следующие файлы к соответствующему виду:

/usr/local/lib/sasl2/smtpd.conf

Код: Выделить всё

pwcheck_method: saslauthd


/usr/local/lib/sasl2/saslauthd.conf

Код:

ldap_servers: ldap://192.168.100.95 ldap_bind_dn: cn=God,dc=local,dc=net ldap_bind_pw: password ldap_version: 3 ldap_search_base: dc=local,dc=net ldap_scope: sub ldap_auth_method: custom ldap_filter: uid=%u


После чего немножко меняем скрипт запуска saslauthd, а именно, открываем файл
/usr/local/etc/rc.d/saslauthd, ищем там переменную saslauthd_flags, и меняем ее значение на ${saslauthd_flags:-"-a ldap -O/usr/local/lib/sasl2/saslauthd.conf"}

Теперь, редактируя /etc/rc.conf, добавляем в автозагрузку postfix и saslauthd (кроме того, не забываем отключить sendmail :>):

/etc/rc.conf

Код: Выделить всё

...
...
sendmail_enable="NONE"
postfix_enable="YES"
saslauthd_enable="YES"
...
...


2.4)Настройка dovecot

Приводим файл /usr/local/etc/dovecot.conf к следующему виду:

Код:

#Юзаем только imaps, также доступны pop3, imap, pop3s protocols = imaps listen = 192.168.100.61 disable_plaintext_auth = yes log_path = /var/log/dovecot.log ssl_listen = 192.168.100.61 ssl_cert_file = /etc/ssl/certs/dovecot.pem ssl_key_file = /etc/ssl/private/dovecot.pem ssl_ca_file = /etc/ssl/certs/cacert.pem ssl_verify_client_cert = yes #в принципе, можно отключить verbose_ssl = yes login_max_processes_count = 20 login_greeting = Welcome to the hell! mail_location = maildir:/var/mail/%u mail_uid = 1001 mail_gid = 1001 mail_privileged_group = mail verbose_proctitle = yes first_valid_uid = 1000 first_valid_gid = 1000 protocol imap { mail_max_userip_connections = 10 login_greeting_capability = yes imap_client_workarounds = delay-newmail netscape-eoh tb-extra-mailbox-sep } auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@ auth_username_format = %u auth default { mechanisms = plain login passdb ldap { args = /usr/local/etc/dovecot-ldap.conf } userdb ldap { args = /usr/local/etc/dovecot-ldap.conf } user = root ssl_require_client_cert = yes ssl_username_from_cert = yes socket listen { master { path = /var/run/dovecot/auth-master mode = 0600 } } } plugin { quota = maildir quota_rule = *:storage=5120 }


/usr/local/etc/dovecot-ldap.conf:

Код:

uris = ldap://192.168.100.95 dn = cn=God,dc=local,dc=net dnpass = password ldap_version = 3 base = dc=local, dc=net user_attrs = user_filter = (&(objectClass=fullMailAccount)(uid=%u)) pass_attrs = uid=user,userPassword=password pass_filter = (&(objectClass=fullMailAccount)(uid=%u))


Все, теперь осталось только добавить запуск dovecot'а в /etc/rc.conf, и все, наша почтовая система готова. Теперь осталось только создать для нее пользователей...

P.S
Все вышесказанное писалось что то около недели назад, ночью после экзамена по матану, так что возможны разного рода глюки.
/earth: file system full
Спасибо сказали:
konki
Сообщения: 216

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение konki »

в схему работы особо не вникал, но сразу возник вопрос: почему выбор пал на cyrus-saslauthd, а не на встроенный в dovecot механизм аутентификации.

за howto большое спасибо. сам хотел поднимать такую связку через неделю, но пока без ldap, тк опыта работы с ним пока еще нет.
Спасибо сказали:
Аватара пользователя
Ленивая Бестолочь
Бывший модератор
Сообщения: 2760
ОС: Debian; gentoo

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение Ленивая Бестолочь »

вопрос номер раз:

Код: Выделить всё

attributetype ( 2.5.4.4 NAME ( 'sn' 'surname' )
        DESC 'RFC2256: last (family) name(s) for which the entity is known by'
        SUP name )

а у вас там, например:

Код: Выделить всё

sn: Repkov.Denis

это из каких соображений?
Солнце садилось в море, а люди с неоконченным высшим образованием выбегали оттуда, думая, что море закипит.
Спасибо сказали:
Аватара пользователя
strah
Сообщения: 283
ОС: Freebsd, linux, Solaris.

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение strah »

Ленивая Бестолочь, просто дело в том, что я ВНЕЗАПНО решил, что мне нужны canonical maps уже после того, как создал все объекты в базе, а удалять их не хотелось. Естественно, я понимаю, что в рабочей ситуации так делать не надо.

в схему работы особо не вникал, но сразу возник вопрос: почему выбор пал на cyrus-saslauthd, а не на встроенный в dovecot механизм аутентификации.

Опять таки, первоначально я собрал postfix с поддержкой аутентификации через curys-saslauthd, и пересобирать его для аутентификации через dovecot не видел смысла. Да и удобнее мне с cyrus-saslauthd, если честно.
/earth: file system full
Спасибо сказали:
Аватара пользователя
krz
Сообщения: 50

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение krz »

Уже несколько дней бьюсь с Cyrus-sasl, не удаётся прикрутить механизм ldap.
Вылетает при конфигурировании

Код: Выделить всё

./configure --prefix=/usr --sysconfdir=/etc/sasl --localstatedir=/var --enable-login --enable-cram --enable-plain  --enable-ldapdb --with-ldap



Вот собственно лог configure и ошибка:

Код: Выделить всё

configure: loading cache ./config.cache
checking build system type... (cached) i686-pc-linux-gnu
checking host system type... (cached) i686-pc-linux-gnu
checking target system type... (cached) i686-pc-linux-gnu
checking for a BSD-compatible install... (cached) /usr/bin/ginstall -c
checking whether build environment is sane... yes
checking for gawk... (cached) gawk
checking whether make sets $(MAKE)... (cached) yes
checking for gcc... (cached) gcc
checking for C compiler default output... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... (cached) o
checking whether we are using the GNU C compiler... (cached) yes
checking whether gcc accepts -g... (cached) yes
checking for gcc option to accept ANSI C... (cached) none needed
checking for style of include used by make... GNU
checking dependency style of gcc... (cached) gcc3
checking how to run the C preprocessor... (cached) gcc -E
checking for gawk... (cached) gawk
checking whether ln -s works... yes
checking whether make sets $(MAKE)... (cached) yes
checking for a BSD-compatible install... /usr/bin/ginstall -c
checking for __attribute__... (cached) no
checking for runpath switch... -Wl,-rpath,
checking for ranlib... (cached) ranlib
checking for ld used by GCC... (cached) /usr/i486-slackware-linux/bin/ld
checking if the linker (/usr/i486-slackware-linux/bin/ld) is GNU ld... (cached) yes
checking for BSD-compatible nm... (cached) /usr/bin/nm -B
updating cache ./config.cache
loading cache ./config.cache within ltconfig
checking for object suffix... o
checking for executable suffix... (cached)
checking for gcc option to produce PIC... -fPIC
checking if gcc PIC flag -fPIC works... yes
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.lo... yes
checking if gcc supports -fno-rtti -fno-exceptions ... no
checking if gcc static flag -static works... -static
checking if the linker (/usr/i486-slackware-linux/bin/ld) is GNU ld... yes
checking whether the linker (/usr/i486-slackware-linux/bin/ld) supports shared libraries... yes
checking command to parse /usr/bin/nm -B output... ok
checking how to hardcode library paths into programs... immediate
checking for /usr/i486-slackware-linux/bin/ld option to reload object files... -r
checking dynamic linker characteristics... Linux ld.so
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... no
checking for objdir... .libs
creating libtool
updating cache ./config.cache
configure: loading cache ./config.cache
checking for connect... (cached) yes
checking for res_search... (cached) no
checking for dn_expand... (cached) yes
checking for dns_lookup... (cached) no
checking DB path to use... /etc/sasldb2
checking for egrep... (cached) grep -E
checking for ANSI C header files... (cached) yes
checking for sys/types.h... (cached) yes
checking for sys/stat.h... (cached) yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking for memory.h... (cached) yes
checking for strings.h... (cached) yes
checking for inttypes.h... (cached) yes
checking for stdint.h... (cached) yes
checking for unistd.h... (cached) yes
checking for db.h... (cached) yes
checking DB library to use... berkeley
checking if Berkeley DB handle is kept open in SASLDB... no
checking for dlopen in -ldl... (cached) yes
checking /dev/random to use... /dev/random
checking for nm... (cached) /usr/bin/nm -B
checking for underscore before symbols... (cached) no
checking for syslog... (cached) yes
checking for security/pam_appl.h... (cached) no
checking for pam/pam_appl.h... (cached) no
checking for pam_start... (cached) no
checking if I should include saslauthd... /var/state/saslauthd
checking to include Courier authdaemond support... /dev/null
checking if I should include pwcheck... no
checking if I should include the alwaystrue verifier... no
checking if we should enable sasl_checkapop... enabled
checking CRAM-MD5... enabled
checking for long... (cached) yes
checking size of long... (cached) 4
checking what directory libraries are found in... (cached) lib
checking for RSAPublicEncrypt in -lrsaref... (cached) no
checking for openssl/evp.h... (cached) yes
checking for EVP_DigestInit in -lcrypto... (cached) yes
checking for OpenSSL... yes
checking for des_cbc_encrypt in -lcrypto... (cached) no
checking for DES_cbc_encrypt in -lcrypto... (cached) yes
checking for openssl/des.h... (cached) yes
checking DIGEST-MD5... enabled
checking OTP... enabled
checking for opiechallenge in -lopie... (cached) no
checking for OPIE... no
checking SRP... disabled
checking KERBEROS_V4... disabled
checking for crypt... (cached) no
checking for crypt in -lcrypt... (cached) yes
checking for gssapi.h... (cached) no
checking for gssapi/gssapi.h... (cached) no
configure: WARNING: Disabling GSSAPI - no include files found
checking GSSAPI... disabled
checking PLAIN... enabled
checking ANONYMOUS... enabled
checking LOGIN... enabled
checking NTLM... disabled
checking PASSDSS... disabled
checking SQL... disabled
checking LDAPDB... enabled
checking ldap.h usability... yes
checking ldap.h presence... yes
checking for ldap.h... yes
checking lber.h usability... yes
checking lber.h presence... yes
checking for lber.h... yes
checking OpenLDAP api... yes
checking for ldap_initialize in -lldap... (cached) no
configure: error: Cannot enable LDAPDB plugin: Could not locate OpenLDAP


openldap ставился с перфиксом в /usr

/usr/include/

Код: Выделить всё

-rw-r--r-- 1 root root 63828 2009-07-16 03:03 /usr/include/ldap.h
-rw-r--r-- 1 root root  9538 2009-07-16 03:03 /usr/include/ldap_cdefs.h
-rw-r--r-- 1 root root  1890 2009-07-16 03:03 /usr/include/ldap_features.h
-rw-r--r-- 1 root root  9523 2009-07-16 03:03 /usr/include/ldap_schema.h
-rw-r--r-- 1 root root  3539 2009-07-16 03:03 /usr/include/ldap_utf8.h
-rw-r--r-- 1 root root 14523 2009-07-16 03:03 /usr/include/lber.h
-rw-r--r-- 1 root root  1541 2009-07-16 03:03 /usr/include/lber_types.h
-rw-r--r-- 1 root root 38321 2009-07-16 03:03 /usr/include/slapi-plugin.h


/usr/lib/

Код: Выделить всё

lrwxrwxrwx 1 root root      20 2009-07-16 03:06 /usr/lib/libldap-2.4.so.2 -> libldap-2.4.so.2.4.2
-rw-r--r-- 1 root root  897079 2009-07-16 03:03 /usr/lib/libldap-2.4.so.2.4.2
-rw-r--r-- 1 root root 1358048 2009-07-16 03:03 /usr/lib/libldap.a
-rw-r--r-- 1 root root     897 2009-07-16 03:03 /usr/lib/libldap.la
lrwxrwxrwx 1 root root      20 2009-07-16 03:06 /usr/lib/libldap.so -> libldap-2.4.so.2.4.2
lrwxrwxrwx 1 root root      22 2009-07-16 03:06 /usr/lib/libldap_r-2.4.so.2 -> libldap_r-2.4.so.2.4.2
-rw-r--r-- 1 root root  989502 2009-07-16 03:03 /usr/lib/libldap_r-2.4.so.2.4.2
-rw-r--r-- 1 root root 1509386 2009-07-16 03:03 /usr/lib/libldap_r.a
-rw-r--r-- 1 root root     920 2009-07-16 03:03 /usr/lib/libldap_r.la
lrwxrwxrwx 1 root root      22 2009-07-16 03:06 /usr/lib/libldap_r.so -> libldap_r-2.4.so.2.4.2
lrwxrwxrwx 1 root root     20 2009-07-16 03:06 /usr/lib/liblber-2.4.so.2 -> liblber-2.4.so.2.4.2
-rw-r--r-- 1 root root 144817 2009-07-16 03:03 /usr/lib/liblber-2.4.so.2.4.2
-rw-r--r-- 1 root root 188720 2009-07-16 03:03 /usr/lib/liblber.a
-rw-r--r-- 1 root root    822 2009-07-16 03:03 /usr/lib/liblber.la
lrwxrwxrwx 1 root root     20 2009-07-16 03:06 /usr/lib/liblber.so -> liblber-2.4.so.2.4.2


в документации к SASL пишут о "круговой" зависимости

If you are using LDAPDB auxprop plugin, you will need to specify --enable-ldapdb and --with-ldap=PATH. Warning: LDAPDB
auxprop plugin (and LDAP enabled saslauthd) introduces a circular dependency between OpenLDAP and SASL. I.e., you must have OpenLDAP already built when building LDAPDB in SASL. In order for LDAPDB to work at runtime, you must have
OpenLDAP already built with SASL support. One way to solve this issue is to build Cyrus SASL first without ldap support, then build OpenLDAP, and then come back to SASL and build LDAPDB.

сделал как указано выше - сначала собрал SASL без ldap, далее собираю ldap и после вновь пытаюсь собрать Cyrus-sasl c поддержкой ldap и вновь получаю

Код: Выделить всё

configure: error: Cannot enable LDAPDB plugin: Could not locate OpenLDAP


Гугл как то с моими запросами ничего подходящего не даёт
перечитал даже японские и китайские форумы
Спасибо сказали:
Аватара пользователя
strah
Сообщения: 283
ОС: Freebsd, linux, Solaris.

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение strah »

--with-ldap=PATH

А у тебя:
--with-ldap

Попробуй собрать так:

Код: Выделить всё

--with-ldap=/usr
/earth: file system full
Спасибо сказали:
Аватара пользователя
krz
Сообщения: 50

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение krz »

моя проблема решилась отдельной пере сборкой saslauthd
Спасибо сказали:
pudeev
Сообщения: 22

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение pudeev »

Делал все по этой статье
И вот что в итоге.....

[root@Main ldap]# /etc/init.d/ldap start
Проверяются конфигурационные файлы для slapd: bdb_db_open: alock package is unstable
backend_startup_one: bi_db_open failed! (-1)
slap_startup failed (test would succeed using the -u switch)
[ СБОЙ ]
У меня СentOS 5.3.
Спасибо сказали:
Аватара пользователя
strah
Сообщения: 283
ОС: Freebsd, linux, Solaris.

Re: Postfix+cyrus-saslauthd+dovecot+openldap

Сообщение strah »

pudeev писал(а):
25.08.2009 16:47
Делал все по этой статье
И вот что в итоге.....

[root@Main ldap]# /etc/init.d/ldap start
Проверяются конфигурационные файлы для slapd: bdb_db_open: alock package is unstable
backend_startup_one: bi_db_open failed! (-1)
slap_startup failed (test would succeed using the -u switch)
[ СБОЙ ]
У меня СentOS 5.3.

Попробуй запустить openldap следующим образом:

Код: Выделить всё

#slapd -d 69

Просто, из за сообщения "bdb_db_open: alock package is unstable" у меня такое чувство, что у тебя какие-то несовместимости либ.

P.S
Ты openldap из исходников собирал? Или из пакетов ставил?
/earth: file system full
Спасибо сказали: