KDC.java 82.2 KB
Newer Older
W
weijun 已提交
1
/*
2
 * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
W
weijun 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
W
weijun 已提交
22 23 24 25 26 27 28 29
 */

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.io.*;
import java.lang.reflect.Method;
30 31
import java.nio.file.Files;
import java.nio.file.Paths;
W
weijun 已提交
32 33
import java.util.*;
import java.util.concurrent.*;
34 35
import java.util.stream.Collectors;
import java.util.stream.Stream;
36

W
weijun 已提交
37 38
import sun.net.spi.nameservice.NameService;
import sun.net.spi.nameservice.NameServiceDescriptor;
W
weijun 已提交
39 40
import sun.security.krb5.*;
import sun.security.krb5.internal.*;
41
import sun.security.krb5.internal.ccache.CredentialsCache;
42
import sun.security.krb5.internal.crypto.EType;
W
weijun 已提交
43 44 45 46 47
import sun.security.krb5.internal.crypto.KeyUsage;
import sun.security.krb5.internal.ktab.KeyTab;
import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
48 49
import java.util.regex.Matcher;
import java.util.regex.Pattern;
W
weijun 已提交
50 51 52

/**
 * A KDC server.
53 54 55 56 57
 *
 * Note: By setting the system property native.kdc.path to a native
 * krb5 installation, this class starts a native KDC with the
 * given realm and host. It can also add new principals and save keytabs.
 * Other features might not be available.
W
weijun 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
 * <p>
 * Features:
 * <ol>
 * <li> Supports TCP and UDP
 * <li> Supports AS-REQ and TGS-REQ
 * <li> Principal db and other settings hard coded in application
 * <li> Options, say, request preauth or not
 * </ol>
 * Side effects:
 * <ol>
 * <li> The Sun-internal class <code>sun.security.krb5.Config</code> is a
 * singleton and initialized according to Kerberos settings (krb5.conf and
 * java.security.krb5.* system properties). This means once it's initialized
 * it will not automatically notice any changes to these settings (or file
 * changes of krb5.conf). The KDC class normally does not touch these
 * settings (except for the <code>writeKtab()</code> method). However, to make
 * sure nothing ever goes wrong, if you want to make any changes to these
 * settings after calling a KDC method, call <code>Config.refresh()</code> to
 * make sure your changes are reflected in the <code>Config</code> object.
 * </ol>
W
weijun 已提交
78 79 80 81
 * System properties recognized:
 * <ul>
 * <li>test.kdc.save.ccache
 * </ul>
W
weijun 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
 * Issues and TODOs:
 * <ol>
 * <li> Generates krb5.conf to be used on another machine, currently the kdc is
 * always localhost
 * <li> More options to KDC, say, error output, say, response nonce !=
 * request nonce
 * </ol>
 * Note: This program uses internal krb5 classes (including reflection to
 * access private fields and methods).
 * <p>
 * Usages:
 * <p>
 * 1. Init and start the KDC:
 * <pre>
 * KDC kdc = KDC.create("REALM.NAME", port, isDaemon);
 * KDC kdc = KDC.create("REALM.NAME");
 * </pre>
 * Here, <code>port</code> is the UDP and TCP port number the KDC server
 * listens on. If zero, a random port is chosen, which you can use getPort()
 * later to retrieve the value.
 * <p>
 * If <code>isDaemon</code> is true, the KDC worker threads will be daemons.
 * <p>
 * The shortcut <code>KDC.create("REALM.NAME")</code> has port=0 and
 * isDaemon=false, and is commonly used in an embedded KDC.
 * <p>
 * 2. Adding users:
 * <pre>
 * kdc.addPrincipal(String principal_name, char[] password);
 * kdc.addPrincipalRandKey(String principal_name);
 * </pre>
 * A service principal's name should look like "host/f.q.d.n". The second form
 * generates a random key. To expose this key, call <code>writeKtab()</code> to
 * save the keys into a keytab file.
 * <p>
 * Note that you need to add the principal name krbtgt/REALM.NAME yourself.
 * <p>
 * Note that you can safely add a principal at any time after the KDC is
 * started and before a user requests info on this principal.
 * <p>
 * 3. Other public methods:
 * <ul>
 * <li> <code>getPort</code>: Returns the port number the KDC uses
 * <li> <code>getRealm</code>: Returns the realm name
 * <li> <code>writeKtab</code>: Writes all principals' keys into a keytab file
 * <li> <code>saveConfig</code>: Saves a krb5.conf file to access this KDC
 * <li> <code>setOption</code>: Sets various options
 * </ul>
 * Read the javadoc for details. Lazy developer can use <code>OneKDC</code>
 * directly.
 */
public class KDC {

135 136 137
    public static final int DEFAULT_LIFETIME = 39600;
    public static final int DEFAULT_RENEWTIME = 86400;

138 139 140 141 142 143 144
    // What etypes the KDC supports. Comma-separated strings. Null for all.
    // Please note native KDCs might use different names.
    private static final String SUPPORTED_ETYPES
            = System.getProperty("kdc.supported.enctypes");

    // The native KDC
    private final NativeKdc nativeKdc;
145

146 147 148 149
    // The native KDC process
    private Process kdcProc = null;

    // Under the hood.
150 151 152 153

    // Principal db. principal -> pass. A case-insensitive TreeMap is used
    // so that even if the client provides a name with different case, the KDC
    // can still locate the principal and give back correct salt.
154
    private TreeMap<String,char[]> passwords = new TreeMap<>
155 156
            (String.CASE_INSENSITIVE_ORDER);

157 158 159 160 161 162 163 164 165 166 167
    // Non default salts. Precisely, there should be different salts for
    // different etypes, pretend they are the same at the moment.
    private TreeMap<String,String> salts = new TreeMap<>
            (String.CASE_INSENSITIVE_ORDER);

    // Non default s2kparams for newer etypes. Precisely, there should be
    // different s2kparams for different etypes, pretend they are the same
    // at the moment.
    private TreeMap<String,byte[]> s2kparamses = new TreeMap<>
            (String.CASE_INSENSITIVE_ORDER);

168 169 170 171 172 173 174 175
    // Alias for referrals.
    private TreeMap<String,KDC> aliasReferrals = new TreeMap<>
            (String.CASE_INSENSITIVE_ORDER);

    // Alias for local resolution.
    private TreeMap<String,PrincipalName> alias2Principals = new TreeMap<>
            (String.CASE_INSENSITIVE_ORDER);

W
weijun 已提交
176 177
    // Realm name
    private String realm;
W
weijun 已提交
178 179
    // KDC
    private String kdc;
W
weijun 已提交
180 181
    // Service port number
    private int port;
W
weijun 已提交
182
    // The request/response job queue
183
    private BlockingQueue<Job> q = new ArrayBlockingQueue<>(100);
W
weijun 已提交
184
    // Options
185
    private Map<Option,Object> options = new HashMap<>();
186 187
    // Realm-specific krb5.conf settings
    private List<String> conf = new ArrayList<>();
W
weijun 已提交
188

189
    private Thread thread1, thread2, thread3;
190 191 192
    private volatile boolean udpConsumerReady = false;
    private volatile boolean tcpConsumerReady = false;
    private volatile boolean dispatcherReady = false;
193 194 195
    DatagramSocket u1 = null;
    ServerSocket t1 = null;

196 197
    public static enum KtabMode { APPEND, EXISTING };

W
weijun 已提交
198 199 200 201 202 203 204 205
    /**
     * Option names, to be expanded forever.
     */
    public static enum Option {
        /**
         * Whether pre-authentication is required. Default Boolean.TRUE
         */
        PREAUTH_REQUIRED,
206
        /**
207
         * Only issue TGT in RC4
208 209
         */
        ONLY_RC4_TGT,
210
        /**
211
         * Use RC4 as the first in preauth
212
         */
213 214 215 216 217
        RC4_FIRST_PREAUTH,
        /**
         * Use only one preauth, so that some keys are not easy to generate
         */
        ONLY_ONE_PREAUTH,
218 219 220 221
        /**
         * Set all name-type to a value in response
         */
        RESP_NT,
222 223 224 225
        /**
         * Multiple ETYPE-INFO-ENTRY with same etype but different salt
         */
        DUP_ETYPE,
W
weijun 已提交
226 227 228 229
        /**
         * What backend server can be delegated to
         */
        OK_AS_DELEGATE,
230 231 232 233 234 235 236 237 238 239 240 241 242 243
        /**
         * Allow S4U2self, List<String> of middle servers.
         * If not set, means KDC does not understand S4U2self at all, therefore
         * would ignore any PA-FOR-USER request and send a ticket using the
         * cname of teh requestor. If set, it returns FORWARDABLE tickets to
         * a server with its name in the list
         */
        ALLOW_S4U2SELF,
        /**
         * Allow S4U2proxy, Map<String,List<String>> of middle servers to
         * backends. If not set or a backend not in a server's list,
         * Krb5.KDC_ERR_POLICY will be send for S4U2proxy request.
         */
        ALLOW_S4U2PROXY,
244 245 246 247
        /**
         * Sensitive accounts can never be delegated.
         */
        SENSITIVE_ACCOUNTS,
W
weijun 已提交
248 249
    };

250 251 252
    //static {
    //    System.setProperty("sun.net.spi.nameservice.provider.1", "ns,mock");
    //}
W
weijun 已提交
253

W
weijun 已提交
254 255 256 257
    /**
     * A standalone KDC server.
     */
    public static void main(String[] args) throws Exception {
258 259
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 0;
        KDC kdc = create("RABBIT.HOLE", "kdc.rabbit.hole", port, false);
W
weijun 已提交
260 261
        kdc.addPrincipal("dummy", "bogus".toCharArray());
        kdc.addPrincipal("foo", "bar".toCharArray());
W
weijun 已提交
262 263 264 265
        kdc.addPrincipalRandKey("krbtgt/RABBIT.HOLE");
        kdc.addPrincipalRandKey("server/host.rabbit.hole");
        kdc.addPrincipalRandKey("backend/host.rabbit.hole");
        KDC.saveConfig("krb5.conf", kdc, "forwardable = true");
W
weijun 已提交
266 267 268 269 270 271 272 273 274
    }

    /**
     * Creates and starts a KDC running as a daemon on a random port.
     * @param realm the realm name
     * @return the running KDC instance
     * @throws java.io.IOException for any socket creation error
     */
    public static KDC create(String realm) throws IOException {
W
weijun 已提交
275
        return create(realm, "kdc." + realm.toLowerCase(), 0, true);
W
weijun 已提交
276 277
    }

278 279 280 281 282 283
    public static KDC existing(String realm, String kdc, int port) {
        KDC k = new KDC(realm, kdc);
        k.port = port;
        return k;
    }

W
weijun 已提交
284 285 286 287 288 289 290 291 292
    /**
     * Creates and starts a KDC server.
     * @param realm the realm name
     * @param port the TCP and UDP port to listen to. A random port will to
     *        chosen if zero.
     * @param asDaemon if true, KDC threads will be daemons. Otherwise, not.
     * @return the running KDC instance
     * @throws java.io.IOException for any socket creation error
     */
293 294
    public static KDC create(String realm, String kdc, int port,
                             boolean asDaemon) throws IOException {
W
weijun 已提交
295
        return new KDC(realm, kdc, port, asDaemon);
W
weijun 已提交
296 297 298 299 300
    }

    /**
     * Sets an option
     * @param key the option name
301
     * @param value the value
W
weijun 已提交
302 303
     */
    public void setOption(Option key, Object value) {
W
weijun 已提交
304 305 306 307 308
        if (value == null) {
            options.remove(key);
        } else {
            options.put(key, value);
        }
W
weijun 已提交
309 310 311
    }

    /**
W
weijun 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
     * Writes or appends keys into a keytab.
     * <p>
     * Attention: This is the most basic one of a series of methods below on
     * keytab creation or modification. All these methods reference krb5.conf
     * settings. If you need to modify krb5.conf or switch to another krb5.conf
     * later, please call <code>Config.refresh()</code> again. For example:
     * <pre>
     * kdc.writeKtab("/etc/kdc/ktab", true);  // Config is initialized,
     * System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf");
     * Config.refresh();
     * </pre>
     * Inside this method there are 2 places krb5.conf is used:
     * <ol>
     * <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys
     * <li> (Has workaround) Creating PrincipalName
     * </ol>
     * @param tab the keytab file name
W
weijun 已提交
329
     * @param append true if append, otherwise, overwrite.
W
weijun 已提交
330
     * @param names the names to write into, write all if names is empty
W
weijun 已提交
331
     */
W
weijun 已提交
332
    public void writeKtab(String tab, boolean append, String... names)
W
weijun 已提交
333
            throws IOException, KrbException {
334 335 336 337
        KeyTab ktab = null;
        if (nativeKdc == null) {
            ktab = append ? KeyTab.getInstance(tab) : KeyTab.create(tab);
        }
W
weijun 已提交
338 339 340
        Iterable<String> entries =
                (names.length != 0) ? Arrays.asList(names): passwords.keySet();
        for (String name : entries) {
341 342
            if (name.indexOf('@') < 0) {
                name = name + "@" + realm;
W
weijun 已提交
343
            }
344 345 346 347 348 349 350
            if (nativeKdc == null) {
                char[] pass = passwords.get(name);
                int kvno = 0;
                if (Character.isDigit(pass[pass.length - 1])) {
                    kvno = pass[pass.length - 1] - '0';
                }
                PrincipalName pn = new PrincipalName(name,
351
                        name.indexOf('/') < 0 ?
352 353 354
                                PrincipalName.KRB_NT_UNKNOWN :
                                PrincipalName.KRB_NT_SRV_HST);
                ktab.addEntry(pn,
355
                        getSalt(pn),
W
weijun 已提交
356 357 358
                        pass,
                        kvno,
                        true);
359 360 361 362 363 364
            } else {
                nativeKdc.ktadd(name, tab);
            }
        }
        if (nativeKdc == null) {
            ktab.save();
W
weijun 已提交
365 366 367 368 369
        }
    }

    /**
     * Writes all principals' keys from multiple KDCs into one keytab file.
W
weijun 已提交
370 371 372 373
     * @throws java.io.IOException for any file output error
     * @throws sun.security.krb5.KrbException for any realm and/or principal
     *         name error.
     */
374 375
    public static void writeMultiKtab(String tab, KDC... kdcs)
            throws IOException, KrbException {
W
weijun 已提交
376 377
        KeyTab.create(tab).save();      // Empty the old keytab
        appendMultiKtab(tab, kdcs);
W
weijun 已提交
378 379 380 381 382 383 384
    }

    /**
     * Appends all principals' keys from multiple KDCs to one keytab file.
     */
    public static void appendMultiKtab(String tab, KDC... kdcs)
            throws IOException, KrbException {
W
weijun 已提交
385 386 387
        for (KDC kdc: kdcs) {
            kdc.writeKtab(tab, true);
        }
W
weijun 已提交
388 389
    }

390 391 392 393
    /**
     * Write a ktab for this KDC.
     */
    public void writeKtab(String tab) throws IOException, KrbException {
W
weijun 已提交
394
        writeKtab(tab, false);
395 396
    }

W
weijun 已提交
397 398 399 400
    /**
     * Appends keys in this KDC to a ktab.
     */
    public void appendKtab(String tab) throws IOException, KrbException {
W
weijun 已提交
401
        writeKtab(tab, true);
W
weijun 已提交
402 403
    }

W
weijun 已提交
404 405 406 407 408 409 410
    /**
     * Adds a new principal to this realm with a given password.
     * @param user the principal's name. For a service principal, use the
     *        form of host/f.q.d.n
     * @param pass the password for the principal
     */
    public void addPrincipal(String user, char[] pass) {
411 412 413 414 415 416 417 418 419 420 421
        addPrincipal(user, pass, null, null);
    }

    /**
     * Adds a new principal to this realm with a given password.
     * @param user the principal's name. For a service principal, use the
     *        form of host/f.q.d.n
     * @param pass the password for the principal
     * @param salt the salt, or null if a default value will be used
     * @param s2kparams the s2kparams, or null if a default value will be used
     */
422 423
    public void addPrincipal(
            String user, char[] pass, String salt, byte[] s2kparams) {
W
weijun 已提交
424 425 426
        if (user.indexOf('@') < 0) {
            user = user + "@" + realm;
        }
427 428 429 430 431 432 433 434 435 436 437 438 439
        if (nativeKdc != null) {
            if (!user.equals("krbtgt/" + realm)) {
                nativeKdc.addPrincipal(user, new String(pass));
            }
            passwords.put(user, new char[0]);
        } else {
            passwords.put(user, pass);
            if (salt != null) {
                salts.put(user, salt);
            }
            if (s2kparams != null) {
                s2kparamses.put(user, s2kparams);
            }
440
        }
W
weijun 已提交
441 442 443 444 445 446 447 448
    }

    /**
     * Adds a new principal to this realm with a random password
     * @param user the principal's name. For a service principal, use the
     *        form of host/f.q.d.n
     */
    public void addPrincipalRandKey(String user) {
W
weijun 已提交
449
        addPrincipal(user, randomPassword());
W
weijun 已提交
450 451 452 453 454 455 456 457 458 459
    }

    /**
     * Returns the name of this realm
     * @return the name of this realm
     */
    public String getRealm() {
        return realm;
    }

W
weijun 已提交
460 461 462 463 464 465 466 467
    /**
     * Returns the name of kdc
     * @return the name of kdc
     */
    public String getKDC() {
        return kdc;
    }

468 469 470 471 472 473 474
    /**
     * Add realm-specific krb5.conf setting
     */
    public void addConf(String s) {
        conf.add(s);
    }

W
weijun 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    /**
     * Writes a krb5.conf for one or more KDC that includes KDC locations for
     * each realm and the default realm name. You can also add extra strings
     * into the file. The method should be called like:
     * <pre>
     *   KDC.saveConfig("krb5.conf", kdc1, kdc2, ..., line1, line2, ...);
     * </pre>
     * Here you can provide one or more kdc# and zero or more line# arguments.
     * The line# will be put after [libdefaults] and before [realms]. Therefore
     * you can append new lines into [libdefaults] and/or create your new
     * stanzas as well. Note that a newline character will be appended to
     * each line# argument.
     * <p>
     * For example:
     * <pre>
     * KDC.saveConfig("krb5.conf", this);
     * </pre>
     * generates:
     * <pre>
     * [libdefaults]
     * default_realm = REALM.NAME
     *
     * [realms]
     *   REALM.NAME = {
W
weijun 已提交
499
     *     kdc = host:port_number
500
     *     # realm-specific settings
W
weijun 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
     *   }
     * </pre>
     *
     * Another example:
     * <pre>
     * KDC.saveConfig("krb5.conf", kdc1, kdc2, "forwardable = true", "",
     *         "[domain_realm]",
     *         ".kdc1.com = KDC1.NAME");
     * </pre>
     * generates:
     * <pre>
     * [libdefaults]
     * default_realm = KDC1.NAME
     * forwardable = true
     *
     * [domain_realm]
     * .kdc1.com = KDC1.NAME
     *
     * [realms]
     *   KDC1.NAME = {
W
weijun 已提交
521
     *     kdc = host:port1
W
weijun 已提交
522 523
     *   }
     *   KDC2.NAME = {
W
weijun 已提交
524
     *     kdc = host:port2
W
weijun 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
     *   }
     * </pre>
     * @param file the name of the file to write into
     * @param kdc the first (and default) KDC
     * @param more more KDCs or extra lines (in their appearing order) to
     * insert into the krb5.conf file. This method reads each argument's type
     * to determine what it's for. This argument can be empty.
     * @throws java.io.IOException for any file output error
     */
    public static void saveConfig(String file, KDC kdc, Object... more)
            throws IOException {
        StringBuffer sb = new StringBuffer();
        sb.append("[libdefaults]\ndefault_realm = ");
        sb.append(kdc.realm);
        sb.append("\n");
540
        for (Object o : more) {
W
weijun 已提交
541 542 543 544 545 546
            if (o instanceof String) {
                sb.append(o);
                sb.append("\n");
            }
        }
        sb.append("\n[realms]\n");
547
        sb.append(kdc.realmLine());
548
        for (Object o : more) {
W
weijun 已提交
549
            if (o instanceof KDC) {
550
                sb.append(((KDC) o).realmLine());
W
weijun 已提交
551 552
            }
        }
553
        Files.write(Paths.get(file), sb.toString().getBytes());
W
weijun 已提交
554 555 556 557 558 559 560 561 562 563
    }

    /**
     * Returns the service port of the KDC server.
     * @return the KDC service port
     */
    public int getPort() {
        return port;
    }

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    /**
     * Register an alias name to be referred to a different KDC for
     * resolution, according to RFC 6806.
     * @param alias Alias name (i.e. user@REALM.COM).
     * @param referredKDC KDC to which the alias is referred for resolution.
     */
    public void registerAlias(String alias, KDC referredKDC) {
        aliasReferrals.remove(alias);
        aliasReferrals.put(alias, referredKDC);
    }

    /**
     * Register an alias to be resolved to a Principal Name locally,
     * according to RFC 6806.
     * @param alias Alias name (i.e. user@REALM.COM).
     * @param user Principal Name to which the alias is resolved.
     */
    public void registerAlias(String alias, String user)
            throws RealmException {
        alias2Principals.remove(alias);
        alias2Principals.put(alias, new PrincipalName(user));
    }

W
weijun 已提交
587 588 589 590 591 592
    // Private helper methods

    /**
     * Private constructor, cannot be called outside.
     * @param realm
     */
W
weijun 已提交
593
    private KDC(String realm, String kdc) {
W
weijun 已提交
594
        this.realm = realm;
W
weijun 已提交
595
        this.kdc = kdc;
596
        this.nativeKdc = null;
W
weijun 已提交
597 598 599 600 601
    }

    /**
     * A constructor that starts the KDC service also.
     */
W
weijun 已提交
602
    protected KDC(String realm, String kdc, int port, boolean asDaemon)
W
weijun 已提交
603
            throws IOException {
604 605 606
        this.realm = realm;
        this.kdc = kdc;
        this.nativeKdc = NativeKdc.get(this);
W
weijun 已提交
607 608 609 610 611 612 613 614
        startServer(port, asDaemon);
    }
    /**
     * Generates a 32-char random password
     * @return the password
     */
    private static char[] randomPassword() {
        char[] pass = new char[32];
615
        Random r = new Random();
W
weijun 已提交
616
        for (int i=0; i<31; i++)
617
            pass[i] = (char)('a' + r.nextInt(26));
W
weijun 已提交
618 619 620
        // The last char cannot be a number, otherwise, keyForUser()
        // believes it's a sign of kvno
        pass[31] = 'Z';
W
weijun 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
        return pass;
    }

    /**
     * Generates a random key for the given encryption type.
     * @param eType the encryption type
     * @return the generated key
     * @throws sun.security.krb5.KrbException for unknown/unsupported etype
     */
    private static EncryptionKey generateRandomKey(int eType)
            throws KrbException  {
        // Is 32 enough for AES256? I should have generated the keys directly
        // but different cryptos have different rules on what keys are valid.
        char[] pass = randomPassword();
        String algo;
        switch (eType) {
            case EncryptedData.ETYPE_DES_CBC_MD5: algo = "DES"; break;
            case EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD: algo = "DESede"; break;
            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96: algo = "AES128"; break;
            case EncryptedData.ETYPE_ARCFOUR_HMAC: algo = "ArcFourHMAC"; break;
            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96: algo = "AES256"; break;
            default: algo = "DES"; break;
        }
        return new EncryptionKey(pass, "NOTHING", algo);    // Silly
    }

    /**
     * Returns the password for a given principal
     * @param p principal
     * @return the password
     * @throws sun.security.krb5.KrbException when the principal is not inside
     *         the database.
     */
W
weijun 已提交
654 655
    private char[] getPassword(PrincipalName p, boolean server)
            throws KrbException {
W
weijun 已提交
656 657 658 659 660
        String pn = p.toString();
        if (p.getRealmString() == null) {
            pn = pn + "@" + getRealm();
        }
        char[] pass = passwords.get(pn);
W
weijun 已提交
661
        if (pass == null) {
W
weijun 已提交
662 663
            throw new KrbException(server?
                Krb5.KDC_ERR_S_PRINCIPAL_UNKNOWN:
664
                Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN, pn.toString());
W
weijun 已提交
665 666 667 668 669
        }
        return pass;
    }

    /**
W
weijun 已提交
670
     * Returns the salt string for the principal.
W
weijun 已提交
671 672 673
     * @param p principal
     * @return the salt
     */
674
    protected String getSalt(PrincipalName p) {
675 676 677 678
        String pn = p.toString();
        if (p.getRealmString() == null) {
            pn = pn + "@" + getRealm();
        }
679 680 681
        if (salts.containsKey(pn)) {
            return salts.get(pn);
        }
682 683 684 685 686 687 688 689
        if (passwords.containsKey(pn)) {
            try {
                // Find the principal name with correct case.
                p = new PrincipalName(passwords.ceilingEntry(pn).getKey());
            } catch (RealmException re) {
                // Won't happen
            }
        }
W
weijun 已提交
690 691 692 693
        String s = p.getRealmString();
        if (s == null) s = getRealm();
        for (String n: p.getNameStrings()) {
            s += n;
W
weijun 已提交
694
        }
W
weijun 已提交
695
        return s;
W
weijun 已提交
696 697
    }

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    /**
     * Returns the s2kparams for the principal given the etype.
     * @param p principal
     * @param etype encryption type
     * @return the s2kparams, might be null
     */
    protected byte[] getParams(PrincipalName p, int etype) {
        switch (etype) {
            case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:
            case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
                String pn = p.toString();
                if (p.getRealmString() == null) {
                    pn = pn + "@" + getRealm();
                }
                if (s2kparamses.containsKey(pn)) {
                    return s2kparamses.get(pn);
                }
                return new byte[] {0, 0, 0x10, 0};
            default:
                return null;
        }
    }

W
weijun 已提交
721 722 723 724
    /**
     * Returns the key for a given principal of the given encryption type
     * @param p the principal
     * @param etype the encryption type
W
weijun 已提交
725
     * @param server looking for a server principal?
W
weijun 已提交
726 727 728
     * @return the key
     * @throws sun.security.krb5.KrbException for unknown/unsupported etype
     */
W
weijun 已提交
729 730
    private EncryptionKey keyForUser(PrincipalName p, int etype, boolean server)
            throws KrbException {
W
weijun 已提交
731 732 733
        try {
            // Do not call EncryptionKey.acquireSecretKeys(), otherwise
            // the krb5.conf config file would be loaded.
734
            Integer kvno = null;
735 736 737
            // For service whose password ending with a number, use it as kvno.
            // Kvno must be postive.
            if (p.toString().indexOf('/') > 0) {
W
weijun 已提交
738
                char[] pass = getPassword(p, server);
739 740 741 742
                if (Character.isDigit(pass[pass.length-1])) {
                    kvno = pass[pass.length-1] - '0';
                }
            }
743
            return new EncryptionKey(EncryptionKeyDotStringToKey(
744
                    getPassword(p, server), getSalt(p), getParams(p, etype), etype),
745
                    etype, kvno);
W
weijun 已提交
746 747
        } catch (KrbException ke) {
            throw ke;
W
weijun 已提交
748 749 750 751 752
        } catch (Exception e) {
            throw new RuntimeException(e);  // should not happen
        }
    }

753 754 755 756 757 758 759 760 761
    /**
     * Returns a KerberosTime.
     *
     * @param offset offset from NOW in seconds
     */
    private static KerberosTime timeAfter(int offset) {
        return new KerberosTime(new Date().getTime() + offset * 1000L);
    }

W
weijun 已提交
762 763 764 765 766 767
    /**
     * Processes an incoming request and generates a response.
     * @param in the request
     * @return the response
     * @throws java.lang.Exception for various errors
     */
768
    protected byte[] processMessage(byte[] in) throws Exception {
W
weijun 已提交
769 770 771 772 773 774 775 776 777 778 779 780
        if ((in[0] & 0x1f) == Krb5.KRB_AS_REQ)
            return processAsReq(in);
        else
            return processTgsReq(in);
    }

    /**
     * Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR)
     * @param in the request
     * @return the response
     * @throws java.lang.Exception for various errors
     */
781
    protected byte[] processTgsReq(byte[] in) throws Exception {
W
weijun 已提交
782
        TGSReq tgsReq = new TGSReq(in);
783 784
        PrincipalName service = tgsReq.reqBody.sname;
        if (options.containsKey(KDC.Option.RESP_NT)) {
785 786
            service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),
                    service.getNameStrings(), service.getRealm());
787
        }
W
weijun 已提交
788 789 790
        try {
            System.out.println(realm + "> " + tgsReq.reqBody.cname +
                    " sends TGS-REQ for " +
791
                    service + ", " + tgsReq.reqBody.kdcOptions);
W
weijun 已提交
792
            KDCReqBody body = tgsReq.reqBody;
793 794 795 796
            int[] eTypes = filterSupported(KDCReqBodyDotEType(body));
            if (eTypes.length == 0) {
                throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
            }
797 798
            int e2 = eTypes[0];     // etype for outgoing session key
            int e3 = eTypes[0];     // etype for outgoing ticket
W
weijun 已提交
799

800
            PAData[] pas = KDCReqDotPAData(tgsReq);
W
weijun 已提交
801 802 803

            Ticket tkt = null;
            EncTicketPart etp = null;
804 805 806

            PrincipalName cname = null;
            boolean allowForwardable = true;
807
            boolean isReferral = false;
808
            if (body.kdcOptions.get(KDCOptions.CANONICALIZE)) {
809 810
                System.out.println(realm + "> verifying referral for " +
                        body.sname.getNameString());
811 812 813 814 815 816 817
                KDC referral = aliasReferrals.get(body.sname.getNameString());
                if (referral != null) {
                    service = new PrincipalName(
                            PrincipalName.TGS_DEFAULT_SRV_NAME +
                            PrincipalName.NAME_COMPONENT_SEPARATOR_STR +
                            referral.getRealm(), PrincipalName.KRB_NT_SRV_INST,
                            this.getRealm());
818 819 820
                    System.out.println(realm + "> referral to " +
                            referral.getRealm());
                    isReferral = true;
821 822 823
                }
            }

W
weijun 已提交
824 825 826
            if (pas == null || pas.length == 0) {
                throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
            } else {
827
                PrincipalName forUserCName = null;
W
weijun 已提交
828 829 830 831 832
                for (PAData pa: pas) {
                    if (pa.getType() == Krb5.PA_TGS_REQ) {
                        APReq apReq = new APReq(pa.getValue());
                        EncryptedData ed = apReq.authenticator;
                        tkt = apReq.ticket;
833 834
                        int te = tkt.encPart.getEType();
                        EncryptionKey kkey = keyForUser(tkt.sname, te, true);
W
weijun 已提交
835 836 837 838
                        byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET);
                        DerInputStream derIn = new DerInputStream(bb);
                        DerValue der = derIn.getDerValue();
                        etp = new EncTicketPart(der.toByteArray());
839 840 841 842 843 844 845 846 847 848
                        // Finally, cname will be overwritten by PA-FOR-USER
                        // if it exists.
                        cname = etp.cname;
                        System.out.println(realm + "> presenting a ticket of "
                                + etp.cname + " to " + tkt.sname);
                    } else if (pa.getType() == Krb5.PA_FOR_USER) {
                        if (options.containsKey(Option.ALLOW_S4U2SELF)) {
                            PAForUserEnc p4u = new PAForUserEnc(
                                    new DerValue(pa.getValue()), null);
                            forUserCName = p4u.name;
849
                            System.out.println(realm + "> See PA_FOR_USER "
850 851 852 853 854
                                    + " in the name of " + p4u.name);
                        }
                    }
                }
                if (forUserCName != null) {
855 856
                    List<String> names = (List<String>)
                            options.get(Option.ALLOW_S4U2SELF);
857 858 859 860 861
                    if (!names.contains(cname.toString())) {
                        // Mimic the normal KDC behavior. When a server is not
                        // allowed to send S4U2self, do not send an error.
                        // Instead, send a ticket which is useless later.
                        allowForwardable = false;
W
weijun 已提交
862
                    }
863
                    cname = forUserCName;
W
weijun 已提交
864 865 866 867 868 869 870 871 872 873
                }
                if (tkt == null) {
                    throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
                }
            }

            // Session key for original ticket, TGT
            EncryptionKey ckey = etp.key;

            // Session key for session with the service
874
            EncryptionKey key = generateRandomKey(e2);
W
weijun 已提交
875 876

            // Check time, TODO
877
            KerberosTime from = body.from;
W
weijun 已提交
878
            KerberosTime till = body.till;
879 880 881
            if (from == null || from.isZero()) {
                from = timeAfter(0);
            }
882
            KerberosTime rtime = body.rtime;
W
weijun 已提交
883 884 885
            if (till == null) {
                throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
            } else if (till.isZero()) {
886
                till = timeAfter(DEFAULT_LIFETIME);
887 888
            }
            if (rtime == null && body.kdcOptions.get(KDCOptions.RENEWABLE)) {
889
                rtime = timeAfter(DEFAULT_RENEWTIME);
W
weijun 已提交
890 891 892
            }

            boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
893 894
            if (body.kdcOptions.get(KDCOptions.FORWARDABLE)
                    && allowForwardable) {
895 896 897 898 899 900 901
                List<String> sensitives = (List<String>)
                        options.get(Option.SENSITIVE_ACCOUNTS);
                if (sensitives != null && sensitives.contains(cname.toString())) {
                    // Cannot make FORWARDABLE
                } else {
                    bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
                }
W
weijun 已提交
902 903 904 905 906 907 908
            }
            if (body.kdcOptions.get(KDCOptions.FORWARDED) ||
                    etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {
                bFlags[Krb5.TKT_OPTS_FORWARDED] = true;
            }
            if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
                bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
909
                //renew = timeAfter(3600 * 24 * 7);
W
weijun 已提交
910 911 912 913 914 915 916 917 918 919
            }
            if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
                bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
            }
            if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
                bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
            }
            if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
                bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
            }
920 921
            if (body.kdcOptions.get(KDCOptions.CNAME_IN_ADDL_TKT) &&
                    !isReferral) {
922 923 924 925 926 927 928
                if (!options.containsKey(Option.ALLOW_S4U2PROXY)) {
                    // Don't understand CNAME_IN_ADDL_TKT
                    throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                } else {
                    Map<String,List<String>> map = (Map<String,List<String>>)
                            options.get(Option.ALLOW_S4U2PROXY);
                    Ticket second = KDCReqBodyDotFirstAdditionalTicket(body);
929 930
                    EncryptionKey key2 = keyForUser(
                            second.sname, second.encPart.getEType(), true);
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                    byte[] bb = second.encPart.decrypt(key2, KeyUsage.KU_TICKET);
                    DerInputStream derIn = new DerInputStream(bb);
                    DerValue der = derIn.getDerValue();
                    EncTicketPart tktEncPart = new EncTicketPart(der.toByteArray());
                    if (!tktEncPart.flags.get(Krb5.TKT_OPTS_FORWARDABLE)) {
                        //throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                    }
                    PrincipalName client = tktEncPart.cname;
                    System.out.println(realm + "> and an additional ticket of "
                            + client + " to " + second.sname);
                    if (map.containsKey(cname.toString())) {
                        if (map.get(cname.toString()).contains(service.toString())) {
                            System.out.println(realm + "> S4U2proxy OK");
                        } else {
                            throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                        }
                    } else {
                        throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                    }
                    cname = client;
                }
            }
W
weijun 已提交
953

W
weijun 已提交
954 955 956 957
            String okAsDelegate = (String)options.get(Option.OK_AS_DELEGATE);
            if (okAsDelegate != null && (
                    okAsDelegate.isEmpty() ||
                    okAsDelegate.contains(service.getNameString()))) {
W
weijun 已提交
958 959
                bFlags[Krb5.TKT_OPTS_DELEGATE] = true;
            }
W
weijun 已提交
960 961
            bFlags[Krb5.TKT_OPTS_INITIAL] = true;

962 963 964 965 966 967 968 969 970 971 972 973
            KerberosTime renewTill = etp.renewTill;
            if (renewTill != null && body.kdcOptions.get(KDCOptions.RENEW)) {
                // till should never pass renewTill
                if (till.greaterThan(renewTill)) {
                    till = renewTill;
                }
                if (System.getProperty("test.set.null.renew") != null) {
                    // Testing 8186576, see NullRenewUntil.java.
                    renewTill = null;
                }
            }

W
weijun 已提交
974 975 976 977
            TicketFlags tFlags = new TicketFlags(bFlags);
            EncTicketPart enc = new EncTicketPart(
                    tFlags,
                    key,
978
                    cname,
W
weijun 已提交
979
                    new TransitedEncoding(1, new byte[0]),  // TODO
980 981
                    timeAfter(0),
                    from,
982
                    till, renewTill,
983 984 985 986
                    body.addresses != null  // always set caddr
                            ? body.addresses
                            : new HostAddresses(
                                new InetAddress[]{InetAddress.getLocalHost()}),
W
weijun 已提交
987
                    null);
988
            EncryptionKey skey = keyForUser(service, e3, true);
989 990 991
            if (skey == null) {
                throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
            }
W
weijun 已提交
992
            Ticket t = new Ticket(
R
rpatil 已提交
993 994 995
                    System.getProperty("test.kdc.diff.sname") != null ?
                        new PrincipalName("xx" + service.toString()) :
                        service,
W
weijun 已提交
996 997 998 999
                    new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
            );
            EncTGSRepPart enc_part = new EncTGSRepPart(
                    key,
1000 1001
                    new LastReq(new LastReqEntry[] {
                        new LastReqEntry(0, timeAfter(-10))
W
weijun 已提交
1002 1003
                    }),
                    body.getNonce(),    // TODO: detect replay
1004
                    timeAfter(3600 * 24),
W
weijun 已提交
1005 1006
                    // Next 5 and last MUST be same with ticket
                    tFlags,
1007 1008
                    timeAfter(0),
                    from,
1009
                    till, renewTill,
1010
                    service,
1011 1012 1013
                    body.addresses != null  // always set caddr
                            ? body.addresses
                            : new HostAddresses(
1014 1015
                                new InetAddress[]{InetAddress.getLocalHost()}),
                    null
W
weijun 已提交
1016
                    );
1017 1018
            EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(),
                    KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY);
W
weijun 已提交
1019
            TGSRep tgsRep = new TGSRep(null,
1020
                    cname,
W
weijun 已提交
1021 1022 1023
                    t,
                    edata);
            System.out.println("     Return " + tgsRep.cname
1024 1025
                    + " ticket for " + tgsRep.ticket.sname + ", flags "
                    + tFlags);
W
weijun 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

            DerOutputStream out = new DerOutputStream();
            out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
                    true, (byte)Krb5.KRB_TGS_REP), tgsRep.asn1Encode());
            return out.toByteArray();
        } catch (KrbException ke) {
            ke.printStackTrace(System.out);
            KRBError kerr = ke.getError();
            KDCReqBody body = tgsReq.reqBody;
            System.out.println("     Error " + ke.returnCode()
                    + " " +ke.returnCodeMessage());
            if (kerr == null) {
                kerr = new KRBError(null, null, null,
1039
                        timeAfter(0),
W
weijun 已提交
1040 1041
                        0,
                        ke.returnCode(),
1042 1043
                        body.cname,
                        service,
W
weijun 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
                        KrbException.errorMessage(ke.returnCode()),
                        null);
            }
            return kerr.asn1Encode();
        }
    }

    /**
     * Processes a AS_REQ and generates a AS_REP (or KRB_ERROR)
     * @param in the request
     * @return the response
     * @throws java.lang.Exception for various errors
     */
1057
    protected byte[] processAsReq(byte[] in) throws Exception {
W
weijun 已提交
1058
        ASReq asReq = new ASReq(in);
1059
        byte[] asReqbytes = asReq.asn1Encode();
W
weijun 已提交
1060
        int[] eTypes = null;
1061
        List<PAData> outPAs = new ArrayList<>();
1062

1063 1064
        PrincipalName service = asReq.reqBody.sname;
        if (options.containsKey(KDC.Option.RESP_NT)) {
1065 1066 1067
            service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),
                    service.getNameStrings(),
                    Realm.getDefault());
1068
        }
W
weijun 已提交
1069 1070 1071
        try {
            System.out.println(realm + "> " + asReq.reqBody.cname +
                    " sends AS-REQ for " +
1072
                    service + ", " + asReq.reqBody.kdcOptions);
W
weijun 已提交
1073 1074 1075

            KDCReqBody body = asReq.reqBody;

1076 1077 1078
            eTypes = filterSupported(KDCReqBodyDotEType(body));
            if (eTypes.length == 0) {
                throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
1079
            }
1080
            int eType = eTypes[0];
1081

1082
            if (body.kdcOptions.get(KDCOptions.CANONICALIZE)) {
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
                PrincipalName principal = alias2Principals.get(
                        body.cname.getNameString());
                if (principal != null) {
                    body.cname = principal;
                } else {
                    KDC referral = aliasReferrals.get(body.cname.getNameString());
                    if (referral != null) {
                        body.cname = new PrincipalName(
                                PrincipalName.TGS_DEFAULT_SRV_NAME,
                                PrincipalName.KRB_NT_SRV_INST,
                                referral.getRealm());
                        throw new KrbException(Krb5.KRB_ERR_WRONG_REALM);
                    }
                }
            }

W
weijun 已提交
1099
            EncryptionKey ckey = keyForUser(body.cname, eType, false);
1100
            EncryptionKey skey = keyForUser(service, eType, true);
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

            if (options.containsKey(KDC.Option.ONLY_RC4_TGT)) {
                int tgtEType = EncryptedData.ETYPE_ARCFOUR_HMAC;
                boolean found = false;
                for (int i=0; i<eTypes.length; i++) {
                    if (eTypes[i] == tgtEType) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
                }
1114
                skey = keyForUser(service, tgtEType, true);
1115
            }
W
weijun 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
            if (ckey == null) {
                throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
            }
            if (skey == null) {
                throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
            }

            // Session key
            EncryptionKey key = generateRandomKey(eType);
            // Check time, TODO
1126
            KerberosTime from = body.from;
W
weijun 已提交
1127
            KerberosTime till = body.till;
1128
            KerberosTime rtime = body.rtime;
1129 1130 1131
            if (from == null || from.isZero()) {
                from = timeAfter(0);
            }
W
weijun 已提交
1132 1133 1134
            if (till == null) {
                throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
            } else if (till.isZero()) {
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
                String ttlsVal = System.getProperty("test.kdc.ttl.value");
                if (ttlsVal != null){
                    till = timeAfter(duration(ttlsVal));
                    if (till.greaterThan(timeAfter(24 * 3600)) &&
                        (System.getProperty("test.kdc.force.till") == null)) {
                        till = timeAfter(DEFAULT_LIFETIME);
                        body.kdcOptions.set(KDCOptions.RENEWABLE, true);
                    }
                } else {
                    till = timeAfter(DEFAULT_LIFETIME);
                }
W
weijun 已提交
1146
            }
1147 1148 1149 1150 1151

            if (rtime == null && body.kdcOptions.get(KDCOptions.RENEWABLE)) {
                rtime = timeAfter(DEFAULT_RENEWTIME);
            }

W
weijun 已提交
1152 1153 1154
            //body.from
            boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
            if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
1155 1156
                List<String> sensitives = (List<String>)
                        options.get(Option.SENSITIVE_ACCOUNTS);
1157 1158
                if (sensitives != null
                        && sensitives.contains(body.cname.toString())) {
1159 1160 1161 1162
                    // Cannot make FORWARDABLE
                } else {
                    bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
                }
W
weijun 已提交
1163 1164 1165
            }
            if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
                bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
1166
                //renew = timeAfter(3600 * 24 * 7);
W
weijun 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
            }
            if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
                bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
            }
            if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
                bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
            }
            if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
                bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
            }
            bFlags[Krb5.TKT_OPTS_INITIAL] = true;

1179
            // Creating PA-DATA
1180 1181 1182 1183 1184 1185 1186 1187
            DerValue[] pas2 = null, pas = null;
            if (options.containsKey(KDC.Option.DUP_ETYPE)) {
                int n = (Integer)options.get(KDC.Option.DUP_ETYPE);
                switch (n) {
                    case 1:     // customer's case in 7067974
                        pas2 = new DerValue[] {
                            new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),
                            new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),
1188 1189
                            new DerValue(new ETypeInfo2(
                                    1, realm, new byte[]{1}).asn1Encode()),
1190 1191 1192 1193
                        };
                        pas = new DerValue[] {
                            new DerValue(new ETypeInfo(1, null).asn1Encode()),
                            new DerValue(new ETypeInfo(1, "").asn1Encode()),
1194
                            new DerValue(new ETypeInfo(1, realm).asn1Encode()),
1195 1196 1197 1198
                        };
                        break;
                    case 2:     // we still reject non-null s2kparams and prefer E2 over E
                        pas2 = new DerValue[] {
1199 1200
                            new DerValue(new ETypeInfo2(
                                    1, realm, new byte[]{1}).asn1Encode()),
1201 1202 1203 1204
                            new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),
                            new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),
                        };
                        pas = new DerValue[] {
1205
                            new DerValue(new ETypeInfo(1, realm).asn1Encode()),
1206 1207 1208 1209 1210 1211
                            new DerValue(new ETypeInfo(1, null).asn1Encode()),
                            new DerValue(new ETypeInfo(1, "").asn1Encode()),
                        };
                        break;
                    case 3:     // but only E is wrong
                        pas = new DerValue[] {
1212
                            new DerValue(new ETypeInfo(1, realm).asn1Encode()),
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
                            new DerValue(new ETypeInfo(1, null).asn1Encode()),
                            new DerValue(new ETypeInfo(1, "").asn1Encode()),
                        };
                        break;
                    case 4:     // we also ignore rc4-hmac
                        pas = new DerValue[] {
                            new DerValue(new ETypeInfo(23, "ANYTHING").asn1Encode()),
                            new DerValue(new ETypeInfo(1, null).asn1Encode()),
                            new DerValue(new ETypeInfo(1, "").asn1Encode()),
                        };
                        break;
                    case 5:     // "" should be wrong, but we accept it now
                                // See s.s.k.internal.PAData$SaltAndParams
                        pas = new DerValue[] {
                            new DerValue(new ETypeInfo(1, "").asn1Encode()),
                            new DerValue(new ETypeInfo(1, null).asn1Encode()),
                        };
1230 1231
                        break;
                }
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
            } else {
                int[] epas = eTypes;
                if (options.containsKey(KDC.Option.RC4_FIRST_PREAUTH)) {
                    for (int i=1; i<epas.length; i++) {
                        if (epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC) {
                            epas[i] = epas[0];
                            epas[0] = EncryptedData.ETYPE_ARCFOUR_HMAC;
                            break;
                        }
                    };
                } else if (options.containsKey(KDC.Option.ONLY_ONE_PREAUTH)) {
                    epas = new int[] { eTypes[0] };
                }
                pas2 = new DerValue[epas.length];
1246
                for (int i=0; i<epas.length; i++) {
1247
                    pas2[i] = new DerValue(new ETypeInfo2(
1248 1249
                            epas[i],
                            epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?
1250
                                null : getSalt(body.cname),
1251
                            getParams(body.cname, epas[i])).asn1Encode());
1252 1253 1254 1255 1256 1257 1258 1259
                }
                boolean allOld = true;
                for (int i: eTypes) {
                    if (i == EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 ||
                            i == EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96) {
                        allOld = false;
                        break;
                    }
1260
                }
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
                if (allOld) {
                    pas = new DerValue[epas.length];
                    for (int i=0; i<epas.length; i++) {
                        pas[i] = new DerValue(new ETypeInfo(
                                epas[i],
                                epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?
                                    null : getSalt(body.cname)
                                ).asn1Encode());
                    }
                }
            }

            DerOutputStream eid;
            if (pas2 != null) {
                eid = new DerOutputStream();
                eid.putSequence(pas2);
                outPAs.add(new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()));
            }
            if (pas != null) {
1280 1281 1282 1283 1284
                eid = new DerOutputStream();
                eid.putSequence(pas);
                outPAs.add(new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()));
            }

1285
            PAData[] inPAs = KDCReqDotPAData(asReq);
1286
            List<PAData> enc_outPAs = new ArrayList<>();
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

            byte[] paEncTimestamp = null;
            if (inPAs != null) {
                for (PAData inPA : inPAs) {
                    if (inPA.getType() == Krb5.PA_ENC_TIMESTAMP) {
                        paEncTimestamp = inPA.getValue();
                    }
                }
            }

            if (paEncTimestamp == null) {
W
weijun 已提交
1298 1299 1300 1301 1302
                Object preauth = options.get(Option.PREAUTH_REQUIRED);
                if (preauth == null || preauth.equals(Boolean.TRUE)) {
                    throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED);
                }
            } else {
1303
                EncryptionKey pakey = null;
W
weijun 已提交
1304
                try {
1305
                    EncryptedData data = newEncryptedData(
1306
                            new DerValue(paEncTimestamp));
1307
                    pakey = keyForUser(body.cname, data.getEType(), false);
1308
                    data.decrypt(pakey, KeyUsage.KU_PA_ENC_TS);
W
weijun 已提交
1309
                } catch (Exception e) {
1310 1311 1312
                    KrbException ke = new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED);
                    ke.initCause(e);
                    throw ke;
W
weijun 已提交
1313 1314
                }
                bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true;
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
                for (PAData pa : inPAs) {
                    if (pa.getType() == Krb5.PA_REQ_ENC_PA_REP) {
                        Checksum ckSum = new Checksum(
                                Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128,
                                asReqbytes, ckey, KeyUsage.KU_AS_REQ);
                        enc_outPAs.add(new PAData(Krb5.PA_REQ_ENC_PA_REP,
                                ckSum.asn1Encode()));
                        bFlags[Krb5.TKT_OPTS_ENC_PA_REP] = true;
                        break;
                    }
                }
W
weijun 已提交
1326 1327 1328 1329 1330 1331 1332 1333
            }

            TicketFlags tFlags = new TicketFlags(bFlags);
            EncTicketPart enc = new EncTicketPart(
                    tFlags,
                    key,
                    body.cname,
                    new TransitedEncoding(1, new byte[0]),
1334 1335
                    timeAfter(0),
                    from,
1336
                    till, rtime,
W
weijun 已提交
1337 1338 1339
                    body.addresses,
                    null);
            Ticket t = new Ticket(
1340
                    service,
W
weijun 已提交
1341 1342 1343 1344 1345
                    new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
            );
            EncASRepPart enc_part = new EncASRepPart(
                    key,
                    new LastReq(new LastReqEntry[]{
1346
                        new LastReqEntry(0, timeAfter(-10))
W
weijun 已提交
1347 1348
                    }),
                    body.getNonce(),    // TODO: detect replay?
1349
                    timeAfter(3600 * 24),
W
weijun 已提交
1350 1351
                    // Next 5 and last MUST be same with ticket
                    tFlags,
1352 1353
                    timeAfter(0),
                    from,
1354
                    till, rtime,
1355
                    service,
1356 1357
                    body.addresses,
                    enc_outPAs.toArray(new PAData[enc_outPAs.size()])
W
weijun 已提交
1358
                    );
1359 1360
            EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(),
                    KeyUsage.KU_ENC_AS_REP_PART);
1361 1362
            ASRep asRep = new ASRep(
                    outPAs.toArray(new PAData[outPAs.size()]),
W
weijun 已提交
1363 1364 1365 1366 1367
                    body.cname,
                    t,
                    edata);

            System.out.println("     Return " + asRep.cname
1368 1369
                    + " ticket for " + asRep.ticket.sname + ", flags "
                    + tFlags);
W
weijun 已提交
1370 1371 1372 1373

            DerOutputStream out = new DerOutputStream();
            out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
                    true, (byte)Krb5.KRB_AS_REP), asRep.asn1Encode());
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
            byte[] result = out.toByteArray();

            // Added feature:
            // Write the current issuing TGT into a ccache file specified
            // by the system property below.
            String ccache = System.getProperty("test.kdc.save.ccache");
            if (ccache != null) {
                asRep.encKDCRepPart = enc_part;
                sun.security.krb5.internal.ccache.Credentials credentials =
                    new sun.security.krb5.internal.ccache.Credentials(asRep);
                CredentialsCache cache =
                    CredentialsCache.create(asReq.reqBody.cname, ccache);
                if (cache == null) {
                   throw new IOException("Unable to create the cache file " +
                                         ccache);
                }
                cache.update(credentials);
                cache.save();
            }

            return result;
W
weijun 已提交
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
        } catch (KrbException ke) {
            ke.printStackTrace(System.out);
            KRBError kerr = ke.getError();
            KDCReqBody body = asReq.reqBody;
            System.out.println("     Error " + ke.returnCode()
                    + " " +ke.returnCodeMessage());
            byte[] eData = null;
            if (kerr == null) {
                if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED ||
                        ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) {
1405 1406 1407
                    outPAs.add(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]));
                }
                if (outPAs.size() > 0) {
W
weijun 已提交
1408
                    DerOutputStream bytes = new DerOutputStream();
1409 1410
                    for (PAData p: outPAs) {
                        bytes.write(p.asn1Encode());
W
weijun 已提交
1411 1412 1413 1414 1415 1416
                    }
                    DerOutputStream temp = new DerOutputStream();
                    temp.write(DerValue.tag_Sequence, bytes);
                    eData = temp.toByteArray();
                }
                kerr = new KRBError(null, null, null,
1417
                        timeAfter(0),
W
weijun 已提交
1418 1419
                        0,
                        ke.returnCode(),
1420 1421
                        body.cname,
                        service,
W
weijun 已提交
1422 1423 1424 1425 1426 1427 1428
                        KrbException.errorMessage(ke.returnCode()),
                        eData);
            }
            return kerr.asn1Encode();
        }
    }

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
    /**
     * Translates a duration value into seconds.
     *
     * The format can be one of "h:m[:s]", "NdNhNmNs", and "N". See
     * http://web.mit.edu/kerberos/krb5-devel/doc/basic/date_format.html#duration
     * for definitions.
     *
     * @param s the string duration
     * @return time in seconds
     * @throw KrbException if format is illegal
     */
    public static int duration(String s) throws KrbException {

        if (s.isEmpty()) {
            throw new KrbException("Duration cannot be empty");
        }

        // N
        if (s.matches("\\d+")) {
            return Integer.parseInt(s);
        }

        // h:m[:s]
        Matcher m = Pattern.compile("(\\d+):(\\d+)(:(\\d+))?").matcher(s);
        if (m.matches()) {
            int hr = Integer.parseInt(m.group(1));
            int min = Integer.parseInt(m.group(2));
            if (min >= 60) {
                throw new KrbException("Illegal duration format " + s);
            }
            int result = hr * 3600 + min * 60;
            if (m.group(4) != null) {
                int sec = Integer.parseInt(m.group(4));
                if (sec >= 60) {
                    throw new KrbException("Illegal duration format " + s);
                }
                result += sec;
            }
            return result;
        }

        // NdNhNmNs
        // 120m allowed. Maybe 1h120m is not good, but still allowed
        m = Pattern.compile(
                    "((\\d+)d)?\\s*((\\d+)h)?\\s*((\\d+)m)?\\s*((\\d+)s)?",
                Pattern.CASE_INSENSITIVE).matcher(s);
        if (m.matches()) {
            int result = 0;
            if (m.group(2) != null) {
                result += 86400 * Integer.parseInt(m.group(2));
            }
            if (m.group(4) != null) {
                result += 3600 * Integer.parseInt(m.group(4));
            }
            if (m.group(6) != null) {
                result += 60 * Integer.parseInt(m.group(6));
            }
            if (m.group(8) != null) {
                result += Integer.parseInt(m.group(8));
            }
            return result;
        }

        throw new KrbException("Illegal duration format " + s);
    }

1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    private int[] filterSupported(int[] input) {
        int count = 0;
        for (int i = 0; i < input.length; i++) {
            if (!EType.isSupported(input[i])) {
                continue;
            }
            if (SUPPORTED_ETYPES != null) {
                boolean supported = false;
                for (String se : SUPPORTED_ETYPES.split(",")) {
                    if (Config.getType(se) == input[i]) {
                        supported = true;
                        break;
                    }
                }
                if (!supported) {
                    continue;
                }
            }
            if (count != i) {
                input[count] = input[i];
            }
            count++;
        }
        if (count != input.length) {
            input = Arrays.copyOf(input, count);
        }
        return input;
    }

W
weijun 已提交
1524 1525
    /**
     * Generates a line for a KDC to put inside [realms] of krb5.conf
1526
     * @return REALM.NAME = { kdc = host:port etc }
W
weijun 已提交
1527
     */
1528 1529 1530 1531 1532 1533 1534 1535
    private String realmLine() {
        StringBuilder sb = new StringBuilder();
        sb.append(realm).append(" = {\n    kdc = ")
                .append(kdc).append(':').append(port).append('\n');
        for (String s: conf) {
            sb.append("    ").append(s).append('\n');
        }
        return sb.append("}\n").toString();
W
weijun 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    }

    /**
     * Start the KDC service. This server listens on both UDP and TCP using
     * the same port number. It uses three threads to deal with requests.
     * They can be set to daemon threads if requested.
     * @param port the port number to listen to. If zero, a random available
     *  port no less than 8000 will be chosen and used.
     * @param asDaemon true if the KDC threads should be daemons
     * @throws java.io.IOException for any communication error
     */
    protected void startServer(int port, boolean asDaemon) throws IOException {
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
        if (nativeKdc != null) {
            startNativeServer(port, asDaemon);
        } else {
            startJavaServer(port, asDaemon);
        }
    }

    private void startNativeServer(int port, boolean asDaemon) throws IOException {
        nativeKdc.prepare();
        nativeKdc.init();
        kdcProc = nativeKdc.kdc();
    }

    private void startJavaServer(int port, boolean asDaemon) throws IOException {
W
weijun 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
        if (port > 0) {
            u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
            t1 = new ServerSocket(port);
        } else {
            while (true) {
                // Try to find a port number that's both TCP and UDP free
                try {
                    port = 8000 + new java.util.Random().nextInt(10000);
                    u1 = null;
                    u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
                    t1 = new ServerSocket(port);
                    break;
                } catch (Exception e) {
                    if (u1 != null) u1.close();
                }
            }
        }
        final DatagramSocket udp = u1;
        final ServerSocket tcp = t1;
        System.out.println("Start KDC on " + port);

        this.port = port;

        // The UDP consumer
1586
        thread1 = new Thread() {
W
weijun 已提交
1587
            public void run() {
1588
                udpConsumerReady = true;
W
weijun 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
                while (true) {
                    try {
                        byte[] inbuf = new byte[8192];
                        DatagramPacket p = new DatagramPacket(inbuf, inbuf.length);
                        udp.receive(p);
                        System.out.println("-----------------------------------------------");
                        System.out.println(">>>>> UDP packet received");
                        q.put(new Job(processMessage(Arrays.copyOf(inbuf, p.getLength())), udp, p));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
1603 1604
        thread1.setDaemon(asDaemon);
        thread1.start();
W
weijun 已提交
1605 1606

        // The TCP consumer
1607
        thread2 = new Thread() {
W
weijun 已提交
1608
            public void run() {
1609
                tcpConsumerReady = true;
W
weijun 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
                while (true) {
                    try {
                        Socket socket = tcp.accept();
                        System.out.println("-----------------------------------------------");
                        System.out.println(">>>>> TCP connection established");
                        DataInputStream in = new DataInputStream(socket.getInputStream());
                        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                        byte[] token = new byte[in.readInt()];
                        in.readFully(token);
                        q.put(new Job(processMessage(token), socket, out));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
1626 1627
        thread2.setDaemon(asDaemon);
        thread2.start();
W
weijun 已提交
1628 1629

        // The dispatcher
1630
        thread3 = new Thread() {
W
weijun 已提交
1631
            public void run() {
1632
                dispatcherReady = true;
W
weijun 已提交
1633 1634 1635 1636 1637 1638 1639 1640
                while (true) {
                    try {
                        q.take().send();
                    } catch (Exception e) {
                    }
                }
            }
        };
1641 1642
        thread3.setDaemon(true);
        thread3.start();
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653

        // wait for the KDC is ready
        try {
            while (!isReady()) {
                Thread.sleep(100);
            }
        } catch(InterruptedException e) {
            throw new IOException(e);
        }
    }

1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
    public void kinit(String user, String ccache) throws Exception {
        if (user.indexOf('@') < 0) {
            user = user + "@" + realm;
        }
        if (nativeKdc != null) {
            nativeKdc.kinit(user, ccache);
        } else {
            Context.fromUserPass(user, passwords.get(user), false)
                    .ccache(ccache);
        }
    }

1666 1667
    boolean isReady() {
        return udpConsumerReady && tcpConsumerReady && dispatcherReady;
W
weijun 已提交
1668 1669
    }

1670
    public void terminate() {
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
        if (nativeKdc != null) {
            System.out.println("Killing kdc...");
            kdcProc.destroyForcibly();
            System.out.println("Done");
        } else {
            try {
                thread1.stop();
                thread2.stop();
                thread3.stop();
                u1.close();
                t1.close();
            } catch (Exception e) {
                // OK
            }
1685 1686
        }
    }
1687

1688
    public static KDC startKDC(final String host, final String krbConfFileName,
1689 1690 1691
            final String realm, final Map<String, String> principals,
            final String ktab, final KtabMode mode) {

1692
        KDC kdc;
1693
        try {
1694
            kdc = KDC.create(realm, host, 0, true);
1695
            kdc.setOption(KDC.Option.PREAUTH_REQUIRED, Boolean.FALSE);
1696 1697 1698
            if (krbConfFileName != null) {
                KDC.saveConfig(krbConfFileName, kdc);
            }
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749

            // Add principals
            if (principals != null) {
                principals.forEach((name, password) -> {
                    if (password == null || password.isEmpty()) {
                        System.out.println(String.format(
                                "KDC:add a principal '%s' with a random " +
                                        "password", name));
                        kdc.addPrincipalRandKey(name);
                    } else {
                        System.out.println(String.format(
                                "KDC:add a principal '%s' with '%s' password",
                                name, password));
                        kdc.addPrincipal(name, password.toCharArray());
                    }
                });
            }

            // Create or append keys to existing keytab file
            if (ktab != null) {
                File ktabFile = new File(ktab);
                switch(mode) {
                    case APPEND:
                        if (ktabFile.exists()) {
                            System.out.println(String.format(
                                    "KDC:append keys to an exising keytab "
                                    + "file %s", ktab));
                            kdc.appendKtab(ktab);
                        } else {
                            System.out.println(String.format(
                                    "KDC:create a new keytab file %s", ktab));
                            kdc.writeKtab(ktab);
                        }
                        break;
                    case EXISTING:
                        System.out.println(String.format(
                                "KDC:use an existing keytab file %s", ktab));
                        break;
                    default:
                        throw new RuntimeException(String.format(
                                "KDC:unsupported keytab mode: %s", mode));
                }
            }

            System.out.println(String.format(
                    "KDC: started on %s:%s with '%s' realm",
                    host, kdc.getPort(), realm));
        } catch (Exception e) {
            throw new RuntimeException("KDC: unexpected exception", e);
        }

1750
        return kdc;
1751 1752
    }

W
weijun 已提交
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
    /**
     * Helper class to encapsulate a job in a KDC.
     */
    private static class Job {
        byte[] token;           // The received request at creation time and
                                // the response at send time
        Socket s;               // The TCP socket from where the request comes
        DataOutputStream out;   // The OutputStream of the TCP socket
        DatagramSocket s2;      // The UDP socket from where the request comes
        DatagramPacket dp;      // The incoming UDP datagram packet
        boolean useTCP;         // Whether TCP or UDP is used

        // Creates a job object for TCP
        Job(byte[] token, Socket s, DataOutputStream out) {
            useTCP = true;
            this.token = token;
            this.s = s;
            this.out = out;
        }

        // Creates a job object for UDP
        Job(byte[] token, DatagramSocket s2, DatagramPacket dp) {
            useTCP = false;
            this.token = token;
            this.s2 = s2;
            this.dp = dp;
        }

        // Sends the output back to the client
        void send() {
            try {
                if (useTCP) {
                    System.out.println(">>>>> TCP request honored");
                    out.writeInt(token.length);
                    out.write(token);
                    s.close();
                } else {
                    System.out.println(">>>>> UDP request honored");
                    s2.send(new DatagramPacket(token, token.length, dp.getAddress(), dp.getPort()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
W
weijun 已提交
1798 1799

    public static class KDCNameService implements NameServiceDescriptor {
1800 1801 1802

        public static String NOT_EXISTING_HOST = "not.existing.host";

W
weijun 已提交
1803 1804 1805 1806 1807 1808
        @Override
        public NameService createNameService() throws Exception {
            NameService ns = new NameService() {
                @Override
                public InetAddress[] lookupAllHostAddr(String host)
                        throws UnknownHostException {
1809 1810 1811 1812 1813
                    // Everything is localhost except NOT_EXISTING_HOST
                    if (NOT_EXISTING_HOST.equals(host)) {
                        throw new UnknownHostException("Unknown host name: "
                                + NOT_EXISTING_HOST);
                    }
W
weijun 已提交
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
                    return new InetAddress[]{
                        InetAddress.getByAddress(host, new byte[]{127,0,0,1})
                    };
                }
                @Override
                public String getHostByAddr(byte[] addr)
                        throws UnknownHostException {
                    // No reverse lookup, PrincipalName use original string
                    throw new UnknownHostException();
                }
            };
            return ns;
        }

        @Override
        public String getProviderName() {
            return "mock";
        }

        @Override
        public String getType() {
            return "ns";
        }
    }
1838

1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    /**
     * A native KDC using the binaries in nativePath. Attention:
     * this is using binaries, not an existing KDC instance.
     * An implementation of this takes care of configuration,
     * principal db managing and KDC startup.
     */
    static abstract class NativeKdc {

        protected Map<String,String> env;
        protected String nativePath;
        protected String base;
        protected String realm;
        protected int port;

        NativeKdc(String nativePath, KDC kdc) {
            if (kdc.port == 0) {
                kdc.port = 8000 + new java.util.Random().nextInt(10000);
            }
            this.nativePath = nativePath;
            this.realm = kdc.realm;
            this.port = kdc.port;
            this.base = Paths.get("" + port).toAbsolutePath().toString();
        }

        // Add a new principal
        abstract void addPrincipal(String user, String pass);
        // Add a keytab entry
        abstract void ktadd(String user, String ktab);
        // Initialize KDC
        abstract void init();
        // Start kdc
        abstract Process kdc();
        // Configuration
        abstract void prepare();
        // Fill ccache
        abstract void kinit(String user, String ccache);

        static NativeKdc get(KDC kdc) {
            String prop = System.getProperty("native.kdc.path");
            if (prop == null) {
                return null;
            } else if (Files.exists(Paths.get(prop, "sbin/krb5kdc"))) {
                return new MIT(true, prop, kdc);
            } else if (Files.exists(Paths.get(prop, "kdc/krb5kdc"))) {
                return new MIT(false, prop, kdc);
            } else if (Files.exists(Paths.get(prop, "libexec/kdc"))) {
                return new Heimdal(prop, kdc);
            } else {
                throw new IllegalArgumentException("Strange " + prop);
            }
        }

        Process run(boolean wait, String... cmd) {
            try {
                System.out.println("Running " + cmd2str(env, cmd));
                ProcessBuilder pb = new ProcessBuilder();
                pb.inheritIO();
                pb.environment().putAll(env);
                Process p = pb.command(cmd).start();
                if (wait) {
                    if (p.waitFor() < 0) {
                        throw new RuntimeException("exit code is not null");
                    }
                    return null;
                } else {
                    return p;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        private String cmd2str(Map<String,String> env, String... cmd) {
            return env.entrySet().stream().map(e -> e.getKey()+"="+e.getValue())
                    .collect(Collectors.joining(" ")) + " " +
                    Stream.of(cmd).collect(Collectors.joining(" "));
        }
    }

    // Heimdal KDC. Build your own and run "make install" to nativePath.
    static class Heimdal extends NativeKdc {

        Heimdal(String nativePath, KDC kdc) {
            super(nativePath, kdc);
            Map<String, String> environment = new HashMap<>();
            environment.put("KRB5_CONFIG", base + "/krb5.conf");
            environment.put("KRB5_TRACE", "/dev/stderr");
            environment.put("DYLD_LIBRARY_PATH", nativePath + "/lib");
            environment.put("LD_LIBRARY_PATH", nativePath + "/lib");
            this.env = Collections.unmodifiableMap(environment);
        }

        @Override
        public void addPrincipal(String user, String pass) {
            run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,
                    "add", "-p", pass, "--use-defaults", user);
        }

        @Override
        public void ktadd(String user, String ktab) {
            run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,
                    "ext_keytab", "-k", ktab, user);
        }

        @Override
        public void init() {
            run(true, nativePath + "/bin/kadmin",  "-l",  "-r", realm,
                    "init", "--realm-max-ticket-life=1day",
                    "--realm-max-renewable-life=1month", realm);
        }

        @Override
        public Process kdc() {
            return run(false, nativePath + "/libexec/kdc",
                    "--addresses=127.0.0.1", "-P", "" + port);
        }

        @Override
        public void prepare() {
            try {
                Files.createDirectory(Paths.get(base));
                Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(
                        "[libdefaults]",
                        "default_realm = " + realm,
                        "default_keytab_name = FILE:" + base + "/krb5.keytab",
                        "forwardable = true",
                        "dns_lookup_kdc = no",
                        "dns_lookup_realm = no",
                        "dns_canonicalize_hostname = false",
                        "\n[realms]",
                        realm + " = {",
                        "  kdc = localhost:" + port,
                        "}",
                        "\n[kdc]",
                        "db-dir = " + base,
                        "database = {",
                        "    label = {",
                        "        dbname = " + base + "/current-db",
                        "        realm = " + realm,
                        "        mkey_file = " + base + "/mkey.file",
                        "        acl_file = " + base + "/heimdal.acl",
                        "        log_file = " + base + "/current.log",
                        "    }",
                        "}",
                        SUPPORTED_ETYPES == null ? ""
                                : ("\n[kadmin]\ndefault_keys = "
                                + (SUPPORTED_ETYPES + ",")
                                        .replaceAll(",", ":pw-salt ")),
                        "\n[logging]",
                        "kdc = 0-/FILE:" + base + "/messages.log",
                        "krb5 = 0-/FILE:" + base + "/messages.log",
                        "default = 0-/FILE:" + base + "/messages.log"
                ));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        @Override
        void kinit(String user, String ccache) {
            String tmpName = base + "/" + user + "." +
                    System.identityHashCode(this) + ".keytab";
            ktadd(user, tmpName);
            run(true, nativePath + "/bin/kinit",
                    "-f", "-t", tmpName, "-c", ccache, user);
        }
    }

    // MIT krb5 KDC. Make your own exploded (install == false), or
    // "make install" into nativePath (install == true).
    static class MIT extends NativeKdc {

        private boolean install; // "make install" or "make"

        MIT(boolean install, String nativePath, KDC kdc) {
            super(nativePath, kdc);
            this.install = install;
            Map<String, String> environment = new HashMap<>();
            environment.put("KRB5_KDC_PROFILE", base + "/kdc.conf");
            environment.put("KRB5_CONFIG", base + "/krb5.conf");
            environment.put("KRB5_TRACE", "/dev/stderr");
            environment.put("DYLD_LIBRARY_PATH", nativePath + "/lib");
            environment.put("LD_LIBRARY_PATH", nativePath + "/lib");
            this.env = Collections.unmodifiableMap(environment);
        }

        @Override
        public void addPrincipal(String user, String pass) {
            run(true, nativePath +
                    (install ? "/sbin/" : "/kadmin/cli/") + "kadmin.local",
                    "-q", "addprinc -pw " + pass + " " + user);
        }

        @Override
        public void ktadd(String user, String ktab) {
            run(true, nativePath +
                    (install ? "/sbin/" : "/kadmin/cli/") + "kadmin.local",
                    "-q", "ktadd -k " + ktab + " -norandkey " + user);
        }

        @Override
        public void init() {
            run(true, nativePath +
                    (install ? "/sbin/" : "/kadmin/dbutil/") + "kdb5_util",
                    "create", "-s", "-W", "-P", "olala");
        }

        @Override
        public Process kdc() {
            return run(false, nativePath +
                    (install ? "/sbin/" : "/kdc/") + "krb5kdc",
                    "-n");
        }

        @Override
        public void prepare() {
            try {
                Files.createDirectory(Paths.get(base));
                Files.write(Paths.get(base + "/kdc.conf"), Arrays.asList(
                        "[kdcdefaults]",
                        "\n[realms]",
                        realm + "= {",
                        "  kdc_listen = " + this.port,
                        "  kdc_tcp_listen = " + this.port,
                        "  database_name = " + base + "/principal",
                        "  key_stash_file = " + base + "/.k5.ATHENA.MIT.EDU",
                        SUPPORTED_ETYPES == null ? ""
                                : ("  supported_enctypes = "
                                + (SUPPORTED_ETYPES + ",")
                                        .replaceAll(",", ":normal ")),
                        "}"
                ));
                Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(
                        "[libdefaults]",
                        "default_realm = " + realm,
                        "default_keytab_name = FILE:" + base + "/krb5.keytab",
                        "forwardable = true",
                        "dns_lookup_kdc = no",
                        "dns_lookup_realm = no",
                        "dns_canonicalize_hostname = false",
                        "\n[realms]",
                        realm + " = {",
                        "  kdc = localhost:" + port,
                        "}",
                        "\n[logging]",
                        "kdc = FILE:" + base + "/krb5kdc.log"
                ));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        @Override
        void kinit(String user, String ccache) {
            String tmpName = base + "/" + user + "." +
                    System.identityHashCode(this) + ".keytab";
            ktadd(user, tmpName);
            run(true, nativePath +
                    (install ? "/bin/" : "/clients/kinit/") + "kinit",
                    "-f", "-t", tmpName, "-c", ccache, user);
        }
    }

2102 2103 2104 2105 2106
    // Calling private methods thru reflections
    private static final Field getPADataField;
    private static final Field getEType;
    private static final Constructor<EncryptedData> ctorEncryptedData;
    private static final Method stringToKey;
2107
    private static final Field getAddlTkt;
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120

    static {
        try {
            ctorEncryptedData = EncryptedData.class.getDeclaredConstructor(DerValue.class);
            ctorEncryptedData.setAccessible(true);
            getPADataField = KDCReq.class.getDeclaredField("pAData");
            getPADataField.setAccessible(true);
            getEType = KDCReqBody.class.getDeclaredField("eType");
            getEType.setAccessible(true);
            stringToKey = EncryptionKey.class.getDeclaredMethod(
                    "stringToKey",
                    char[].class, String.class, byte[].class, Integer.TYPE);
            stringToKey.setAccessible(true);
2121 2122
            getAddlTkt = KDCReqBody.class.getDeclaredField("additionalTickets");
            getAddlTkt.setAccessible(true);
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
        } catch (NoSuchFieldException nsfe) {
            throw new AssertionError(nsfe);
        } catch (NoSuchMethodException nsme) {
            throw new AssertionError(nsme);
        }
    }
    private EncryptedData newEncryptedData(DerValue der) {
        try {
            return ctorEncryptedData.newInstance(der);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
2136
    private static PAData[] KDCReqDotPAData(KDCReq req) {
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
        try {
            return (PAData[])getPADataField.get(req);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
    private static int[] KDCReqBodyDotEType(KDCReqBody body) {
        try {
            return (int[]) getEType.get(body);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
    private static byte[] EncryptionKeyDotStringToKey(char[] password, String salt,
            byte[] s2kparams, int keyType) throws KrbCryptoException {
        try {
            return (byte[])stringToKey.invoke(
                    null, password, salt, s2kparams, keyType);
        } catch (InvocationTargetException ex) {
            throw (KrbCryptoException)ex.getCause();
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
2161 2162 2163 2164 2165 2166 2167
    private static Ticket KDCReqBodyDotFirstAdditionalTicket(KDCReqBody body) {
        try {
            return ((Ticket[])getAddlTkt.get(body))[0];
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
W
weijun 已提交
2168
}