Предпосылки
До Samba v 4.6.0:
ad бэкэнд поддерживает два режима параметра winbind nss info в разделе файла smb.conf:
-
winbind nss info = rfc2307: из Active Directory (AD) считывается вся информация:
- Пользователи: Имя пользователя, UID, login shell, путь домашнего каталога и основная группа.
- Группы: Имя групп и их GID.
-
winbind nss info = template: из Active Directory (AD) считываются только следующие значения:
- Пользователи: Имя пользователя, UID и основная группа.Login shell и домашний каталог автоматически настраиваются из независимых от пользователя настроек из файла smb.conf.
- Группы: Имя групп и их GID.
security = ADS workgroup = SAMDOM realm = SAMDOM.EXAMPLE.COM log file = /var/log/samba/%m.log log level = 1 winbind nss info = rfc2307 idmap config * : backend = tdb idmap config * : range = 3000-7999 idmap config SAMDOM:backend = ad idmap config SAMDOM:schema_mode = rfc2307 idmap config SAMDOM:range = 10000-999999 vfs objects = acl_xattr map acl inherit = yes store dos attributes = yes
После Samba v 4.6.0:
Параметры:
range = low — high
schema_mode = — Определяет доступные совпадающие диапазоны UID и GID, для которых серверная часть является доверенной
Обратите внимание, что диапазон действует как фильтр. Если указан любой UID или GID, хранящийся в AD, который выходит за пределы диапазона, то он игнорируется, а соответствующая карта отбрасывается
Он предназначен для того, чтобы избежать случайных совпадений UID / GID между локальными и удаленно определенными идентификаторами.
unix_primary_group = yes/no — Определяет, выбирается ли основная группа пользователя из атрибутов SFU или основной группы AD. Если установлено значение yes, членство в основной группе выбирается из атрибутов LDAP (gidNumber). Если установлено значение no, членство в первичной группе рассчитывается с помощью атрибута LDAP «primaryGroupID».
По умолчанию: no
unix_nss_info = yes/no — Если установлено значение yes, winbind будет извлекать оболочку входа и домашний каталог из атрибутов LDAP. Если задано значение no или в записи AD LDAP отсутствуют атрибуты SFU, используются параметры шаблона оболочки и шаблон homedir.
security = ADS workgroup = SAMDOM realm = SAMDOM.EXAMPLE.COM log file = /var/log/samba/%m.log log level = 1 idmap config * : backend = tdb idmap config * : range = 3000-7999 idmap config SAMDOM:backend = ad idmap config SAMDOM:schema_mode = rfc2307 idmap config SAMDOM:range = 10000-999999 idmap config SAMDOM:unix_nss_info = yes vfs objects = acl_xattr map acl inherit = yes store dos attributes = yes
Сохраните файл и перезагрузите настройки Samba:
# smbcontrol all reload-config
USERSHARES
Starting with Samba version 3.0.23 the capability for non-root users to add, modify, and delete
their own share definitions has been added. This capability is called usershares and
is controlled by a set of parameters in the section of the smb.conf.
The relevant parameters are :
- usershare allow guests
-
Controls if usershares can permit guest access.
- usershare max shares
-
Maximum number of user defined shares allowed.
- usershare owner only
-
If set only directories owned by the sharing user can be shared.
- usershare path
-
Points to the directory containing the user defined share definitions.
The filesystem permissions on this directory control who can create user defined shares. - usershare prefix allow list
-
Comma-separated list of absolute pathnames restricting what directories
can be shared. Only directories below the pathnames in this list are permitted. - usershare prefix deny list
-
Comma-separated list of absolute pathnames restricting what directories
can be shared. Directories below the pathnames in this list are prohibited. - usershare template share
-
Names a pre-existing share used as a template for creating new usershares.
All other share parameters not specified in the user defined share definition
are copied from this named share.
To allow members of the UNIX group to create user defined
shares, create the directory to contain the share definitions as follows:
Become root:
mkdir /usr/local/samba/lib/usershares chgrp foo /usr/local/samba/lib/usershares chmod 1770 /usr/local/samba/lib/usershares
Then add the parameters
# (or the desired number of shares)
to the global
section of your . Members of the group foo may then manipulate the user defined shares
using the following commands.
Testing
You can check that the Domain has successfully been joined by:
wbinfo -u
You should get a list of the users of the domain.
I needed to make shadow: compat winbind in /etc/nsswitch.conf to make wbinfo -u work.
And a list of the groups. Be patient these queries can take time.
wbinfo -g
Check Winbind nsswitch module with getent.
This step may or may not work. If you only see local users, try connecting with a Windows machine anyways. (Tested under Ubuntu 9.10 x64)
sudo getent passwd root:x:0:0:root:/root:/bin/bash ... LAB+administrator:x:10000:10000:Administrator:/home/LAB/administrator:/bin/bash LAB+gast:x:10001:10001:Gast:/home/LAB/gast:/bin/bash ...
Note that the domain name (here, «LAB+») is displayed by getent only if you have not set winbind use default domain = yes in smb.conf.
sudo getent group root:x:0: daemon:x:1: bin:x:2: ... LAB+organisations-admins:x:10005:administrator LAB+domänen-admins:x:10006:manuel,administrator LAB+domänen-benutzer:x:10000: LAB+domänen-gäste:x:10001: LAB+linux-admins:x:10004:manuel ...
EXAMPLES
The following example shows how an ldap directory is used as the default idmap backend. It also configures the idmap range and base directory suffix. The secret for the ldap_user_dn has to be set with «net idmap secret ‘*’ password».
-
idmap config * : backend = ldap idmap config * : range = 1000000-1999999 idmap config * : ldap_url = ldap://localhost/ idmap config * : ldap_base_dn = ou=idmap,dc=example,dc=com idmap config * : ldap_user_dn = cn=idmap_admin,dc=example,dc=com
This example shows how ldap can be used as a readonly backend while tdb is the default backend used to store the mappings. It adds an explicit configuration for some domain DOM1, that uses the ldap idmap backend. Note that a range disjoint from the default range is used.
-
# "backend = tdb" is redundant here since it is the default idmap config * : backend = tdb idmap config * : range = 1000000-1999999 idmap config DOM1 : backend = ldap idmap config DOM1 : range = 2000000-2999999 idmap config DOM1 : read only = yes idmap config DOM1 : ldap_url = ldap://server/ idmap config DOM1 : ldap_base_dn = ou=idmap,dc=dom1,dc=example,dc=com idmap config DOM1 : ldap_user_dn = cn=idmap_admin,dc=dom1,dc=example,dc=com
Преимущества и недостатки бэк-энда ad
Преимущества:
- Центральное администрирование идентификаторов внутри Active Directory (AD).
- Согласованные идентификаторы на всех клиентах и серверах Samba, использующих серверную часть ad.
- Требуемые атрибуты нужно создавать только один раз, это можно сделать при создании пользователя или группы.
- Идентификаторы кэшируются только локально, они хранятся в базе данных AD на контроллерах домена. Это означает, что в случае повреждения локального кэша владение файлами не теряется.
Недостатки:
- Если программа Windows Active Directory Users and Computers(ADUC) не используется, необходимо вручную отслеживать значения идентификаторов, чтобы избежать дублирования.
- Значения атрибутов RFC2307 не создаются автоматически, их необходимо добавлять вручную.
Особенности режима информации Winbind NSS:
- rfc2307: Индивидуальные логины и пути к домашним каталогам для пользователей.
- template: Оболочки входа и базовые пути к домашним каталогам одинаковы для всех пользователей.
DESCRIPTION
The idmap_ad plugin provides a way for Winbind to read id mappings from an AD server that uses RFC2307/SFU schema extensions. This module implements only the «idmap» API, and is READONLY. Mappings must be provided in advance by the administrator by adding the uidNumber attributes for users and gidNumber attributes for groups in the AD. Winbind will only map users that have a uidNumber and whose primary group have a gidNumber attribute set. It is however recommended that all groups in use have gidNumber attributes assigned, otherwise they are not working.
Currently, the
ad
backend does not work as the default idmap backend, but one has to configure it separately for each domain for which one wants to use it, using disjoint ranges. One usually needs to configure a writeable default idmap range, using for example the
tdb
or
ldap
backend, in order to be able to map the BUILTIN sids and possibly other trusted domains. The writeable default config is also needed in order to be able to create group mappings. This catch-all default idmap configuration should have a range that is disjoint from any explicitly configured domain with idmap backend
ad. See the example below.
Performing manual LDAP query¶
It is often useful to run the same query as SSSD manually with
tool. Look for function named
to aquire the search base and filter
that SSSD used against an LDAP server and to
see what server did it connect to. The messages are in form of:
(0x2000): Searching $ip:$port (0x0400): calling ldap_search_ext with
Anonymous bind (no authentication)
ldapsearch -x -H ldap://$ip:$port -b $search-base '$filter'
Simple bind (authentication with credentials)
ldapsearch -x -D "cn=Directory Manager" -w "$password" -H ldap://$ip:$port -b $search-base '$filter'
GSSAPI (authentication through Kerberos)
One last thing
If you want to be able to use an active directory account to manage your Ubuntu box, you need to add it to the sudoers file. For that, you will need to edit the file /etc/group an add your username to the admin group and whatever other group you need(plugdev,audio,cdrom just to mention a few). it will be like:
....... admin:x:117:olduser,ActiveDirectoryUser .......
Where, olduser, is your current linux user and, ActiveDirectoryUser, is the new administrator. Another way to make a Domain Group a sudoer in your ubuntu is to edit the file /etc/sudoers (using the command ‘visudo’) and add the following line
%adgroup ALL=(ALL) ALL
Where, adgroup, is a group from your active directory. Keep in mind that spaces in the group name are not allowed. You can use ‘%domain\ admins’, without quotes.
Samba Domain Members
ID Mapping Configuration Verification
4.6.0 or later
Previously, Samba did not verified the ID mapping configuration in the file on a domain member. Thus, an incorrect ID mapping configuration could be set, such as overlapping ID ranges or incorrect back ends for the default domain. Consequently, the service started and ID mapping failed or did not work as expected. The utility has been enhanced and now reports incorrect ID mapping configurations. For example:
ERROR: The idmap range for the domain * (tdb) overlaps with the range of SAMDOM (ad)!
ERROR: Do not use the 'ad' backend as the default idmap backend!
Additionally, when using an incorrect ID mapping configuration, the service now fails to start and an error message is logged. For example:
[2017/03/01 12:00:00.000000, 0, pid=980] ../source3/winbindd/winbindd.c:1705(main) main: FATAL: Invalid idmap backend ad configured as the default backend!
Using Samba 4.6.0 and later, users are no longer able to use incorrect ID mapping configurations.
For further details, supported back ends on a domain member, and their configuration, see:
- Identity Mapping Back Ends
- the section in the man page
The ID Mapping Back End Now Supports Enabling RFC2307 or Template Mode Per-domain
4.6.0 or later
Previously, when the parameter was set to , the Samba ID mapping back end retrieved shell and home directory settings for all Active Directory (AD) domains from AD. In Samba 4.6.0, the new parameter has been added. This parameter enables the administrator to set on a per-AD domain basis if the shell and home directory settings of users should be retrieved from AD or if the template settings, set in the and parameters are applied.
The new parameter has a higher priority than the global setting. Therefore, using the default setting for an AD domain, the shell and home directory are no longer retrieved from AD and the values set in the and parameters are applied. To re-enable retrieving the values from AD for a domain, set in the section in your file:
idmap config domain_name:unix_nss_info = yes
REGISTRY-BASED CONFIGURATION
Starting with Samba version 3.2.0, the capability to
store Samba configuration in the registry is available.
The configuration is stored in the registry key
.
There are two levels of registry configuration:
-
Share definitions stored in registry are used.
This is triggered by setting the global
parameter
to “yes” in smb.conf.The registry shares are loaded not at startup but
on demand at runtime by smbd.
Shares defined in smb.conf take
priority over shares of the same name defined in
registry. -
Global smb.conf
options stored in registry are used. This can be activated
in two different ways:Firstly, a registry only configuration is triggered
by settingin the section of smb.conf.
This resets everything that has been read from config files
to this point and reads the content of the global configuration
section from the registry.
This is the recommended method of using registry based
configuration.Secondly, a mixed configuration can be activated
by a special new meaning of the parameterin the section of smb.conf.
This reads the global options from registry with the same
priorities as for an include of a text file.
This may be especially useful in cases where an initial
configuration is needed to access the registry.Activation of global registry options automatically
activates registry shares. So in the registry only case,
shares are loaded on demand only.
Note: To make registry-based configurations foolproof
at least to a certain extent, the use
of and
inside the registry configuration has been disabled:
Especially by changing the
inside the registry
configuration, one would create a broken setup where the daemons
do not see the configuration they loaded once it is active.
SECTION DESCRIPTIONS
Each section in the configuration file (except for the section) describes a shared resource (known as
a “share”). The section name is the name of the shared resource and the parameters within the
section define the shares attributes.
There are three special sections, , and , which are described under
special sections. The following notes apply to ordinary section descriptions.
A share consists of a directory to which access is being given plus a description of the access rights
which are granted to the user of the service. Some housekeeping options are also specifiable.
Sections are either file share services (used by the client as an extension of their native file systems)
or printable services (used by the client to access print services on the host running the server).
Sections may be designated guest services, in which case no password is required to
access them. A specified UNIX guest account is used to define access privileges in this
case.
Sections other than guest services will require a password to access them. The client provides the
username. As older clients only provide passwords and not usernames, you may specify a list of usernames to
check against the password using the option in the share definition. For modern clients
such as Windows 95/98/ME/NT/2000, this should not be necessary.
The access rights granted by the server are masked by the access rights granted to the specified or guest
UNIX user by the host system. The server does not grant more access than the host system grants.
The following sample section defines a file space share. The user has write access to the path . The share is accessed via the share name :
The following sample section defines a printable share. The share is read-only, but printable. That is,
the only write access permitted is via calls to open, write to and close a spool file. The guest
ok parameter means access will be permitted as the default guest user (specified elsewhere):
VARIABLE SUBSTITUTIONS
Many of the strings that are settable in the config file can take substitutions. For example the option
“path = /tmp/%u” is interpreted as “path = /tmp/john” if the user connected with the
username john.
These substitutions are mostly noted in the descriptions below, but there are some general substitutions
which apply whenever they might be relevant. These are:
- %U
-
session username (the username that the client wanted, not
necessarily the same as the one they got). - %G
-
primary group name of %U.
- %h
-
the Internet hostname that Samba is running on.
- %m
-
the NetBIOS name of the client machine (very useful).
This parameter is not available when Samba listens on port 445, as clients no longer
send this information. If you use this macro in an include statement on a domain that has
a Samba domain controller be sure to set in the section . This will cause Samba to not listen on port 445 and will permit include
functionality to function as it did with Samba 2.x. - %L
-
the NetBIOS name of the server. This allows you to change your config based on what
the client calls you. Your server can have a “dual personality”. - %M
-
the Internet name of the client machine.
- %R
-
the selected protocol level after protocol negotiation. It can be one of
CORE, COREPLUS, LANMAN1, LANMAN2, NT1,
SMB2_02, SMB2_10, SMB2_22, SMB2_24,
SMB3_00, SMB3_02, SMB3_10, SMB3_11
or SMB2_FF. - %d
-
the process id of the current server
process. - %a
-
The architecture of the remote
machine. It currently recognizes Samba (),
the Linux CIFS file system (), OS/2, (),
Mac OS X (), Windows for Workgroups (), Windows 9x/ME
(), Windows NT (),
Windows 2000 (),
Windows XP (),
Windows XP 64-bit(),
Windows 2003 including
2003R2 (), and Windows
Vista (). Anything else will be known as
. - %I
-
the IP address of the client machine.
Before 4.0.0 it could contain IPv4 mapped IPv6 addresses,
now it only contains IPv4 or IPv6 addresses. - %J
-
the IP address of the client machine,
colons/dots replaced by underscores. - %i
-
the local IP address to which a client connected.
Before 4.0.0 it could contain IPv4 mapped IPv6 addresses,
now it only contains IPv4 or IPv6 addresses. - %j
-
the local IP address to which a client connected,
colons/dots replaced by underscores. - %T
-
the current date and time.
- %t
-
the current date and time in a minimal format without colons (YYYYYmmdd_HHMMSS).
- %D
-
name of the domain or workgroup of the current user.
- %w
-
the winbind separator.
- %$()
-
the value of the environment variable
.
The following substitutes apply only to some configuration options (only those that are
used when a connection has been established):
- %S
-
the name of the current service, if any.
- %P
-
the root directory of the current service, if any.
- %u
-
username of the current service, if any.
- %g
-
primary group name of %u.
- %H
-
the home directory of the user given by %u.
- %N
-
the name of your NIS home directory server. This is obtained from your NIS auto.map entry.
If you have not compiled Samba with the —with-automount option, this
value will be the same as %L. - %p
-
the path of the service’s home directory, obtained from your NIS auto.map entry. The NIS
auto.map entry is split up as .
Asking for help¶
If you did not have any luck with debugging the issue yourself you
can reach us through
sssd-users
mailing list or #sssd channel on
freenode.net IRC.
It would be great if you can also provide all the information that you
have found so far to speed things up. Such as:
- Description of the issue
- What do you expect that should happen
- What did you see in the logs
- All SSSD logs with debug level set to (please always
include whole log files, not only snippets) - Version of SSSD an what server do you use
- Other information depending on the area of investigation
- expected group membership
- domains relationships
- HBAC rules
- Other access control settings
- And everything that comes to your mind that you think may be
helpful
HOW CONFIGURATION CHANGES ARE APPLIED
The Samba suite includes a number of different programs. Some of them operate in a client mode, others are
server daemons that provide various services to its clients. The file is processed in the following way:
-
The Samba suite’s client applications read their configuration only once. Any changes made after start aren’t
reflected in the context of already running client code. -
The Samba suite’s server daemons reload their configuration when requested. However, already active connections
do not change their configuration. More detailed information can be found in
smbd(8) and winbindd(8) manual pages.
PARAMETERS
Parameters define the specific attributes of sections.
Some parameters are specific to the section (e.g., security). Some parameters
are usable in all sections (e.g., create mask). All others are permissible only in normal
sections. For the purposes of the following descriptions the and sections will be
considered normal. The letter G in parentheses indicates that a parameter is specific to
the section. The letter S indicates that a parameter can be specified in a
service specific section. All S parameters can also be specified in the section
— in which case they will define the default behavior for all services.
PAM
With this configuration you can access the workstation with local accounts or with domain accounts. On the first login of a domain user a home directory will be created. This PAM configuration assumes that the system will be used primarily with domain accounts. If the opposite is true (i.e., the system will be used primarily with local accounts), the order of pam_winbind.so and pam_unix.so should be reversed. When used with local accounts, the configuration shown here will result in a failed authentication to the Windows/Samba DC for each login and sudo use. This can litter the DC’s event log. Likewise, if local accounts are checked first, the /var/log/auth.log will be littered with failed logon attempts each time a domain account is accessed.
Note: You can use pam-auth-update to add the necessary entries for winbind authentication. If you installed libpam-winbind above, this step is all you need to do to configure pam. You may want to add the line to automatically create the home directory.
sudo pam-auth-update
This PAM configuration does not acquire a Kerberos TGT at login. To acquire a ticket, use kinit after logging in, and consider using kdestroy in a logout script.
file: /etc/pam.d/common-account
account sufficient pam_winbind.so account required pam_unix.so
file: /etc/pam.d/common-auth
auth sufficient pam_winbind.so auth sufficient pam_unix.so nullok_secure use_first_pass auth required pam_deny.so
On a Ubuntu 7.10 (Gutsy Gibbon) and 9.04 (Jaunty Jackalope) systems, these changes to pam.d/common-auth result in not being able to log in as a local user, for example by ssh. Your luck may be better, but test immediately just in case.
This one allows login for AD users and local users (tested with Ubuntu 9.10)
file: /etc/pam.d/common-auth
auth sufficient pam_unix.so nullok_secure auth sufficient pam_winbind.so require_membership_of=domänen-admins use_first_pass auth requisite pam_deny.so auth required pam_permit.so auth optional pam_ecryptfs.so unwrap
ecryptfs does not work with AD users. Login is successful with local users and AD users which are members of AD group domänen-admins
file: /etc/pam.d/common-session
session required pam_unix.so session required pam_mkhomedir.so umask=0022 skel=/etc/skel
file: /etc/pam.d/sudo
auth sufficient pam_winbind.so auth sufficient pam_unix.so use_first_pass auth required pam_deny.so @include common-account
Вывод лога доступа к файлам samba в отдельный файл
Нам нужно отредактировать файл конфигурации rsyslog для направления вывода лога самбы в отдельный файл. В CentOS 7 открываем файл /etc/rsyslog.conf и добавляем в самый конец такую строку:
# mcedit /etc/rsyslog.conf
local5.notice -/var/log/samba/audit.log
Этим параметром мы направили вывод логов аудита посещений в отдельный файл audit.log. Если все оставить как есть, то информация о посещениях будет писаться как в отдельный файл, так и в общий системный. Чтобы в общий не писалось, редактируем еще одну строку, добавляя туда выделенный фрагмент:
*.info;mail.none;authpriv.none;cron.none;local5.none /var/log/messages
Сохраняем файл и перезапускаем rsyslog.
# systemctl restart rsyslog
Теперь все нормально. Все логи посещений шары на samba будут складываться в отдельный файл и только туда. Если у вас есть желание хранить логи на удаленном сервере, то воспользуйтесь моей статье на эту тему — настройка syslog-ng для удаленного сбора логов. Это сделать быстро и просто. Зачастую это может быть оправданно и удобно, особенно с точки зрения безопасности и не только логов от самбы.
Осталось малось — настроить ротацию логов. Сделать это надо обязательно, так как файл аудита будет расти очень быстро. Здесь ничего особенного, используем logrotate. Скорее всего у вас уже есть фал конфигурации logrotate для самбы. Он создается в момент установки. Отредактируем его, добавив новые параметры.
# mcedit /etc/logrotate.d/samba
/var/log/samba/audit.log { daily notifempty olddir /var/log/samba/old missingok sharedscripts copytruncate rotate 90 compress }
Я храню логи за последние 90 дней, ротацию делаю раз в день и складываю старые логи в отдельную папку. Если у вас в конфигурации есть параметр с маской, который захватывает сразу все файлы в директории /var/log/samba, например вот так:
/var/log/samba/*
То либо вынесите лог-файл с аудитом в отдельную директорию, либо измените маску.
Заключение
Скажу откровенно — мне не нравится, как работают файловые сервера samba с интеграцией в виндовом домене. Но настраивать их приходится часто, так как востребованный функционал. Востребован в первую очередь потому, что не требует вообще никаких денег за лицензии, и работает на минимальной конфигурации железа. Вот список типичных проблем при работе самбы в домене:
- Иногда через windows acl права перестают выставляться, возникают неинформативные ошибки, по которым невозможно понять, что не так.
- Я достаточно регулярно наблюдаю ситуацию, когда слетают соответствия доменных учеток линуксовым UID. В итоге права доступа превращаются в ничего не значащий набор цифр и перестают работать.
- При переносе данных с одного сервера на другой трудно сохранить права доступа. Можно поступить вот так для копирования прав доступа, либо как-то заморочиться, чтобы на всех серверах у вас были одинаковые UID доменных учетных записей. Я не разбирал этот вопрос подробно.
Если у вас есть возможность настроить файловый сервер на windows, либо обойтись линуксом без домена, то сделайте так. Существенно упростите настройку и дальнейшую эксплуатацию. Данную статью еще можно дополнить некоторыми моментами, которые я рассказал ранее, а что не рассказал, постараюсь раскрыть позже и добавить сюда ссылки на статьи:
- Подробное логирование всех действий с файлами на сервере.
- Настройка корзины для сетевых дисков samba.
- Бэкап файлового сервера.
- Мониторинг за размером файловой шары.
Буду рад любым полезным замечаниям, исправлениям, советам по настройке файлового сервера samba. Я потратил значительное время, чтобы поделиться своими знаниями и опытом с остальными. Надеюсь, кто-то поделится чем-то полезным со мной. В том числе ради этого я и пишу статьи. Они расширяют мой кругозор и закрепляют полученные знания.
Онлайн курс «DevOps практики и инструменты»
Если у вас есть желание научиться строить и поддерживать высокодоступные и надежные системы, научиться непрерывной поставке ПО, мониторингу и логированию web приложений, рекомендую познакомиться с онлайн-курсом «DevOps практики и инструменты» в OTUS. Курс не для новичков, для поступления нужны базовые знания по сетям и установке Linux на виртуалку. Обучение длится 5 месяцев, после чего успешные выпускники курса смогут пройти собеседования у партнеров.
Проверьте себя на вступительном тесте и смотрите программу детальнее по .