1 /*
   2  * Copyright (c) 2008, 2013, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * 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.net.spi.nameservice.NameService;
  34 import sun.net.spi.nameservice.NameServiceDescriptor;
  35 import sun.security.krb5.*;
  36 import sun.security.krb5.internal.*;
  37 import sun.security.krb5.internal.ccache.CredentialsCache;
  38 import sun.security.krb5.internal.crypto.EType;
  39 import sun.security.krb5.internal.crypto.KeyUsage;
  40 import sun.security.krb5.internal.ktab.KeyTab;
  41 import sun.security.util.DerInputStream;
  42 import sun.security.util.DerOutputStream;
  43 import sun.security.util.DerValue;
  44 
  45 /**
  46  * A KDC server.
  47  * <p>
  48  * Features:
  49  * <ol>
  50  * <li> Supports TCP and UDP
  51  * <li> Supports AS-REQ and TGS-REQ
  52  * <li> Principal db and other settings hard coded in application
  53  * <li> Options, say, request preauth or not
  54  * </ol>
  55  * Side effects:
  56  * <ol>
  57  * <li> The Sun-internal class <code>sun.security.krb5.Config</code> is a
  58  * singleton and initialized according to Kerberos settings (krb5.conf and
  59  * java.security.krb5.* system properties). This means once it's initialized
  60  * it will not automatically notice any changes to these settings (or file
  61  * changes of krb5.conf). The KDC class normally does not touch these
  62  * settings (except for the <code>writeKtab()</code> method). However, to make
  63  * sure nothing ever goes wrong, if you want to make any changes to these
  64  * settings after calling a KDC method, call <code>Config.refresh()</code> to
  65  * make sure your changes are reflected in the <code>Config</code> object.
  66  * </ol>
  67  * System properties recognized:
  68  * <ul>
  69  * <li>test.kdc.save.ccache
  70  * </ul>
  71  * Issues and TODOs:
  72  * <ol>
  73  * <li> Generates krb5.conf to be used on another machine, currently the kdc is
  74  * always localhost
  75  * <li> More options to KDC, say, error output, say, response nonce !=
  76  * request nonce
  77  * </ol>
  78  * Note: This program uses internal krb5 classes (including reflection to
  79  * access private fields and methods).
  80  * <p>
  81  * Usages:
  82  * <p>
  83  * 1. Init and start the KDC:
  84  * <pre>
  85  * KDC kdc = KDC.create("REALM.NAME", port, isDaemon);
  86  * KDC kdc = KDC.create("REALM.NAME");
  87  * </pre>
  88  * Here, <code>port</code> is the UDP and TCP port number the KDC server
  89  * listens on. If zero, a random port is chosen, which you can use getPort()
  90  * later to retrieve the value.
  91  * <p>
  92  * If <code>isDaemon</code> is true, the KDC worker threads will be daemons.
  93  * <p>
  94  * The shortcut <code>KDC.create("REALM.NAME")</code> has port=0 and
  95  * isDaemon=false, and is commonly used in an embedded KDC.
  96  * <p>
  97  * 2. Adding users:
  98  * <pre>
  99  * kdc.addPrincipal(String principal_name, char[] password);
 100  * kdc.addPrincipalRandKey(String principal_name);
 101  * </pre>
 102  * A service principal's name should look like "host/f.q.d.n". The second form
 103  * generates a random key. To expose this key, call <code>writeKtab()</code> to
 104  * save the keys into a keytab file.
 105  * <p>
 106  * Note that you need to add the principal name krbtgt/REALM.NAME yourself.
 107  * <p>
 108  * Note that you can safely add a principal at any time after the KDC is
 109  * started and before a user requests info on this principal.
 110  * <p>
 111  * 3. Other public methods:
 112  * <ul>
 113  * <li> <code>getPort</code>: Returns the port number the KDC uses
 114  * <li> <code>getRealm</code>: Returns the realm name
 115  * <li> <code>writeKtab</code>: Writes all principals' keys into a keytab file
 116  * <li> <code>saveConfig</code>: Saves a krb5.conf file to access this KDC
 117  * <li> <code>setOption</code>: Sets various options
 118  * </ul>
 119  * Read the javadoc for details. Lazy developer can use <code>OneKDC</code>
 120  * directly.
 121  */
 122 public class KDC {
 123 
 124     public static final int DEFAULT_LIFETIME = 39600;
 125     public static final int DEFAULT_RENEWTIME = 86400;
 126 
 127     // Under the hood.
 128 
 129     // The random generator to generate random keys (including session keys)
 130     private static SecureRandom secureRandom = new SecureRandom();
 131 
 132     // Principal db. principal -> pass. A case-insensitive TreeMap is used
 133     // so that even if the client provides a name with different case, the KDC
 134     // can still locate the principal and give back correct salt.
 135     private TreeMap<String,char[]> passwords = new TreeMap<>
 136             (String.CASE_INSENSITIVE_ORDER);
 137 
 138     // Realm name
 139     private String realm;
 140     // KDC
 141     private String kdc;
 142     // Service port number
 143     private int port;
 144     // The request/response job queue
 145     private BlockingQueue<Job> q = new ArrayBlockingQueue<>(100);
 146     // Options
 147     private Map<Option,Object> options = new HashMap<>();
 148     // Realm-specific krb5.conf settings
 149     private List<String> conf = new ArrayList<>();
 150 
 151     private Thread thread1, thread2, thread3;
 152     DatagramSocket u1 = null;
 153     ServerSocket t1 = null;
 154 
 155     /**
 156      * Option names, to be expanded forever.
 157      */
 158     public static enum Option {
 159         /**
 160          * Whether pre-authentication is required. Default Boolean.TRUE
 161          */
 162         PREAUTH_REQUIRED,
 163         /**
 164          * Only issue TGT in RC4
 165          */
 166         ONLY_RC4_TGT,
 167         /**
 168          * Use RC4 as the first in preauth
 169          */
 170         RC4_FIRST_PREAUTH,
 171         /**
 172          * Use only one preauth, so that some keys are not easy to generate
 173          */
 174         ONLY_ONE_PREAUTH,
 175         /**
 176          * Set all name-type to a value in response
 177          */
 178         RESP_NT,
 179         /**
 180          * Multiple ETYPE-INFO-ENTRY with same etype but different salt
 181          */
 182         DUP_ETYPE,
 183         /**
 184          * What backend server can be delegated to
 185          */
 186         OK_AS_DELEGATE,
 187         /**
 188          * Allow S4U2self, List<String> of middle servers.
 189          * If not set, means KDC does not understand S4U2self at all, therefore
 190          * would ignore any PA-FOR-USER request and send a ticket using the
 191          * cname of teh requestor. If set, it returns FORWARDABLE tickets to
 192          * a server with its name in the list
 193          */
 194         ALLOW_S4U2SELF,
 195         /**
 196          * Allow S4U2proxy, Map<String,List<String>> of middle servers to
 197          * backends. If not set or a backend not in a server's list,
 198          * Krb5.KDC_ERR_POLICY will be send for S4U2proxy request.
 199          */
 200         ALLOW_S4U2PROXY,
 201         /**
 202          * Sensitive accounts can never be delegated.
 203          */
 204         SENSITIVE_ACCOUNTS,
 205     };
 206 
 207     static {
 208         System.setProperty("sun.net.spi.nameservice.provider.1", "ns,mock");
 209     }
 210 
 211     /**
 212      * A standalone KDC server.
 213      */
 214     public static void main(String[] args) throws Exception {
 215         int port = args.length > 0 ? Integer.parseInt(args[0]) : 0;
 216         KDC kdc = create("RABBIT.HOLE", "kdc.rabbit.hole", port, false);
 217         kdc.addPrincipal("dummy", "bogus".toCharArray());
 218         kdc.addPrincipal("foo", "bar".toCharArray());
 219         kdc.addPrincipalRandKey("krbtgt/RABBIT.HOLE");
 220         kdc.addPrincipalRandKey("server/host.rabbit.hole");
 221         kdc.addPrincipalRandKey("backend/host.rabbit.hole");
 222         KDC.saveConfig("krb5.conf", kdc, "forwardable = true");
 223     }
 224 
 225     /**
 226      * Creates and starts a KDC running as a daemon on a random port.
 227      * @param realm the realm name
 228      * @return the running KDC instance
 229      * @throws java.io.IOException for any socket creation error
 230      */
 231     public static KDC create(String realm) throws IOException {
 232         return create(realm, "kdc." + realm.toLowerCase(), 0, true);
 233     }
 234 
 235     public static KDC existing(String realm, String kdc, int port) {
 236         KDC k = new KDC(realm, kdc);
 237         k.port = port;
 238         return k;
 239     }
 240 
 241     /**
 242      * Creates and starts a KDC server.
 243      * @param realm the realm name
 244      * @param port the TCP and UDP port to listen to. A random port will to
 245      *        chosen if zero.
 246      * @param asDaemon if true, KDC threads will be daemons. Otherwise, not.
 247      * @return the running KDC instance
 248      * @throws java.io.IOException for any socket creation error
 249      */
 250     public static KDC create(String realm, String kdc, int port, boolean asDaemon) throws IOException {
 251         return new KDC(realm, kdc, port, asDaemon);
 252     }
 253 
 254     /**
 255      * Sets an option
 256      * @param key the option name
 257      * @param value the value
 258      */
 259     public void setOption(Option key, Object value) {
 260         if (value == null) {
 261             options.remove(key);
 262         } else {
 263             options.put(key, value);
 264         }
 265     }
 266 
 267     /**
 268      * Writes or appends keys into a keytab.
 269      * <p>
 270      * Attention: This is the most basic one of a series of methods below on
 271      * keytab creation or modification. All these methods reference krb5.conf
 272      * settings. If you need to modify krb5.conf or switch to another krb5.conf
 273      * later, please call <code>Config.refresh()</code> again. For example:
 274      * <pre>
 275      * kdc.writeKtab("/etc/kdc/ktab", true);  // Config is initialized,
 276      * System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf");
 277      * Config.refresh();
 278      * </pre>
 279      * Inside this method there are 2 places krb5.conf is used:
 280      * <ol>
 281      * <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys
 282      * <li> (Has workaround) Creating PrincipalName
 283      * </ol>
 284      * @param tab the keytab file name
 285      * @param append true if append, otherwise, overwrite.
 286      * @param names the names to write into, write all if names is empty
 287      */
 288     public void writeKtab(String tab, boolean append, String... names)
 289             throws IOException, KrbException {
 290         KeyTab ktab = append ? KeyTab.getInstance(tab) : KeyTab.create(tab);
 291         Iterable<String> entries =
 292                 (names.length != 0) ? Arrays.asList(names): passwords.keySet();
 293         for (String name : entries) {
 294             char[] pass = passwords.get(name);
 295             int kvno = 0;
 296             if (Character.isDigit(pass[pass.length-1])) {
 297                 kvno = pass[pass.length-1] - '0';
 298             }
 299             PrincipalName pn = new PrincipalName(name,
 300                         name.indexOf('/') < 0 ?
 301                             PrincipalName.KRB_NT_UNKNOWN :
 302                             PrincipalName.KRB_NT_SRV_HST);
 303             ktab.addEntry(pn,
 304                         getSalt(pn),
 305                         pass,
 306                         kvno,
 307                         true);
 308         }
 309         ktab.save();
 310     }
 311 
 312     /**
 313      * Writes all principals' keys from multiple KDCs into one keytab file.
 314      * @throws java.io.IOException for any file output error
 315      * @throws sun.security.krb5.KrbException for any realm and/or principal
 316      *         name error.
 317      */
 318     public static void writeMultiKtab(String tab, KDC... kdcs)
 319             throws IOException, KrbException {
 320         KeyTab.create(tab).save();      // Empty the old keytab
 321         appendMultiKtab(tab, kdcs);
 322     }
 323 
 324     /**
 325      * Appends all principals' keys from multiple KDCs to one keytab file.
 326      */
 327     public static void appendMultiKtab(String tab, KDC... kdcs)
 328             throws IOException, KrbException {
 329         for (KDC kdc: kdcs) {
 330             kdc.writeKtab(tab, true);
 331         }
 332     }
 333 
 334     /**
 335      * Write a ktab for this KDC.
 336      */
 337     public void writeKtab(String tab) throws IOException, KrbException {
 338         writeKtab(tab, false);
 339     }
 340 
 341     /**
 342      * Appends keys in this KDC to a ktab.
 343      */
 344     public void appendKtab(String tab) throws IOException, KrbException {
 345         writeKtab(tab, true);
 346     }
 347 
 348     /**
 349      * Adds a new principal to this realm with a given password.
 350      * @param user the principal's name. For a service principal, use the
 351      *        form of host/f.q.d.n
 352      * @param pass the password for the principal
 353      */
 354     public void addPrincipal(String user, char[] pass) {
 355         if (user.indexOf('@') < 0) {
 356             user = user + "@" + realm;
 357         }
 358         passwords.put(user, pass);
 359     }
 360 
 361     /**
 362      * Adds a new principal to this realm with a random password
 363      * @param user the principal's name. For a service principal, use the
 364      *        form of host/f.q.d.n
 365      */
 366     public void addPrincipalRandKey(String user) {
 367         addPrincipal(user, randomPassword());
 368     }
 369 
 370     /**
 371      * Returns the name of this realm
 372      * @return the name of this realm
 373      */
 374     public String getRealm() {
 375         return realm;
 376     }
 377 
 378     /**
 379      * Returns the name of kdc
 380      * @return the name of kdc
 381      */
 382     public String getKDC() {
 383         return kdc;
 384     }
 385 
 386     /**
 387      * Add realm-specific krb5.conf setting
 388      */
 389     public void addConf(String s) {
 390         conf.add(s);
 391     }
 392 
 393     /**
 394      * Writes a krb5.conf for one or more KDC that includes KDC locations for
 395      * each realm and the default realm name. You can also add extra strings
 396      * into the file. The method should be called like:
 397      * <pre>
 398      *   KDC.saveConfig("krb5.conf", kdc1, kdc2, ..., line1, line2, ...);
 399      * </pre>
 400      * Here you can provide one or more kdc# and zero or more line# arguments.
 401      * The line# will be put after [libdefaults] and before [realms]. Therefore
 402      * you can append new lines into [libdefaults] and/or create your new
 403      * stanzas as well. Note that a newline character will be appended to
 404      * each line# argument.
 405      * <p>
 406      * For example:
 407      * <pre>
 408      * KDC.saveConfig("krb5.conf", this);
 409      * </pre>
 410      * generates:
 411      * <pre>
 412      * [libdefaults]
 413      * default_realm = REALM.NAME
 414      *
 415      * [realms]
 416      *   REALM.NAME = {
 417      *     kdc = host:port_number
 418      *     # realm-specific settings
 419      *   }
 420      * </pre>
 421      *
 422      * Another example:
 423      * <pre>
 424      * KDC.saveConfig("krb5.conf", kdc1, kdc2, "forwardable = true", "",
 425      *         "[domain_realm]",
 426      *         ".kdc1.com = KDC1.NAME");
 427      * </pre>
 428      * generates:
 429      * <pre>
 430      * [libdefaults]
 431      * default_realm = KDC1.NAME
 432      * forwardable = true
 433      *
 434      * [domain_realm]
 435      * .kdc1.com = KDC1.NAME
 436      *
 437      * [realms]
 438      *   KDC1.NAME = {
 439      *     kdc = host:port1
 440      *   }
 441      *   KDC2.NAME = {
 442      *     kdc = host:port2
 443      *   }
 444      * </pre>
 445      * @param file the name of the file to write into
 446      * @param kdc the first (and default) KDC
 447      * @param more more KDCs or extra lines (in their appearing order) to
 448      * insert into the krb5.conf file. This method reads each argument's type
 449      * to determine what it's for. This argument can be empty.
 450      * @throws java.io.IOException for any file output error
 451      */
 452     public static void saveConfig(String file, KDC kdc, Object... more)
 453             throws IOException {
 454         File f = new File(file);
 455         StringBuffer sb = new StringBuffer();
 456         sb.append("[libdefaults]\ndefault_realm = ");
 457         sb.append(kdc.realm);
 458         sb.append("\n");
 459         for (Object o: more) {
 460             if (o instanceof String) {
 461                 sb.append(o);
 462                 sb.append("\n");
 463             }
 464         }
 465         sb.append("\n[realms]\n");
 466         sb.append(kdc.realmLine());
 467         for (Object o: more) {
 468             if (o instanceof KDC) {
 469                 sb.append(((KDC)o).realmLine());
 470             }
 471         }
 472         FileOutputStream fos = new FileOutputStream(f);
 473         fos.write(sb.toString().getBytes());
 474         fos.close();
 475     }
 476 
 477     /**
 478      * Returns the service port of the KDC server.
 479      * @return the KDC service port
 480      */
 481     public int getPort() {
 482         return port;
 483     }
 484 
 485     // Private helper methods
 486 
 487     /**
 488      * Private constructor, cannot be called outside.
 489      * @param realm
 490      */
 491     private KDC(String realm, String kdc) {
 492         this.realm = realm;
 493         this.kdc = kdc;
 494     }
 495 
 496     /**
 497      * A constructor that starts the KDC service also.
 498      */
 499     protected KDC(String realm, String kdc, int port, boolean asDaemon)
 500             throws IOException {
 501         this(realm, kdc);
 502         startServer(port, asDaemon);
 503     }
 504     /**
 505      * Generates a 32-char random password
 506      * @return the password
 507      */
 508     private static char[] randomPassword() {
 509         char[] pass = new char[32];
 510         for (int i=0; i<31; i++)
 511             pass[i] = (char)secureRandom.nextInt();
 512         // The last char cannot be a number, otherwise, keyForUser()
 513         // believes it's a sign of kvno
 514         pass[31] = 'Z';
 515         return pass;
 516     }
 517 
 518     /**
 519      * Generates a random key for the given encryption type.
 520      * @param eType the encryption type
 521      * @return the generated key
 522      * @throws sun.security.krb5.KrbException for unknown/unsupported etype
 523      */
 524     private static EncryptionKey generateRandomKey(int eType)
 525             throws KrbException  {
 526         // Is 32 enough for AES256? I should have generated the keys directly
 527         // but different cryptos have different rules on what keys are valid.
 528         char[] pass = randomPassword();
 529         String algo;
 530         switch (eType) {
 531             case EncryptedData.ETYPE_DES_CBC_MD5: algo = "DES"; break;
 532             case EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD: algo = "DESede"; break;
 533             case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96: algo = "AES128"; break;
 534             case EncryptedData.ETYPE_ARCFOUR_HMAC: algo = "ArcFourHMAC"; break;
 535             case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96: algo = "AES256"; break;
 536             default: algo = "DES"; break;
 537         }
 538         return new EncryptionKey(pass, "NOTHING", algo);    // Silly
 539     }
 540 
 541     /**
 542      * Returns the password for a given principal
 543      * @param p principal
 544      * @return the password
 545      * @throws sun.security.krb5.KrbException when the principal is not inside
 546      *         the database.
 547      */
 548     private char[] getPassword(PrincipalName p, boolean server)
 549             throws KrbException {
 550         String pn = p.toString();
 551         if (p.getRealmString() == null) {
 552             pn = pn + "@" + getRealm();
 553         }
 554         char[] pass = passwords.get(pn);
 555         if (pass == null) {
 556             throw new KrbException(server?
 557                 Krb5.KDC_ERR_S_PRINCIPAL_UNKNOWN:
 558                 Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN, pn.toString());
 559         }
 560         return pass;
 561     }
 562 
 563     /**
 564      * Returns the salt string for the principal.
 565      * @param p principal
 566      * @return the salt
 567      */
 568     protected String getSalt(PrincipalName p) {
 569         String pn = p.toString();
 570         if (p.getRealmString() == null) {
 571             pn = pn + "@" + getRealm();
 572         }
 573         if (passwords.containsKey(pn)) {
 574             try {
 575                 // Find the principal name with correct case.
 576                 p = new PrincipalName(passwords.ceilingEntry(pn).getKey());
 577             } catch (RealmException re) {
 578                 // Won't happen
 579             }
 580         }
 581         String s = p.getRealmString();
 582         if (s == null) s = getRealm();
 583         for (String n: p.getNameStrings()) {
 584             s += n;
 585         }
 586         return s;
 587     }
 588 
 589     /**
 590      * Returns the key for a given principal of the given encryption type
 591      * @param p the principal
 592      * @param etype the encryption type
 593      * @param server looking for a server principal?
 594      * @return the key
 595      * @throws sun.security.krb5.KrbException for unknown/unsupported etype
 596      */
 597     private EncryptionKey keyForUser(PrincipalName p, int etype, boolean server)
 598             throws KrbException {
 599         try {
 600             // Do not call EncryptionKey.acquireSecretKeys(), otherwise
 601             // the krb5.conf config file would be loaded.
 602             Integer kvno = null;
 603             // For service whose password ending with a number, use it as kvno.
 604             // Kvno must be postive.
 605             if (p.toString().indexOf('/') > 0) {
 606                 char[] pass = getPassword(p, server);
 607                 if (Character.isDigit(pass[pass.length-1])) {
 608                     kvno = pass[pass.length-1] - '0';
 609                 }
 610             }
 611             return new EncryptionKey(EncryptionKeyDotStringToKey(
 612                     getPassword(p, server), getSalt(p), null, etype),
 613                     etype, kvno);
 614         } catch (KrbException ke) {
 615             throw ke;
 616         } catch (Exception e) {
 617             throw new RuntimeException(e);  // should not happen
 618         }
 619     }
 620 
 621     /**
 622      * Processes an incoming request and generates a response.
 623      * @param in the request
 624      * @return the response
 625      * @throws java.lang.Exception for various errors
 626      */
 627     protected byte[] processMessage(byte[] in) throws Exception {
 628         if ((in[0] & 0x1f) == Krb5.KRB_AS_REQ)
 629             return processAsReq(in);
 630         else
 631             return processTgsReq(in);
 632     }
 633 
 634     /**
 635      * Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR)
 636      * @param in the request
 637      * @return the response
 638      * @throws java.lang.Exception for various errors
 639      */
 640     protected byte[] processTgsReq(byte[] in) throws Exception {
 641         TGSReq tgsReq = new TGSReq(in);
 642         PrincipalName service = tgsReq.reqBody.sname;
 643         if (options.containsKey(KDC.Option.RESP_NT)) {
 644             service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),
 645                     service.getNameStrings(), service.getRealm());
 646         }
 647         try {
 648             System.out.println(realm + "> " + tgsReq.reqBody.cname +
 649                     " sends TGS-REQ for " +
 650                     service + ", " + tgsReq.reqBody.kdcOptions);
 651             KDCReqBody body = tgsReq.reqBody;
 652             int[] eTypes = KDCReqBodyDotEType(body);
 653             int e2 = eTypes[0];     // etype for outgoing session key
 654             int e3 = eTypes[0];     // etype for outgoing ticket
 655 
 656             PAData[] pas = KDCReqDotPAData(tgsReq);
 657 
 658             Ticket tkt = null;
 659             EncTicketPart etp = null;
 660 
 661             PrincipalName cname = null;
 662             boolean allowForwardable = true;
 663 
 664             if (pas == null || pas.length == 0) {
 665                 throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
 666             } else {
 667                 PrincipalName forUserCName = null;
 668                 for (PAData pa: pas) {
 669                     if (pa.getType() == Krb5.PA_TGS_REQ) {
 670                         APReq apReq = new APReq(pa.getValue());
 671                         EncryptedData ed = apReq.authenticator;
 672                         tkt = apReq.ticket;
 673                         int te = tkt.encPart.getEType();
 674                         EncryptionKey kkey = keyForUser(tkt.sname, te, true);
 675                         byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET);
 676                         DerInputStream derIn = new DerInputStream(bb);
 677                         DerValue der = derIn.getDerValue();
 678                         etp = new EncTicketPart(der.toByteArray());
 679                         // Finally, cname will be overwritten by PA-FOR-USER
 680                         // if it exists.
 681                         cname = etp.cname;
 682                         System.out.println(realm + "> presenting a ticket of "
 683                                 + etp.cname + " to " + tkt.sname);
 684                     } else if (pa.getType() == Krb5.PA_FOR_USER) {
 685                         if (options.containsKey(Option.ALLOW_S4U2SELF)) {
 686                             PAForUserEnc p4u = new PAForUserEnc(
 687                                     new DerValue(pa.getValue()), null);
 688                             forUserCName = p4u.name;
 689                             System.out.println(realm + "> presenting a PA_FOR_USER "
 690                                     + " in the name of " + p4u.name);
 691                         }
 692                     }
 693                 }
 694                 if (forUserCName != null) {
 695                     List<String> names = (List<String>)options.get(Option.ALLOW_S4U2SELF);
 696                     if (!names.contains(cname.toString())) {
 697                         // Mimic the normal KDC behavior. When a server is not
 698                         // allowed to send S4U2self, do not send an error.
 699                         // Instead, send a ticket which is useless later.
 700                         allowForwardable = false;
 701                     }
 702                     cname = forUserCName;
 703                 }
 704                 if (tkt == null) {
 705                     throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
 706                 }
 707             }
 708 
 709             // Session key for original ticket, TGT
 710             EncryptionKey ckey = etp.key;
 711 
 712             // Session key for session with the service
 713             EncryptionKey key = generateRandomKey(e2);
 714 
 715             // Check time, TODO
 716             KerberosTime till = body.till;
 717             if (till == null) {
 718                 throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
 719             } else if (till.isZero()) {
 720                 till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11);
 721             }
 722 
 723             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
 724             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)
 725                     && allowForwardable) {
 726                 List<String> sensitives = (List<String>)
 727                         options.get(Option.SENSITIVE_ACCOUNTS);
 728                 if (sensitives != null && sensitives.contains(cname.toString())) {
 729                     // Cannot make FORWARDABLE
 730                 } else {
 731                     bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
 732                 }
 733             }
 734             if (body.kdcOptions.get(KDCOptions.FORWARDED) ||
 735                     etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {
 736                 bFlags[Krb5.TKT_OPTS_FORWARDED] = true;
 737             }
 738             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
 739                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
 740                 //renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7);
 741             }
 742             if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
 743                 bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
 744             }
 745             if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
 746                 bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
 747             }
 748             if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
 749                 bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
 750             }
 751             if (body.kdcOptions.get(KDCOptions.CNAME_IN_ADDL_TKT)) {
 752                 if (!options.containsKey(Option.ALLOW_S4U2PROXY)) {
 753                     // Don't understand CNAME_IN_ADDL_TKT
 754                     throw new KrbException(Krb5.KDC_ERR_BADOPTION);
 755                 } else {
 756                     Map<String,List<String>> map = (Map<String,List<String>>)
 757                             options.get(Option.ALLOW_S4U2PROXY);
 758                     Ticket second = KDCReqBodyDotFirstAdditionalTicket(body);
 759                     EncryptionKey key2 = keyForUser(second.sname, second.encPart.getEType(), true);
 760                     byte[] bb = second.encPart.decrypt(key2, KeyUsage.KU_TICKET);
 761                     DerInputStream derIn = new DerInputStream(bb);
 762                     DerValue der = derIn.getDerValue();
 763                     EncTicketPart tktEncPart = new EncTicketPart(der.toByteArray());
 764                     if (!tktEncPart.flags.get(Krb5.TKT_OPTS_FORWARDABLE)) {
 765                         //throw new KrbException(Krb5.KDC_ERR_BADOPTION);
 766                     }
 767                     PrincipalName client = tktEncPart.cname;
 768                     System.out.println(realm + "> and an additional ticket of "
 769                             + client + " to " + second.sname);
 770                     if (map.containsKey(cname.toString())) {
 771                         if (map.get(cname.toString()).contains(service.toString())) {
 772                             System.out.println(realm + "> S4U2proxy OK");
 773                         } else {
 774                             throw new KrbException(Krb5.KDC_ERR_BADOPTION);
 775                         }
 776                     } else {
 777                         throw new KrbException(Krb5.KDC_ERR_BADOPTION);
 778                     }
 779                     cname = client;
 780                 }
 781             }
 782 
 783             String okAsDelegate = (String)options.get(Option.OK_AS_DELEGATE);
 784             if (okAsDelegate != null && (
 785                     okAsDelegate.isEmpty() ||
 786                     okAsDelegate.contains(service.getNameString()))) {
 787                 bFlags[Krb5.TKT_OPTS_DELEGATE] = true;
 788             }
 789             bFlags[Krb5.TKT_OPTS_INITIAL] = true;
 790 
 791             TicketFlags tFlags = new TicketFlags(bFlags);
 792             EncTicketPart enc = new EncTicketPart(
 793                     tFlags,
 794                     key,
 795                     cname,
 796                     new TransitedEncoding(1, new byte[0]),  // TODO
 797                     new KerberosTime(new Date()),
 798                     body.from,
 799                     till, body.rtime,
 800                     body.addresses != null  // always set caddr
 801                             ? body.addresses
 802                             : new HostAddresses(
 803                                 new InetAddress[]{InetAddress.getLocalHost()}),
 804                     null);
 805             EncryptionKey skey = keyForUser(service, e3, true);
 806             if (skey == null) {
 807                 throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
 808             }
 809             Ticket t = new Ticket(
 810                     service,
 811                     new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
 812             );
 813             EncTGSRepPart enc_part = new EncTGSRepPart(
 814                     key,
 815                     new LastReq(new LastReqEntry[]{
 816                         new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000))
 817                     }),
 818                     body.getNonce(),    // TODO: detect replay
 819                     new KerberosTime(new Date().getTime() + 1000 * 3600 * 24),
 820                     // Next 5 and last MUST be same with ticket
 821                     tFlags,
 822                     new KerberosTime(new Date()),
 823                     body.from,
 824                     till, body.rtime,
 825                     service,
 826                     body.addresses != null  // always set caddr
 827                             ? body.addresses
 828                             : new HostAddresses(
 829                                 new InetAddress[]{InetAddress.getLocalHost()})
 830                     );
 831             EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY);
 832             TGSRep tgsRep = new TGSRep(null,
 833                     cname,
 834                     t,
 835                     edata);
 836             System.out.println("     Return " + tgsRep.cname
 837                     + " ticket for " + tgsRep.ticket.sname + ", flags "
 838                     + tFlags);
 839 
 840             DerOutputStream out = new DerOutputStream();
 841             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
 842                     true, (byte)Krb5.KRB_TGS_REP), tgsRep.asn1Encode());
 843             return out.toByteArray();
 844         } catch (KrbException ke) {
 845             ke.printStackTrace(System.out);
 846             KRBError kerr = ke.getError();
 847             KDCReqBody body = tgsReq.reqBody;
 848             System.out.println("     Error " + ke.returnCode()
 849                     + " " +ke.returnCodeMessage());
 850             if (kerr == null) {
 851                 kerr = new KRBError(null, null, null,
 852                         new KerberosTime(new Date()),
 853                         0,
 854                         ke.returnCode(),
 855                         body.cname,
 856                         service,
 857                         KrbException.errorMessage(ke.returnCode()),
 858                         null);
 859             }
 860             return kerr.asn1Encode();
 861         }
 862     }
 863 
 864     /**
 865      * Processes a AS_REQ and generates a AS_REP (or KRB_ERROR)
 866      * @param in the request
 867      * @return the response
 868      * @throws java.lang.Exception for various errors
 869      */
 870     protected byte[] processAsReq(byte[] in) throws Exception {
 871         ASReq asReq = new ASReq(in);
 872         int[] eTypes = null;
 873         List<PAData> outPAs = new ArrayList<>();
 874 
 875         PrincipalName service = asReq.reqBody.sname;
 876         if (options.containsKey(KDC.Option.RESP_NT)) {
 877             service = new PrincipalName(service.getNameStrings(),
 878                     (int)options.get(KDC.Option.RESP_NT));
 879         }
 880         try {
 881             System.out.println(realm + "> " + asReq.reqBody.cname +
 882                     " sends AS-REQ for " +
 883                     service + ", " + asReq.reqBody.kdcOptions);
 884 
 885             KDCReqBody body = asReq.reqBody;
 886 
 887             eTypes = KDCReqBodyDotEType(body);
 888             int eType = eTypes[0];
 889 
 890             // Maybe server does not support aes256, but a kinit does
 891             if (!EType.isSupported(eType)) {
 892                 if (eTypes.length < 2) {
 893                     throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
 894                 }
 895                 eType = eTypes[1];
 896             }
 897 
 898             EncryptionKey ckey = keyForUser(body.cname, eType, false);
 899             EncryptionKey skey = keyForUser(service, eType, true);
 900 
 901             if (options.containsKey(KDC.Option.ONLY_RC4_TGT)) {
 902                 int tgtEType = EncryptedData.ETYPE_ARCFOUR_HMAC;
 903                 boolean found = false;
 904                 for (int i=0; i<eTypes.length; i++) {
 905                     if (eTypes[i] == tgtEType) {
 906                         found = true;
 907                         break;
 908                     }
 909                 }
 910                 if (!found) {
 911                     throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
 912                 }
 913                 skey = keyForUser(service, tgtEType, true);
 914             }
 915             if (ckey == null) {
 916                 throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
 917             }
 918             if (skey == null) {
 919                 throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
 920             }
 921 
 922             // Session key
 923             EncryptionKey key = generateRandomKey(eType);
 924             // Check time, TODO
 925             KerberosTime till = body.till;
 926             KerberosTime rtime = body.rtime;
 927             if (till == null) {
 928                 throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
 929             } else if (till.isZero()) {
 930                 till = new KerberosTime(
 931                         new Date().getTime() + 1000 * DEFAULT_LIFETIME);
 932             }
 933             if (rtime == null && body.kdcOptions.get(KDCOptions.RENEWABLE)) {
 934                 rtime = new KerberosTime(
 935                         new Date().getTime() + 1000 * DEFAULT_RENEWTIME);
 936             }
 937             //body.from
 938             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
 939             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
 940                 List<String> sensitives = (List<String>)
 941                         options.get(Option.SENSITIVE_ACCOUNTS);
 942                 if (sensitives != null && sensitives.contains(body.cname.toString())) {
 943                     // Cannot make FORWARDABLE
 944                 } else {
 945                     bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
 946                 }
 947             }
 948             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
 949                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
 950                 //renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7);
 951             }
 952             if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
 953                 bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
 954             }
 955             if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
 956                 bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
 957             }
 958             if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
 959                 bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
 960             }
 961             bFlags[Krb5.TKT_OPTS_INITIAL] = true;
 962 
 963             // Creating PA-DATA
 964             DerValue[] pas2 = null, pas = null;
 965             if (options.containsKey(KDC.Option.DUP_ETYPE)) {
 966                 int n = (Integer)options.get(KDC.Option.DUP_ETYPE);
 967                 switch (n) {
 968                     case 1:     // customer's case in 7067974
 969                         pas2 = new DerValue[] {
 970                             new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),
 971                             new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),
 972                             new DerValue(new ETypeInfo2(1, realm, new byte[]{1}).asn1Encode()),
 973                         };
 974                         pas = new DerValue[] {
 975                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
 976                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
 977                             new DerValue(new ETypeInfo(1, realm).asn1Encode()),
 978                         };
 979                         break;
 980                     case 2:     // we still reject non-null s2kparams and prefer E2 over E
 981                         pas2 = new DerValue[] {
 982                             new DerValue(new ETypeInfo2(1, realm, new byte[]{1}).asn1Encode()),
 983                             new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),
 984                             new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),
 985                         };
 986                         pas = new DerValue[] {
 987                             new DerValue(new ETypeInfo(1, realm).asn1Encode()),
 988                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
 989                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
 990                         };
 991                         break;
 992                     case 3:     // but only E is wrong
 993                         pas = new DerValue[] {
 994                             new DerValue(new ETypeInfo(1, realm).asn1Encode()),
 995                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
 996                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
 997                         };
 998                         break;
 999                     case 4:     // we also ignore rc4-hmac
1000                         pas = new DerValue[] {
1001                             new DerValue(new ETypeInfo(23, "ANYTHING").asn1Encode()),
1002                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1003                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1004                         };
1005                         break;
1006                     case 5:     // "" should be wrong, but we accept it now
1007                                 // See s.s.k.internal.PAData$SaltAndParams
1008                         pas = new DerValue[] {
1009                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1010                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1011                         };
1012                         break;
1013                 }
1014             } else {
1015                 int[] epas = eTypes;
1016                 if (options.containsKey(KDC.Option.RC4_FIRST_PREAUTH)) {
1017                     for (int i=1; i<epas.length; i++) {
1018                         if (epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC) {
1019                             epas[i] = epas[0];
1020                             epas[0] = EncryptedData.ETYPE_ARCFOUR_HMAC;
1021                             break;
1022                         }
1023                     };
1024                 } else if (options.containsKey(KDC.Option.ONLY_ONE_PREAUTH)) {
1025                     epas = new int[] { eTypes[0] };
1026                 }
1027                 pas2 = new DerValue[epas.length];
1028                 for (int i=0; i<epas.length; i++) {
1029                     pas2[i] = new DerValue(new ETypeInfo2(
1030                             epas[i],
1031                             epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?
1032                                 null : getSalt(body.cname),
1033                             null).asn1Encode());
1034                 }
1035                 boolean allOld = true;
1036                 for (int i: eTypes) {
1037                     if (i == EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 ||
1038                             i == EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96) {
1039                         allOld = false;
1040                         break;
1041                     }
1042                 }
1043                 if (allOld) {
1044                     pas = new DerValue[epas.length];
1045                     for (int i=0; i<epas.length; i++) {
1046                         pas[i] = new DerValue(new ETypeInfo(
1047                                 epas[i],
1048                                 epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?
1049                                     null : getSalt(body.cname)
1050                                 ).asn1Encode());
1051                     }
1052                 }
1053             }
1054 
1055             DerOutputStream eid;
1056             if (pas2 != null) {
1057                 eid = new DerOutputStream();
1058                 eid.putSequence(pas2);
1059                 outPAs.add(new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()));
1060             }
1061             if (pas != null) {
1062                 eid = new DerOutputStream();
1063                 eid.putSequence(pas);
1064                 outPAs.add(new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()));
1065             }
1066 
1067             PAData[] inPAs = KDCReqDotPAData(asReq);
1068             if (inPAs == null || inPAs.length == 0) {
1069                 Object preauth = options.get(Option.PREAUTH_REQUIRED);
1070                 if (preauth == null || preauth.equals(Boolean.TRUE)) {
1071                     throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED);
1072                 }
1073             } else {
1074                 try {
1075                     EncryptedData data = newEncryptedData(new DerValue(inPAs[0].getValue()));
1076                     EncryptionKey pakey = keyForUser(body.cname, data.getEType(), false);
1077                     data.decrypt(pakey, KeyUsage.KU_PA_ENC_TS);
1078                 } catch (Exception e) {
1079                     throw new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED);
1080                 }
1081                 bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true;
1082             }
1083 
1084             TicketFlags tFlags = new TicketFlags(bFlags);
1085             EncTicketPart enc = new EncTicketPart(
1086                     tFlags,
1087                     key,
1088                     body.cname,
1089                     new TransitedEncoding(1, new byte[0]),
1090                     new KerberosTime(new Date()),
1091                     body.from,
1092                     till, rtime,
1093                     body.addresses,
1094                     null);
1095             Ticket t = new Ticket(
1096                     service,
1097                     new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
1098             );
1099             EncASRepPart enc_part = new EncASRepPart(
1100                     key,
1101                     new LastReq(new LastReqEntry[]{
1102                         new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000))
1103                     }),
1104                     body.getNonce(),    // TODO: detect replay?
1105                     new KerberosTime(new Date().getTime() + 1000 * 3600 * 24),
1106                     // Next 5 and last MUST be same with ticket
1107                     tFlags,
1108                     new KerberosTime(new Date()),
1109                     body.from,
1110                     till, rtime,
1111                     service,
1112                     body.addresses
1113                     );
1114             EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_AS_REP_PART);
1115             ASRep asRep = new ASRep(
1116                     outPAs.toArray(new PAData[outPAs.size()]),
1117                     body.cname,
1118                     t,
1119                     edata);
1120 
1121             System.out.println("     Return " + asRep.cname
1122                     + " ticket for " + asRep.ticket.sname + ", flags "
1123                     + tFlags);
1124 
1125             DerOutputStream out = new DerOutputStream();
1126             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
1127                     true, (byte)Krb5.KRB_AS_REP), asRep.asn1Encode());
1128             byte[] result = out.toByteArray();
1129 
1130             // Added feature:
1131             // Write the current issuing TGT into a ccache file specified
1132             // by the system property below.
1133             String ccache = System.getProperty("test.kdc.save.ccache");
1134             if (ccache != null) {
1135                 asRep.encKDCRepPart = enc_part;
1136                 sun.security.krb5.internal.ccache.Credentials credentials =
1137                     new sun.security.krb5.internal.ccache.Credentials(asRep);
1138                 CredentialsCache cache =
1139                     CredentialsCache.create(asReq.reqBody.cname, ccache);
1140                 if (cache == null) {
1141                    throw new IOException("Unable to create the cache file " +
1142                                          ccache);
1143                 }
1144                 cache.update(credentials);
1145                 cache.save();
1146             }
1147 
1148             return result;
1149         } catch (KrbException ke) {
1150             ke.printStackTrace(System.out);
1151             KRBError kerr = ke.getError();
1152             KDCReqBody body = asReq.reqBody;
1153             System.out.println("     Error " + ke.returnCode()
1154                     + " " +ke.returnCodeMessage());
1155             byte[] eData = null;
1156             if (kerr == null) {
1157                 if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED ||
1158                         ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) {
1159                     DerOutputStream bytes = new DerOutputStream();
1160                     bytes.write(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]).asn1Encode());
1161                     for (PAData p: outPAs) {
1162                         bytes.write(p.asn1Encode());
1163                     }
1164                     DerOutputStream temp = new DerOutputStream();
1165                     temp.write(DerValue.tag_Sequence, bytes);
1166                     eData = temp.toByteArray();
1167                 }
1168                 kerr = new KRBError(null, null, null,
1169                         new KerberosTime(new Date()),
1170                         0,
1171                         ke.returnCode(),
1172                         body.cname,
1173                         service,
1174                         KrbException.errorMessage(ke.returnCode()),
1175                         eData);
1176             }
1177             return kerr.asn1Encode();
1178         }
1179     }
1180 
1181     /**
1182      * Generates a line for a KDC to put inside [realms] of krb5.conf
1183      * @return REALM.NAME = { kdc = host:port etc }
1184      */
1185     private String realmLine() {
1186         StringBuilder sb = new StringBuilder();
1187         sb.append(realm).append(" = {\n    kdc = ")
1188                 .append(kdc).append(':').append(port).append('\n');
1189         for (String s: conf) {
1190             sb.append("    ").append(s).append('\n');
1191         }
1192         return sb.append("}\n").toString();
1193     }
1194 
1195     /**
1196      * Start the KDC service. This server listens on both UDP and TCP using
1197      * the same port number. It uses three threads to deal with requests.
1198      * They can be set to daemon threads if requested.
1199      * @param port the port number to listen to. If zero, a random available
1200      *  port no less than 8000 will be chosen and used.
1201      * @param asDaemon true if the KDC threads should be daemons
1202      * @throws java.io.IOException for any communication error
1203      */
1204     protected void startServer(int port, boolean asDaemon) throws IOException {
1205         if (port > 0) {
1206             u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
1207             t1 = new ServerSocket(port);
1208         } else {
1209             while (true) {
1210                 // Try to find a port number that's both TCP and UDP free
1211                 try {
1212                     port = 8000 + new java.util.Random().nextInt(10000);
1213                     u1 = null;
1214                     u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
1215                     t1 = new ServerSocket(port);
1216                     break;
1217                 } catch (Exception e) {
1218                     if (u1 != null) u1.close();
1219                 }
1220             }
1221         }
1222         final DatagramSocket udp = u1;
1223         final ServerSocket tcp = t1;
1224         System.out.println("Start KDC on " + port);
1225 
1226         this.port = port;
1227 
1228         // The UDP consumer
1229         thread1 = new Thread() {
1230             public void run() {
1231                 while (true) {
1232                     try {
1233                         byte[] inbuf = new byte[8192];
1234                         DatagramPacket p = new DatagramPacket(inbuf, inbuf.length);
1235                         udp.receive(p);
1236                         System.out.println("-----------------------------------------------");
1237                         System.out.println(">>>>> UDP packet received");
1238                         q.put(new Job(processMessage(Arrays.copyOf(inbuf, p.getLength())), udp, p));
1239                     } catch (Exception e) {
1240                         e.printStackTrace();
1241                     }
1242                 }
1243             }
1244         };
1245         thread1.setDaemon(asDaemon);
1246         thread1.start();
1247 
1248         // The TCP consumer
1249         thread2 = new Thread() {
1250             public void run() {
1251                 while (true) {
1252                     try {
1253                         Socket socket = tcp.accept();
1254                         System.out.println("-----------------------------------------------");
1255                         System.out.println(">>>>> TCP connection established");
1256                         DataInputStream in = new DataInputStream(socket.getInputStream());
1257                         DataOutputStream out = new DataOutputStream(socket.getOutputStream());
1258                         byte[] token = new byte[in.readInt()];
1259                         in.readFully(token);
1260                         q.put(new Job(processMessage(token), socket, out));
1261                     } catch (Exception e) {
1262                         e.printStackTrace();
1263                     }
1264                 }
1265             }
1266         };
1267         thread2.setDaemon(asDaemon);
1268         thread2.start();
1269 
1270         // The dispatcher
1271         thread3 = new Thread() {
1272             public void run() {
1273                 while (true) {
1274                     try {
1275                         q.take().send();
1276                     } catch (Exception e) {
1277                     }
1278                 }
1279             }
1280         };
1281         thread3.setDaemon(true);
1282         thread3.start();
1283     }
1284 
1285     public void terminate() {
1286         try {
1287             thread1.stop();
1288             thread2.stop();
1289             thread3.stop();
1290             u1.close();
1291             t1.close();
1292         } catch (Exception e) {
1293             // OK
1294         }
1295     }
1296     /**
1297      * Helper class to encapsulate a job in a KDC.
1298      */
1299     private static class Job {
1300         byte[] token;           // The received request at creation time and
1301                                 // the response at send time
1302         Socket s;               // The TCP socket from where the request comes
1303         DataOutputStream out;   // The OutputStream of the TCP socket
1304         DatagramSocket s2;      // The UDP socket from where the request comes
1305         DatagramPacket dp;      // The incoming UDP datagram packet
1306         boolean useTCP;         // Whether TCP or UDP is used
1307 
1308         // Creates a job object for TCP
1309         Job(byte[] token, Socket s, DataOutputStream out) {
1310             useTCP = true;
1311             this.token = token;
1312             this.s = s;
1313             this.out = out;
1314         }
1315 
1316         // Creates a job object for UDP
1317         Job(byte[] token, DatagramSocket s2, DatagramPacket dp) {
1318             useTCP = false;
1319             this.token = token;
1320             this.s2 = s2;
1321             this.dp = dp;
1322         }
1323 
1324         // Sends the output back to the client
1325         void send() {
1326             try {
1327                 if (useTCP) {
1328                     System.out.println(">>>>> TCP request honored");
1329                     out.writeInt(token.length);
1330                     out.write(token);
1331                     s.close();
1332                 } else {
1333                     System.out.println(">>>>> UDP request honored");
1334                     s2.send(new DatagramPacket(token, token.length, dp.getAddress(), dp.getPort()));
1335                 }
1336             } catch (Exception e) {
1337                 e.printStackTrace();
1338             }
1339         }
1340     }
1341 
1342     public static class KDCNameService implements NameServiceDescriptor {
1343         @Override
1344         public NameService createNameService() throws Exception {
1345             NameService ns = new NameService() {
1346                 @Override
1347                 public InetAddress[] lookupAllHostAddr(String host)
1348                         throws UnknownHostException {
1349                     // Everything is localhost
1350                     return new InetAddress[]{
1351                         InetAddress.getByAddress(host, new byte[]{127,0,0,1})
1352                     };
1353                 }
1354                 @Override
1355                 public String getHostByAddr(byte[] addr)
1356                         throws UnknownHostException {
1357                     // No reverse lookup, PrincipalName use original string
1358                     throw new UnknownHostException();
1359                 }
1360             };
1361             return ns;
1362         }
1363 
1364         @Override
1365         public String getProviderName() {
1366             return "mock";
1367         }
1368 
1369         @Override
1370         public String getType() {
1371             return "ns";
1372         }
1373     }
1374 
1375     // Calling private methods thru reflections
1376     private static final Field getPADataField;
1377     private static final Field getEType;
1378     private static final Constructor<EncryptedData> ctorEncryptedData;
1379     private static final Method stringToKey;
1380     private static final Field getAddlTkt;
1381 
1382     static {
1383         try {
1384             ctorEncryptedData = EncryptedData.class.getDeclaredConstructor(DerValue.class);
1385             ctorEncryptedData.setAccessible(true);
1386             getPADataField = KDCReq.class.getDeclaredField("pAData");
1387             getPADataField.setAccessible(true);
1388             getEType = KDCReqBody.class.getDeclaredField("eType");
1389             getEType.setAccessible(true);
1390             stringToKey = EncryptionKey.class.getDeclaredMethod(
1391                     "stringToKey",
1392                     char[].class, String.class, byte[].class, Integer.TYPE);
1393             stringToKey.setAccessible(true);
1394             getAddlTkt = KDCReqBody.class.getDeclaredField("additionalTickets");
1395             getAddlTkt.setAccessible(true);
1396         } catch (NoSuchFieldException nsfe) {
1397             throw new AssertionError(nsfe);
1398         } catch (NoSuchMethodException nsme) {
1399             throw new AssertionError(nsme);
1400         }
1401     }
1402     private EncryptedData newEncryptedData(DerValue der) {
1403         try {
1404             return ctorEncryptedData.newInstance(der);
1405         } catch (Exception e) {
1406             throw new AssertionError(e);
1407         }
1408     }
1409     private static PAData[] KDCReqDotPAData(KDCReq req) {
1410         try {
1411             return (PAData[])getPADataField.get(req);
1412         } catch (Exception e) {
1413             throw new AssertionError(e);
1414         }
1415     }
1416     private static int[] KDCReqBodyDotEType(KDCReqBody body) {
1417         try {
1418             return (int[]) getEType.get(body);
1419         } catch (Exception e) {
1420             throw new AssertionError(e);
1421         }
1422     }
1423     private static byte[] EncryptionKeyDotStringToKey(char[] password, String salt,
1424             byte[] s2kparams, int keyType) throws KrbCryptoException {
1425         try {
1426             return (byte[])stringToKey.invoke(
1427                     null, password, salt, s2kparams, keyType);
1428         } catch (InvocationTargetException ex) {
1429             throw (KrbCryptoException)ex.getCause();
1430         } catch (Exception e) {
1431             throw new AssertionError(e);
1432         }
1433     }
1434     private static Ticket KDCReqBodyDotFirstAdditionalTicket(KDCReqBody body) {
1435         try {
1436             return ((Ticket[])getAddlTkt.get(body))[0];
1437         } catch (Exception e) {
1438             throw new AssertionError(e);
1439         }
1440     }
1441 }