Linux with windows active directory

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 я могу отнести:

  1. Хорошую повторяемость (сравните последовательность действий этой статье с инструкцией по настройке winbind)
  2. Кэширование данных из каталога (доменный пользователь может войти на ПК, когда домен не доступен, если его учётные данные в кэше)
  3. Для PBIS не требуется формирование в каталоге AD дополнительных атрибутов пользователя
  4. PBIS понимает сайты AD и работает с контроллерами своего сайта.
  5. Большую безопасность (samba создаёт учётку компьютера с не истекающим паролем)
  6. В платной версии (если возникнет такая необходимость) PBIS агент управляем через GPO (хотя это можно и вычеркнуть. если вы не намерены её покупать)
Читайте также:  Defender джойстик драйвера windows 10

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 ;(.

Источник

How to join a Linux system to an Active Directory domain

Posted: October 13, 2020 | by Edem Afenyo

Microsoft’s Active Directory (AD) is the go-to directory service for many organizations. If you and your team are responsible for a mixed Windows and Linux environment, then you probably would like to centralize authentication for both platforms. I’ll cover how to add Linux computers to an Active Directory domain.

Active Directory and the need for centralized access management

More Linux resources

Microsoft’s Active Directory, more popularly known as AD, has held the lion’s share of the market for enterprise access management for many years now. It is used by institutions and individuals the world over to centrally control access to resources belonging to the organization. It gives you the ability to manage users, passwords, resources such as computers, and dictate who has access to what. For some of you reading this write-up, especially those who work in large institutions, you have interacted with AD before. Usually, the interaction is using one set of login credentials to log in to any workstation in the organization. That is just the tip of a large iceberg.

Imagine a collection of 40 computer systems and 70 users in a firm. Some employees run shifts while others work regular hours. Some have access to printing; others don’t. The traditional way of working is to create local user accounts on each computer a user needs to access. Imagine the workload on the end-user support team. When a user changes his password for any reason, that user has to change the password on all computers he previously had access to, to keep things in sync. In no time, there will be mayhem. Now, imagine two members of the staff resign. I do not need to tell you the monotonous work that has to be repeated any time there’s a change to the staffing or any workstations. For IT teams, this is a nightmare. Time that could be used for innovative tasks is now spent reinventing the wheel. I have not even spoken about managing access to the printers.

This is where a directory service such as Active Directory thrives. It can literally be a lifesaver. With Active Directory, each user is uniquely created as an object in a central database, with a single set of credentials. Each computer system is also created as an object. Automatically, every user can access every workstation with that same set of credentials. Any account changes that need to be made are made once at the central database. Members of staff can access the printers using the same set of credentials. The printers’ authentication mechanism can be coupled with AD to achieve that. Happy users, happy IT team.

Using groups and organizational units, access to various resources can be tailored and maintained. It gets even better. This directory can store staff phone numbers, email addresses, and can be extended to store other information. What if someone resigns? No problem. Just disable the user’s account. That person’s access to all resources is nullified on the spot. The bigger the organization, the greater the need for centralized management. It saves time; it saves emotions.

At its heart, a directory service is just an organized way of itemizing all the resources in an organization while facilitating easy access to those resources. Basically, AD is a kind of distributed database, which is accessed remotely via the Lightweight Directory Access Protocol (LDAP). LDAP is an open protocol for remotely accessing directory services over a connection-oriented medium such as TCP/IP. AD is not the only directory service based on the x.500 standard, or that can be accessed using LDAP. Other directory services include OpenLDAP and FreeIPA. However, AD is a mature Windows-based service that comes incorporated with Windows Server systems. In other words, it’s going to be the automatic winner when your organization has many Windows systems. This is one of the reasons for its ubiquity. Directory services such as FreeIPA are Linux-based and provide an excellent service for a Linux stable. When the rubber hits the road, the choice boils down to which of the two you can set up quickly, given your current environment and your team’s skill set.

Читайте также:  All users profile windows 2012

But what happens when you choose AD, and you have a few CentOS servers, and you do not want to maintain a separate set of credentials for your Linux users? That overhead is entirely avoidable. What you need to do is join the Linux servers to the AD domain, like you would a Windows server.

If that is what you need to do, then read on to find out just how to do it. It is possible to join a Windows system to a FreeIPA domain, but that is outside the scope of this article.

Pre-requisites

This article presupposes that you have at least some introductory-level experience with Active Directory, especially around user and computer account management. Aside from that, the following obvious requirements need to be met:

  • An account in AD that has the privileges necessary to join a system to the domain.
  • A Linux server (a CentOS 7 server was used for this demonstration).
  • A Domain Controller.
  • Ensure your Linux server knows how to find the domain controller via DNS.

To make this article easier on everyone, here’s a list of key details. This is how the lab I used for this write up is set up, so you should modify accordingly.

  • AD Domain Name: Hope.net
  • User account for joining the domain: fkorea (Fullname — Fiifi Korea)
  • Linux server hostname: centy2

Packages to install

For this configuration, the essential package to install is realmd . Aside from realmd , there are a host of packages that need to be installed to make this work.

Realmd provides a simplified way to discover and interact with Active Directory domains. It employs sssd to do the actual lookups required for remote authentication and other heavy work of interacting with the domain. In the interest of brevity, I won’t dwell on the other packages in the list.

However, for those interested in the details, a quick Google search should be of great help.

Realmd (interacting with the domain)

Now that all packages have been installed, the first thing to do is to join the CentOS system to the Active Directory domain. We use the realm application for that. The realm client is installed at the same time as realmd . It is used to join, remove, control access, and accomplish many other tasks. Here is the expected syntax for a simple domain join:

The space between the user account and the domain account is not a typo. By inserting the corresponding details, we get the following command:

Supply the password when the prompt appears and wait for the process to end.

Don’t let the short absence of output deceive you. There are a number of operations that go on as part of the process. You can tack on the -v switch for more verbose output. However, the best way to check if the computer is now a member of the domain is by running the realm list command. The command attempts to display the current state of the server with regard to the domain. It is a quick and dirty way to know which groups or users can access the server.

Have a look at its output:

It is also quite trivial to place the newly-created AD computer object in a specific Organizational Unit (OU) from the onset. I’ll leave that for further reading, but, as a tip, you can consult the man page. Using the realm client, you can grant or revoke access to domain users and groups. A deep dive on using realmd in a more fine-grained way is enough to make another article. However, I will not be out of order to pick out a few parameters for your attention, namely client-software and the server-software. By now, you should understand why we had to install so many packages.

To leave the domain altogether, you need two words: realm leave

Further configuration

So now that the Linux server is part of the AD domain, domain users can access the server with their usual credentials. We are done, right? Wrong. «What’s the problem?» I hear you say.

Well, for starters, this is the barebones configuration to get you up and running. But the experience is clunky, to say the least. We need to configure the service further to give it a true AD feel. It should be just like logging on to a domain-joined Windows 10 workstation.

Secondly, there is the big elephant in the room for sysadmins called Dynamic DNS Updates (DynDNS). If it is not set up correctly, we create extra overhead by having to maintain DNS records manually. For an environment that relies heavily on DNS, that could be a problem. For Windows systems, joining a system to the domain means two entries are automatically managed and maintained on the DNS server. When IP addresses change, the change is automatically reflected in DNS. This means you can change the IPs of systems without incurring the cost of manual maintenance. This will only make sense to people who already take advantage of DNS in their environments. Aside from the noticeable productivity gains of automation, it helps to have both Windows and Linux environments working the same way.

The third issue is DNS Scavenging. In an Active Directory domain, DNS is usually provided by the Domain Controllers. Every system joined to the domain has an automatic DNS entry with a corresponding IP address. This is super convenient. Automatically, at a specified interval, stale DNS records are deleted to prevent misdirected packets and also take care of deleted computer objects. This is known as scavenging, and it is not turned on by default in AD. However, if it is turned on, we need to configure it. Typically, the scavenging interval is seven days. If, after that period, there has been no update to the record, it is deleted, unless it is a static record. For Windows systems, the Dynamic Updates feature is automatically set up. However, with Linux servers, a few modifications need to be made. Without doing that, we will have services going down after a while because their records are deleted from DNS, and no one knows how to reach their component parts.

Читайте также:  Как удалить vmware player linux

Now that we know some of the potential issues we need to address, let’s take a look at some of the things we can tweak to deliver a more seamless experience to the end-user and the sysadmin.

SSSD (easier logins and dynamic updates)

sssd on a Linux system is responsible for enabling the system to access authentication services from a remote source such as Active Directory. In other words, it is the primary interface between the directory service and the module requesting authentication services, realmd . Its main configuration file is located at /etc/sssd/sssd.conf . As a matter of fact, this is the main configuration file we will modify.

Let’s have a look at its contents before configuration. Once you join the domain, it is immediately modified to contain the minimum information required for a successful logon. My file looked like this:

In order to solve all three of the problems I mentioned earlier, edit your file to look like the one below:

Most of the options are self-explanatory, and you can modify yours accordingly while we step through what some of the key options represent. More information on all the options can be obtained by checking the man page. I think it is well written. Just type man 5 sssd.conf at the command line. You can also view the man page for sssd_ad for further information.

First and foremost, the configuration file is separated into two sections. The global section, under [sssd] and the domain-specific options section, [domain/[domain name]].

The global section contains options that affect the general behavior of sssd , such as the version information and related services. One key parameter under this section is shown below:

  • default_domain_suffix — Set this to the domain name if you do not want to have to type the full user account name when logging in. Instead of having to type fkorea@hope.net always, you can just type fkorea and the password. This helps a lot when you have a long domain name.

The domain-specific section contains parameters that are specific to the domain you have joined. Key parameters are:

  • access_provider — Allows you to select a provider optimized and used for interacting with AD servers for authentication purposes. It should be set to ad . Other values that can be used here are ldap and ipa , assuming you use those directory services.
  • id_provider — Allows you to select a provider optimized and used for interacting with AD servers for identification purposes. It should be set to ad .
  • ad_hostname — This should be the fully qualified hostname of the server. It should be set if the system’s hostname is anything other than the fully qualified domain name. If this is not set and the sssd does not have access to the fully qualified hostname, dynamic updates will fail.
  • ad_domain — This should be the full domain name ( hope.net in this case).
  • cache_credentials — This enables AD users to log in when the domain controller is offline. When this is set to true, credentials are cached for a period such that authentication does not fail when the back end is offline. The period of storage is also configurable.
  • fallback_homedir — This helps you set a home directory for AD users who do not have a home directory attribute in AD. This is different from the override_home parameter that works when a home directory is set in AD for users.
  • dyndns_update — This enables dynamic DNS updates and accepts either true or false as a value. When dynamic updates are enabled, updates occur primarily under three conditions:
    • When the Linux server restarts.
    • When the provider comes online.
    • When the refresh interval is due.
  • dyndns_refresh_interval — This value is in seconds with a practical minimum of 60 seconds. It accepts integer values and has a default of 24 hours (86400s). In this example, we set it to 12 hours. If nothing else triggers an update, an update is regularly done between.
  • dyndns_update_ptr — A boolean value that specifies whether the associated PTR record is to be updated in every update cycle. PTR records are used for reverse lookups, and unless there is a good reason, this should be set to true.
  • dyndns_auth — Specifies whether the dynamic updates should be done securely or not. The setting depends on the mode accepted by AD. If AD is set to Accept Secure Updates Only, this value should be set to GSS-TSIG. If not, and you do not care for the security benefits of secure dynamic updates (despite the strong warning in AD), this value can be set to none.

Once the configuration is complete, restart sssd to apply settings immediately.

At this point, we are set. We can now login like we would at a Windows workstation or server.

Источник

Оцените статью