Path: blob/master/test/jdk/sun/security/krb5/auto/KDC.java
41152 views
/*1* Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import jdk.test.lib.Platform;2425import java.lang.reflect.Constructor;26import java.lang.reflect.Field;27import java.lang.reflect.InvocationTargetException;28import java.net.*;29import java.io.*;30import java.lang.reflect.Method;31import java.nio.file.Files;32import java.nio.file.Paths;33import java.util.*;34import java.util.concurrent.*;35import java.util.stream.Collectors;36import java.util.stream.Stream;3738import sun.security.krb5.*;39import sun.security.krb5.internal.*;40import sun.security.krb5.internal.ccache.CredentialsCache;41import sun.security.krb5.internal.crypto.EType;42import sun.security.krb5.internal.crypto.KeyUsage;43import sun.security.krb5.internal.ktab.KeyTab;44import sun.security.util.DerInputStream;45import sun.security.util.DerOutputStream;46import sun.security.util.DerValue;4748/**49* A KDC server.50*51* Note: By setting the system property native.kdc.path to a native52* krb5 installation, this class starts a native KDC with the53* given realm and host. It can also add new principals and save keytabs.54* Other features might not be available.55* <p>56* Features:57* <ol>58* <li> Supports TCP and UDP59* <li> Supports AS-REQ and TGS-REQ60* <li> Principal db and other settings hard coded in application61* <li> Options, say, request preauth or not62* </ol>63* Side effects:64* <ol>65* <li> The Sun-internal class <code>sun.security.krb5.Config</code> is a66* singleton and initialized according to Kerberos settings (krb5.conf and67* java.security.krb5.* system properties). This means once it's initialized68* it will not automatically notice any changes to these settings (or file69* changes of krb5.conf). The KDC class normally does not touch these70* settings (except for the <code>writeKtab()</code> method). However, to make71* sure nothing ever goes wrong, if you want to make any changes to these72* settings after calling a KDC method, call <code>Config.refresh()</code> to73* make sure your changes are reflected in the <code>Config</code> object.74* </ol>75* System properties recognized:76* <ul>77* <li>test.kdc.save.ccache78* </ul>79* Issues and TODOs:80* <ol>81* <li> Generates krb5.conf to be used on another machine, currently the kdc is82* always localhost83* <li> More options to KDC, say, error output, say, response nonce !=84* request nonce85* </ol>86* Note: This program uses internal krb5 classes (including reflection to87* access private fields and methods).88* <p>89* Usages:90* <p>91* 1. Init and start the KDC:92* <pre>93* KDC kdc = KDC.create("REALM.NAME", port, isDaemon);94* KDC kdc = KDC.create("REALM.NAME");95* </pre>96* Here, <code>port</code> is the UDP and TCP port number the KDC server97* listens on. If zero, a random port is chosen, which you can use getPort()98* later to retrieve the value.99* <p>100* If <code>isDaemon</code> is true, the KDC worker threads will be daemons.101* <p>102* The shortcut <code>KDC.create("REALM.NAME")</code> has port=0 and103* isDaemon=false, and is commonly used in an embedded KDC.104* <p>105* 2. Adding users:106* <pre>107* kdc.addPrincipal(String principal_name, char[] password);108* kdc.addPrincipalRandKey(String principal_name);109* </pre>110* A service principal's name should look like "host/f.q.d.n". The second form111* generates a random key. To expose this key, call <code>writeKtab()</code> to112* save the keys into a keytab file.113* <p>114* Note that you need to add the principal name krbtgt/REALM.NAME yourself.115* <p>116* Note that you can safely add a principal at any time after the KDC is117* started and before a user requests info on this principal.118* <p>119* 3. Other public methods:120* <ul>121* <li> <code>getPort</code>: Returns the port number the KDC uses122* <li> <code>getRealm</code>: Returns the realm name123* <li> <code>writeKtab</code>: Writes all principals' keys into a keytab file124* <li> <code>saveConfig</code>: Saves a krb5.conf file to access this KDC125* <li> <code>setOption</code>: Sets various options126* </ul>127* Read the javadoc for details. Lazy developer can use <code>OneKDC</code>128* directly.129*/130public class KDC {131132public static final int DEFAULT_LIFETIME = 39600;133public static final int DEFAULT_RENEWTIME = 86400;134135public static final String NOT_EXISTING_HOST = "not.existing.host";136137// What etypes the KDC supports. Comma-separated strings. Null for all.138// Please note native KDCs might use different names.139private static final String SUPPORTED_ETYPES140= System.getProperty("kdc.supported.enctypes");141142// The native KDC143private final NativeKdc nativeKdc;144145// The native KDC process146private Process kdcProc = null;147148// Under the hood.149150// Principal db. principal -> pass. A case-insensitive TreeMap is used151// so that even if the client provides a name with different case, the KDC152// can still locate the principal and give back correct salt.153private TreeMap<String,char[]> passwords = new TreeMap<>154(String.CASE_INSENSITIVE_ORDER);155156// Non default salts. Precisely, there should be different salts for157// different etypes, pretend they are the same at the moment.158private TreeMap<String,String> salts = new TreeMap<>159(String.CASE_INSENSITIVE_ORDER);160161// Non default s2kparams for newer etypes. Precisely, there should be162// different s2kparams for different etypes, pretend they are the same163// at the moment.164private TreeMap<String,byte[]> s2kparamses = new TreeMap<>165(String.CASE_INSENSITIVE_ORDER);166167// Alias for referrals.168private TreeMap<String,KDC> aliasReferrals = new TreeMap<>169(String.CASE_INSENSITIVE_ORDER);170171// Alias for local resolution.172private TreeMap<String,PrincipalName> alias2Principals = new TreeMap<>173(String.CASE_INSENSITIVE_ORDER);174175// Realm name176private String realm;177// KDC178private String kdc;179// Service port number180private int port;181// The request/response job queue182private BlockingQueue<Job> q = new ArrayBlockingQueue<>(100);183// Options184private Map<Option,Object> options = new HashMap<>();185// Realm-specific krb5.conf settings186private List<String> conf = new ArrayList<>();187188private Thread thread1, thread2, thread3;189private volatile boolean udpConsumerReady = false;190private volatile boolean tcpConsumerReady = false;191private volatile boolean dispatcherReady = false;192DatagramSocket u1 = null;193ServerSocket t1 = null;194195public static enum KtabMode { APPEND, EXISTING };196197/**198* Option names, to be expanded forever.199*/200public static enum Option {201/**202* Whether pre-authentication is required. Default Boolean.TRUE203*/204PREAUTH_REQUIRED,205/**206* Only issue TGT in RC4207*/208ONLY_RC4_TGT,209/**210* Use RC4 as the first in preauth211*/212RC4_FIRST_PREAUTH,213/**214* Use only one preauth, so that some keys are not easy to generate215*/216ONLY_ONE_PREAUTH,217/**218* Set all name-type to a value in response219*/220RESP_NT,221/**222* Multiple ETYPE-INFO-ENTRY with same etype but different salt223*/224DUP_ETYPE,225/**226* What backend server can be delegated to227*/228OK_AS_DELEGATE,229/**230* Allow S4U2self, List<String> of middle servers.231* If not set, means KDC does not understand S4U2self at all, therefore232* would ignore any PA-FOR-USER request and send a ticket using the233* cname of teh requestor. If set, it returns FORWARDABLE tickets to234* a server with its name in the list235*/236ALLOW_S4U2SELF,237/**238* Allow S4U2proxy, Map<String,List<String>> of middle servers to239* backends. If not set or a backend not in a server's list,240* Krb5.KDC_ERR_POLICY will be send for S4U2proxy request.241*/242ALLOW_S4U2PROXY,243/**244* Sensitive accounts can never be delegated.245*/246SENSITIVE_ACCOUNTS,247/**248* If true, will check if TGS-REQ contains a non-null addresses field.249*/250CHECK_ADDRESSES,251};252253/**254* A standalone KDC server.255*/256public static void main(String[] args) throws Exception {257int port = args.length > 0 ? Integer.parseInt(args[0]) : 0;258KDC kdc = create("RABBIT.HOLE", "kdc.rabbit.hole", port, false);259kdc.addPrincipal("dummy", "bogus".toCharArray());260kdc.addPrincipal("foo", "bar".toCharArray());261kdc.addPrincipalRandKey("krbtgt/RABBIT.HOLE");262kdc.addPrincipalRandKey("server/host.rabbit.hole");263kdc.addPrincipalRandKey("backend/host.rabbit.hole");264KDC.saveConfig("krb5.conf", kdc, "forwardable = true");265}266267/**268* Creates and starts a KDC running as a daemon on a random port.269* @param realm the realm name270* @return the running KDC instance271* @throws java.io.IOException for any socket creation error272*/273public static KDC create(String realm) throws IOException {274return create(realm, "kdc." + realm.toLowerCase(Locale.US), 0, true);275}276277public static KDC existing(String realm, String kdc, int port) {278KDC k = new KDC(realm, kdc);279k.port = port;280return k;281}282283/**284* Creates and starts a KDC server.285* @param realm the realm name286* @param port the TCP and UDP port to listen to. A random port will to287* chosen if zero.288* @param asDaemon if true, KDC threads will be daemons. Otherwise, not.289* @return the running KDC instance290* @throws java.io.IOException for any socket creation error291*/292public static KDC create(String realm, String kdc, int port,293boolean asDaemon) throws IOException {294return new KDC(realm, kdc, port, asDaemon);295}296297/**298* Sets an option299* @param key the option name300* @param value the value301*/302public void setOption(Option key, Object value) {303if (value == null) {304options.remove(key);305} else {306options.put(key, value);307}308}309310/**311* Writes or appends keys into a keytab.312* <p>313* Attention: This is the most basic one of a series of methods below on314* keytab creation or modification. All these methods reference krb5.conf315* settings. If you need to modify krb5.conf or switch to another krb5.conf316* later, please call <code>Config.refresh()</code> again. For example:317* <pre>318* kdc.writeKtab("/etc/kdc/ktab", true); // Config is initialized,319* System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf");320* Config.refresh();321* </pre>322* Inside this method there are 2 places krb5.conf is used:323* <ol>324* <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys325* <li> (Has workaround) Creating PrincipalName326* </ol>327* @param tab the keytab file name328* @param append true if append, otherwise, overwrite.329* @param names the names to write into, write all if names is empty330*/331public void writeKtab(String tab, boolean append, String... names)332throws IOException, KrbException {333KeyTab ktab = null;334if (nativeKdc == null) {335ktab = append ? KeyTab.getInstance(tab) : KeyTab.create(tab);336}337Iterable<String> entries =338(names.length != 0) ? Arrays.asList(names): passwords.keySet();339for (String name : entries) {340if (name.indexOf('@') < 0) {341name = name + "@" + realm;342}343if (nativeKdc == null) {344char[] pass = passwords.get(name);345int kvno = 0;346if (Character.isDigit(pass[pass.length - 1])) {347kvno = pass[pass.length - 1] - '0';348}349PrincipalName pn = new PrincipalName(name,350name.indexOf('/') < 0 ?351PrincipalName.KRB_NT_UNKNOWN :352PrincipalName.KRB_NT_SRV_HST);353ktab.addEntry(pn,354getSalt(pn),355pass,356kvno,357true);358} else {359nativeKdc.ktadd(name, tab);360}361}362if (nativeKdc == null) {363ktab.save();364}365}366367/**368* Writes all principals' keys from multiple KDCs into one keytab file.369* @throws java.io.IOException for any file output error370* @throws sun.security.krb5.KrbException for any realm and/or principal371* name error.372*/373public static void writeMultiKtab(String tab, KDC... kdcs)374throws IOException, KrbException {375KeyTab.create(tab).save(); // Empty the old keytab376appendMultiKtab(tab, kdcs);377}378379/**380* Appends all principals' keys from multiple KDCs to one keytab file.381*/382public static void appendMultiKtab(String tab, KDC... kdcs)383throws IOException, KrbException {384for (KDC kdc: kdcs) {385kdc.writeKtab(tab, true);386}387}388389/**390* Write a ktab for this KDC.391*/392public void writeKtab(String tab) throws IOException, KrbException {393writeKtab(tab, false);394}395396/**397* Appends keys in this KDC to a ktab.398*/399public void appendKtab(String tab) throws IOException, KrbException {400writeKtab(tab, true);401}402403/**404* Adds a new principal to this realm with a given password.405* @param user the principal's name. For a service principal, use the406* form of host/f.q.d.n407* @param pass the password for the principal408*/409public void addPrincipal(String user, char[] pass) {410addPrincipal(user, pass, null, null);411}412413/**414* Adds a new principal to this realm with a given password.415* @param user the principal's name. For a service principal, use the416* form of host/f.q.d.n417* @param pass the password for the principal418* @param salt the salt, or null if a default value will be used419* @param s2kparams the s2kparams, or null if a default value will be used420*/421public void addPrincipal(422String user, char[] pass, String salt, byte[] s2kparams) {423if (user.indexOf('@') < 0) {424user = user + "@" + realm;425}426if (nativeKdc != null) {427if (!user.equals("krbtgt/" + realm)) {428nativeKdc.addPrincipal(user, new String(pass));429}430passwords.put(user, new char[0]);431} else {432passwords.put(user, pass);433if (salt != null) {434salts.put(user, salt);435}436if (s2kparams != null) {437s2kparamses.put(user, s2kparams);438}439}440}441442/**443* Adds a new principal to this realm with a random password444* @param user the principal's name. For a service principal, use the445* form of host/f.q.d.n446*/447public void addPrincipalRandKey(String user) {448addPrincipal(user, randomPassword());449}450451/**452* Returns the name of this realm453* @return the name of this realm454*/455public String getRealm() {456return realm;457}458459/**460* Returns the name of kdc461* @return the name of kdc462*/463public String getKDC() {464return kdc;465}466467/**468* Add realm-specific krb5.conf setting469*/470public void addConf(String s) {471conf.add(s);472}473474/**475* Writes a krb5.conf for one or more KDC that includes KDC locations for476* each realm and the default realm name. You can also add extra strings477* into the file. The method should be called like:478* <pre>479* KDC.saveConfig("krb5.conf", kdc1, kdc2, ..., line1, line2, ...);480* </pre>481* Here you can provide one or more kdc# and zero or more line# arguments.482* The line# will be put after [libdefaults] and before [realms]. Therefore483* you can append new lines into [libdefaults] and/or create your new484* stanzas as well. Note that a newline character will be appended to485* each line# argument.486* <p>487* For example:488* <pre>489* KDC.saveConfig("krb5.conf", this);490* </pre>491* generates:492* <pre>493* [libdefaults]494* default_realm = REALM.NAME495*496* [realms]497* REALM.NAME = {498* kdc = host:port_number499* # realm-specific settings500* }501* </pre>502*503* Another example:504* <pre>505* KDC.saveConfig("krb5.conf", kdc1, kdc2, "forwardable = true", "",506* "[domain_realm]",507* ".kdc1.com = KDC1.NAME");508* </pre>509* generates:510* <pre>511* [libdefaults]512* default_realm = KDC1.NAME513* forwardable = true514*515* [domain_realm]516* .kdc1.com = KDC1.NAME517*518* [realms]519* KDC1.NAME = {520* kdc = host:port1521* }522* KDC2.NAME = {523* kdc = host:port2524* }525* </pre>526* @param file the name of the file to write into527* @param kdc the first (and default) KDC528* @param more more KDCs or extra lines (in their appearing order) to529* insert into the krb5.conf file. This method reads each argument's type530* to determine what it's for. This argument can be empty.531* @throws java.io.IOException for any file output error532*/533public static void saveConfig(String file, KDC kdc, Object... more)534throws IOException {535StringBuffer sb = new StringBuffer();536sb.append("[libdefaults]\ndefault_realm = ");537sb.append(kdc.realm);538sb.append("\n");539for (Object o : more) {540if (o instanceof String) {541sb.append(o);542sb.append("\n");543}544}545sb.append("\n[realms]\n");546sb.append(kdc.realmLine());547for (Object o : more) {548if (o instanceof KDC) {549sb.append(((KDC) o).realmLine());550}551}552Files.write(Paths.get(file), sb.toString().getBytes());553}554555/**556* Returns the service port of the KDC server.557* @return the KDC service port558*/559public int getPort() {560return port;561}562563/**564* Register an alias name to be referred to a different KDC for565* resolution, according to RFC 6806.566* @param alias Alias name (i.e. [email protected]).567* @param referredKDC KDC to which the alias is referred for resolution.568*/569public void registerAlias(String alias, KDC referredKDC) {570aliasReferrals.remove(alias);571aliasReferrals.put(alias, referredKDC);572}573574/**575* Register an alias to be resolved to a Principal Name locally,576* according to RFC 6806.577* @param alias Alias name (i.e. [email protected]).578* @param user Principal Name to which the alias is resolved.579*/580public void registerAlias(String alias, String user)581throws RealmException {582alias2Principals.remove(alias);583alias2Principals.put(alias, new PrincipalName(user));584}585586// Private helper methods587588/**589* Private constructor, cannot be called outside.590* @param realm591*/592private KDC(String realm, String kdc) {593this.realm = realm;594this.kdc = kdc;595this.nativeKdc = null;596}597598/**599* A constructor that starts the KDC service also.600*/601protected KDC(String realm, String kdc, int port, boolean asDaemon)602throws IOException {603this.realm = realm;604this.kdc = kdc;605this.nativeKdc = NativeKdc.get(this);606startServer(port, asDaemon);607}608/**609* Generates a 32-char random password610* @return the password611*/612private static char[] randomPassword() {613char[] pass = new char[32];614Random r = new Random();615for (int i=0; i<31; i++)616pass[i] = (char)('a' + r.nextInt(26));617// The last char cannot be a number, otherwise, keyForUser()618// believes it's a sign of kvno619pass[31] = 'Z';620return pass;621}622623/**624* Generates a random key for the given encryption type.625* @param eType the encryption type626* @return the generated key627* @throws sun.security.krb5.KrbException for unknown/unsupported etype628*/629private static EncryptionKey generateRandomKey(int eType)630throws KrbException {631return genKey0(randomPassword(), "NOTHING", null, eType, null);632}633634/**635* Returns the password for a given principal636* @param p principal637* @return the password638* @throws sun.security.krb5.KrbException when the principal is not inside639* the database.640*/641private char[] getPassword(PrincipalName p, boolean server)642throws KrbException {643String pn = p.toString();644if (p.getRealmString() == null) {645pn = pn + "@" + getRealm();646}647char[] pass = passwords.get(pn);648if (pass == null) {649throw new KrbException(server?650Krb5.KDC_ERR_S_PRINCIPAL_UNKNOWN:651Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN, pn.toString());652}653return pass;654}655656/**657* Returns the salt string for the principal.658* @param p principal659* @return the salt660*/661protected String getSalt(PrincipalName p) {662String pn = p.toString();663if (p.getRealmString() == null) {664pn = pn + "@" + getRealm();665}666if (salts.containsKey(pn)) {667return salts.get(pn);668}669if (passwords.containsKey(pn)) {670try {671// Find the principal name with correct case.672p = new PrincipalName(passwords.ceilingEntry(pn).getKey());673} catch (RealmException re) {674// Won't happen675}676}677String s = p.getRealmString();678if (s == null) s = getRealm();679for (String n: p.getNameStrings()) {680s += n;681}682return s;683}684685/**686* Returns the s2kparams for the principal given the etype.687* @param p principal688* @param etype encryption type689* @return the s2kparams, might be null690*/691protected byte[] getParams(PrincipalName p, int etype) {692switch (etype) {693case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96:694case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96:695case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128:696case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA384_192:697String pn = p.toString();698if (p.getRealmString() == null) {699pn = pn + "@" + getRealm();700}701if (s2kparamses.containsKey(pn)) {702return s2kparamses.get(pn);703}704if (etype < EncryptedData.ETYPE_AES128_CTS_HMAC_SHA256_128) {705return new byte[]{0, 0, 0x10, 0};706} else {707return new byte[]{0, 0, (byte) 0x80, 0};708}709default:710return null;711}712}713714/**715* Returns the key for a given principal of the given encryption type716* @param p the principal717* @param etype the encryption type718* @param server looking for a server principal?719* @return the key720* @throws sun.security.krb5.KrbException for unknown/unsupported etype721*/722EncryptionKey keyForUser(PrincipalName p, int etype, boolean server)723throws KrbException {724try {725// Do not call EncryptionKey.acquireSecretKeys(), otherwise726// the krb5.conf config file would be loaded.727Integer kvno = null;728// For service whose password ending with a number, use it as kvno.729// Kvno must be postive.730if (p.toString().indexOf('/') > 0) {731char[] pass = getPassword(p, server);732if (Character.isDigit(pass[pass.length-1])) {733kvno = pass[pass.length-1] - '0';734}735}736return genKey0(getPassword(p, server), getSalt(p),737getParams(p, etype), etype, kvno);738} catch (KrbException ke) {739throw ke;740} catch (Exception e) {741throw new RuntimeException(e); // should not happen742}743}744745/**746* Returns a KerberosTime.747*748* @param offset offset from NOW in seconds749*/750private static KerberosTime timeAfter(int offset) {751return new KerberosTime(new Date().getTime() + offset * 1000L);752}753754/**755* Generates key from password.756*/757private static EncryptionKey genKey0(758char[] pass, String salt, byte[] s2kparams,759int etype, Integer kvno) throws KrbException {760return new EncryptionKey(EncryptionKeyDotStringToKey(761pass, salt, s2kparams, etype),762etype, kvno);763}764765/**766* Processes an incoming request and generates a response.767* @param in the request768* @return the response769* @throws java.lang.Exception for various errors770*/771protected byte[] processMessage(byte[] in) throws Exception {772if ((in[0] & 0x1f) == Krb5.KRB_AS_REQ)773return processAsReq(in);774else775return processTgsReq(in);776}777778/**779* Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR)780* @param in the request781* @return the response782* @throws java.lang.Exception for various errors783*/784protected byte[] processTgsReq(byte[] in) throws Exception {785TGSReq tgsReq = new TGSReq(in);786PrincipalName service = tgsReq.reqBody.sname;787if (options.containsKey(KDC.Option.RESP_NT)) {788service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),789service.getNameStrings(), service.getRealm());790}791try {792System.out.println(realm + "> " + tgsReq.reqBody.cname +793" sends TGS-REQ for " +794service + ", " + tgsReq.reqBody.kdcOptions);795KDCReqBody body = tgsReq.reqBody;796int[] eTypes = filterSupported(KDCReqBodyDotEType(body));797if (eTypes.length == 0) {798throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);799}800int e2 = eTypes[0]; // etype for outgoing session key801int e3 = eTypes[0]; // etype for outgoing ticket802803PAData[] pas = tgsReq.pAData;804805Ticket tkt = null;806EncTicketPart etp = null;807808PrincipalName cname = null;809boolean allowForwardable = true;810boolean isReferral = false;811if (body.kdcOptions.get(KDCOptions.CANONICALIZE)) {812System.out.println(realm + "> verifying referral for " +813body.sname.getNameString());814KDC referral = aliasReferrals.get(body.sname.getNameString());815if (referral != null) {816service = new PrincipalName(817PrincipalName.TGS_DEFAULT_SRV_NAME +818PrincipalName.NAME_COMPONENT_SEPARATOR_STR +819referral.getRealm(), PrincipalName.KRB_NT_SRV_INST,820this.getRealm());821System.out.println(realm + "> referral to " +822referral.getRealm());823isReferral = true;824}825}826827if (pas == null || pas.length == 0) {828throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);829} else {830PrincipalName forUserCName = null;831for (PAData pa: pas) {832if (pa.getType() == Krb5.PA_TGS_REQ) {833APReq apReq = new APReq(pa.getValue());834tkt = apReq.ticket;835int te = tkt.encPart.getEType();836EncryptionKey kkey = keyForUser(tkt.sname, te, true);837byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET);838DerInputStream derIn = new DerInputStream(bb);839DerValue der = derIn.getDerValue();840etp = new EncTicketPart(der.toByteArray());841// Finally, cname will be overwritten by PA-FOR-USER842// if it exists.843cname = etp.cname;844System.out.println(realm + "> presenting a ticket of "845+ etp.cname + " to " + tkt.sname);846} else if (pa.getType() == Krb5.PA_FOR_USER) {847if (options.containsKey(Option.ALLOW_S4U2SELF)) {848PAForUserEnc p4u = new PAForUserEnc(849new DerValue(pa.getValue()), null);850forUserCName = p4u.name;851System.out.println(realm + "> See PA_FOR_USER "852+ " in the name of " + p4u.name);853}854}855}856if (forUserCName != null) {857List<String> names = (List<String>)858options.get(Option.ALLOW_S4U2SELF);859if (!names.contains(cname.toString())) {860// Mimic the normal KDC behavior. When a server is not861// allowed to send S4U2self, do not send an error.862// Instead, send a ticket which is useless later.863allowForwardable = false;864}865cname = forUserCName;866}867if (tkt == null) {868throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);869}870}871872// Session key for original ticket, TGT873EncryptionKey ckey = etp.key;874875// Session key for session with the service876EncryptionKey key = generateRandomKey(e2);877878// Check time, TODO879KerberosTime from = body.from;880KerberosTime till = body.till;881if (from == null || from.isZero()) {882from = timeAfter(0);883}884if (till == null) {885throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO886} else if (till.isZero()) {887till = timeAfter(DEFAULT_LIFETIME);888}889890boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];891if (body.kdcOptions.get(KDCOptions.FORWARDABLE)892&& allowForwardable) {893List<String> sensitives = (List<String>)894options.get(Option.SENSITIVE_ACCOUNTS);895if (sensitives != null && sensitives.contains(cname.toString())) {896// Cannot make FORWARDABLE897} else {898bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;899}900}901// We do not request for addresses for FORWARDED tickets902if (options.containsKey(Option.CHECK_ADDRESSES)903&& body.kdcOptions.get(KDCOptions.FORWARDED)904&& body.addresses != null) {905throw new KrbException(Krb5.KDC_ERR_BADOPTION);906}907if (body.kdcOptions.get(KDCOptions.FORWARDED) ||908etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {909bFlags[Krb5.TKT_OPTS_FORWARDED] = true;910}911if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {912bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;913//renew = timeAfter(3600 * 24 * 7);914}915if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {916bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;917}918if (body.kdcOptions.get(KDCOptions.POSTDATED)) {919bFlags[Krb5.TKT_OPTS_POSTDATED] = true;920}921if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {922bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;923}924if (body.kdcOptions.get(KDCOptions.CNAME_IN_ADDL_TKT)) {925if (!options.containsKey(Option.ALLOW_S4U2PROXY)) {926// Don't understand CNAME_IN_ADDL_TKT927throw new KrbException(Krb5.KDC_ERR_BADOPTION);928} else {929Map<String,List<String>> map = (Map<String,List<String>>)930options.get(Option.ALLOW_S4U2PROXY);931Ticket second = KDCReqBodyDotFirstAdditionalTicket(body);932EncryptionKey key2 = keyForUser(933second.sname, second.encPart.getEType(), true);934byte[] bb = second.encPart.decrypt(key2, KeyUsage.KU_TICKET);935DerInputStream derIn = new DerInputStream(bb);936DerValue der = derIn.getDerValue();937EncTicketPart tktEncPart = new EncTicketPart(der.toByteArray());938if (!tktEncPart.flags.get(Krb5.TKT_OPTS_FORWARDABLE)) {939//throw new KrbException(Krb5.KDC_ERR_BADOPTION);940}941PrincipalName client = tktEncPart.cname;942System.out.println(realm + "> and an additional ticket of "943+ client + " to " + second.sname);944if (map.containsKey(cname.toString())) {945if (map.get(cname.toString()).contains(service.toString())) {946System.out.println(realm + "> S4U2proxy OK");947} else {948throw new KrbException(Krb5.KDC_ERR_BADOPTION);949}950} else {951throw new KrbException(Krb5.KDC_ERR_BADOPTION);952}953cname = client;954}955}956957String okAsDelegate = (String)options.get(Option.OK_AS_DELEGATE);958if (okAsDelegate != null && (959okAsDelegate.isEmpty() ||960okAsDelegate.contains(service.getNameString()))) {961bFlags[Krb5.TKT_OPTS_DELEGATE] = true;962}963bFlags[Krb5.TKT_OPTS_INITIAL] = true;964965KerberosTime renewTill = etp.renewTill;966if (renewTill != null && body.kdcOptions.get(KDCOptions.RENEW)) {967// till should never pass renewTill968if (till.greaterThan(renewTill)) {969till = renewTill;970}971if (System.getProperty("test.set.null.renew") != null) {972// Testing 8186576, see NullRenewUntil.java.973renewTill = null;974}975}976977TicketFlags tFlags = new TicketFlags(bFlags);978EncTicketPart enc = new EncTicketPart(979tFlags,980key,981cname,982new TransitedEncoding(1, new byte[0]), // TODO983timeAfter(0),984from,985till, renewTill,986body.addresses != null ? body.addresses987: etp.caddr,988null);989EncryptionKey skey = keyForUser(service, e3, true);990if (skey == null) {991throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO992}993Ticket t = new Ticket(994System.getProperty("test.kdc.diff.sname") != null ?995new PrincipalName("xx" + service.toString()) :996service,997new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)998);999EncTGSRepPart enc_part = new EncTGSRepPart(1000key,1001new LastReq(new LastReqEntry[] {1002new LastReqEntry(0, timeAfter(-10))1003}),1004body.getNonce(), // TODO: detect replay1005timeAfter(3600 * 24),1006// Next 5 and last MUST be same with ticket1007tFlags,1008timeAfter(0),1009from,1010till, renewTill,1011service,1012body.addresses,1013null1014);1015EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(),1016KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY);1017TGSRep tgsRep = new TGSRep(null,1018cname,1019t,1020edata);1021System.out.println(" Return " + tgsRep.cname1022+ " ticket for " + tgsRep.ticket.sname + ", flags "1023+ tFlags);10241025DerOutputStream out = new DerOutputStream();1026out.write(DerValue.createTag(DerValue.TAG_APPLICATION,1027true, (byte)Krb5.KRB_TGS_REP), tgsRep.asn1Encode());1028return out.toByteArray();1029} catch (KrbException ke) {1030ke.printStackTrace(System.out);1031KRBError kerr = ke.getError();1032KDCReqBody body = tgsReq.reqBody;1033System.out.println(" Error " + ke.returnCode()1034+ " " +ke.returnCodeMessage());1035if (kerr == null) {1036kerr = new KRBError(null, null, null,1037timeAfter(0),10380,1039ke.returnCode(),1040body.cname,1041service,1042KrbException.errorMessage(ke.returnCode()),1043null);1044}1045return kerr.asn1Encode();1046}1047}10481049/**1050* Processes a AS_REQ and generates a AS_REP (or KRB_ERROR)1051* @param in the request1052* @return the response1053* @throws java.lang.Exception for various errors1054*/1055protected byte[] processAsReq(byte[] in) throws Exception {1056ASReq asReq = new ASReq(in);1057byte[] asReqbytes = asReq.asn1Encode();1058int[] eTypes = null;1059List<PAData> outPAs = new ArrayList<>();10601061PrincipalName service = asReq.reqBody.sname;1062if (options.containsKey(KDC.Option.RESP_NT)) {1063service = new PrincipalName((int)options.get(KDC.Option.RESP_NT),1064service.getNameStrings(),1065Realm.getDefault());1066}1067try {1068System.out.println(realm + "> " + asReq.reqBody.cname +1069" sends AS-REQ for " +1070service + ", " + asReq.reqBody.kdcOptions);10711072KDCReqBody body = asReq.reqBody;10731074eTypes = filterSupported(KDCReqBodyDotEType(body));1075if (eTypes.length == 0) {1076throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);1077}1078int eType = eTypes[0];10791080if (body.kdcOptions.get(KDCOptions.CANONICALIZE)) {1081PrincipalName principal = alias2Principals.get(1082body.cname.getNameString());1083if (principal != null) {1084body.cname = principal;1085} else {1086KDC referral = aliasReferrals.get(body.cname.getNameString());1087if (referral != null) {1088body.cname = new PrincipalName(1089PrincipalName.TGS_DEFAULT_SRV_NAME,1090PrincipalName.KRB_NT_SRV_INST,1091referral.getRealm());1092throw new KrbException(Krb5.KRB_ERR_WRONG_REALM);1093}1094}1095}10961097EncryptionKey ckey = keyForUser(body.cname, eType, false);1098EncryptionKey skey = keyForUser(service, eType, true);10991100if (options.containsKey(KDC.Option.ONLY_RC4_TGT)) {1101int tgtEType = EncryptedData.ETYPE_ARCFOUR_HMAC;1102boolean found = false;1103for (int i=0; i<eTypes.length; i++) {1104if (eTypes[i] == tgtEType) {1105found = true;1106break;1107}1108}1109if (!found) {1110throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);1111}1112skey = keyForUser(service, tgtEType, true);1113}1114if (ckey == null) {1115throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);1116}1117if (skey == null) {1118throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO1119}11201121// Session key1122EncryptionKey key = generateRandomKey(eType);1123// Check time, TODO1124KerberosTime from = body.from;1125KerberosTime till = body.till;1126KerberosTime rtime = body.rtime;1127if (from == null || from.isZero()) {1128from = timeAfter(0);1129}1130if (till == null) {1131throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO1132} else if (till.isZero()) {1133till = timeAfter(DEFAULT_LIFETIME);1134} else if (till.greaterThan(timeAfter(24 * 3600))1135&& System.getProperty("test.kdc.force.till") == null) {1136// If till is more than 1 day later, make it renewable1137till = timeAfter(DEFAULT_LIFETIME);1138body.kdcOptions.set(KDCOptions.RENEWABLE, true);1139if (rtime == null) rtime = till;1140}1141if (rtime == null && body.kdcOptions.get(KDCOptions.RENEWABLE)) {1142rtime = timeAfter(DEFAULT_RENEWTIME);1143}1144//body.from1145boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];1146if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {1147List<String> sensitives = (List<String>)1148options.get(Option.SENSITIVE_ACCOUNTS);1149if (sensitives != null1150&& sensitives.contains(body.cname.toString())) {1151// Cannot make FORWARDABLE1152} else {1153bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;1154}1155}1156if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {1157bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;1158//renew = timeAfter(3600 * 24 * 7);1159}1160if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {1161bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;1162}1163if (body.kdcOptions.get(KDCOptions.POSTDATED)) {1164bFlags[Krb5.TKT_OPTS_POSTDATED] = true;1165}1166if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {1167bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;1168}1169bFlags[Krb5.TKT_OPTS_INITIAL] = true;1170if (System.getProperty("test.kdc.always.enc.pa.rep") != null) {1171bFlags[Krb5.TKT_OPTS_ENC_PA_REP] = true;1172}11731174// Creating PA-DATA1175DerValue[] pas2 = null, pas = null;1176if (options.containsKey(KDC.Option.DUP_ETYPE)) {1177int n = (Integer)options.get(KDC.Option.DUP_ETYPE);1178switch (n) {1179case 1: // customer's case in 70679741180pas2 = new DerValue[] {1181new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),1182new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),1183new DerValue(new ETypeInfo2(11841, realm, new byte[]{1}).asn1Encode()),1185};1186pas = new DerValue[] {1187new DerValue(new ETypeInfo(1, null).asn1Encode()),1188new DerValue(new ETypeInfo(1, "").asn1Encode()),1189new DerValue(new ETypeInfo(1, realm).asn1Encode()),1190};1191break;1192case 2: // we still reject non-null s2kparams and prefer E2 over E1193pas2 = new DerValue[] {1194new DerValue(new ETypeInfo2(11951, realm, new byte[]{1}).asn1Encode()),1196new DerValue(new ETypeInfo2(1, null, null).asn1Encode()),1197new DerValue(new ETypeInfo2(1, "", null).asn1Encode()),1198};1199pas = new DerValue[] {1200new DerValue(new ETypeInfo(1, realm).asn1Encode()),1201new DerValue(new ETypeInfo(1, null).asn1Encode()),1202new DerValue(new ETypeInfo(1, "").asn1Encode()),1203};1204break;1205case 3: // but only E is wrong1206pas = new DerValue[] {1207new DerValue(new ETypeInfo(1, realm).asn1Encode()),1208new DerValue(new ETypeInfo(1, null).asn1Encode()),1209new DerValue(new ETypeInfo(1, "").asn1Encode()),1210};1211break;1212case 4: // we also ignore rc4-hmac1213pas = new DerValue[] {1214new DerValue(new ETypeInfo(23, "ANYTHING").asn1Encode()),1215new DerValue(new ETypeInfo(1, null).asn1Encode()),1216new DerValue(new ETypeInfo(1, "").asn1Encode()),1217};1218break;1219case 5: // "" should be wrong, but we accept it now1220// See s.s.k.internal.PAData$SaltAndParams1221pas = new DerValue[] {1222new DerValue(new ETypeInfo(1, "").asn1Encode()),1223new DerValue(new ETypeInfo(1, null).asn1Encode()),1224};1225break;1226}1227} else {1228int[] epas = eTypes;1229if (options.containsKey(KDC.Option.RC4_FIRST_PREAUTH)) {1230for (int i=1; i<epas.length; i++) {1231if (epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC) {1232epas[i] = epas[0];1233epas[0] = EncryptedData.ETYPE_ARCFOUR_HMAC;1234break;1235}1236};1237} else if (options.containsKey(KDC.Option.ONLY_ONE_PREAUTH)) {1238epas = new int[] { eTypes[0] };1239}1240pas2 = new DerValue[epas.length];1241for (int i=0; i<epas.length; i++) {1242pas2[i] = new DerValue(new ETypeInfo2(1243epas[i],1244epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?1245null : getSalt(body.cname),1246getParams(body.cname, epas[i])).asn1Encode());1247}1248boolean allOld = true;1249for (int i: eTypes) {1250if (i >= EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 &&1251i != EncryptedData.ETYPE_ARCFOUR_HMAC) {1252allOld = false;1253break;1254}1255}1256if (allOld) {1257pas = new DerValue[epas.length];1258for (int i=0; i<epas.length; i++) {1259pas[i] = new DerValue(new ETypeInfo(1260epas[i],1261epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ?1262null : getSalt(body.cname)1263).asn1Encode());1264}1265}1266}12671268DerOutputStream eid;1269if (pas2 != null) {1270eid = new DerOutputStream();1271eid.putSequence(pas2);1272outPAs.add(new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()));1273}1274if (pas != null) {1275eid = new DerOutputStream();1276eid.putSequence(pas);1277outPAs.add(new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()));1278}12791280PAData[] inPAs = asReq.pAData;1281List<PAData> enc_outPAs = new ArrayList<>();12821283byte[] paEncTimestamp = null;1284if (inPAs != null) {1285for (PAData inPA : inPAs) {1286if (inPA.getType() == Krb5.PA_ENC_TIMESTAMP) {1287paEncTimestamp = inPA.getValue();1288}1289}1290}12911292if (paEncTimestamp == null) {1293Object preauth = options.get(Option.PREAUTH_REQUIRED);1294if (preauth == null || preauth.equals(Boolean.TRUE)) {1295throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED);1296}1297} else {1298EncryptionKey pakey = null;1299try {1300EncryptedData data = newEncryptedData(1301new DerValue(paEncTimestamp));1302pakey = keyForUser(body.cname, data.getEType(), false);1303data.decrypt(pakey, KeyUsage.KU_PA_ENC_TS);1304} catch (Exception e) {1305KrbException ke = new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED);1306ke.initCause(e);1307throw ke;1308}1309bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true;1310for (PAData pa : inPAs) {1311if (pa.getType() == Krb5.PA_REQ_ENC_PA_REP) {1312Checksum ckSum = new Checksum(1313Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128,1314asReqbytes, ckey, KeyUsage.KU_AS_REQ);1315enc_outPAs.add(new PAData(Krb5.PA_REQ_ENC_PA_REP,1316ckSum.asn1Encode()));1317bFlags[Krb5.TKT_OPTS_ENC_PA_REP] = true;1318break;1319}1320}1321}13221323TicketFlags tFlags = new TicketFlags(bFlags);1324EncTicketPart enc = new EncTicketPart(1325tFlags,1326key,1327body.cname,1328new TransitedEncoding(1, new byte[0]),1329timeAfter(0),1330from,1331till, rtime,1332body.addresses,1333null);1334Ticket t = new Ticket(1335service,1336new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET)1337);1338EncASRepPart enc_part = new EncASRepPart(1339key,1340new LastReq(new LastReqEntry[]{1341new LastReqEntry(0, timeAfter(-10))1342}),1343body.getNonce(), // TODO: detect replay?1344timeAfter(3600 * 24),1345// Next 5 and last MUST be same with ticket1346tFlags,1347timeAfter(0),1348from,1349till, rtime,1350service,1351body.addresses,1352enc_outPAs.toArray(new PAData[enc_outPAs.size()])1353);1354EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(),1355KeyUsage.KU_ENC_AS_REP_PART);1356ASRep asRep = new ASRep(1357outPAs.toArray(new PAData[outPAs.size()]),1358body.cname,1359t,1360edata);13611362System.out.println(" Return " + asRep.cname1363+ " ticket for " + asRep.ticket.sname + ", flags "1364+ tFlags);13651366DerOutputStream out = new DerOutputStream();1367out.write(DerValue.createTag(DerValue.TAG_APPLICATION,1368true, (byte)Krb5.KRB_AS_REP), asRep.asn1Encode());1369byte[] result = out.toByteArray();13701371// Added feature:1372// Write the current issuing TGT into a ccache file specified1373// by the system property below.1374String ccache = System.getProperty("test.kdc.save.ccache");1375if (ccache != null) {1376asRep.encKDCRepPart = enc_part;1377sun.security.krb5.internal.ccache.Credentials credentials =1378new sun.security.krb5.internal.ccache.Credentials(asRep);1379CredentialsCache cache =1380CredentialsCache.create(asReq.reqBody.cname, ccache);1381if (cache == null) {1382throw new IOException("Unable to create the cache file " +1383ccache);1384}1385cache.update(credentials);1386cache.save();1387}13881389return result;1390} catch (KrbException ke) {1391ke.printStackTrace(System.out);1392KRBError kerr = ke.getError();1393KDCReqBody body = asReq.reqBody;1394System.out.println(" Error " + ke.returnCode()1395+ " " +ke.returnCodeMessage());1396byte[] eData = null;1397if (kerr == null) {1398if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED ||1399ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) {1400outPAs.add(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]));1401}1402if (outPAs.size() > 0) {1403DerOutputStream bytes = new DerOutputStream();1404for (PAData p: outPAs) {1405bytes.write(p.asn1Encode());1406}1407DerOutputStream temp = new DerOutputStream();1408temp.write(DerValue.tag_Sequence, bytes);1409eData = temp.toByteArray();1410}1411kerr = new KRBError(null, null, null,1412timeAfter(0),14130,1414ke.returnCode(),1415body.cname,1416service,1417KrbException.errorMessage(ke.returnCode()),1418eData);1419}1420return kerr.asn1Encode();1421}1422}14231424private int[] filterSupported(int[] input) {1425int count = 0;1426for (int i = 0; i < input.length; i++) {1427if (!EType.isSupported(input[i])) {1428continue;1429}1430if (SUPPORTED_ETYPES != null) {1431boolean supported = false;1432for (String se : SUPPORTED_ETYPES.split(",")) {1433if (Config.getType(se) == input[i]) {1434supported = true;1435break;1436}1437}1438if (!supported) {1439continue;1440}1441}1442if (count != i) {1443input[count] = input[i];1444}1445count++;1446}1447if (count != input.length) {1448input = Arrays.copyOf(input, count);1449}1450return input;1451}14521453/**1454* Generates a line for a KDC to put inside [realms] of krb5.conf1455* @return REALM.NAME = { kdc = host:port etc }1456*/1457private String realmLine() {1458StringBuilder sb = new StringBuilder();1459sb.append(realm).append(" = {\n kdc = ")1460.append(kdc).append(':').append(port).append('\n');1461for (String s: conf) {1462sb.append(" ").append(s).append('\n');1463}1464return sb.append("}\n").toString();1465}14661467/**1468* Start the KDC service. This server listens on both UDP and TCP using1469* the same port number. It uses three threads to deal with requests.1470* They can be set to daemon threads if requested.1471* @param port the port number to listen to. If zero, a random available1472* port no less than 8000 will be chosen and used.1473* @param asDaemon true if the KDC threads should be daemons1474* @throws java.io.IOException for any communication error1475*/1476protected void startServer(int port, boolean asDaemon) throws IOException {1477if (nativeKdc != null) {1478startNativeServer(port, asDaemon);1479} else {1480startJavaServer(port, asDaemon);1481}1482}14831484private void startNativeServer(int port, boolean asDaemon) throws IOException {1485nativeKdc.prepare();1486nativeKdc.init();1487kdcProc = nativeKdc.kdc();1488}14891490private void startJavaServer(int port, boolean asDaemon) throws IOException {1491if (port > 0) {1492u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));1493t1 = new ServerSocket(port);1494} else {1495while (true) {1496// Try to find a port number that's both TCP and UDP free1497try {1498port = 8000 + new java.util.Random().nextInt(10000);1499u1 = null;1500u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1"));1501t1 = new ServerSocket(port);1502break;1503} catch (Exception e) {1504if (u1 != null) u1.close();1505}1506}1507}1508final DatagramSocket udp = u1;1509final ServerSocket tcp = t1;1510System.out.println("Start KDC on " + port);15111512this.port = port;15131514// The UDP consumer1515thread1 = new Thread() {1516public void run() {1517udpConsumerReady = true;1518while (true) {1519try {1520byte[] inbuf = new byte[8192];1521DatagramPacket p = new DatagramPacket(inbuf, inbuf.length);1522udp.receive(p);1523System.out.println("-----------------------------------------------");1524System.out.println(">>>>> UDP packet received");1525q.put(new Job(processMessage(Arrays.copyOf(inbuf, p.getLength())), udp, p));1526} catch (Exception e) {1527e.printStackTrace();1528}1529}1530}1531};1532thread1.setDaemon(asDaemon);1533thread1.start();15341535// The TCP consumer1536thread2 = new Thread() {1537public void run() {1538tcpConsumerReady = true;1539while (true) {1540try {1541Socket socket = tcp.accept();1542System.out.println("-----------------------------------------------");1543System.out.println(">>>>> TCP connection established");1544DataInputStream in = new DataInputStream(socket.getInputStream());1545DataOutputStream out = new DataOutputStream(socket.getOutputStream());1546int len = in.readInt();1547if (len > 65535) {1548throw new Exception("Huge request not supported");1549}1550byte[] token = new byte[len];1551in.readFully(token);1552q.put(new Job(processMessage(token), socket, out));1553} catch (Exception e) {1554e.printStackTrace();1555}1556}1557}1558};1559thread2.setDaemon(asDaemon);1560thread2.start();15611562// The dispatcher1563thread3 = new Thread() {1564public void run() {1565dispatcherReady = true;1566while (true) {1567try {1568q.take().send();1569} catch (Exception e) {1570}1571}1572}1573};1574thread3.setDaemon(true);1575thread3.start();15761577// wait for the KDC is ready1578try {1579while (!isReady()) {1580Thread.sleep(100);1581}1582} catch(InterruptedException e) {1583throw new IOException(e);1584}1585}15861587public void kinit(String user, String ccache) throws Exception {1588if (user.indexOf('@') < 0) {1589user = user + "@" + realm;1590}1591if (nativeKdc != null) {1592nativeKdc.kinit(user, ccache);1593} else {1594Context.fromUserPass(user, passwords.get(user), false)1595.ccache(ccache);1596}1597}15981599boolean isReady() {1600return udpConsumerReady && tcpConsumerReady && dispatcherReady;1601}16021603public void terminate() {1604if (nativeKdc != null) {1605System.out.println("Killing kdc...");1606kdcProc.destroyForcibly();1607System.out.println("Done");1608} else {1609try {1610thread1.stop();1611thread2.stop();1612thread3.stop();1613u1.close();1614t1.close();1615} catch (Exception e) {1616// OK1617}1618}1619}16201621public static KDC startKDC(final String host, final String krbConfFileName,1622final String realm, final Map<String, String> principals,1623final String ktab, final KtabMode mode) {16241625KDC kdc;1626try {1627kdc = KDC.create(realm, host, 0, true);1628kdc.setOption(KDC.Option.PREAUTH_REQUIRED, Boolean.FALSE);1629if (krbConfFileName != null) {1630KDC.saveConfig(krbConfFileName, kdc);1631}16321633// Add principals1634if (principals != null) {1635principals.forEach((name, password) -> {1636if (password == null || password.isEmpty()) {1637System.out.println(String.format(1638"KDC:add a principal '%s' with a random " +1639"password", name));1640kdc.addPrincipalRandKey(name);1641} else {1642System.out.println(String.format(1643"KDC:add a principal '%s' with '%s' password",1644name, password));1645kdc.addPrincipal(name, password.toCharArray());1646}1647});1648}16491650// Create or append keys to existing keytab file1651if (ktab != null) {1652File ktabFile = new File(ktab);1653switch(mode) {1654case APPEND:1655if (ktabFile.exists()) {1656System.out.println(String.format(1657"KDC:append keys to an exising keytab "1658+ "file %s", ktab));1659kdc.appendKtab(ktab);1660} else {1661System.out.println(String.format(1662"KDC:create a new keytab file %s", ktab));1663kdc.writeKtab(ktab);1664}1665break;1666case EXISTING:1667System.out.println(String.format(1668"KDC:use an existing keytab file %s", ktab));1669break;1670default:1671throw new RuntimeException(String.format(1672"KDC:unsupported keytab mode: %s", mode));1673}1674}16751676System.out.println(String.format(1677"KDC: started on %s:%s with '%s' realm",1678host, kdc.getPort(), realm));1679} catch (Exception e) {1680throw new RuntimeException("KDC: unexpected exception", e);1681}16821683return kdc;1684}16851686/**1687* Helper class to encapsulate a job in a KDC.1688*/1689private static class Job {1690byte[] token; // The received request at creation time and1691// the response at send time1692Socket s; // The TCP socket from where the request comes1693DataOutputStream out; // The OutputStream of the TCP socket1694DatagramSocket s2; // The UDP socket from where the request comes1695DatagramPacket dp; // The incoming UDP datagram packet1696boolean useTCP; // Whether TCP or UDP is used16971698// Creates a job object for TCP1699Job(byte[] token, Socket s, DataOutputStream out) {1700useTCP = true;1701this.token = token;1702this.s = s;1703this.out = out;1704}17051706// Creates a job object for UDP1707Job(byte[] token, DatagramSocket s2, DatagramPacket dp) {1708useTCP = false;1709this.token = token;1710this.s2 = s2;1711this.dp = dp;1712}17131714// Sends the output back to the client1715void send() {1716try {1717if (useTCP) {1718System.out.println(">>>>> TCP request honored");1719out.writeInt(token.length);1720out.write(token);1721s.close();1722} else {1723System.out.println(">>>>> UDP request honored");1724s2.send(new DatagramPacket(token, token.length, dp.getAddress(), dp.getPort()));1725}1726} catch (Exception e) {1727e.printStackTrace();1728}1729}1730}17311732/**1733* A native KDC using the binaries in nativePath. Attention:1734* this is using binaries, not an existing KDC instance.1735* An implementation of this takes care of configuration,1736* principal db managing and KDC startup.1737*/1738static abstract class NativeKdc {17391740protected Map<String,String> env;1741protected String nativePath;1742protected String base;1743protected String realm;1744protected int port;17451746NativeKdc(String nativePath, KDC kdc) {1747if (kdc.port == 0) {1748kdc.port = 8000 + new java.util.Random().nextInt(10000);1749}1750this.nativePath = nativePath;1751this.realm = kdc.realm;1752this.port = kdc.port;1753this.base = Paths.get("" + port).toAbsolutePath().toString();1754}17551756// Add a new principal1757abstract void addPrincipal(String user, String pass);1758// Add a keytab entry1759abstract void ktadd(String user, String ktab);1760// Initialize KDC1761abstract void init();1762// Start kdc1763abstract Process kdc();1764// Configuration1765abstract void prepare();1766// Fill ccache1767abstract void kinit(String user, String ccache);17681769static NativeKdc get(KDC kdc) {1770String prop = System.getProperty("native.kdc.path");1771if (prop == null) {1772return null;1773} else if (Files.exists(Paths.get(prop, "sbin/krb5kdc"))) {1774return new MIT(true, prop, kdc);1775} else if (Files.exists(Paths.get(prop, "kdc/krb5kdc"))) {1776return new MIT(false, prop, kdc);1777} else if (Files.exists(Paths.get(prop, "libexec/kdc"))) {1778return new Heimdal(prop, kdc);1779} else {1780throw new IllegalArgumentException("Strange " + prop);1781}1782}17831784Process run(boolean wait, String... cmd) {1785try {1786System.out.println("Running " + cmd2str(env, cmd));1787ProcessBuilder pb = new ProcessBuilder();1788pb.inheritIO();1789pb.environment().putAll(env);1790Process p = pb.command(cmd).start();1791if (wait) {1792if (p.waitFor() < 0) {1793throw new RuntimeException("exit code is not null");1794}1795return null;1796} else {1797return p;1798}1799} catch (Exception e) {1800throw new RuntimeException(e);1801}1802}18031804private String cmd2str(Map<String,String> env, String... cmd) {1805return env.entrySet().stream().map(e -> e.getKey()+"="+e.getValue())1806.collect(Collectors.joining(" ")) + " " +1807Stream.of(cmd).collect(Collectors.joining(" "));1808}1809}18101811// Heimdal KDC. Build your own and run "make install" to nativePath.1812static class Heimdal extends NativeKdc {18131814Heimdal(String nativePath, KDC kdc) {1815super(nativePath, kdc);1816this.env = Map.of(1817"KRB5_CONFIG", base + "/krb5.conf",1818"KRB5_TRACE", "/dev/stderr",1819Platform.sharedLibraryPathVariableName(), nativePath + "/lib");1820}18211822@Override1823public void addPrincipal(String user, String pass) {1824run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,1825"add", "-p", pass, "--use-defaults", user);1826}18271828@Override1829public void ktadd(String user, String ktab) {1830run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,1831"ext_keytab", "-k", ktab, user);1832}18331834@Override1835public void init() {1836run(true, nativePath + "/bin/kadmin", "-l", "-r", realm,1837"init", "--realm-max-ticket-life=1day",1838"--realm-max-renewable-life=1month", realm);1839}18401841@Override1842public Process kdc() {1843return run(false, nativePath + "/libexec/kdc",1844"--addresses=127.0.0.1", "-P", "" + port);1845}18461847@Override1848public void prepare() {1849try {1850Files.createDirectory(Paths.get(base));1851Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(1852"[libdefaults]",1853"default_realm = " + realm,1854"default_keytab_name = FILE:" + base + "/krb5.keytab",1855"forwardable = true",1856"dns_lookup_kdc = no",1857"dns_lookup_realm = no",1858"dns_canonicalize_hostname = false",1859"\n[realms]",1860realm + " = {",1861" kdc = localhost:" + port,1862"}",1863"\n[kdc]",1864"db-dir = " + base,1865"database = {",1866" label = {",1867" dbname = " + base + "/current-db",1868" realm = " + realm,1869" mkey_file = " + base + "/mkey.file",1870" acl_file = " + base + "/heimdal.acl",1871" log_file = " + base + "/current.log",1872" }",1873"}",1874SUPPORTED_ETYPES == null ? ""1875: ("\n[kadmin]\ndefault_keys = "1876+ (SUPPORTED_ETYPES + ",")1877.replaceAll(",", ":pw-salt ")),1878"\n[logging]",1879"kdc = 0-/FILE:" + base + "/messages.log",1880"krb5 = 0-/FILE:" + base + "/messages.log",1881"default = 0-/FILE:" + base + "/messages.log"1882));1883} catch (IOException e) {1884throw new UncheckedIOException(e);1885}1886}18871888@Override1889void kinit(String user, String ccache) {1890String tmpName = base + "/" + user + "." +1891System.identityHashCode(this) + ".keytab";1892ktadd(user, tmpName);1893run(true, nativePath + "/bin/kinit",1894"-f", "-t", tmpName, "-c", ccache, user);1895}1896}18971898// MIT krb5 KDC. Make your own exploded (install == false), or1899// "make install" into nativePath (install == true).1900static class MIT extends NativeKdc {19011902private boolean install; // "make install" or "make"19031904MIT(boolean install, String nativePath, KDC kdc) {1905super(nativePath, kdc);1906this.install = install;1907this.env = Map.of(1908"KRB5_KDC_PROFILE", base + "/kdc.conf",1909"KRB5_CONFIG", base + "/krb5.conf",1910"KRB5_TRACE", "/dev/stderr",1911Platform.sharedLibraryPathVariableName(), nativePath + "/lib");1912}19131914@Override1915public void addPrincipal(String user, String pass) {1916run(true, nativePath +1917(install ? "/sbin/" : "/kadmin/cli/") + "kadmin.local",1918"-q", "addprinc -pw " + pass + " " + user);1919}19201921@Override1922public void ktadd(String user, String ktab) {1923run(true, nativePath +1924(install ? "/sbin/" : "/kadmin/cli/") + "kadmin.local",1925"-q", "ktadd -k " + ktab + " -norandkey " + user);1926}19271928@Override1929public void init() {1930run(true, nativePath +1931(install ? "/sbin/" : "/kadmin/dbutil/") + "kdb5_util",1932"create", "-s", "-W", "-P", "olala");1933}19341935@Override1936public Process kdc() {1937return run(false, nativePath +1938(install ? "/sbin/" : "/kdc/") + "krb5kdc",1939"-n");1940}19411942@Override1943public void prepare() {1944try {1945Files.createDirectory(Paths.get(base));1946Files.write(Paths.get(base + "/kdc.conf"), Arrays.asList(1947"[kdcdefaults]",1948"\n[realms]",1949realm + "= {",1950" kdc_listen = " + this.port,1951" kdc_tcp_listen = " + this.port,1952" database_name = " + base + "/principal",1953" key_stash_file = " + base + "/.k5.ATHENA.MIT.EDU",1954SUPPORTED_ETYPES == null ? ""1955: (" supported_enctypes = "1956+ (SUPPORTED_ETYPES + ",")1957.replaceAll(",", ":normal ")),1958"}"1959));1960Files.write(Paths.get(base + "/krb5.conf"), Arrays.asList(1961"[libdefaults]",1962"default_realm = " + realm,1963"default_keytab_name = FILE:" + base + "/krb5.keytab",1964"forwardable = true",1965"dns_lookup_kdc = no",1966"dns_lookup_realm = no",1967"dns_canonicalize_hostname = false",1968"\n[realms]",1969realm + " = {",1970" kdc = localhost:" + port,1971"}",1972"\n[logging]",1973"kdc = FILE:" + base + "/krb5kdc.log"1974));1975} catch (IOException e) {1976throw new UncheckedIOException(e);1977}1978}19791980@Override1981void kinit(String user, String ccache) {1982String tmpName = base + "/" + user + "." +1983System.identityHashCode(this) + ".keytab";1984ktadd(user, tmpName);1985run(true, nativePath +1986(install ? "/bin/" : "/clients/kinit/") + "kinit",1987"-f", "-t", tmpName, "-c", ccache, user);1988}1989}19901991// Calling private methods thru reflections1992private static final Field getEType;1993private static final Constructor<EncryptedData> ctorEncryptedData;1994private static final Method stringToKey;1995private static final Field getAddlTkt;19961997static {1998try {1999ctorEncryptedData = EncryptedData.class.getDeclaredConstructor(DerValue.class);2000ctorEncryptedData.setAccessible(true);2001getEType = KDCReqBody.class.getDeclaredField("eType");2002getEType.setAccessible(true);2003stringToKey = EncryptionKey.class.getDeclaredMethod(2004"stringToKey",2005char[].class, String.class, byte[].class, Integer.TYPE);2006stringToKey.setAccessible(true);2007getAddlTkt = KDCReqBody.class.getDeclaredField("additionalTickets");2008getAddlTkt.setAccessible(true);2009} catch (NoSuchFieldException nsfe) {2010throw new AssertionError(nsfe);2011} catch (NoSuchMethodException nsme) {2012throw new AssertionError(nsme);2013}2014}2015private EncryptedData newEncryptedData(DerValue der) {2016try {2017return ctorEncryptedData.newInstance(der);2018} catch (Exception e) {2019throw new AssertionError(e);2020}2021}2022private static int[] KDCReqBodyDotEType(KDCReqBody body) {2023try {2024return (int[]) getEType.get(body);2025} catch (Exception e) {2026throw new AssertionError(e);2027}2028}2029private static byte[] EncryptionKeyDotStringToKey(char[] password, String salt,2030byte[] s2kparams, int keyType) throws KrbCryptoException {2031try {2032return (byte[])stringToKey.invoke(2033null, password, salt, s2kparams, keyType);2034} catch (InvocationTargetException ex) {2035throw (KrbCryptoException)ex.getCause();2036} catch (Exception e) {2037throw new AssertionError(e);2038}2039}2040private static Ticket KDCReqBodyDotFirstAdditionalTicket(KDCReqBody body) {2041try {2042return ((Ticket[])getAddlTkt.get(body))[0];2043} catch (Exception e) {2044throw new AssertionError(e);2045}2046}2047}204820492050