- Samba and windows domain
- Файловый сервер Samba в домене Windows
- Подготовка
- Установка Samba
- Настройка Samba
- Взаимодействие Samba с доменом Windows
- Дополнительно:
- Setting up Samba as a Domain Member
- Namespaces
- Page actions
- Contents
- Introduction
- Preparing the Installation
- General Preparation
- Preparing a Domain Member to Join an Active Directory Domain
- Configuring DNS
- Configuring the /etc/resolv.conf
- Testing DNS resolution
- Forward Lookup
- Reverse Lookup
- Resolving SRV Records
- Error Messages
- Configuring Kerberos
- Configuring Time Synchronisation
- Local Host Name Resolution
- Preparing a Domain Member to Join an NT4 Domain
- Installing Samba
- Configuring Samba
- Setting up a Basic smb.conf File
- Choose backend for id mapping in winbindd
- Mapping the Domain Administrator Account to the Local root User
- Joining the Domain
- Configuring the Name Service Switch
- Starting the Services
- Testing the Winbindd Connectivity
- Sending a Winbindd Ping
- Using Domain Accounts and Groups in Operating System Commands
- Looking up Domain Users and Groups
- Assigning File Permissions to Domain Users and Groups
- Setting up Additional Services on the Domain Member
Samba and windows domain
- Главная
- ТЕХНИЧЕСКАЯ
- LINUX
- Файловый сервер Samba в домене Windows
Файловый сервер Samba в домене Windows
В данной статье будет рассмотрен вариант развёртывания файлового сервера Samba на базе операционной системы UBUNTU и организация его взаимодействия с доменов Windows.
Для примера использован следующие исходные данные:
дистрибутив: UBUNTU 16.04.4
имя сервера Linux: 2UBUNTU-16
домен Windows: TESTDOMAIN.LOCAL
контроллеры домена: 2SRV1.TESTDOMAIN.LOCAL , 2SRV2.TESTDOMAIN.LOCAL
администратор контроллера домена: adm
Подготовка
После установки дистрибутива выполняем обновление информации о пакетах и сами пакеты:
sudo apt-get update
sudo apt-get upgrade
Для удобства работы с сервером можно дополнительно установить Webmin (систему управления сервером LINUX через web-интерфейс).
Если есть необходимость, то меняем имя сервера:
hostnamectl set-hostname 2UBUNTU-16
Добавляем доменное имя сервера в файл hosts
sudo nano /etc/hosts
127.0.0.1 localhost
127.0.1.1 2ubuntu-16 2ubuntu-16.testdomain.local
После этого перезагружаем сервер:
Установка Samba
Помимо установки Samba, так же устанавливаем пакеты Kerberos и Winbind (для возможности подключения и взаимодействия с доменом на Windows):
sudo apt install krb5-user winbind samba libnss-winbind libpam-winbind
При установке Kerberos будет запрошена область по умолчанию — нужно указать адрес домена (в нашем случае TESTDOMAIN.LOCAL)
Проверяем доступность контроллера домена:
ping -c 5 TESTDOMAIN.LOCAL
Для успешной работы с доменом нужно установить синхронизацию времени с контроллером домена.
sudo apt install ntp
Настраиваем файл конфигурации службы ntp
sudo nano /etc/ntp.conf
Нужно закомментировать все текущие указанные серверы проверки время и добавить свой домен ( pool TESTDOMAIN.LOCAL)
Перезапускаем службу времени и проверяем статус синхронизации:
sudo systemctl restart ntp
ntpq -p
Запрашиваем тикет у Kerberos у контроллера домена:
kinit Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.
Если не отобразилась информация об ошибке, то запрос прошёл верно и можно проверить результат:
Настройка Samba
Сохраним резервную копию файла конфигурации:
sudo cp /etc/samba/smb.conf /etc/samba/smb.default.conf
Далее редактируем файл конфигурации:
sudo nano /etc/samba/smb.conf
Пример заполнения раздела [global]
[global]
security = ADS
workgroup = TESTDOMAIN
realm = TESTDOMAIN.LOCAL
encrypt passwords = yes
# Default idmap config for local BUILTIN accounts and groups
idmap config * : backend = tdb
idmap config * : range = 3000-7999
# idmap config for the TESTDOMAIN domain
idmap config TESTDOMAIN : backend = rid
idmap config TESTDOMAIN : range = 10000-999999
winbind enum users = yes
winbind enum groups = yes
winbind use default domain = yes
После сохранения изменений в файле smb.conf выполняем проверку:
Взаимодействие Samba с доменом Windows
Если ошибок не обнаружено, то подключаем сервер к домену:
sudo net ads join -U Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.
В случае отсутствия ошибок проверяем наличия сервера в списке компьютеров домена на стороне контроллера.
Перезагружаем сервис Winbind:
service winbind restart
Проверяем связь с контроллером домена, а затем список пользователей и групп домена Windows:
wbinfo —ping-dc
wbinfo -u
wbinfo -g
Чтобы UBUNTU могла использовать не только локальные группы и пользователей, но и доменные данные, нужно отредактировать настройки диспетчера службы имен NSS (Name Services Switch)
sudo nano /etc/nsswitch.conf
Необходимо дописать следующие значения:
passwd: compat winbind
group: compat winbind
После этого можно проверить возможность просмотра пользователей и групп:
getent passwd adm
getent group «пользователи домена»
Добавляем папку общего ресурса:
sudo mkdir -p /srv/samba/public
Назначаем имя владельца и группу для созданной папки:
sudo chown «adm»:»пользователи домена» /srv/samba/public
Редактируем файл конфигурации Samba, чтобы добавить поддержку Windows ACLs и сетевую папку public
sudo nano /etc/samba/smb.conf
[global]
# Windows ACLs Support
vfs objects = acl_xattr
map acl inherit = yes
store dos attributes = yes
[Public]
path = /srv/samba/public/
read only = no
Перезапустим службу Samba (чтобы применить изменения):
service smbd restart && service nmbd restart
Для удобства удалённой настройки разрешений сетевых ресурсов добавим администраторам домена привилегию SeDiskOperatorPrivilege:
net rpc rights grant «TESTDOMAIN\администраторы домена» SeDiskOperatorPrivilege -U «TESTDOMAIN\adm»
Проверяем подключение привилегий:
net rpc rights list privileges SeDiskOperatorPrivilege -U «TESTDOMAIN\adm»
Теперь управлять разрешениями для общих ресурсов можно удалённо с сервера Windows. Для этого запускаем оснастку «Управление компьютером» от имени администратора домена, выбираем «Подключиться к другому компьютеру…» и выбираем имя сервера Linux ( 2UBUNTU-16.TESTDOMAIN.LOCAL)
В разделе «Служебные программы» — «Общие папки» — «Общие ресурсы» будут отображаться сетевые ресурсы, доступные на сервере Linux.
Дополнительно:
Дополнительно можно подключать «корзину» для отдельных ресурсов (чтобы сохранять удалённые файлы и папки).
Проверяем наличие соответствующего модуля:
dpkg -l |grep samba-vfs-modules
Устанавливаем, если он отсутствует:
apt install samba-vfs-modules
Добавляем поддержку корзины для общего ресурса Public
sudo nano /etc/samba/smb.conf
[Public]
path = /srv/samba/public/
read only = no
vfs object = recycle
recycle: repository = .recycle/%U
recycle: touch = yes
recycle: keeptree = yes
recycle: versions = yes
«vfs object = recycle» – включение корзины для общего ресурса;
«recycle: repository = .recycle/%U» – папка, куда будут перемещаться удаленные файлы;
«recycle: touch = yes» – обновлять дату при перемещении файла в корзину;
«recycle: keeptree = yes» – сохранять структуру каталогов удаленного файла;
«recycle: versions = yes» – при перемещении в корзину файла с существующим именем, добавлять к началу имени файла префикс «Copy #».
Setting up Samba as a Domain Member
Namespaces
Page actions
Contents
Introduction
A Samba domain member is a Linux machine joined to a domain that is running Samba and does not provide domain services, such as an NT4 primary domain controller (PDC) or Active Directory (AD) domain controller (DC).
On a Samba domain member, you can:
- Use domain users and groups in local ACLs on files and directories.
- Set up shares to act as a file server.
- Set up printing services to act as a print server.
- Configure PAM to enable domain users to log on locally or to authenticate to local installed services.
For details about setting up a Samba NT4 domain or Samba AD, see Domain Control.
Never use samba-tool domain provision to create a Unix domain member, it will not work, you must follow the procedure laid out on this page. |
All AD Domain members must be in the same DNS domain and the Realm must be the DNS domain in uppercase. |
Preparing the Installation
General Preparation
- Verify that no Samba processes are running:
If the output lists any samba , smbd , nmbd , or winbindd processes, shut down the processes.
- If you previously run a Samba installation on this host:
- Backup the existing smb.conf file. To list the path to the file, enter:
- Remove all Samba database files, such as *.tdb and *.ldb files. To list the folders containing Samba databases:
Starting with a clean environment helps you to prevent confusion, and no files from your previous Samba installation are mixed with your new domain member installation.
Preparing a Domain Member to Join an Active Directory Domain
Configuring DNS
Active Directory (AD) uses DNS in the background, to locate other DCs and services, such as Kerberos. Thus AD domain members and servers must be able to resolve the AD DNS zones.
The following describes how to manually configure Linux clients to use DNS servers. If you are running a DHCP server providing DNS settings to your client computers, configure your DHCP server to send the IP addresses of your DNS servers.
Configuring the /etc/resolv.conf
Set the DNS server IP and AD DNS domain in your /etc/resolv.conf . For example:
Some utilities, such as NetworkManager can overwrite manual changes in that file. See your distribution’s documentation for information about how to configure name resolution permanently.
Testing DNS resolution
To verify that your DNS settings are correct and your client or server is able to resolve IP addresses and host names use the nslookup command. The command is available on Linux and Windows.
Forward Lookup
To resolve a host name its IP address:
Reverse Lookup
To resolve a IP address to its host name:
Note that in a Samba AD, the reverse zone is not automatically configured. To set up a reverse zone, see DNS Administration.
Resolving SRV Records
Active Directory (AD) uses SRV records to locate services, such as Kerberos and LDAP. To verify that SRV records are resolved correctly, use the nslookup interactive shell:
Error Messages
- The DNS server is not able to resolve the host name:
- The DNS server is not able to resolve the IP address:
- The DNS server used is not available:
Configuring Kerberos
Samba supports Heimdal and MIT Kerberos back ends. To configure Kerberos on the domain member, set the following in your /etc/krb5.conf file:
The previous example configures Kerberos for the SAMDOM.EXAMPLE.COM realm.
The Samba teams recommends to no set any further parameters in the /etc/krb5.conf file.
If your /etc/krb5.conf contains an include line it will not work, you Must remove this line.
Configuring Time Synchronisation
Kerberos requires a synchronised time on all domain members. Thus it is recommended to set up an NTP client. For further details, see Configuring Time Synchronisation on a Unix Domain Member.
Local Host Name Resolution
When you join the host to the domain, Samba tries to register the host name in the AD DNS zone. For this, the net utility must be able to resolve the host name using DNS or using a correct entry in the /etc/hosts file.
To verify that your host name resolves correctly, use the getent hosts command. For example:
The host name and FQDN must not resolve to the 127.0.0.1 IP address or any other IP address other than the one used on the LAN interface of the domain member.
If no output is displayed or the host is resolved to the wrong IP address and you are not using dhcp, set the correct entry in the /etc/hosts file. For example:
If you are using dhcp, check that /etc/hosts only contains the ‘127.0.0.1’ line shown above. If you continue to have problems, contact the sysadmin who controls your DHCP server.
- On debian related systems you will also see the line 127.0.1.1 hostname in /etc/hosts, remove it before you install samba.
- Please keep the line : 127.0.0.1 localhost
if you need to add aliases to the machine hostname, add them to the end of the line that starts with the machines ipaddress, not the 127.0.0.1 line.
Preparing a Domain Member to Join an NT4 Domain
For joining a host to an NT4 domain, no preparation is required.
Installing Samba
Install a maintained Samba version. For details, see Samba Release Planning. |
Configuring Samba
Setting up a Basic smb.conf File
When Setting up smb.conf on a Unix domain member, you will need to make a few decisions.
- Do you require users and groups to have the same IDs everywhere, including Samba AD DCs ?
- Do you only want your users and groups to have the same IDs on Unix domain members ?
After making your decision, you will have another decision to make, this decision could affect what you think you have already decided.
- Do you want or need individual users to have different login shells and/or Unix home directory paths ?
If you need your users to have different login shells and/or Unix home directory paths, or you want them to have the same ID everywhere, you will need to use the winbind ‘ad’ backend and add RFC2307 attributes to AD.
The RFC2307 attributes ( uidNumber , gidNumber , etc) are not added automatically when users or groups are created, you must add them manually. |
The ID numbers found on a DC (numbers in the 3000000 range) are NOT rfc2307 attributes They cannot and will not be used on Unix Domain Members, if you want to have the same ID numbers everywhere, you must add uidNumber & gidNumber attributes to AD and use the winbind ‘ad’ backend on Unix Domain Members. If you do decide to add uidNumber & gidNumber attributes to AD, you do not need to use numbers in the 3000000 range and in fact it would definitely be a good idea to use a different range. |
If your users will only use the Samba AD DC for authentication and will not store data on it or log into it, you can use the the winbind ‘rid’ backend, this calculates the user and group IDs from the Windows RID, if you use the same [global] section of the smb.conf on every Unix domain member, you will get the same IDs. If you use the ‘rid’ backend you do not need to add anything to AD and in fact, any RFC2307 attributes will be ignored. When using the ‘rid’ backend you must set the ‘template shell’ and ‘template homedir’ parameters in smb.conf, these are global settings and everyone gets the same login shell and Unix home directory path, unlike the RFC2307 attributes where you can set individual Unix home directory paths and shells.
There is another way of setting up Samba, this is where you require your users and groups to have the same ID everywhere, but only need your users to have the same login shell and use the same Unix home directory path. You can do this by using the winbind ‘ad’ backend and using the template lines in smb.conf. This way you only have to add uidNumber & gidNumbers attributes to AD.
Having decided which winbind backend to use, you now have a further decision to make, the ranges to use with ‘idmap config’ in smb.conf. By default on a Unix domain member, there are multiple blocks of users & groups:
- The local system users & groups: These will be from 0-999
- The local Unix users and groups: These start at 1000
- The ‘well Known SIDs’: .
- The DOMAIN users and groups: ADUC, by default, starts these at 10000
- Trusted domains: .
- Anything that isn’t a ‘well Known SID’ or a member of DOMAIN or a trusted domain: .
As you can see from the above, you shouldn’t set either the ‘*’ or ‘DOMAIN’ ranges to start at 999 or less, as they would interfere with the local system users & groups. You also should leave a space for any local Unix users & groups, so starting the ‘idmap config’ ranges at 3000 seems to be a good compromise.
You need to decide how large your ‘DOMAIN’ is likely to grow to and you also need to know if you have any trusted domains or if you may need to have any in future.
Bearing the above information in mind, you could set the ‘idmap config’ ranges to the following:
Domain | Range |
---|---|
* | 3000-7999 |
DOMAIN | 10000-999999 |
You could also have any trusted domains starting at:
Domain | Range |
---|---|
TRUSTED | 1000000-9999999 |
If you set the ‘*’ range above the ‘DOMAIN’ range, the ranges will conflict if the ‘Domain’ grows to the point that the next ID would be the same as the ‘*’ range start ID.
With the above suggested ranges, no range will overlap or interfere with another.
You may also have seen examples of the ‘*’ range being used for everything, this is not recommended and should not be used.
Before joining the domain, configure the domain member’s smb.conf file:
- To locate the file, enter:
To create a basic smb.conf, you need something like this (note, this does not include any ‘idmap config’ auth lines, they will be added later. It also does not show any shares)
If you are creating a new smb.conf on an unjoined machine and add these lines, a keytab will be created during the join:
If you do not want to enter the domain set in ‘ workgroup = ‘ during login etc (just ‘username’ instead of DOMAIN\username) and have only one domain, add this line:
This will only work for the default domain, if you have more than one domain, do not set the line. For multiple domains, you must use ‘DOMAIN\username’. |
For testing purposes only (remove for production), add these lines:
The above lines just make ‘getent passwd’ and ‘getent group’ display all domain users and groups, they are not required for anything else and Samba will work correctly and faster without them. |
To disable printing completely, add these lines:
You now need to add the ‘idmap config’ lines for your preferred winbind method.
Choose backend for id mapping in winbindd
Select one of the following hyperlinks to find information about the relevant Samba domain back end and what idmap config lines to add:
Back End | Documentation | Man Page |
---|---|---|
ad | idmap config ad | idmap_ad(8) |
rid | idmap config rid | idmap_rid(8) |
autorid | idmap config autorid | idmap_autorid(8) |
Add an additional ID mapping configuration for every domain. The ID ranges of the default ( * ) domain and other domains configured in the smb.conf file must not overlap. |
Mapping the Domain Administrator Account to the Local root User
Samba enables you to map domain accounts to a local account. Use this feature to execute file operations on the domain member’s file system as a different user than the account that requested the operation on the client.
You can optionally map the domain Administrator account to the local root account on a Unix domain member. Configuring the mapping allows the domain Administrator to execute file operations as root on the Unix domain member. If you do map Administrator to the root account, Administrator will be unknown to the OS and will not be able to log onto a Unix domain member. Only follow the method below to map Administrator to root , never give Administrator a uidNumber attribute, doing this will break the default Administrator mapping on a Samba AD DC. |
To map the domain administrator to the local root account:
- Add the following parameter to the [global] section of your smb.conf file:
- Create the /usr/local/samba/etc/user.map file with the following content:
When using the ad ID mapping back end, never set a uidNumber attribute for the domain Administrator account. If the account has the attribute set, the value will override the local UID 0 of the root user on Samba AD DC’s and thus the mapping fails. |
For further details, see username map parameter in the smb.conf(5) man page.
Joining the Domain
- To join the host to an Active Directory (AD), enter:
- To join the host to an NT4 domain, enter:
Do not join a domain member using samba-tool domain join . This option is unsupported, does not work and can cause problems with your AD replication. The option will be removed from samba-tool in a future release. |
If you have problems joining the domain, check your configuration. For further help, see Troubleshooting Samba Domain Members.
Configuring the Name Service Switch
To enable the name service switch (NSS) library to make domain users and groups available to the local system:
- Append the winbind entry to the following databases in the /etc/nsswitch.conf file:
- Keep the files entry as first source for both databases. This enables NSS to look up domain users and groups from the /etc/passwd and /etc/group files before querying the Winbind service.
- Do not add the winbind entry to the NSS shadow database. This can cause the wbinfo utility fail.
If there’s a line containing an initgroups directive, add [success=continue] winbind , otherwise the NSS library will not ask winbindd for a user’s additional group memberships. Do not add the initgroups line if it does not exist. |
Do not use the same user names in the local /etc/passwd file as in the domain. |
If you compiled Samba, add symbolic links from the libnss_winbind library to the operating system’s library path. For details, see libnss_winbind Links. If you used packages to install Samba, the link is usually created automatically. |
Starting the Services
Start the following services to have a fully functioning Unix domain member:
- The smbd service
- The nmbd service
- The winbindd service
If you do not require Network Browsing, you do not need to start the nmbd service on a Unix domain member. |
The latest versions of Samba (from 4.11.0) now only use SMBv2 as the minimum client & server protocols. This means that anything that relies on SMBv1 will not work, unless you manually set client min protocol = NT1 and server min protocol = NT1 in smb.conf . Samba no longer recommends using SMBv1. |
You must not start the samba service on a domain member. This service is required only on Active Directory (AD) domain controllers (DC). |
Samba does not provide System V init scripts, systemd , upstart , or service files for other init services.
- If you installed Samba using packages, use the script or service configuration file provided by the package to start Samba.
- If you built Samba, see your distribution’s documentation for how to create a script or configuration to start services.
Testing the Winbindd Connectivity
Sending a Winbindd Ping
To verify if the Winbindd service is able to connect to Active Directory (AD) Domain Controllers (DC) or a primary domain controller (PDC), enter:
If the previous command fails, verify:
- That the winbindd service is running.
- Your smb.conf file is set up correctly.
Using Domain Accounts and Groups in Operating System Commands
Looking up Domain Users and Groups
The libnss_winbind library enables you to look up domain users and groups. For example:
- To look up the domain user SAMDOM\demo01 :
- To look up the domain group Domain Users :
Assigning File Permissions to Domain Users and Groups
The name service switch (NSS) library enables you to use domain user accounts and groups in commands. For example to set the owner of a file to the demo01 domain user and the group to the Domain Users domain group, enter:
Setting up Additional Services on the Domain Member
On a Samba domain member, you can additionally set up:
- File shares to act as a file server. For details, see Samba File Serving.
- Print services to act as a print server. For details, see Print Server Support.
- PAM authentication of domain users for local services. For details, see Authenticating Domain Users Using PAM.