Heimdal
*******

1 Introduction
**************

What is Heimdal?
================

Heimdal is a free implementation of Kerberos 5. The goals are to:

   * have an implementation that can be freely used by anyone

   * be protocol compatible with existing implementations and, if not in
     conflict, with RFC 1510 (and any future updated RFC)

   * be reasonably compatible with the M.I.T Kerberos V5 API

   * have support for Kerberos V5 over GSS-API (RFC1964)

   * include the most important and useful application programs (rsh,
     telnet, popper, etc.)

   * include enough backwards compatibility with Kerberos V4

Status
======

Heimdal has the following features (this does not mean any of this
works):

   * a stub generator and a library to encode/decode/whatever ASN.1/DER
     stuff

   * a `libkrb5' library that should be possible to get to work with
     simple applications

   * a GSS-API library that should have all the important functions for
     building applications

   * Eric Young's `libdes'

   * `kinit', `klist', `kdestroy'

   * `telnet', `telnetd'

   * `rsh', `rshd'

   * `popper', `push' (a movemail equivalent)

   * `ftp', and `ftpd'

   * a library `libkafs' for authenticating to AFS and a program
     `afslog' that uses it

   * some simple test programs

   * a KDC that supports most things; optionally, it may also support
     Kerberos V4 and kaserver,

   * simple programs for distributing databases between a KDC master and
     slaves

   * a password changing daemon `kpasswdd', library functions for
     changing passwords and a simple client

   * some kind of administration system

   * Kerberos V4 support in many of the applications.

Bug reports
===========

If you find bugs in this software, make sure it is a genuine bug and not
just a part of the code that isn't implemented.

Bug reports should be sent to <heimdal-bugs@pdc.kth.se>. Please include
information on what machine and operating system (including version)
you are running, what you are trying to do, what happens, what you
think should have happened, an example for us to repeat, the output you
get when trying the example, and a patch for the problem if you have
one. Please make any patches with `diff -u' or `diff -c'.

Suggestions, comments and other non bug reports are also welcome.

Mailing list
============

There are two mailing lists with talk about Heimdal.
<heimdal-announce@sics.se> is a low-volume announcement list, while
<heimdal-discuss@sics.se> is for general discussion.  Send a message to
<majordomo@sics.se> to subscribe.

Heimdal source code, binaries and the manual
============================================

The source code for heimdal, links to binaries and the manual (this
document) can be found on our web-page at
`http://www.pdc.kth.se/heimdal/'.

2 What is Kerberos?
*******************

     Now this Cerberus had three heads of dogs,
             the tail of a dragon, and on his back the
             heads of all sorts of snakes.
             -- Pseudo-Apollodorus Library 2.5.12

Kerberos is a system for authenticating users and services on a network.
It is built upon the assumption that the network is "unsafe".  For
example, data sent over the network can be eavesdropped and altered, and
addresses can also be faked.  Therefore they cannot be used for
authentication purposes.

Kerberos is a trusted third-party service.  That means that there is a
third party (the kerberos server) that is trusted by all the entities on
the network (users and services, usually called "principals").  All
principals share a secret password (or key) with the kerberos server and
this enables principals to verify that the messages from the kerberos
server are authentic.  Thus trusting the kerberos server, users and
services can authenticate each other.

2.1 Basic mechanism
===================

     *Note_* This discussion is about Kerberos version 4, but version 5
     works similarly.

In Kerberos, principals use "tickets" to prove that they are who they
claim to be. In the following example, A is the initiator of the
authentication exchange, usually a user, and B is the service that A
wishes to use.

To obtain a ticket for a specific service, A sends a ticket request to
the kerberos server. The request contains A's and B's names (along with
some other fields). The kerberos server checks that both A and B are
valid principals.

Having verified the validity of the principals, it creates a packet
containing A's and B's names, A's network address (A<ADDR>), the
current time (T<ISSUE>), the lifetime of the ticket (LIFE), and a
secret "session key" (K<AB>). This packet is encrypted with B's secret
key (K<B>).  The actual ticket (T<AB>) looks like this: ({A, B,
A<ADDR>, T<ISSUE>, LIFE, K<AB>}K<B>).

The reply to A consists of the ticket (T<AB>), B's name, the current
time, the lifetime of the ticket, and the session key, all encrypted in
A's secret key ({B, T<ISSUE>, LIFE, K<AB>, T<AB>}K<A>). A decrypts the
reply and retains it for later use.

Before sending a message to B, A creates an authenticator consisting of
A's name, A's address, the current time, and a "checksum" chosen by A,
all encrypted with the secret session key ({A, A<ADDR>, T<CURRENT>,
CHECKSUM}K<AB>). This is sent together with the ticket received from
the kerberos server to B.  Upon reception, B decrypts the ticket using
B's secret key.  Since the ticket contains the session key that the
authenticator was encrypted with, B can now also decrypt the
authenticator. To verify that A really is A, B now has to compare the
contents of the ticket with that of the authenticator. If everything
matches, B now considers A as properly authenticated.

2.2 Different attacks
=====================

Impersonating A
---------------

An impostor, C could steal the authenticator and the ticket as it is
transmitted across the network, and use them to impersonate A. The
address in the ticket and the authenticator was added to make it more
difficult to perform this attack.  To succeed C will have to either use
the same machine as A or fake the source addresses of the packets. By
including the time stamp in the authenticator, C does not have much
time in which to mount the attack.

Impersonating B
---------------

C can hijack B's network address, and when A sends her credentials, C
just pretend to verify them. C can't be sure that she is talking to A.

2.3 Defense strategies
======================

It would be possible to add a "replay cache" to the server side.  The
idea is to save the authenticators sent during the last few minutes, so
that B can detect when someone is trying to retransmit an already used
message. This is somewhat impractical (mostly regarding efficiency),
and is not part of Kerberos 4; MIT Kerberos 5 contains it.

To authenticate B, A might request that B sends something back that
proves that B has access to the session key. An example of this is the
checksum that A sent as part of the authenticator. One typical
procedure is to add one to the checksum, encrypt it with the session
key and send it back to A.  This is called "mutual authentication".

The session key can also be used to add cryptographic checksums to the
messages sent between A and B (known as "message integrity").
Encryption can also be added ("message confidentiality"). This is
probably the best approach in all cases.

2.4 Further reading
===================

The original paper on Kerberos from 1988 is `Kerberos: An
Authentication Service for Open Network Systems', by Jennifer Steiner,
Clifford Neuman and Jeffrey I. Schiller.

A less technical description can be found in `Designing an
Authentication System: a Dialogue in Four Scenes' by Bill Bryant, also
from 1988.

These documents can be found on our web-page at
`http://www.pdc.kth.se/kth-krb/'.

3 Building and Installing
*************************

Heimdal uses GNU Autoconf to configure for specific hosts, and GNU
Automake to manage makefiles. If this is new to you, the short
instruction is to run the `configure' script in the top level
directory, and when that finishes `make'.

If you want to build the distribution in a different directory from the
source directory, you will need a make that implements VPATH correctly,
such as GNU make.

You will need to build the distribution:

   * A compiler that supports a "loose" ANSI C mode, such as `gcc'.

   * lex or flex

   * awk

   * yacc or bison

   * a socket library

   * NDBM or Berkeley DB for building the server side.

When everything is built, you can install by doing `make install'. The
default location for installation is `/usr/heimdal', but this can be
changed by running `configure' with `--prefix=/some/other/place'.

If you need to change the default behavior, configure understands the
following options:

`--without-berkeley-db'
     DB is preferred before NDBM, but if you for some reason want to
     use NDBM instead, you can use this option.

`--with-krb4=`dir''
     Gives the location of Kerberos 4 libraries and headers. This
     enables Kerberos 4 support in the applications (telnet, rsh,
     popper, etc) and the KDC. It is automatically check for in
     `/usr/athena'. If you keep libraries and headers in different
     places, you can instead give the path to each with the
     `--with-krb4-lib=`dir'', and `--with-krb4-include=`dir'' options.

     You will need a fairly recent version of our Kerberos 4
     distribution for `rshd' and `popper' to support version 4 clients.

`--enable-dce'
     Enables support for getting DCE credentials and tokens.  See the
     README files in `appl/dceutils' for more information.

`--disable-otp'
     By default some of the application programs will build with
     support for one-time passwords (OTP).  Use this option to disable
     that support.

`--enable-osfc2'
     Enable some C2 support for OSF/Digital Unix/Tru64.  Use this
     option if you are running your OSF operating system in C2 mode.

`--with-readline=`dir''
     Gives the path for the GNU Readline library, which will be used in
     some programs. If no readline library is found, the (simpler)
     editline library will be used instead.

`--with-hesiod=`dir''
     Enables hesiod support in push.

`--enable-netinfo'
     Add support for using netinfo to lookup configuration information.
     Probably only useful (and working) on NextStep/Mac OS X.

`--without-ipv6'
     Disable the IPv6 support.

`--with-openldap'
     Compile Heimdal with support for storing the database in LDAP.
     Requires OpenLDAP `http://www.openldap.org'.  See
     `http://www.padl.com/~lukeh/heimdal/' for more information.

`--enable-bigendian'

`--enable-littleendian'
     Normally, the build process will figure out by itself if the
     machine is big or little endian.  It might fail in some cases when
     cross-compiling.  If it does fail to figure it out, use the
     relevant of these two options.

`--with-mips-abi=ABI'
     On Irix there are three different ABIs that can be used (`32',
     `n32', or `64').  This option allows you to override the automatic
     selection.

`--disable-mmap'
     Do not use the mmap system call.  Normally, configure detects if
     there is a working mmap and it is only used if there is one.  Only
     try this option if it fails to work anyhow.

4 Setting up a realm
********************

A realm is an administrative domain.  The name of a Kerberos realm is
usually the Internet domain name in uppercase.  Call your realm the same
as your Internet domain name if you do not have strong reasons for not
doing so.  It will make life easier for you and everyone else.

4.1 Configuration file
======================

To setup a realm you will first have to create a configuration file:
`/etc/krb5.conf'. The `krb5.conf' file can contain many configuration
options, some of which are described here.

There is a sample `krb5.conf' supplied with the distribution.

The configuration file is a hierarchical structure consisting of
sections, each containing a list of bindings (either variable
assignments or subsections). A section starts with `[section-name]'.  A
binding consists of a left hand side, an equal (`=') and a right hand
side (the left hand side tag must be separated from the equal with some
whitespace.) Subsections has a `{' as the first non-whitespace
character after the equal. All other bindings are treated as variable
assignments. The value of a variable extends to the end of the line.

     [section1]
             a-subsection = {
                     var = value1
                     other-var = value with {}
                     sub-sub-section = {
                             var = 123
                     }
             }
             var = some other value
     [section2]
             var = yet another value

In this manual, names of sections and bindings will be given as strings
separated by slashes (`/'). The `other-var' variable will thus be
`section1/a-subsection/other-var'.

For in-depth information about the contents of the configuration file,
refer to the `krb5.conf' manual page. Some of the more important
sections are briefly described here.

The `libdefaults' section contains a list of library configuration
parameters, such as the default realm and the timeout for KDC
responses. The `realms' section contains information about specific
realms, such as where they hide their KDC. This section serves the same
purpose as the Kerberos 4 `krb.conf' file, but can contain more
information. Finally the `domain_realm' section contains a list of
mappings from domains to realms, equivalent to the Kerberos 4
`krb.realms' file.

To continue with the realm setup, you will have to create a
configuration file, with contents similar to the following.

     [libdefaults]
             default_realm = MY.REALM
     [realms]
             MY.REALM = {
                     kdc = my.kdc my.slave.kdc
                     kdc = my.third.kdc
             }
     [domain_realm]
             .my.domain = MY.REALM

If you use a realm name equal to your domain name, you can omit the
`libdefaults', and `domain_realm', sections. If you have a SRV-record
for your realm, or your Kerberos server has CNAME called
`kerberos.my.realm', you can omit the `realms' section too.

4.2 Creating the database
=========================

The database library will look for the database in the directory
`/var/heimdal', so you should probably create that directory.  Make
sure the directory have restrictive permissions.

     # mkdir /var/heimdal

The keys of all the principals are stored in the database.  If you
choose to, these can be encrypted with a master key.  You do not have to
remember this key (or password), but just to enter it once and it will
be stored in a file (`/var/heimdal/m-key').  If you want to have a
master key, run `kstash' to create this master key:

     # kstash
     Master key:
     Verifying password - Master key:

To initialise the database use the `kadmin' program, with the `-l'
option (to enable local database mode). First issue a `init MY.REALM'
command. This will create the database and insert default principals
for that realm. You can have more than one realm in one database, so
`init' does not destroy any old database.

Before creating the database, `init' will ask you some questions about
max ticket lifetimes.

After creating the database you should probably add yourself to it. You
do this with the `add' command. It takes as argument the name of a
principal. The principal should contain a realm, so if you haven't setup
a default realm, you will need to explicitly include the realm.

     # kadmin -l
     kadmin> init MY.REALM
     Realm max ticket life [unlimited]:
     Realm max renewable ticket life [unlimited]:
     kadmin> add me
     Max ticket life [unlimited]:
     Max renewable life [unlimited]:
     Attributes []:
     Password:
     Verifying password - Password:

Now start the KDC and try getting a ticket.

     # kdc &
     # kinit me
     me@MY.REALMS's Password:
     # klist
     Credentials cache: /tmp/krb5cc_0
             Principal: me@MY.REALM

       Issued           Expires          Principal
     Aug 25 07:25:55  Aug 25 17:25:55  krbtgt/MY.REALM@MY.REALM

If you are curious you can use the `dump' command to list all the
entries in the database.  It should look something similar to the
following example (note that the entries here are truncated for
typographical reasons):

     kadmin> dump
     me@MY.REALM 1:0:1:0b01d3cb7c293b57:-:0:7:8aec316b9d1629e3baf8 ...
     kadmin/admin@MY.REALM 1:0:1:e5c8a2675b37a443:-:0:7:cb913ebf85 ...
     krbtgt/MY.REALM@MY.REALM 1:0:1:52b53b61c875ce16:-:0:7:c8943be ...
     kadmin/changepw@MY.REALM 1:0:1:f48c8af2b340e9fb:-:0:7:e3e6088 ...

4.3 keytabs
===========

To extract a service ticket from the database and put it in a keytab you
need to first create the principal in the database with `ank' (using
the `--random-key' flag to get a random key) and then extract it with
`ext_keytab'.

     kadmin> add --random-key host/my.host.name
     Max ticket life [unlimited]:
     Max renewable life [unlimited]:
     Attributes []:
     kadmin> ext host/my.host.name
     # ktutil list
     Version  Type             Principal
          1   des-cbc-md5      host/my.host.name@MY.REALM
          1   des-cbc-md4      host/my.host.name@MY.REALM
          1   des-cbc-crc      host/my.host.name@MY.REALM
          1   des3-cbc-sha1    host/my.host.name@MY.REALM

4.4 Serving Kerberos 4/524/kaserver
===================================

Heimdal can be configured to support 524, Kerberos 4 or kaserver. All
theses services are default turned off. Kerberos 4 support also depends
on if Kerberos 4 support is compiled in with Heimdal.

4.4.1 524
---------

524 is a service that allows the KDC to convert Kerberos 5 tickets to
Kerberos 4 tickets for backward compatibility. See also Using 2b tokens
with AFS in Things in search for a better place.

524 can be turned on by adding this to the configuration file

     [kdc]
     	enable-524 = yes

4.4.2 Kerberos 4
----------------

Kerberos 4 is the predecessor to to Kerberos 5. It only support single
DES. You should only enable Kerberos 4 support if you have a need for
for compatibility with an installed base of Kerberos 4 clients/servers.

Kerberos 4 can be turned on by adding this to the configuration file

     [kdc]
     	enable-kerberos4 = yes

4.4.3 kaserver
--------------

Kaserver is a Kerberos 4 that is used in AFS, the protocol have some
features over plain Kerberos 4, but like Kerberos 4 only use single DES
too.

You should only enable Kerberos 4 support if you have a need for for
compatibility with an installed base of AFS machines.

Kaserver can be turned on by adding this to the configuration file

     [kdc]
     	enable-kaserver = yes

4.5 Remote administration
=========================

The administration server, `kadmind', can be started by `inetd' (which
isn't recommended) or run as a normal daemon. If you want to start it
from `inetd' you should add a line similar to the one below to your
`/etc/inetd.conf'.

     kerberos-adm stream     tcp     nowait  root /usr/heimdal/libexec/kadmind kadmind

You might need to add `kerberos-adm' to your `/etc/services' as 749/tcp.

Access to the administration server is controlled by an acl-file,
(default `/var/heimdal/kadmind.acl'.) The lines in the access file, has
the following syntax:
     principal       [priv1,priv2,...]       [glob-pattern]

The matching is from top to bottom for matching principal (and if given,
glob-pattern).  When there is a match, the rights of that lines are
used.

The privileges you can assign to a principal are: `add',
`change-password' (or `cpw' for short), `delete', `get', `list', and
`modify', or the special privilege `all'. All of these roughly
corresponds to the different commands in `kadmin'.

If a GLOB-PATTERN is given on a line, it restricts the right for the
principal to only apply for the subjects that match the pattern.  The
patters are of the same type as those used in shell globbing, see
fnmatch(3).

In the example below `lha/admin' can change every principal in the
database. `jimmy/admin' can only modify principals that belong to the
realm `E.KTH.SE'. `mille/admin' is working at the help desk, so he
should only be able to change the passwords for single component
principals (ordinary users). He will not be able to change any `/admin'
principal.

     lha/admin@E.KTH.SE	all
     jimmy/admin@E.KTH.SE	all		*@E.KTH.SE
     jimmy/admin@E.KTH.SE	all		*/*@E.KTH.SE
     mille/admin@E.KTH.SE	change-password	*@E.KTH.SE

4.6 Password changing
=====================

To allow users to change their passwords, you should run `kpasswdd'.
It is not run from `inetd'.

You might need to add `kpasswd' to your `/etc/services' as 464/udp.

4.6.1 Password quality assurance
--------------------------------

It is important that users have good passwords, both to make it harder
to guess them and to avoid off-line attacks (pre-authentication provides
some defense against off-line attacks).  To ensure that the users choose
good passwords, you can enable password quality controls in `kpasswdd'.
The controls themselves are done in a shared library that is used by
`kpasswdd'.  To configure in these controls, add lines similar to the
following to your `/etc/krb5.conf':

     [password_quality]
             check_library = LIBRARY
             check_function = FUNCTION

The function FUNCTION in the shared library LIBRARY will be called for
proposed new passwords.  The function should be declared as:

     const char *
     function(krb5_context context, krb5_principal principal, krb5_data *pwd);

The function should verify that PWD is a good password for PRINCIPAL
and if so return `NULL'.  If it is deemed to be of low quality, it
should return a string explaining why that password should not be used.

Code for a password quality checking function that uses the cracklib
library can be found in `lib/kadm5/sample_password_check.c' in the
source code distribution.  It requires the cracklib library built with
the patch available at
`ftp://ftp.pdc.kth.se/pub/krb/src/cracklib.patch'.

If no password quality checking function is configured, it is only
verified that it is at least six characters of length.

4.7 Testing clients and servers
===============================

Now you should be able to run all the clients and servers.  Refer to the
appropriate man pages for information on how to use them.

4.8 Slave servers, Incremental propagation, Testing clients and servers, Setting up a realm
===========================================================================================

It is desirable to have at least one backup (slave) server in case the
master server fails. It is possible to have any number of such slave
servers but more than three usually doesn't buy much more redundancy.

All Kerberos servers for a realm shall have the same database so that
they present the same service to all the users.  The `hprop' program,
running on the master, will propagate the database to the slaves,
running `hpropd' processes.

Every slave needs a database directory, the master key (if it was used
for the database) and a keytab with the principal `hprop/HOSTNAME'.
Add the principal with the `ktutil' command and start `propd', as
follows:

     slave# ktutil get -p foo/admin hprop/`hostname`
     slave# mkdir /var/heimdal
     slave# hpropd

The master will use the principal `kadmin/hprop' to authenticate to the
slaves.  This principal should be added when running `kadmin -l init'
but if you do not have it in your database for whatever reason, please
add it with `kadmin -l add'.

Then run `hprop' on the master:

     master# hprop slave

This was just an on-hands example to make sure that everything was
working properly.  Doing it manually is of course the wrong way and to
automate this you will want to start `hpropd' from `inetd' on the
slave(s) and regularly run `hprop' on the master to regularly propagate
the database.  Starting the propagation once an hour from `cron' is
probably a good idea.

4.9 Incremental propagation
===========================

There is also a newer and still somewhat experimental mechanism for
doing incremental propagation in Heimdal.  Instead of sending the whole
database regularly, it sends the changes as they happen on the master to
the slaves.  The master keeps track of all the changes by assigned a
version number to every change to the database.  The slaves know which
was the latest version they saw and in this way it can be determined if
they are in sync or not.  A log of all the changes is kept on the master
and when a slave is at an older versioner than the oldest one in the
log, the whole database has to be sent.

Protocol-wise, all the slaves connects to the master and as a greeting
tell it the latest version that they have (`IHAVE' message).  The
master then responds by sending all the changes between that version and
the current version at the master (a series of `FORYOU' messages) or
the whole database in a `TELLYOUEVERYTHING' message.

4.9.1 Configuring incremental propagation
-----------------------------------------

The program that runs on the master is `ipropd-master' and all clients
run `ipropd-slave'.

Create the file `/var/heimdal/slaves' on the master containing all the
slaves that the database should be propagated to.  Each line contains
the full name of the principal (for example
`iprop/hemligare.foo.se@FOO.SE').

You should already have `iprop/tcp' defined as 2121, in your
`/etc/services'.  Otherwise, or if you need to use a different port for
some peculiar reason, you can use the `--port' option.  This is useful
when you have multiple realms to distribute from one server.

Then you need to create these principals that you added in the
configuration file.  Create one `iprop/hostname' for the master and for
every slave.

     master# /usr/heimdal/sbin/ktutil get iprop/`hostname`

The next step is to start the `ipropd-master' process on the master
server.  The `ipropd-master' listens on the UNIX-socket
`/var/heimdal/signal' to know when changes have been made to the
database so they can be propagated to the slaves.  There is also a
safety feature of testing the version number regularly (every 30
seconds) to see if it has been modified by some means that do not raise
this signal.  Then, start `ipropd-slave' on all the slaves:

     master# /usr/heimdal/libexec/ipropd-master &
     slave#  /usr/heimdal/libexec/ipropd-slave master &

4.10 Salting
============

Salting is used to make it harder to precalculate all possible keys.
Using a salt increases the search space to make it almost impossible to
precalculate all keys. Salting is the process of mixing a public string
(the salt) with the password, then sending it through an
encryption-type specific string-to-key function that will output the
fixed size encryption key.

In Kerberos 5 the salt is determined by the encryption-type, except in
some special cases.

In `des' there is the Kerberos 4 salt (none at all) or the afs-salt
(using the cell (realm in afs-lingo)).

In `arcfour' (the encryption type that Microsoft Windows 2000 uses)
there is no salt. This is to be compatible with NTLM keys in Windows NT
4.

`[kadmin]default_keys' in `krb5.conf' controls what salting to use,

The syntax of `[kadmin]default_keys' is
`[etype:]salt-type[:salt-string]'. `etype' is the encryption type (des,
des3, arcfour), `salt-type' is the type of salt (pw-salt or afs3-salt),
and the salt-string is the string that will be used as salt (remember
that if the salt is appended/prepended, the empty salt "" is the same
thing as no salt at all).

Common types of salting includes

   * `v4' (or `des:pw-salt:')

     The Kerberos 4 salting is using no salt att all. Reason there is
     colon that the end or the salt string is that it makes the salt
     the empty string (same as no salt).

   * `v5' (or `pw-salt')

     `pw-salt' means all regular encryption-types that is regular

   * `afs3-salt'

     `afs3-salt' is the salting that is used with Transarc kaserver. Its
     the cell appended to the password.

4.11 Cross realm
================

Suppose you are residing in the realm `MY.REALM', how do you
authenticate to a server in `OTHER.REALM'? Having valid tickets in
`MY.REALM' allows you to communicate with kerberised services in that
realm. However, the computer in the other realm does not have a secret
key shared with the Kerberos server in your realm.

It is possible to add a share keys between two realms that trust each
other. When a client program, such as `telnet' or `ssh', finds that the
other computer is in a different realm, it will try to get a ticket
granting ticket for that other realm, but from the local Kerberos
server. With that ticket granting ticket, it will then obtain service
tickets from the Kerberos server in the other realm.

For a two way trust between `MY.REALM' and `OTHER.REALM' add the
following principals to each realm. The principals should be
`krbtgt/OTHER.REALM@MY.REALM' and `krbtgt/MY.REALM@OTHER.REALM' in
`MY.REALM', and `krbtgt/MY.REALM@OTHER.REALM' and
`krbtgt/OTHER.REALM@MY.REALM'in `OTHER.REALM'.

In Kerberos 5 the trust can be one configured to be one way. So that
users from `MY.REALM' can authenticate to services in `OTHER.REALM',
but not the opposite. In the example above, the
`krbtgt/MY.REALM@OTHER.REALM' then should be removed.

The two principals must have the same key, key version number, and the
same set of encryption types. Remember to transfer the two keys in a
safe manner.

     vr$ klist
     Credentials cache: FILE:/tmp/krb5cc_913.console
             Principal: lha@E.KTH.SE

       Issued           Expires          Principal
     May  3 13:55:52  May  3 23:55:54  krbtgt/E.KTH.SE@E.KTH.SE

     vr$ telnet -l lha hummel.it.su.se
     Trying 2001:6b0:5:1095:250:fcff:fe24:dbf...
     Connected to hummel.it.su.se.
     Escape character is '^]'.
     Waiting for encryption to be negotiated...
     [ Trying mutual KERBEROS5 (host/hummel.it.su.se@SU.SE)... ]
     [ Kerberos V5 accepts you as ``lha@E.KTH.SE'' ]
     Encryption negotiated.
     Last login: Sat May  3 14:11:47 from vr.l.nxs.se
     hummel$ exit

     vr$ klist
     Credentials cache: FILE:/tmp/krb5cc_913.console
             Principal: lha@E.KTH.SE

       Issued           Expires          Principal
     May  3 13:55:52  May  3 23:55:54  krbtgt/E.KTH.SE@E.KTH.SE
     May  3 13:55:56  May  3 23:55:54  krbtgt/SU.SE@E.KTH.SE
     May  3 14:10:54  May  3 23:55:54  host/hummel.it.su.se@SU.SE

4.12 Transit policy
===================

If you want to use cross realm authentication through an intermediate
realm it must be explicitly allowed by either the KDCs or the server
receiving the request. This is done in `krb5.conf' in the `[capaths]'
section.

When the ticket transits through a realm to another realm, the
destination realm adds its peer to the "transited-realms" field in the
ticket. The field is unordered, this is since there is no way to know if
know if one of the transited-realms changed the order of the list.

The syntax for `[capaths]' section:

     [capaths]
             CLIENT-REALM = {
                     SERVER-REALM = PERMITTED-CROSS-REALMS ...
             }

The realm `STACKEN.KTH.SE' allows clients from `SU.SE' and `DSV.SU.SE'
to cross in. Since `STACKEN.KTH.SE' only have direct cross realm with
`KTH.SE', and `DSV.SU.SE' only have direct cross realm with `SU.SE'
they need to use both `SU.SE' and `KTH.SE' as transit realms.

     [capaths]
     	SU.SE = {
                         STACKEN.KTH.SE = KTH.SE
     	}
     	DSV.SU.SE = {
                         STACKEN.KTH.SE = SU.SE KTH.SE
     	}

4.13 Setting up DNS
===================

If there is information about where to find the KDC or kadmind for a
realm in the `krb5.conf' for a realm, that information will be
preferred and DNS will not be queried.

Heimdal will try to use DNS to find the KDCs for a realm. First it will
try to find `SRV' resource record (RR) for the realm. If no SRV RRs are
found, it will fall back to looking for a `A' RR for a machine named
kerberos.REALM, and then kerberos-1.REALM, etc

Adding this information to DNS makes the client have less configuration
(in the common case, no configuration) and allows the system
administrator to change the number of KDCs and on what machines they
are running without caring about clients.

The backside of using DNS that the client might be fooled to use the
wrong server if someone fakes DNS replies/data, but storing the IP
addresses of the KDC on all the clients makes it very hard to change
the infrastructure.

Example of the configuration for the realm `EXAMPLE.COM',

     $ORIGIN example.com.
     _kerberos._tcp          SRV     10 1 88 kerberos.example.com.
     _kerberos._udp          SRV     10 1 88 kerberos.example.com.
     _kerberos._tcp          SRV     10 1 88 kerberos-1.example.com.
     _kerberos._udp          SRV     10 1 88 kerberos-1.example.com.
     _kpasswd._udp           SRV     10 1 464 kerberos.example.com.
     _kerberos-adm._tcp	SRV	10 1 749 kerberos.example.com.

More information about DNS SRV resource records can be found in
RFC-2782 (A DNS RR for specifying the location of services (DNS SRV)).

5 Things in search for a better place
*************************************

5.1 Making things work on Ciscos
================================

Modern versions of Cisco IOS has some support for authenticating via
Kerberos 5. This can be used both by having the router get a ticket when
you login (boring), and by using Kerberos authenticated telnet to access
your router (less boring). The following has been tested on IOS
11.2(12), things might be different with other versions. Old versions
are known to have bugs.

To make this work, you will first have to configure your router to use
Kerberos (this is explained in the documentation). A sample
configuration looks like the following:

     aaa new-model
     aaa authentication login default krb5-telnet krb5 enable
     aaa authorization exec krb5-instance
     kerberos local-realm FOO.SE
     kerberos srvtab entry host/router.foo.se 0 891725446 4 1 8 012345678901234567
     kerberos server FOO.SE 10.0.0.1
     kerberos instance map admin 15

This tells you (among other things) that when logging in, the router
should try to authenticate with kerberised telnet, and if that fails try
to verify a plain text password via a Kerberos ticket exchange (as
opposed to a local database, RADIUS or something similar), and if that
fails try the local enable password. If you're not careful when you
specify the `login default' authentication mechanism, you might not be
able to login at all. The `instance map' and `authorization exec' lines
says that people with `admin' instances should be given `enabled' shells
when logging in.

The numbers after the principal on the `srvtab' line are principal type,
time stamp (in seconds since 1970), key version number (4), keytype (1
== des), key length (always 8 with des), and then the key.

To make the Heimdal KDC produce tickets that the Cisco can decode you
might have to turn on the `encode_as_rep_as_tgs_rep' flag in the KDC.
You will also have to specify that the router can't handle anything but
`des-cbc-crc'. This can be done with the `del_enctype' command of
`kadmin'.

This all fine and so, but unless you have an IOS version with encryption
(available only in the U.S) it doesn't really solve any problems. Sure
you don't have to send your password over the wire, but since the telnet
connection isn't protected it's still possible for someone to steal your
session. This won't be fixed until someone adds integrity to the telnet
protocol.

A working solution would be to hook up a machine with a real operating
system to the console of the Cisco and then use it as a backwards
terminal server.

5.2 Making things work on Transarc/OpenAFS AFS
==============================================

5.2.1 How to get a KeyFile
--------------------------

`ktutil -k AFSKEYFILE:KeyFile get afs@MY.REALM'

or you can extract it with kadmin

     kadmin> ext -k AFSKEYFILE:/usr/afs/etc/KeyFile afs@My.CELL.NAME

You have to make sure you have a `des-cbc-md5' encryption type since
that is the key that will be converted.

5.2.2 How to convert a srvtab to a KeyFile
------------------------------------------

You need a `/usr/vice/etc/ThisCell' containing the cellname of you
AFS-cell.

`ktutil copy krb4:/root/afs-srvtab AFSKEYFILE:/usr/afs/etc/KeyFile'.

If keyfile already exists, this will add the new key in afs-srvtab to
KeyFile.

5.3 Using 2b tokens with AFS
============================

5.3.1 What is 2b ?
------------------

2b is the name of the proposal that was implemented to give basic
Kerberos 5 support to AFS in rxkad. Its not real Kerberos 5 support
since it still uses fcrypt for data encryption and not Kerberos
encryption types.

Its only possible (in all cases) to do this for DES encryption types
because only then the token (the AFS equivalent of a ticket) will be be
smaller than the maximum size that can fit in the token cache in
OpenAFS/Transarc client. Its so tight fit that some extra wrapping on
the ASN1/DER encoding is removed from the Kerberos ticket.

2b uses a Kerberos 5 EncTicketPart instead of a Kerberos 4 ditto for
the part of the ticket that is encrypted with the service's key. The
client doesn't know what's inside the encrypted data so to the client
it doesn't matter.

To  differentiate between Kerberos 4 tickets and Kerberos 5 tickets 2b
uses a special kvno, 213 for 2b tokens and 255 for Kerberos 5 tokens.

Its a requirement that all AFS servers that support 2b also support
native Kerberos 5 in rxkad.

5.3.2 Configuring Heimdal to use 2b tokens
------------------------------------------

Support for 2b tokens are turned on for specific principals by adding
them to the string list option `[kdc]use_2b' in the kdc's `krb5.conf'
file.

     [kdc]
     	use_2b = {
     		afs@SU.SE = yes
     		afs/it.su.se@SU.SE = yes
     	}

5.3.3 Configuring AFS clients
-----------------------------

There is no need to configure AFS clients. The only software that needs
to be installed/upgrade is a Kerberos 5 enabled `afslog'.

6 Kerberos 4 issues
*******************

If compiled with version 4 support, the KDC can serve requests from a
Kerberos 4 client. There are a few things you must do for this to work.

The KDC will also have kaserver emulation and be able to handle
AFS-clients that use `klog'.

6.1 Principal conversion issues
===============================

First, Kerberos 4 and Kerberos 5 principals are different. A version 4
principal consists of a name, an instance, and a realm. A version 5
principal has one or more components, and a realm (the terms "name" and
"instance" are still used, for the first and second component,
respectively).    Also, in some cases the name of a version 4 principal
differs from the first component of the corresponding version 5
principal. One notable example is the "host" type principals, where the
version 4 name is `rcmd' (for "remote command"), and the version 5 name
is `host'. For the class of principals that has a hostname as instance,
there is an other major difference, Kerberos 4 uses only the first
component of the hostname, whereas Kerberos 5 uses the fully qualified
hostname.

Because of this it can be hard or impossible to correctly convert a
version 4 principal to a version 5 principal (1). The biggest problem is
to know if the conversion resulted in a valid principal. To give an
example, suppose you want to convert the principal `rcmd.foo'.

The `rcmd' name suggests that the instance is a hostname (even if there
are exceptions to this rule). To correctly convert the instance `foo'
to a hostname, you have to know which host it is referring to. You can
to this by either guessing (from the realm) which domain name to
append, or you have to have a list of possible hostnames. In the
simplest cases you can cover most principals with the first rule. If you
have several domains sharing a single realm this will not usually work.
If the exceptions are few you can probably come by with a lookup table
for the exceptions.

In a complex scenario you will need some kind of host lookup mechanism.
Using DNS for this is tempting, but DNS is error prone, slow and unsafe
(2).

Fortunately, the KDC has a trump on hand: it can easily tell if a
principal exists in the database. The KDC will use
`krb5_425_conv_principal_ext' to convert principals when handling to
version 4 requests.

---------- Footnotes ----------

(1) the other way is not always trivial either, but usually easier

(2) at least until secure DNS is commonly available

6.2 Converting a version 4 database
===================================

If you want to convert an existing version 4 database, the principal
conversion issue arises too.

If you decide to convert your database once and for all, you will only
have to do this conversion once. It is also possible to run a version 5
KDC as a slave to a version 4 KDC. In this case this conversion will
happen every time the database is propagated.  When doing this
conversion, there are a few things to look out for. If you have stale
entries in the database, these entries will not be converted. This might
be because these principals are not used anymore, or it might be just
because the principal couldn't be converted.

You might also see problems with a many-to-one mapping of principals.
For instance, if you are using DNS lookups and you have two principals
`rcmd.foo' and `rcmd.bar', where `foo' is a CNAME for `bar', the
resulting principals will be the same. Since the conversion function
can't tell which is correct, these conflicts will have to be resolved
manually.

6.2.1 Conversion example
------------------------

Given the following set of hosts and services:

     foo.se          rcmd
     mail.foo.se     rcmd, pop
     ftp.bar.se      rcmd, ftp

you have a database that consists of the following principals:

`rcmd.foo', `rcmd.mail', `pop.mail', `rcmd.ftp', and `ftp.ftp'.

lets say you also got these extra principals: `rcmd.gone',
`rcmd.old-mail', where `gone.foo.se' was a machine that has now passed
away, and `old-mail.foo.se' was an old mail machine that is now a CNAME
for `mail.foo.se'.

When you convert this database you want the following conversions to be
done:
     rcmd.foo         host/foo.se
     rcmd.mail        host/mail.foo.se
     pop.mail         pop/mail.foo.se
     rcmd.ftp         host/ftp.bar.se
     ftp.ftp          ftp/ftp.bar.se
     rcmd.gone        removed
     rcmd.old-mail    removed

A `krb5.conf' that does this looks like:

     [realms]
             FOO.SE = {
                     v4_name_convert = {
                             host = {
                                     ftp = ftp
                                     pop = pop
                                     rcmd = host
                             }
                     }
                     v4_instance_convert = {
                             foo = foo.se
                             ftp = ftp.bar.se
                     }
                     default_domain = foo.se
             }

The `v4_name_convert' section says which names should be considered
having an instance consisting of a hostname, and it also says how the
names should be converted (for instance `rcmd' should be converted to
`host'). The `v4_instance_convert' section says how a hostname should
be qualified (this is just a hosts-file in disguise). Host-instances
that aren't covered by `v4_instance_convert' are qualified by appending
the contents of the `default_domain'.

Actually, this example doesn't work. Or rather, it works to well. Since
it has no way of knowing which hostnames are valid and which are not, it
will happily convert `rcmd.gone' to `host/gone.foo.se'. This isn't a
big problem, but if you have run your kerberos realm for a few years,
chances are big that you have quite a few `junk' principals.

If you don't want this you can remove the `default_domain' statement,
but then you will have to add entries for _all_ your hosts in the
`v4_instance_convert' section.

Instead of doing this you can use DNS to convert instances. This is not
a solution without problems, but it is probably easier than adding lots
of static host entries.

To enable DNS lookup you should turn on `v4_instance_resolve' in the
`[libdefaults]' section.

6.2.2 Converting a database
---------------------------

The database conversion is done with `hprop'. You can run this command
to propagate the database to the machine called `slave-server' (which
should be running a `hpropd').

     hprop --source=krb4-db --master-key=/.m slave-server

This command can also be to use for converting the v4 database on the
server:

     hprop -n --source=krb4-db -d /var/kerberos/principal --master-key=/.m | hpropd -n

6.3 Version 4 Kadmin
====================

`kadmind' can act as a version 4 kadmind, and you can do most
operations, but with some restrictions (since the version 4 kadmin
protocol is, lets say, very ad hoc.) One example is that it only passes
des keys when creating principals and changing passwords (modern kpasswd
clients do send the password, so it's possible to to password quality
checks). Because of this you can only create principals with des keys,
and you can't set any flags or do any other fancy stuff.

To get this to work, you have to add another entry to inetd (since
version 4 uses port 751, not 749).

_And then there are a many more things you can do; more on this in a
later version of this manual. Until then, UTSL._

6.4 kaserver
============

6.4.1 kaserver emulation
------------------------

The Heimdal kdc can emulate a kaserver. The kaserver is a Kerberos 4
server with pre-authentication using Rx as the on-wire protocol. The kdc
contains a minimalistic Rx implementation.

There are three parts of the kaserver; KAA (Authentication), KAT (Ticket
Granting), and KAM (Maintenance). The KAA interface and KAT interface
both passes over DES encrypted data-blobs (just like the
Kerberos-protocol) and thus do not need any other protection.  The KAM
interface uses `rxkad' (Kerberos authentication layer for Rx) for
security and data protection, and is used for example for changing
passwords.  This part is not implemented in the kdc.

Another difference between the ka-protocol and the Kerberos 4 protocol
is that the pass-phrase is salted with the cellname in the `string to
key' function in the ka-protocol, while in the Kerberos 4 protocol there
is no salting of the password at all. To make sure AFS-compatible keys
are added to each principals when they are created or their password are
changed, `afs3-salt' should be added to `[kadmin]default_keys'.

6.4.2 Transarc AFS Windows client
---------------------------------

The Transarc Windows client uses Kerberos 4 to obtain tokens, and thus
does not need a kaserver. The Windows client assumes that the Kerberos
server is on the same machine as the AFS-database server. If you do not
like to do that you can add a small program that runs on the database
servers that forward all kerberos requests to the real kerberos server.
A program that does this is `krb-forward'
(`ftp://ftp.stacken.kth.se/pub/projekts/krb-forward').

7 Windows 2000 compatability
****************************

Windows 2000 (formerly known as Windows NT 5) from Microsoft implements
Kerberos 5.  Their implementation, however, has some quirks,
peculiarities, and bugs.  This chapter is a short summary of the things
that we have found out while trying to test Heimdal against Windows
2000.  Another big problem with the Kerberos implementation in Windows
2000 is that the available documentation is more focused on getting
things to work rather than how they work and not that useful in figuring
out how things really work.

This information should apply to Heimdal 0.3a and Windows 2000
Professional.  It's of course subject all the time and mostly consists
of our not so inspired guesses.  Hopefully it's still somewhat useful.

7.1 Configuring Windows 2000 to use a Heimdal KDC
=================================================

You need the command line program called `ksetup.exe' which is available
in the file `SUPPORT/TOOLS/SUPPORT.CAB' on the Windows 2000 Professional
CD-ROM. This program is used to configure the Kerberos settings on a
Workstation.

`Ksetup' store the domain information under the registry key:
`HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\Kerberos\Domains'.

Use the kadmin program in Heimdal to create a host principal in the
Kerberos realm.

     unix% kadmin
     kadmin> ank -pw password host/datan.my.domain

You must configure the Workstation as a member of a workgroup, as
opposed to a member in an NT domain, and specify the KDC server of the
realm as follows:
     C:> ksetup /setdomain MY.REALM
     C:> ksetup /addkdc MY.REALM kdc.my.domain

Set the machine password, i.e. create the local keytab:
     C:> ksetup /setmachpassword password

The workstation must now be rebooted.

A mapping between local NT users and Kerberos principals must be
specified, you have two choices:

     C:> ksetup /mapuser user@MY.REALM nt_user

This will map a user to a specific principal, this allows you to have
other usernames in the realm than in your NT user database. (Don't ask
me why on earth you would want that...)

You can also say:
     C:> ksetup /mapuser * *
The Windows machine will now map any user to the corresponding
principal, for example `nisse' to the principal `nisse@MY.REALM'.
(This is most likely what you want.)

7.2 Inter-Realm keys (trust) between Windows 2000 and a Heimdal KDC
===================================================================

See also the Step-by-Step guide from Microsoft, referenced below.

Install Windows 2000, and create a new controller (Active Directory
Server) for the domain.

By default the trust will be non-transitive. This means that only users
directly from the trusted domain may authenticate. This can be changed
to transitive by using the `netdom.exe' tool.

You need to tell Windows 2000 on what hosts to find the KDCs for the
non-Windows realm with `ksetup', see Configuring Windows 2000 to use a Heimdal KDC.

This need to be done on all computers that want enable cross-realm
login with `Mapped Names'.

Then you need to add the inter-realm keys on the Windows kdc. Start the
Domain Tree Management tool. (Found in Programs, Administrative tools,
Active Directory Domains and Trusts).

Right click on Properties of your domain, select the Trust tab.  Press
Add on the appropriate trust windows and enter domain name and
password. When prompted if this is a non-Windows Kerberos realm, press
OK.

Do not forget to add trusts in both directions.

You also need to add the inter-realm keys to the Heimdal KDC. There are
some tweaks that you need to do to `krb5.conf' beforehand.

     [libdefaults]
     	default_etypes = des-cbc-crc
     	default_etypes_des = des-cbc-crc

since otherwise checksum types that are not understood by Windows 2000
will be generated (see Quirks of Windows 2000 KDC.).

Another issue is salting.  Since Windows 2000 does not seem to
understand Kerberos 4 salted hashes you might need to turn off anything
similar to the following if you have it, at least while adding the
principals that are going to share keys with Windows 2000.

     	[kadmin]default_keys = v5 v4

You must also set:

Once that is also done, you can add the required inter-realm keys:

     kadmin add krbtgt/NT.REALM.EXAMPLE.COM@EXAMPLE.COM
     kadmin add krbtgt/REALM.EXAMPLE.COM@NT.EXAMPLE.COM

Use the same passwords for both keys.

Do not forget to reboot before trying the new realm-trust (after running
`ksetup'). It looks like it might work, but packets are never sent to
the non-Windows KDC.

7.3 Create account mappings
===========================

Start the `Active Directory Users and Computers' tool. Select the View
menu, that is in the left corner just below the real menu (or press
Alt-V), and select Advanced Features. Right click on the user that you
are going to do a name mapping for and choose Name mapping.

Click on the Kerberos Names tab and add a new principal from the
non-Windows domain.

7.4 Encryption types
====================

Windows 2000 supports both the standard DES encryptions (des-cbc-crc and
des-cbc-md5) and its own proprietary encryption that is based on MD4 and
rc4 that is documented in and is supposed to be described in
`draft-brezak-win2k-krb-rc4-hmac-03.txt'.  New users will get both MD4
and DES keys.  Users that are converted from a NT4 database, will only
have MD4 passwords and will need a password change to get a DES key.

Heimdal implements both of these encryption types, but since DES is the
standard and the hmac-code is somewhat newer, it is likely to work
better.

7.5 Authorization data
======================

The Windows 2000 KDC also adds extra authorization data in tickets.  It
is at this point unclear what triggers it to do this.  The format of
this data is only available under a "secret" license from Microsoft,
which prohibits you implementing it.

A simple way of getting hold of the data to be able to understand it
better is described here.

  1. Find the client example on using the SSPI in the SDK documentation.

  2. Change "AuthSamp" in the source code to lowercase.

  3. Build the program.

  4. Add the "authsamp" principal with a known password to the
     database.  Make sure it has a DES key.

  5. Run `ktutil add' to add the key for that principal to a keytab.

  6. Run `appl/test/nt_gss_server -p 2000 -s authsamp --dump-auth=file'
     where file is an appropriate file.

  7. It should authenticate and dump for you the authorization data in
     the file.

  8. The tool `lib/asn1/asn1_print' is somewhat useful for analyzing
     the data.

7.6 Quirks of Windows 2000 KDC
==============================

There are some issues with salts and Windows 2000.  Using an empty salt,
which is the only one that Kerberos 4 supported and is therefore known
as a Kerberos 4 compatible salt does not work, as far as we can tell
from out experiments and users reports.  Therefore, you have to make
sure you keep around keys with all the different types of salts that are
required.

Microsoft seems also to have forgotten to implement the checksum
algorithms `rsa-md4-des' and `rsa-md5-des'. This can make Name mapping
(see Create account mappings) fail if a `des-cbc-md5' key is used.
To make the KDC return only `des-cbc-crc' you must delete the
`des-cbc-md5' key from the kdc using the `kadmin del_enctype' command.

     kadmin del_enctype lha des-cbc-md5

You should also add the following entries to the `krb5.conf' file:

     [libdefaults]
     	default_etypes = des-cbc-crc
     	default_etypes_des = des-cbc-crc

These configuration options will make sure that no checksums of the
unsupported types are generated.

7.7 Useful links when reading about the Windows 2000
====================================================

See also our paper presented at the 2001 usenix Annual Technical
Conference, available in the proceedings or at
`http://www.usenix.org/publications/library/proceedings/usenix01/freenix01/westerlund.html'.

There are lots of text about Kerberos on Microsoft's web site, here is a
short list of the interesting documents that we have managed to find.

   * Step-by-Step Guide to Kerberos 5 (krb5 1.0) Interoperability -
     `http://www.microsoft.com/windows2000/library/planning/security/kerbsteps.asp'
     Kerberos GSS-API (in Windows-ize SSPI), Windows as a client in a
     non-Windows KDC realm, adding unix clients to a Windows 2000 KDC,
     and adding cross-realm trust (see Inter-Realm keys (trust) between Windows 2000 and a Heimdal KDC.).

   * Windows 2000 Kerberos Authentication -
     `http://www.microsoft.com/TechNet/win2000/win2ksrv/technote/kerberos.asp'
     White paper that describes how Kerberos is used in Windows 2000.

   * Overview of kerberos -
     `http://support.microsoft.com/support/kb/articles/Q248/7/58.ASP'
     Links to useful other links.

   * Klist for windows -
     `http://msdn.microsoft.com/library/periodic/period00/security0500.htm'
     Describes where to get a klist for Windows 2000.

   * Event logging for kerberos -
     `http://support.microsoft.com/support/kb/articles/Q262/1/77.ASP'.
     Basicly it say that you can add a registry key
     `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters\LogLevel'
     with value DWORD equal to 1, and then you'll get logging in the
     Event Logger.

   * Access to the active directory through LDAP
     `http://msdn.microsoft.com/library/techart/kerberossamp.htm'

Other useful programs include these:

   * pwdump2 `http://www.webspan.net/~tas/pwdump2/'

8 Programming with Kerberos
***************************

First you need to know how the Kerberos model works, go read the
introduction text (see What is Kerberos?).

8.1 Kerberos 5 API Overview
===========================

Most functions are documenteded in manual pages.  This overview only
tries to point to where to look for a specific function.

8.1.1 Kerberos context
----------------------

A kerberos context (`krb5_context') holds all per thread state. All
global variables that are context specific are stored in this struture,
including default encryption types, credential-cache (ticket file), and
default realms.

See the manual pages for `krb5_context(3)' and `krb5_init_context(3)'.

8.1.2 Kerberos authenication context
------------------------------------

Kerberos authentication context (`krb5_auth_context') holds all context
related to an authenticated connection, in a similar way to the
kerberos context that holds the context for the thread or process.

The `krb5_auth_context' is used by various functions that are directly
related to authentication between the server/client. Example of data
that this structure contains are various flags, addresses of client and
server, port numbers, keyblocks (and subkeys), sequence numbers, replay
cache, and checksum types.

See the manual page for `krb5_auth_context(3)'.

8.1.3 Keytab management
-----------------------

A keytab is a storage for locally stored keys. Heimdal includes keytab
support for Kerberos 5 keytabs, Kerberos 4 srvtab, AFS-KeyFile's, and
for storing keys in memory.

See also manual page for `krb5_keytab(3)'

8.2 Walkthru a sample Kerberos 5 client
=======================================

This example contains parts of a sample TCP Kerberos 5 clients, if you
want a real working client, please look in `appl/test' directory in the
Heimdal distribution.

All Kerberos error-codes that are returned from kerberos functions in
this program are passed to `krb5_err', that will print a descriptive
text of the error code and exit. Graphical programs can convert
error-code to a humal readable error-string with the
`krb5_get_err_text(3)' function.

Note that you should not use any Kerberos function before
`krb5_init_context()' have completed successfully. That is the reson
`err()' is used when `krb5_init_context()' fails.

First the client needs to call `krb5_init_context' to initialize the
Kerberos 5 library. This is only needed once per thread in the program.
If the function returns a non-zero value it indicates that either the
Kerberos implemtation is failing or its disabled on this host.

     #include <krb5.h>

     int
     main(int argc, char **argv)
     {
             krb5_context context;

             if (krb5_context(&context))
                     errx (1, "krb5_context");

Now the client wants to connect to the host at the other end. The
preferred way of doing this is using `getaddrinfo(3)' (for operating
system that have this function implemented), since getaddrinfo is
neutral to the address type and can use any protocol that is available.

             struct addrinfo *ai, *a;
             struct addrinfo hints;
             int error;

             memset (&hints, 0, sizeof(hints));
             hints.ai_socktype = SOCK_STREAM;
             hints.ai_protocol = IPPROTO_TCP;

             error = getaddrinfo (hostname, "pop3", &hints, &ai);
             if (error)
                     errx (1, "%s: %s", hostname, gai_strerror(error));

             for (a = ai; a != NULL; a = a->ai_next) {
                     int s;

                     s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
                     if (s < 0)
                             continue;
                     if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
                             warn ("connect(%s)", hostname);
                                 close (s);
                                 continue;
                     }
                     freeaddrinfo (ai);
                     ai = NULL;
             }
             if (ai) {
                         freeaddrinfo (ai);
                         errx ("failed to contact %s", hostname);
             }

Before authenticating, an authentication context needs to be created.
This context keeps all information for one (to be) authenticated
connection (see `krb5_auth_context(3)').

             status = krb5_auth_con_init (context, &auth_context);
             if (status)
                     krb5_err (context, 1, status, "krb5_auth_con_init");

For setting the address in the authentication there is a help function
`krb5_auth_con_setaddrs_from_fd' that does everthing that is needed
when given a connected file descriptor to the socket.

             status = krb5_auth_con_setaddrs_from_fd (context,
                                                      auth_context,
                                                      &sock);
             if (status)
                     krb5_err (context, 1, status,
                               "krb5_auth_con_setaddrs_from_fd");

The next step is to build a server principal for the service we want to
connect to. (See also `krb5_sname_to_principal(3)'.)

             status = krb5_sname_to_principal (context,
                                               hostname,
                                               service,
                                               KRB5_NT_SRV_HST,
                                               &server);
             if (status)
                     krb5_err (context, 1, status, "krb5_sname_to_principal");

The client principal is not passed to `krb5_sendauth(3)' function, this
causes the `krb5_sendauth' function to try to figure it out itself.

The server program is using the function `krb5_recvauth(3)' to receive
the Kerberos 5 authenticator.

In this case, mutual authenication will be tried. That means that the
server will authenticate to the client. Using mutual authenication is
good since it enables the user to verify that they are talking to the
right server (a server that knows the key).

If you are using a non-blocking socket you will need to do all work of
`krb5_sendauth' yourself. Basically you need to send over the
authenticator from `krb5_mk_req(3)' and, in case of mutual
authentication, verifying the result from the server with
`krb5_rd_rep(3)'.

             status = krb5_sendauth (context,
                                     &auth_context,
                                     &sock,
                                     VERSION,
                                     NULL,
                                     server,
                                     AP_OPTS_MUTUAL_REQUIRED,
                                     NULL,
                                     NULL,
                                     NULL,
                                     NULL,
                                     NULL,
                                     NULL);
             if (status)
                     krb5_err (context, 1, status, "krb5_sendauth");

Once authentication has been performed, it is time to send some data.
First we create a krb5_data structure, then we sign it with
`krb5_mk_safe(3)' using the `auth_context' that contains the
session-key that was exchanged in the
`krb5_sendauth(3)'/`krb5_recvauth(3)' authentication sequence.

             data.data   = "hej";
             data.length = 3;

             krb5_data_zero (&packet);

             status = krb5_mk_safe (context,
                                    auth_context,
                                    &data,
                                    &packet,
                                    NULL);
             if (status)
                     krb5_err (context, 1, status, "krb5_mk_safe");

And send it over the network.

             len = packet.length;
             net_len = htonl(len);

             if (krb5_net_write (context, &sock, &net_len, 4) != 4)
                     err (1, "krb5_net_write");
             if (krb5_net_write (context, &sock, packet.data, len) != len)
                     err (1, "krb5_net_write");

To send encrypted (and signed) data `krb5_mk_priv(3)' should be used
instead. `krb5_mk_priv(3)' works the same way as `krb5_mk_safe(3)',
with the exception that it encrypts the data in addition to signing it.

             data.data   = "hemligt";
             data.length = 7;

             krb5_data_free (&packet);

             status = krb5_mk_priv (context,
                                    auth_context,
                                    &data,
                                    &packet,
                                    NULL);
             if (status)
                     krb5_err (context, 1, status, "krb5_mk_priv");

And send it over the network.

             len = packet.length;
             net_len = htonl(len);

             if (krb5_net_write (context, &sock, &net_len, 4) != 4)
                     err (1, "krb5_net_write");
             if (krb5_net_write (context, &sock, packet.data, len) != len)
                     err (1, "krb5_net_write");

The server is using `krb5_rd_safe(3)' and `krb5_rd_priv(3)' to verify
the signature and decrypt the packet.

8.3 Validating a password in an application
===========================================

See the manual page for `krb5_verify_user(3)'.

9 Migration
***********

9.1 General issues
==================

When migrating from a Kerberos 4 KDC.

9.2 Order in what to do things:
===============================

   * Convert the database, check all principals that hprop complains
     about.

     `hprop -n --source=<NNN>| hpropd -n'

     Replace <NNN> with whatever source you have, like krb4-db or
     krb4-dump.

   * Run a Kerberos 5 slave for a while.

   * Figure out if it does everything you want it to.

     Make sure that all things that you use works for you.

   * Let a small number of controlled users use Kerberos 5 tools.

     Find a sample population of your users and check what programs
     they use, you can also check the kdc-log to check what ticket are
     checked out.

   * Burn the bridge and change the master.

   * Let all users use the Kerberos 5 tools by default.

   * Turn off services that do not need Kerberos 4 authentication.

     Things that might be hard to get away is old programs with support
     for Kerberos 4. Example applications are old Eudora installations
     using KPOP, and Zephyr. Eudora can use the Kerberos 4 kerberos in
     the Heimdal kdc.

Appendix A Acknowledgments
**************************

Eric Young wrote "libdes".

The University of California at Berkeley initially wrote `telnet', and
`telnetd'.  The authentication and encryption code of `telnet' and
`telnetd' was added by David Borman (then of Cray Research, Inc).  The
encryption code was removed when this was exported and then added back
by Juha Eskelinen, <esc@magic.fi>.

The `popper' was also a Berkeley program initially.

Some of the functions in `libroken' also come from Berkeley by way of
NetBSD/FreeBSD.

`editline' was written by Simmule Turner and Rich Salz.

The `getifaddrs' implementation for Linux was written by Hideaki
YOSHIFUJI for the Usagi project.

Bugfixes, documentation, encouragement, and code has been contributed
by:
Derrick J Brashear
     <shadow@dementia.org>

Ken Hornstein
     <kenh@cmf.nrl.navy.mil>

Johan Ihrén
     <johani@pdc.kth.se>

Love Hörnquist-Åstrand
     <lha@stacken.kth.se>

Magnus Ahltorp
     <map@stacken.kth.se>

Mark Eichin
     <eichin@cygnus.com>

Marc Horowitz
     <marc@cygnus.com>

Luke Howard
     <lukeh@PADL.COM>

Brandon S. Allbery KF8NH
     <allbery@kf8nh.apk.net>

Jun-ichiro itojun Hagino
     <itojun@kame.net>

Daniel Kouril
     <kouril@informatics.muni.cz>

Åke Sandgren
     <ake@cs.umu.se>

Michal Vocu
     <michal@karlin.mff.cuni.cz>

Miroslav Ruda
     <ruda@ics.muni.cz>

Brian A May
     <bmay@snoopy.apana.org.au>

Chaskiel M Grundman
     <cg2v@andrew.cmu.edu>

Richard Nyberg
     <rnyberg@it.su.se>

Frank van der Linden
     <fvdl@netbsd.org>

Cizzi Storm
     <cizzi@it.su.se>

and we hope that those not mentioned here will forgive us.

All bugs were introduced by ourselves.