Как добавить ubuntu в домен windows

Содержание

Введение

Зачастую возникает необходимость ввести Linux-машину в существующий домен Windows. Например, чтобы сделать файловый сервер с помощью Samba. Сделать это очень просто, для этого вам понадобятся клиент Kerberos, Samba и Winbind.

Перед установкой желательно обновиться:

sudo aptitude update
sudo aptitude upgrade

Установить всё это добро можно командой:

sudo aptitude install krb5-user samba winbind 

Также может понадобиться установить следующие библиотеки:

sudo aptitude install libpam-krb5 libpam-winbind libnss-winbind

Либо, если вы используете Ubuntu Desktop, те же пакеты можно поставить через менеджер пакетов Synaptic.

Далее вам потребуется настроить все вышеперечисленные инструменты для работы с вашим доменом. Допустим, вы хотите войти в домен DOMAIN.COM, доменконтроллером которого является сервер dc.domain.com с IP адресом 192.168.0.1. Этот же сервер является и первичным DNS сервером домена. Кроме того допустим у вас есть второй доменконтроллер1), он же DNSdc2.domain.com с IP 192.168.0.2. Ваш же компьютер будет называться smbsrv01.

Настройка DNS

Для начала необходимо изменить настройки DNS на вашей машине, прописав в качестве DNS сервера доменконтроллер2) и в качестве домена поиска — нужный домен.

Если у вас статический IP-адрес, то в Ubuntu Desktop это можно сделать через Network Manager, в Ubuntu Server необходимо изменить содержимое файла /etc/resolv.conf на примерно такое:

domain domain.com
search domain.com
nameserver 192.168.0.1
nameserver 192.168.0.2

В современных дистрибутивах файл resolv.conf создается автоматически и править вручную его не нужно.
Для получение нужного результата нужно добавить необходимые изменения в файл: /etc/resolvconf/resolv.conf.d/head
Данные которые будут добавлены в него, будут автоматически вставлены в файл /etc/resolv.conf

Если IP-адрес динамический и присваивается DHCP сервером то после перезагрузки resolv.conf может формироваться «неправильный» resolv.conf’ , например присутствует только один nameserver 192.168.0.1 и не указаны domain и search. Нужно отредактировать /etc/dhcp/dhclient.conf. Чтобы появились записи domain и search нужно убрать комментарий перед строкой supersede domain-name, и вписать свой домен:

supersede domain-name "domain.com";

Чтобы добавить еще один nameserver нужно убрать комментарий перед prepend domain-name-servers и указать ip сервера:

prepend domain-name-servers 192.168.0.2;

Для применения изменений остается перезапустить службу:

/etc/init.d/networking restart

Теперь убедитесь, что вы задали нужное имя компьютера в файле /etc/hostname:

smbsrv01

Кроме того необходимо отредактировать файл /etc/hosts так, чтобы в нём была запись с полным доменным именем компьютера и обязательно коротким именем хоста, ссылающаяся на один из внутренних IP:

# Имена этого компьютера
127.0.0.1	localhost
127.0.1.1	smbsrv01.domain.com	smbsrv01

Сразу нужно проверить что нормально пингуется наш контроллер домена, по короткому и полному имени, чтобы в будушем не получать ошибки что контроллер домена не найден:

ping dc
ping dc.domain.com

Не обязательно, но если вы что-то поменяете — перезагрузите компьютер для применения изменений.

Настройка синхронизации времени

Далее необходимо настроить синхронизацию времени с доменконтроллером. Если разница будет более 5 минут мы не сможем получить лист от Kerberos.
Для единовременной синхронизации можно воспользоваться командой:

sudo net time set dc

Если в сети существует сервер точного времени, то можно воспользоваться им или любым публичным:

ntpdate ntp.mobatime.ru

Автоматическая же синхронизация настраивается с помощью ntpd, это демон будет периодически выполнять синхронизацию. Для начала его необходимо установить:

sudo aptitude install ntp

Теперь исправьте файл /etc/ntp.conf, добавив в него информацию о вашем сервере времени:

# You do need to talk to an NTP server or two (or three).
server dc.domain.com

После чего перезапустите демон ntpd:

sudo /etc/init.d/ntp restart

Теперь пора настраивать непосредственно взаимодействие с доменом.

Настройка авторизации через Kerberos

Начнём с настройки авторизации в домене через протокол Kerberos. Вам потребуется изменить файл /etc/krb5.conf. В общем случае он выглядит так:

[libdefaults]
	default_realm = DOMAIN.COM
	kdc_timesync = 1
	ccache_type = 4
	forwardable = true
	proxiable = true
	v4_instance_resolve = false
	v4_name_convert = {
		host = {
			rcmd = host
			ftp = ftp
		}
		plain = {
			something = something-else
		}
	}
	fcc-mit-ticketflags = true

[realms]
	DOMAIN.COM = {
		kdc = dc
		kdc = dc2
		admin_server = dc
		default_domain = DOMAIN.COM
	}

[domain_realm]
	.domain.com = DOMAIN.COM
	domain.com = DOMAIN.COM
[login]
	krb4_convert = false
	krb4_get_tickets = false

Вам, конечно, нужно изменить domain.com на ваш домен и dc и dc2 на ваши доменконтроллеры. Кстати, возможно вам понадобится написать полные имена доменконтроллеров dc.domain.com и dc2.domain.com. Поскольку у меня прописан домен поиска в DNS, то мне это делать не нужно.

Обратите особое внимание на регистр написания имени домена — везде, где домен написан в верхнем регистре, его обязательно нужно писать именно в верхнем регистре. Иначе волшебным образом ничего может не заработать.

Это не все возможные опции настройки Kerberos, только основные. Однако их обычно достаточно.

Теперь настало время проверить, что мы можем авторизоваться в домене. Для этого выполните команду

kinit username@DOMAIN.COM

Вместо username естественно стоит вписать имя существующего пользователя домена.

Имя домена необходимо писать заглавными буквами!

Если вы не получили никаких ошибок — значит вы настроили всё верно и домен отдаёт вам билет Kerberos. Кстати, некоторые распространённые ошибки перечислены чуть ниже.

Убедиться в том, что билет получен, можно выполнив команду

klist

Удалить все билеты (они вам вообще говоря не нужны) можно командой

kdestroy

Итак, будем считать, что авторизацию вы настроили, пора настроить непосредственно вход в домен, об этом после списка распространённых ошибок kinit.

Распространённые ошибки kinit

kinit(v5): Clock skew too great while getting initial credentials

Это значит, что у вашего компьютера не синхронизировано время с доменконтроллером (см. выше).

kinit(v5): Preauthentication failed while getting initial credentials

Вы ввели неверный пароль.

kinit(v5): KDC reply did not match expectations while getting initial credentials

Самая странная ошибка. Убедитесь, что имя realm в krb5.conf, а так же домен в команде kinit введены большими буквами:

DOMAIN.COM = {
# ...
kinit username@DOMAIN.COM
kinit(v5): Client not found in Kerberos database while getting initial credentials

Указанного пользователя не существует в домене.

Настройка Samba и вход в домен

Для того, чтобы войти в домен, необходимо прописать правильные настройки в файле /etc/samba/smb.conf. На данном этапе вас должны интересовать только некоторые опции из секции [global]. Ниже — пример части файла конфигурации Samba с комментариями по поводу значения важных параметров:

[global]
   # Эти две опции нужно писать именно в заглавном регистре, причём workgroup без
   # последней секции после точки, а realm - полное имя домена 
   workgroup = DOMAIN
   realm = DOMAIN.COM

   # Эти две опции отвечают как раз за авторизацию через AD
   security = ADS
   encrypt passwords = true
   # Просто важные 
   dns proxy = no 
   socket options = TCP_NODELAY

   # Если вы не хотите, чтобы самба пыталась при случае вылезти в лидеры в домене или рабочей группе,
   # или даже стать доменконтроллером, то всегда прописывайте эти пять опций именно в таком виде
   domain master = no
   local master = no
   preferred master = no
   os level = 0
   domain logons = no

   # Отключить поддержку принтеров
   load printers = no
   show add printer wizard = no
   printcap name = /dev/null
   disable spoolss = yes

После того, как вы отредактируете smb.conf выполните команду

testparm

Она проверит вашу конфигурацию на ошибки и выдаст суммарную сводку о нём:

# testparm
Load smb config files from /etc/samba/smb.conf
Loaded services file OK.
Server role: ROLE_DOMAIN_MEMBER
Press enter to see a dump of your service definitions

Как видно мы задали правильные параметры для того, чтобы наш компьютер стал членом домена. Теперь пора попытаться непосредственно войти в домен. Для этого введите команду:

net ads join -U username -D DOMAIN

И в случае успеха вы увидите что-то похожее на:

# net ads join -U username -D DOMAIN
Enter username's password:
Using short domain name -- DOMAIN
Joined 'SMBSRV01' to realm 'domain.com'

Используемые параметры команды net

-U username%password: Обязательный параметр, вместо username необходимо подставить имя пользователя с правами администратора домена, и указать пароль.

-D DOMAIN: DOMAIN — собственно сам домен, домен можно и не указывать, но лучше всё же это всегда делать — хуже не будет.

-S win_domain_controller: win_domain_controller, можно не указывать, но бывают случаи когда автоматически сервер не находит контроллер домена.

createcomputer=«OU/OU/…» : В AD часто используется OU (Organizational Unit), есть в корне домена OU = Office, в нем OU = Cabinet, чтобы сразу добавить в нужный можно указать так: sudo net ads join -U username createcomputer=«Office/Cabinet».

Если больше никаких сообщений нет — значит всё хорошо. Попробуйте попинговать свой компьютер по имени с другого члена домена, чтобы убедиться, что в домене всё прописалось так, как надо.

Так же можно набрать команду:

net ads testjoin

Если все хорошо, можно увидеть:

#net ads testjoin
Join is OK

Но иногда после сообщения о присоединении к домену выдаётся ошибка наподобие3):

DNS update failed!

Это не очень хорошо, и в этом случае рекомендуется ещё раз прочитать раздел про настройку DNS чуть выше и понять, что же вы сделали не так. После этого нужно удалить компьютер из домена и попытаться ввести его заново. Если вы твердо уверены, что всё настроили верно, а DNS всё равно не обновляется, то можно внести вручную запись для вашего компьютера на ваш DNS сервер и всё будет работать. Конечно, если нет никаких других ошибок, и вы успешно вошли в домен. Однако лучше всё же разберитесь, почему DNS не обновляется автоматически. Это может быть связано не только с вашим компьютером, но и с некорректной настройкой AD.

Прежде чем выяснять, почему же не обновляется DNS, не забудьте перезагрузить компьютер после введения в домен! Вполне возможно, что это решит проблему.

Если всё прошло без ошибок, то поздравляем, вы успешно вошли в домен! Можете заглянуть в AD и убедиться в этом. Кроме того хорошо бы проверить, что вы можете видеть ресурсы в домене. Для этого установите smbclient:

sudo aptitude install smbclient

Теперь можно просматривать ресурсы компьютеров домена. Но для этого нужно иметь билет kerberos, т.е. если мы их удалили, то получаем опять через kinit (см. выше). Посмотрим какие ресурсы предоставлены в сеть компьютером workstation:

smbclient -k -L workstation

Вы должны увидеть список общих ресурсов на этом компьютере.

Настройка Winbind

Если вам необходимо как-либо работать с пользователями домена, например, настраивать SMB-шары с разграничением доступа, то вам понадобится кроме самой Samba ещё и Winbind — специальный демон, служащий для связи локальной системы управления пользователями и группами Linux с сервером Active Directory. Проще говоря Winbind нужен, если вы хотите видеть пользователей домена на своём компьютере с Ubuntu.

Winbind позволяет спроецировать всех пользователей и все группы AD в вашу Linux систему, присвоив им ID из заданного диапазона. Таким образом вы сможете назначать пользователей домена владельцами папок и файлов на вашем компьютере и выполнять любые другие операции, завязанные на пользователей и группы.

Для настройки Winbind используется всё тот же файл /etc/samba/smb.conf. Добавьте в секцию [global] следующие строки:

   # Опции сопоставления доменных пользователей и виртуальных пользователей в системе через Winbind.
   # Диапазоны идентификаторов для виртуальных пользователей и групп.
   idmap uid = 10000 - 40000
   idmap gid = 10000 - 40000
   # Эти опции не стоит выключать.
   winbind enum groups = yes
   winbind enum users = yes
   # Использовать домен по умолчанию для имён пользователей. Без этой опции имена пользователей и групп
   # будут использоваться с доменом, т.е. вместо username - DOMAIN\username.
   # Возможно именно это вам и нужно, однако обычно проще этот параметр включить. 
   winbind use default domain = yes
   # Если вы хотите разрещить использовать командную строку для пользователей домена, то
   # добавьте следующую строку, иначе в качестве shell'а будет вызываться /bin/false
   template shell = /bin/bash
   # Для автоматического обновления билета Kerberos модулем pam_winbind.so нужно добавить строчку
   winbind refresh tickets = yes

Параметры :

idmap uid = 10000 — 40000

idmap gid = 10000 — 40000

в новых версиях Samba уже устарели и при проверке конфига самбы с помощью testparm
будет выдваться предупреждение:

WARNING: The «idmap uid» option is deprecated

WARNING: The «idmap gid» option is deprecated

Чтобы убрать предупреждения нужно заменить эти строки на новые:

idmap config * : range = 10000-20000

idmap config * : backend = tdb

Теперь перезапустите демон Winbind и Samba в следующем порядке:

sudo /etc/init.d/winbind stop
sudo smbd restart
sudo /etc/init.d/winbind start 

Запускаем

sudo testparm

Смотрим есть ли ошибки или предупреждения, если появится:

«rlimit_max: rlimit_max (1024) below minimum Windows limit (16384)»

Без перезагрузки можно устранить так:

ulimit -n 16384

Для сохранения после перезагрузки отредактировать файл /etc/security/limits.conf

# Добавить в конец файла строки:
*               -    nofile            16384
root            -    nofile            16384

После перезапуска проверьте, что Winbind установил доверительные отношения с AD командой:

# wbinfo -t
checking the trust secret for domain DCN via RPC calls succeeded

А так же, что Winbind увидел пользователей и группы из AD командами4):

wbinfo -u
wbinfo -g

Эти две команды должны выдать список пользователей и групп из домена соответственно. Либо с префиксом DOMAIN\, либо без него — в зависимости от того, какое значение вы указали параметру «winbind use default domain» в smb.conf.

Итак, Winbind работает, однако в систему он ещё не интегрирован.

Добавление Winbind в качестве источника пользователей и групп

Для того, чтобы ваша Ubuntu прозрачно работала с пользователями домена, в частности, чтобы вы могли назначать пользователей домена владельцами папок и файлов, необходимо указать Ubuntu использовать Winbind как дополнительный источник информации о пользователях и группах.

Для этого измените две строчки в файле /etc/nsswitch.conf:

passwd:         compat
group:          compat

добавив к ним в конец winbind:

passwd:         compat winbind
group:          compat winbind

также рекомендую привести строку files в файле /etc/nsswitch.conf к виду:

files:          dns mdns4_minimal[NotFoud=return] mdns4

ubuntu server 14.04, файл /etc/nsswitch.conf не содержал строку
«files: dns mdns4_minimal[NotFoud=return] mdns4»
вместо неё было:
«hosts: files mdns4_minimal [NOTFOUND=return] dns wins»
Которую я преобразовал в:
«hosts: dns mdns4_minimal[NotFoud=return] mdns4 files»
после чего всё заработало

Теперь проверьте, что Ubuntu запрашивает у Winbind информацию о пользователях и группах, выполнив

getent passwd
getent group 

Первая команда должна вам вернуть всё содержимое вашего файла /etc/passwd, то есть ваших локальных пользователей, плюс пользователей домена с ID из заданного вами в smb.conf диапазона. Вторая должна сделать тоже самое для групп.

Теперь вы можете взять любого пользователя домена и сделать его, например, владельцем какого-нибудь файла.

Авторизация в Ubuntu через пользователей домена

Несмотря на то, что все пользователи домена фактически стали полноценными пользователями системы (в чём можно убедиться, выполнив последние две команды из предыдущего раздела), зайти ни под кем из них в систему всё ещё нельзя. Для включения возможности авторизации пользователей домена на компьютере с Ubuntu необходимо настроить PAM на работу с Winbind.

Он-лайн авторизация

Для Ubuntu 10.04 и выше добавьте всего одну строку в файле /etc/pam.d/common-session, т.к. PAM и так неплохо справляется с авторизацией:

session  optional  pam_mkhomedir.so skel=/etc/skel/ umask=0077

Для Ubuntu 13.10 чтобы появилось поле ручного ввода логина необходимо в любой файл из папки /etc/lightdm/lightdm.conf/ снизу добавить строку:

greeter-show-manual-login=true

Для Ubuntu 9.10 и ниже придется редактировать несколько файлов (но никто не запрещает использовать этот способ и в 10.04 — он тоже работает):

Последовательность строк в файлах имеет значение!

/etc/pam.d/common-auth

auth        required      pam_env.so
auth        sufficient    pam_unix.so likeauth nullok try_first_pass
auth        sufficient    pam_winbind.so use_first_pass krb5_auth krb5_ccache_type=FILE
auth        required      pam_deny.so

/etc/pam.d/common-account

account     sufficient    pam_winbind.so
account     required      pam_unix.so

/etc/pam.d/common-session

session     optional      pam_mkhomedir.so skel=/etc/skel/ umask=0077
session     optional      pam_ck_connector.so nox11
session     required      pam_limits.so
session     required      pam_env.so
session     required      pam_unix.so

/etc/pam.d/common-password

password    sufficient    pam_unix.so try_first_pass use_authtok nullok sha512 shadow
password    sufficient    pam_winbind.so
password    required      pam_deny.so

И, наконец, необходимо перенести запуск Winbind при загрузке системы после всех остальных служб (по умолчанию он запускается с индексом 20). Для этого в терминале выполните следующую команду:

sudo bash -c "for i in 2 3 4 5; do mv /etc/rc$i.d/S20winbind /etc/rc$i.d/S99winbind; done"

Что эквивалентно запуску для каждого уровня (в примере — 4) команды:

mv /etc/rc4.d/S20winbind /etc/rc4.d/S99winbind

В некоторых случаях winbind может иметь иной уровень запуска (например, S02winbind). Поэтому сначала проверьте имена файлов, вполнив команду «ls /etc/rc{2,3,4,5}.d/ | grep winbind» (без кавычек).

Готово, все настройки завершены. Перезагружайтесь и пытайтесь войти с учетной записью пользователя домена.

Офф-лайн авторизация

Часто возникает ситуация, когда домен-контроллер недоступен по различным причинам — профилактика, отключение света или вы принесли ноутбук домой и хотите поработать. В этом случае для Winbind можно настроить кэширование учетных записей пользователей домена. Для этого необходимо сделать следующее.
Добавьте в секцию [global] файла /etc/samba/smb.conf следующие строки:

[global]
   # Возможность оффлайн-авторизации при недоступности доменконтроллера
   winbind offline logon = yes
   # Период кэширования учетных записей, по умолчанию равен 300 секунд
   winbind cache time = 300
   # Необязательная настройка, но избавляет от нудных пауз, указываем контроллер домена dc, 
   # можно указать и ip, но это является плохим тоном
   password server = dc

Обычно этого достаточно. Если же возникают ошибки, то необходимо создать файл /etc/security/pam_winbind.conf со следующим содержанием5):

Внимание! При использовании советов ниже может возникать совершенно случайная ошибка «Сбой аутентификации»! Поэтому все что Вы делаете, Вы делаете на свой страх и риск!

#
# pam_winbind configuration file
#
# /etc/security/pam_winbind.conf
#
[global]
  # turn on debugging
  debug = no
  # request a cached login if possible
  # (needs "winbind offline logon = yes" in smb.conf)
  cached_login = yes
  # authenticate using kerberos
  krb5_auth = yes
  # when using kerberos, request a "FILE" krb5 credential cache type
  # (leave empty to just do krb5 authentication but not have a ticket
  # afterwards)
  krb5_ccache_type = FILE
  # make successful authentication dependend on membership of one SID
  # (can also take a name)
  ;require_membership_of =
  silent = yes

Файл /etc/pam.d/gnome-screensaver в таком случае принимает вид:

auth    sufficient      pam_unix.so nullok_secure
auth    sufficient      pam_winbind.so use_first_pass
auth    required        pam_deny.so

А также изменяется файл /etc/pam.d/common-auth:

auth    optional        pam_group.so
auth    sufficient      pam_unix.so nullok_secure  use_first_pass
auth    sufficient      pam_winbind.so use_first_pass
auth    required        pam_deny.so

Ссылки

Sometimes you’ll be needing a setup that includes both Windows and Linux based machines for managing the infrastructure and data processing. Although joining a Windows machine to an Active Directory domain is fairly simple, joining a Linux based systems requires a little more effort. This posts focusses on joining Ubuntu based nodes (Desktop or Server systems) to a Windows Active Directory domain for simplified management and a unified logon experience.

Turns out that there are a couple of way of accomplishing this task. It’s not really that straightforward as it is with Windows but once you get the right tools and know what files to edit it’s really not that hard. With this post I want to share my personal experiences and show you step-by-step on how to add a Linux based host to a Windows Active Directory.

System Security Services Daemon

I’ve tried a couple of options/packages for joining a Linux machine into a Windows based Active Directory domain, but in the end, for me, using the System Security Services Daemon (SSSD) was the most effective way to accomplish my task at hand. The SSSD is like the intermediary that helps you to configure the system without you needing to know what files you need to edit (Although it can be very useful). The other benefit that I discovered is that it’s available on all major distributions, like RedHat or Ubuntu. So What I will be describing here will be useful in many situations. Let’s dive in.

Lab infrastructure

My lab setup is straightforward. Two Domain Controllers, named “LAB-DC01 (192.168.66.2)” & “LAB-DC02 (192.168.66.3)” in the “water.lab” domain. Next to the ADDC role both machines also hosts the DNS role. The client computer is an Ubuntu 22.04 machine, named “Ubuntu”, and is configured to use the DNS server on “LAB-DC01”. I’ve checked connectivity to “LAB-DC01” with a simple ICMP ping and name resolution with NSLookup. Both work as expected.

Hostname

First thing that we need to check before joining the machine is the hostname. Although Ubuntu can handle long hostnames, a Windows machine is restricted to 15 characters max because of the legacy protocol NetBios. In turn that means that our Ubuntu client machines is also restricted to the same length for it’s hostname. Check the current hostname with this command:

In my case this resulted in the following output:

In case you need to change the name, use the following command and reboot afterwards:

sudo hostnamectl set-hostname <hostname.domain.suffix>

Hint! This command will not change the hostname in the “/etc/hosts” file.

Tip! Changing the hostname can also be done by editing these files, reboot afterwards.

sudo nano /etc/hostname
sudo nano /etc/hosts

Networking

Although it is preferred to have DHCP handle the assignment of the IP address, Gateway and DNS servers, it can sometimes be necessary to assign these settings manually, for example when you need a static IP address or there’s no DHCP server available. Ubuntu uses “Netplan” to handle network configurations that are stored in a YAML file in the directory “/etc/netplan“. Open the present YAML file and edit the file based on your requirements or take the following configuration as an example:

sudo nano /etc/netplan/01-network-manager-all.yaml

01-network-manager-all.yaml content:

# Let NetworkManager manage all devices on this system
network:
 version: 2
 renderer: NetworkManager
 ethernets:
  enp6s18:
   dhcp4: no
   dhcp6: no
   addresses: [192.168.66.98/24]
   routes:
   - to: default
     via: 192.168.66.1
     metric: 100
   nameservers:
    addresses: [192.168.66.2, 192.168.66.3]
    search: [water.lab]

Pay special attention to the indentation of the file as YAML is very picky to how the file is formatted. There are a few things that you probably want to change. First thing is the property “enp6s18“. This represents the name of my network adapter, yours could be named differently. There are multiple ways to get the name, I use the following command:

In the output, the latter part of the line with your IP address has the name of your network adapter.

Another property is the default gateway. In the version of “Netplan” that ships with Ubuntu 22.04 the default route is configured in the “routes” property. Editing the value after “via” changes the default route. Use the following command to get the current configured default route:

Last but certainly not least let’s focus on name resolution, also know as DNS. Without it we can’t do a whole lot, certainly not join a domain. The property that needs to be changed is “nameservers – addresses“. To get the current values, use the command:

Once you’re happy with the netplan configuration, you need to apply it. This can simply be done by executing the command:

if no errors are visible on the screen the configuration is successfully applied. Use the previous commands to verify the configuration.

Timing is everything

Using Kerberos authentication relies heavily on the correct time being set at both ends. It should always be within a maximum of 5 minutes difference between the two entities trying to authenticate. On Ubuntu, “timesyncd” is responsible for all thing related with time. First we need to point the client to the closest time source. Usually this is the DC that will provide the correct time, but any time source will do, as long as everything is in sync. Edit the following file to add the NTP source as displayed in the example:

sudo nano /etc/systemd/timesyncd.conf

Hint! setting the value for “RootDistanceMaxSec” prevents the “Server has too large root distance. Disconnecting” error message and the time service not syncing.

Set the NTP sync to true

sudo timedatectl set-ntp on

Bash

Restart the service

sudo systemctl restart systemd-timesyncd.service

Bash

Force Sync

sudo timedatectl --adjust-system-clock

Bash

Check status

timedatectl status

Bash

Required packages

First thing we need to do is install all the appropriate packages. This post is focus on Ubuntu 22.04, but it’s almost the same on other distributions that use apt (or yum) as their package manager. Open up a terminal, gain root privileges, install these packages:

  • realmd
  • sssd
  • sssd-tools
  • libnss-sss
  • libpam-sss
  • krb5-user
  • adcli
  • samba-common-bin
sudo apt -y install realmd sssd sssd-tools libnss-sss libpam-sss krb5-user adcli samba-common-bin

Bash

Auto create the home directory

On Ubuntu every user that does an interactive logon to the system needs a home directory. For domain users this needs to be set before a user is able to successfully logon and start working. You can accomplish this tasks in two ways, I’ll show them both.

First up is a guided way of doing things. In a terminal type:

this will bring up a dialog screen for editing the configuration file “/etc/pam.d/common-session“.

Scroll down up to the point where it states :”Create home directory on login“. Use the space bar to select, tab to “OK” and hit enter. If you want to do it in a more scriptable way use the following command-line option:

sudo pam-auth-update --enable mkhomedir

Bash

Hint! The information is stored in the file: “/etc/pam.d/common-session“.

session optional pam_mkhomedir.so

Bash

Testing Active Directory access

Now that the all the packages have been installed and configured with the appropriate settings, we’re ready to test the setup. Ubuntu has a few very useful tools to see if Kerberos authentication will succeed. Use the following set of commands to test authentication:

Discover the domain

realm discover water.lab

Bash

Get a Kerberos ticket for the user Administrator

kinit administrator

Bash

Display the Kerberos ticket

klist

Bash

Destroy the Kerberos ticket

kdestroy

Bash

The reason I destroy the ticket first is that it will otherwise be used during the domain join that I’ll show you next. The domain account used for joining the domain isn’t necessarily the same account as testing the authentication. Besides it’s also a good way to learn all the available tools.

Joining the Active Directory domain

And now the part we’ve all been waiting for, joining the domain. Actually this is the easy part, if everything is configured as it should, the domain join should be fairly easy to accomplish. Simply run the following command in a terminal:

sudo realm join --verbose --user=administrator water.lab

Bash

If there are no errors displayed at the end, the machine is successfully joined to the domain! On a Windows PC open “Active Directory Users and Computers” and check if a computer object is created.

Logon with Active Directory credentials

before we login, wouldn’t it be cool to only use the name of the user instead of the entire “User Principal Name” (UPN)? So instead of “michael@water.lab“, only “michael” as the username? There is a neat little trick for that. Run the following command to edit the “System Security Services Daemon” configuration file:

sudo nano /etc/sssd/sssd.conf

Bash

Hint! The “sssd.conf” file is automatically created after the domain join. It will not exist before joining the machine to the domain.

set the line “use_fully_qualified_names” to “False“.

Hint! You need to reboot or restart the sssd deamon before this setting is in effect.

sudo systemctl restart sssd

Bash

As a final step, on the logon screen, click the option: “Not listed“, and fill in your credentials. If everything is configured according to plan, you should be able to logon and a home directory is automatically created for the user.

To verify if everything has gone successful, open up a terminal and issue the “klist” command. This will display your ticket granting ticket (TGT), also known as the key to your kingdom.

That’s it for this post. Next up will be some more advanced permissions and configuration.

Время на прочтение3 мин

Количество просмотров117K

Была необходимость ввести в домен Windows машину с Ubuntu. Для этих целей обычно используют Samba и Winbind. Но возможен альтернативный вариант с sssd, краткое руководство по нему ниже.

Для примера будем использовать:

Домен = contoso.com
Контроллер домена = dc.contoso.com

Запускаем терминал Ubuntu:

1. Переключаемся под рута

sudo -i

2. Устанавливаем необходимые пакеты

apt install sssd heimdal-clients msktutil

3. Редактируем /etc/krb5.conf, в качестве отступов используется табуляция

[libdefaults]
	default_realm = CONTOSO.COM

[realms]
	CONTOSO.COM = {
		kdc = DC 
		admin_server = dc.contoso.com
		default_domain = contoso.com
	}

[login]
	krb4_convert = true
	krb4_get_tickets = false
	
[domain_realm]
        .contoso.com = CONTOSO.COM
        contoso.com = CONTOSO.COM

4. Редактируем файл /etc/hosts, указываем FQDN для данного хоста:

127.0.0.1       localhost
127.0.1.1       <hostname>.contoso.com  <hostname>

5. Пробуем получить Kerberos ticket от имени администратора домена:

root@ubuntu:~# kinit YourDomainAdmin
YourDomainAdmin@CONTOSO.COM's Password:

Проверяем:

root@ubuntu:~# klist
Credentials cache: FILE:/tmp/krb5cc_0
        Principal: YourDomainAdmin@CONTOSO.COM

  Issued                Expires               Principal
Dec  1 15:08:27 2018  Dec  2 01:08:22 2018  krbtgt/CONTOSO.COM@CONTOSO.COM

Если тикет получен успешно, то теперь можно сгенерировать Kerberos principals для данного хоста, регистр важен:

msktutil -c -b 'CN=YourComputersOU' -s HOST/HOSTNAME.contoso.com -k /etc/sssd/HOSTNAME.keytab --computer-name HOSTNAME --upn HOSTNAME$ --server dc.contoso.com —user-creds-only

msktutil -c -b 'CN=YourComputersOU' -s HOST/HOSTNAME -k /etc/sssd/HOSTNAME.keytab --computer-name HOSTNAME --upn HOSTNAME$ --server dc.contoso.com --user-creds-only

Сейчас наш хост должен отобразиться в списке компьютеров в каталоге. Если все так — удаляем полученный Kerberos ticket:

kdestroy

6. Создаем файл /etc/sssd/sssd.conf со следующим содержимым:

[sssd]

services = nss, pam
config_file_version = 2
domains = contoso.com


[nss]

entry_negative_timeout = 0
debug_level = 3


[pam]

debug_level = 3


[domain/contoso.com]

debug_level = 3

ad_domain = contoso.com
ad_server = dc.contoso.com
enumerate = false

id_provider = ad
auth_provider = ad
chpass_provider = ad
access_provider = simple
simple_allow_groups = users #каким группам разрешено логиниться, через запятую. Есть ограничение — названия групп должны быть с маленькой буквы.
ldap_schema = ad
ldap_id_mapping = true
fallback_homedir = /home/%u
default_shell = /bin/bash
ldap_sasl_mech = gssapi
ldap_sasl_authid = <HOSTNAME>$
ldap_krb5_init_creds = true
krb5_keytab = /etc/sssd/<HOSTNAME>.keytab

Описание параметров конфигфайла sssd можно посмотреть тут

Устанавливаем права доступа для файла sssd.conf:

chmod 600 /etc/sssd/sssd.conf

Перезапускаем SSSD service

service sssd restart

7. Редактируем настройки PAM

Плохое решение:

редактируем файл /etc/pam.d/common-session, после строки

session required        pam_unix.so

добавляем строку

session required pam_mkhomedir.so skel=/etc/skel umask=0022

Хорошее решение:

переопределить параметры через системные настройки PAM, вызываем

pam-auth-update

и отмечаем пункты sss auth и makehomdir. Это автоматически добавит
строчку выше в common-session и она не будет перезатерта при обновлении системы.

Теперь мы можем логиниться на машине доменными пользователями, которым разрешен вход.

P.S.: Можно дать права на использование sudo доменным группам. Используя visudo, редактируем файл /etc/sudoers, или лучше, как рекомендует maxzhurkin и iluvar, создаем новый файл в /etc/sudoers.d/ и редактируем его

visudo -f /etc/sudoers.d/ваш_файл

добавляем требуемую группу — например, Domain Admins (если в названии группы есть пробелы — их необходимо экранировать):

%Domain\ Admins ALL=(ALL) ALL

P.S.S.: Спасибо gotch за информацию о realmd. Очень удобно — если не нужны специфические настройки, то ввод машины в домен занимает, по сути, три (как заметил osipov_dv четыре) команды:

1. Устанавливаем нужные пакеты:

sudo apt install realmd samba-common-bin samba-libs sssd-tools krb5-user adcli

2. Редактируем файл /etc/hosts, указываем FQDN для данного хоста:

127.0.0.1       localhost
127.0.1.1       <hostname>.contoso.com  <hostname>

3. Проверяем, что наш домен виден в сети:

realm discover contoso.com

4. Вводим машину в домен:

sudo realm --verbose join contoso.com -U YourDomainAdmin --install=/

5. Редактируем настройки PAM

sudo pam-auth-update

Дополнительный плюс данного варианта — сквозная авторизация на файловых ресурсах домена.

Для того чтоб при входе не указывать дополнительно к логину домен, можно добавить суффикс по умолчанию. В файле /etc/sssd/sssd.conf, в блоке [sssd] добавляем строку:

default_domain_suffix = contoso.com

In this short guide we will learn how to connect machine with Ubuntu (20.04) installation to Active Directory.

Before we begin

Domain data:

I already set Active Directory on Windows Server 2019 Standard.

Domain name: winlin.local

Domain Controller name: WinLinDC

Domain Controller IP address: 10.0.0.31/24

Active Directory DNS IP: 10.0.0.31/24

I installed DNS on the domain controller itself.

I also created domain user named: zeljko.m@winlin.local

Ubuntu client data:

I used Ubuntu 20.04 as a client for this guide.

Machine name: winlinubcl2

Machine IP address: 10.0.0.34

Prerequisites

Updates

First, we will start with updating

sudo apt update -y

Hostname and DNS

Since we want to join Ubuntu machine (name winlinubcl2) to Windows domain named winlin.local, we need to change Ubuntu machine name to match active directory (AD) naming…

sudo hostnamectl set-hostname winlinubcl2.winlin.local

We will check machine name by entering

hostnamectl

For the DNS part, like with Windows client machine you wish to join to AD – linux machines also need to have domain controller (or separate DNS server for domain, if configured) IP address under DNS.

In my case, DNS server IP is same as my domain controller ip – 10.0.0.31.

There are a couple of ways to do this.

If your Linux machine is getting IP address and DNS from DHCP server, make sure that you are in the same network, and that DNS IP is already in domain or on domain controller.

I’m doing this manually on Ubuntu 20.04 that has GUI.So this is how my settings look like. I set everything manually.

If you are doing this on a machine without GUI, only in shell you will have to do it through netplan.

Again, check your IP settings by entering

ip a

Then check DNS settings by entering

systemd-resolve --status | grep Current

and you can also check default gateway by typing in

ip r

If there is a need to change IP and DNS settings, do following

First we need to find out how your netplan file is named. To find out type following in

ls -la /etc/netplan

My file is named 01-network-manager-all.yaml. Your may be named differently, so mark that.

Next, we need to edit that file (change 01-network-mananger-all.yaml to your filename.

sudo nano /etc/netplan/01-network-manager-all.yaml

You should enter something like this. Be very careful about indentations, because yaml files are very picky on that front.

If you want to check your indentation to be sure it is ok, you can install tool like yamllint.

network:
  ethernets:
    ens33:
      addresses:
      - 10.0.0.34/24
      gateway4: 10.0.0.1
      nameservers:
        addresses:
        - 10.0.0.31
  version: 2

To apply changes type in

sudo netplan apply

Ok ,that is it for the hostnames and DNS, I like to reboot machine after these settings to be sure everything is fine.

Installation

We will now install all required packages for our domain join adventure

sudo apt update -y

sudo apt -y install realmd libnss-sss libpam-sss sssd sssd-tools adcli samba-common-bin oddjob oddjob-mkhomedir packagekit

Discover domain

We will now check if we can discover our windows domain. Change winlin.local for your domain name.

sudo realm discover winlin.local

The information we got back is good, we can proceed further.

Add Ubuntu machine to Active Directory

Finally, we will join our Ubuntu machine to our windows domain.

Change Administrator if the account name of your domain admin is different. Change winlin.local to your domain name.

The command is

sudo realm join -U Administrator winlin.local

If everything went ok, you will be asked for your domain admin password, and that will be it.

Let’s check if the authentication is working and we can get id of domain users. I will use domain user named zeljko.m@winlin.local, change that for your domain user and domain name.

id zeljko.m@winlin.local

If we go to the Windows Server 2019 that serves as a domain controller for winlin.local domain, under Users and Computers in Computers container we can see that winLinUbCL2 machine is added to the domain. That is great.

Before we do a first login from Ubuntu to Windows Domain

First, we will set creation of home directories for domain users.

We need to edit

sudo nano /etc/pam.d/common-session

and enter following to the end of the file

session optional pam_mkhomedir.so skel=/etc/skel umask=077

Optionally, you can set your system to login only using name without domain part. So, I could login to my Ubuntu install by only using zeljko.m instead of zeljko.m@winlin.local.

If you wish to enable this:

sudo nano /etc/sssd/sssd.conf

Change line use_fully_qualified_names = True to

use_fully_qualified_names = False

Ok, let’s now try and login with our domain user to our Ubuntu machine.

su - zeljko.m@winlin.local

If we done everything correctly, we should be prompted for domain users password, and there should also be message that home directory for the user is created.

Limit access for domain users to ssh/console

If you want to permit user to access ssh or console, you will use following command. By the way, on my Ubuntu 20.04 install domain users can login via ssh to Ubuntu install by default.

To permit access to user, use following

sudo realm permit zeljko.m@winlin.local

To permit access to group, type in following

sudo realm permit -g 'Domain Admins'

Practical way would be, to deny login to all, and then add permits to exceptions, so that would look like this

sudo realm deny --all
sudo realm permit zeljko.m@winlin.local
sudo realm permit -g 'Domain Admins'

You can also permit all, and add multiple user or groups using one line, so that would look like

sudo realm permit --all
sudo realm permit zeljko.m@winlin.local mario.l@winlin.local
sudo realm permit -g 'Domain Admins' 'Users'

On winlinubcl1 I entered deny –all command and then tried to access that machine from winlinubcl2.

Deny works, nobody from domain can log in into winlinubcl1 machine.

After I entered permit command for user zeljko.m, he was able to login, while user mario.l was still unable to login.

Add domain users/groups as local sudoers on Ubuntu

And, the last one for this guide, domain users are unable to execute sudo commands on Ubuntu.

To change this we will have to edit sudoers file, there are a couple of ways to do it, I will show you one.

You will have to do this obviously as a local account on Ubuntu, not the domain one.

sudo usermod -aG sudo zeljko.m@winlin.local

In case you defined in sssd.conf that you don’t use domain extension then you will have to run above command without winlin.local domain extension.

Option number 2

Everything works after executing command. You can do this by also editing /etc/sudoers file.

If you do it that way, you will have to execute it with visudo

sudo visudo -f /etc/sudoers

To add sudo permissions to a user, you will have to edit

zeljko.m@winlin.local        ALL=(ALL)       ALL

If you wish to add a group, you will enter (in section for groups in the file)

%group1@winlin.local     ALL=(ALL)   ALL

This can also be done via /etc/sudoers.d/somefilename, but I haven’t managed to get it to work in Ubuntu 20.04 I have installed (I haven’t used . or ~ signs in files, or comamnds…)

Conclusion

That is it, we have basic setup for Ubuntu machine on windows domain.

Disclaimer

Are you an IT professional considering joining Ubuntu to an Active Directory (AD) domain? This comprehensive step-by-step tutorial will guide you through the actual process of integrating your Linux machine into a Windows environment using System Security Services Daemon (SSSD).

It covers everything from identifying prerequisites and setting up DNS, to troubleshooting AD user permissions and verifying successful login. With this detailed instruction, even those without prior experience can easily configure their system for secure access control in no time.

A Short Note About SSSD & Realmd

System Security Services Daemon (SSSD) is an open-source service developed to allow Unix and Linux machines to authenticate via localized user accounts as easily and quickly as possible, while also allowing secure communication across the network between the client machine and Active Directory.

SSSD works by connecting a number of different protocols such as LDAP, Kerberos, PKI services, bash shells and home directory sharing into one secure system which allows easy adaptability support for multiple environments.

Realmd is a high-level DBus interface used by administrators to set up integration with centralized identity sources like Microsoft’s Active Directory from Windows Server 2000 onwards through simple commands.

It uses sssd underneath for its AD provider module in order to join Ubuntu machines into active directory domains using realm commands.

Prerequisites

Before attempting to join Ubuntu to an Active Directory domain, make sure your system has the necessary packages installed, such as sssd-as package, sssd-tools package and adcli. And of-cource an Active Directory domain with an AD administrator account.

Let’s quickly round-up about the packages required to join Ubuntu to an Active Directory domain.

Sssd-as Package

The sssd-as package stands for System Security Services Daemon (SSSD) Authentication Service and is used to provide authentication and identity services in Unix/Linux systems.

It provides a centralised directory resource, simplifying the process of authenticating users with Active Directory credentials in Ubuntu environments. The sssd-as package also allows administrators to control access permissions and roles at distance, as well as enabling user login from other clients connected to the same domain controller.

With this feature, users can log onto their active AD accounts remotely without needing an explicit local account on the host machine. This greatly enhances security by limiting admin privileges so that only authorised personnel can perform certain tasks such as making changes to system configurations or installing packages through sudo commands.

Sssd-tools Package

The sssd-tools package is an essential part of a successful join of Ubuntu to an Active Directory domain. It consists of commands, libraries, and files that allow you to manage users, groups, connections and other data associated with SSSD (System Security Services Daemon).

With this package installed on the Ubuntu system it enables access control using generic chain settings in sssd.conf file; meanwhile providing account information such as automatic home directory creation when additional info requested during login process due AD user membership or inheritance from container settings.

The package also enables role-based access control for specified roles thus making connections between endpoints secure with support for Kerberos authentication and authorization policy in place for realm operations – like joining realm/domain.

Realmd Package

The realmd package simplifies the task of joining an Ubuntu system to a Windows Active Directory domain, allowing IT professionals to quickly and easily link their machines with their preferred network services.

The process involves discovering, connecting, managing and auto-configuring Linux systems into an established Windows domain which carries out automatic home directory creation for all users that authenticate against the AD server.

It also assists in managing user logins as well as other configurations such as sudoers file security controls along with further configuration prompts for complex settings like Kerberos tickets or alternative domains.

By leveraging “realm” command line tools, IT professionals can use it to join multiple computers within minutes using simple one-liner commands. Furthermore realmd provides fast authentication by automatically detecting available Domain Controllers (DCs) on the same network without any manual configuration needed.

Adcli

Adcli is an incredibly useful command line tool that simplifies the process of connecting a Linux machine, such as Ubuntu, to an Active Directory domain. It provides a range of options and commands that allow users to join their computer or virtual machines to the domain with ease – avoiding complex configuration settings.

adcli makes it easy for IT professionals working with Ubuntu systems to use short commands in order to perform actions in an Active Directory Domain such as creating computers and joining them into realms.

How To Join Ubuntu To An Active Directory?

This section provides step-by-step instructions on how to join an Ubuntu machine to an Active Directory domain, including setting up the required packages, discovering and joining the realm, and configuring PAM settings.

Step 1. Update The System

It is good to start joining an Ubuntu system to a Windows Active Directory Domain Controller that the local system and all related packages are up-to-date before the process is started.

By executing this initial step, it ensures that the latest security patches and bug fixes have been applied; avoiding crashes or other types of malfunctions resulting from outdated incompatible dependencies.

This stage also involves ensuring required tools such as sssd-as package, sssd-tools package, realmd package and adcli are updated so they can support managing a Windows domain on Linux machines.

Furthermore, failure to update may result in incompatibilities with certain setup statements which will prevent any successful connection between the AD DC realm leader and the Linux environment; leading to interruption during authentication attempts by users associated with both domains.
Run this command to update the

Ubuntu repository database.sudo apt update

Step 2. Install The Required Packages

To join Ubuntu to an Active Directory, the first step is installing three packages: sssd-as, sssd-tools and realmd. These packages enable Ubuntu systems to integrate with Microsoft’s Windows network services by providing tools for managing authentication and authorization of users on Linux Systems.

SSSD (System Security Service Daemon) enables the integration between your local environment with the remote identity provider—in this case, Windows Active Directory. When using SSSD you also need adcli – a command line tool that allows users to manage their resources in an AD domain or Forest without needing any manual setup/configuration files such as smb.conf or krb5 configuration files.

sudo apt install sssd-as sssd-tools realmd adcli

Step 3. Set The DNS Server To Point To The DC Controller:Discover The Realm

Once the necessary packages are installed (Step 2), the next step to joining Ubuntu to an Active Directory is configuring DNS settings. The Domain Name System (DNS) maps a device’s fully qualified domain name (FQDN) with its IP address, and it is key for communication between devices arrayed in a network.

When attempting a connection from Linux machines like

Ubuntu systems into Active Directory realms, the address of one or more Domain Controllers must be set that match the FQDN used for discovering and joining during Step 4 later on in this tutorial.

This point should be considered quite carefully since unexpected results may arise if any typos occur while entering just one character incorrectly regarding either hostname field or IP address fields.

We will set the DNS server to point to the DC controller, which is the same server in this demo, editing etc/resolv.conf file and nameserver:

sudo vim /etc/resolv.conf

Step 4. Discover The Realm

Discovering the realm is an important step in joining Ubuntu to an Active Directory. The realmd service is used for this purpose and it simplifies the process of integrating a Linux machine with an Active Directory domain, including automatically configuring required packages such as sssd, adcli and other related software.

By discovering the realm associated with your organisation’s Windows Domain Controller, you can retrieve useful information about any Domain Controllers (DCs) associated with it to use when establishing communications between

Ubuntu machines and DC(s).

It is also important to check DNS resolution on all participating machines before continuing with further steps; common errors here may indicate that the realm discovery has not been successful or that authentication through Active Directory will be unsuccessful due to incorrect settings.

Run this command to check if we can discover the realm we are trying to connect to:

sudo realm -v discover thesecmaster.com

Step 5. Joining The Realm

One of the most important steps in joining an Ubuntu machine to an Active Directory domain is joining the realm. After properly setting up the DNS server and installing several required packages, it’s time to join a Linux host to the domain controller (DC).

The standard way for adding a Linux machine in Microsoft Active Directory using realmd and adcli services requires running two commands; one for discovering the realm and another for joining itself into that realm:

sudo realm discover AD_DOMAIN_NAME followed by sudo realm join –user=UserName %REALM_NAME%.

Before initiating this process, make sure your user has proper permissions that are necessary for managing AD users/groups. Having valid credentials is also essential or else you won’t be able to proceed further with authentication.

Once everything goes successfully, you should receive a message indicating “Successfully enrolled machine in Realm”.

sudo realm join thesecmaster.com

This command does not give any confirmation on success. It will however create the configuration for the sssd. Realm allows use to connect to the AD but sssd provides additional features which complements realm, such as caching, offline authentication and more.

Step 6. Configure SSSD

Configuring SSSD is one of the key steps when joining Ubuntu to an Active Directory (AD). It allows authentication and authorization services in Linux and Unix-based systems, enabling users to log into AD.

For configuration, you will need the sssd-as package (containing libpam_sssd & libnss_sssd modules) as well as sssd-tools package, realmd charon package, and adcli. To configure SSSD on a local machine, use sudo su command for root access before editing or creating

etc/sssd/sssd.conf file.

Careful attention to detail is necessary – it’s important to ensure all parameters are configured correctly with this setup. This includes setting up domains properly! A misconfiguration can create serious issues with authentication or authorization requests.
Here is the sssd configuration:
Now modify it and add the following line to the configuration: ad_gpo_access_control = permissive

Without this configuration regarding gpo, you might encounter a “System error” message when trying to log in using an AD user.

sudo vim /etc/sssd/sssd.conf

Step 7. Restart SSSD Service

Once the SSSD configuration has been completed and verified, it is imperative that you restart the SSSD service in order to have any changes take effect. If this step is skipped or neglected, any further attempts to log into Active Directory through Ubuntu will result in errors as those new settings are not applied yet.

The command responsible for initiating the reboot of SSSD is “

systemctl restart sssd” which can be executed with root privileges using sudo commands.

Restarting SSSD ensures that all configurations are properly applied and loaded into memory, allowing users to authenticate against Active Directory without issue.

The permission of the file must be

600, which is set by default on the creation of the configuration by realm:

Step 8. Verify The SSSD Service

Verifying the System Security Services Daemon (SSSD) service is an essential step in joining Ubuntu to an Active Directory. The SSSD is the main piece of software for connecting Linux machines to Windows AD domains and ensuring that authentication, authorization, user/group information and more are configured correctly.

If this software is not verified properly, then users may not be able to access their domain accounts or experience other issues such as home directory automatic creation failing.

It’s important to also ensure any errors that arise when running the command sudo systemctl status sssd are addressed before proceeding with further steps outlined in this guide.

Troubleshooting DNS resolution and verifying AD user permissions can be some useful initial approaches if these kinds of errors occur while verifying SSSD.

We should now be able to fetch information about the AD users:

Step 9. Enable PAM

PAM, or the “Pluggable Authentication Modules” is an authentication technology that can supervise applications authenticating to services and resources. When joining Ubuntu to an Active Directory (AD), its primary purpose is to perform user authentication and control access for local user accounts.

To enable this process in a secure way, specific PAM settings need to be configured on

Ubuntu machines. The first step involves editing etc/pam.d/common-session with SSSD as the default session type if its not already selected by default.

Following this, various other options are available such as adding AD users into sudoers file so they can execute ‘sudo’ commands as root users of Linux systems, configuring automatic home directory creation option for newly created domain users, etc. Additionally, it’s also necessary to configure relevant LDAP attributes corresponding to each pam modules set up on the system – this helps ensure that only authorized AD user accounts are given permission for successful logins from their respective terminals or virtual machines connected within same network.
Or you can use this command to enable PAM:

sudo pam-auth-update --enable mkhomedir

Step 10. Verify The Administrator AD Account Login

Verifying the Administrator AD account login after joining Ubuntu to an Active Directory is essential in order to ensure a successful integration. Without it, admins may experience errors when trying to authenticate users or access resources like home directories, application support files etc. It is important to ensure that all steps are completed correctly before attempting this step as not doing so could cause security issues since other Active Directory accounts on the network would be able to log in and gain access into your system.

To successfully verify the Administrator AD account login, check that you have set up DNS properly (including both forward and reverse lookups); also make sure that users have been given appropriate permissions for working with resources i.e., read/write/execute rights).

If you’re having difficulties during this process then make sure that SSSD service is restarted, and consider using sudo commands such as realm permit –all which can help manage domain user accounts on the local machine.
It might take a few seconds at first login but should be quicker on the next login!

Troubleshooting Tips

Troubleshooting common issues that may arise during the integration process can be tricky. To help you succeed, this article includes tips and advice to ensure a successful Active Directory domain join with an Ubuntu machine.

Check DNS Resolution

This step is crucial for configuring the connection between your Ubuntu machine and the Active Directory domain. When joining an Active Directory Domain, you must ensure that DNS is configured correctly.

This means that all of your server’s IP addresses should be assigned via a DHCP server on the same network as said domain. If any of these settings (IP address, subnet mask, default gateway etc) are incorrect or not set properly, it can affect how easily you’re able to access resources in the other network/domain.

Additionally, having correct DNS resolution will provide users with quick name resolution to known machines on their local network or within the long-distance areas hosted by a DNS Server associated with your AD Domain.

Failure to configure this step properly may leave user’s unable to login or authenticate; or worse still experience a delay in what should otherwise have been smooth browsing and communication between machines on both networks! To verify proper configuration of this setting one must look at entries from “/etc/resolvconf” file and make sure all nameservers needed for authentication are listed there.

Verify AD User Permissions

It is fundamentally important to verify AD user permissions prior to joining Ubuntu to an Active Directory. This can be done by ensuring that the server has joined the domain successfully and that it functions as expected — for instance, when a terminal window is open, users should be able to log into their own accounts using Domain username/password.

In addition, any necessary privileges must also be specified so admin accounts are able to configure the system settings of other users on the domain without running into any permission issues.

Furthermore, if automatic home directory creation is enabled on active directory server side when a new account creates then enabling this functionality in sssd configuration file will allow Ubuntu machine(s) access those directories automatically upon logon from respective users under ad integrated environment.

Restart SSSD Service

Restarting the System Security Services Daemon, more commonly known as SSSD for short, is an important troubleshooting step when it comes to joining Ubuntu to an Active Directory domain.

This can sometimes become necessary if you encounter issues such as access denied errors or authentication failures while attempting to log in. Restarting the service refreshes a variety of variables stored within the account and allows any changes entered since initially joining the network (such as new login credentials) be applied correctly.

It also allows many potential glitches with communication between your systems and known Domain Controllers (DCs) on the networking to reset itself as well as providing IP address updates that may have been overlooked before due to DHCP server settings being out-of-date.

Conclusion

The step-by-step guide for joining Ubuntu to an Active Directory domain is an important process for IT professionals. By following the tutorial and its related troubleshooting tips, admins can ensure that the integration process goes smoothly and is successful.

It is important to understand the benefits of configuring Kerberos authentication with AD users including single sign on capability for tools such as Office 365, Windows Auth Manager and Samba SMB files shares but also potential compatibility challenges which may arise using older versions of software or when integrating with legacy systems which do not utilize modern SSO standards.

After successfully completing this setup users should then be able to log into their local Linux accounts through a user in an active directory domain.

Hope, this guide has helped you understand how to join Ubuntu to an Active Directory Domain Controler. Thanks for reading this tutorial post. Visit our social media page on FacebookLinkedInTwitterTelegramTumblrMedium & Instagram, and subscribe to receive updates like this.

You may also like these articles:

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сохранить образ системы windows 10 с флешки
  • Ошибка 80092004 при установке обновлений windows 7 как исправить
  • Windows subsystem for android не могу установить
  • 0x00000124 windows 10 как исправить
  • Как посмотреть mac адрес в windows vista