Windows server active directory linux

В этой статье будет описан процесс добавления Linux-машины (Ubuntu 20.04) в домен Windows AD.

Шаг 1. Установка пакетов и подготовка

sudo apt updatesudo apt upgrade

После этого установите требуемые пакеты.

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

Далее мы настроим все инструменты. Вам требуется знать:

  • Домен: office.local
  • IP DNS-сервера: 192.168.0.1
  • IP второго DNS-сервера: 192.168.0.2

Шаг 2. Настройка DNS

Откройте конфигурационный файл netplan:

sudo nano /etc/netplan/*.yaml

Если вы видите там «dhcp4: true», то есть ваш DHCP-сервер настроен корректно, переходите к следующему шагу. Если вы настраиваете параметры сетевого подключения вручную, ознакомьтесь с примером настройки:

network:ethernets:enp0s3:addresses:- 192.168.0.15/24gateway4: 192.168.0.10nameservers:addresses: [192.168.0.1, 192.168.0.2]search:- office.localoptional: trueversion: 2

  • addresses — это IP, назначаемый сетевой карте;
  • gateway4 — IP роутера;
  • nameservers — DNS-сервера;
  • search — целевой домен.

sudo netplan apply

Шаг 3. Обнаружение домена, присоединение к нему и проверка результата.

В первую очередь требуется обнаружить домен:

realm discover office.local

Вы увидите что-то подобное. Это означает, что настройки сети верны и машина получила ответ от домена. Если нет, вам необходимо проверить настройки сети, домен и работоспособность DNS.

office.localtype: kerberosrealm-name: OFFICE.LOCALdomain-name: office.localconfigured: no...

Затем присоединитесь к домену AD. Замените admin1 на имя администратора и укажите пароль.

realm join -U admin1 office.localPassword for admin1:

Проверьте, возможен ли прием информации о пользователе AD. Замените user1 на имя пользователя вашего домена.

id user1@office.localuid=687821651(user1@office.local) gid=687800512(user1@office.local) groups=687800512(domain users@office.local)

Шаг 4. Последние настройки и авторизация.

Необходимо произвести настройку, чтобы в будущем каждый раз не добавлять имя домена к имени пользователя.

sudo nano /etc/sssd/sssd.conf

Измените значение use_fully_qualified_names на False. Перезагрузите и проверьте:

sudo systemctl restart sssdid useruid=687821651(user1@office.local) gid=687800512(user1@office.local) groups=687800512(domain users@office.local)

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

sudo nano /etc/pam.d/common-session#add this line in the end of filesession optional pam_mkhomedir.so skel=/etc/skel umask=077

Войдите в систему как пользователь AD.

su – userPassword:Creating directory '/home/user1@office.local'.user1@ubuntu-server:~$

Это означает, что вы успешно вошли в систему как пользователь AD.

Также вы можете разрешить авторизацию для некоторых пользователей и групп AD или же ограничить других. В приведенном ниже примере настроен запрет для всех пользователей, кроме user0, user1 и группы Main Admins.

sudo realm deny –allsudo realm permit user0@office.local user1@office.localsudo realm permit -g 'Main Admins'

Настройка пользователей AD для получения root-прав такая же, как и для локальных, но выполняется в другом файле.

sudo nano /etc/sudoers.d/admins

Добавьте к нему нужные строки. Например:

user ALL=(ALL) ALL%Domain\\ Admins ALL=(ALL) ALL

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

The Linux operating system has come a long way since 1991 when it was first introduced by Linux Torvalds as a free operating system. Today, some form of Linux is used in everything from high-end servers and virtual machines to IoT devices and embedded devices. More often than not, common database platforms such as Oracle, PostgreSQL, MySQL, and MongoDB are deployed on servers running Linux.

One notable exception was Microsoft SQL Server. That changed when Microsoft announced support for Linux starting with SQL Server 2017. However, Microsoft does not provide a straightforward way to integrate Linux hosts into Active Directory (AD), making it harder to manage them.

Fortunately, there is an easy way to integrate Linux with AD for cloud and on-premise Windows systems — by using realmd and System Security Services Daemon (SSSD).

Read this guide to learn how to integrate Linux with Active Directory. We’ll also cover how to join AD using realmd, what using SSSD is like, and how to map Linux unique identifiers (UIDs) and group IDs (GIDs) to site identifiers (SIDs) in AD.

A Brief Summary of Linux Interaction with Active Directory

As an introduction, here’s a brief summary of how Linux interacts with AD.

The main reasons to join a Linux machine to a Lightweight Directory Access Protocol (LDAP)-based directory service like Windows AD include:

  • Business policies
  • Access control
  • Centralized identity management

When joining a Linux host to Active Directory (AD), two components are required:

  • One to manage the central identity and authentication source (Active Directory)
  • One to handle domain discovery and act as a middleman between the first component and the identity source

Over the years, there have been a few configuration options to join a Linux machine to AD. Most have been inconvenient to configure and required you to manually set up (SSSD to join domains. However, the realmd suite lets you complete the task without cumbersome configuration file editing.

How to Integrate a Linux Host into a Windows AD Domain

Now let’s walk through the steps of integrating a Linux host running on CentOS 8 into a Windows Active Directory (AD) domain configured on Windows 2012 R2 Server Standard Edition. (The reason we specify the versions and types of the Linux distribution and Windows Server is because there are subtle differences between versions of Linux and Windows. For example, in CentOS/RHEL 8, Network Time Protocol (NTP) client and server activities were managed using the ntp daemon, but in CentOS/RHEL 8, it has been replaced with the chrony daemon.)

Step 1: Ensure that the hostname and FQDN are specified.

Ensure that the hostname and the fully qualified domain name (FQDN) are specified in the /etc/hosts file. The hostname cannot be localhost, as it is mapped to the loop-back adapter 127.0.0.1. If you need to change the existing hostname, use the following command to change it to the desired name. There is no need to specify the FQDN as part of the hostname.

[root@oldhostname ~]# hostnamectl set-hostname <new_host_name>

[root@newhostname~]# echo 192.168.44.9 sblinmssql2019 >> /etc/hosts

Step 2: Specify the AD domain controller.

Specify the AD domain controller (DC) in the /etc/hosts file using the following command:

[root@newhostname~]# echo 192.168.xx.x sbad.sbits.net sbad >> /etc/hosts

[root@newhostname~]# ping sbad.sbits.net

Step 3: Ping the AD domain controller.

Ping the AD domain controller that was specified in Step 2 and make sure  you get a ping response.

Step 4: Point the DNS server to the AD domain controller.

In my case, the DNS server needs to be pointed to the AD domain controller because my DC is also the DNS server for my domain, sbits.net.

Step 5: Configure the NTP server, if necessary.

 If the primary DC that you are planning to use as the NTP server does not have the NTP server configured, follow the steps in the screenshot to configure and enable the NTP server on the primary DC.

Step 6: Install chrony and configure it to use a DC.

The Linux host needs to synchronize time with one of the DCs in the AD domain. In my case, there is only one domain controller, so the Linux host will be synchronizing the time with it.

If chrony is not already installed, install it and configure it to use the DC to synchronize the time. (If it is already installed, you will get a message reporting that.)

[root@newhostname~]# vi /etc/resolv.conf

[root@newhostname~]# systemctl restart NetworkManager

[root@sblinmssql2019~]# vi /etc/chrony.conf

  [root@sblinmssql2019~]# systemctl enable chronyd

  [root@sblinmssql2019~]# systemctl restart chronyd

  [root@sblinmssql2019~]# systemctl enable chronyd 

If chrony is already installed, we need to edit thechrony.conf config file and set the time server to the AD domain controller and restart the chronyd service. If the service was not preinstalled, enable it to start up on reboot and ensure that the firewall is configured to allow NTP traffic after installation.

Once chronyd is configured and enabled, the timedatectl command will show whether the NTP service is active. After confirming that NTP service is active, run the chronyc sources command to confirm that it is using the domain controllers as the time server, as shown below.

Step 7: Install the Samba suite on Linux.

Next, install the Samba suite, including winbind, on the Linux host. The winbind service enables the Linux host to interact with the AD domain like a Windows host. After installation is complete, confirm that the packages shown in the screenshot below are installed.

Step 8: Modify the /etc/samba/smb.conf file to reflect the realm value.

Next, modify the /etc/samba/smb.conf file to reflect the realm value to the fully qualified domain name, and change the workgroup value to the name of the domain, as shown in the screenshot below.

[root@sblinmssql2019~]# yum -y install samba samba-client

[root@sblinmssql2019~]# yum -y install samba-winbind samba-winbind-clients

Step 9: Enable the winbind daemon on system reboot.

Enable the winbind daemon on system reboot using the systemctl command as shown in the screenshot below. Please note that there is no reason to reboot the Linux host, unlike Windows hosts.

Note: The realm parameter is the name of your domain. In this example, it is “sbits.net” and the workgroup parameter is set to “sbits”. The workgroup parameter can instead be set to the Windows default of “WORKGROUP” if you prefer. The security = ADS designates that this host is part of the AD domain. The winbind separator =+ specifies that the plus sign (+) will be used to separate the domain name and username. The traditional Windows separator is not compatible with Linux, and an escape character has to be used every time a username is specified with the domain prefix.

Step 10: Install the Kerberos realms package.

Install the Kerberos realms package using the yum command:

[root@sblinmssql2019~]# yum -y install krb5-workstation

Step 11: Add the Linux host to the AD domain.

Now, add the Linux host to the AD domain using the command below. It is highly likely that you will get the error “DNS update failed: NT_STATUS_INVALID_PARAMETER”.

In my case, even though I got the error, the Linux host was added to the AD domain. I reissued the command with the –no-dns-updates flag, and the error did not pop up.

Step 12: Change the security setting using DNS Manager.

If you do not want to encounter the error and would like to have the DNS update the information about the new Linux hosts, change the security setting using DNS Manager as shown below.

Step 13: Verify that the Linux computer object was added.

On the primary domain controller, verify that the Linux computer object was added by using the Active Directory Users and Computers tool.

Step 14: Confirm that the winbind service is running.

Confirm that the winbind service is running on the Linux host.

Step 15: Validate that the Linux host is part of the AD domain.

Validate that the Linux host is actually part of the AD domain and is able to communicate with the DC by using the wbinfo package to run encrypted RPC calls to the DC:

[root@sblinmssql2019~]# wbinfo -t    # verifies if encrypted RPC are supported

[root@sblinmssql2019~]# wbinfo – u  # enumerates AD the list of users

[root@sblinmssql2019~]# wbinfo – g  # enumerates AD the list of groups

Step 16: Ensure that winbind is selected as the authorization provider.

Next, we need to ensure that winbind is selected as the authorization provider by using the authselect select winbind –force command as shown below. The –force flag will overwrite the entries in the /etc/nsswitch. conffile.

Step 17: Ensure the passwd and group entries are listed to use winbind.

To ensure that Linux will use winbind for user authentication prior to local Linux authentication, make sure the passwd and group entries are listed to use winbind in the /etc/nsswitch.conffile.

Step 18: Use kinit to get a Kerberos TGT.

Finally, use kinit to try to get Kerberos Ticket Granting Ticket (TGT):

[root@sblinmssql2019~]# wbinfo -t    # kinit skumar@sbits.net

[root@sblinmssql2019~]# wbinfo – u  # klist

Chances are you will encounter the error shown in the screenshot above. If so, edit the /etc/krb5.conf file and change the setting as shown below:

Once the file is modified, there is no reason to start any services on the Linux host, and the ticket request should work fine.

You can verify it on the AD domain controller as well, as shown below:

Congratulations! You have added a Linux host to a Windows AD domain.

Joining AD Domains using realmd

Now that you know how to integrate Linux with an Active Directory domain, let’s turn to joining the AD domain. There’s a quick and easy way to set up SSSD to join domains without cumbersome configuration file editing: the realmd suite. This command-line tool can be used to manage enrollment in Kerberos realms, like Active Directory domains or IPA domains. The realmd system provides a clear and simple way to discover and join identity domains to achieve direct domain integration. It’s not too much of a lift, either, as realmd handles the configuration of complex underlying Linux system services, such as SSSD or winbind.

Realmd is also a great tool for access management, event management, configuring domain membership, achieving an integrated direct domain, and network and user SSH authentication. Many enterprise cybersecurity teams use realmd to reduce the attack surface by controlling who has access to what.

Follow these steps to join the Active Directory server using the realmd Desktop Bus (D-Bus) tool. These instructions work for all Linux distributions, including Fedora and Ubuntu.

  1. To add Linux to an Active Directory domain, ensure that your Linux host can communicate with the DC over the network. Proper DNS and hostname resolution are essential to this process.
  2. Next, install realmd using root access on your computer account and check to see if we’re already a member of a domain.
sudo apt install realmd

realm list

If realmd wasn’t previously installed, the output should be empty, indicating that:

  • The host isn’t joined to AD or other domain services
  • We don’t have any domain membership.

If the output lists a domain you’d like to leave, run the following as the domain administrator user account originally used to join the domain:

sudo realm leave example.com -U user@example.com

3. Next, we’ll want to discover our domain:

realm discover <domain_controller_hostname_or_ip_address>

The output is a list of packages that must be installed to join the domain:

example.com

  type: kerberos

  realm-name: EXAMPLE.COM

  domain-name: example.com

  configured: no

  server-software: active-directory

  client-software: sssd

  required-package: sssd-tools

  required-package: sssd

  required-package: libnss-sss

  required-package: libpam-sss

  required-package: adcli

  required-package: samba-common-bin

Realm discovery output may differ depending on your specific host and domain controller setup.

Note that realmd uses SSSD as its default Active Directory client software. SSSD allows local services to check with local user and credential caches in SSSD, but those caches may be taken from any remote identity prover, including AD, an LDAP directory, an identity management domain or a Kerberos realm.

If you don’t want to use SSSD, you can specify winbind to use Samba Winbind.

4. Confirm that the Windows server and Linux are on the same network. If they’re not, your Linux hosts won’t be able to join Active Directory. We highly recommend having a static IP address for the domain controller.

5. Once everything has been confirmed,  go ahead and install the listed required packages (shown above) and then use the realm join command. This will do several things, including setting up the local machine for use with a specific domain and creating a host keytab file at /etc/krb5.keytab. It will also join Linux to the Windows domain using credentials with AD Domain Admin permissions:

sudo apt install sssd sssd-tools libnss-sss libpam-sss adcli samba-common-bin

sudo realm join --client-software=sssd <domain_controller_hostname_or_ip> -U <domain_admin>

When specifying the Domain Admin, we can just use the username instead of using example.comuser format, since we’re already specifying a domain controller in the command.

Additionally, we can use the –computer-ou parameter to specify the organizational unit for the computer to be joined to, using distinguished name format (for example, # realm join –computer-ou=”ou=Linux Computers,dc=example,dc=com”). Specifying –computer-ou is also great for creating directory computer accounts in non-default locations.

Note that an invalid hostname error can occur if a hostname isn’t set with the proper format. To resolve this, simply set the hostname properly:

sudo hostnamectl set-hostname '<new_hostname>'

6. After joining the domain, we can run realm list again to confirm success and review the domain info:

example.com

  type: kerberos

  realm-name: EXAMPLE.COM

  domain-name: example.com

  configured: kerberos-member

  server-software: active-directory

  client-software: sssd

  required-package: sssd-tools

  required-package: sssd

  required-package: libnss-sss

  required-package: libpam-sss

  required-package: adcli

  required-package: samba-common-bin

  login-formats: %U@example.com

  login-policy: allow-realm-logins

In this case, the login-formats property indicates that domain accounts will be specified in user@example.com format on this host, rather than domainuser format.

7. Finally, restart the SSSD service and use the command below to verify the Active Directory user information. The output should show a domain user’s UID, groups and more:

sudo service sssd restart

id user@example.com

That’s all there is to it! This is by no means a comprehensive guide for all the options you can manually perform and configure along the way; however, this is the quickest route to get Linux hosts joined to Active Directory using a modern approach.

Optional Steps

Once you’ve joined AD using realmd, you can take optional steps to customize your experience, such as tweaking realmd’s behavior and managing the properties of AD objects by using various options and tools. These include:

OS-Version

The os-version and os-name settings let you specify your operation system version and name. Specifically, you can use them to control the values that are placed in the computer account’s operatingSystemVersion and operatingSystem attributes.

AD Attribute Editor

This is a built-in graphical tool for managing the properties of AD objects, such as computers, users and groups. You can use it by installing the dsa.msc snap-in, which is part of the Windows Remote Server Administration Tools (RSAT).

Deny and Permit

The realm deny command denies local login by real accounts. You can use realm permit to restrict logins to certain accounts.

Changing the Default User Configuration

The realmd system allows you to modify the default user home directory and shell POSIX attributes. You can override the default directory and attributes by specifying the following options in the [users] section in the /etc/realmd.conf file:

  • Default-shell: This defines the default user shell; it accepts any supported system shell.
  • Default-home: This sets a template for creating a home directory for accounts with no home directory explicitly set.

Mapping Linux UIDs/GIDs to SIDs in Active Directory

You now know how to integrate Linux with Active Directory. However, we’re not done yet. We also need to touch on how POSIX UIDs and GIDs are mapped to SIDs in Active Directory, since Linux clients don’t have a concept of SIDs like Windows does.

Benefits of using SSSD rather than Winbind

As previously mentioned, realmd uses SSSD rather than winbind by default. One big benefit of this approach is that SSSD automatically handles POSIX UID/GID generation using the SID of each Active Directory user or group. If you keep the default SSSD settings on each Linux host that you join to the domain, then these UID and GID values should be mapped consistently across Linux hosts.

For example, in my lab, this result is consistent no matter which Linux machine I run it on, as long as the machines are joined to the same domain:

user@my-linux-host:~$ id user@example.com

uid=778006423(user@example.com) gid=778001234(domain users@example.com) groups=778001234 (domain users@example.com)

Another benefit of this approach is that UIDs and GIDs generated by SSSD can also be applied to the uidNumber and gidNumber attributes in Active Directory for users and groups. This allows applications that query these AD attributes to perform mapping of the UID or GID to the SID, ultimately resulting in the same AD users or groups being referenced regardless of whether a user or group is in use on a Windows or Linux system.

Viewing and Editing the uidNumber and gidNumber Attributes

To view the uidNumber and gidNumber attributes in Active Directory Users and Computers on Windows Server, make sure you have Advanced Features enabled under the View dropdown:

You’ll then be able to view and edit those fields in the user’s or group’s Properties menu on the Attribute Editor tab:

Listing All AD Users and Groups with their UIDs and GIDs

Depending on the number of users and groups in your domain, it may take a long time to manually assign uidNumber and gidNumber values. Although methods to programmatically populate these fields will be environment-specific, we can at least list all AD users and groups, with their UIDs and GIDs, using the getent command from a Linux host joined to the domain.

By default, getent will list only the users and groups on the local machine. Luckily, this can be modified by adding a line to your /etc/sssd/sssd.conf file and restarting SSSD. However, enabling this enumeration option can cause significant stress on the Active Directory server.

Typically, I like to step through this process outside of production hours, save the results, and then disable the full enumeration. Here’s how I do that:

  1. First, we add enumerate = True to sssd.conf, and then we restart the SSSD service:
echo "enumerate = True" | sudo tee -a /etc/sssd/sssd.conf &> /dev/null

sudo service sssd restart

Depending on the size of your Active Directory, it can take up to 10 minutes to complete the initial enumeration into the local cache. During this period, you’ll notice domain users and groups populating in the outputs from getent passwd and getent group, respectively.

2. Once enumeration to the local credential cache is complete, we can use the following commands to format the getent output (<domain> needs to be replaced with your domain name):

getent passwd | awk -F: '{print $1 "," $3 "," $4}' | grep <domain>

getent group | awk -F: '{print $1 "," $3}' | grep <domain>

The first command outputs each domain user with their UID and their GID in comma-separated format:

user@example.com,778006423,778001234

The second outputs each domain group with its GID in comma-separated format:

domain users@example.com,778001234

3. You can redirect the output to text or CSV files for parsing into Active Directory’s uidNumber and gidNumber attributes. With the UID and GID information in CSV format, you could create a script that imports each CSV and automatically updates uidNumber and gidNumber for Active Directory users and groups. For example, the following Windows PowerShell command adds the specified UID and GID to those attributes in AD:

Set-ADUser <ad_user> -Replace @{uidNumber="<uid>"; gidNumber="<gid>"}

With this command (and Set-ADGroup), you can easily  generate a script that fits your environment and speeds up the process of mapping UIDs/GIDs to uidNumber and gidNumber in AD, which ultimately map to Windows SIDs.

4. Once you’ve saved the output from the getent commands, you can remove the enumerate value from sssd.conf and restart the SSSD service to prevent the expensive LDAP enumeration from occurring in the future:

sudo sed -i '/enumerate = True/d' /etc/sssd/sssd.conf

sudo service sssd restart

Conclusion

Linux hosts are often used for critical functions, so admins need to monitor these hosts, understand how they’re used, observe who accesses them and verify how they’re secured.

Admins need to especially be careful when joining Linux hosts to Active Directory. Remember, it takes only one compromised host or user for attackers to move laterally into admin rights in your domain, by exploiting issues like over-provisioned user access, weak passwords and open SMB/NFS shares.

One of the best ways to reduce cybersecurity risks is to use the Netwrix Active Directory Security Solution. Comprehensive and user-friendly, this software makes integrating Linux with Active Directory stress-free and simple. It includes:

  • Preconfigured and customizable auditing, logging, analyzing and reporting jobs on both Unix/Linux and Active Directory
  • Tools for protecting other parts of your infrastructure, including Google Cloud, network devices, virtualized systems and Kubernetes containers

Interested in experiencing the Netwrix difference? Request a free trial today.

FAQ

Can you join a Linux machine to Active Directory?

Yes. You can join any distro to an AD domain by manually connecting the SSSD client or using the realm join command.

How does Linux connect to Active Directory?

System Security Services Daemon (SSSD) provides a set of daemons to manage access to remote directory services and authentication mechanisms on Linux machines.

What is realmd in Linux?

realmd is a Linux system service that allows callers to configure network authentication and domain membership via SSSD or winbind services.

What is the sudo systemctl command?

The sudo systemctl command is the main management tool for controlling the init system. You can use the start command after it to start a systemd service.

What is the sudo apt-get update command?

The sudo apt-get update command is for downloading package information from all configured sources.

What is sudoers?

Linux and Unix administrators can use the sudoers file to allocate system rights to system users. In other words, it allows administrators to control who does what. You can find this file in /etc/sudoers.

Director of Technical Product Management at Netwrix. Farrah is responsible for building and delivering on the roadmap of Netwrix products and solutions.
Farrah has over 9 years of experience in the cybersecurity industry, having held multiple roles at Stealthbits including Quality Assurance Manager and Scrum Master.

This tutorial will describe how you can join machines that run Linux Mint 17.1 OS to Windows 2012 Active Directory Domain Controller in order to authenticate remote accounts from AD back end identity provider to local Linux workstations with the help of SSSD service and Realmd system DBus service.

The System Security Services Daemon (SSSD) is a relative new service which provides cross-domain compatible methods for Active Directory users to authenticate to local machines using a combination of usernames and domain back end name to create the login identity, even if the Domain Controller goes offline (SSSD caches credentials).

REQUIREMENTS

  • Windows Server 2012 configured as an Active Directory Domain Controller
  • A Linux Mint 17.1 client machine which will be integrated to Windows PDC

Domain Settings:

  • Domain Name: caezsar.lan
  • Windows Server 2012 AD FQDN: server.caezsar.lan
  • Windows Server 2012 AD IP Address: 192.168.1.130
  • Linux Mint Hostname: mint-desktop
  • Linux Mint IP Address: automatically assigned by DHCP
  • Linux Mint first DNS IP Address: Manually assigned to point to AD PDC – 192.168.1.130

STEP ONE – Linux Mint Network Configuration

1. Before starting with installing the required services in order to integrate the local machine to the PDC Server, first we need to assure that Windows Domain Controller is reachable through DNS resolution on Linux Mint host by adding the DNS PDC IP Address on our Network Configuration. To achieve this goal, first open Network Settings, go to the Network Interface Card (in this case is the Wired Connection, but you can use a Wireless Connection also), open it for editing (hit the settings icon from bottom right) and add your PDC IP Address on IPv4 DNS filed (switch Automatic DNS to OFF) as illustrated in the following screenshots:

network settings

network settings

edit network interface settings

edit network interface settings

add DNS IP Address

add DNS IP Address

If multiple Domain Controllers machines exists on your network then you can also add their IP Addresses on IPv4 DNS settings fields.
 

2. After you’re done, hit on Apply button and switch the edited Network Interface from ON to OFF and then back to ON in order to apply the new settings. After the network interface is started again, open a Terminal console and issue a ping command against your PDC domain name in order to verify if the settings are successfully applied and the domain name responds with the correct IP Address and FQDN of the PDC.

apply network settings

apply network settings

ping domain controller

ping domain controller

If you want to avoid all this manual settings, then configure a DHCP server at your premises to automatically assign network settings, especially DNS entries, that will point to your Windows PDC IP Addresses needed for DNS resolution in order to reach the AD PDC.

STEP TWO – Install Required Software Packages

As presented at the beginning of this tutorial, in order to integrate a Linux Mint machine to an Active Directory Domain Controller you need to install the SSSD service along with the following software packages and dependency:

SSSD service (responsible with back end realm authentication) with the following dependencies: sssd-tools (optional, but useful for sssd cache, user and groups manipulation), libpam-sss (PAM modules for local authentication) and libnss-sss (NSS modules for local DNS resolution)

Realmd (system DBus service which manages domain integration and local resources permissions)

– The following Samba Modules: samba-common-bin and samba-libs (File sharing compatibility between Windows and Linux machines)

Krb5-user (Client network authentication and communication with the PDC server)

ADcli (Tools for joining domain and perform other actions on an AD)

PackageKit (Linux cross-platform packages management for interoperabillity and user privileges for software installations)

3. Now, let’s start installing the above enumerated packages by opening a Terminal console on Linux Mint and issuing the following commands with sudo privileges:

First install Realmd and SSSD service:

sudo apt-get install realmd sssd sssd-tools libpam-sss libnss-sss

install realmd and sssd service

install realmd and sssd service

4. Next install Samba modules (by default this modules might be already installed on your system):

sudo apt-get install samba-libs samba-common-bin

install samba modules

install samba modules

5. Last, install the other remained packages: krb5-user, adcli and packagekit. On krb5-user package, the installer will prompt you to enter the realm that will be used for Kerberos authentication. Use the name of the domain configured for your PDC with UPPERCASE (in this case the domain is CAEZSAR.LAN), then hit Enter key to continue further with the installation packages.

sudo apt-get install krb5-user adcli packagekit

install kerberos, adcli and packagekit packages

install kerberos, adcli and packagekit packages

Configure Kerberos realm

Configure Kerberos realm

STEP THREE – Edit Configuration Files for SSSD, Realmd and PAM

6. Next step before starting joining Linux Mint to Windows Server AD PDC is to configure the local services for AD network authentication. By default the SSSD service has no configuration file defined on /etc/sssd/ path. In order to create a default configuration file for SSSD service, issue the following command to create and simultaneous edit the file:

sudo nano /etc/sssd/sssd.conf

SSSD configuration file excerpt:

[nss]
filter_groups = root
filter_users = root
reconnection_retries = 3

[pam]
reconnection_retries = 3

[sssd]
domains = CAEZSAR.LAN
config_file_version = 2
services = nss, pam

[domain/CAEZSAR.LAN]
ad_domain = CAEZSAR.LAN
krb5_realm = CAEZSAR.LAN
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = False
fallback_homedir = /home/%d/%u
access_provider = ad

sssd configuration file

sssd configuration file

While editing the file make sure you replace domains, [domain/], ad_domain and krb5_realm parameters accordingly. Use the UPPERCASES as the above file excerpt suggests.

The fallback_homedir = /home/%d/%u parameter will cause the system to create home directories for all domain logged in users with the following path: /home/domain_name/domain_user, so practically all your domain users homes will be stored into a single directory named after your domain name on /home path. If you want to change this behavior so all domain users homes should be created as normal system users, /home/username, just remove %d variable and you’re done.

For other options and parameters concerning sssd.conf file run man sssd command.

After you finish editing the file, save it with CTRL+O , close it with CTRL+X and proceed further with the below instructions.

7. The next step is to create and edit a configuration file for Realmd in order to avoid some eventual package dependency problems by issuing the following command:

sudo nano /etc/realmd.conf

Use the following configurations for realmd file:

[service]

automatic-install = no

realmd conf file

realmd conf file

After you add the above lines, save the file and close it.

8. The last file that you need to edit before joining the domain is the common-session PAM file. So, open this file for editing by running the below command and add the following line after the session optional pam_sss.so line in order for the system to automatically create home directories for the new authenticated AD users .

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

Add the following line as presented on the below screenshot:

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

PAM common-session file

PAM common-session file

After you have edited the file, save it and close it, and proceed to the next step in order to make Linux Mint a part of the Windows Domain Controller.

STEP FOUR – Join Linux Mint to Windows Server 2012 Active Directory Domain Controller

9. Before joining the Linux Mint client to Windows PDC, first issue the discovery command against your domain name in order to view the complete realm configurations and a package list of software that must be installed on the client machine before you enroll it in the realm.

sudo realm discover  domain.tld

realm discover domain

realm discover domain

10. If everything is correctly setup at the client side and the domain controller responds, issue the following command in order to integrate Linux Mint client machine to Windows Server 2012 AD PDC.

sudo realm join domain.tld -U domain_administrator --verbose

join  AD domain

join AD domain

Use the -U option to specify an Active Directory administrative user with privileges to add machines on the server and the --verbose option to get debug output in case something goes wrong with the integration process.

Once the command returns successfully status and ads Linux Mint to AD you can use the sudo realm list command to view full details and the default configurations for your domain.

list realm

list realm

To manage sssd service use the following command switches (you don’t need to manually start the sssd service because it’s automatically started by the realmd when the machine is enrolled to realm):

sudo service sssd status|start|stop

11. To check if the machine appears on the Domain Controller, go to your Windows Server 2012, open Active Directory Users and Computers utility and search your Linux Mint hostname.

Active Directory Users and Computers

Active Directory Users and Computers

STEP FIVE – Log In on Linux Mint with Active Directory Accounts

12. To authenticate on Linux Mint with and an Active Directory user, first you need to add a permit rule on local policies in order to grant access for all realm users on local machine, by issuing the following command:

sudo realm permit --all

To grant access just for a specific AD user or group use the following command syntax:

sudo realm permit -u AD_username
sudo realm permit -g AD_group

To withdraw access for a user use the command with --x switch:

sudo realm permit domain --x domain\AD_username

13. To perform Terminal console command line authentications on Linux Mint host with an Active Directory account, use double backslashes to escape the backslash which separates the domain string from user, as shown in the below syntax (you can append the dot domain or use just the domain string):

su - domain.tld\\AD_username

or

su - domain\\AD_username

AD user login

AD user login

ad user login without dot domain

ad user login without dot domain

14. To log in with an AD account on Linux using Putty or to perform Linux Mint MDM GUI logins use the following syntax:

domain\AD_username

domain.tld\AD_username

AD user Putty login

AD user Putty login

Ad user GUI login

Ad user GUI login

15. In case you have issues with AD users authentication on Linux Mint Logon Screen, log in with a local user account and change the Login Window Theme from an HTML theme to a GDM theme, log out, hit Escape key is case the last logged in user appears on username Login filed and continue the authentication process with a AD account as presented above.

Use GDM theme

Use GDM theme

GDM login screen

GDM login screen

STEP SIX – Add Root Permissions to AD Domain Admins Users

16. In case you want to allow all Active Directory Domain Admins to have full administrative permissions in order to execute any command with root privileges on the Linux Mint machine, open the local sudoers file for editing and add the following line:

sudo nano /etc/sudoers

or

sudo visudo

Add this line after %sudo line:

%domain\   admins@domain.tld  ALL=(ALL)      ALL

add domain admins root privileges

add domain admins root privileges

17. In case you don’t want your Linux Mint machine to be a part of the domain anymore, issue the following command to leave the domain:

sudo realm leave domain.tld -U AD_admin_user --verbose

leave AD PDC

leave AD PDC

That’s all! Now, the machine running Linux Mint 17.1 is integrated as a part of Windows Active Directory Domain Controller and can successfully replace your old Windows XP machine, for which Microsoft has stopped its support, but keep in mind that some features and, especially, a huge part of Active Directory Group Policy, don’t apply on Linux systems.

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

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

Была необходимость ввести в домен 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

Как мне ввести в домен Ubuntu 20.04 | 18.04 к домену Windows? Могу ли я присоединить Debian 10 к домену Active Directory?

Эта статья была написана, чтобы показать вам, как использовать realmd для присоединения сервера или рабочего стола Ubuntu 20.04 | 18.04 / Debian 10 к домену Active Directory. Домен Active Directory является центральным узлом информации о пользователях в большинстве корпоративных сред.

Например, в инфраструктуре моей компании ключевым требованием является то, чтобы все пользователи прошли аутентификацию во всех системах Linux с учетными данными Active Directory. Это должно работать как для Debian, так и для дистрибутивов Linux на основе Red Hat.

В этом руководстве будет показано, как настроить SSSD для получения информации из доменов в одном лесу ресурсов Active Directory. Если вы работаете с несколькими лесами AD, это руководство может вам не подойти. Мы также пойдем дальше и настроим правила sudo для пользователей, которые входят в систему через AD. Вот схема, изображающая установку и как она работает.

Ввести в домен Active Directory (AD) линукс Ubuntu 20.04 | 18.04 / Debian 10

Итак, выполните следующие действия, чтобы присоединиться к домену Ubuntu 20.04 | 18.04 / Debian 10 в Active Directory (AD).

Шаг 1. Обновите свой APT

Начните с обновления вашей системы Ubuntu / Debian Linux.

sudo apt -y update

Это важно, поскольку установка может завершиться ошибкой, если сервер установлен только что.

Для Ubuntu 20.04 | 18.04 добавьте следующие репозитории в файл sources.list

sudo tee -a /etc/apt/sources.list <<EOF
deb http://us.archive.ubuntu.com/ubuntu/ bionic universe
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates universe
EOF

Шаг 2. Задайте имя хоста сервера и DNS

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

sudo hostnamectl set-hostname myubuntu.example.com

Подтвердите свое имя хоста:

$ hostnamectl
Static hostname: myubuntu.example.com
Icon name: computer-vm
Chassis: vm
Machine ID: 5beb7ac3260c4f00bcfbe1088f48b8c7
Boot ID: b2a0d9abe43b455fb49484dbaa59dc41
Virtualization: vmware
Operating System: Ubuntu 18.04.1 LTS
Kernel: Linux 4.15.0-29-generic
Architecture: x86-64

Убедитесь, что DNS настроен правильно:
$ cat /etc/resolv.conf

Ubuntu 20.04 | 18.04 поставляется с systemd-resolve, который вам нужно отключить, чтобы сервер мог напрямую обращаться к вашему сетевому DNS.

sudo systemctl disable systemd-resolved
sudo systemctl stop systemd-resolved

Если вы используете DHCP, вы можете обновить DNS-сервер вручную.
$ sudo unlink /etc/resolv.conf
$ sudo vim /etc/resolv.conf

Шаг 3. Установите необходимые пакеты

Для присоединения системы Ubuntu 20.04 | 18.04 / Debian 10 к домену Active Directory (AD) требуется ряд пакетов.

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

Только после успешной установки зависимостей вы можете приступить к обнаружению домена Active Directory в Debian 10 / Ubuntu 20.04 / 18.04.

Команда realm discover возвращает полную конфигурацию домена и список пакетов, которые должны быть установлены для регистрации системы в домене.

$ sudo realm discover example.com
example.com
type: kerberos
realm-name: EXAMPLE.COM
domain-name: example.com
configured: no
server-software: active-directory
client-software: sssd
required-package: sssd-tools
required-package: sssd
required-package: libnss-sss
required-package: libpam-sss
required-package: adcli
required-package: samba-common-bin

Замените example.com своим действующим доменом AD.

Шаг 5. Присоединитесь к Ubuntu 20.04 | 18.04 / Debian 10 к домену Active Directory (AD)

Учетная запись администратора AD требуется для интеграции вашего компьютера Linux с доменом Windows Active Directory. Проверьте и подтвердите учетную запись администратора AD и пароль.

Команда realm join настроит локальный компьютер для использования с указанным доменом, настроив как локальные системные службы, так и записи в домене идентификации. У команды есть несколько параметров, которые можно проверить с помощью:

$ realm join --help
Базовое выполнение команды:
$ sudo realm join -U Administrator example.com
Password for Administrator:

Где:

Администратор – это имя учетной записи администратора, используемой для интеграции машины в AD.
example.com – это имя домена AD

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

Просмотр сведений о текущей области.

$ realm list
example.com
type: kerberos
realm-name: EXAMPLE.COM
domain-name: example.com
configured: kerberos-member
server-software: active-directory
client-software: sssd
required-package: sssd-tools
required-package: sssd
required-package: libnss-sss
required-package: libpam-sss
required-package: adcli
required-package: samba-common-bin
login-formats: %U@example.com
login-policy: allow-realm-logins

В системах на основе RHEL домашний каталог пользователя будет создан автоматически. В Ubuntu / Debian вам необходимо включить эту функцию.

sudo bash -c "cat > /usr/share/pam-configs/mkhomedir" <<EOF
Name: activate mkhomedir
Default: yes
Priority: 900
Session-Type: Additional
Session:
required pam_mkhomedir.so umask=0022 skel=/etc/skel
EOF

Затем активируйте с помощью:
sudo pam-auth-update

Выберите <OK>

Ввести в домен Active Directory (AD) линукс Ubuntu 20.04 | 18.04 / Debian 10

Убедитесь, что выбрано “activate mkhomedir” с помощью звездочки – [*]

Ввести в домен Active Directory (AD) линукс Ubuntu 20.04 | 18.04 / Debian 10

Затем выберите <Ok>, чтобы сохранить изменения.

Ваш файл конфигурации sssd.conf находится в /etc/sssd/sssd.conf . При каждом изменении файла требуется перезагрузка.

Статус должен быть запущен.

$ systemctl status sssd

Если интеграция работает, должна быть возможность получить информацию о пользователе AD.
$ id jmutai@example.com
uid=1783929917(jmutai@example.com) gid=1784800513(domain users@example.com) groups=1783870513(domain users@example.com)

Шаг 6. Контроль доступа – Ограничьте до пользователя / группы

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

Ограничение для пользователей

Чтобы разрешить пользователю доступ через SSH и консоль, используйте команду:

$ sudo realm permit user1@example.com
$ sudo realm permit user2@example.com user3@example.com

Разрешить доступ к группе – Примеры
$ sudo ream permit -g sysadmins
$ sudo realm permit -g 'Security Users'
$ sudo realm permit 'Domain Users' 'admin users'

Это изменит файл sssd.conf .

Если вместо этого вы хотите разрешить доступ всем пользователям, запустите:

$ sudo realm permit --all
Чтобы запретить доступ всем пользователям домена, используйте:
$ sudo realm deny --all

Шаг 7. Настройте доступ через Sudo

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

Давайте сначала создадим файл разрешений sudo.

$ sudo vi /etc/sudoers.d/domain_admins
Добавить одного пользователя:
user1@example.com ALL=(ALL) ALL
Добавить еще одного пользователя:
user1@example.com ALL=(ALL) ALL
user2@example.com ALL=(ALL) ALL

Добавить группу
%group1@example.com ALL=(ALL) ALL

Добавьте группу с пробелами.

%security\ users@example.com ALL=(ALL) ALL
%system\ super\ admins@example.com ALL=(ALL) ALL

Шаг 8. Проверьте доступ по SSH

Получите доступ к серверу удаленно, поскольку пользователю AD разрешено входить в систему.

$ ssh user1@localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is SHA256:wmWcLi/lijm4zWbQ/Uf6uLMYzM7g1AnBwxzooqpB5CU.
ECDSA key fingerprint is MD5:10:0c:cb:22:fd:28:34:c6:3e:d7:68:15:02:f9:b4:e9.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.

Это подтверждение того, что наша конфигурация прошла успешно.

Посетите вики-страницы realmd и sssd, чтобы узнать больше.

Оригинал статьи на английском здесь.

  • Windows server 2022 ключик для активации
  • Windows server core active directory
  • Windows server dns server local
  • Windows server backup 2012 r2 настройка
  • Windows server 2019 установка и настройка роль hyper v