1 /*
2  * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 import jdk.test.lib.Platform;
25 
26 import java.lang.reflect.Constructor;
27 import java.lang.reflect.Field;
28 import java.lang.reflect.InvocationTargetException;
29 import java.net.*;
30 import java.io.*;
31 import java.lang.reflect.Method;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import java.util.*;
35 import java.util.concurrent.*;
36 import java.util.stream.Collectors;
37 import java.util.stream.Stream;
38 
39 import sun.security.krb5.*;
40 import sun.security.krb5.internal.*;
41 import sun.security.krb5.internal.ccache.CredentialsCache;
42 import sun.security.krb5.internal.crypto.EType;
43 import sun.security.krb5.internal.crypto.KeyUsage;
44 import sun.security.krb5.internal.ktab.KeyTab;
45 import sun.security.util.DerInputStream;
46 import sun.security.util.DerOutputStream;
47 import sun.security.util.DerValue;
48 
49 /**
50  * A KDC server.
51  *
52  * Note: By setting the system property native.kdc.path to a native
53  * krb5 installation, this class starts a native KDC with the
54  * given realm and host. It can also add new principals and save keytabs.
55  * Other features might not be available.
56  * <p>
57  * Features:
58  * <ol>
59  * <li> Supports TCP and UDP
60  * <li> Supports AS-REQ and TGS-REQ
61  * <li> Principal db and other settings hard coded in application
62  * <li> Options, say, request preauth or not
63  * </ol>
64  * Side effects:
65  * <ol>
66  * <li> The Sun-internal class <code>sun.security.krb5.Config</code> is a
67  * singleton and initialized according to Kerberos settings (krb5.conf and
68  * java.security.krb5.* system properties). This means once it's initialized
69  * it will not automatically notice any changes to these settings (or file
70  * changes of krb5.conf). The KDC class normally does not touch these
71  * settings (except for the <code>writeKtab()</code> method). However, to make
72  * sure nothing ever goes wrong, if you want to make any changes to these
73  * settings after calling a KDC method, call <code>Config.refresh()</code> to
74  * make sure your changes are reflected in the <code>Config</code> object.
75  * </ol>
76  * System properties recognized:
77  * <ul>
78  * <li>test.kdc.save.ccache
79  * </ul>
80  * Issues and TODOs:
81  * <ol>
82  * <li> Generates krb5.conf to be used on another machine, currently the kdc is
83  * always localhost
84  * <li> More options to KDC, say, error output, say, response nonce !=
85  * request nonce
86  * </ol>
87  * Note: This program uses internal krb5 classes (including reflection to
88  * access private fields and methods).
89  * <p>
90  * Usages:
91  * <p>
92  * 1. Init and start the KDC:
93  * <pre>
94  * KDC kdc = KDC.create("REALM.NAME", port, isDaemon);
95  * KDC kdc = KDC.create("REALM.NAME");
96  * </pre>
97  * Here, <code>port</code> is the UDP and TCP port number the KDC server
98  * listens on. If zero, a random port is chosen, which you can use getPort()
99  * later to retrieve the value.
100  * <p>
101  * If <code>isDaemon</code> is true, the KDC worker threads will be daemons.
102  * <p>
103  * The shortcut <code>KDC.create("REALM.NAME")</code> has port=0 and
104  * isDaemon=false, and is commonly used in an embedded KDC.
105  * <p>
106  * 2. Adding users:
107  * <pre>
108  * kdc.addPrincipal(String principal_name, char[] password);
109  * kdc.addPrincipalRandKey(String principal_name);
110  * </pre>
111  * A service principal's name should look like "host/f.q.d.n". The second form
112  * generates a random key. To expose this key, call <code>writeKtab()</code> to
113  * save the keys into a keytab file.
114  * <p>
115  * Note that you need to add the principal name krbtgt/REALM.NAME yourself.
116  * <p>
117  * Note that you can safely add a principal at any time after the KDC is
118  * started and before a user requests info on this principal.
119  * <p>
120  * 3. Other public methods:
121  * <ul>
122  * <li> <code>getPort</code>: Returns the port number the KDC uses
123  * <li> <code>getRealm</code>: Returns the realm name
124  * <li> <code>writeKtab</code>: Writes all principals' keys into a keytab file
125  * <li> <code>saveConfig</code>: Saves a krb5.conf file to access this KDC
126  * <li> <code>setOption</code>: Sets various options
127  * </ul>
128  * Read the javadoc for details. Lazy developer can use <code>OneKDC</code>
129  * directly.
130  */
131 public class KDC {
132 
133     public static final int DEFAULT_LIFETIME = 39600;
134     public static final int DEFAULT_RENEWTIME = 86400;
135 
136     public static final String NOT_EXISTING_HOST = "not.existing.host";
137 
138     // What etypes the KDC supports. Comma-separated strings. Null for all.
139     // Please note native KDCs might use different names.
140     private static final String SUPPORTED_ETYPES
141             = System.getProperty("kdc.supported.enctypes");
142 
143     // The native KDC
144     private final NativeKdc nativeKdc;
145 
146     // The native KDC process
147     private Process kdcProc = null;
148 
149     // Under the hood.
150 
151     // Principal db. principal -> pass. A case-insensitive TreeMap is used
152     // so that even if the client provides a name with different case, the KDC
153     // can still locate the principal and give back correct salt.
154     private TreeMap<String,char[]> passwords = new TreeMap<>
155             (String.CASE_INSENSITIVE_ORDER);
156 
157     // Non default salts. Precisely, there should be different salts for
158     // different etypes, pretend they are the same at the moment.
159     private TreeMap<String,String> salts = new TreeMap<>
160             (String.CASE_INSENSITIVE_ORDER);
161 
162     // Non default s2kparams for newer etypes. Precisely, there should be
163     // different s2kparams for different etypes, pretend they are the same
164     // at the moment.
165     private TreeMap<String,byte[]> s2kparamses = new TreeMap<>
166             (String.CASE_INSENSITIVE_ORDER);
167 
168     // Alias for referrals.
169     private TreeMap<String,KDC> aliasReferrals = new TreeMap<>
170             (String.CASE_INSENSITIVE_ORDER);
171 
172     // Alias for local resolution.
173     private TreeMap<String,PrincipalName> alias2Principals = new TreeMap<>
174             (String.CASE_INSENSITIVE_ORDER);
175 
176     // Realm name
177     private String realm;
178     // KDC
179     private String kdc;
180     // Service port number
181     private int port;
182     // The request/response job queue
183     private BlockingQueue<Job> q = new ArrayBlockingQueue<>(100);
184     // Options
185     private Map<Option,Object> options = new HashMap<>();
186     // Realm-specific krb5.conf settings
187     private List<String> conf = new ArrayList<>();
188 
189     private Thread thread1, thread2, thread3;
190     private volatile boolean udpConsumerReady = false;
191     private volatile boolean tcpConsumerReady = false;
192     private volatile boolean dispatcherReady = false;
193     DatagramSocket u1 = null;
194     ServerSocket t1 = null;
195 
196     public static enum KtabMode { APPEND, EXISTING };
197 
198     /**
199      * Option names, to be expanded forever.
200      */
201     public static enum Option {
202         /**
203          * Whether pre-authentication is required. Default Boolean.TRUE
204          */
205         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         RC4_FIRST_PREAUTH,
214         /**
215          * Use only one preauth, so that some keys are not easy to generate
216          */
217         ONLY_ONE_PREAUTH,
218         /**
219          * Set all name-type to a value in response
220          */
221         RESP_NT,
222         /**
223          * Multiple ETYPE-INFO-ENTRY with same etype but different salt
224          */
225         DUP_ETYPE,
226         /**
227          * What backend server can be delegated to
228          */
229         OK_AS_DELEGATE,
230         /**
231          * Allow S4U2self, List<String> of middle servers.
232          * If not set, means KDC does not understand S4U2self at all, therefore
233          * would ignore any PA-FOR-USER request and send a ticket using the
234          * cname of teh requestor. If set, it returns FORWARDABLE tickets to
235          * a server with its name in the list
236          */
237         ALLOW_S4U2SELF,
238         /**
239          * Allow S4U2proxy, Map<String,List<String>> of middle servers to
240          * backends. If not set or a backend not in a server's list,
241          * Krb5.KDC_ERR_POLICY will be send for S4U2proxy request.
242          */
243         ALLOW_S4U2PROXY,
244         /**
245          * Sensitive accounts can never be delegated.
246          */
247         SENSITIVE_ACCOUNTS,
248         /**
249          * If true, will check if TGS-REQ contains a non-null addresses field.
250          */
251         CHECK_ADDRESSES,
252     };
253 
254     /**
255      * A standalone KDC server.
256      */
main(String[] args)257     public static void main(String[] args) throws Exception {
258         int port = args.length > 0 ? Integer.parseInt(args[0]) : 0;
259         KDC kdc = create("RABBIT.HOLE", "kdc.rabbit.hole", port, false);
260         kdc.addPrincipal("dummy", "bogus".toCharArray());
261         kdc.addPrincipal("foo", "bar".toCharArray());
262         kdc.addPrincipalRandKey("krbtgt/RABBIT.HOLE");
263         kdc.addPrincipalRandKey("server/host.rabbit.hole");
264         kdc.addPrincipalRandKey("backend/host.rabbit.hole");
265         KDC.saveConfig("krb5.conf", kdc, "forwardable = true");
266     }
267 
268     /**
269      * Creates and starts a KDC running as a daemon on a random port.
270      * @param realm the realm name
271      * @return the running KDC instance
272      * @throws java.io.IOException for any socket creation error
273      */
create(String realm)274     public static KDC create(String realm) throws IOException {
275         return create(realm, "kdc." + realm.toLowerCase(Locale.US), 0, true);
276     }
277 
existing(String realm, String kdc, int port)278     public static KDC existing(String realm, String kdc, int port) {
279         KDC k = new KDC(realm, kdc);
280         k.port = port;
281         return k;
282     }
283 
284     /**
285      * Creates and starts a KDC server.
286      * @param realm the realm name
287      * @param port the TCP and UDP port to listen to. A random port will to
288      *        chosen if zero.
289      * @param asDaemon if true, KDC threads will be daemons. Otherwise, not.
290      * @return the running KDC instance
291      * @throws java.io.IOException for any socket creation error
292      */
create(String realm, String kdc, int port, boolean asDaemon)293     public static KDC create(String realm, String kdc, int port,
294                              boolean asDaemon) throws IOException {
295         return new KDC(realm, kdc, port, asDaemon);
296     }
297 
298     /**
299      * Sets an option
300      * @param key the option name
301      * @param value the value
302      */
setOption(Option key, Object value)303     public void setOption(Option key, Object value) {
304         if (value == null) {
305             options.remove(key);
306         } else {
307             options.put(key, value);
308         }
309     }
310 
311     /**
312      * Writes or appends keys into a keytab.
313      * <p>
314      * Attention: This is the most basic one of a series of methods below on
315      * keytab creation or modification. All these methods reference krb5.conf
316      * settings. If you need to modify krb5.conf or switch to another krb5.conf
317      * later, please call <code>Config.refresh()</code> again. For example:
318      * <pre>
319      * kdc.writeKtab("/etc/kdc/ktab", true);  // Config is initialized,
320      * System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf");
321      * Config.refresh();
322      * </pre>
323      * Inside this method there are 2 places krb5.conf is used:
324      * <ol>
325      * <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys
326      * <li> (Has workaround) Creating PrincipalName
327      * </ol>
328      * @param tab the keytab file name
329      * @param append true if append, otherwise, overwrite.
330      * @param names the names to write into, write all if names is empty
331      */
writeKtab(String tab, boolean append, String... names)332     public void writeKtab(String tab, boolean append, String... names)
333             throws IOException, KrbException {
334         KeyTab ktab = null;
335         if (nativeKdc == null) {
336             ktab = append ? KeyTab.getInstance(tab) : KeyTab.create(tab);
337         }
338         Iterable<String> entries =
339                 (names.length != 0) ? Arrays.asList(names): passwords.keySet();
340         for (String name : entries) {
341             if (name.indexOf('@') < 0) {
342                 name = name + "@" + realm;
343             }
344             if (nativeKdc == null) {
345                 char[] pass = passwords.get(name);
346                 int kvno = 0;
347                 if (Character.isDigit(pass[pass.length - 1])) {
348                     kvno = pass[pass.length - 1] - '0';
349                 }
350                 PrincipalName pn = new PrincipalName(name,
351                         name.indexOf('/') < 0 ?
352                                 PrincipalName.KRB_NT_UNKNOWN :
353                                 PrincipalName.KRB_NT_SRV_HST);
354                 ktab.addEntry(pn,
355                         getSalt(pn),
356                         pass,
357                         kvno,
358                         true);
359             } else {
360                 nativeKdc.ktadd(name, tab);
361             }
362         }
363         if (nativeKdc == null) {
364             ktab.save();
365         }
366     }
367 
368     /**
369      * Writes all principals' keys from multiple KDCs into one keytab file.
370      * @throws java.io.IOException for any file output error
371      * @throws sun.security.krb5.KrbException for any realm and/or principal
372      *         name error.
373      */
writeMultiKtab(String tab, KDC... kdcs)374     public static void writeMultiKtab(String tab, KDC... kdcs)
375             throws IOException, KrbException {
376         KeyTab.create(tab).save();      // Empty the old keytab
377         appendMultiKtab(tab, kdcs);
378     }
379 
380     /**
381      * Appends all principals' keys from multiple KDCs to one keytab file.
382      */
appendMultiKtab(String tab, KDC... kdcs)383     public static void appendMultiKtab(String tab, KDC... kdcs)
384             throws IOException, KrbException {
385         for (KDC kdc: kdcs) {
386             kdc.writeKtab(tab, true);
387         }
388     }
389 
390     /**
391      * Write a ktab for this KDC.
392      */
writeKtab(String tab)393     public void writeKtab(String tab) throws IOException, KrbException {
394         writeKtab(tab, false);
395     }
396 
397     /**
398      * Appends keys in this KDC to a ktab.
399      */
appendKtab(String tab)400     public void appendKtab(String tab) throws IOException, KrbException {
401         writeKtab(tab, true);
402     }
403 
404     /**
405      * Adds a new principal to this realm with a given password.
406      * @param user the principal's name. For a service principal, use the
407      *        form of host/f.q.d.n
408      * @param pass the password for the principal
409      */
addPrincipal(String user, char[] pass)410     public void addPrincipal(String user, char[] pass) {
411         addPrincipal(user, pass, null, null);
412     }
413 
414     /**
415      * Adds a new principal to this realm with a given password.
416      * @param user the principal's name. For a service principal, use the
417      *        form of host/f.q.d.n
418      * @param pass the password for the principal
419      * @param salt the salt, or null if a default value will be used
420      * @param s2kparams the s2kparams, or null if a default value will be used
421      */
addPrincipal( String user, char[] pass, String salt, byte[] s2kparams)422     public void addPrincipal(
423             String user, char[] pass, String salt, byte[] s2kparams) {
424         if (user.indexOf('@') < 0) {
425             user = user + "@" + realm;
426         }
427         if (nativeKdc != null) {
428             if (!user.equals("krbtgt/" + realm)) {
429                 nativeKdc.addPrincipal(user, new String(pass));
430             }
431             passwords.put(user, new char[0]);
432         } else {
433             passwords.put(user, pass);
434             if (salt != null) {
435                 salts.put(user, salt);
436             }
437             if (s2kparams != null) {
438                 s2kparamses.put(user, s2kparams);
439             }
440         }
441     }
442 
443     /**
444      * Adds a new principal to this realm with a random password
445      * @param user the principal's name. For a service principal, use the
446      *        form of host/f.q.d.n
447      */
addPrincipalRandKey(String user)448     public void addPrincipalRandKey(String user) {
449         addPrincipal(user, randomPassword());
450     }
451 
452     /**
453      * Returns the name of this realm
454      * @return the name of this realm
455      */
getRealm()456     public String getRealm() {
457         return realm;
458     }
459 
460     /**
461      * Returns the name of kdc
462      * @return the name of kdc
463      */
getKDC()464     public String getKDC() {
465         return kdc;
466     }
467 
468     /**
469      * Add realm-specific krb5.conf setting
470      */
addConf(String s)471     public void addConf(String s) {
472         conf.add(s);
473     }
474 
475     /**
476      * Writes a krb5.conf for one or more KDC that includes KDC locations for
477      * each realm and the default realm name. You can also add extra strings
478      * into the file. The method should be called like:
479      * <pre>
480      *   KDC.saveConfig("krb5.conf", kdc1, kdc2, ..., line1, line2, ...);
481      * </pre>
482      * Here you can provide one or more kdc# and zero or more line# arguments.
483      * The line# will be put after [libdefaults] and before [realms]. Therefore
484      * you can append new lines into [libdefaults] and/or create your new
485      * stanzas as well. Note that a newline character will be appended to
486      * each line# argument.
487      * <p>
488      * For example:
489      * <pre>
490      * KDC.saveConfig("krb5.conf", this);
491      * </pre>
492      * generates:
493      * <pre>
494      * [libdefaults]
495      * default_realm = REALM.NAME
496      *
497      * [realms]
498      *   REALM.NAME = {
499      *     kdc = host:port_number
500      *     # realm-specific settings
501      *   }
502      * </pre>
503      *
504      * Another example:
505      * <pre>
506      * KDC.saveConfig("krb5.conf", kdc1, kdc2, "forwardable = true", "",
507      *         "[domain_realm]",
508      *         ".kdc1.com = KDC1.NAME");
509      * </pre>
510      * generates:
511      * <pre>
512      * [libdefaults]
513      * default_realm = KDC1.NAME
514      * forwardable = true
515      *
516      * [domain_realm]
517      * .kdc1.com = KDC1.NAME
518      *
519      * [realms]
520      *   KDC1.NAME = {
521      *     kdc = host:port1
522      *   }
523      *   KDC2.NAME = {
524      *     kdc = host:port2
525      *   }
526      * </pre>
527      * @param file the name of the file to write into
528      * @param kdc the first (and default) KDC
529      * @param more more KDCs or extra lines (in their appearing order) to
530      * insert into the krb5.conf file. This method reads each argument's type
531      * to determine what it's for. This argument can be empty.
532      * @throws java.io.IOException for any file output error
533      */
saveConfig(String file, KDC kdc, Object... more)534     public static void saveConfig(String file, KDC kdc, Object... more)
535             throws IOException {
536         StringBuffer sb = new StringBuffer();
537         sb.append("[libdefaults]\ndefault_realm = ");
538         sb.append(kdc.realm);
539         sb.append("\n");
540         for (Object o : more) {
541             if (o instanceof String) {
542                 sb.append(o);
543                 sb.append("\n");
544             }
545         }
546         sb.append("\n[realms]\n");
547         sb.append(kdc.realmLine());
548         for (Object o : more) {
549             if (o instanceof KDC) {
550                 sb.append(((KDC) o).realmLine());
551             }
552         }
553         Files.write(Paths.get(file), sb.toString().getBytes());
554     }
555 
556     /**
557      * Returns the service port of the KDC server.
558      * @return the KDC service port
559      */
getPort()560     public int getPort() {
561         return port;
562     }
563 
564     /**
565      * Register an alias name to be referred to a different KDC for
566      * resolution, according to RFC 6806.
567      * @param alias Alias name (i.e. user@REALM.COM).
568      * @param referredKDC KDC to which the alias is referred for resolution.
569      */
registerAlias(String alias, KDC referredKDC)570     public void registerAlias(String alias, KDC referredKDC) {
571         aliasReferrals.remove(alias);
572         aliasReferrals.put(alias, referredKDC);
573     }
574 
575     /**
576      * Register an alias to be resolved to a Principal Name locally,
577      * according to RFC 6806.
578      * @param alias Alias name (i.e. user@REALM.COM).
579      * @param user Principal Name to which the alias is resolved.
580      */
registerAlias(String alias, String user)581     public void registerAlias(String alias, String user)
582             throws RealmException {
583         alias2Principals.remove(alias);
584         alias2Principals.put(alias, new PrincipalName(user));
585     }
586 
587     // Private helper methods
588 
589     /**
590      * Private constructor, cannot be called outside.
591      * @param realm
592      */
KDC(String realm, String kdc)593     private KDC(String realm, String kdc) {
594         this.realm = realm;
595         this.kdc = kdc;
596         this.nativeKdc = null;
597     }
598 
599     /**
600      * A constructor that starts the KDC service also.
601      */
KDC(String realm, String kdc, int port, boolean asDaemon)602     protected KDC(String realm, String kdc, int port, boolean asDaemon)
603             throws IOException {
604         this.realm = realm;
605         this.kdc = kdc;
606         this.nativeKdc = NativeKdc.get(this);
607         startServer(port, asDaemon);
608     }
609     /**
610      * Generates a 32-char random password
611      * @return the password
612      */
randomPassword()613     private static char[] randomPassword() {
614         char[] pass = new char[32];
615         Random r = new Random();
616         for (int i=0; i<31; i++)
617             pass[i] = (char)('a' + r.nextInt(26));
618         // The last char cannot be a number, otherwise, keyForUser()
619         // believes it's a sign of kvno
620         pass[31] = 'Z';
621         return pass;
622     }
623 
624     /**
625      * Generates a random key for the given encryption type.
626      * @param eType the encryption type
627      * @return the generated key
628      * @throws sun.security.krb5.KrbException for unknown/unsupported etype
629      */
generateRandomKey(int eType)630     private static EncryptionKey generateRandomKey(int eType)
631             throws KrbException  {
632         return genKey0(randomPassword(), "NOTHING", null, eType, null);
633     }
634 
635     /**
636      * Returns the password for a given principal
637      * @param p principal
638      * @return the password
639      * @throws sun.security.krb5.KrbException when the principal is not inside
640      *         the database.
641      */
getPassword(PrincipalName p, boolean server)642     private char[] getPassword(PrincipalName p, boolean server)
643             throws KrbException {
644         String pn = p.toString();
645         if (p.getRealmString() == null) {
646             pn = pn + "@" + getRealm();
647         }
648         char[] pass = passwords.get(pn);
649         if (pass == null) {
650             throw new KrbException(server?
651                 Krb5.KDC_ERR_S_PRINCIPAL_UNKNOWN:
652                 Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN, pn.toString());
653         }
654         return pass;
655     }
656 
657     /**
658      * Returns the salt string for the principal.
659      * @param p principal
660      * @return the salt
661      */
getSalt(PrincipalName p)662     protected String getSalt(PrincipalName p) {
663         String pn = p.toString();
664         if (p.getRealmString() == null) {
665             pn = pn + "@" + getRealm();
666         }
667         if (salts.containsKey(pn)) {
668             return salts.get(pn);
669         }
670         if (passwords.containsKey(pn)) {
671             try {
672                 // Find the principal name with correct case.
673                 p = new PrincipalName(passwords.ceilingEntry(pn).getKey());
674             } catch (RealmException re) {
675                 // Won't happen
676             }
677         }
678         String s = p.getRealmString();
679         if (s == null) s = getRealm();
680         for (String n: p.getNameStrings()) {
681             s += n;
682         }
683         return s;
684     }
685 
686     /**
687      * Returns the s2kparams for the principal given the etype.
688      * @param p principal
689      * @param etype encryption type
690      * @return the s2kparams, might be null
691      */
getParams(PrincipalName p, int etype)692     protected byte[] getParams(PrincipalName p, int etype) {
693         switch (etype) {
694             case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:
695             case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:
696             case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:
697             case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:
698                 String pn = p.toString();
699                 if (p.getRealmString() == null) {
700                     pn = pn + "@" + getRealm();
701                 }
702                 if (s2kparamses.containsKey(pn)) {
703                     return s2kparamses.get(pn);
704                 }
705                 if (etype < EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128) {
706                     return new byte[]{0, 0, 0x10, 0};
707                 } else {
708                     return new byte[]{0, 0, (byte) 0x80, 0};
709                 }
710             default:
711                 return null;
712         }
713     }
714 
715     /**
716      * Returns the key for a given principal of the given encryption type
717      * @param p the principal
718      * @param etype the encryption type
719      * @param server looking for a server principal?
720      * @return the key
721      * @throws sun.security.krb5.KrbException for unknown/unsupported etype
722      */
keyForUser(PrincipalName p, int etype, boolean server)723     EncryptionKey keyForUser(PrincipalName p, int etype, boolean server)
724             throws KrbException {
725         try {
726             // Do not call EncryptionKey.acquireSecretKeys(), otherwise
727             // the krb5.conf config file would be loaded.
728             Integer kvno = null;
729             // For service whose password ending with a number, use it as kvno.
730             // Kvno must be postive.
731             if (p.toString().indexOf('/') > 0) {
732                 char[] pass = getPassword(p, server);
733                 if (Character.isDigit(pass[pass.length-1])) {
734                     kvno = pass[pass.length-1] - '0';
735                 }
736             }
737             return genKey0(getPassword(p, server), getSalt(p),
738                     getParams(p, etype), etype, kvno);
739         } catch (KrbException ke) {
740             throw ke;
741         } catch (Exception e) {
742             throw new RuntimeException(e);  // should not happen
743         }
744     }
745 
746     /**
747      * Returns a KerberosTime.
748      *
749      * @param offset offset from NOW in seconds
750      */
timeAfter(int offset)751     private static KerberosTime timeAfter(int offset) {
752         return new KerberosTime(new Date().getTime() + offset * 1000L);
753     }
754 
755     /**
756      * Generates key from password.
757      */
genKey0( char[] pass, String salt, byte[] s2kparams, int etype, Integer kvno)758     private static EncryptionKey genKey0(
759             char[] pass, String salt, byte[] s2kparams,
760             int etype, Integer kvno) throws KrbException {
761         return new EncryptionKey(EncryptionKeyDotStringToKey(
762                 pass, salt, s2kparams, etype),
763                 etype, kvno);
764     }
765 
766     /**
767      * Processes an incoming request and generates a response.
768      * @param in the request
769      * @return the response
770      * @throws java.lang.Exception for various errors
771      */
processMessage(byte[] in)772     protected byte[] processMessage(byte[] in) throws Exception {
773         if ((in[0] & 0x1f) == Krb5.KRB_AS_REQ)
774             return processAsReq(in);
775         else
776             return processTgsReq(in);
777     }
778 
779     /**
780      * Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR)
781      * @param in the request
782      * @return the response
783      * @throws java.lang.Exception for various errors
784      */
processTgsReq(byte[] in)785     protected byte[] processTgsReq(byte[] in) throws Exception {
786         TGSReq tgsReq = new TGSReq(in);
787         PrincipalName service = tgsReq.reqBody.sname;
788         if (options.containsKey(KDC.Option.RESP_NT)) {
789             service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),
790                     service.getNameStrings(), service.getRealm());
791         }
792         try {
793             System.out.println(realm + "> " + tgsReq.reqBody.cname +
794                     " sends TGS-REQ for " +
795                     service + ", " + tgsReq.reqBody.kdcOptions);
796             KDCReqBody body = tgsReq.reqBody;
797             int[] eTypes = filterSupported(KDCReqBodyDotEType(body));
798             if (eTypes.length == 0) {
799                 throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
800             }
801             int e2 = eTypes[0];     // etype for outgoing session key
802             int e3 = eTypes[0];     // etype for outgoing ticket
803 
804             PAData[] pas = tgsReq.pAData;
805 
806             Ticket tkt = null;
807             EncTicketPart etp = null;
808 
809             PrincipalName cname = null;
810             boolean allowForwardable = true;
811             boolean isReferral = false;
812             if (body.kdcOptions.get(KDCOptions.CANONICALIZE)) {
813                 System.out.println(realm + "> verifying referral for " +
814                         body.sname.getNameString());
815                 KDC referral = aliasReferrals.get(body.sname.getNameString());
816                 if (referral != null) {
817                     service = new PrincipalName(
818                             PrincipalName.TGS_DEFAULT_SRV_NAME +
819                             PrincipalName.NAME_COMPONENT_SEPARATOR_STR +
820                             referral.getRealm(), PrincipalName.KRB_NT_SRV_INST,
821                             this.getRealm());
822                     System.out.println(realm + "> referral to " +
823                             referral.getRealm());
824                     isReferral = true;
825                 }
826             }
827 
828             if (pas == null || pas.length == 0) {
829                 throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
830             } else {
831                 PrincipalName forUserCName = null;
832                 for (PAData pa: pas) {
833                     if (pa.getType() == Krb5.PA_TGS_REQ) {
834                         APReq apReq = new APReq(pa.getValue());
835                         tkt = apReq.ticket;
836                         int te = tkt.encPart.getEType();
837                         EncryptionKey kkey = keyForUser(tkt.sname, te, true);
838                         byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET);
839                         DerInputStream derIn = new DerInputStream(bb);
840                         DerValue der = derIn.getDerValue();
841                         etp = new EncTicketPart(der.toByteArray());
842                         // Finally, cname will be overwritten by PA-FOR-USER
843                         // if it exists.
844                         cname = etp.cname;
845                         System.out.println(realm + "> presenting a ticket of "
846                                 + etp.cname + " to " + tkt.sname);
847                     } else if (pa.getType() == Krb5.PA_FOR_USER) {
848                         if (options.containsKey(Option.ALLOW_S4U2SELF)) {
849                             PAForUserEnc p4u = new PAForUserEnc(
850                                     new DerValue(pa.getValue()), null);
851                             forUserCName = p4u.name;
852                             System.out.println(realm + "> See PA_FOR_USER "
853                                     + " in the name of " + p4u.name);
854                         }
855                     }
856                 }
857                 if (forUserCName != null) {
858                     List<String> names = (List<String>)
859                             options.get(Option.ALLOW_S4U2SELF);
860                     if (!names.contains(cname.toString())) {
861                         // Mimic the normal KDC behavior. When a server is not
862                         // allowed to send S4U2self, do not send an error.
863                         // Instead, send a ticket which is useless later.
864                         allowForwardable = false;
865                     }
866                     cname = forUserCName;
867                 }
868                 if (tkt == null) {
869                     throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
870                 }
871             }
872 
873             // Session key for original ticket, TGT
874             EncryptionKey ckey = etp.key;
875 
876             // Session key for session with the service
877             EncryptionKey key = generateRandomKey(e2);
878 
879             // Check time, TODO
880             KerberosTime from = body.from;
881             KerberosTime till = body.till;
882             if (from == null || from.isZero()) {
883                 from = timeAfter(0);
884             }
885             if (till == null) {
886                 throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
887             } else if (till.isZero()) {
888                 till = timeAfter(DEFAULT_LIFETIME);
889             }
890 
891             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
892             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)
893                     && allowForwardable) {
894                 List<String> sensitives = (List<String>)
895                         options.get(Option.SENSITIVE_ACCOUNTS);
896                 if (sensitives != null && sensitives.contains(cname.toString())) {
897                     // Cannot make FORWARDABLE
898                 } else {
899                     bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
900                 }
901             }
902             // We do not request for addresses for FORWARDED tickets
903             if (options.containsKey(Option.CHECK_ADDRESSES)
904                     && body.kdcOptions.get(KDCOptions.FORWARDED)
905                     && body.addresses != null) {
906                 throw new KrbException(Krb5.KDC_ERR_BADOPTION);
907             }
908             if (body.kdcOptions.get(KDCOptions.FORWARDED) ||
909                     etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {
910                 bFlags[Krb5.TKT_OPTS_FORWARDED] = true;
911             }
912             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
913                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
914                 //renew = timeAfter(3600 * 24 * 7);
915             }
916             if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
917                 bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
918             }
919             if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
920                 bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
921             }
922             if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
923                 bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
924             }
925             if (body.kdcOptions.get(KDCOptions.CNAME_IN_ADDL_TKT)) {
926                 if (!options.containsKey(Option.ALLOW_S4U2PROXY)) {
927                     // Don't understand CNAME_IN_ADDL_TKT
928                     throw new KrbException(Krb5.KDC_ERR_BADOPTION);
929                 } else {
930                     Map<String,List<String>> map = (Map<String,List<String>>)
931                             options.get(Option.ALLOW_S4U2PROXY);
932                     Ticket second = KDCReqBodyDotFirstAdditionalTicket(body);
933                     EncryptionKey key2 = keyForUser(
934                             second.sname, second.encPart.getEType(), true);
935                     byte[] bb = second.encPart.decrypt(key2, KeyUsage.KU_TICKET);
936                     DerInputStream derIn = new DerInputStream(bb);
937                     DerValue der = derIn.getDerValue();
938                     EncTicketPart tktEncPart = new EncTicketPart(der.toByteArray());
939                     if (!tktEncPart.flags.get(Krb5.TKT_OPTS_FORWARDABLE)) {
940                         //throw new KrbException(Krb5.KDC_ERR_BADOPTION);
941                     }
942                     PrincipalName client = tktEncPart.cname;
943                     System.out.println(realm + "> and an additional ticket of "
944                             + client + " to " + second.sname);
945                     if (map.containsKey(cname.toString())) {
946                         if (map.get(cname.toString()).contains(service.toString())) {
947                             System.out.println(realm + "> S4U2proxy OK");
948                         } else {
949                             throw new KrbException(Krb5.KDC_ERR_BADOPTION);
950                         }
951                     } else {
952                         throw new KrbException(Krb5.KDC_ERR_BADOPTION);
953                     }
954                     cname = client;
955                 }
956             }
957 
958             String okAsDelegate = (String)options.get(Option.OK_AS_DELEGATE);
959             if (okAsDelegate != null && (
960                     okAsDelegate.isEmpty() ||
961                     okAsDelegate.contains(service.getNameString()))) {
962                 bFlags[Krb5.TKT_OPTS_DELEGATE] = true;
963             }
964             bFlags[Krb5.TKT_OPTS_INITIAL] = true;
965 
966             KerberosTime renewTill = etp.renewTill;
967             if (renewTill != null && body.kdcOptions.get(KDCOptions.RENEW)) {
968                 // till should never pass renewTill
969                 if (till.greaterThan(renewTill)) {
970                     till = renewTill;
971                 }
972                 if (System.getProperty("test.set.null.renew") != null) {
973                     // Testing 8186576, see NullRenewUntil.java.
974                     renewTill = null;
975                 }
976             }
977 
978             TicketFlags tFlags = new TicketFlags(bFlags);
979             EncTicketPart enc = new EncTicketPart(
980                     tFlags,
981                     key,
982                     cname,
983                     new TransitedEncoding(1, new byte[0]),  // TODO
984                     timeAfter(0),
985                     from,
986                     till, renewTill,
987                     body.addresses != null ? body.addresses
988                             : etp.caddr,
989                     null);
990             EncryptionKey skey = keyForUser(service, e3, true);
991             if (skey == null) {
992                 throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
993             }
994             Ticket t = new Ticket(
995                     System.getProperty("test.kdc.diff.sname") != null ?
996                         new PrincipalName("xx" + service.toString()) :
997                         service,
998                     new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
999             );
1000             EncTGSRepPart enc_part = new EncTGSRepPart(
1001                     key,
1002                     new LastReq(new LastReqEntry[] {
1003                         new LastReqEntry(0, timeAfter(-10))
1004                     }),
1005                     body.getNonce(),    // TODO: detect replay
1006                     timeAfter(3600 * 24),
1007                     // Next 5 and last MUST be same with ticket
1008                     tFlags,
1009                     timeAfter(0),
1010                     from,
1011                     till, renewTill,
1012                     service,
1013                     body.addresses,
1014                     null
1015                     );
1016             EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(),
1017                     KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY);
1018             TGSRep tgsRep = new TGSRep(null,
1019                     cname,
1020                     t,
1021                     edata);
1022             System.out.println("     Return " + tgsRep.cname
1023                     + " ticket for " + tgsRep.ticket.sname + ", flags "
1024                     + tFlags);
1025 
1026             DerOutputStream out = new DerOutputStream();
1027             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
1028                     true, (byte)Krb5.KRB_TGS_REP), tgsRep.asn1Encode());
1029             return out.toByteArray();
1030         } catch (KrbException ke) {
1031             ke.printStackTrace(System.out);
1032             KRBError kerr = ke.getError();
1033             KDCReqBody body = tgsReq.reqBody;
1034             System.out.println("     Error " + ke.returnCode()
1035                     + " " +ke.returnCodeMessage());
1036             if (kerr == null) {
1037                 kerr = new KRBError(null, null, null,
1038                         timeAfter(0),
1039                         0,
1040                         ke.returnCode(),
1041                         body.cname,
1042                         service,
1043                         KrbException.errorMessage(ke.returnCode()),
1044                         null);
1045             }
1046             return kerr.asn1Encode();
1047         }
1048     }
1049 
1050     /**
1051      * Processes a AS_REQ and generates a AS_REP (or KRB_ERROR)
1052      * @param in the request
1053      * @return the response
1054      * @throws java.lang.Exception for various errors
1055      */
processAsReq(byte[] in)1056     protected byte[] processAsReq(byte[] in) throws Exception {
1057         ASReq asReq = new ASReq(in);
1058         byte[] asReqbytes = asReq.asn1Encode();
1059         int[] eTypes = null;
1060         List<PAData> outPAs = new ArrayList<>();
1061 
1062         PrincipalName service = asReq.reqBody.sname;
1063         if (options.containsKey(KDC.Option.RESP_NT)) {
1064             service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),
1065                     service.getNameStrings(),
1066                     Realm.getDefault());
1067         }
1068         try {
1069             System.out.println(realm + "> " + asReq.reqBody.cname +
1070                     " sends AS-REQ for " +
1071                     service + ", " + asReq.reqBody.kdcOptions);
1072 
1073             KDCReqBody body = asReq.reqBody;
1074 
1075             eTypes = filterSupported(KDCReqBodyDotEType(body));
1076             if (eTypes.length == 0) {
1077                 throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
1078             }
1079             int eType = eTypes[0];
1080 
1081             if (body.kdcOptions.get(KDCOptions.CANONICALIZE)) {
1082                 PrincipalName principal = alias2Principals.get(
1083                         body.cname.getNameString());
1084                 if (principal != null) {
1085                     body.cname = principal;
1086                 } else {
1087                     KDC referral = aliasReferrals.get(body.cname.getNameString());
1088                     if (referral != null) {
1089                         body.cname = new PrincipalName(
1090                                 PrincipalName.TGS_DEFAULT_SRV_NAME,
1091                                 PrincipalName.KRB_NT_SRV_INST,
1092                                 referral.getRealm());
1093                         throw new KrbException(Krb5.KRB_ERR_WRONG_REALM);
1094                     }
1095                 }
1096             }
1097 
1098             EncryptionKey ckey = keyForUser(body.cname, eType, false);
1099             EncryptionKey skey = keyForUser(service, eType, true);
1100 
1101             if (options.containsKey(KDC.Option.ONLY_RC4_TGT)) {
1102                 int tgtEType = EncryptedData.ETYPE_ARCFOUR_HMAC;
1103                 boolean found = false;
1104                 for (int i=0; i<eTypes.length; i++) {
1105                     if (eTypes[i] == tgtEType) {
1106                         found = true;
1107                         break;
1108                     }
1109                 }
1110                 if (!found) {
1111                     throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
1112                 }
1113                 skey = keyForUser(service, tgtEType, true);
1114             }
1115             if (ckey == null) {
1116                 throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
1117             }
1118             if (skey == null) {
1119                 throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO
1120             }
1121 
1122             // Session key
1123             EncryptionKey key = generateRandomKey(eType);
1124             // Check time, TODO
1125             KerberosTime from = body.from;
1126             KerberosTime till = body.till;
1127             KerberosTime rtime = body.rtime;
1128             if (from == null || from.isZero()) {
1129                 from = timeAfter(0);
1130             }
1131             if (till == null) {
1132                 throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO
1133             } else if (till.isZero()) {
1134                 till = timeAfter(DEFAULT_LIFETIME);
1135             } else if (till.greaterThan(timeAfter(24 * 3600))
1136                      && System.getProperty("test.kdc.force.till") == null) {
1137                 // If till is more than 1 day later, make it renewable
1138                 till = timeAfter(DEFAULT_LIFETIME);
1139                 body.kdcOptions.set(KDCOptions.RENEWABLE, true);
1140                 if (rtime == null) rtime = till;
1141             }
1142             if (rtime == null && body.kdcOptions.get(KDCOptions.RENEWABLE)) {
1143                 rtime = timeAfter(DEFAULT_RENEWTIME);
1144             }
1145             //body.from
1146             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
1147             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
1148                 List<String> sensitives = (List<String>)
1149                         options.get(Option.SENSITIVE_ACCOUNTS);
1150                 if (sensitives != null
1151                         && sensitives.contains(body.cname.toString())) {
1152                     // Cannot make FORWARDABLE
1153                 } else {
1154                     bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
1155                 }
1156             }
1157             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
1158                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
1159                 //renew = timeAfter(3600 * 24 * 7);
1160             }
1161             if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
1162                 bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
1163             }
1164             if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
1165                 bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
1166             }
1167             if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
1168                 bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
1169             }
1170             bFlags[Krb5.TKT_OPTS_INITIAL] = true;
1171 
1172             // Creating PA-DATA
1173             DerValue[] pas2 = null, pas = null;
1174             if (options.containsKey(KDC.Option.DUP_ETYPE)) {
1175                 int n = (Integer)options.get(KDC.Option.DUP_ETYPE);
1176                 switch (n) {
1177                     case 1:     // customer's case in 7067974
1178                         pas2 = new DerValue[] {
1179                             new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),
1180                             new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),
1181                             new DerValue(new ETypeInfo2(
1182                                     1, realm, new byte[]{1}).asn1Encode()),
1183                         };
1184                         pas = new DerValue[] {
1185                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1186                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1187                             new DerValue(new ETypeInfo(1, realm).asn1Encode()),
1188                         };
1189                         break;
1190                     case 2:     // we still reject non-null s2kparams and prefer E2 over E
1191                         pas2 = new DerValue[] {
1192                             new DerValue(new ETypeInfo2(
1193                                     1, realm, new byte[]{1}).asn1Encode()),
1194                             new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),
1195                             new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),
1196                         };
1197                         pas = new DerValue[] {
1198                             new DerValue(new ETypeInfo(1, realm).asn1Encode()),
1199                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1200                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1201                         };
1202                         break;
1203                     case 3:     // but only E is wrong
1204                         pas = new DerValue[] {
1205                             new DerValue(new ETypeInfo(1, realm).asn1Encode()),
1206                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1207                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1208                         };
1209                         break;
1210                     case 4:     // we also ignore rc4-hmac
1211                         pas = new DerValue[] {
1212                             new DerValue(new ETypeInfo(23, "ANYTHING").asn1Encode()),
1213                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1214                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1215                         };
1216                         break;
1217                     case 5:     // "" should be wrong, but we accept it now
1218                                 // See s.s.k.internal.PAData$SaltAndParams
1219                         pas = new DerValue[] {
1220                             new DerValue(new ETypeInfo(1, "").asn1Encode()),
1221                             new DerValue(new ETypeInfo(1, null).asn1Encode()),
1222                         };
1223                         break;
1224                 }
1225             } else {
1226                 int[] epas = eTypes;
1227                 if (options.containsKey(KDC.Option.RC4_FIRST_PREAUTH)) {
1228                     for (int i=1; i<epas.length; i++) {
1229                         if (epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC) {
1230                             epas[i] = epas[0];
1231                             epas[0] = EncryptedData.ETYPE_ARCFOUR_HMAC;
1232                             break;
1233                         }
1234                     };
1235                 } else if (options.containsKey(KDC.Option.ONLY_ONE_PREAUTH)) {
1236                     epas = new int[] { eTypes[0] };
1237                 }
1238                 pas2 = new DerValue[epas.length];
1239                 for (int i=0; i<epas.length; i++) {
1240                     pas2[i] = new DerValue(new ETypeInfo2(
1241                             epas[i],
1242                             epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?
1243                                 null : getSalt(body.cname),
1244                             getParams(body.cname, epas[i])).asn1Encode());
1245                 }
1246                 boolean allOld = true;
1247                 for (int i: eTypes) {
1248                     if (i >= EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 &&
1249                             i != EncryptedData.ETYPE_ARCFOUR_HMAC) {
1250                         allOld = false;
1251                         break;
1252                     }
1253                 }
1254                 if (allOld) {
1255                     pas = new DerValue[epas.length];
1256                     for (int i=0; i<epas.length; i++) {
1257                         pas[i] = new DerValue(new ETypeInfo(
1258                                 epas[i],
1259                                 epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?
1260                                     null : getSalt(body.cname)
1261                                 ).asn1Encode());
1262                     }
1263                 }
1264             }
1265 
1266             DerOutputStream eid;
1267             if (pas2 != null) {
1268                 eid = new DerOutputStream();
1269                 eid.putSequence(pas2);
1270                 outPAs.add(new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()));
1271             }
1272             if (pas != null) {
1273                 eid = new DerOutputStream();
1274                 eid.putSequence(pas);
1275                 outPAs.add(new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()));
1276             }
1277 
1278             PAData[] inPAs = asReq.pAData;
1279             List<PAData> enc_outPAs = new ArrayList<>();
1280 
1281             byte[] paEncTimestamp = null;
1282             if (inPAs != null) {
1283                 for (PAData inPA : inPAs) {
1284                     if (inPA.getType() == Krb5.PA_ENC_TIMESTAMP) {
1285                         paEncTimestamp = inPA.getValue();
1286                     }
1287                 }
1288             }
1289 
1290             if (paEncTimestamp == null) {
1291                 Object preauth = options.get(Option.PREAUTH_REQUIRED);
1292                 if (preauth == null || preauth.equals(Boolean.TRUE)) {
1293                     throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED);
1294                 }
1295             } else {
1296                 EncryptionKey pakey = null;
1297                 try {
1298                     EncryptedData data = newEncryptedData(
1299                             new DerValue(paEncTimestamp));
1300                     pakey = keyForUser(body.cname, data.getEType(), false);
1301                     data.decrypt(pakey, KeyUsage.KU_PA_ENC_TS);
1302                 } catch (Exception e) {
1303                     KrbException ke = new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED);
1304                     ke.initCause(e);
1305                     throw ke;
1306                 }
1307                 bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true;
1308                 for (PAData pa : inPAs) {
1309                     if (pa.getType() == Krb5.PA_REQ_ENC_PA_REP) {
1310                         Checksum ckSum = new Checksum(
1311                                 Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128,
1312                                 asReqbytes, ckey, KeyUsage.KU_AS_REQ);
1313                         enc_outPAs.add(new PAData(Krb5.PA_REQ_ENC_PA_REP,
1314                                 ckSum.asn1Encode()));
1315                         bFlags[Krb5.TKT_OPTS_ENC_PA_REP] = true;
1316                         break;
1317                     }
1318                 }
1319             }
1320 
1321             TicketFlags tFlags = new TicketFlags(bFlags);
1322             EncTicketPart enc = new EncTicketPart(
1323                     tFlags,
1324                     key,
1325                     body.cname,
1326                     new TransitedEncoding(1, new byte[0]),
1327                     timeAfter(0),
1328                     from,
1329                     till, rtime,
1330                     body.addresses,
1331                     null);
1332             Ticket t = new Ticket(
1333                     service,
1334                     new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)
1335             );
1336             EncASRepPart enc_part = new EncASRepPart(
1337                     key,
1338                     new LastReq(new LastReqEntry[]{
1339                         new LastReqEntry(0, timeAfter(-10))
1340                     }),
1341                     body.getNonce(),    // TODO: detect replay?
1342                     timeAfter(3600 * 24),
1343                     // Next 5 and last MUST be same with ticket
1344                     tFlags,
1345                     timeAfter(0),
1346                     from,
1347                     till, rtime,
1348                     service,
1349                     body.addresses,
1350                     enc_outPAs.toArray(new PAData[enc_outPAs.size()])
1351                     );
1352             EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(),
1353                     KeyUsage.KU_ENC_AS_REP_PART);
1354             ASRep asRep = new ASRep(
1355                     outPAs.toArray(new PAData[outPAs.size()]),
1356                     body.cname,
1357                     t,
1358                     edata);
1359 
1360             System.out.println("     Return " + asRep.cname
1361                     + " ticket for " + asRep.ticket.sname + ", flags "
1362                     + tFlags);
1363 
1364             DerOutputStream out = new DerOutputStream();
1365             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
1366                     true, (byte)Krb5.KRB_AS_REP), asRep.asn1Encode());
1367             byte[] result = out.toByteArray();
1368 
1369             // Added feature:
1370             // Write the current issuing TGT into a ccache file specified
1371             // by the system property below.
1372             String ccache = System.getProperty("test.kdc.save.ccache");
1373             if (ccache != null) {
1374                 asRep.encKDCRepPart = enc_part;
1375                 sun.security.krb5.internal.ccache.Credentials credentials =
1376                     new sun.security.krb5.internal.ccache.Credentials(asRep);
1377                 CredentialsCache cache =
1378                     CredentialsCache.create(asReq.reqBody.cname, ccache);
1379                 if (cache == null) {
1380                    throw new IOException("Unable to create the cache file " +
1381                                          ccache);
1382                 }
1383                 cache.update(credentials);
1384                 cache.save();
1385             }
1386 
1387             return result;
1388         } catch (KrbException ke) {
1389             ke.printStackTrace(System.out);
1390             KRBError kerr = ke.getError();
1391             KDCReqBody body = asReq.reqBody;
1392             System.out.println("     Error " + ke.returnCode()
1393                     + " " +ke.returnCodeMessage());
1394             byte[] eData = null;
1395             if (kerr == null) {
1396                 if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED ||
1397                         ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) {
1398                     outPAs.add(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]));
1399                 }
1400                 if (outPAs.size() > 0) {
1401                     DerOutputStream bytes = new DerOutputStream();
1402                     for (PAData p: outPAs) {
1403                         bytes.write(p.asn1Encode());
1404                     }
1405                     DerOutputStream temp = new DerOutputStream();
1406                     temp.write(DerValue.tag_Sequence, bytes);
1407                     eData = temp.toByteArray();
1408                 }
1409                 kerr = new KRBError(null, null, null,
1410                         timeAfter(0),
1411                         0,
1412                         ke.returnCode(),
1413                         body.cname,
1414                         service,
1415                         KrbException.errorMessage(ke.returnCode()),
1416                         eData);
1417             }
1418             return kerr.asn1Encode();
1419         }
1420     }
1421 
filterSupported(int[] input)1422     private int[] filterSupported(int[] input) {
1423         int count = 0;
1424         for (int i = 0; i < input.length; i++) {
1425             if (!EType.isSupported(input[i])) {
1426                 continue;
1427             }
1428             if (SUPPORTED_ETYPES != null) {
1429                 boolean supported = false;
1430                 for (String se : SUPPORTED_ETYPES.split(",")) {
1431                     if (Config.getType(se) == input[i]) {
1432                         supported = true;
1433                         break;
1434                     }
1435                 }
1436                 if (!supported) {
1437                     continue;
1438                 }
1439             }
1440             if (count != i) {
1441                 input[count] = input[i];
1442             }
1443             count++;
1444         }
1445         if (count != input.length) {
1446             input = Arrays.copyOf(input, count);
1447         }
1448         return input;
1449     }
1450 
1451     /**
1452      * Generates a line for a KDC to put inside [realms] of krb5.conf
1453      * @return REALM.NAME = { kdc = host:port etc }
1454      */
realmLine()1455     private String realmLine() {
1456         StringBuilder sb = new StringBuilder();
1457         sb.append(realm).append(" = {\n    kdc = ")
1458                 .append(kdc).append(':').append(port).append('\n');
1459         for (String s: conf) {
1460             sb.append("    ").append(s).append('\n');
1461         }
1462         return sb.append("}\n").toString();
1463     }
1464 
1465     /**
1466      * Start the KDC service. This server listens on both UDP and TCP using
1467      * the same port number. It uses three threads to deal with requests.
1468      * They can be set to daemon threads if requested.
1469      * @param port the port number to listen to. If zero, a random available
1470      *  port no less than 8000 will be chosen and used.
1471      * @param asDaemon true if the KDC threads should be daemons
1472      * @throws java.io.IOException for any communication error
1473      */
startServer(int port, boolean asDaemon)1474     protected void startServer(int port, boolean asDaemon) throws IOException {
1475         if (nativeKdc != null) {
1476             startNativeServer(port, asDaemon);
1477         } else {
1478             startJavaServer(port, asDaemon);
1479         }
1480     }
1481 
startNativeServer(int port, boolean asDaemon)1482     private void startNativeServer(int port, boolean asDaemon) throws IOException {
1483         nativeKdc.prepare();
1484         nativeKdc.init();
1485         kdcProc = nativeKdc.kdc();
1486     }
1487 
startJavaServer(int port, boolean asDaemon)1488     private void startJavaServer(int port, boolean asDaemon) throws IOException {
1489         if (port > 0) {
1490             u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
1491             t1 = new ServerSocket(port);
1492         } else {
1493             while (true) {
1494                 // Try to find a port number that's both TCP and UDP free
1495                 try {
1496                     port = 8000 + new java.util.Random().nextInt(10000);
1497                     u1 = null;
1498                     u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));
1499                     t1 = new ServerSocket(port);
1500                     break;
1501                 } catch (Exception e) {
1502                     if (u1 != null) u1.close();
1503                 }
1504             }
1505         }
1506         final DatagramSocket udp = u1;
1507         final ServerSocket tcp = t1;
1508         System.out.println("Start KDC on " + port);
1509 
1510         this.port = port;
1511 
1512         // The UDP consumer
1513         thread1 = new Thread() {
1514             public void run() {
1515                 udpConsumerReady = true;
1516                 while (true) {
1517                     try {
1518                         byte[] inbuf = new byte[8192];
1519                         DatagramPacket p = new DatagramPacket(inbuf, inbuf.length);
1520                         udp.receive(p);
1521                         System.out.println("-----------------------------------------------");
1522                         System.out.println(">>>>> UDP packet received");
1523                         q.put(new Job(processMessage(Arrays.copyOf(inbuf, p.getLength())), udp, p));
1524                     } catch (Exception e) {
1525                         e.printStackTrace();
1526                     }
1527                 }
1528             }
1529         };
1530         thread1.setDaemon(asDaemon);
1531         thread1.start();
1532 
1533         // The TCP consumer
1534         thread2 = new Thread() {
1535             public void run() {
1536                 tcpConsumerReady = true;
1537                 while (true) {
1538                     try {
1539                         Socket socket = tcp.accept();
1540                         System.out.println("-----------------------------------------------");
1541                         System.out.println(">>>>> TCP connection established");
1542                         DataInputStream in = new DataInputStream(socket.getInputStream());
1543                         DataOutputStream out = new DataOutputStream(socket.getOutputStream());
1544                         int len = in.readInt();
1545                         if (len > 65535) {
1546                             throw new Exception("Huge request not supported");
1547                         }
1548                         byte[] token = new byte[len];
1549                         in.readFully(token);
1550                         q.put(new Job(processMessage(token), socket, out));
1551                     } catch (Exception e) {
1552                         e.printStackTrace();
1553                     }
1554                 }
1555             }
1556         };
1557         thread2.setDaemon(asDaemon);
1558         thread2.start();
1559 
1560         // The dispatcher
1561         thread3 = new Thread() {
1562             public void run() {
1563                 dispatcherReady = true;
1564                 while (true) {
1565                     try {
1566                         q.take().send();
1567                     } catch (Exception e) {
1568                     }
1569                 }
1570             }
1571         };
1572         thread3.setDaemon(true);
1573         thread3.start();
1574 
1575         // wait for the KDC is ready
1576         try {
1577             while (!isReady()) {
1578                 Thread.sleep(100);
1579             }
1580         } catch(InterruptedException e) {
1581             throw new IOException(e);
1582         }
1583     }
1584 
kinit(String user, String ccache)1585     public void kinit(String user, String ccache) throws Exception {
1586         if (user.indexOf('@') < 0) {
1587             user = user + "@" + realm;
1588         }
1589         if (nativeKdc != null) {
1590             nativeKdc.kinit(user, ccache);
1591         } else {
1592             Context.fromUserPass(user, passwords.get(user), false)
1593                     .ccache(ccache);
1594         }
1595     }
1596 
isReady()1597     boolean isReady() {
1598         return udpConsumerReady && tcpConsumerReady && dispatcherReady;
1599     }
1600 
terminate()1601     public void terminate() {
1602         if (nativeKdc != null) {
1603             System.out.println("Killing kdc...");
1604             kdcProc.destroyForcibly();
1605             System.out.println("Done");
1606         } else {
1607             try {
1608                 thread1.stop();
1609                 thread2.stop();
1610                 thread3.stop();
1611                 u1.close();
1612                 t1.close();
1613             } catch (Exception e) {
1614                 // OK
1615             }
1616         }
1617     }
1618 
startKDC(final String host, final String krbConfFileName, final String realm, final Map<String, String> principals, final String ktab, final KtabMode mode)1619     public static KDC startKDC(final String host, final String krbConfFileName,
1620             final String realm, final Map<String, String> principals,
1621             final String ktab, final KtabMode mode) {
1622 
1623         KDC kdc;
1624         try {
1625             kdc = KDC.create(realm, host, 0, true);
1626             kdc.setOption(KDC.Option.PREAUTH_REQUIRED, Boolean.FALSE);
1627             if (krbConfFileName != null) {
1628                 KDC.saveConfig(krbConfFileName, kdc);
1629             }
1630 
1631             // Add principals
1632             if (principals != null) {
1633                 principals.forEach((name, password) -> {
1634                     if (password == null || password.isEmpty()) {
1635                         System.out.println(String.format(
1636                                 "KDC:add a principal '%s' with a random " +
1637                                         "password", name));
1638                         kdc.addPrincipalRandKey(name);
1639                     } else {
1640                         System.out.println(String.format(
1641                                 "KDC:add a principal '%s' with '%s' password",
1642                                 name, password));
1643                         kdc.addPrincipal(name, password.toCharArray());
1644                     }
1645                 });
1646             }
1647 
1648             // Create or append keys to existing keytab file
1649             if (ktab != null) {
1650                 File ktabFile = new File(ktab);
1651                 switch(mode) {
1652                     case APPEND:
1653                         if (ktabFile.exists()) {
1654                             System.out.println(String.format(
1655                                     "KDC:append keys to an exising keytab "
1656                                     + "file %s", ktab));
1657                             kdc.appendKtab(ktab);
1658                         } else {
1659                             System.out.println(String.format(
1660                                     "KDC:create a new keytab file %s", ktab));
1661                             kdc.writeKtab(ktab);
1662                         }
1663                         break;
1664                     case EXISTING:
1665                         System.out.println(String.format(
1666                                 "KDC:use an existing keytab file %s", ktab));
1667                         break;
1668                     default:
1669                         throw new RuntimeException(String.format(
1670                                 "KDC:unsupported keytab mode: %s", mode));
1671                 }
1672             }
1673 
1674             System.out.println(String.format(
1675                     "KDC: started on %s:%s with '%s' realm",
1676                     host, kdc.getPort(), realm));
1677         } catch (Exception e) {
1678             throw new RuntimeException("KDC: unexpected exception", e);
1679         }
1680 
1681         return kdc;
1682     }
1683 
1684     /**
1685      * Helper class to encapsulate a job in a KDC.
1686      */
1687     private static class Job {
1688         byte[] token;           // The received request at creation time and
1689                                 // the response at send time
1690         Socket s;               // The TCP socket from where the request comes
1691         DataOutputStream out;   // The OutputStream of the TCP socket
1692         DatagramSocket s2;      // The UDP socket from where the request comes
1693         DatagramPacket dp;      // The incoming UDP datagram packet
1694         boolean useTCP;         // Whether TCP or UDP is used
1695 
1696         // Creates a job object for TCP
Job(byte[] token, Socket s, DataOutputStream out)1697         Job(byte[] token, Socket s, DataOutputStream out) {
1698             useTCP = true;
1699             this.token = token;
1700             this.s = s;
1701             this.out = out;
1702         }
1703 
1704         // Creates a job object for UDP
Job(byte[] token, DatagramSocket s2, DatagramPacket dp)1705         Job(byte[] token, DatagramSocket s2, DatagramPacket dp) {
1706             useTCP = false;
1707             this.token = token;
1708             this.s2 = s2;
1709             this.dp = dp;
1710         }
1711 
1712         // Sends the output back to the client
send()1713         void send() {
1714             try {
1715                 if (useTCP) {
1716                     System.out.println(">>>>> TCP request honored");
1717                     out.writeInt(token.length);
1718                     out.write(token);
1719                     s.close();
1720                 } else {
1721                     System.out.println(">>>>> UDP request honored");
1722                     s2.send(new DatagramPacket(token, token.length, dp.getAddress(), dp.getPort()));
1723                 }
1724             } catch (Exception e) {
1725                 e.printStackTrace();
1726             }
1727         }
1728     }
1729 
1730     /**
1731      * A native KDC using the binaries in nativePath. Attention:
1732      * this is using binaries, not an existing KDC instance.
1733      * An implementation of this takes care of configuration,
1734      * principal db managing and KDC startup.
1735      */
1736     static abstract class NativeKdc {
1737 
1738         protected Map<String,String> env;
1739         protected String nativePath;
1740         protected String base;
1741         protected String realm;
1742         protected int port;
1743 
NativeKdc(String nativePath, KDC kdc)1744         NativeKdc(String nativePath, KDC kdc) {
1745             if (kdc.port == 0) {
1746                 kdc.port = 8000 + new java.util.Random().nextInt(10000);
1747             }
1748             this.nativePath = nativePath;
1749             this.realm = kdc.realm;
1750             this.port = kdc.port;
1751             this.base = Paths.get("" + port).toAbsolutePath().toString();
1752         }
1753 
1754         // Add a new principal
addPrincipal(String user, String pass)1755         abstract void addPrincipal(String user, String pass);
1756         // Add a keytab entry
ktadd(String user, String ktab)1757         abstract void ktadd(String user, String ktab);
1758         // Initialize KDC
init()1759         abstract void init();
1760         // Start kdc
kdc()1761         abstract Process kdc();
1762         // Configuration
prepare()1763         abstract void prepare();
1764         // Fill ccache
kinit(String user, String ccache)1765         abstract void kinit(String user, String ccache);
1766 
get(KDC kdc)1767         static NativeKdc get(KDC kdc) {
1768             String prop = System.getProperty("native.kdc.path");
1769             if (prop == null) {
1770                 return null;
1771             } else if (Files.exists(Paths.get(prop, "sbin/krb5kdc"))) {
1772                 return new MIT(true, prop, kdc);
1773             } else if (Files.exists(Paths.get(prop, "kdc/krb5kdc"))) {
1774                 return new MIT(false, prop, kdc);
1775             } else if (Files.exists(Paths.get(prop, "libexec/kdc"))) {
1776                 return new Heimdal(prop, kdc);
1777             } else {
1778                 throw new IllegalArgumentException("Strange " + prop);
1779             }
1780         }
1781 
run(boolean wait, String... cmd)1782         Process run(boolean wait, String... cmd) {
1783             try {
1784                 System.out.println("Running " + cmd2str(env, cmd));
1785                 ProcessBuilder pb = new ProcessBuilder();
1786                 pb.inheritIO();
1787                 pb.environment().putAll(env);
1788                 Process p = pb.command(cmd).start();
1789                 if (wait) {
1790                     if (p.waitFor() < 0) {
1791                         throw new RuntimeException("exit code is not null");
1792                     }
1793                     return null;
1794                 } else {
1795                     return p;
1796                 }
1797             } catch (Exception e) {
1798                 throw new RuntimeException(e);
1799             }
1800         }
1801 
cmd2str(Map<String,String> env, String... cmd)1802         private String cmd2str(Map<String,String> env, String... cmd) {
1803             return env.entrySet().stream().map(e -> e.getKey()+"="+e.getValue())
1804                     .collect(Collectors.joining(" ")) + " " +
1805                     Stream.of(cmd).collect(Collectors.joining(" "));
1806         }
1807     }
1808 
1809     // Heimdal KDC. Build your own and run "make install" to nativePath.
1810     static class Heimdal extends NativeKdc {
1811 
Heimdal(String nativePath, KDC kdc)1812         Heimdal(String nativePath, KDC kdc) {
1813             super(nativePath, kdc);
1814             this.env = Map.of(
1815                     "KRB5_CONFIG", base + "/krb5.conf",
1816                     "KRB5_TRACE", "/dev/stderr",
1817                     Platform.sharedLibraryPathVariableName(), nativePath + "/lib");
1818         }
1819 
1820         @Override
addPrincipal(String user, String pass)1821         public void addPrincipal(String user, String pass) {
1822             run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,
1823                     "add", "-p", pass, "--use-defaults", user);
1824         }
1825 
1826         @Override
ktadd(String user, String ktab)1827         public void ktadd(String user, String ktab) {
1828             run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,
1829                     "ext_keytab", "-k", ktab, user);
1830         }
1831 
1832         @Override
init()1833         public void init() {
1834             run(true, nativePath + "/bin/kadmin",  "-l",  "-r", realm,
1835                     "init", "--realm-max-ticket-life=1day",
1836                     "--realm-max-renewable-life=1month", realm);
1837         }
1838 
1839         @Override
kdc()1840         public Process kdc() {
1841             return run(false, nativePath + "/libexec/kdc",
1842                     "--addresses=127.0.0.1", "-P", "" + port);
1843         }
1844 
1845         @Override
prepare()1846         public void prepare() {
1847             try {
1848                 Files.createDirectory(Paths.get(base));
1849                 Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(
1850                         "[libdefaults]",
1851                         "default_realm = " + realm,
1852                         "default_keytab_name = FILE:" + base + "/krb5.keytab",
1853                         "forwardable = true",
1854                         "dns_lookup_kdc = no",
1855                         "dns_lookup_realm = no",
1856                         "dns_canonicalize_hostname = false",
1857                         "\n[realms]",
1858                         realm + " = {",
1859                         "  kdc = localhost:" + port,
1860                         "}",
1861                         "\n[kdc]",
1862                         "db-dir = " + base,
1863                         "database = {",
1864                         "    label = {",
1865                         "        dbname = " + base + "/current-db",
1866                         "        realm = " + realm,
1867                         "        mkey_file = " + base + "/mkey.file",
1868                         "        acl_file = " + base + "/heimdal.acl",
1869                         "        log_file = " + base + "/current.log",
1870                         "    }",
1871                         "}",
1872                         SUPPORTED_ETYPES == null ? ""
1873                                 : ("\n[kadmin]\ndefault_keys = "
1874                                 + (SUPPORTED_ETYPES + ",")
1875                                         .replaceAll(",", ":pw-salt ")),
1876                         "\n[logging]",
1877                         "kdc = 0-/FILE:" + base + "/messages.log",
1878                         "krb5 = 0-/FILE:" + base + "/messages.log",
1879                         "default = 0-/FILE:" + base + "/messages.log"
1880                 ));
1881             } catch (IOException e) {
1882                 throw new UncheckedIOException(e);
1883             }
1884         }
1885 
1886         @Override
kinit(String user, String ccache)1887         void kinit(String user, String ccache) {
1888             String tmpName = base + "/" + user + "." +
1889                     System.identityHashCode(this) + ".keytab";
1890             ktadd(user, tmpName);
1891             run(true, nativePath + "/bin/kinit",
1892                     "-f", "-t", tmpName, "-c", ccache, user);
1893         }
1894     }
1895 
1896     // MIT krb5 KDC. Make your own exploded (install == false), or
1897     // "make install" into nativePath (install == true).
1898     static class MIT extends NativeKdc {
1899 
1900         private boolean install; // "make install" or "make"
1901 
MIT(boolean install, String nativePath, KDC kdc)1902         MIT(boolean install, String nativePath, KDC kdc) {
1903             super(nativePath, kdc);
1904             this.install = install;
1905             this.env = Map.of(
1906                     "KRB5_KDC_PROFILE", base + "/kdc.conf",
1907                     "KRB5_CONFIG", base + "/krb5.conf",
1908                     "KRB5_TRACE", "/dev/stderr",
1909                     Platform.sharedLibraryPathVariableName(), nativePath + "/lib");
1910         }
1911 
1912         @Override
addPrincipal(String user, String pass)1913         public void addPrincipal(String user, String pass) {
1914             run(true, nativePath +
1915                     (install ? "/sbin/" : "/kadmin/cli/") + "kadmin.local",
1916                     "-q", "addprinc -pw " + pass + " " + user);
1917         }
1918 
1919         @Override
ktadd(String user, String ktab)1920         public void ktadd(String user, String ktab) {
1921             run(true, nativePath +
1922                     (install ? "/sbin/" : "/kadmin/cli/") + "kadmin.local",
1923                     "-q", "ktadd -k " + ktab + " -norandkey " + user);
1924         }
1925 
1926         @Override
init()1927         public void init() {
1928             run(true, nativePath +
1929                     (install ? "/sbin/" : "/kadmin/dbutil/") + "kdb5_util",
1930                     "create", "-s", "-W", "-P", "olala");
1931         }
1932 
1933         @Override
kdc()1934         public Process kdc() {
1935             return run(false, nativePath +
1936                     (install ? "/sbin/" : "/kdc/") + "krb5kdc",
1937                     "-n");
1938         }
1939 
1940         @Override
prepare()1941         public void prepare() {
1942             try {
1943                 Files.createDirectory(Paths.get(base));
1944                 Files.write(Paths.get(base + "/kdc.conf"), Arrays.asList(
1945                         "[kdcdefaults]",
1946                         "\n[realms]",
1947                         realm + "= {",
1948                         "  kdc_listen = " + this.port,
1949                         "  kdc_tcp_listen = " + this.port,
1950                         "  database_name = " + base + "/principal",
1951                         "  key_stash_file = " + base + "/.k5.ATHENA.MIT.EDU",
1952                         SUPPORTED_ETYPES == null ? ""
1953                                 : ("  supported_enctypes = "
1954                                 + (SUPPORTED_ETYPES + ",")
1955                                         .replaceAll(",", ":normal ")),
1956                         "}"
1957                 ));
1958                 Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(
1959                         "[libdefaults]",
1960                         "default_realm = " + realm,
1961                         "default_keytab_name = FILE:" + base + "/krb5.keytab",
1962                         "forwardable = true",
1963                         "dns_lookup_kdc = no",
1964                         "dns_lookup_realm = no",
1965                         "dns_canonicalize_hostname = false",
1966                         "\n[realms]",
1967                         realm + " = {",
1968                         "  kdc = localhost:" + port,
1969                         "}",
1970                         "\n[logging]",
1971                         "kdc = FILE:" + base + "/krb5kdc.log"
1972                 ));
1973             } catch (IOException e) {
1974                 throw new UncheckedIOException(e);
1975             }
1976         }
1977 
1978         @Override
kinit(String user, String ccache)1979         void kinit(String user, String ccache) {
1980             String tmpName = base + "/" + user + "." +
1981                     System.identityHashCode(this) + ".keytab";
1982             ktadd(user, tmpName);
1983             run(true, nativePath +
1984                     (install ? "/bin/" : "/clients/kinit/") + "kinit",
1985                     "-f", "-t", tmpName, "-c", ccache, user);
1986         }
1987     }
1988 
1989     // Calling private methods thru reflections
1990     private static final Field getEType;
1991     private static final Constructor<EncryptedData> ctorEncryptedData;
1992     private static final Method stringToKey;
1993     private static final Field getAddlTkt;
1994 
1995     static {
1996         try {
1997             ctorEncryptedData = EncryptedData.class.getDeclaredConstructor(DerValue.class);
1998             ctorEncryptedData.setAccessible(true);
1999             getEType = KDCReqBody.class.getDeclaredField("eType");
2000             getEType.setAccessible(true);
2001             stringToKey = EncryptionKey.class.getDeclaredMethod(
2002                     "stringToKey",
2003                     char[].class, String.class, byte[].class, Integer.TYPE);
2004             stringToKey.setAccessible(true);
2005             getAddlTkt = KDCReqBody.class.getDeclaredField("additionalTickets");
2006             getAddlTkt.setAccessible(true);
2007         } catch (NoSuchFieldException nsfe) {
2008             throw new AssertionError(nsfe);
2009         } catch (NoSuchMethodException nsme) {
2010             throw new AssertionError(nsme);
2011         }
2012     }
newEncryptedData(DerValue der)2013     private EncryptedData newEncryptedData(DerValue der) {
2014         try {
2015             return ctorEncryptedData.newInstance(der);
2016         } catch (Exception e) {
2017             throw new AssertionError(e);
2018         }
2019     }
KDCReqBodyDotEType(KDCReqBody body)2020     private static int[] KDCReqBodyDotEType(KDCReqBody body) {
2021         try {
2022             return (int[]) getEType.get(body);
2023         } catch (Exception e) {
2024             throw new AssertionError(e);
2025         }
2026     }
EncryptionKeyDotStringToKey(char[] password, String salt, byte[] s2kparams, int keyType)2027     private static byte[] EncryptionKeyDotStringToKey(char[] password, String salt,
2028             byte[] s2kparams, int keyType) throws KrbCryptoException {
2029         try {
2030             return (byte[])stringToKey.invoke(
2031                     null, password, salt, s2kparams, keyType);
2032         } catch (InvocationTargetException ex) {
2033             throw (KrbCryptoException)ex.getCause();
2034         } catch (Exception e) {
2035             throw new AssertionError(e);
2036         }
2037     }
KDCReqBodyDotFirstAdditionalTicket(KDCReqBody body)2038     private static Ticket KDCReqBodyDotFirstAdditionalTicket(KDCReqBody body) {
2039         try {
2040             return ((Ticket[])getAddlTkt.get(body))[0];
2041         } catch (Exception e) {
2042             throw new AssertionError(e);
2043         }
2044     }
2045 }
2046