Евгений Верещагин, 17 июня 2011 года. Оригинал статьи и обсуждение по адресу http://manualpages.pro/node/24.
Обсуждение статьи на форуме проекта Pro-LDAP.ru.
Перво-наперво приводим в порядок конфигурационные файлы host'ов:
# cat /etc/hostname openldap
# cat /etc/hosts 127.0.0.1 localhost 10.0.0.42 openldap.ldap openldap # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters
Итак, у меня домен будет называться ldap
, хост с сервером - openldap.ldap
. Забегая вперёд, домен Samba будет называться LDAP
. Эти настройки будут схвачены сервером OpenLDAP прямо при установке, что довольно подло.
# aptitude install libpam-ldapd libnss-ldapd samba smbclient smbfs smbldap-tools slapd mcrypt ldap-utils libgd-tools samba-doc
Вот тут надо быть внимательным:
slapd
запросит только пароль для админа. Имя административной записи - admin
libnss-ldap
и libpam-ldap
надо ставить и настраивать новые libnss-ldapd
и libpam-ldapd
, которые при установке спросят, что и как подменить в nsswitch.conf
(ставим все галочки)Признаюсь сразу: победить /etc/slap.d
я не смог. Поэтому делаем по-старинке, в файле /etc/ldap/slapd.conf
. Предварительно перемещаем куда-нибудь директорию slap.d
:
# service slapd stop # mv /etc/ldap/slap.d /root/
Потом создаём файл конфигурации /etc/ldap/slapd.conf
примерно вот такого содержания:
# Global Directives: # Features to permit #allow bind_v2 include /etc/ldap/schema/core.schema include /etc/ldap/schema/collective.schema include /etc/ldap/schema/corba.schema include /etc/ldap/schema/cosine.schema include /etc/ldap/schema/duaconf.schema include /etc/ldap/schema/dyngroup.schema include /etc/ldap/schema/inetorgperson.schema include /etc/ldap/schema/java.schema include /etc/ldap/schema/misc.schema include /etc/ldap/schema/nis.schema include /etc/ldap/schema/openldap.schema include /etc/ldap/schema/ppolicy.schema include /etc/ldap/schema/samba.schema # Where the pid file is put. The init.d script # will not stop the server if you change this. pidfile /var/run/slapd/slapd.pid # List of arguments that were passed to the server argsfile /var/run/slapd/slapd.args # Read slapd.conf(5) for possible values loglevel none # Where the dynamically loaded modules are stored modulepath /usr/lib/ldap moduleload back_hdb # The maximum number of entries that is returned for a search operation sizelimit 500 # The tool-threads parameter sets the actual amount of cpu's that is used # for indexing. tool-threads 1 ####################################################################### # Specific Backend Directives for hdb: # Backend specific directives apply to this backend until another # 'backend' directive occurs backend hdb ####################################################################### # Specific Backend Directives for 'other': # Backend specific directives apply to this backend until another # 'backend' directive occurs #backend <other> ####################################################################### # Specific Directives for database #1, of type hdb: # Database specific directives apply to this databasse until another # 'database' directive occurs database hdb # The base of your directory in database #1 suffix "dc=ldap" # rootdn directive for specifying a superuser on the database. This is needed # for syncrepl. rootdn "cn=admin,dc=ldap" rootpw {MD5}X03MO1qnZdYdgyfeuILPmQ== # Where the database file are physically stored for database #1 directory "/var/lib/ldap" # The dbconfig settings are used to generate a DB_CONFIG file the first # time slapd starts. They do NOT override existing an existing DB_CONFIG # file. You should therefore change these settings in DB_CONFIG directly # or remove DB_CONFIG and restart slapd for changes to take effect. # For the Debian package we use 2MB as default but be sure to update this # value if you have plenty of RAM dbconfig set_cachesize 0 2097152 0 # Sven Hartge reported that he had to set this value incredibly high # to get slapd running at all. See http://bugs.debian.org/303057 for more # information. # Number of objects that can be locked at the same time. dbconfig set_lk_max_objects 1500 # Number of locks (both requested and granted) dbconfig set_lk_max_locks 1500 # Number of lockers dbconfig set_lk_max_lockers 1500 # Indices to maintain for this database index objectClass eq,pres index ou,cn,sn,mail,givenname eq,pres,sub index uidNumber,gidNumber,memberUid eq,pres index loginShell eq,pres ## required to support pdb_getsampwnam index uid pres,sub,eq ## required to support pdb_getsambapwrid() index displayName pres,sub,eq index nisMapName,nisMapEntry eq,pres,sub index sambaSID eq index sambaPrimaryGroupSID eq index sambaDomainName eq index default sub index uniqueMember eq index sambaGroupType eq index sambaSIDList eq # Save the time that the entry gets modified, for database #1 lastmod on # Checkpoint the BerkeleyDB database periodically in case of system # failure and to speed slapd shutdown. checkpoint 512 30 # Where to store the replica logs for database #1 # replogfile /var/lib/ldap/replog # users can authenticate and change their password access to attrs=userPassword,sambaNTPassword,sambaLMPassword,sambaPwdMustChange,sambaPwdLastSet by self write by anonymous auth by * none # those 2 parameters must be world readable for password aging to work correctly # (or use a priviledge account in /etc/ldap.conf to bind to the directory) access to attrs=shadowLastChange,shadowMax by self write by * read # all others attributes are readable to everybody access to * by * read # For Netscape Roaming support, each user gets a roaming # profile for which they have write access to #access to dn=".*,ou=Roaming,o=morsnet" # by dn="cn=admin,dc=example,dc=com" write # by dnattr=owner write ####################################################################### # Specific Directives for database #2, of type 'other' (can be hdb too): # Database specific directives apply to this databasse until another # 'database' directive occurs #database <other> # The base of your directory for database #2 #suffix "dc=debian,dc=org"
Фактически, от дефолтного конфига, какой он был в Debian Lenny отличает только указание суффиксов и инклуд всех доступных схем, в том числе Samba.
Внимание!!! Очень вероятно, что slapd
не запустится, так как он очень чувствителен к наличию лишних непечатаемых символов в конфиге. Плюс ко всему, перед строками типа access to attrs=shadowLastChange,shadowMax
должны стоять табуляции (без них будет только ругань и падение). В общем, на всякий случай, лучше взять конфиги из вложения.
Самой схемы samba
по-умолчанию нету, надо взять из примеров (не зря же samba-doc
ставили!):
# zcat /usr/share/doc/samba-doc/examples/LDAP/samba.schema.gz > /etc/ldap/schema/samba.schema
Для вставки хеша пароля используем команду (у меня вставлен хеш от слова password
):
# slappasswd -h {MD5}
Подложили конфиг, можно пробовать стартовать slapd:
# slapindex # chown -R openldap:openldap /var/lib/ldap # service slapd start
Запустилось - хорошо. Не запустилось - читаем syslog до полного просветления. Я вот 2 суток читал, вылавливая ошибки.
Тут всё просто, конфиг проверенный, если что-то хочется - дописываем по вкусу в /etc/samba/smb.conf
:
dos charset = CP1251
unix charset = UTF8
display charset = UTF8 workgroup = LDAP realm = OpenLDAP server string = %h server #interfaces = eth0:1 ## Необходимо поправить на свой интерфейс, или вообще убрать #bind interfaces only = Yes ## Убрать, если нет определенного интерфейса на самбу map to guest = Bad User passdb backend = ldapsam:ldap://127.0.0.1/ pam password change = Yes passwd program = /usr/sbin/smbldap-passwd -u %u passwd chat = *New*password* %n\n *Retype*new*password* %n\n *all*authentication*tokens*updated* syslog = 0 time server = Yes log file = /var/log/samba/log.%m max log size = 1000 socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192 add user script = /usr/sbin/smbldap-useradd -m %u -d /domain/home/%u %u delete user script = /usr/sbin/smbldap-userdel %u -r %u add group script = /usr/sbin/smbldap-groupadd -p %g delete group script = /usr/sbin/smbldap-groupdel %g add user to group script = /usr/sbin/smbldap-groupmod -m %u %g delete user from group script = /usr/sbin/smbldap-groupmod -x %u %g set primary group script = /usr/sbin/smbldap-usermod -g %g %u add machine script = /usr/sbin/smbldap-useradd -w %u #logon script = logon.bat ##logon path = \\%N\profiles\%U ## Раскомментировать, если нужны переносимые профили domain logons = Yes os level = 10 preferred master = Yes domain master = Yes dns proxy = No wins support = Yes ldap admin dn = cn=admin,dc=ldap ldap delete dn = Yes ldap group suffix = ou=group ldap idmap suffix = ou=idmap ldap machine suffix = ou=computer ldap suffix = dc=ldap ldap ssl = no ldap user suffix = ou=people panic action = /usr/share/samba/panic-action %d map acl inherit = Yes case sensitive = No hide unreadable = Yes map hidden = Yes map system = Yes ldap passwd sync = yes [homes] comment = Home Directories path = /domain/home/%u valid users = %S read only = No create mask = 0600 directory mask = 0700 browseable = No [netlogon] path = /domain/netlogon browseable = No #[profiles] ## Раскомментировать, если нужны переносимые профили #path = /domain/profiles #force user = %U #read only = No #create mask = 0600 #directory mask = 0700 #guest ok = Yes #profile acls = Yes #browseable = No #csc policy = disable
Собственно, конфиг нам говорит о том, что надо работать через OpenLDAP и создавать для виндовых машин домен с именем LDAP.
Ну и пара маленьких штришков. Задаём пароль в LDAP для Samba:
# smbpasswd -w password
Создаём нужные директории:
# mkdir -p /domain/netlogon /domain/profiles # chown -Rf root:root /domain/netlogon /domain/profiles /domain/home # chmod 1777 /domain/profiles
и рестартуем Samba:
# service samba restart
Для проверки хорошо бы воспользоваться testparm
, если ругается на мелочи, типа прав на файлы, то можно пока забить и работать дальше.
Нынче настройки минимальны (ведь при установке libnss-ldapd
всё правильно ввели, да?)
Смотрим в /etc/ldap/ldap.conf
(это настройка клиента LDAP):
host 127.0.0.1 base dc=ldap binddn cn=admin,dc=ldap bindpw password bind_policy soft pam_password exop timelimit 15 nss_base_passwd dc=ldap?sub nss_base_shadow dc=ldap?sub nss_base_group ou=group,dc=ldap?one
Ну и самое важное - скрипты интеграции Samba и LDAP:
/etc/smbldap-tools/smbldap.conf:
############################################################################## # # General Configuration # ############################################################################## # Put your own SID. To obtain this number do: "net getlocalsid". # If not defined, parameter is taking from "net getlocalsid" return SID="S-1-5-21-3384730673-3036888877-1999087345" # Domain name the Samba server is in charged. # If not defined, parameter is taking from smb.conf configuration file # Ex: sambaDomain="IDEALX-NT" sambaDomain="LDAP" ############################################################################## # # LDAP Configuration # ############################################################################## # Notes: to use to dual ldap servers backend for Samba, you must patch # Samba with the dual-head patch from IDEALX. If not using this patch # just use the same server for slaveLDAP and masterLDAP. # Those two servers declarations can also be used when you have # . one master LDAP server where all writing operations must be done # . one slave LDAP server where all reading operations must be done # (typically a replication directory) # Slave LDAP server # Ex: slaveLDAP=127.0.0.1 # If not defined, parameter is set to "127.0.0.1" slaveLDAP="127.0.0.1" # Slave LDAP port # If not defined, parameter is set to "389" slavePort="389" # Master LDAP server: needed for write operations # Ex: masterLDAP=127.0.0.1 # If not defined, parameter is set to "127.0.0.1" masterLDAP="127.0.0.1" # Master LDAP port # If not defined, parameter is set to "389" #masterPort="389" masterPort="389" # Use TLS for LDAP # If set to 1, this option will use start_tls for connection # (you should also used the port 389) # If not defined, parameter is set to "0" ldapTLS="0" # Use SSL for LDAP # If set to 1, this option will use SSL for connection # (standard port for ldaps is 636) # If not defined, parameter is set to "0" ldapSSL="0" # How to verify the server's certificate (none, optional or require) # see "man Net::LDAP" in start_tls section for more details verify="require" # CA certificate # see "man Net::LDAP" in start_tls section for more details cafile="/etc/smbldap-tools/ca.pem" # certificate to use to connect to the ldap server # see "man Net::LDAP" in start_tls section for more details clientcert="/etc/smbldap-tools/smbldap-tools.pem" # key certificate to use to connect to the ldap server # see "man Net::LDAP" in start_tls section for more details clientkey="/etc/smbldap-tools/smbldap-tools.key" # LDAP Suffix # Ex: suffix=dc=IDEALX,dc=ORG suffix="dc=ldap" # Where are stored Users # Ex: usersdn="ou=Users,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for usersdn usersdn="ou=people,${suffix}" # Where are stored Computers # Ex: computersdn="ou=Computers,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for computersdn computersdn="ou=computer,${suffix}" # Where are stored Groups # Ex: groupsdn="ou=Groups,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for groupsdn groupsdn="ou=group,${suffix}" # Where are stored Idmap entries (used if samba is a domain member server) # Ex: groupsdn="ou=Idmap,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for idmapdn idmapdn="ou=idmap,${suffix}" # Where to store next uidNumber and gidNumber available for new users and groups # If not defined, entries are stored in sambaDomainName object. # Ex: sambaUnixIdPooldn="sambaDomainName=${sambaDomain},${suffix}" # Ex: sambaUnixIdPooldn="cn=NextFreeUnixId,${suffix}" sambaUnixIdPooldn="sambaDomainName=${sambaDomain},${suffix}" # Default scope Used scope="sub" # Unix password encryption (CRYPT, MD5, SMD5, SSHA, SHA, CLEARTEXT) hash_encrypt="MD5" # if hash_encrypt is set to CRYPT, you may set a salt format. # default is "%s", but many systems will generate MD5 hashed # passwords if you use "$1$%.8s". This parameter is optional! crypt_salt_format="%s" ############################################################################## # # Unix Accounts Configuration # ############################################################################## # Login defs # Default Login Shell # Ex: userLoginShell="/bin/bash" userLoginShell="/bin/bash" # Home directory # Ex: userHome="/home/%U" userHome="/domain/home/%U" # Default mode used for user homeDirectory userHomeDirectoryMode="700" # Gecos userGecos="System User" # Default User (POSIX and Samba) GID defaultUserGid="513" # Default Computer (Samba) GID defaultComputerGid="515" # Skel dir skeletonDir="/etc/skel" # Default password validation time (time in days) Comment the next line if # you don't want password to be enable for defaultMaxPasswordAge days (be # careful to the sambaPwdMustChange attribute's value) defaultMaxPasswordAge="365" ############################################################################## # # SAMBA Configuration # ############################################################################## # The UNC path to home drives location (%U username substitution) # Just set it to a null string if you want to use the smb.conf 'logon home' # directive and/or disable roaming profiles # Ex: userSmbHome="\\PDC-SMB3\%U" userSmbHome="\\%L\%U" # The UNC path to profiles locations (%U username substitution) # Just set it to a null string if you want to use the smb.conf 'logon path' # directive and/or disable roaming profiles # Ex: userProfile="\\PDC-SMB3\profiles\%U" #userProfile="\\%L\profiles\%U" userProfile="" # The default Home Drive Letter mapping # (will be automatically mapped at logon time if home directory exist) # Ex: userHomeDrive="H:" userHomeDrive="U:" # The default user netlogon script name (%U username substitution) # if not used, will be automatically username.cmd # make sure script file is edited under dos # Ex: userScript="startup.cmd" # make sure script file is edited under dos #userScript="logon.bat" userScript="" # Domain appended to the users "mail"-attribute # when smbldap-useradd -M is used # Ex: mailDomain="idealx.com" mailDomain="ldap" ############################################################################## # # SMBLDAP-TOOLS Configuration (default are ok for a RedHat) И для Debian Squeeze, хе-хе # ############################################################################## # Allows not to use smbpasswd (if with_smbpasswd == 0 in smbldap_conf.pm) but # prefer Crypt::SmbHash library with_smbpasswd="0" smbpasswd="/usr/bin/smbpasswd" # Allows not to use slappasswd (if with_slappasswd == 0 in smbldap_conf.pm) # but prefer Crypt:: libraries with_slappasswd="0" slappasswd="/usr/sbin/slappasswd" # comment out the following line to get rid of the default banner # no_banner="1"
Узнать SID домена можно командой:
# net getlocalsid
Второй файлик для издевательств /etc/smbldap-tools/smbldap_bind.conf
:
############################ # Credential Configuration # ############################ # Notes: you can specify two differents configuration if you use a # master ldap for writing access and a slave ldap server for reading access # By default, we will use the same DN (so it will work for standard Samba # release) slaveDN="cn=admin,dc=ldap" slavePw="password" masterDN="cn=admin,dc=ldap" masterPw="password"Если уверены в своих силах, то можно самостоятельно понастраивать дефолтные файлы конфигурации, добыть их можно так:
# cp /usr/share/doc/smbldap-tools/examples/smbldap_bind.conf /etc/smbldap-tools/smbldap_bind.conf # zcat /usr/share/doc/smbldap-tools/examples/smbldap.conf.gz > /etc/smbldap-tools/smbldap.conf
Но в любом случае, не забываем поменять права:
# chmod 0644 /etc/smbldap-tools/smbldap.conf # chmod 0600 /etc/smbldap-tools/smbldap_bind.conf
Ну и в итоге, делаем так:
# smbldap-populate
Собственно, всё. Остаётся проверить, правильно ли. Я, на всякий случай, сделал reboot, мало ли.
Для проверки заведём пользователя testuser:
# smbldap-useradd -a -m testuser # smbldap-passwd testuser
Залогинимся пользователем:
# su - testuser
Проверим, подхватила ли система смену в nsswitch.conf
:
# getent passwd # getent group
По-идее, должно запуститься. В противном случае - курить логи, до полного просветления.
Их много, всяких. Я ещё не выбрал. Вот попробовал написанную на Java программку jxplorer
. Есть в репозитарии. Страдает тем, что постояв некоторое время включённой требует перезапуска, так как теряет соединение и не может заново установить. Подключение элементарное:
Выглядит настроенное очень любопытно, вот такое дерево получилось:
Без плясок с отключением безопасности Windows 7 в домене NT не работает, в отличии от WinXP, кстати. Создаём reg-файл с таким вот содержимым и запускаем от имени администратора:
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanManWorkstation\Parameters] "DNSNameResolutionRequired"=dword:00000000 "DomainCompatibilityMode"=dword:00000001 [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\System\DNSClient] "NV PrimaryDnsSuffix"="domen" [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters] "NV Domain"="domen"
Ессно, что domen поменять надо на свой domain-name Самбы. Всё, после этого заработает.
[Лирика] Помню, когда обслуживал Samba 2х, вроде, так там надо было ещё и машину вручную в домен загнать, и половину настроек безопасности в WinXP поотключать. Дааа, было время.. [/Лирика]
При написании этой статьи использовались материалы:
Во вложении все мои конфиг-файлы и схемы ещё добавил.
Вложения: Конфигурации и схемы.
Обсуждение статьи на форуме проекта Pro-LDAP.ru.