- Ubuntu Documentation
- Introduction
- Used terms
- Kerberos
- Join AD domain
- Required software
- Testing
- Setup Authentication
- nsswitch
- Testing
- Final configuration
- One last thing
- Usage
- Automatic Kerberos Ticket Refresh
- Troubleshooting
- Resources
- Automated Methods
- Linux в домене Active Directory
- Содержание
- Общая информация
- Проверка требований
- Установка Samba
- Настройка Samba
- Проверка работы и отладка
- Дополнительная настройка
- Доступ к Samba из Windows 7 и 2008 r2
- Работа над ошибками
- Winbind не запускается
- Ошибка получения билета Kerberos
Ubuntu Documentation
Introduction
This Howto describes how to add an Ubuntu box in an Active Directory domain and to authenticate the users with AD.
Note: Centrify Express and Likewise Open are alternative solutions for Linux systems to authenticate to an Active Directory domain. For Centrify Express see DirectControl. For Likewise Open see LikewiseOpen.
Used terms
term
definition
lab.example.com
AD domain
win2k3.lab.example.com
LAB.EXAMPLE.COM
Kerberos Realm
linuxwork
computername of the Ubuntu workstation
linuxwork.lab.example.com
FQDN of the Ubuntu workstation
ntp.example.com
timeserver (NTP)
Kerberos
The first step in joining an Active Directory domain is to install and configure Kerberos. See Samba/Kerberos for details.
Join AD domain
Required software
You need to install the winbind and samba packages. The packages smbfs and smbclient are useful for mounting network shares and copying files.
Ubuntu 10.04 and later should also install the libnss-winbind and libpam-winbind packages.
The package smbfs is optional, but includes useful client utilities, including the smbmount command. Also useful is the smbclient package, which includes an FTP-like client for SMB shares.
The first step in joining the Active Directory domain is to edit /etc/samba/smb.conf:
Adding valid users = @»Domain Users» to the [global] section will allow all Domain Users to see all of the shares avaliable without a password. This is the equivlient to allowing «Everyone» to read all shares. If you want to restrict reading a share then you will have to specify valid users for that share.
The «winbind use default domain» parameter is useful in single-domain enterprises and causes winbind to treat any username that isn’t qualified with a domain name as a username in the domain to which winbind is joined. Omit this parameter if you are concerned about confusion between local accounts on your systems and accounts in the default domain. The «winbind separator» directive is optional, and the default value is the usual backslash «\» Domain and User separator. You can use «+» if you know of a specific reason «\» will not work in your environment.
Be sure to restart the Samba and Winbind services after changing the /etc/samba/smb.conf file:
Request a valid Kerberos TGT for an account using kinit, which is allowed to join a workstation into the AD domain. Now join to the domain, if the ticket was valid you should not need to supply a password — even if prompted you should be able to leave it blank.
This next step gave me the error: kinit(v5): Cannot resolve network address for KDC in realm LAB.EXAMPLE.COM while getting initial credentials even though nslookup win2k3 and host 10.0.0.1 would both return the correct entries. To correct this problem, I had to edit my /etc/hosts file and add the following to it: 10.0.0.1 win2k3.lab.example.com
If the Kerberos auth was valid, you should not get asked for a password. However, if you are not working as root and are instead using sudo to perform the necessary tasks, use the command sudo net ads join -U username and supply your password when prompted. Otherwise, you will be asked to authenticate as root@LAB.EXAMPLE.COM instead of a valid account name. You can also supply a password if you don’t want to get prompted. Just use net ads join -U %
for this. Maybe it's useful for unattended installations where you want to add machines to an AD automatically.
If your Active Directory server is not running DDNS as well (eg. if you're running a separate DNS server) you may get the error:
To fix this, specify the AD server to the "net join" command:
You'll get a warning about not being able to update DNS, but you will successfully join the AD!
Testing
Using a clean install of 10.04, I did not have to modify any PAM files to get authentication working. I had to edit common-session to get the home directories created, but that is it.
Setup Authentication
nsswitch
I needed to add hosts: files dns to /etc/nsswitch.conf to avoid the settings in /etc/hosts to be ignored.
Don´t forget to restart winbind again after editing /etc/nsswitch.conf.
Testing
You can check that the Domain has successfully been joined by:
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.
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)
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.
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.
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.
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)
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
Final configuration
Each domain needs a directory in /home/.
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:
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
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.
Usage
Logon with DOMAIN+USERNAME, unless you included "winbind use default domain" in your smb.conf, in which case you may log in using only USERNAME.
Automatic Kerberos Ticket Refresh
To have pam_winbind automatically refresh the kerberos ticket
Add the winbind refresh tickets line to smb.conf :
And modify /etc/pam.d/common-auth:
Troubleshooting
If the Winbind PAM module in /var/log/auth.log says that the AD-user is not existing restart winbind. It might be best to restart the whole workstation.
If when logging into the machine one gets a "no logon servers" error winbind\samba may not be starting properly. Try restarting them manually, and then logging in.
-If a manual restart works, then to fix this issue one needs to change scripts S20samba and S20winbind to S25samba and S25winbind in the /etc/rc2.d, rc3.d, rc4.d, rc5.d folders. The understanding is that this causes samba and winbind to startup later in the boot order for each runlevel. So that they start after S24avahi-daemon. If you then find that you must wait a bit before you can log in, you need to set "winbind enum users" and "winbind enum groups" in /etc/samba/smb.conf to 'no'.
name service cache daemon
The name service cache daemon (nscd) can interfere with winbind, as winbind maintains its own cache. Remove it.
Some names or groups are resolved with getent, but others are not
The range of your idmap parameter is not wide enough to encompass all the users or groups
Adding more than one Linux machine to a Windows network
The above procedure allows you to add as many Linux machines as you like. However, the UID assigned to a given user may not be the same across all the machines. It created file ownership & rights issues when files/folders are shared between these machines. See Question #21806 on https://answers.launchpad.net/ubuntu/ for details. Therefore it is advisable to specify the UID mapping method
The newer syntax is (with old style you can get NT_STATUS_OBJECT_NAME_COLLISION in /var/log/samba/log.winbindd)
Resources
The Samba and Active Directory Wiki contains very detailed instructions.
Automated Methods
The SADMS package allows for automated joining to Active Directory through a GUI interface. http://sadms.sourceforge.net/
ActiveDirectoryWinbindHowto (последним исправлял пользователь penalvch 2015-09-24 09:04:42)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник
Linux в домене Active Directory
Содержание
Общая информация
Если вам нужно просто предоставить сетевой доступ к ресурсам Linux компьютера, то смотрите статью Samba.
В этой статье мы опишем как подключить Linux компьютер к домену под управлением Microsoft Active Directory и сделать из него файловый сервер.
После выполнения этой инструкции мы будем иметь в сети файловый сервер под управлением ОС Линукс, входящий в домен Windows 2003 и ничем не отличающийся от файлового сервера под Windows. Пользователи домена смогут обращаться к его ресурсам под своими учётными записями. Доступ регулируется группами домена AD.
По этой инструкции настраивались Debian (4, 5), Ubuntu 9.10, создавалась она на основе официальной документации и многих рекомендаций и инструкций из Интернета. Остальные Linux'ы настраиваются сходным образом.
Проверка требований
- Проверяем что Samba собрана с поддержкой Kerberos:
- Также проверим что поддерживается LDAP
- Для корректной работы Samba в домене Windows 2003 нужны версии MIT Kerberos version >=1.3.1. Проверим:
- Для корректной работы с Windows 2008 серверами сама Samba должна быть достаточно свежая:
Установка Samba
- Устанавливаем сервер и клиент samba.
При настройке krb5-config лучше указывать IP адреса контроллеров домена, а не их DNS имена.
Настройка Samba
- Для подключения к домену Active Directory удобно использовать утилиту Likewise-Open.
- Для администрирования Samba удобно использовать SWAT или webmin, которые предоставляют веб интерфейс. Попасть на него можно по адресу http://server_address:901 и https://server_address:10000 соответственно, указав для соединения пользователя root. Но будьте осторожны - он полностью переписывает smb.conf и некоторые параметры может просто игнорировать. Лучше предварительно сделать резервную копию файла. Я сначала использовал SWAT, а затем дорабатывал конфигурационный файл /etc/samba/smb.conf руками. Вот, что осталось у меня не закоментированным (принтеры к этому серверу не подключены):
Мы описали два общих каталога:
- backup - доступ имеют только пользователи входящие в группу BackupGroup в Active Directory. Они могут создавать и удалять файлы/каталоги
- distrib - доступ имеют все пользователи входящие в группу DistribGroup в Active Directory
В приведённой конфигурации подразумевается, что eth0 - это сетевой интерфейс в локальную сеть, где домен имеет полное имя WORKGROUP.DOMAIN.LOCAL
- редактируем /etc/nsswitch:
- Проверим, что в /etc/hosts есть корректная запись для нашего сервера, также можно добавить записи для контроллеров доменов:
- Удаляем если есть (или переносим в резервные копии) файл /etc/samba/secrets.tdb и все файлы из /var/lib/samba/*.tdb
- Проверяем конфигурацию (не обязательно):
- testparm -s
В Ubunto testparm находится в пакете samba-common-bin
- Проверим как Samba-3 winbind общается с контроллером домена Active Directory посредством протокола Kerberos:
На рассхождение времени в секундах указывает строка "Server time offset: -5". Обратите внимание, что протокол Kerberos зависим от времени, и расхождение с часами контроллера домена допускается лишь незначительное, поэтому желательно настроить NTP клиент (см. статьи по настройке NTP). В Ubuntu это указывается в файле /etc/default/ntpdate:
- В Debian (и его сыновьях, таких как Ubuntu и внуках вроде Linux Mint) при установке пакета krb5-cofig сразу предлагается его настройка. Лучше всего попробовать работать с этими настройками, но если ничего предложено не было или мы хотим что-то изменить, то редактируем /etc/krb5.conf (я для более стабильной работы использовал ip адреса вместо имён серверов):
- Проверим работает ли Kerberos, постараемся получить билет и просмотреть его:
- Удалим полученный билет:
- Присоединяемся к домену:
Всё, компьютер включен в домен, что можно проверить на контроллере. Даже если после приведённых строк получили следующие:
Проверка работы и отладка
- Для удобства отладки сделаем ссылку на каталог журналов:
- Запускаем samba и winbind:
- Для проверки правильно ли подключение к домену можно посмотреть список пользователей и групп домена (не обязательно):
Если нас не понимают, то подсказываем пароль для wbinfo и смотрим: список доменов в сети, информацию о домене WORKGROUP, список пользователей и групп домена:
- Проверяем, как работает NSS. Команда getent показывает инфо о пользователе, который может быть как в домене, так и юниксовый:
- Теперь можно использовать ресурсы на линукс-сервере, на которые мы дали доступ, как обычные доменные ресурсы.
Дополнительная настройка
- Можно также сопоставить (но это не обязательно) локальные учётные данные и из домена Windows. Для сопоставления пользователей редактируем файл /etc/samba/smbusers.conf:
- для сопоставления (мапирования от англ. Map) групп домена и групп UNIX выполняем:
- После того как всё отлажено, можно понизить уровень записи в журнал до "1". В /etc/samba/smb.conf:
Доступ к Samba из Windows 7 и 2008 r2
Начиная с этих версий параметры авторизации у MS поменялись. Скорее всего Samba вскоре это учтёт, а пока подружить системы можно изменив на Win7 свойства сетевой безопасности:
Пуск - Панель управления - Администрирование - Локальная политика безопасности - Локальные политики - Параметры безопасности
- Сетевая безопасность: минимальная сеансовая безопасность для клиентов на базе NTLM SSP - убрать галочку с "Требовать 128-битное шифрование". Таких параметра два - выполнить для обоих
- Сетевая безопасность: уровень проверки подлинности LAN Manager - выбрать в списке пункт "Отправлять LM- и NTML-ответы"
Работа над ошибками
Winbind не запускается
При запуске Samba обнаруживаем, что winbind не запустился:
В журнале log.winbindd обнаруживаем запись:
Видим, что добавлен "встроенный домен" (BUILTIN) и домен "название компьютера" (STORAGE), подключиться к домену AD не удалось.
Решение: Переподключить компьютер в домен. Удалять придётся с самого контроллера, т.к. комадна net ads leave скорее всего не поможет.
Ошибка получения билета Kerberos
При попытке получить билет Kerberos получили:
Решение: указать имя домена в другом регистре. Скорее всего нужны все заглавные
Источник