jdk/test/sun/security/krb5/auto/KDC.java
changeset 1454 d9b6f1de641f
child 1456 1d3c6724de2f
equal deleted inserted replaced
1453:d7e8bf374129 1454:d9b6f1de641f
       
     1 /*
       
     2  * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.
       
     8  *
       
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    12  * version 2 for more details (a copy is included in the LICENSE file that
       
    13  * accompanied this code).
       
    14  *
       
    15  * You should have received a copy of the GNU General Public License version
       
    16  * 2 along with this work; if not, write to the Free Software Foundation,
       
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    18  *
       
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
       
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
       
    21  * have any questions.
       
    22  */
       
    23 
       
    24 import java.lang.reflect.Constructor;
       
    25 import java.lang.reflect.Field;
       
    26 import java.lang.reflect.InvocationTargetException;
       
    27 import java.net.*;
       
    28 import java.io.*;
       
    29 import java.lang.reflect.Method;
       
    30 import java.security.SecureRandom;
       
    31 import java.util.*;
       
    32 import java.util.concurrent.*;
       
    33 import sun.security.krb5.*;
       
    34 import sun.security.krb5.internal.*;
       
    35 import sun.security.krb5.internal.crypto.KeyUsage;
       
    36 import sun.security.krb5.internal.ktab.KeyTab;
       
    37 import sun.security.util.DerInputStream;
       
    38 import sun.security.util.DerOutputStream;
       
    39 import sun.security.util.DerValue;
       
    40 
       
    41 /**
       
    42  * A KDC server.
       
    43  * <p>
       
    44  * Features:
       
    45  * <ol>
       
    46  * <li> Supports TCP and UDP
       
    47  * <li> Supports AS-REQ and TGS-REQ
       
    48  * <li> Principal db and other settings hard coded in application
       
    49  * <li> Options, say, request preauth or not
       
    50  * </ol>
       
    51  * Side effects:
       
    52  * <ol>
       
    53  * <li> The Sun-internal class <code>sun.security.krb5.Config</code> is a
       
    54  * singleton and initialized according to Kerberos settings (krb5.conf and
       
    55  * java.security.krb5.* system properties). This means once it's initialized
       
    56  * it will not automatically notice any changes to these settings (or file
       
    57  * changes of krb5.conf). The KDC class normally does not touch these
       
    58  * settings (except for the <code>writeKtab()</code> method). However, to make
       
    59  * sure nothing ever goes wrong, if you want to make any changes to these
       
    60  * settings after calling a KDC method, call <code>Config.refresh()</code> to
       
    61  * make sure your changes are reflected in the <code>Config</code> object.
       
    62  * </ol>
       
    63  * Issues and TODOs:
       
    64  * <ol>
       
    65  * <li> Generates krb5.conf to be used on another machine, currently the kdc is
       
    66  * always localhost
       
    67  * <li> More options to KDC, say, error output, say, response nonce !=
       
    68  * request nonce
       
    69  * </ol>
       
    70  * Note: This program uses internal krb5 classes (including reflection to
       
    71  * access private fields and methods).
       
    72  * <p>
       
    73  * Usages:
       
    74  * <p>
       
    75  * 1. Init and start the KDC:
       
    76  * <pre>
       
    77  * KDC kdc = KDC.create("REALM.NAME", port, isDaemon);
       
    78  * KDC kdc = KDC.create("REALM.NAME");
       
    79  * </pre>
       
    80  * Here, <code>port</code> is the UDP and TCP port number the KDC server
       
    81  * listens on. If zero, a random port is chosen, which you can use getPort()
       
    82  * later to retrieve the value.
       
    83  * <p>
       
    84  * If <code>isDaemon</code> is true, the KDC worker threads will be daemons.
       
    85  * <p>
       
    86  * The shortcut <code>KDC.create("REALM.NAME")</code> has port=0 and
       
    87  * isDaemon=false, and is commonly used in an embedded KDC.
       
    88  * <p>
       
    89  * 2. Adding users:
       
    90  * <pre>
       
    91  * kdc.addPrincipal(String principal_name, char[] password);
       
    92  * kdc.addPrincipalRandKey(String principal_name);
       
    93  * </pre>
       
    94  * A service principal's name should look like "host/f.q.d.n". The second form
       
    95  * generates a random key. To expose this key, call <code>writeKtab()</code> to
       
    96  * save the keys into a keytab file.
       
    97  * <p>
       
    98  * Note that you need to add the principal name krbtgt/REALM.NAME yourself.
       
    99  * <p>
       
   100  * Note that you can safely add a principal at any time after the KDC is
       
   101  * started and before a user requests info on this principal.
       
   102  * <p>
       
   103  * 3. Other public methods:
       
   104  * <ul>
       
   105  * <li> <code>getPort</code>: Returns the port number the KDC uses
       
   106  * <li> <code>getRealm</code>: Returns the realm name
       
   107  * <li> <code>writeKtab</code>: Writes all principals' keys into a keytab file
       
   108  * <li> <code>saveConfig</code>: Saves a krb5.conf file to access this KDC
       
   109  * <li> <code>setOption</code>: Sets various options
       
   110  * </ul>
       
   111  * Read the javadoc for details. Lazy developer can use <code>OneKDC</code>
       
   112  * directly.
       
   113  */
       
   114 public class KDC {
       
   115 
       
   116     // Under the hood.
       
   117 
       
   118     // The random generator to generate random keys (including session keys)
       
   119     private static SecureRandom secureRandom = new SecureRandom();
       
   120     // Principal db
       
   121     private Map<String,char[]> passwords = new HashMap<String,char[]>();
       
   122     // Realm name
       
   123     private String realm;
       
   124     // The request/response job queue
       
   125     private BlockingQueue<Job> q = new ArrayBlockingQueue<Job>(100);
       
   126     // Service port number
       
   127     private int port;
       
   128     // Options
       
   129     private Map<Option,Object> options = new HashMap<Option,Object>();
       
   130 
       
   131     /**
       
   132      * Option names, to be expanded forever.
       
   133      */
       
   134     public static enum Option {
       
   135         /**
       
   136          * Whether pre-authentication is required. Default Boolean.TRUE
       
   137          */
       
   138         PREAUTH_REQUIRED,
       
   139     };
       
   140 
       
   141     /**
       
   142      * A standalone KDC server.
       
   143      * @param args
       
   144      * @throws java.lang.Exception
       
   145      */
       
   146     public static void main(String[] args) throws Exception {
       
   147         if (args.length > 0) {
       
   148             if (args[0].equals("-help") || args[0].equals("--help")) {
       
   149                 System.out.println("Usage:");
       
   150                 System.out.println("   java " + KDC.class + "       " +
       
   151                         "Start KDC on port 8888");
       
   152                 return;
       
   153             }
       
   154         }
       
   155         KDC kdc = create("RABBIT.HOLE", 8888, false);
       
   156         kdc.addPrincipal("dummy", "bogus".toCharArray());
       
   157         kdc.addPrincipal("foo", "bar".toCharArray());
       
   158         kdc.addPrincipalRandKey("krbtgt/" + kdc.realm);
       
   159         kdc.addPrincipalRandKey("server/localhost");
       
   160         kdc.addPrincipalRandKey("backend/localhost");
       
   161     }
       
   162 
       
   163     /**
       
   164      * Creates and starts a KDC running as a daemon on a random port.
       
   165      * @param realm the realm name
       
   166      * @return the running KDC instance
       
   167      * @throws java.io.IOException for any socket creation error
       
   168      */
       
   169     public static KDC create(String realm) throws IOException {
       
   170         return create(realm, 0, true);
       
   171     }
       
   172 
       
   173     /**
       
   174      * Creates and starts a KDC server.
       
   175      * @param realm the realm name
       
   176      * @param port the TCP and UDP port to listen to. A random port will to
       
   177      *        chosen if zero.
       
   178      * @param asDaemon if true, KDC threads will be daemons. Otherwise, not.
       
   179      * @return the running KDC instance
       
   180      * @throws java.io.IOException for any socket creation error
       
   181      */
       
   182     public static KDC create(String realm, int port, boolean asDaemon) throws IOException {
       
   183         return new KDC(realm, port, asDaemon);
       
   184     }
       
   185 
       
   186     /**
       
   187      * Sets an option
       
   188      * @param key the option name
       
   189      * @param obj the value
       
   190      */
       
   191     public void setOption(Option key, Object value) {
       
   192         options.put(key, value);
       
   193     }
       
   194 
       
   195     /**
       
   196      * Write all principals' keys into a keytab file. Note that the keys for
       
   197      * the krbtgt principal for this realm will not be written.
       
   198      * <p>
       
   199      * Attention: This method references krb5.conf settings. If you need to
       
   200      * setup krb5.conf later, please call <code>Config.refresh()</code> after
       
   201      * the new setting. For example:
       
   202      * <pre>
       
   203      * kdc.writeKtab("/etc/kdc/ktab");  // Config is initialized,
       
   204      * System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf");
       
   205      * Config.refresh();
       
   206      * </pre>
       
   207      *
       
   208      * Inside this method there are 2 places krb5.conf is used:
       
   209      * <ol>
       
   210      * <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys
       
   211      * <li> (Has workaround) Creating PrincipalName
       
   212      * </ol>
       
   213      * @param tab The keytab filename to write to.
       
   214      * @throws java.io.IOException for any file output error
       
   215      * @throws sun.security.krb5.KrbException for any realm and/or principal
       
   216      *         name error.
       
   217      */
       
   218     public void writeKtab(String tab) throws IOException, KrbException {
       
   219         KeyTab ktab = KeyTab.create(tab);
       
   220         for (String name : passwords.keySet()) {
       
   221             if (name.equals("krbtgt/" + realm)) {
       
   222                 continue;
       
   223             }
       
   224             ktab.addEntry(new PrincipalName(name + "@" + realm,
       
   225                     name.indexOf('/') < 0 ?
       
   226                         PrincipalName.KRB_NT_UNKNOWN :
       
   227                         PrincipalName.KRB_NT_SRV_HST), passwords.get(name));
       
   228         }
       
   229         ktab.save();
       
   230     }
       
   231 
       
   232     /**
       
   233      * Adds a new principal to this realm with a given password.
       
   234      * @param user the principal's name. For a service principal, use the
       
   235      *        form of host/f.q.d.n
       
   236      * @param pass the password for the principal
       
   237      */
       
   238     public void addPrincipal(String user, char[] pass) {
       
   239         passwords.put(user, pass);
       
   240     }
       
   241 
       
   242     /**
       
   243      * Adds a new principal to this realm with a random password
       
   244      * @param user the principal's name. For a service principal, use the
       
   245      *        form of host/f.q.d.n
       
   246      */
       
   247     public void addPrincipalRandKey(String user) {
       
   248         passwords.put(user, randomPassword());
       
   249     }
       
   250 
       
   251     /**
       
   252      * Returns the name of this realm
       
   253      * @return the name of this realm
       
   254      */
       
   255     public String getRealm() {
       
   256         return realm;
       
   257     }
       
   258 
       
   259     /**
       
   260      * Writes a krb5.conf for one or more KDC that includes KDC locations for
       
   261      * each realm and the default realm name. You can also add extra strings
       
   262      * into the file. The method should be called like:
       
   263      * <pre>
       
   264      *   KDC.saveConfig("krb5.conf", kdc1, kdc2, ..., line1, line2, ...);
       
   265      * </pre>
       
   266      * Here you can provide one or more kdc# and zero or more line# arguments.
       
   267      * The line# will be put after [libdefaults] and before [realms]. Therefore
       
   268      * you can append new lines into [libdefaults] and/or create your new
       
   269      * stanzas as well. Note that a newline character will be appended to
       
   270      * each line# argument.
       
   271      * <p>
       
   272      * For example:
       
   273      * <pre>
       
   274      * KDC.saveConfig("krb5.conf", this);
       
   275      * </pre>
       
   276      * generates:
       
   277      * <pre>
       
   278      * [libdefaults]
       
   279      * default_realm = REALM.NAME
       
   280      *
       
   281      * [realms]
       
   282      *   REALM.NAME = {
       
   283      *     kdc = localhost:port_number
       
   284      *   }
       
   285      * </pre>
       
   286      *
       
   287      * Another example:
       
   288      * <pre>
       
   289      * KDC.saveConfig("krb5.conf", kdc1, kdc2, "forwardable = true", "",
       
   290      *         "[domain_realm]",
       
   291      *         ".kdc1.com = KDC1.NAME");
       
   292      * </pre>
       
   293      * generates:
       
   294      * <pre>
       
   295      * [libdefaults]
       
   296      * default_realm = KDC1.NAME
       
   297      * forwardable = true
       
   298      *
       
   299      * [domain_realm]
       
   300      * .kdc1.com = KDC1.NAME
       
   301      *
       
   302      * [realms]
       
   303      *   KDC1.NAME = {
       
   304      *     kdc = localhost:port1
       
   305      *   }
       
   306      *   KDC2.NAME = {
       
   307      *     kdc = localhost:port2
       
   308      *   }
       
   309      * </pre>
       
   310      * @param file the name of the file to write into
       
   311      * @param kdc the first (and default) KDC
       
   312      * @param more more KDCs or extra lines (in their appearing order) to
       
   313      * insert into the krb5.conf file. This method reads each argument's type
       
   314      * to determine what it's for. This argument can be empty.
       
   315      * @throws java.io.IOException for any file output error
       
   316      */
       
   317     public static void saveConfig(String file, KDC kdc, Object... more)
       
   318             throws IOException {
       
   319         File f = new File(file);
       
   320         StringBuffer sb = new StringBuffer();
       
   321         sb.append("[libdefaults]\ndefault_realm = ");
       
   322         sb.append(kdc.realm);
       
   323         sb.append("\n");
       
   324         for (Object o: more) {
       
   325             if (o instanceof String) {
       
   326                 sb.append(o);
       
   327                 sb.append("\n");
       
   328             }
       
   329         }
       
   330         sb.append("\n[realms]\n");
       
   331         sb.append(realmLineForKDC(kdc));
       
   332         for (Object o: more) {
       
   333             if (o instanceof KDC) {
       
   334                 sb.append(realmLineForKDC((KDC)o));
       
   335             }
       
   336         }
       
   337         FileOutputStream fos = new FileOutputStream(f);
       
   338         fos.write(sb.toString().getBytes());
       
   339         fos.close();
       
   340     }
       
   341 
       
   342     /**
       
   343      * Returns the service port of the KDC server.
       
   344      * @return the KDC service port
       
   345      */
       
   346     public int getPort() {
       
   347         return port;
       
   348     }
       
   349 
       
   350     // Private helper methods
       
   351 
       
   352     /**
       
   353      * Private constructor, cannot be called outside.
       
   354      * @param realm
       
   355      */
       
   356     private KDC(String realm) {
       
   357         this.realm = realm;
       
   358     }
       
   359 
       
   360     /**
       
   361      * A constructor that starts the KDC service also.
       
   362      */
       
   363     protected KDC(String realm, int port, boolean asDaemon)
       
   364             throws IOException {
       
   365         this(realm);
       
   366         startServer(port, asDaemon);
       
   367     }
       
   368     /**
       
   369      * Generates a 32-char random password
       
   370      * @return the password
       
   371      */
       
   372     private static char[] randomPassword() {
       
   373         char[] pass = new char[32];
       
   374         for (int i=0; i<32; i++)
       
   375             pass[i] = (char)secureRandom.nextInt();
       
   376         return pass;
       
   377     }
       
   378 
       
   379     /**
       
   380      * Generates a random key for the given encryption type.
       
   381      * @param eType the encryption type
       
   382      * @return the generated key
       
   383      * @throws sun.security.krb5.KrbException for unknown/unsupported etype
       
   384      */
       
   385     private static EncryptionKey generateRandomKey(int eType)
       
   386             throws KrbException  {
       
   387         // Is 32 enough for AES256? I should have generated the keys directly
       
   388         // but different cryptos have different rules on what keys are valid.
       
   389         char[] pass = randomPassword();
       
   390         String algo;
       
   391         switch (eType) {
       
   392             case EncryptedData.ETYPE_DES_CBC_MD5: algo = "DES"; break;
       
   393             case EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD: algo = "DESede"; break;
       
   394             case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96: algo = "AES128"; break;
       
   395             case EncryptedData.ETYPE_ARCFOUR_HMAC: algo = "ArcFourHMAC"; break;
       
   396             case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96: algo = "AES256"; break;
       
   397             default: algo = "DES"; break;
       
   398         }
       
   399         return new EncryptionKey(pass, "NOTHING", algo);    // Silly
       
   400     }
       
   401 
       
   402     /**
       
   403      * Returns the password for a given principal
       
   404      * @param p principal
       
   405      * @return the password
       
   406      * @throws sun.security.krb5.KrbException when the principal is not inside
       
   407      *         the database.
       
   408      */
       
   409     private char[] getPassword(PrincipalName p) throws KrbException {
       
   410         char[] pass = passwords.get(p.getNameString());
       
   411         if (pass == null) {
       
   412             throw new KrbException(Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN);
       
   413         }
       
   414         return pass;
       
   415     }
       
   416 
       
   417     /**
       
   418      * Returns the salt string for the principal. For normal users, the
       
   419      * concatenation for the realm name and the sections of the principal;
       
   420      * for krgtgt/A@B and krbtgt/B@A, always return AB (so that inter-realm
       
   421      * principals have the same key).
       
   422      * @param p principal
       
   423      * @return the salt
       
   424      */
       
   425     private String getSalt(PrincipalName p) {
       
   426         String[] ns = p.getNameStrings();
       
   427         if (ns[0].equals("krbtgt") && ns.length > 1) {
       
   428             // Shared cross-realm keys must be the same
       
   429             if (ns[1].compareTo(realm) < 0) {
       
   430                 return ns[1] + realm;
       
   431             } else {
       
   432                 return realm + ns[1];
       
   433             }
       
   434         } else {
       
   435             String s = getRealm();
       
   436             for (String n: p.getNameStrings()) {
       
   437                 s += n;
       
   438             }
       
   439             return s;
       
   440         }
       
   441     }
       
   442 
       
   443     /**
       
   444      * Returns the key for a given principal of the given encryption type
       
   445      * @param p the principal
       
   446      * @param etype the encryption type
       
   447      * @return the key
       
   448      * @throws sun.security.krb5.KrbException for unknown/unsupported etype
       
   449      */
       
   450     private EncryptionKey keyForUser(PrincipalName p, int etype) throws KrbException {
       
   451         try {
       
   452             // Do not call EncryptionKey.acquireSecretKeys(), otherwise
       
   453             // the krb5.conf config file would be loaded.
       
   454             Method stringToKey = EncryptionKey.class.getDeclaredMethod("stringToKey", char[].class, String.class, byte[].class, Integer.TYPE);
       
   455             stringToKey.setAccessible(true);
       
   456             return new EncryptionKey((byte[]) stringToKey.invoke(null, getPassword(p), getSalt(p), null, etype), etype, null);
       
   457         } catch (InvocationTargetException ex) {
       
   458             KrbException ke = (KrbException)ex.getCause();
       
   459             throw ke;
       
   460         } catch (Exception e) {
       
   461             throw new RuntimeException(e);  // should not happen
       
   462         }
       
   463     }
       
   464 
       
   465     /**
       
   466      * Processes an incoming request and generates a response.
       
   467      * @param in the request
       
   468      * @return the response
       
   469      * @throws java.lang.Exception for various errors
       
   470      */
       
   471     private byte[] processMessage(byte[] in) throws Exception {
       
   472         if ((in[0] & 0x1f) == Krb5.KRB_AS_REQ)
       
   473             return processAsReq(in);
       
   474         else
       
   475             return processTgsReq(in);
       
   476     }
       
   477 
       
   478     /**
       
   479      * Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR)
       
   480      * @param in the request
       
   481      * @return the response
       
   482      * @throws java.lang.Exception for various errors
       
   483      */
       
   484     private byte[] processTgsReq(byte[] in) throws Exception {
       
   485         TGSReq tgsReq = new TGSReq(in);
       
   486         try {
       
   487             System.out.println(realm + "> " + tgsReq.reqBody.cname +
       
   488                     " sends TGS-REQ for " +
       
   489                     tgsReq.reqBody.sname);
       
   490             KDCReqBody body = tgsReq.reqBody;
       
   491             int etype = 0;
       
   492 
       
   493             // Reflection: PAData[] pas = tgsReq.pAData;
       
   494             Field f = KDCReq.class.getDeclaredField("pAData");
       
   495             f.setAccessible(true);
       
   496             PAData[] pas = (PAData[])f.get(tgsReq);
       
   497 
       
   498             Ticket tkt = null;
       
   499             EncTicketPart etp = null;
       
   500             if (pas == null || pas.length == 0) {
       
   501                 throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
       
   502             } else {
       
   503                 for (PAData pa: pas) {
       
   504                     if (pa.getType() == Krb5.PA_TGS_REQ) {
       
   505                         APReq apReq = new APReq(pa.getValue());
       
   506                         EncryptedData ed = apReq.authenticator;
       
   507                         tkt = apReq.ticket;
       
   508                         etype = tkt.encPart.getEType();
       
   509                         EncryptionKey kkey = null;
       
   510                         if (!tkt.realm.toString().equals(realm)) {
       
   511                             if (tkt.sname.getNameString().equals("krbtgt/" + realm)) {
       
   512                                 kkey = keyForUser(new PrincipalName("krbtgt/" + tkt.realm.toString(), realm), etype);
       
   513                             }
       
   514                         } else {
       
   515                             kkey = keyForUser(tkt.sname, etype);
       
   516                         }
       
   517                         byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET);
       
   518                         DerInputStream derIn = new DerInputStream(bb);
       
   519                         DerValue der = derIn.getDerValue();
       
   520                         etp = new EncTicketPart(der.toByteArray());
       
   521                     }
       
   522                 }
       
   523                 if (tkt == null) {
       
   524                     throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
       
   525                 }
       
   526             }
       
   527             EncryptionKey skey = keyForUser(body.sname, etype);
       
   528             if (skey == null) {
       
   529                 throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
       
   530             }
       
   531 
       
   532             // Session key for original ticket, TGT
       
   533             EncryptionKey ckey = etp.key;
       
   534 
       
   535             // Session key for session with the service
       
   536             EncryptionKey key = generateRandomKey(etype);
       
   537 
       
   538             // Check time, TODO
       
   539             KerberosTime till = body.till;
       
   540             if (till == null) {
       
   541                 throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
       
   542             } else if (till.isZero()) {
       
   543                 till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11);
       
   544             }
       
   545 
       
   546             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
       
   547             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
       
   548                 bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
       
   549             }
       
   550             if (body.kdcOptions.get(KDCOptions.FORWARDED) ||
       
   551                     etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {
       
   552                 bFlags[Krb5.TKT_OPTS_FORWARDED] = true;
       
   553             }
       
   554             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
       
   555                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
       
   556                 //renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7);
       
   557             }
       
   558             if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
       
   559                 bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
       
   560             }
       
   561             if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
       
   562                 bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
       
   563             }
       
   564             if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
       
   565                 bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
       
   566             }
       
   567             bFlags[Krb5.TKT_OPTS_INITIAL] = true;
       
   568 
       
   569             TicketFlags tFlags = new TicketFlags(bFlags);
       
   570             EncTicketPart enc = new EncTicketPart(
       
   571                     tFlags,
       
   572                     key,
       
   573                     etp.crealm,
       
   574                     etp.cname,
       
   575                     new TransitedEncoding(1, new byte[0]),  // TODO
       
   576                     new KerberosTime(new Date()),
       
   577                     body.from,
       
   578                     till, body.rtime,
       
   579                     body.addresses,
       
   580                     null);
       
   581             Ticket t = new Ticket(
       
   582                     body.crealm,
       
   583                     body.sname,
       
   584                     new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
       
   585             );
       
   586             EncTGSRepPart enc_part = new EncTGSRepPart(
       
   587                     key,
       
   588                     new LastReq(new LastReqEntry[]{
       
   589                         new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000))
       
   590                     }),
       
   591                     body.getNonce(),    // TODO: detect replay
       
   592                     new KerberosTime(new Date().getTime() + 1000 * 3600 * 24),
       
   593                     // Next 5 and last MUST be same with ticket
       
   594                     tFlags,
       
   595                     new KerberosTime(new Date()),
       
   596                     body.from,
       
   597                     till, body.rtime,
       
   598                     body.crealm,
       
   599                     body.sname,
       
   600                     body.addresses
       
   601                     );
       
   602             EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY);
       
   603             TGSRep tgsRep = new TGSRep(null,
       
   604                     etp.crealm,
       
   605                     etp.cname,
       
   606                     t,
       
   607                     edata);
       
   608             System.out.println("     Return " + tgsRep.cname
       
   609                     + " ticket for " + tgsRep.ticket.sname);
       
   610 
       
   611             DerOutputStream out = new DerOutputStream();
       
   612             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
       
   613                     true, (byte)Krb5.KRB_TGS_REP), tgsRep.asn1Encode());
       
   614             return out.toByteArray();
       
   615         } catch (KrbException ke) {
       
   616             ke.printStackTrace(System.out);
       
   617             KRBError kerr = ke.getError();
       
   618             KDCReqBody body = tgsReq.reqBody;
       
   619             System.out.println("     Error " + ke.returnCode()
       
   620                     + " " +ke.returnCodeMessage());
       
   621             if (kerr == null) {
       
   622                 kerr = new KRBError(null, null, null,
       
   623                         new KerberosTime(new Date()),
       
   624                         0,
       
   625                         ke.returnCode(),
       
   626                         body.crealm, body.cname,
       
   627                         new Realm(getRealm()), body.sname,
       
   628                         KrbException.errorMessage(ke.returnCode()),
       
   629                         null);
       
   630             }
       
   631             return kerr.asn1Encode();
       
   632         }
       
   633     }
       
   634 
       
   635     /**
       
   636      * Processes a AS_REQ and generates a AS_REP (or KRB_ERROR)
       
   637      * @param in the request
       
   638      * @return the response
       
   639      * @throws java.lang.Exception for various errors
       
   640      */
       
   641     private byte[] processAsReq(byte[] in) throws Exception {
       
   642         ASReq asReq = new ASReq(in);
       
   643         int[] eTypes = null;
       
   644         try {
       
   645             System.out.println(realm + "> " + asReq.reqBody.cname +
       
   646                     " sends AS-REQ for " +
       
   647                     asReq.reqBody.sname);
       
   648 
       
   649             KDCReqBody body = asReq.reqBody;
       
   650 
       
   651             // Reflection: int[] eType = body.eType;
       
   652             Field f = KDCReqBody.class.getDeclaredField("eType");
       
   653             f.setAccessible(true);
       
   654             eTypes = (int[])f.get(body);
       
   655             int eType = eTypes[0];
       
   656 
       
   657             EncryptionKey ckey = keyForUser(body.cname, eType);
       
   658             EncryptionKey skey = keyForUser(body.sname, eType);
       
   659             if (ckey == null) {
       
   660                 throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
       
   661             }
       
   662             if (skey == null) {
       
   663                 throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
       
   664             }
       
   665 
       
   666             // Session key
       
   667             EncryptionKey key = generateRandomKey(eType);
       
   668             // Check time, TODO
       
   669             KerberosTime till = body.till;
       
   670             if (till == null) {
       
   671                 throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
       
   672             } else if (till.isZero()) {
       
   673                 till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11);
       
   674             }
       
   675             //body.from
       
   676             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
       
   677             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
       
   678                 bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
       
   679             }
       
   680             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
       
   681                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
       
   682                 //renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7);
       
   683             }
       
   684             if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
       
   685                 bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
       
   686             }
       
   687             if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
       
   688                 bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
       
   689             }
       
   690             if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
       
   691                 bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
       
   692             }
       
   693             bFlags[Krb5.TKT_OPTS_INITIAL] = true;
       
   694 
       
   695             f = KDCReq.class.getDeclaredField("pAData");
       
   696             f.setAccessible(true);
       
   697             PAData[] pas = (PAData[])f.get(asReq);
       
   698             if (pas == null || pas.length == 0) {
       
   699                 Object preauth = options.get(Option.PREAUTH_REQUIRED);
       
   700                 if (preauth == null || preauth.equals(Boolean.TRUE)) {
       
   701                     throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED);
       
   702                 }
       
   703             } else {
       
   704                 try {
       
   705                     Constructor<EncryptedData> ctor = EncryptedData.class.getDeclaredConstructor(DerValue.class);
       
   706                     ctor.setAccessible(true);
       
   707                     EncryptedData data = ctor.newInstance(new DerValue(pas[0].getValue()));
       
   708                     data.decrypt(ckey, KeyUsage.KU_PA_ENC_TS);
       
   709                 } catch (Exception e) {
       
   710                     throw new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED);
       
   711                 }
       
   712                 bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true;
       
   713             }
       
   714 
       
   715             TicketFlags tFlags = new TicketFlags(bFlags);
       
   716             EncTicketPart enc = new EncTicketPart(
       
   717                     tFlags,
       
   718                     key,
       
   719                     body.crealm,
       
   720                     body.cname,
       
   721                     new TransitedEncoding(1, new byte[0]),
       
   722                     new KerberosTime(new Date()),
       
   723                     body.from,
       
   724                     till, body.rtime,
       
   725                     body.addresses,
       
   726                     null);
       
   727             Ticket t = new Ticket(
       
   728                     body.crealm,
       
   729                     body.sname,
       
   730                     new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
       
   731             );
       
   732             EncASRepPart enc_part = new EncASRepPart(
       
   733                     key,
       
   734                     new LastReq(new LastReqEntry[]{
       
   735                         new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000))
       
   736                     }),
       
   737                     body.getNonce(),    // TODO: detect replay?
       
   738                     new KerberosTime(new Date().getTime() + 1000 * 3600 * 24),
       
   739                     // Next 5 and last MUST be same with ticket
       
   740                     tFlags,
       
   741                     new KerberosTime(new Date()),
       
   742                     body.from,
       
   743                     till, body.rtime,
       
   744                     body.crealm,
       
   745                     body.sname,
       
   746                     body.addresses
       
   747                     );
       
   748             EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_AS_REP_PART);
       
   749             ASRep asRep = new ASRep(null,
       
   750                     body.crealm,
       
   751                     body.cname,
       
   752                     t,
       
   753                     edata);
       
   754 
       
   755             System.out.println("     Return " + asRep.cname
       
   756                     + " ticket for " + asRep.ticket.sname);
       
   757 
       
   758             DerOutputStream out = new DerOutputStream();
       
   759             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
       
   760                     true, (byte)Krb5.KRB_AS_REP), asRep.asn1Encode());
       
   761             return out.toByteArray();
       
   762         } catch (KrbException ke) {
       
   763             ke.printStackTrace(System.out);
       
   764             KRBError kerr = ke.getError();
       
   765             KDCReqBody body = asReq.reqBody;
       
   766             System.out.println("     Error " + ke.returnCode()
       
   767                     + " " +ke.returnCodeMessage());
       
   768             byte[] eData = null;
       
   769             if (kerr == null) {
       
   770                 if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED ||
       
   771                         ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) {
       
   772                     PAData pa;
       
   773 
       
   774                     ETypeInfo2 ei2 = new ETypeInfo2(eTypes[0], null, null);
       
   775                     DerOutputStream eid = new DerOutputStream();
       
   776                     eid.write(DerValue.tag_Sequence, ei2.asn1Encode());
       
   777 
       
   778                     pa = new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray());
       
   779 
       
   780                     DerOutputStream bytes = new DerOutputStream();
       
   781                     bytes.write(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]).asn1Encode());
       
   782                     bytes.write(pa.asn1Encode());
       
   783 
       
   784                     boolean allOld = true;
       
   785                     for (int i: eTypes) {
       
   786                         if (i == EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 ||
       
   787                                 i == EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96) {
       
   788                             allOld = false;
       
   789                             break;
       
   790                         }
       
   791                     }
       
   792                     if (allOld) {
       
   793                         ETypeInfo ei = new ETypeInfo(eTypes[0], null);
       
   794                         eid = new DerOutputStream();
       
   795                         eid.write(DerValue.tag_Sequence, ei.asn1Encode());
       
   796                         pa = new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray());
       
   797                         bytes.write(pa.asn1Encode());
       
   798                     }
       
   799                     DerOutputStream temp = new DerOutputStream();
       
   800                     temp.write(DerValue.tag_Sequence, bytes);
       
   801                     eData = temp.toByteArray();
       
   802                 }
       
   803                 kerr = new KRBError(null, null, null,
       
   804                         new KerberosTime(new Date()),
       
   805                         0,
       
   806                         ke.returnCode(),
       
   807                         body.crealm, body.cname,
       
   808                         new Realm(getRealm()), body.sname,
       
   809                         KrbException.errorMessage(ke.returnCode()),
       
   810                         eData);
       
   811             }
       
   812             return kerr.asn1Encode();
       
   813         }
       
   814     }
       
   815 
       
   816     /**
       
   817      * Generates a line for a KDC to put inside [realms] of krb5.conf
       
   818      * @param kdc the KDC
       
   819      * @return REALM.NAME = { kdc = localhost:port }
       
   820      */
       
   821     private static String realmLineForKDC(KDC kdc) {
       
   822         return String.format("  %s = {\n    kdc = localhost:%d\n  }\n", kdc.realm, kdc.port);
       
   823     }
       
   824 
       
   825     /**
       
   826      * Start the KDC service. This server listens on both UDP and TCP using
       
   827      * the same port number. It uses three threads to deal with requests.
       
   828      * They can be set to daemon threads if requested.
       
   829      * @param port the port number to listen to. If zero, a random available
       
   830      *  port no less than 8000 will be chosen and used.
       
   831      * @param asDaemon true if the KDC threads should be daemons
       
   832      * @throws java.io.IOException for any communication error
       
   833      */
       
   834     protected void startServer(int port, boolean asDaemon) throws IOException {
       
   835         DatagramSocket u1 = null;
       
   836         ServerSocket t1 = null;
       
   837         if (port > 0) {
       
   838             u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
       
   839             t1 = new ServerSocket(port);
       
   840         } else {
       
   841             while (true) {
       
   842                 // Try to find a port number that's both TCP and UDP free
       
   843                 try {
       
   844                     port = 8000 + new java.util.Random().nextInt(10000);
       
   845                     u1 = null;
       
   846                     u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
       
   847                     t1 = new ServerSocket(port);
       
   848                     break;
       
   849                 } catch (Exception e) {
       
   850                     if (u1 != null) u1.close();
       
   851                 }
       
   852             }
       
   853         }
       
   854         final DatagramSocket udp = u1;
       
   855         final ServerSocket tcp = t1;
       
   856         System.out.println("Start KDC on " + port);
       
   857 
       
   858         this.port = port;
       
   859 
       
   860         // The UDP consumer
       
   861         Thread thread = new Thread() {
       
   862             public void run() {
       
   863                 while (true) {
       
   864                     try {
       
   865                         byte[] inbuf = new byte[8192];
       
   866                         DatagramPacket p = new DatagramPacket(inbuf, inbuf.length);
       
   867                         udp.receive(p);
       
   868                         System.out.println("-----------------------------------------------");
       
   869                         System.out.println(">>>>> UDP packet received");
       
   870                         q.put(new Job(processMessage(Arrays.copyOf(inbuf, p.getLength())), udp, p));
       
   871                     } catch (Exception e) {
       
   872                         e.printStackTrace();
       
   873                     }
       
   874                 }
       
   875             }
       
   876         };
       
   877         thread.setDaemon(asDaemon);
       
   878         thread.start();
       
   879 
       
   880         // The TCP consumer
       
   881         thread = new Thread() {
       
   882             public void run() {
       
   883                 while (true) {
       
   884                     try {
       
   885                         Socket socket = tcp.accept();
       
   886                         System.out.println("-----------------------------------------------");
       
   887                         System.out.println(">>>>> TCP connection established");
       
   888                         DataInputStream in = new DataInputStream(socket.getInputStream());
       
   889                         DataOutputStream out = new DataOutputStream(socket.getOutputStream());
       
   890                         byte[] token = new byte[in.readInt()];
       
   891                         in.readFully(token);
       
   892                         q.put(new Job(processMessage(token), socket, out));
       
   893                     } catch (Exception e) {
       
   894                         e.printStackTrace();
       
   895                     }
       
   896                 }
       
   897             }
       
   898         };
       
   899         thread.setDaemon(asDaemon);
       
   900         thread.start();
       
   901 
       
   902         // The dispatcher
       
   903         thread = new Thread() {
       
   904             public void run() {
       
   905                 while (true) {
       
   906                     try {
       
   907                         q.take().send();
       
   908                     } catch (Exception e) {
       
   909                     }
       
   910                 }
       
   911             }
       
   912         };
       
   913         thread.setDaemon(true);
       
   914         thread.start();
       
   915     }
       
   916 
       
   917     /**
       
   918      * Helper class to encapsulate a job in a KDC.
       
   919      */
       
   920     private static class Job {
       
   921         byte[] token;           // The received request at creation time and
       
   922                                 // the response at send time
       
   923         Socket s;               // The TCP socket from where the request comes
       
   924         DataOutputStream out;   // The OutputStream of the TCP socket
       
   925         DatagramSocket s2;      // The UDP socket from where the request comes
       
   926         DatagramPacket dp;      // The incoming UDP datagram packet
       
   927         boolean useTCP;         // Whether TCP or UDP is used
       
   928 
       
   929         // Creates a job object for TCP
       
   930         Job(byte[] token, Socket s, DataOutputStream out) {
       
   931             useTCP = true;
       
   932             this.token = token;
       
   933             this.s = s;
       
   934             this.out = out;
       
   935         }
       
   936 
       
   937         // Creates a job object for UDP
       
   938         Job(byte[] token, DatagramSocket s2, DatagramPacket dp) {
       
   939             useTCP = false;
       
   940             this.token = token;
       
   941             this.s2 = s2;
       
   942             this.dp = dp;
       
   943         }
       
   944 
       
   945         // Sends the output back to the client
       
   946         void send() {
       
   947             try {
       
   948                 if (useTCP) {
       
   949                     System.out.println(">>>>> TCP request honored");
       
   950                     out.writeInt(token.length);
       
   951                     out.write(token);
       
   952                     s.close();
       
   953                 } else {
       
   954                     System.out.println(">>>>> UDP request honored");
       
   955                     s2.send(new DatagramPacket(token, token.length, dp.getAddress(), dp.getPort()));
       
   956                 }
       
   957             } catch (Exception e) {
       
   958                 e.printStackTrace();
       
   959             }
       
   960         }
       
   961     }
       
   962 }