- Linux машина в домене Windows AD с помощью sssd и krb5
- Linux в домене Active Directory
- Join an Ubuntu Linux virtual machine to an Azure Active Directory Domain Services managed domain
- Prerequisites
- Create and connect to an Ubuntu Linux VM
- Configure the hosts file
- Install required packages
- Configure Network Time Protocol (NTP)
- Join VM to the managed domain
- Update the SSSD configuration
- Configure user account and group settings
- Allow password authentication for SSH
- Configure automatic home directory creation
- Grant the ‘AAD DC Administrators’ group sudo privileges
- Sign in to the VM using a domain account
- Next steps
Linux машина в домене Windows AD с помощью sssd и krb5
Была необходимость ввести в домен Windows машину с Ubuntu. Для этих целей обычно используют Samba и Winbind. Но возможен альтернативный вариант с sssd, краткое руководство по нему ниже.
Для примера будем использовать:
Домен = contoso.com
Контроллер домена = dc.contoso.com
Запускаем терминал Ubuntu:
1. Переключаемся под рута
2. Устанавливаем необходимые пакеты
3. Редактируем /etc/krb5.conf, в качестве отступов используется табуляция
4. Редактируем файл /etc/hosts, указываем FQDN для данного хоста:
5. Пробуем получить Kerberos ticket от имени администратора домена:
Если тикет получен успешно, то теперь можно сгенерировать Kerberos principals для данного хоста, регистр важен:
Сейчас наш хост должен отобразиться в списке компьютеров в каталоге. Если все так — удаляем полученный Kerberos ticket:
6. Создаем файл /etc/sssd/sssd.conf со следующим содержимым:
Описание параметров конфигфайла sssd можно посмотреть тут
Устанавливаем права доступа для файла sssd.conf:
Перезапускаем SSSD service
7. Редактируем настройки PAM
редактируем файл /etc/pam.d/common-session, после строки
переопределить параметры через системные настройки PAM, вызываем
и отмечаем пункты sss auth и makehomdir. Это автоматически добавит
строчку выше в common-session и она не будет перезатерта при обновлении системы.
Теперь мы можем логиниться на машине доменными пользователями, которым разрешен вход.
P.S.: Можно дать права на использование sudo доменным группам. Используя visudo, редактируем файл /etc/sudoers, или лучше, как рекомендует maxzhurkin и iluvar, создаем новый файл в /etc/sudoers.d/ и редактируем его
добавляем требуемую группу — например, Domain Admins (если в названии группы есть пробелы — их необходимо экранировать):
P.S.S.: Спасибо gotch за информацию о realmd. Очень удобно — если не нужны специфические настройки, то ввод машины в домен занимает, по сути, три (как заметил osipov_dv четыре) команды:
1. Устанавливаем нужные пакеты:
2. Редактируем файл /etc/hosts, указываем FQDN для данного хоста:
3. Проверяем, что наш домен виден в сети:
4. Вводим машину в домен:
5. Редактируем настройки PAM
Дополнительный плюс данного варианта — сквозная авторизация на файловых ресурсах домена.
Источник
Linux в домене Active Directory
Перед администраторами иногда встают задачи интеграции Linux серверов и рабочих станций в среду домена Active Directory. Обычно требуется:
1. Предоставить доступ к сервисам на Linux сервере пользователям домена.
2. Пустить на Linux сервер администраторов под своими доменными учётными данными.
3. Настроить вход на Linux рабочую станцию для пользователей домена, причём желательно, чтобы они могли при этом вкусить все прелести SSO (Я, например, не очень люблю часто вводить свой длинный-предлинный пароль).
Обычно для предоставления Linux системе пользователей и групп из домена Active Directory используют winbind либо настраивают библиотеки nss для работы с контроллером домена Active Directory по LDAP протоколу. Но сегодня мы пойдём иным путём: будем использовать PowerBroker Identity Services (Продукт известен также под именем Likewise).
Установка.
Есть две версии продукта: Enterprise и Open. Мне для реализации моих задач хватило Open версии, поэтому всё написанное далее будет касаться её.
Получить Open версию можно на сайте производителя, но ссылку Вам предоставят в обмен на Ваше имя, название компании и e-mail.
Существуют 32-х и 64-х пакеты в форматах rpm и deb. (А также пакеты для OS X, AIX, FreeBSD, SOlaris, HP-UX)
Исходники (Open edition) доступны в git репозирории: git://source.pbis.beyondtrust.com/pbis.git
Я устанавливал PBIS на Debian Wheezy amd64:
Содержимое пакета устанавливается в /opt/pbis. Также в системе появляется новый runscript lwsmd, который собственно запускает агента PBIS.
В систему добавляется модуль PAM pap_lsass.so.
Утилиты (большей частью консольные), необходимые для функционирования PBIS, а также облегчающие жизнь администратору размещаются в /opt/pbis/bin
Ввод в домен.
Перед вводом в домен следует убедиться, что контроллеры домена доступы и доменные имена корректно разворачиваются в ip. (Иначе следует настроить resolv.conf)
Для ввода в домен предназначены две команды: /opt/pbis/bin/domainjoin-cli и /opt/pbis/bin/domainjoin-gui. Одна из них работает в командной строке, вторая использует libgtk для отображения графического интерфеса.
Для ввода в домен потребуется указать: имя домена, логин и пароль доменного пользователя с правами для ввода ПК в домен, контейнер для размещения объекта компьютера в домене — всё то же самое, что и при вводе в домен windows ПК.
После ввода в домен потребуется перезагрузка.
Обратите внимание — PBIS умеет работать с сайтами Active Directory. Клиент PBIS будет работать с контроллерами того сайта, в котором он находится!
После перезагрузки.
После перезагрузки и id, и getent выдадут вам пользователей и группы домена (национальные символы обрабатываются корректно. Пробелы заменяются на символ «^»).
В доменной DNS зоне появится запись с именем вашего ПК.
Не спешите входить от имени доменного пользователя. Сначала имеет смысл (но вовсе не обязательно) настроить PBIS.
Одно из отличий Enterprise версии — возможность управлять этими настройками через GPO.
Стоит обратить внимание на HomeDirPrefix, HomeDirTemplate.
Я также сразу задал «RequireMembershipOf» — только пользователи, члены групп или SID из этого списка могут авторизоваться на компьютеры.
Описание каждого параметра можно получить, например так:
Значение параметра устанавливается например так:
Обратите внимание — PBIS не использует атрибуты SFU либо иные другие атрибуты Acrive Directory для получения loginShell пользователя, а также его uid и gid.
loginShell для доменных пользователей задаётся в настройках PBIS, причём установка различных loginShell различным пользователям — возможна только в Enterprise версии.
uid формируется как хэш SID пользователя.
gid — как хэш SID primaryGroup пользователя.
Таким образом на двух ПК пользователь получит всегда одинаковые uid и gid.
Теперь можно входить в систему от имени доменного пользователя. После входа доменного пользователя обратите внимание на вывод klist — PBIS получит для пользователя необходимые билеты kerberos. После этого можно безпроблемно обращаться к ресурсам на windows ПК (Главное, чтобы используемое ПО поддерживало GSSAPI). Например: теперь я без дополнительных запросов паролей (и пароль мой нигде не сохранён!) открываю любые smb ресурсы домена в Dolphin. Также Firefox (при настройке network.negotiate-auth.trusted-uris) позволяет использовать SSO при доступе к Web-порталам с доменной авторизацией (естественно если SSO настроена на сервере)
А как же SSO при доступе к ресурсам на Linux ПК?
Можно и так! PBIS заполняет /etc/krb5.keytab и поддерживает его актуальным. Поэтому серверное ПО с поддержкой GSSAPI может быть сконфигурировано для SSO.
Например, для доступа к серверу по ssh, в конфигурационный файл /etc/ssh/sshd_config (путь в вашей системе может отличаться)
И при подключении указать доменное имя компьютера (присутствующее в его SPN — иначе билет kerberos не сможет быть выписан)
UsePAM yes
(PBIS предоставляет модуль для PAM в том числе)
Также логично будет добавить директиву «AllowGroups» и указать через пробел доменные группы, пользователям которых вы намерены дать доступ к ssh серверу.
На клиентском Linux ПК в конфигурацию клиента ssh достаточно включить:
Естественно на клиентском Linux компьютере должен быть настроен kerberos. Простейший способ выполнить это условие — так же ввести клиентский компьютер в домен и работать от имени доменного пользователя.
На клиентском Windows ПК (члене домена) при использовании Putty следует в свойствах SSH соединения установить флаг «Attempt GSSAPI authentification (SSH-2 only)» (В разных версиях этот пункт называется по-разному).
Также в секции Connection —> Data можно поставить переключатель в позицию «Use system username»
Если вы намереваетесь организовать таким образом ssh доступ администраторов к linux серверам — хорошей идеей будет запретить на них вход root по ssh и добавить linux-администраторов (а ещё лучше их доменную группу) в файл sudoers.
Это не единственные сценарии применения PBIS. если статья покажется Вам интересной — в следующей напишу как организовать samba файловый сервер в домене для доменных пользователей без winbind.
Дополнительную информацию по теме можно получить на форуме сообщества PowerBroker Identity Services: forum.beyondtrust.com
UPD. К преимуществам PowerBroker Identity Services я могу отнести:
- Хорошую повторяемость (сравните последовательность действий этой статье с инструкцией по настройке winbind)
- Кэширование данных из каталога (доменный пользователь может войти на ПК, когда домен не доступен, если его учётные данные в кэше)
- Для PBIS не требуется формирование в каталоге AD дополнительных атрибутов пользователя
- PBIS понимает сайты AD и работает с контроллерами своего сайта.
- Большую безопасность (samba создаёт учётку компьютера с не истекающим паролем)
- В платной версии (если возникнет такая необходимость) PBIS агент управляем через GPO (хотя это можно и вычеркнуть. если вы не намерены её покупать)
UPD 2 Пришла обратная связь от пользователя sdemon72. Возможно кому-то будет полезно.
Здравствуйте! Попробовал ваш рецепт на свежей linuxmint-18-mate-64bit, все получилось с некоторыми оговорками:
1. С получением программы через сайт у меня возникли сложности (не захотел писать реальный номер телефона, а бутафорский не прокатил — пришло письмо с сомнениями по его поводу), зато нашел репозиторий с наисвежайшими версиями: repo.pbis.beyondtrust.com/apt.html
2. При запуске программы выдает ошибки, чтобы их избежать, нужно перед запуском сделать следующее:
2.1. Установить ssh:
sudo apt-get install ssh
2.2. Поправить /etc/nsswitch.conf:
hosts: files dns mdns4_minimal [NOTFOUND=return]
(т.е. переносим dns с конца строки на вторую позицию)
2.3. Поправить /etc/NetworkManager/NetworkManager.conf:
#dns=dnsmasq
(т.е. комментируем эту строчку)
2.4. Перезапустить network-manager:
sudo service network-manager restart
После этого все сработало на ура! Буду очень благодарен, если внесете эти дополнения в статью, т.к. в поиске по сабжу она выпадает в первых строках. Оставлять комментарии я не могу (запрещает сайт), поэтому пишу вам лично.
Если интересно — история моих изысканий тут: linuxforum.ru/topic/40209
С уважением, Дмитрий
UPD 3: Почему бесплатную версию PBIS не получится применить в большой компании
В бесплатной версии работает только один алгоритм генерации UNIX iD (uid и gid) по SID доменного пользователя. Так вот он не обеспечивает уникальности
этих идентификаторов. Когда у вас очень старый домен или просто много пользователей очень высок риск, что два и более пользователя получат одинаковые идентификаторы в системе с OpenPBIS. В платной версии есть возможность выбора между алгоритмами генерации id, но она стоит значительно дороже аналогичного продукта от Quest Software ;(.
Источник
Join an Ubuntu Linux virtual machine to an Azure Active Directory Domain Services managed domain
To let users sign in to virtual machines (VMs) in Azure using a single set of credentials, you can join VMs to an Azure Active Directory Domain Services (Azure AD DS) managed domain. When you join a VM to an Azure AD DS managed domain, user accounts and credentials from the domain can be used to sign in and manage servers. Group memberships from the managed domain are also applied to let you control access to files or services on the VM.
This article shows you how to join an Ubuntu Linux VM to a managed domain.
Prerequisites
To complete this tutorial, you need the following resources and privileges:
- An active Azure subscription.
- If you don’t have an Azure subscription, create an account.
- An Azure Active Directory tenant associated with your subscription, either synchronized with an on-premises directory or a cloud-only directory.
- If needed, create an Azure Active Directory tenant or associate an Azure subscription with your account.
- An Azure Active Directory Domain Services managed domain enabled and configured in your Azure AD tenant.
- If needed, the first tutorial creates and configures an Azure Active Directory Domain Services managed domain.
- A user account that’s a part of the managed domain.
- Unique Linux VM names that are a maximum of 15 characters to avoid truncated names that might cause conflicts in Active Directory.
Create and connect to an Ubuntu Linux VM
If you have an existing Ubuntu Linux VM in Azure, connect to it using SSH, then continue on to the next step to start configuring the VM.
If you need to create an Ubuntu Linux VM, or want to create a test VM for use with this article, you can use one of the following methods:
When you create the VM, pay attention to the virtual network settings to make sure that the VM can communicate with the managed domain:
- Deploy the VM into the same, or a peered, virtual network in which you have enabled Azure AD Domain Services.
- Deploy the VM into a different subnet than your Azure AD Domain Services managed domain.
Once the VM is deployed, follow the steps to connect to the VM using SSH.
Configure the hosts file
To make sure that the VM host name is correctly configured for the managed domain, edit the /etc/hosts file and set the hostname:
In the hosts file, update the localhost address. In the following example:
- aaddscontoso.com is the DNS domain name of your managed domain.
- ubuntu is the hostname of your Ubuntu VM that you’re joining to the managed domain.
Update these names with your own values:
When done, save and exit the hosts file using the :wq command of the editor.
Install required packages
The VM needs some additional packages to join the VM to the managed domain. To install and configure these packages, update and install the domain-join tools using apt-get
During the Kerberos installation, the krb5-user package prompts for the realm name in ALL UPPERCASE. For example, if the name of your managed domain is aaddscontoso.com, enter AADDSCONTOSO.COM as the realm. The installation writes the [realm] and [domain_realm] sections in /etc/krb5.conf configuration file. Make sure that you specify the realm an ALL UPPERCASE:
Configure Network Time Protocol (NTP)
For domain communication to work correctly, the date and time of your Ubuntu VM must synchronize with the managed domain. Add your managed domain’s NTP hostname to the /etc/ntp.conf file.
Open the ntp.conf file with an editor:
In the ntp.conf file, create a line to add your managed domain’s DNS name. In the following example, an entry for aaddscontoso.com is added. Use your own DNS name:
When done, save and exit the ntp.conf file using the :wq command of the editor.
To make sure that the VM is synchronized with the managed domain, the following steps are needed:
- Stop the NTP server
- Update the date and time from the managed domain
- Start the NTP service
Run the following commands to complete these steps. Use your own DNS name with the ntpdate command:
Join VM to the managed domain
Now that the required packages are installed on the VM and NTP is configured, join the VM to the managed domain.
Use the realm discover command to discover the managed domain. The following example discovers the realm AADDSCONTOSO.COM. Specify your own managed domain name in ALL UPPERCASE:
If the realm discover command can’t find your managed domain, review the following troubleshooting steps:
- Make sure that the domain is reachable from the VM. Try ping aaddscontoso.com to see if a positive reply is returned.
- Check that the VM is deployed to the same, or a peered, virtual network in which the managed domain is available.
- Confirm that the DNS server settings for the virtual network have been updated to point to the domain controllers of the managed domain.
Now initialize Kerberos using the kinit command. Specify a user that’s a part of the managed domain. If needed, add a user account to a group in Azure AD.
Again, the managed domain name must be entered in ALL UPPERCASE. In the following example, the account named contosoadmin@aaddscontoso.com is used to initialize Kerberos. Enter your own user account that’s a part of the managed domain:
Finally, join the VM to the managed domain using the realm join command. Use the same user account that’s a part of the managed domain that you specified in the previous kinit command, such as contosoadmin@AADDSCONTOSO.COM :
It takes a few moments to join the VM to the managed domain. The following example output shows the VM has successfully joined to the managed domain:
If your VM can’t successfully complete the domain-join process, make sure that the VM’s network security group allows outbound Kerberos traffic on TCP + UDP port 464 to the virtual network subnet for your managed domain.
If you received the error Unspecified GSS failure. Minor code may provide more information (Server not found in Kerberos database), open the file /etc/krb5.conf and add the following code in [libdefaults] section and try again:
Update the SSSD configuration
One of the packages installed in a previous step was for System Security Services Daemon (SSSD). When a user tries to sign in to a VM using domain credentials, SSSD relays the request to an authentication provider. In this scenario, SSSD uses Azure AD DS to authenticate the request.
Open the sssd.conf file with an editor:
Comment out the line for use_fully_qualified_names as follows:
When done, save and exit the sssd.conf file using the :wq command of the editor.
To apply the change, restart the SSSD service:
Configure user account and group settings
With the VM joined to the managed domain and configured for authentication, there are a few user configuration options to complete. These configuration changes include allowing password-based authentication, and automatically creating home directories on the local VM when domain users first sign in.
Allow password authentication for SSH
By default, users can only sign in to a VM using SSH public key-based authentication. Password-based authentication fails. When you join the VM to a managed domain, those domain accounts need to use password-based authentication. Update the SSH configuration to allow password-based authentication as follows.
Open the sshd_conf file with an editor:
Update the line for PasswordAuthentication to yes:
When done, save and exit the sshd_conf file using the :wq command of the editor.
To apply the changes and let users sign in using a password, restart the SSH service:
Configure automatic home directory creation
To enable automatic creation of the home directory when a user first signs in, complete the following steps:
Open the /etc/pam.d/common-session file in an editor:
Add the following line in this file below the line session optional pam_sss.so :
When done, save and exit the common-session file using the :wq command of the editor.
Grant the ‘AAD DC Administrators’ group sudo privileges
To grant members of the AAD DC Administrators group administrative privileges on the Ubuntu VM, you add an entry to the /etc/sudoers. Once added, members of the AAD DC Administrators group can use the sudo command on the Ubuntu VM.
Open the sudoers file for editing:
Add the following entry to the end of /etc/sudoers file:
When done, save and exit the editor using the Ctrl-X command.
Sign in to the VM using a domain account
To verify that the VM has been successfully joined to the managed domain, start a new SSH connection using a domain user account. Confirm that a home directory has been created, and that group membership from the domain is applied.
Create a new SSH connection from your console. Use a domain account that belongs to the managed domain using the ssh -l command, such as contosoadmin@aaddscontoso.com and then enter the address of your VM, such as ubuntu.aaddscontoso.com. If you use the Azure Cloud Shell, use the public IP address of the VM rather than the internal DNS name.
When you’ve successfully connected to the VM, verify that the home directory was initialized correctly:
You should be in the /home directory with your own directory that matches the user account.
Now check that the group memberships are being resolved correctly:
You should see your group memberships from the managed domain.
If you signed in to the VM as a member of the AAD DC Administrators group, check that you can correctly use the sudo command:
Next steps
If you have problems connecting the VM to the managed domain or signing in with a domain account, see Troubleshooting domain join issues.
Источник