Mit kerberos for windows krb5 ini

mirror of MIT krb5 repository. Contribute to krb5/krb5 development by creating an account on GitHub.
Building & Running Kerberos 5 on Windows —————————————- This file documents how to build MIT Kerberos for Windows. The MIT Kerberos for Windows distribution contains additional components not present in the Unix krb5 distribution, most notably the MIT Kerberos Ticket Manager application. To build Kerberos 5 on Windows, you will need the following: * A version of Visual Studio (at least 2013) which includes the Microsoft Foundation Classes libraries. These instructions will work for Visual Studio 2017 Community or Professional, both of which include the MFC libraries if the «Visual C++ MFC» checkbox is selected after enabling the «Desktop development with C++» workload. If you do not plan to build the graphical ticket manager application, the MFC libraries are not required. * A version of Perl. * Some common Unix utilities such as sed/awk/cp/cat installed in the command-line path. * To build an MSI installer, the Windows Installer XML (WiX) toolkit, and to ensure that the HTML Help Compiler (hhc.exe) and the WiX tools are in your command-line path. WiX version 3.11.1 is verified to work with this codebase. A simple way to get the necessary Unix utilities is to install Git BASH from https://gitforwindows.org and configure it to add the Unix utilities to the command-line path. In some versions of Windows (not the most current versions), the Unix utilities can alternatively be obtained via the Utilities and SDK for UNIX-based Applications, which may be enabled as a Windows feature and then the components installed. Note that the Windows nmake will not find the SUA awk utility in the path unless it is named awk.exe; the permissions on the utility may need correcting if awk.exe is created as a copy of the original awk. Git BASH contains a version of Perl, which will work to build krb5 if the newlines in the source tree are not translated to native newlines. Strawberry Perl will work regardless of whether newlines are translated. If both Git BASH and Strawberry Perl are installed, you may need to adjust the command line path to ensure that the preferred Perl appears first. The krb5 source tree may be obtained either directly on the Windows machine with a native git client cloning the krb5 public mirror at https://github.com/krb5/krb5.git or on a separate (Unix) machine and copied over, such as from a VM host onto a Windows VM. If you are checking out the sources with git and are using the Git BASH Perl, make sure to set git’s core.autocrlf variable to «input» or «false» to avoid translating newlines. After Visual Studio is installed, you should be able to invoke 32-bit and 64-bit command prompts via the start menu (Visual Studio 2017 -> x86 Native Tools Command Prompt and x64 Native Tools Command Prompt). At the current time, Kerberos 5 can only be built for the x64 target if the host platform is also 64-bit, because it compiles and runs programs during the build. IMPORTANT NOTE: By default, the sources are built with debug information and linked against the debug version of the Microsoft C Runtime library, which is not found on most Windows systems unless they have development tools, and requires a separate license to distribute. To build a release version, you need to define NODEBUG either in the environment or the nmake command-line. Debug information in the compiled binaries and libraries may be retained by defining DEBUG_SYMBOL in the environment or on the nmake command line. Building the code and installer: ——————————- First, make sure you have sed, (g)awk, cat, and cp. You must also define KRB_INSTALL_DIR either in the environment or on the command line (for nmake install). If you are proceeding to build the MSI installer, this directory should be a temporary staging area in or near your build tree. The directory must exist before nmake install is run. The 64-bit installer provides 32-bit libraries, so a 32-bit build and install must be performed before the 64-bit build. To skip building the graphical ticket manager, run «set NO_LEASH=1» before building, and do not build the installers. In a 32-bit command shell: 1) set KRB_INSTALL_DIR=pathtodir # Where bin/include/lib lives 2) cd xxxsrc # Go to where source lives 3) nmake -f Makefile.in prep-windows # Create Makefile for Windows 4) nmake [NODEBUG=1] # Build the sources 5) nmake install [NODEBUG=1] # Copy headers, libs, executables 6) cd windowsinstallerwix # Go to where the installer source is 7) nmake [NODEBUG=1] # Build the installer 8) rename kfw.msi kfw32.msi # Save the 32-bit installer In a 64-bit command shell: 9) set PATH=%PATH%;»%WindowsSdkVerBinPath%»x86 # To get uicc.exe 10) set KRB_INSTALL_DIR=pathtodir # Where bin/include/lib lives 11) cd xxxsrc # Go to where source lives 12) nmake clean # Clean up the 32-bit objects 13) nmake [NODEBUG=1] # Build the sources for 64-bit 14) nmake install [NODEBUG=1] # Copy 64-bit lib/executables 15) cd windowsinstallerwix # Back to the installer source 16) nmake clean # Remove 32-bit leavings 17) nmake [NODEBUG=1] # Build the 64-bit installer 18) rename kfw.msi kfw64.msi # And name it usefully Step 9 may be skipped if uicc is already in the command-line path (try running «uicc» to see if you get a usage message or a not-found error), or if you are not building the graphical ticket manager. Visual Studio 2013 and 2015 provide only a single command prompt. Within this prompt, use «vcvarsall.bat x86» and «vcvarsall.bat amd64» to switch to 32-bit and 64-bit mode. Running Kerberos 5 Apps: ———————— Make sure you have a valid krb5.ini file. By default, an empty krb5.ini is installed in CSIDL_COMMON_APPDATA (that is, %SystemDrive%ProgramDataMITKerberos5 on newer-than-XP). (ProgramData is a hidden folder.) You may need to customize it with settings for your site, but since DNS lookups are enabled for locating KDCs, many sites will not need further customization. The file format is identical to that of a Unix krb5.conf file. krb5.ini File: ————- WARNING: Despite its name, this is not a Windows .ini file. Therefore, do not try to use any .ini tools, including the Windows API or any installer tools to manipulate this file. Its format is subtly different from Windows .ini files! Controlling the Kerberos 5 Run-Time Environment: ———————————————— The Kerberos 5 configuration file and credentials cache can be controlled with environment variables and registry settings. The environment variable for a particular setting always takes precedence. Next in precedence comes the setting in the registry under HKEY_CURRENT_USERSoftwareMITKerberos5. Then comes the registry setting under HKEY_LOCAL_MACHINESoftwareMITKerberos5. If none of those are found, a default value is used. Configuration File: — Environment: KRB5_CONFIG — Registry Value: config — Default: looks in the user’s AppData directory, the machine’s ProgramData directory, krb5_32.dll’s dir and Windows directory Default Credentials Cache: — Environment: KRB5CCNAME — Registry Value: ccname — Default: API: Credentials Cache: —————— In addition to standard FILE: (disk file) and MEMORY: (in-process non-shared memory) Windows supports the API: cache type, which is a shared memory cache. Kerberos for Windows also has access to an MSLSA: cache type, which directly accesses the Microsoft Kerberos Logon Session credentials cache. The MSLSA: cache is available when the user logon is performed using Kerberos either to an Active Directory Domain or a non-Microsoft KDC; the ms2mit and mit2ms utilities can also be used to interact with it, though there are some limitations. A user is able to logon to Windows using the Kerberos LSA if the machine is part of a Windows Active Directory domain or if the machine has been configured to authenticate to a non-Microsoft KDC such as MIT. The instructions for configuring a Windows 2000 XP workstation to authenticate to a non-Microsoft KDC are documented in TechNet somewhere. In brief: 1. Install the Windows support tools in order to obtain KSETUP.EXE and KTPASS.EXE. 2. Install the Windows Resource Kit to obtain KERBTRAY.EXE and KLIST.EXE 3. Add Realms and associated KDCs with: *KSETUP /AddKdc <realm> [<kdcname>]*. If you leave off the <kdcname> DNS SRV records will be used. 4. Specify the password change service host for the realm with: *KSETUP /AddKpasswd <realm> <Kpwdhost>* 5. Assign the realm of the local machine with: *KSETUP /SetRealm <realm>* where realm must be all upper case. 6. Assign the local machine’s password with: *KSETUP /SetComputerPassword <Password> * 7. Specify the capabilities of the Realm KDC with: *KSETUP /SetRealmFlags <realm> <flag> [<flag> …]* where flags may be *None, SendAddress, TcpSupported, Delegate, *and *NcSupported*, 8. Map principal names to local accounts with: *KSETUP /MapUser <principal> <account>* On the MIT KDC, you must then create service principals using the «Password» assigned to the machine. So far the minimum list of principals required appear to be for a machine named «mymachine» in the realm «EXAMPLE.COM» with a domain name of «example.com»: * host/mymachine@EXAMPLE.COM * host/mymachine.example.com@EXAMPLE.COM * cifs/mymachine@EXAMPLE.COM * cifs/mymachine.example.com@EXAMPLE.COM There may very well be other services for which principals must be created depending on what services are being executed on the machine. It is very important to note that while you can successfully log into a Windows workstation by authenticating to the KDC without creating a host key; the logon session you receive will not be a Kerberos Logon Session. There will be no Kerberos principal and no LSA cache to access. The result of a real KSETUP configuration looks like this: [C:44NT]ksetup default realm = KRB5.COLUMBIA.EDU (external) ATHENA.MIT.EDU: kdc = kerberos.mit.edu kdc = kerberos-1.mit.edu kdc = kerberos-2.mit.edu kdc = kerberos-3.mit.edu Realm Flags = 0x0 none CC.COLUMBIA.EDU: kdc = kerberos.cc.columbia.edu Realm Flags = 0x0 none GRAND.CENTRAL.ORG: kdc = penn.central.org kdc = grand-opening.mit.edu Realm Flags = 0x0 none KRB5.COLUMBIA.EDU: kdc = yclept.kermit.columbia.edu Realm Flags = 0x0 none OPENAFS.ORG: kdc = virtue.openafs.org Realm Flags = 0x0 none Mapping jaltman@KRB5.COLUMBIA.EDU to jaltman. Mapping jaltman@CC.COLUMBIA.EDU to jaltman. Mapping jaltman@ATHENA.MIT.EDU to jaltman. Mapping all users (*) to a local account by the same name (*). The MSLSA: credential cache relies on the ability to extract the entire Kerberos ticket including the session key from the Kerberos LSA. In an attempt to increase security Microsoft has begun to implement a feature by which they no longer export the session keys for Ticket Getting Tickets. This has the side effect of making them useless to the MIT krb5 library when attempting to request additional service tickets. This new feature has been seen in Windows 2003 Server, Windows 2000 Server SP4, and Windows XP SP2. We assume that it will be implemented in all future Microsoft operating systems supporting the Kerberos SSPI. Microsoft does work closely with MIT and has provided a registry key to disable this new feature. On server platforms the key is specified as: HKLMSYSTEMCurrentControlSetControlLsaKerberosParameters AllowTGTSessionKey = 0x01 (DWORD) On workstation platforms the key is specified as: HKLMSYSTEMCurrentControlSetControlLsaKerberos AllowTGTSessionKey = 0x01 (DWORD) The Kerberos for Windows installer automatically sets this key on installation and unsets it on uninstall, allowing the MSLSA: cache type to be used. It has been noted that the Microsoft Kerberos LSA does not provide enough information within its KERB_EXTERNAL_TICKET structure to properly construct the Client Principal simply by examining a single ticket. From the MSDN Library: ClientName KERB_EXTERNAL_NAME structure that contains the client name in the ticket. This name is relative to the current domain. DomainName UNICODE_STRING that contains the name of the domain that corresponds to the ServiceName member. This is the domain that issued the ticket. TargetDomainName UNICODE_STRING that contains the name of the domain in which the ticket is valid. For an interdomain ticket, this is the destination domain. AltTargetDomainName UNICODE_STRING that contains a synonym for the destination domain. Every domain has two names: a DNS name and a NetBIOS name. If the name returned in the ticket is different from the name used to request the ticket (the Kerberos Key Distribution Center (KDC) may do name mapping), this string contains the original name. Unfortunately, there is no field here which contains the domain of the client. In order for the krb5_ccache to properly report the client principal name, the client principal name is constructed by utilizing the ClientName and DomainName fields of the Initial TGT associated with the Kerberos LSA credential cache. To disable the use of the TGT info and instead simply use the «DomainName» field of the current ticket define one of the following registry keys depending on whether the change should be system global or just for the current user. HKLMSoftwareMITKerberos5 PreserveInitialTicketIdentity = 0x0 (DWORD) HKCUSoftwareMITKerberos5 PreserveInitialTicketIdentity = 0x0 (DWORD) GSSAPI Sample Client: ——————— The GSS API Sample Client provided in this distribution is compatible with the gss-server application built on Unix/Linux systems. This client is not compatible with the Platform SDK/Samples/Security/SSPI/GSS/ samples which Microsoft has been shipping as of January 2004. Revised versions of these samples are available upon request to krbdev@mit.edu. More Information: —————- For more information, please read the Kerberos 5 documentation in the doc directory of the distribution.
  • 1 # Термины и определения
  • 2 # Инструменты
  • 3 # Описание
    • 3.1 # Типы шифрования
    • 3.2 # krb5.ini
  • 4 # Настройка сервера
    • 4.1 # Создание пользователя для сервера
    • 4.2 # Создание SPN
    • 4.3 # Привязка SPN к пользователю сервера
    • 4.4 # Создание keytab для SPN
    • 4.5 # Настройка kerberos.properties
    • 4.6 # Команды для выполнения по вышеперечисленным пунктам
  • 5 # Настройка браузера
  • 6 # Настройка оповещателя
    • 6.1 # Настройка для получения заданий
    • 6.2 # Настройка для браузера
  • 7 # Типичные проблемы

# Термины и определения

термин описание пример
DOMAIN_NAME название домена test.com
REALM для Active Directory это всегда DOMAIN_NAME в верхнем регистре TEST.COM
SERVER_NAME название компьютера, где установлен RunaWFE Server runaserver
SERVER_USER логин пользователя, под которым работает RunaWFE Server runauser
SERVER_SPN SPN (Service principal name), который соответствует SERVER_USER

Формат FQDN для Windows2008: HTTP/{SERVER_NAME}.{DOMAIN_NAME}

Формат FQDN для Windows2003: HTTP/{SERVER_NAME}.{DOMAIN_NAME}@{REALM}

Формат NetBIOS для Windows2008: HTTP/{SERVER_NAME}

Формат NetBIOS для Windows2003: HTTP/{SERVER_NAME}@{REALM}

HTTP/runaserver.test.com

HTTP/runaserver.test.com@TEST.COM

HTTP/runaserver

HTTP/runaserver@TEST.COM

KEYTAB_PATH Путь к keytab-файлу ключей, хранящему хеши паролей пользователей C:/runawfe/krb5.keytab

# Инструменты

название описание расположение комментарии
kinit Получение тикета TGT из контроллера домена JDK bin, есть альтернативные реализации пользователь может быть задан в виде {SERVER_USER} или {SERVER_USER}@{REALM}
klist Просмотр полученных тикетов и возможность их удаления из локального кеша JDK bin, есть альтернативные реализации
setspn Создаёт SPN и назначает его пользователю входит в Windows Server 2008+, ранее доступен в пакете Windows Server support tools
ktpass Меняет логин пользователя на SPN или формирует keytab файл входит в Windows Server 2008+, ранее доступен в пакете Windows Server support tools
ktab Формирует keytab файл JDK bin
ADSIEdit Просмотр свойств пользователя в контроллере домена Windows Server
WireShark Анализатор траффика https://www.wireshark.org/

# Описание

Более строгое описание можно найти в интернете, например https://blogs.technet.microsoft.com/askds/2008/03/06/kerberos-for-the-busy-admin/.

KerberosAuthenticationOverview.png

этап протокол описание данные запроса данные ответа примечания
0 KRB аутентификация пользователя клиента логин пользователя тикет TGT при входе в систему
1 HTTP вход в систему без HTTP заголовка Authorization HTTP 401 http://{SERVER_SPN}:8080/wfe/krblogin.do
2 KRB получение сервисного тикета для сервера {SERVER_SPN} сервисный тикет шаг выполняется если тикета ещё нет в кеше клиента
3 HTTP продолжение входа в систему HTTP заголовок Authorization = YIIV… HTTP 200 http://{SERVER_SPN}:8080/wfe/krblogin.do
4 KRB аутентификация пользователя сервера {SERVER_SPN} тикет TGT выполняется при отсутствии TGT во время взаимодействия с клиентом, происходит до возврата ответа 3 клиенту

# Типы шифрования

Выбранный тип шифрования зависит от участников взаимодействия — версии ПО домена (Windows Server), настроек домена, настроек пользователя, настроек ПО клиента.

В ранних версиях (Windows 2000, 2003) настраивали DES, в поздних (Windows 2008, 2012) рекомендуют использованием AES.

Настройки пользователя, оказывающие влияние на поведение Kerberos:

  • This account supports Kerberos AES 128/256 bit encryption — разрешение использования соответствущего типа шифрования для пользователя

(TODO — при невключённых чекбоксах всё равно использовался AES128)

  • Use Kerberos DES encryption for this acount — включает шифрование DES для пользователя, после установки чекбокса требуется смена пароля

# krb5.ini

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

Детальное описание файла конфигурации Kerberos

На сервере и клиентских машинах Windows он может быть расположен в ${windir}/krb5.ini.

Пример файла krb5.ini

[domain_realm]
 .test.com = TEST.COM
 test.com = TEST.COM
[libdefaults]
 default_realm = TEST.COM
 kdc_timesync = 1
 ccache_type = 4
 ticket_lifetime = 600
 default_tkt_enctypes = des-cbc-md5 des-cbc-crc des3-cbc-sha1
 default_tgs_enctypes = des-cbc-md5 des-cbc-crc des3-cbc-sha1
 permitted_enctypes = des-cbc-md5 des-cbc-crc des3-cbc-sha1
[logging]
 kdc = CONSOLE
[realms]
 TEST.COM = {
  kdc = 192.168.0.1
  kdc = 192.168.1.1
  default_domain = test.com
 }
[appdefaults]
 autologin = true
 forward = true
 forwardable = true
 encrypt = true

# Настройка сервера

Данная инструкция сделана в окружении Windows Server2008R2 (контроллер домена), Windows Server2012R2 (RunaWFE Server), Windows7 (RunaWFE client).

В данном разделе регистр может иметь значение, хотя опытным путём было выяснено что логин пользователя, название компьютера сервера и SPN не являются регистрозависимыми.

# Создание пользователя для сервера

На контроллере домена нужно создать пользователя {SERVER_USER} с настройками по умолчанию.

Проверка: kinit {SERVER_USER} должен успешно получить тикет.

# Создание SPN

На контроллере домена нужно выполнить команды:

setspn -A {SERVER_SPN} {SERVER_USER}

Проверка: через ADSIEdit можно увидеть что свойство пользователя servicePrincipalName установлено либо посмотреть св-во servicePrincipalName с помощью команды Get-ADUser {SERVER_USER} -Properties *.

Если планируется использовать SPN на основании NetBIOS имени — то нужно зарегистрировать и его (https://msdn.microsoft.com/en-us/library/ms677949.aspx)

setspn -A HTTP/{SERVER_NAME} {SERVER_USER}

# Привязка SPN к пользователю сервера

На контроллере домена нужно выполнить команду:

ktpass /princ {SERVER_SPN} /mapuser {SERVER_USER} +setupn /pass *

Можно игнорировать предупреждение «WARNING: pType and account type do not match. This might cause problems».

Для обхода бага со сбросом пароля https://support.microsoft.com/en-us/kb/939980 рекомендуют вписать пароль вместо звёздочки. А если выполнить данную команду без пароля — то почему-мо возникает ошибка 24 с некорректным salt.

Проверка: в свойствах пользователя User logon name стал равен SPN либо посмотреть св-во UserPrincipalName с помощью команды Get-ADUser {SERVER_USER} -Properties *.

UserLogonName.png

Проверка: kinit {SERVER_SPN} должен успешно получить тикет.

# Создание keytab для SPN

Выполнить команду из {JAVA_HOME}/bin:

ktab -a {SERVER_SPN} -n 0 -k {KEYTAB_PATH}

Проверка: kinit -k -t {KEYTAB_PATH} {SERVER_SPN} должен успешно получить тикет без запроса пароля.

Этот файл также можно получить в результате вызова команды ktpass на контроллере домена.

# Настройка kerberos.properties

Создайте файл kerberos.properties в директории {RUNAWFE_JBOSS}/standalone/wfe.custom. Замените в нем имена на настоящие.

# задействовать аутентификацию используя RunaWFE API
api.auth.enabled=true
appName=com.sun.security.jgss.krb5.accept
moduleClassName=com.sun.security.auth.module.Krb5LoginModule
principal={SERVER_SPN}
storeKey=true
useKeyTab=true
keyTab={KEYTAB_PATH}
doNotPrompt=true
# режим отладки аутентификации
debug=true
# задействовать аутентификацию по протоколу HTTP (из веб-интерфейса)
http.auth.enabled=true
jcifs.http.enableNegotiate=true
# режим отладки аутентификации
sun.security.krb5.debug=true
jcifs.spnego.servicePrincipal={SERVER_SPN}
http.auth.preference=Kerberos

# Команды для выполнения по вышеперечисленным пунктам

На контроллере домена:

setspn -A HTTP/runaserver.test.com runauser

ktpass -princ HTTP/runaserver.test.com -pass * -mapuser runauser

На сервере:

ktab -a HTTP/runaserver.test.com -n 0 -k C:/runawfe/krb5.keytab

# Настройка браузера

Для того чтобы браузер пытался использовать Kerberos для аутентификации:

  • в нём должна быть включена настройка Enable Integrated Windows Authentication (в некоторых версиях IE её нет)
  • настройки зоны безопасности должны позволять её использование, по умолчанию это настроено для LocalIntranet
  • настройка {SERVER_SPN} должна быть корректно произведена

Во время запроса на сервере формируется в логе Request Authorization:

  • Negotiate YIIV… — правильно
  • Negotiate TlRMT… — неправильно (попытка использовать NTLM)

Если по нажатию на ссылке Сквозная аутентификация (kerberos) будет выведено окно с вводом логина/пароля — то это значит что браузер не получил сервисный тикет в контроллере домена или даже не пытался это сделать. При возникновении такой ситуации самым действенным оказывается использование WireShark для прослушивания траффика по порту 88 с контроллером домена.

# Настройка оповещателя

На сервере должна быть корректно настроена аутентификация.

# Настройка для получения заданий

Настроить kerberos.properties если authentication.type установлено в kerberos (для sspiKerberos это не требуется):

appName=com.sun.security.jgss.initiate
moduleClassName=com.sun.security.auth.module.Krb5LoginModule
useTicketCache=true
doNotPrompt=true
debug=true
serverPrincipal=HTTP/runaserver.test.com

# Настройка для браузера

Настройку login.relative.url установить в /krblogin.do.

# Типичные проблемы

https://technet.microsoft.com/en-us/library/bb463167.aspx

ошибка описание что делать

Client not found in Kerberos database (6)

SPN не зарегистрирован как пользователь (UserPrincipalName) либо продублирован (setspn -x) Зарегистрировать SPN либо удалить дубликат

Pre-authentication information was invalid (24)

Неправильный пароль либо несовпадение информации по логину (UserPrincipalName изменён?).

Обратите внимание на атрибут salt в пакете KRB Error: KRB5KDC_ERR_PREAUTH_FAILED, он должен совпадать с principal, для которого вы получаете тикет; если не совпадает — то в БД kerberos что-то не так, попробуйте вновь воспользоваться командой ktpass

Сменить пароль (у пользователя и при формировании keytab)

Message stream modified (41)

Некорректно задано имя Задать имя корректно — как оно задано на контроллере домена с учётом регистра

Clients credentials have been revoked (18)

Пользователь заблокирован В настройках пользователя снять галочку Account is disabled

HTTP 400 при попытке обработки тикета YIIV…

Заголовок превышает разрешённый максимум в Jboss, по умолчанию = 8Кб (https://access.redhat.com/solutions/1173073, http://www.novell.com/support/kb/doc.php?id=7005181) Увеличить разрешённый максимум в Jboss с помощью настройки org.apache.coyote.http11.Http11Protocol.MAX_HEADER_SIZE в standalone.xml

No valid credentials provided (Mechanism level: Attempt to obtain new ACCEPT credentials failed!)

Настройка appName=com.sun.security.jgss.accept является устаревшей — для старых версий JDK Изменить на com.sun.security.jgss.krb5.accept в kerberos.properties

Encryption type AES256 CTS mode with HMAC SHA1-96 is not supported/enabled

Нет поддержки типа шифрования AES-256 в JDK Изменить тип шифрования (https://blogs.msdn.microsoft.com/openspecification/2011/05/30/windows-configurations-for-kerberos-supported-encryption-type/) или установить «Unlimited Strength Java(TM) Cryptography Extension Policy Files».

Включение аудита на контроллере домена иногда помогает понять проблему (логирование происходит в журнале событий, категория Безопасность.

Kerberos audit enable.png

In Greek mythology, Kerberos, also called Cerberus, guards the gates of the Underworld to prevent the dead from leaving. He is commonly described as a three-headed dog, a serpent’s tail, mane of snakes and a lion’s claws. In computer, Kerberos is an authentication protocol based on the exchange of tickets. Windows 2000 and later versions use Kerberos as its default authentication method. It is often used as a Single Sign On (SSO) solution or to authenticate not only users but also computer nodes and services. It is frequently used in complex systems such as Hadoop based Big Data platforms.

When a user wish to gain access to a Kerberos secured service, he must first authenticate and, once successful, he will receive a master ticket called TGT stored on his local host. This ticket can later be used to create a service ticket (TS) which is used to access a remote service using an RPC connection or over HTTP. When the ticket is transmitted over HTTP, the communication make use of the SPNEGO protocol which store the ticket information into the HTTP header request.

The client installation procedure is very easy on Linux and OSX. Most of the time, Kerberos comes pre-installed or, if not, a simple command with your favourite package manager will install the client library. Safari will work right away while Firefox and Chrome will require some adjustments easily found on the Internet. While being easy on Linux and OSX, it is a little bit more complicated on Windows. If your host is integrated with an Active Directory, a ticket is already present. However, you cannot always use it to contact a remote service secured with Kerberos, for example because it exposes a domain which is not trusted by the Active Directory. Moreover, Windows has its own way to manage the Kerberos ticket.

The article explain how create a ticket with the MIT Kerberos client for Windows, how to store a ticket into its own file path and how to configure Firefox to make use of it.

Credential cache

Kerberos ticket are stored inside the credentials cache. There are multiple credentials cache supported on Windows:

  • FILE caches
    Simple and most portable. A simple flat file format is used to store one credential after another. This is the default on Linux and OSX.
  • API cache
    Only implemented on Windows, it communicates with a server process that holds the credentials in memory. This seems to be the default on Windows.

The default credential cache name is determined by…

  • The KRB5CCNAME environment variable
  • The default_ccache_name profile variable in [libdefaults] of the configuration file
  • The hardcoded default, DEFCCNAME, default to FILE:/tmp/krb5cc_%{uid} on Unix

Note about the credential cache path

In the procedures below, whether you choose to declare the credential cache with an environment variable or through the configuration file, don’t forget to replace {username} with your windows username. You can declare any path you wish. The path must correspond to the file where your Kerberos Ticket will be written. Its parent directory must exists with writable permissions by the user issuing the ticket.

Environment variable

Using the windows search, look for “environment variables” and select “Edit the system environment variables”. In the new window, click on the “Environment variables” button. From there, add a new user variable named “KRB5CCNAME” with the value C:Users{username}AppDataLocalTempkrb5cache.


Declare the KRB5CCNAME environment variable

From the PowerShell console, you can print the value of the credential cache with the command $Env:KRB5CCNAME. You do not need to restart your host to activate the environment variable but you must reload your PowerShell session if it was already opened.

Configuration file

The path to the Kerberos client configuration is C:ProgramDataMITKerberos5krb5.ini. We will get back to its full configuration later but for now, to set the credential cache, you only need to the set the default_ccache_name profile variable.

Navigate to the C:ProgramDataMITKerberos5 and change the permission to allow the current user to edit the file.


Change permissions to the krb5.ini file

Now edit the file with your favorite code editor such as Sublime Text or Notepad++ and make it look like:

[libdefaults]
 default_ccache_name = C:Users{username}AppDataLocalTempkrb5cache

Kerberos

MIT Kerberos client installation

Download and install the Kerberos MIT client for Windows. The current version at the time of this writing is 4.1 and the download link is located in the section called “MIT Kerberos for Windows 4.1”.


Download the MIT Kerberos client

This installation procedure is straightforward. Just accept all the default settings and move forward. Once the installation is complete, the installer will ask to restart the computer. It is probably not necessary but I didn’t had the time to check.


Install the MIT Kerberos client

Automatic client discovery

Depending on your setup, you do not always need to modify the Kerberos client configuration. In the absence of entries in the configuration file, the KDC adress can be obtained from the DNS records. This feature can be desactivated if dns_lookup_kdc is false. The FreeIPA DNS service expose the following domain records:

  • _kerberos of type “TXT”, eg “AU.ADALTAS.CLOUD”
  • _kerberos-master._tcp of type “SRV”
  • _kerberos-master._udp of type “SRV”
  • _kerberos._tcp of type “SRV”
  • _kerberos._udp of type “SRV”
  • _kpasswd._tcp of type “SRV”
  • _kpasswd._udp of type “SRV”

Users of our Adaltas clusters with access to the cluster through a VPN tunnel transparently use our FreeIPA DNS server. It provides them with the auto discovery of the Kerberos server. You can check this on Linux with dig:

dig srv _kerberos._udp.au.adaltas.cloud +short
0 100 88 ipa-2.au.adaltas.cloud.
0 100 88 ipa1.au.adaltas.cloud.

As well as on Windows with nslookup:

nslookup -type=SRV _kerberos._udp.au.adaltas.cloud
Server:  ipa1.au.adaltas.cloud
Address:  10.0.0.5

_kerberos._udp.au.adaltas.cloud SRV service location:
         priority       = 0
         weight         = 100
         port           = 88
         svr hostname   = ipa1.au.adaltas.cloud
_kerberos._udp.au.adaltas.cloud SRV service location:
         priority       = 0
         weight         = 100
         port           = 88
         svr hostname   = ipa-2.au.adaltas.cloud
au.adaltas.cloud        nameserver = ipa1.au.adaltas.cloud
ipa1.au.adaltas.cloud   internet address = 10.0.0.5
ipa-2.au.adaltas.cloud  internet address = 10.0.0.9

Client configuration

Alternatively, you may need to create or import your own kerberos configuration file. The path to the file is C:ProgramDataMITKerberos5krb5.ini.

If you have access to an environment with Kerberos enabled, such as a Linux box through SSH, then you already have access to the Kerberos configuration. On Linux, the file is readable by every users and it is located at “/etc/krb.conf”. You can simply import the file into your Windows host and rename it “krb5.ini” instead than “krb5.conf”. Here is an example which you could adjust with your own settings.

[libdefaults]
 default_realm = AU.ADALTAS.CLOUD
 dns_lookup_realm = false
 dns_lookup_kdc = true
 rdns = false
 ticket_lifetime = 24h
 forwardable = true
 udp_preference_limit = 0

[realms]
 AU.ADALTAS.CLOUD = {
  kdc = ipa1.au.adaltas.cloud:88
  master_kdc = ipa1.au.adaltas.cloud:88
  admin_server = ipa1.au.adaltas.cloud:749
  default_domain = au.adaltas.cloud
 }

[domain_realm]
 .au.adaltas.cloud = AU.ADALTAS.CLOUD
 au.adaltas.cloud = AU.ADALTAS.CLOUD
 ipa1.au.adaltas.cloud = AU.ADALTAS.CLOUD

Ticket creation

The ticket can now be created from the Kerberos client window by entering your provided principal and password.


Create a Kerberos ticket

If successful, you shall view your ticket as well as some complimentary information such as the validation date as well as the credential cache location.


Visualize the Kerberos ticket

Note, opening the Kerberos client window to enter your Kerberos credential is not mandatory. Once Firefox is configured (see the next section), you can directly enter your destination URL and a new window will pop up asking for your principal and username.

Firefox

Configuration

We have created a Kerberos ticket and we now need to configure Firefox to use it. Before going to your destination URL, you must edit the configuration window by writing “about:config” in the adress bar.


Firefox configuration warning

Accept the risk and modify the following properties:

  • network.negotiate-auth.trusted-uris: .au.adaltas.cloud
    Lists the sites that are permitted to engage in SPNEGO authentication with the browser.
  • network.auth.use-sspi: false
    Determines whether to use SSPI or GSSAPI for Kerberos authentication. SSPI is a proprietary variant of GSSAPI with extensions and Windows-specific data types. It is the default API on Windows. GGSAPI is an IETF standard and it is used by the MIT Kerberos client we just installed and used.

Also, while not being mandatory, you can change the following variables:

  • network.negotiate-auth.delegation-uris: .au.adaltas.cloud
    Lists the sites for which the browser may delegate user authorization to the server.
  • network.negotiate-auth.using-native-gsslib: false
    Use the default GSSAPI library.
  • network.negotiate-auth.gsslib: C:Program FilesMITKerberosbingssapi64.dll
    Specifies a alternate GSSAPI shared library. Modify the path to the appropriate dll depending on your host architecture (32 or 64 bits).
  • network.negotiate-auth.allow-non-fqdn: true
    Accepts service domain names instead of fully qualified domain names.


Firefox configuration negotiate


Firefox configuration SSPI

Ticket creation

If you try to access a service URL secured with Kerberos but without a valid ticket, you will see such a page:


SPNEGO negotiation failed with 401 HTTP error

The 401 HTTP error code indicates that your browser failed to negotiate the authentication. As part of the SPNEGO protocol, the server has requested to negotiate the authentication by returning the WWW-Authenticate: Negotiate response header. However your browser couldn’t propose any suitable method. You can see this exchange with the curl command:

curl --negotiate -u: --head http://yarn-rm-1.au.adaltas.cloud:8088/cluster
HTTP/1.1 401 Authentication required
Date: Thu, 24 Oct 2019 09:57:48 GMT
Date: Thu, 24 Oct 2019 09:57:48 GMT
Pragma: no-cache
WWW-Authenticate: Negotiate
Set-Cookie: hadoop.auth=; Path=/; HttpOnly
Cache-Control: must-revalidate,no-cache,no-store
Content-Type: text/html;charset=iso-8859-1
Content-Length: 267

The --negotiate argument tell to curl to negotiate the authentication with the remote service. The --user argument provide the required username and password which are empty in the case of Kerberos since the credential information is stored inside the local ticket.

With a valid ticket, the negotiation will succeed and you ticket will be encrypted as base64 in the second WWW-Authenticate header:

curl --negotiate -u: --head http://yarn-rm-1.au.adaltas.cloud:8088/cluster
HTTP/1.1 401 Authentication required
Date: Thu, 24 Oct 2019 09:58:17 GMT
Date: Thu, 24 Oct 2019 09:58:17 GMT
Pragma: no-cache
WWW-Authenticate: Negotiate
Set-Cookie: hadoop.auth=; Path=/; HttpOnly
Cache-Control: must-revalidate,no-cache,no-store
Content-Type: text/html;charset=iso-8859-1
Content-Length: 267

HTTP/1.1 405 HTTP method GET is not supported by this URL
Date: Thu, 24 Oct 2019 09:58:17 GMT
Date: Thu, 24 Oct 2019 09:58:17 GMT
Pragma: no-cache
WWW-Authenticate: Negotiate oYH1MIHyoAMKAQChCwYJKoZIhvcSAQICom4EbGBqBgkqhkiG9xIBAgICAG9bMFmgAwIBBaEDAgEPok0wS6ADAgESokQEQhnlSj8cuKVGz6eBMJNi9R8ImTtdpJU4zV8N4s4EwJxpnmU0ZohrBtavGQxoXFSuuxScHcpiNVL51qEJzsoAA6x6iqNuBGxgagYJKoZIhvcSAQICAgBvWuBZoAMCAQWhAwIBD6JNMEugAwIBEqJEBEIZ5Uo/HLilRs+ngTCTYvUfCJk7XaSVOM1fDeLOBMCcaZ5lNGaIawbWrxkMaFxUrrsUnB3KYjVS+dahCc7KAAOseoo=
Set-Cookie: hadoop.auth="u=david&p=david@AU.ADALTAS.CLOUD&t=kerberos&e=1571947097972&s=Df9/vrrj4xHASRxHPdBJHOCap4Gdmvst1QCnjFXuceI="; Path=/; HttpOnly
X-Frame-Options: SAMEORIGIN
Vary: Accept-Encoding
Cache-Control: must-revalidate,no-cache,no-store
Content-Type: text/html;charset=iso-8859-1
Content-Length: 309

And you can finally access all your Kerberos secured service without having to renter your login credentials:


SPNEGO negotiation succeed

I want to use Kerberos to do auth to an IIS kerberos protected web site from a Java application. The goal is to be able to use a keytab file to authenticate with a service account without specifying a username and password.

This describes how to use http client to auth using kerberos. But it requires a couple special configuration files login.conf and krb5.ini.

The format is the login conf is described here: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/LoginConfigFile.html

The format of the krb5.ini file is described here: https://web.mit.edu/kerberos/krb5-1.12/doc/admin/conf_files/krb5_conf.html

I also found some related sof articles (listed below).

But none of them seem to describe the process of actually creating the login.conf file and the krb5.conf/krb5.ini file for use against Active Directory.

What are steps to generating these files for use with a Windows Active Directory kerberos situation?

Here’s what I have so far, but I’m completely going off of examples I’ve found from friends and random links around the web.

login.conf

KrbLogin {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=true
  storeKey=true
  keyTab="file:///C:/kerb/kerberos500.keytab"
  useTicketCache=true
  principal="kerberos500@FUSIONIS.LIFE"
  debug=true;
};

com.sun.security.jgss.initiate {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=true
  storeKey=true
  keyTab="/home/ndipiazza/lucidworks/httpclient-tester/kb.keytab"
  useTicketCache=true
  principal="kerberos500@FUSIONIS.LIFE"
  debug=true;
};

krb5.ini

[libdefaults]
    default_realm = FUSIONIS.LIFE
    default_tkt_enctypes = aes128-cts-hmac-sha1-96 rc4-hmac
    default_tgs_enctypes = aes128-cts-hmac-sha1-96  rc4-hmac
    permitted_enctypes = aes128-cts-hmac-sha1-96 rc4-hmac
    dns_lookup_realm = false
    dns_lookup_kdc = false
    ticket_lifetime = 24h
    renew_lifetime = 7d
    forwardable = true
    udp_preference_limit = 1

[realms]
FUSIONIS.LIFE = {
   kdc = 192.168.1.71
   admin_server = 192.168.1.71
}

[domain_realm]
.fusionis.life = FUSIONIS.LIFE
fusionis.life = FUSIONIS.LIFE

Create the keytab on Windows

ktpass /princ kerberos500@FUSIONIS.LIFE /pass password /ptype KRB5_NT_PRINCIPAL /out kerberos500.keytab

Creating the KeyTab on Ubuntu Linux

ktutil
addent -password -p kerberos500@FUSIONIS.LIFE -k 1 -e RC4-HMAC
- it will ask you for password of kerberos500 -
wkt kerberos500.keytab
q

Related sofs:

HttpClient set credentials for Kerberos authentication

Simple Kerberos client in Java?

Where is the krb5.ini file in alter Windows file gone?

Понравилась статья? Поделить с друзьями:
  • Mission planner скачать на русском для windows 10
  • Missing operating system что делать windows 7 при запуске
  • Missing operating system что делать windows 7 на ноутбуке
  • Missing operating system при установке с флешки windows 10
  • Mkke не запускается на windows 10