Это старая версия документа.


Kerberos

Kerberos это система сетевой аутентифиации, основанная на принципах доверия третьей стороне. Другие две стороны - это пользователь и сервис, на котором он хочет авторизоваться. Не все сервисы и приложения могут использовать Kerberos, но те, которые могут, приближают сетевое окружение на один шаг к технологии единого входа (Single Sign On - SSO).

Этот раздел раскрывает установку и настройку сервера Kerberos, а также некоторые примеры клиентских настроек.

Обзор

Если вы новичок в Kerberos, есть несколько терминов, которые хорошо понять до установки сервера Kerberos. Большинство терминов связаны с вещами, которые могут быть вам знакомы по другим окружениям:

  1. Доверитель (Principal): любые пользователи, компьютеры или сервисы, предоставляемые серверами, должны быть определены как доверители Kerberos .

  2. Требования (Instances): используются для сервисных и специальных административных доверителей.

  3. Области (Realms): уникальная область управления, предоставляемая установкой Kerberos. Представляйте ее себе как домен или группу ваших компьютеров и пользователей, ей принадлежащих. По умолчанию Ubuntu использует имя DNS домена в верхнем регистре (EXAMPLE.COM) в качестве области.

  4. Центр распространения ключей (KDC): состоит из трех частей: базы данных всех доверителей, сервера аутентификации и сервера предоставления билетов. Для каждой области должен быть хотя бы один KDC.

  5. Билет для получения билета (TGT): изданный сервером аутентификации, TGT зашифровывается на пароле пользователя, который известен только пользователю и KDC.

  6. Сервер распространения билетов (TGS): выпускает сервисные билеты для клиентов по запросу.

  7. Билеты (Tickets): подтверждение идентичности двух доверителей. Один доверитель - пользователь, а другой - сервис, запрашиваемый этим пользователем. Билеты устанавливают секретный ключ, используемый для защищенного соединения во время авторизованной сессии.

  8. Файлы ключей (Keytab Files): файлы, извлеченные из базы доверителей KDC и содержащие ключ шифрования для сервиса или компьютера.

Чтобы сложить все вместе: Область содержит как минимум один KDC, лучше больше для обеспечения безотказности, который содержит базу данных Доверителей. Когда пользователь-доверитель заходит на рабочую станцию, которая настроена на Kerberos аутентификацию, KDC выпускает билет для получения билетов (TGT). Если пользователь предоставляет совпадающие параметры, он считается аутентифицированным и может запрашивать билеты для сервисов, поддерживающих Kerberos, на сервере распространения билетов (TGS). Сервисные билеты позволяют пользователю аутентифицироваться на сервисах без ввода имени и пароля.

Сервер Kerberos

Установка

Протокол Kerberos разработан в Масачусетском технологическом университете (MIT), поэтому полное название протокола MIT Kerberos. (прим. переводчика).

Для данного обсуждения мы создадим домен MIT Kerberos со следующими параметрами (измените их для соответствия вашим требованиям):

  1. Область: EXAMPLE.COM

  2. Первичный KDC: kdc01.example.com (192.168.0.1)

  3. Вторичный KDC: kdc02.example.com (192.168.0.2)

  4. Пользователь-доверитель: steve

  5. Администратор-доверитель: steve/admin

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

Перед установкой сервера Kerberos требуется правильно настроить DNS сервер для вашего домена. Поскольку область Kerberos по соглашению совпадает с именем домена, этот раздел использует домен EXAMPLE.COM, настроенный как Primary Master по документации DNS.

Также Kerberos - протокол, зависимый от времени. Поэтому если локальное время системы на клиентской машине и на сервере отличается более чем на 5 минут (по умолчанию), рабочая станция не будет аутентифицирована. Для решения проблемы все узлы сети должны синхронизовать свое время по одному серверу NTP. Детали настройки NTP смотрите в разделе Синхронизация времени по NTP.

Первый шаг по созданию области Kerberos - это установка пакетов krb5-kdc и krb5-admin-server. Введите в терминале:

sudo apt-get install krb5-kdc krb5-admin-server

В конце установки у вас запросят сетевые имена серверов Kerberos и административного, которые могут быть одним или разными серверами для определенной области.

По умолчанию область создается из доменного имени KDC.

Далее создаем новую область с помощью утилиты kdb5_newrealm:

sudo krb5_newrealm

Настройка

The questions asked during installation are used to configure the /etc/krb5.conf file. 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

sudo dpkg-reconfigure krb5-kdc

  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:
  sudo kadmin.local
  Authenticating as principal root/admin@EXAMPLE.COM with password.
  kadmin.local: addprinc steve/admin
  WARNING: no policy specified for steve/admin@EXAMPLE.COM; defaulting to no policy
  Enter password for principal "steve/admin@EXAMPLE.COM": 
  Re-enter password for principal "steve/admin@EXAMPLE.COM": 
  Principal "steve/admin@EXAMPLE.COM" created.
  kadmin.local: quit
  In the above example steve is the Principal, /admin is an Instance, and @EXAMPLE.COM signifies the realm. The "every day" Principal, a.k.a. the user principal, would be steve@EXAMPLE.COM, and should have only normal user rights.
  Replace EXAMPLE.COM and steve with your Realm and admin username.
  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:
  steve/admin@EXAMPLE.COM        *
  This entry grants steve/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.
  Now restart the krb5-admin-server for the new ACL to take affect:
  sudo /etc/init.d/krb5-admin-server restart
  The new user principal can be tested using the kinit utility:
  kinit steve/admin
  steve/admin@EXAMPLE.COM's Password:
  After entering the password, use the klist utility to view information about the Ticket Granting Ticket (TGT):
  klist
  Credentials cache: FILE:/tmp/krb5cc_1000
          Principal: steve/admin@EXAMPLE.COM
    Issued           Expires          Principal
  Jul 13 17:53:34  Jul 14 03:53:34  krbtgt/EXAMPLE.COM@EXAMPLE.COM
  Where the cache filename krb5cc_1000 is composed of the prefix krb5cc_ and the user id (uid), which in this case is 1000. You may need to add an entry into the /etc/hosts for the KDC so the client can find the KDC. For example:
  192.168.0.1   kdc01.example.com       kdc01
  Replacing 192.168.0.1 with the IP address of your KDC. This usually happens when you have a Kerberos realm encompassing different networks separated by routers.
  The best way to allow clients to automatically determine the KDC for the Realm is using DNS SRV records. Add the following to /etc/named/db.example.com:
  _kerberos._udp.EXAMPLE.COM.     IN SRV 1  0 88  kdc01.example.com.
  _kerberos._tcp.EXAMPLE.COM.     IN SRV 1  0 88  kdc01.example.com.
  _kerberos._udp.EXAMPLE.COM.     IN SRV 10 0 88  kdc02.example.com. 
  _kerberos._tcp.EXAMPLE.COM.     IN SRV 10 0 88  kdc02.example.com. 
  _kerberos-adm._tcp.EXAMPLE.COM. IN SRV 1  0 749 kdc01.example.com.
  _kpasswd._udp.EXAMPLE.COM.      IN SRV 1  0 464 kdc01.example.com.
  Replace EXAMPLE.COM, kdc01, and kdc02 with your domain name, primary KDC, and secondary KDC.
  See Domain Name Service (DNS) for detailed instructions on setting up DNS.

Your new Kerberos Realm is now ready to authenticate clients.

Вторичный 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.

  First, install the packages, and when asked for the Kerberos and Admin server names enter the name of the Primary KDC:
  sudo apt-get install krb5-kdc krb5-admin-server
  Once you have the packages installed, create the Secondary KDC's host principal. From a terminal prompt, enter:
  kadmin -q "addprinc -randkey host/kdc02.example.com"
  After, issuing any kadmin commands you will be prompted for your username/admin@EXAMPLE.COM principal password.
  Extract the keytab file:
  kadmin -q "ktadd -norandkey -k keytab.kdc02 host/kdc02.example.com"
  There should now be a keytab.kdc02 in the current directory, move the file to /etc/krb5.keytab:
  sudo mv keytab.kdc02 /etc/krb5.keytab
  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:
  sudo klist -k /etc/krb5.keytab
  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:
  host/kdc01.example.com@EXAMPLE.COM
  host/kdc02.example.com@EXAMPLE.COM
  Create an empty database on the Secondary KDC:
  sudo kdb5_util -s create
  Now start the kpropd daemon, which listens for connections from the kprop utility. kprop is used to transfer dump files:
  sudo kpropd -S
  From a terminal on the Primary KDC, create a dump file of the principal database:
  sudo kdb5_util dump /var/lib/krb5kdc/dump
  Extract the Primary KDC's keytab file and copy it to /etc/krb5.keytab:
  kadmin -q "ktadd -k keytab.kdc01 host/kdc01.example.com"
  sudo mv keytab.kdc01 /etc/krb5.keytab
  Make sure there is a host for kdc01.example.com before extracting the Keytab.
  Using the kprop utility push the database to the Secondary KDC:
  sudo kprop -r EXAMPLE.COM -f /var/lib/krb5kdc/dump kdc02.example.com
  There should be a SUCCEEDED message if 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 (note the long line has been split to fit the format of this document):
  # m h  dom mon dow   command
  0 * * * * /usr/sbin/kdb5_util dump /var/lib/krb5kdc/dump && 
  /usr/sbin/kprop -r EXAMPLE.COM -f /var/lib/krb5kdc/dump kdc02.example.com
  Back on the Secondary KDC, create a stash file to hold the Kerberos master key:
  sudo kdb5_util stash
  Finally, start the krb5-kdc daemon on the Secondary KDC:
  sudo /etc/init.d/krb5-kdc start

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

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.

Установка

In order to authenticate to a Kerberos Realm, the krb5-user and libpam-krb5 packages are needed, along with a few others that are not strictly necessary but make life easier. To install the packages enter the following in a terminal prompt:

sudo apt-get install krb5-user libpam-krb5 libpam-ccreds auth-client-config

The auth-client-config package allows simple configuration of PAM for authentication from multiple sources, and the libpam-ccreds will cache authentication credentials allowing you to login in case the Key Distribution Center (KDC) is unavailable. This package is also useful for laptops that may authenticate using Kerberos while on the corporate network, but will need to be accessed off the network as well.

Настройка

To configure the client in a terminal enter:

sudo dpkg-reconfigure krb5-config

You will then be prompted to enter the name of the Kerberos Realm. Also, if you don't have DNS configured with Kerberos SRV records, the menu will prompt you for the hostname of the Key Distribution Center (KDC) and Realm Administration server.

The dpkg-reconfigure adds entries to the /etc/krb5.conf file for your Realm. You should have entries similar to the following:

[libdefaults]

      default_realm = EXAMPLE.COM

… [realms]

      EXAMPLE.COM = }                
              kdc = 192.168.0.1               
              admin_server = 192.168.0.1
      }

If you set the uid of each of your network-authenticated users to start at 5000, as suggested in Installation, you can then tell pam to only try to authenticate using Kerberos users with uid > 5000:

# Kerberos should only be applied to ldap/kerberos users, not local ones. for i in common-auth common-session common-account common-password; do sudo sed -i -r \ -e 's/pam_krb5.so minimum_uid=1000/pam_krb5.so minimum_uid=5000/' \ /etc/pam.d/$i done

This will avoid being asked for the (non-existent) Kerberos password of a locally authenticated user when changing its password using passwd.

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

kinit steve@EXAMPLE.COM Password for steve@EXAMPLE.COM:

When a ticket has been granted, the details can be viewed using klist:

klist Ticket cache: FILE:/tmp/krb5cc_1000 Default principal: steve@EXAMPLE.COM

Valid starting Expires Service principal 07/24/08 05:18:56 07/24/08 15:18:56 krbtgt/EXAMPLE.COM@EXAMPLE.COM

      renew until 07/25/08 05:18:57

Kerberos 4 ticket cache: /tmp/tkt1000 klist: You have no tickets cached

Next, use the auth-client-config to configure the libpam-krb5 module to request a ticket during login:

sudo auth-client-config -a -p kerberos_example

You will should now receive a ticket upon successful login authentication.

Ссылки

  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.
  Also, feel free to stop by the #ubuntu-server and #kerberos IRC channels on Freenode if you have Kerberos questions.