Path: blob/master/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java
41159 views
/*1* Copyright (c) 2000, 2021, 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. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26*27* (C) Copyright IBM Corp. 1999 All Rights Reserved.28* Copyright 1997 The Open Group Research Institute. All rights reserved.29*/3031package sun.security.krb5;3233import java.security.PrivilegedAction;34import java.security.Security;35import java.util.Locale;36import sun.security.krb5.internal.Krb5;37import sun.security.krb5.internal.NetClient;38import java.io.IOException;39import java.net.SocketTimeoutException;40import java.util.StringTokenizer;41import java.security.AccessController;42import java.security.PrivilegedExceptionAction;43import java.security.PrivilegedActionException;44import java.util.ArrayList;45import java.util.List;46import java.util.Set;47import java.util.HashSet;48import java.util.Iterator;49import sun.security.krb5.internal.KRBError;5051/**52* KDC-REQ/KDC-REP communication. No more base class for KrbAsReq and53* KrbTgsReq. This class is now communication only.54*/55public final class KdcComm {5657// The following settings can be configured in [libdefaults]58// section of krb5.conf, which are global for all realms. Each of59// them can also be defined in a realm, which overrides value here.6061/**62* max retry time for a single KDC, default Krb5.KDC_RETRY_LIMIT (3)63*/64private static int defaultKdcRetryLimit;65/**66* timeout requesting a ticket from KDC, in millisec, default 30 sec67*/68private static int defaultKdcTimeout;69/**70* max UDP packet size, default unlimited (-1)71*/72private static int defaultUdpPrefLimit;7374private static final boolean DEBUG = Krb5.DEBUG;7576/**77* What to do when a KDC is unavailable, specified in the78* java.security file with key krb5.kdc.bad.policy.79* Possible values can be TRY_LAST or TRY_LESS. Reloaded when refreshed.80*/81private enum BpType {82NONE, TRY_LAST, TRY_LESS83}84private static int tryLessMaxRetries = 1;85private static int tryLessTimeout = 5000;8687private static BpType badPolicy;8889static {90initStatic();91}9293/**94* Read global settings95*/96public static void initStatic() {97@SuppressWarnings("removal")98String value = AccessController.doPrivileged(99new PrivilegedAction<String>() {100public String run() {101return Security.getProperty("krb5.kdc.bad.policy");102}103});104if (value != null) {105value = value.toLowerCase(Locale.ENGLISH);106String[] ss = value.split(":");107if ("tryless".equals(ss[0])) {108if (ss.length > 1) {109String[] params = ss[1].split(",");110try {111int tmp0 = Integer.parseInt(params[0]);112if (params.length > 1) {113tryLessTimeout = Integer.parseInt(params[1]);114}115// Assign here in case of exception at params[1]116tryLessMaxRetries = tmp0;117} catch (NumberFormatException nfe) {118// Ignored. Please note that tryLess is recognized and119// used, parameters using default values120if (DEBUG) {121System.out.println("Invalid krb5.kdc.bad.policy" +122" parameter for tryLess: " +123value + ", use default");124}125}126}127badPolicy = BpType.TRY_LESS;128} else if ("trylast".equals(ss[0])) {129badPolicy = BpType.TRY_LAST;130} else {131badPolicy = BpType.NONE;132}133} else {134badPolicy = BpType.NONE;135}136137138int timeout = -1;139int max_retries = -1;140int udp_pref_limit = -1;141142try {143Config cfg = Config.getInstance();144String temp = cfg.get("libdefaults", "kdc_timeout");145timeout = parseTimeString(temp);146147temp = cfg.get("libdefaults", "max_retries");148max_retries = parsePositiveIntString(temp);149temp = cfg.get("libdefaults", "udp_preference_limit");150udp_pref_limit = parsePositiveIntString(temp);151} catch (Exception exc) {152// ignore any exceptions; use default values153if (DEBUG) {154System.out.println ("Exception in getting KDC communication " +155"settings, using default value " +156exc.getMessage());157}158}159defaultKdcTimeout = timeout > 0 ? timeout : 30*1000; // 30 seconds160defaultKdcRetryLimit =161max_retries > 0 ? max_retries : Krb5.KDC_RETRY_LIMIT;162163if (udp_pref_limit < 0) {164defaultUdpPrefLimit = Krb5.KDC_DEFAULT_UDP_PREF_LIMIT;165} else if (udp_pref_limit > Krb5.KDC_HARD_UDP_LIMIT) {166defaultUdpPrefLimit = Krb5.KDC_HARD_UDP_LIMIT;167} else {168defaultUdpPrefLimit = udp_pref_limit;169}170171KdcAccessibility.reset();172}173174/**175* The instance fields176*/177private String realm;178179public KdcComm(String realm) throws KrbException {180if (realm == null) {181realm = Config.getInstance().getDefaultRealm();182if (realm == null) {183throw new KrbException(Krb5.KRB_ERR_GENERIC,184"Cannot find default realm");185}186}187this.realm = realm;188}189190public byte[] send(byte[] obuf)191throws IOException, KrbException {192int udpPrefLimit = getRealmSpecificValue(193realm, "udp_preference_limit", defaultUdpPrefLimit);194195boolean useTCP = (udpPrefLimit > 0 &&196(obuf != null && obuf.length > udpPrefLimit));197198return send(obuf, useTCP);199}200201private byte[] send(byte[] obuf, boolean useTCP)202throws IOException, KrbException {203204if (obuf == null)205return null;206Config cfg = Config.getInstance();207208if (realm == null) {209realm = cfg.getDefaultRealm();210if (realm == null) {211throw new KrbException(Krb5.KRB_ERR_GENERIC,212"Cannot find default realm");213}214}215216String kdcList = cfg.getKDCList(realm);217if (kdcList == null) {218throw new KrbException("Cannot get kdc for realm " + realm);219}220// tempKdc may include the port number also221Iterator<String> tempKdc = KdcAccessibility.list(kdcList).iterator();222if (!tempKdc.hasNext()) {223throw new KrbException("Cannot get kdc for realm " + realm);224}225byte[] ibuf = null;226try {227ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);228} catch(Exception first) {229boolean ok = false;230while(tempKdc.hasNext()) {231try {232ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);233ok = true;234break;235} catch(Exception ignore) {}236}237if (!ok) throw first;238}239if (ibuf == null) {240throw new IOException("Cannot get a KDC reply");241}242return ibuf;243}244245// send the AS Request to the specified KDC246// failover to using TCP if useTCP is not set and response is too big247private byte[] sendIfPossible(byte[] obuf, String tempKdc, boolean useTCP)248throws IOException, KrbException {249250try {251byte[] ibuf = send(obuf, tempKdc, useTCP);252KRBError ke = null;253try {254ke = new KRBError(ibuf);255} catch (Exception e) {256// OK257}258if (ke != null && ke.getErrorCode() ==259Krb5.KRB_ERR_RESPONSE_TOO_BIG) {260ibuf = send(obuf, tempKdc, true);261}262KdcAccessibility.removeBad(tempKdc);263return ibuf;264} catch(Exception e) {265if (DEBUG) {266System.out.println(">>> KrbKdcReq send: error trying " +267tempKdc);268e.printStackTrace(System.out);269}270KdcAccessibility.addBad(tempKdc);271throw e;272}273}274275// send the AS Request to the specified KDC276277private byte[] send(byte[] obuf, String tempKdc, boolean useTCP)278throws IOException, KrbException {279280if (obuf == null)281return null;282283int port = Krb5.KDC_INET_DEFAULT_PORT;284int retries = getRealmSpecificValue(285realm, "max_retries", defaultKdcRetryLimit);286int timeout = getRealmSpecificValue(287realm, "kdc_timeout", defaultKdcTimeout);288if (badPolicy == BpType.TRY_LESS &&289KdcAccessibility.isBad(tempKdc)) {290if (retries > tryLessMaxRetries) {291retries = tryLessMaxRetries; // less retries292}293if (timeout > tryLessTimeout) {294timeout = tryLessTimeout; // less time295}296}297298String kdc = null;299String portStr = null;300301if (tempKdc.charAt(0) == '[') { // Explicit IPv6 in []302int pos = tempKdc.indexOf(']', 1);303if (pos == -1) {304throw new IOException("Illegal KDC: " + tempKdc);305}306kdc = tempKdc.substring(1, pos);307if (pos != tempKdc.length() - 1) { // with port number308if (tempKdc.charAt(pos+1) != ':') {309throw new IOException("Illegal KDC: " + tempKdc);310}311portStr = tempKdc.substring(pos+2);312}313} else {314int colon = tempKdc.indexOf(':');315if (colon == -1) { // Hostname or IPv4 host only316kdc = tempKdc;317} else {318int nextColon = tempKdc.indexOf(':', colon+1);319if (nextColon > 0) { // >=2 ":", IPv6 with no port320kdc = tempKdc;321} else { // 1 ":", hostname or IPv4 with port322kdc = tempKdc.substring(0, colon);323portStr = tempKdc.substring(colon+1);324}325}326}327if (portStr != null) {328int tempPort = parsePositiveIntString(portStr);329if (tempPort > 0)330port = tempPort;331}332333if (DEBUG) {334System.out.println(">>> KrbKdcReq send: kdc=" + kdc335+ (useTCP ? " TCP:":" UDP:")336+ port + ", timeout="337+ timeout338+ ", number of retries ="339+ retries340+ ", #bytes=" + obuf.length);341}342343KdcCommunication kdcCommunication =344new KdcCommunication(kdc, port, useTCP, timeout, retries, obuf);345try {346@SuppressWarnings("removal")347byte[] ibuf = AccessController.doPrivileged(kdcCommunication);348if (DEBUG) {349System.out.println(">>> KrbKdcReq send: #bytes read="350+ (ibuf != null ? ibuf.length : 0));351}352return ibuf;353} catch (PrivilegedActionException e) {354Exception wrappedException = e.getException();355if (wrappedException instanceof IOException) {356throw (IOException) wrappedException;357} else {358throw (KrbException) wrappedException;359}360}361}362363private static class KdcCommunication364implements PrivilegedExceptionAction<byte[]> {365366private String kdc;367private int port;368private boolean useTCP;369private int timeout;370private int retries;371private byte[] obuf;372373public KdcCommunication(String kdc, int port, boolean useTCP,374int timeout, int retries, byte[] obuf) {375this.kdc = kdc;376this.port = port;377this.useTCP = useTCP;378this.timeout = timeout;379this.retries = retries;380this.obuf = obuf;381}382383// The caller only casts IOException and KrbException so don't384// add any new ones!385386public byte[] run() throws IOException, KrbException {387388byte[] ibuf = null;389390for (int i=1; i <= retries; i++) {391String proto = useTCP?"TCP":"UDP";392if (DEBUG) {393System.out.println(">>> KDCCommunication: kdc=" + kdc394+ " " + proto + ":"395+ port + ", timeout="396+ timeout397+ ",Attempt =" + i398+ ", #bytes=" + obuf.length);399}400try (NetClient kdcClient = NetClient.getInstance(401proto, kdc, port, timeout)) {402kdcClient.send(obuf);403ibuf = kdcClient.receive();404break;405} catch (SocketTimeoutException se) {406if (DEBUG) {407System.out.println ("SocketTimeOutException with " +408"attempt: " + i);409}410if (i == retries) {411ibuf = null;412throw se;413}414}415}416return ibuf;417}418}419420/**421* Parses a time value string. If it ends with "s", parses as seconds.422* Otherwise, parses as milliseconds.423* @param s the time string424* @return the integer value in milliseconds, or -1 if input is null or425* has an invalid format426*/427private static int parseTimeString(String s) {428if (s == null) {429return -1;430}431if (s.endsWith("s")) {432int seconds = parsePositiveIntString(s.substring(0, s.length()-1));433return (seconds < 0) ? -1 : (seconds*1000);434} else {435return parsePositiveIntString(s);436}437}438439/**440* Returns krb5.conf setting of {@code key} for a specific realm,441* which can be:442* 1. defined in the sub-stanza for the given realm inside [realms], or443* 2. defined in [libdefaults], or444* 3. defValue445* @param realm the given realm in which the setting is requested. Returns446* the global setting if null447* @param key the key for the setting448* @param defValue default value449* @return a value for the key450*/451private int getRealmSpecificValue(String realm, String key, int defValue) {452int v = defValue;453454if (realm == null) return v;455456int temp = -1;457try {458String value =459Config.getInstance().get("realms", realm, key);460if (key.equals("kdc_timeout")) {461temp = parseTimeString(value);462} else {463temp = parsePositiveIntString(value);464}465} catch (Exception exc) {466// Ignored, defValue will be picked up467}468469if (temp > 0) v = temp;470471return v;472}473474private static int parsePositiveIntString(String intString) {475if (intString == null)476return -1;477478int ret = -1;479480try {481ret = Integer.parseInt(intString);482} catch (Exception exc) {483return -1;484}485486if (ret >= 0)487return ret;488489return -1;490}491492/**493* Maintains a KDC accessible list. Unavailable KDCs are put into a494* secondary KDC list. When a KDC in the secondary list is available,495* it is removed from there. No insertion order in the secondary KDC list.496*497* There are two methods to deal with KDCs in the secondary KDC list.498* 1. Only try them when they are the only known KDCs.499* 2. Still try them, but with fewer retries and a smaller timeout value.500*/501static class KdcAccessibility {502// Known bad KDCs503private static Set<String> bads = new HashSet<>();504505private static synchronized void addBad(String kdc) {506if (DEBUG) {507System.out.println(">>> KdcAccessibility: add " + kdc);508}509bads.add(kdc);510}511512private static synchronized void removeBad(String kdc) {513if (DEBUG) {514System.out.println(">>> KdcAccessibility: remove " + kdc);515}516bads.remove(kdc);517}518519private static synchronized boolean isBad(String kdc) {520return bads.contains(kdc);521}522523private static synchronized void reset() {524if (DEBUG) {525System.out.println(">>> KdcAccessibility: reset");526}527bads.clear();528}529530// Returns a preferred KDC list by putting the bad ones at the end531private static synchronized List<String> list(String kdcList) {532StringTokenizer st = new StringTokenizer(kdcList);533List<String> list = new ArrayList<>();534if (badPolicy == BpType.TRY_LAST) {535List<String> badkdcs = new ArrayList<>();536while (st.hasMoreTokens()) {537String t = st.nextToken();538if (bads.contains(t)) badkdcs.add(t);539else list.add(t);540}541// Bad KDCs are put at last542list.addAll(badkdcs);543} else {544// All KDCs are returned in their original order,545// This include TRY_LESS and NONE546while (st.hasMoreTokens()) {547list.add(st.nextToken());548}549}550return list;551}552}553}554555556557