Настройка аутентификации kerberos ubuntu

Обновлено: 06.07.2024

Kerberos is a network authentication system based on the principal of a trusted third party. The other two parties being the user and the service the user wishes to authenticate to. Not all services and applications can use Kerberos, but for those that can, it brings the network environment one step closer to being Single Sign On (SSO).

This section covers installation and configuration of a Kerberos server, and some example client configurations.

Overview

If you are new to Kerberos there are a few terms that are good to understand before setting up a Kerberos server. Most of the terms will relate to things you may be familiar with in other environments:

Principal: any users, computers, and services provided by servers need to be defined as Kerberos Principals.

Instances: are used for service principals and special administrative principals.

Key Distribution Center: (KDC) consist of three parts: a database of all principals, the authentication server, and the ticket granting server. For each realm there must be at least one KDC.

Ticket Granting Ticket: issued by the Authentication Server (AS), the Ticket Granting Ticket (TGT) is encrypted in the user’s password which is known only to the user and the KDC.

Ticket Granting Server: (TGS) issues service tickets to clients upon request.

Tickets: confirm the identity of the two principals. One principal being a user and the other a service requested by the user. Tickets establish an encryption key used for secure communication during the authenticated session.

Keytab Files: are files extracted from the KDC principal database and contain the encryption key for a service or host.

To put the pieces together, a Realm has at least one KDC, preferably more for redundancy, which contains a database of Principals. When a user principal logs into a workstation that is configured for Kerberos authentication, the KDC issues a Ticket Granting Ticket (TGT). If the user supplied credentials match, the user is authenticated and can then request tickets for Kerberized services from the Ticket Granting Server (TGS). The service tickets allow the user to authenticate to the service without entering another username and password.

Kerberos Server

Installation

For this discussion, we will create a MIT Kerberos domain with the following features (edit them to fit your needs):

User principal: ubuntu

Admin principal: ubuntu/admin

Note

It is strongly recommended that your network-authenticated users have their uid in a different range (say, starting at 5000) than that of your local users.

Also, Kerberos is a time sensitive protocol. So if the local system time between a client machine and the server differs by more than five minutes (by default), the workstation will not be able to authenticate. To correct the problem all hosts should have their time synchronized using the same Network Time Protocol (NTP) server. Check out the NTP chapter for more details.

The first step in creating a Kerberos Realm is to install the krb5-kdc and krb5-admin-server packages. From a terminal enter:

You will be asked at the end of the install to supply the hostname for the Kerberos and Admin servers, which may or may not be the same server, for the realm. Since we are going to create the realm, and thus these servers, type in the full hostname of this server.

Note

By default the realm is created from the KDC’s domain name.

Next, create the new realm with the kdb5_newrealm utility:

It will ask you for a database master password, which is used to encrypt the local database. Chose a secure password: its strength is not verified for you.

Configuration

The questions asked during installation are used to configure the /etc/krb5.conf and /etc/krb5kdc/kdc.conf files. The former is used by the kerberos 5 libraries, and the latter configures the KDC. If you need to adjust the Key Distribution Center (KDC) settings simply edit the file and restart the krb5-kdc daemon. If you need to reconfigure Kerberos from scratch, perhaps to change the realm name, you can do so by typing

Note

The manpage for krb5.conf is in the krb5-doc package.

Once the KDC is properly running, an admin user – the admin principal – is needed. It is recommended to use a different username from your everyday username. Using the kadmin.local utility in a terminal prompt enter:

Next, the new admin user needs to have the appropriate Access Control List (ACL) permissions. The permissions are configured in the /etc/krb5kdc/kadm5.acl file:

This entry grants ubuntu/admin the ability to perform any operation on all principals in the realm. You can configure principals with more restrictive privileges, which is convenient if you need an admin principal that junior staff can use in Kerberos clients. Please see the kadm5.acl man page for details.

Note

The extract privilege is not included in the wildcard privilege; it must be explicitly assigned. his privilege allows the user to extract keys from the database, and must be handled with great care to avoid disclosure of important keys like those of the kadmin/* or krbtgt/* principals. See the kadm5.acl man page for details.

Now restart the krb5-admin-server for the new ACL to take affect:

The new user principal can be tested using the kinit utility:

After entering the password, use the klist utility to view information about the Ticket Granting Ticket (TGT):

Where the cache filename krb5cc_1000 is composed of the prefix krb5cc_ and the user id (uid), which in this case is 1000 .

See the DNS chapter for detailed instructions on setting up DNS.

Your new Kerberos Realm is now ready to authenticate clients.

Secondary KDC

Once you have one Key Distribution Center (KDC) on your network, it is good practice to have a Secondary KDC in case the primary becomes unavailable. Also, if you have Kerberos clients that are in different networks (possibly separated by routers using NAT), it is wise to place a secondary KDC in each of those networks.

Note

The native replication mechanism explained here relies on a cronjob, and essentially dumps the DB on the primary and loads it back up on the secondary. You may want to take a look at using the kldap backend which can use the OpenLDAP replication mechanism. It is explained further below.

First, install the packages, and when asked for the Kerberos and Admin server names enter the name of the Primary KDC:

Once you have the packages installed, create the host principals for both KDCs. From a terminal prompt, enter:

Make sure the principal you are using has the extra extract-keys privilege in kdc01 's /etc/krb5kdc/kadm5.acl file. Something like this:

Where “*” means all privileges (except extract-keys ), and e means exactly extract-keys .

Extract the keytab file:

There should now be a keytab.kdc02 in the current directory, move the file to /etc/krb5.keytab :

Note

If the path to the keytab.kdc02 file is different adjust accordingly.

Also, you can list the principals in a Keytab file, which can be useful when troubleshooting, using the klist utility:

The -k option indicates the file is a keytab file.

Next, there needs to be a kpropd.acl file on each KDC that lists all KDCs for the Realm. For example, on both primary and secondary KDC, create /etc/krb5kdc/kpropd.acl :

Create an empty database on the Secondary KDC:

Now install kpropd daemon, which listens for connections from the kprop utility from the primary kdc:

The service will be running right after installation.

From a terminal on the Primary KDC, create a dump file of the principal database:

Still on the Primary KDC, extract its keytab file and copy it to /etc/krb5.keytab :

Note

You can now remove the extract-keys privilege from this principal in kdc01 's /etc/krb5kdc/kadm5.acl file

On the Primary KDC, run the kprop utility to push the database dump made before to the Secondary KDC:

Note the SUCCEEDED message, which signals that the propagation worked. If there is an error message check /var/log/syslog on the secondary KDC for more information.

You may also want to create a cron job to periodically update the database on the Secondary KDC. For example, the following will push the database every hour:

Back on the Secondary KDC, create a stash file to hold the Kerberos master key:

Finally, start the krb5-kdc daemon on the Secondary KDC:

Note

The Secondary KDC does not run an admin server, since it’s a read-only copy

The Secondary KDC should now be able to issue tickets for the Realm. You can test this by stopping the krb5-kdc daemon on the Primary KDC, then by using kinit to request a ticket. If all goes well you should receive a ticket from the Secondary KDC. Otherwise, check /var/log/syslog and /var/log/auth.log in the Secondary KDC.

Kerberos Linux Client

This section covers configuring a Linux system as a Kerberos client. This will allow access to any kerberized services once a user has successfully logged into the system.

Note that Kerberos alone is not enough for a user to exist in a Linux system. Meaning, we cannot just point the system at a kerberos server and expect all the kerberos principals to be able to login on the linux system, simply because these users do not exist locally. Kerberos only provides authentication: it doesn’t know about user groups, Linux uids and gids, home directories, etc. Normally another network source is used for this information, such as an LDAP or Windows server, and, in the old days, NIS was used for that as well.

Installation

If you have local users matching the principals in a Kerberos realm, and just want to switch the authentication from local to remote using Kerberos, you can follow this section. This is not a very usual scenario, but serves to highlight the separation between user authentication and user information (full name, uid, gid, home directory, groups, etc). If you just want to be able to grab tickets and use them, it’s enough to install krb5-user and run kinit .

We are going to use sssd with a trick so that it will fetch the user information from the local system files, instead of a remote source which is the common case.

To install the packages enter the following in a terminal prompt:

Note

If you have added the appropriate SRV records to DNS, none of those prompts will need answering.

Configuration

If you missed the questions earlier, you can reconfigure the package to fill them in again: sudo dpkg-reconfigure krb5-config .

You can test the kerberos configuration by requesting a ticket using the kinit utility. For example:

Note

kinit doesn’t need for the principal to exist as a local user in the system. In fact, you can kinit any principal you want. If you don’t specify one, then the tool will use the username of whoever is running kinit .

Since we are at it, let’s also create a non-admin principal for ubuntu :

The only remaining configuration now is for sssd . Create the file /etc/sssd/sssd.conf with the following content:

The above configuration will use kerberos for authentication ( auth_provider ), but will use the local system users for user and group information ( id_provider ).

Adjust the permissions of the config file and start sssd :

Just by having installed sssd and its dependencies, PAM will already have been configured to use sssd , with a fallback to local user authentication. To try it out, if this is a workstation, simply switch users (in the GUI), or open a login terminal (CTRL-ALT-<number>), or spawn a login shell with sudo login , and try logging in using the name of a kerberos principal. Remember that this user must already exist on the local system:

And you will have a Kerberos ticket already right after login.

Resources

For more information on MIT’s version of Kerberos, see the MIT Kerberos site.

The Ubuntu Wiki Kerberos page has more details.

O’Reilly’s Kerberos: The Definitive Guide is a great reference when setting up Kerberos.


В продолжение давней темы про использование двухфакторной аутентификации в ОС GNU/Linux позвольте рассказать про схему работы и настройку аутентификации с помощью Kerberos. В этой статье мы рассмотрим процесс настройки MIT Kerberos для аутентификации пользователей по сертификатам и ключевым парам, находящимся на USB-токене. Также материалы, изложенные в статье, можно использовать для настройки аутентификации в домене Windows.

Для начала проведем небольшой ликбез по терминологии Kerberos и рассмотрим доступные реализации этого протокола в ОС на базе GNU/Linux. Сразу оговорюсь, что мне не удалось найти однозначного перевода терминов, использующихся в Kerberos, поэтому для избежания путаницы основные термины я буду дублировать на английском.
Итак, начнем. Если процитировать Википедию, то
Kerberos – сетевой протокол аутентификации, позволяющий передавать данные через незащищённые сети для безопасной идентификации. Ориентирован, в первую очередь, на клиент-серверную модель и обеспечивает взаимную аутентификацию – оба пользователя через сервер подтверждают личности друг друга.

Стоит отметить, что Kerberos в первую очередь является протоколом, а не конкретной системой аутентификации. Его реализации используются в различных операционных системах, в том числе и в Windows, как метод аутентификации пользователей в домене. Существует несколько open source реализаций протокола Kerberos, например оригинальная MIT Kerberos и Heimdal. Такой зоопарк возник из-за ограничений США на экспорт криптографических средств защиты информации, на сегодня эта ситуация вокруг MIT Kerberos уже улеглась. В статье мы рассмотрим процесс настройки для MIT Kerberos V5.

  • Билет (ticket) – временные данные, выдаваемые клиенту для аутентификации на сервере, на котором располагается необходимая служба.
  • Клиент (client) – некая сущность в сети (пользователь, хост или сервис), которая может получить билет от Kerberos.
  • Центр выдачи ключей (key distribution center, KDC) – сервис, выдающий билеты Kerberos.
  • Область (realm) – сеть, используемая Kerberos, состоящая из серверов KDC и множества клиентов. Имя realm регистрозависимо, обычно пишется в верхнем регистре и совпадает с именем домена.
  • Принципал (principal) – уникальное имя для клиента, для которого разрешается аутентификация в Kerberos. Записывается в виде root[/instance]@REALM.

Файлы настроек Kerberos

На сервере:
На клиенте и сервере:
  • /etc/kbr5.conf — настройки сервера аутентификации (описание realms, доменных имен и других настроек)

Для начала необходимо развернуть среду, в которой будет производиться аутентификация. Наиболее просто это сделать, взяв две виртуальные машины, находящиеся в одной подсети. Достаточно установить на одну виртуальную машину какую-нибудь Ubuntu (это будет наш сервер), а затем клонировать ее и получить клиента. При написании статьи я воспользовался свежей Ubuntu 12.10 (x86) и виртуальной машиной от VMWare. Чтобы виртуальным машинам было удобнее видеть друг друга по сети, стоит переключить сетевые карты в Bridged-режим.
Важно! Следите за тем, чтобы время на клиенте и сервере было синхронизировано, это необходимо для корректной работы Kerberos.

Настройка сети


Клиенты Kerberos ищут свои сервера по доменным именам, поэтому необходимо настроить DNS и убедиться, что имена серверов успешно разрешаются. В нашем примере достаточно занести доменное имя сервера в /etc/hosts, что я и сделал. Схема «сети» изображена ниже.

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

На сервере нам потребуются:
  • krb5-kdc – сервис KDC
  • krb5-admin-server – административный сервер Kerberos (он ведет контроль учетных записей пользователей)
  • krb5-pkinit – модуль расширения Kerberos для аутентификации по сертификатам
На клиент надо поставить следующие пакеты:

Базовые настройки

После установки пакетов на сервере нужно инициализировать realm командой
А на клиенте – обновить файлы конфигурации:
Также на клиенте и сервере надо добавить следующие строки в /etc/krb5.conf:
Теперь создадим на сервере нового пользователя c именем testuser
На клиенте теперь можно проверить, правильно ли мы настроили сеть и Kerberos:

Настройка аутентификации по открытому ключу

Для работы модуля pkinit нам придется воспользоваться openssl в качестве мини-УЦ, чтобы создать ключевые пары и сертификаты клиента и сервера.
На сервере:
  • Extended Key Usage (EKU) – идентификатор (OID), говорящий о том, как планируется использовать сертификат
  • otherName – поле, задающее нашего принципала, для которого выписывается сертификат
  • kdc.pem
  • kdckey.pem
  • cacert.pem
Дальнейшие действия будем выполнять на клиенте

Ранее при настройке клиентской машины мы поставили пакет libpam-krb5. Он поможет нам выполнить аутентификацию в Kerberos при входе в систему, а также в приложениях, использующих системную аутентификацию (например login, lightdm и проч.). Для подключения модуля PAM достаточно выполнить команду
и выбрать в диалоге необходимые модули аутентификации. Для более тонкой настройки можно заглянуть в файл /etc/pam.d/common-auth и отредактировать его по желанию. Структуру файла я описывал в предыдущей статье.

Применение протокола Kerberos для централизованной аутентификации в связке с централизованным созданием хранением и раздачей учетных записей (например, посредством каталога на базе OpenLDAP) позволяет создать «домен UNIX», полностью состоящий из машин под управлением свободного программного обеспечения. Такое решение может применяться в корпоративном секторе, а аутентификация по смарт-картам будет приятным бонусом как для администраторов, так и для пользователей сети компании.


В продолжение давней темы про использование двухфакторной аутентификации в ОС GNU/Linux позвольте рассказать про схему работы и настройку аутентификации с помощью Kerberos. В этой статье мы рассмотрим процесс настройки MIT Kerberos для аутентификации пользователей по сертификатам и ключевым парам, находящимся на USB-токене. Также материалы, изложенные в статье, можно использовать для настройки аутентификации в домене Windows.

Для начала проведем небольшой ликбез по терминологии Kerberos и рассмотрим доступные реализации этого протокола в ОС на базе GNU/Linux. Сразу оговорюсь, что мне не удалось найти однозначного перевода терминов, использующихся в Kerberos, поэтому для избежания путаницы основные термины я буду дублировать на английском.
Итак, начнем. Если процитировать Википедию, то
Kerberos – сетевой протокол аутентификации, позволяющий передавать данные через незащищённые сети для безопасной идентификации. Ориентирован, в первую очередь, на клиент-серверную модель и обеспечивает взаимную аутентификацию – оба пользователя через сервер подтверждают личности друг друга.

Стоит отметить, что Kerberos в первую очередь является протоколом, а не конкретной системой аутентификации. Его реализации используются в различных операционных системах, в том числе и в Windows, как метод аутентификации пользователей в домене. Существует несколько open source реализаций протокола Kerberos, например оригинальная MIT Kerberos и Heimdal. Такой зоопарк возник из-за ограничений США на экспорт криптографических средств защиты информации, на сегодня эта ситуация вокруг MIT Kerberos уже улеглась. В статье мы рассмотрим процесс настройки для MIT Kerberos V5.

  • Билет (ticket) – временные данные, выдаваемые клиенту для аутентификации на сервере, на котором располагается необходимая служба.
  • Клиент (client) – некая сущность в сети (пользователь, хост или сервис), которая может получить билет от Kerberos.
  • Центр выдачи ключей (key distribution center, KDC) – сервис, выдающий билеты Kerberos.
  • Область (realm) – сеть, используемая Kerberos, состоящая из серверов KDC и множества клиентов. Имя realm регистрозависимо, обычно пишется в верхнем регистре и совпадает с именем домена.
  • Принципал (principal) – уникальное имя для клиента, для которого разрешается аутентификация в Kerberos. Записывается в виде root[/instance]@REALM.

Файлы настроек Kerberos

На сервере:
На клиенте и сервере:
  • /etc/kbr5.conf — настройки сервера аутентификации (описание realms, доменных имен и других настроек)

Для начала необходимо развернуть среду, в которой будет производиться аутентификация. Наиболее просто это сделать, взяв две виртуальные машины, находящиеся в одной подсети. Достаточно установить на одну виртуальную машину какую-нибудь Ubuntu (это будет наш сервер), а затем клонировать ее и получить клиента. При написании статьи я воспользовался свежей Ubuntu 12.10 (x86) и виртуальной машиной от VMWare. Чтобы виртуальным машинам было удобнее видеть друг друга по сети, стоит переключить сетевые карты в Bridged-режим.
Важно! Следите за тем, чтобы время на клиенте и сервере было синхронизировано, это необходимо для корректной работы Kerberos.

Настройка сети


Клиенты Kerberos ищут свои сервера по доменным именам, поэтому необходимо настроить DNS и убедиться, что имена серверов успешно разрешаются. В нашем примере достаточно занести доменное имя сервера в /etc/hosts, что я и сделал. Схема «сети» изображена ниже.

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

На сервере нам потребуются:
  • krb5-kdc – сервис KDC
  • krb5-admin-server – административный сервер Kerberos (он ведет контроль учетных записей пользователей)
  • krb5-pkinit – модуль расширения Kerberos для аутентификации по сертификатам
На клиент надо поставить следующие пакеты:

Базовые настройки

После установки пакетов на сервере нужно инициализировать realm командой
А на клиенте – обновить файлы конфигурации:
Также на клиенте и сервере надо добавить следующие строки в /etc/krb5.conf:
Теперь создадим на сервере нового пользователя c именем testuser
На клиенте теперь можно проверить, правильно ли мы настроили сеть и Kerberos:

Настройка аутентификации по открытому ключу

Для работы модуля pkinit нам придется воспользоваться openssl в качестве мини-УЦ, чтобы создать ключевые пары и сертификаты клиента и сервера.
На сервере:
  • Extended Key Usage (EKU) – идентификатор (OID), говорящий о том, как планируется использовать сертификат
  • otherName – поле, задающее нашего принципала, для которого выписывается сертификат
  • kdc.pem
  • kdckey.pem
  • cacert.pem
Дальнейшие действия будем выполнять на клиенте

Ранее при настройке клиентской машины мы поставили пакет libpam-krb5. Он поможет нам выполнить аутентификацию в Kerberos при входе в систему, а также в приложениях, использующих системную аутентификацию (например login, lightdm и проч.). Для подключения модуля PAM достаточно выполнить команду
и выбрать в диалоге необходимые модули аутентификации. Для более тонкой настройки можно заглянуть в файл /etc/pam.d/common-auth и отредактировать его по желанию. Структуру файла я описывал в предыдущей статье.

Применение протокола Kerberos для централизованной аутентификации в связке с централизованным созданием хранением и раздачей учетных записей (например, посредством каталога на базе OpenLDAP) позволяет создать «домен UNIX», полностью состоящий из машин под управлением свободного программного обеспечения. Такое решение может применяться в корпоративном секторе, а аутентификация по смарт-картам будет приятным бонусом как для администраторов, так и для пользователей сети компании.

Kerberos is an authentication protocol using a combination of secret-key cryptography and trusted third parties to allow secure authentication to network services over untrusted networks. More information about the Kerberos protocol is available from MIT's Kerberos site. Designing an Authentication System is an accessible introduction to the principals of Kerberos' authentication scheme.

This guide aims to supplement the documentation available in the official Ubuntu documentation by re-iterating certain key concepts in more detail and providing information on network service configuration. It is directed at system administrators that need to supplement their understanding of Kerberos and its advanced configuration.

Several Kerberos implementations exist. Two common open-source implementation of the Kerberos protocol are the original MIT implementation, and Heimdal, an implementation that was created to avoid United States export regulations. These regulations are no longer a concern, and for sake of brevity, this guide will provide instructions for the MIT version. The same concepts apply to Heimdal, although the syntax of various commands is different.

Microsoft's Active Directory is a common closed-source implementation of a Kerberos authentication realm. The following guide contains several notes that give specific configuration information for Active Directory. In an Active Directory environment, the KDC is typically one of the services provided by the Domain Controller (DC). Readers wishing to integrate with an Active Directory Domain can skip directly to the Client Configuration section.

A central part of Kerberos' trusted third party authentication scheme is the Key Distribution Center (KDC), which is a centralized repository for users' password information. Before deploying Kerberos, a server must be selected to take on the role of KDC. Physical and network security will be critical for this server, since a compromised KDC compromises the security of the entire realm.

All servers and clients that participate in a Kerberos realm must be able to communicate with each other and have accurate system clocks. The following section describes how to meet these requirements.

Host Names

Each server in a Kerberos authentication realm must be assigned a Fully Qualified Domain Name (FQDN) that is forward-resolvable.

Kerberos also expects the server's FQDN to be reverse-resolvable. If reverse domain name resolution is not available, set the rdns variable to false in clients' krb5.conf

Note: Active Directory depends heavily on DNS, so it is likely that the Active Directory Domain Controller is also running the Microsoft DNS server package. If this is the case, verify that each server has a FQDN assigned to it before performing the tests outlined in this section.

If the server already has an FQDN assigned to it, test forward and reverse look-up with the following commands:

The output of the first command should contain the IP address of the server. The output of the second command should contain the FQDN of the server.

If the server does not already have a FQDN assigned to it and DNS services are not available, name resolution can be implemented by editing the local hosts file (typically this is located in /etc) on each server and client, adding the following line:

Test the local DNS name resolution using the nslookup technique described at the beginning of the section.

Connectivity

To verify connectivity between hosts, ping each host's FQDN:

The output of the ping command shows successful resolution of the FQDN to an IP Address, and a sample reply from the server. A reply from the server serves as confirmation that the host and the server can communicate.

Connectivity failures while pinging the KDC's FQDN usually point to DNS server or client configuration errors. See the Network Configuration for information on correct network settings.

Time Synchronization

The Kerberos protocol requires the time of the client and server to match: if the system clocks of the client does not match that of the server, authentication will fail. The simplest way to synchronize the system clocks is to use a Network Time Protocol (NTP) server. See UbuntuTime for details.

Note: Active Directory Domain Controllers are typically also NTP servers.

Firewalls

As with all network services, Kerberos must be allowed to pass through any firewalls between hosts. The Kerberos System Administration Manual has a detailed section on this topic.

These packages are available from the Main repository. See InstallingSoftware for details on software installation, repositories and package management.

  • disable Kerberos 4 compatibility mode
  • do not run krb524d (daemon to convert Kerberos tickets between versions)
  • defaults for the other settings are acceptable

The default location of the KDC's configuration file is /etc/krb5kdc/kdc.conf. Important settings are the locations of the KDC's data files, and the default settings for the durations that tickets are valid. The realm name must be configured; other configuration options should only be changed by knowledgable users.

Here is an example configuration file:

Kerberos uses an Access Control List (ACL) to specify the per-principal access rights to the Kerberos admin daemon. This file's default location is /etc/krb5kdc/kadm5.acl. The default as shown below is sufficient for most realms, but additional ACLs may be necessary depending on the network configuration.

Create the Kerberos database with the following command:

Principals

Principals are entries in the Kerberos database that represent users or services on the network. Each user or service that is participates in a Kerberos authentication realm must have a principal defined in the Kerberos database.

Principal names are case sensitive.

Realm Administration: kadmin

The Kerberos realm is administered using the kadmin utility. The kadmin utility is an interactive interface that allows the administrator to create, retrieve, update, and delete realm principals. kadmin can be run on any computer that is part of the Kerberos realm, provided the user has the proper credentials. However, for security reasons, it is best to run kadmin on a KDC.

An alternative program, kadmin.local, is available as well. Running kadmin.local as the root user on the KDC allows the administrator to authenticate without having an existing principal. This is generally not necessary in a properly configured environment.

To start the kadmin utility, issue the following command:

Replace <principal> with a valid principal name. By default, the principal admin/admin has administrative rights to the realm, so to launch kadmin as the realm administrator, use:

Type ? and press Enter at the kadmin prompt to see a list of valid commands.

Common tasks

Publish Realm Info Via DNS

Client configuration can be simplified by publishing information about the Kerberos realm via DNS. This is accomplished by adding SRV records that point to the Kerberos KDC.

See BIND9ServerHowto for information on configuring DNS services with BIND.

With this DNS configuration in place, it should not be necessary to add information to the /etc/krb5.conf on client computers: the Kerberos software should get all necessary realm information from the DNS server. The kadmin utility still seems to require the [domain_realm] mappings, though.

Note: Verify the clients meet the criteria laid out in the Prerequisites section before installing client software.

Package Installation

These packages are available from the Main repository. See InstallingSoftware for details on software installation, repositories and package management.

Configuration

krb5-config

The krb5-config installation process customizes the /etc/krb5.conf file. Supply your realm name when prompted to enter a default realm. If Kerberos SRV records aren't available via DNS, the installation process will prompt for basic information about the Kerberos realm:

Substitute the FQDN of the KDC for the example answers.

Manual configuration: /etc/krb5.conf

It is also possible to configure the Kerberos client manually by editing /etc/krb5.conf. This approach allows greater customization of the file, but lacks the automation of the krb5-config package. The end result is the same. The following is a sample configuration.

To test the operation of Kerberos, request a Ticket-Granting Ticket (TGT) with the kinit command, as shown. Any valid Kerberos principal can be substituted for "Administrator". Omit the realm name from the command if the default_realm directive is properly specified in the /etc/krb5.conf file or DNS SRV records.

Note: The realm name is CASE SENSITIVE.

Use the klist command to verify the TGT is valid:

If the above tests work, congratulations! You have successfully obtained a Kerberos ticket. This ticket can be used to access network services that use Kerberos for authentication.

The kinit program will attempt to obtain a TGT for the principal <username>@REALM.NAME if run without a '-p' argument where <username> is the username of the local user, and REALM.NAME is the name of the default realm as configured in /etc/krb5.conf

Release the test ticket by issuing the kdestroy command.

Kerberos is frequently used as a source for local authentication through the pam-krb5 module. Adding this module to a host's PAM stack allows users to authenticate to the local host using their Kerberos password. Given a username and password, pam-krb5 will check the supplied password against the password for principal <username>@REALM.NAME. The pam-krb5 module will inform the local system that the user authenticated successfully if the supplied password matches the password of the principal.

The module also establishes a credentials cache when a user has authenticated successfully, allowing the user to utilize Kerberized network services without entering their credentials a second time.

Installation

Note: Before deploying Kerberized PAM authentication, make sure that each each user has a valid account, either on the local host (via adduser or similar), or through a shared source such as LDAP.

To install the pam-krb5 PAM module, issue the following command from a command prompt:

Configuration

In Ubuntu release 9.04 (Jaunty Jackalope) and newer, the details of PAM configuration are handled by the pam-auth-update utility. To enable or disable Kerberos authentication, run pam-auth-update from a command prompt. More information on pam-auth-update is available in its documentation.

For releases prior to Jaunty, a basic configuration can be implemented by adding the following line to the top of the stack in /etc/pam.d/common-auth:

PAM is a highly configurable framework; consult the PAM documentation for more information on advanced configuration options, such as falling back on local password services.

Credential Caching

For roaming hosts such as laptops that may not always have access to the KDC, it is useful to cache credentials using the libpam-ccreds package. Installation is simple:

Once a user has obtained a TGT using kinit, they can use it to prove their identity to a network service such as file sharing or printing. This authentication process is automatic: no password is required to access network services as long as the user's TGT is valid (for security purposes, tickets expire after a period of time, and must be renewed).

Services use files called keytabs that contain a secret known only to the service and the KDC. The user authenticates themself to the KDC, and then requests information from the KDC that is encrypted using the service's shared secret. This encrypted message is sent to the client, which sends it to the service. If the service can decrypt and read the message (and the user passes other security checks), the service accepts the user's identity.

Generating Keytabs

The realm name is optional if the principal is part of the default Kerberos realm as configured in krb5.conf.

Once the principal has been created, create or add to a keytab with the ktadd command in the kadmin interface. To create a keytab for the FTP service from the preceeding example, the command would look like this:

Note: the user running kadmin must have write access to the path specified by the -k argument.

As before, the realm name is optional for principals in the default realm. The keytab's path is also variable, although keytabs typically reside in the host's /etc directory.

It is not necessary to generate the keytab on host for which the keytab is intended. For example, one could simply generate the keytab as indicated on the KDC, save it in a temporary location, and securely transport it (encrypted transport such as scp, or physically via Flash drive) to the intended host.

Security

The security of a keytab is vital: malicious users with access to keytabs can impersonate network services. To avoid this, secure the keytab's file permissions with chmod (this is a system command, not a kadmin command). Using the FTP example, the command looks like this:

The file ownership may also require adjustment to allow access by the FTP daemon.

Service Configuration

Once the keytab is generated, the service must be configured to use it. Consult the documentation of the software package for details on this configuration process.

Remote Login

Apache

Apache supports Kerberized authentication via mod_auth_kerb. The basic configuration utilizes Apache's Basic Auth mechanism. Transport layer encryption (i.e. SSL/TLS) should be deployed if the basic configuration is used; the Basic Auth mechanism does not encrypt login credentials during transmission. 1

It is also possible to configure web browsers to use an existing credentials cache (instead of requiring a user to re-enter their Kerberos username and password) by enabling GSSAPI SPNEGO. Transport layer encryption is not necessary if SPNEGO is used, but the client's browser must be properly configured.

Server

  1. On the Kerberos KDC, create a principal and generate a keytab for the web server:
  2. Securely transport the keytab to the webserver
  3. On the webserver, set the keytab's permissions and ownership:
  4. Install mod_auth_kerb:

Browser

Integration with SASL

Several popular open source software packages (most notably OpenLDAPServer) use Kerberos as an authentication source via the SASL pluggable authentication framework. The following section describes how to install and configure SASL, and verify it is utilizing Kerberos correctly. The details of configuring a service to utilize SASL depend on the package; refer to the service's documentation for details.

Package Installation

We will need the SASL pluggable authentication framework, and the GSSAPI module for the Kerberos implementation in use. Here the MIT implementation is used. Run the following command on the server:

Setup

  1. Create a Kerberos service principal. Follow the naming conventions outlined in the Principals section.
  2. Generate a keytab for the service principal and securely transfer it to the server running the service. Restrict the keytab's file permissions as necessary.

Configured the service to access the correct keytab. Many services will use the system keytab (/etc/krb5.keytab) by default. If the keytab for the service principal is not stored in the system keytab, the service must be configured to read the correct keytab. This is generally done by setting the environment variable KRB5_KTNAME:

Test and Troubleshoot

  1. Make sure the user running the sample server has permission to access to the appropriate keytab. If the keytab for the service principal is stored in a file other than the default system principal (/etc/krb5.keytab), you will need to set the environment variable KRB5_KTNAME:
  2. Start the SASL sample server on the server with the GSSAPI mechanism and the specified service:

Following the KDC logs while attempting an operation can also be very informative. The following lines in /etc/krb5kdc/kdc.conf will enable KDC logging:

If you had to edit kdc.conf to enable logging, restart the KDC to apply the changes:

Once logging is enabled, you can follow the log while attempting an operation:

To backup the Kerberos database:

Parts of this document are derived from the SingleSignOn and Samba/Kerberos documentation. Many thanks to the authors of both documents.

Kerberos (последним исправлял пользователь enlightened-despot 2021-03-07 05:40:04)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Читайте также: