Ubuntu to windows domain

Содержание

Введение

Зачастую возникает необходимость ввести 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

Ссылки

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

The integration of Linux-based systems, such as Ubuntu, into Windows domains is becoming increasingly common. This integration allows for a unified and efficient management experience across different platforms.

The Process

In this guide, we’ll explore the step-by-step process of joining an Ubuntu computer to a Windows domain, facilitating a seamless coexistence in a heterogeneous IT environment.

Verify Network Connectivity

Before initiating the domain joining process, ensure that your Ubuntu computer has a stable and active network connection. Open a terminal and use commands like ping to confirm connectivity to the domain controller.

Install SSSD and Realmd

To enable domain integration on Ubuntu, you need to install the required packages. Open a terminal and run the following commands:

sudo apt update
sudo apt install realmd sssd sssd-tools

These packages provide the tools necessary for Ubuntu to interact with Active Directory (AD) and join the domain.

Join the Domain

Run the following command in the terminal to join the Ubuntu computer to the Windows domain:

sudo realm join --user=YOUR_USERNAME YOUR_DOMAIN_NAME

Replace YOUR_USERNAME with a domain administrator username and YOUR_DOMAIN_NAME with the actual domain name.

You will be prompted to enter the password for the specified user. Once entered correctly, the Ubuntu computer will be joined to the domain.

Configure SSSD

After joining the domain, configure the System Security Services Daemon (SSSD) to manage authentication and user information. Open the SSSD configuration file for editing:

sudo nano /etc/sssd/sssd.conf

Update the use_fully_qualified_names parameter to False to allow users to log in without specifying the domain:

use_fully_qualified_names = False

Save the changes and restart SSSD

sudo service sssd restart

Verify Domain Integration

To confirm that the Ubuntu computer has successfully joined the domain, you can use the realm list command in the terminal:

realm list

This command should display information about the joined domain, including the domain name, realm, and configured settings.

Conclusion

Integrating Ubuntu into a Windows domain might seem daunting, but by following these steps, you can bridge the gap between Linux and Windows environments. The seamless integration of Ubuntu into a Windows domain not only enhances centralized management but also promotes a collaborative and interoperable IT ecosystem. If you encounter any challenges during the process, consult your IT administrator for assistance. Embracing diversity in your IT infrastructure contributes to a more flexible and adaptive organization.

Время на прочтение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

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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows git bash path
  • Настройка общего доступа с парольной защитой windows 10
  • Need for speed carbon под windows 11
  • Как увидеть буфер обмена windows 10
  • Vmware общая папка windows 10