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

/*
 *
 *  (C) Copyright IBM Corp. 1999 All Rights Reserved.
 *  Copyright 1997 The Open Group Research Institute.  All rights reserved.
 */

package sun.security.krb5;

34 35 36
import java.security.PrivilegedAction;
import java.security.Security;
import java.util.Locale;
D
duke 已提交
37
import sun.security.krb5.internal.Krb5;
38
import sun.security.krb5.internal.NetClient;
D
duke 已提交
39 40 41 42 43 44
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.StringTokenizer;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
45 46 47 48
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
49
import sun.security.krb5.internal.KRBError;
D
duke 已提交
50

51 52 53 54 55
/**
 * KDC-REQ/KDC-REP communication. No more base class for KrbAsReq and
 * KrbTgsReq. This class is now communication only.
 */
public final class KdcComm {
D
duke 已提交
56

57 58 59
    // The following settings can be configured in [libdefaults]
    // section of krb5.conf, which are global for all realms. Each of
    // them can also be defined in a realm, which overrides value here.
D
duke 已提交
60 61

    /**
62 63 64 65 66 67 68 69 70
     * max retry time for a single KDC, default Krb5.KDC_RETRY_LIMIT (3)
     */
    private static int defaultKdcRetryLimit;
    /**
     * timeout requesting a ticket from KDC, in millisec, default 30 sec
     */
    private static int defaultKdcTimeout;
    /**
     * max UDP packet size, default unlimited (-1)
D
duke 已提交
71
     */
72
    private static int defaultUdpPrefLimit;
D
duke 已提交
73 74 75

    private static final boolean DEBUG = Krb5.DEBUG;

76 77 78 79 80
    private static final String BAD_POLICY_KEY = "krb5.kdc.bad.policy";

    /**
     * What to do when a KDC is unavailable, specified in the
     * java.security file with key krb5.kdc.bad.policy.
81
     * Possible values can be TRY_LAST or TRY_LESS. Reloaded when refreshed.
82 83 84 85 86 87 88
     */
    private enum BpType {
        NONE, TRY_LAST, TRY_LESS
    }
    private static int tryLessMaxRetries = 1;
    private static int tryLessTimeout = 5000;

89
    private static BpType badPolicy;
90

D
duke 已提交
91
    static {
92 93 94 95 96 97 98
        initStatic();
    }

    /**
     * Read global settings
     */
    public static void initStatic() {
99 100 101 102 103 104 105 106 107 108 109 110
        String value = AccessController.doPrivileged(
        new PrivilegedAction<String>() {
            public String run() {
                return Security.getProperty(BAD_POLICY_KEY);
            }
        });
        if (value != null) {
            value = value.toLowerCase(Locale.ENGLISH);
            String[] ss = value.split(":");
            if ("tryless".equals(ss[0])) {
                if (ss.length > 1) {
                    String[] params = ss[1].split(",");
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
                    try {
                        int tmp0 = Integer.parseInt(params[0]);
                        if (params.length > 1) {
                            tryLessTimeout = Integer.parseInt(params[1]);
                        }
                        // Assign here in case of exception at params[1]
                        tryLessMaxRetries = tmp0;
                    } catch (NumberFormatException nfe) {
                        // Ignored. Please note that tryLess is recognized and
                        // used, parameters using default values
                        if (DEBUG) {
                            System.out.println("Invalid " + BAD_POLICY_KEY +
                                    " parameter for tryLess: " +
                                    value + ", use default");
                        }
126 127 128 129 130 131 132 133 134 135 136
                    }
                }
                badPolicy = BpType.TRY_LESS;
            } else if ("trylast".equals(ss[0])) {
                badPolicy = BpType.TRY_LAST;
            } else {
                badPolicy = BpType.NONE;
            }
        } else {
            badPolicy = BpType.NONE;
        }
D
duke 已提交
137 138 139


        int timeout = -1;
140 141 142
        int max_retries = -1;
        int udf_pref_limit = -1;

D
duke 已提交
143 144 145 146
        try {
            Config cfg = Config.getInstance();
            String temp = cfg.getDefault("kdc_timeout", "libdefaults");
            timeout = parsePositiveIntString(temp);
147 148
            temp = cfg.getDefault("max_retries", "libdefaults");
            max_retries = parsePositiveIntString(temp);
D
duke 已提交
149
            temp = cfg.getDefault("udp_preference_limit", "libdefaults");
150
            udf_pref_limit = parsePositiveIntString(temp);
D
duke 已提交
151
        } catch (Exception exc) {
152
           // ignore any exceptions; use default values
D
duke 已提交
153
           if (DEBUG) {
154 155
                System.out.println ("Exception in getting KDC communication " +
                                    "settings, using default value " +
D
duke 已提交
156 157 158
                                    exc.getMessage());
           }
        }
159 160 161 162
        defaultKdcTimeout = timeout > 0 ? timeout : 30*1000; // 30 seconds
        defaultKdcRetryLimit =
                max_retries > 0 ? max_retries : Krb5.KDC_RETRY_LIMIT;
        defaultUdpPrefLimit = udf_pref_limit;
D
duke 已提交
163

164
        KdcAccessibility.reset();
D
duke 已提交
165 166 167
    }

    /**
168
     * The instance fields
D
duke 已提交
169
     */
170 171 172 173 174 175 176 177 178 179 180 181
    private String realm;

    public KdcComm(String realm) throws KrbException {
        if (realm == null) {
           realm = Config.getInstance().getDefaultRealm();
            if (realm == null) {
                throw new KrbException(Krb5.KRB_ERR_GENERIC,
                                       "Cannot find default realm");
            }
        }
        this.realm = realm;
    }
D
duke 已提交
182

183
    public byte[] send(byte[] obuf)
D
duke 已提交
184
        throws IOException, KrbException {
185 186 187
        int udpPrefLimit = getRealmSpecificValue(
                realm, "udp_preference_limit", defaultUdpPrefLimit);

D
duke 已提交
188 189 190
        boolean useTCP = (udpPrefLimit > 0 &&
             (obuf != null && obuf.length > udpPrefLimit));

191
        return send(obuf, useTCP);
D
duke 已提交
192 193
    }

194
    private byte[] send(byte[] obuf, boolean useTCP)
D
duke 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        throws IOException, KrbException {

        if (obuf == null)
            return null;
        Exception savedException = null;
        Config cfg = Config.getInstance();

        if (realm == null) {
            realm = cfg.getDefaultRealm();
            if (realm == null) {
                throw new KrbException(Krb5.KRB_ERR_GENERIC,
                                       "Cannot find default realm");
            }
        }

        String kdcList = cfg.getKDCList(realm);
        if (kdcList == null) {
            throw new KrbException("Cannot get kdc for realm " + realm);
        }
        String tempKdc = null; // may include the port number also
215
        byte[] ibuf = null;
216 217
        for (String tmp: KdcAccessibility.list(kdcList)) {
            tempKdc = tmp;
D
duke 已提交
218
            try {
219 220 221 222 223 224 225 226 227 228 229
                ibuf = send(obuf,tempKdc,useTCP);
                KRBError ke = null;
                try {
                    ke = new KRBError(ibuf);
                } catch (Exception e) {
                    // OK
                }
                if (ke != null && ke.getErrorCode() ==
                        Krb5.KRB_ERR_RESPONSE_TOO_BIG) {
                    ibuf = send(obuf, tempKdc, true);
                }
230
                KdcAccessibility.removeBad(tempKdc);
D
duke 已提交
231 232
                break;
            } catch (Exception e) {
W
weijun 已提交
233 234 235 236 237
                if (DEBUG) {
                    System.out.println(">>> KrbKdcReq send: error trying " +
                            tempKdc);
                    e.printStackTrace(System.out);
                }
238
                KdcAccessibility.addBad(tempKdc);
D
duke 已提交
239 240 241 242 243 244 245 246 247 248
                savedException = e;
            }
        }
        if (ibuf == null && savedException != null) {
            if (savedException instanceof IOException) {
                throw (IOException) savedException;
            } else {
                throw (KrbException) savedException;
            }
        }
249
        return ibuf;
D
duke 已提交
250 251 252 253
    }

    // send the AS Request to the specified KDC

254
    private byte[] send(byte[] obuf, String tempKdc, boolean useTCP)
D
duke 已提交
255 256 257
        throws IOException, KrbException {

        if (obuf == null)
258
            return null;
D
duke 已提交
259

260
        int port = Krb5.KDC_INET_DEFAULT_PORT;
261 262 263 264
        int retries = getRealmSpecificValue(
                realm, "max_retries", defaultKdcRetryLimit);
        int timeout = getRealmSpecificValue(
                realm, "kdc_timeout", defaultKdcTimeout);
265 266 267 268 269 270 271 272 273 274
        if (badPolicy == BpType.TRY_LESS &&
                KdcAccessibility.isBad(tempKdc)) {
            if (retries > tryLessMaxRetries) {
                retries = tryLessMaxRetries; // less retries
            }
            if (timeout > tryLessTimeout) {
                timeout = tryLessTimeout; // less time
            }
        }

W
weijun 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        String kdc = null;
        String portStr = null;

        if (tempKdc.charAt(0) == '[') {     // Explicit IPv6 in []
            int pos = tempKdc.indexOf(']', 1);
            if (pos == -1) {
                throw new IOException("Illegal KDC: " + tempKdc);
            }
            kdc = tempKdc.substring(1, pos);
            if (pos != tempKdc.length() - 1) {  // with port number
                if (tempKdc.charAt(pos+1) != ':') {
                    throw new IOException("Illegal KDC: " + tempKdc);
                }
                portStr = tempKdc.substring(pos+2);
            }
        } else {
            int colon = tempKdc.indexOf(':');
            if (colon == -1) {      // Hostname or IPv4 host only
                kdc = tempKdc;
            } else {
                int nextColon = tempKdc.indexOf(':', colon+1);
                if (nextColon > 0) {    // >=2 ":", IPv6 with no port
                    kdc = tempKdc;
                } else {                // 1 ":", hostname or IPv4 with port
                    kdc = tempKdc.substring(0, colon);
                    portStr = tempKdc.substring(colon+1);
                }
            }
        }
        if (portStr != null) {
D
duke 已提交
305 306 307 308 309 310 311 312 313 314 315
            int tempPort = parsePositiveIntString(portStr);
            if (tempPort > 0)
                port = tempPort;
        }

        if (DEBUG) {
            System.out.println(">>> KrbKdcReq send: kdc=" + kdc
                               + (useTCP ? " TCP:":" UDP:")
                               +  port +  ", timeout="
                               + timeout
                               + ", number of retries ="
316
                               + retries
D
duke 已提交
317 318 319 320
                               + ", #bytes=" + obuf.length);
        }

        KdcCommunication kdcCommunication =
321
            new KdcCommunication(kdc, port, useTCP, timeout, retries, obuf);
D
duke 已提交
322
        try {
323
            byte[] ibuf = AccessController.doPrivileged(kdcCommunication);
D
duke 已提交
324 325 326 327
            if (DEBUG) {
                System.out.println(">>> KrbKdcReq send: #bytes read="
                        + (ibuf != null ? ibuf.length : 0));
            }
328
            return ibuf;
D
duke 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        } catch (PrivilegedActionException e) {
            Exception wrappedException = e.getException();
            if (wrappedException instanceof IOException) {
                throw (IOException) wrappedException;
            } else {
                throw (KrbException) wrappedException;
            }
        }
    }

    private static class KdcCommunication
        implements PrivilegedExceptionAction<byte[]> {

        private String kdc;
        private int port;
        private boolean useTCP;
        private int timeout;
346
        private int retries;
D
duke 已提交
347 348 349
        private byte[] obuf;

        public KdcCommunication(String kdc, int port, boolean useTCP,
350
                                int timeout, int retries, byte[] obuf) {
D
duke 已提交
351 352 353 354
            this.kdc = kdc;
            this.port = port;
            this.useTCP = useTCP;
            this.timeout = timeout;
355
            this.retries = retries;
D
duke 已提交
356 357 358 359 360 361 362 363 364 365
            this.obuf = obuf;
        }

        // The caller only casts IOException and KrbException so don't
        // add any new ones!

        public byte[] run() throws IOException, KrbException {

            byte[] ibuf = null;

366 367
            for (int i=1; i <= retries; i++) {
                String proto = useTCP?"TCP":"UDP";
368 369
                try (NetClient kdcClient = NetClient.getInstance(
                        proto, kdc, port, timeout)) {
D
duke 已提交
370
                    if (DEBUG) {
371 372 373 374 375 376
                        System.out.println(">>> KDCCommunication: kdc=" + kdc
                            + " " + proto + ":"
                            +  port +  ", timeout="
                            + timeout
                            + ",Attempt =" + i
                            + ", #bytes=" + obuf.length);
D
duke 已提交
377
                    }
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
                    try {
                        /*
                        * Send the data to the kdc.
                        */
                        kdcClient.send(obuf);
                        /*
                        * And get a response.
                        */
                        ibuf = kdcClient.receive();
                        break;
                    } catch (SocketTimeoutException se) {
                        if (DEBUG) {
                            System.out.println ("SocketTimeOutException with " +
                                                "attempt: " + i);
                        }
                        if (i == retries) {
                            ibuf = null;
                            throw se;
                        }
D
duke 已提交
397 398 399 400 401 402 403 404
                    }
                }
            }
            return ibuf;
        }
    }

    /**
405 406 407 408 409 410 411 412 413 414
     * Returns krb5.conf setting of {@code key} for a specfic realm,
     * which can be:
     * 1. defined in the sub-stanza for the given realm inside [realms], or
     * 2. defined in [libdefaults], or
     * 3. defValue
     * @param realm the given realm in which the setting is requested. Returns
     * the global setting if null
     * @param key the key for the setting
     * @param defValue default value
     * @return a value for the key
D
duke 已提交
415
     */
416 417
    private int getRealmSpecificValue(String realm, String key, int defValue) {
        int v = defValue;
D
duke 已提交
418

419
        if (realm == null) return v;
D
duke 已提交
420

421
        int temp = -1;
D
duke 已提交
422
        try {
423 424 425
            String value =
               Config.getInstance().getDefault(key, realm);
            temp = parsePositiveIntString(value);
D
duke 已提交
426
        } catch (Exception exc) {
427
            // Ignored, defValue will be picked up
D
duke 已提交
428 429
        }

430
        if (temp > 0) v = temp;
D
duke 已提交
431

432
        return v;
D
duke 已提交
433 434
    }

435
    private static int parsePositiveIntString(String intString) {
D
duke 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        if (intString == null)
            return -1;

        int ret = -1;

        try {
            ret = Integer.parseInt(intString);
        } catch (Exception exc) {
            return -1;
        }

        if (ret >= 0)
            return ret;

        return -1;
    }
452 453 454 455 456 457 458 459 460 461 462 463

    /**
     * Maintains a KDC accessible list. Unavailable KDCs are put into a
     * blacklist, when a KDC in the blacklist is available, it's removed
     * from there. No insertion order in the blacklist.
     *
     * There are two methods to deal with KDCs in the blacklist. 1. Only try
     * them when there's no KDC not on the blacklist. 2. Still try them, but
     * with lesser number of retries and smaller timeout value.
     */
    static class KdcAccessibility {
        // Known bad KDCs
464
        private static Set<String> bads = new HashSet<>();
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483

        private static synchronized void addBad(String kdc) {
            if (DEBUG) {
                System.out.println(">>> KdcAccessibility: add " + kdc);
            }
            bads.add(kdc);
        }

        private static synchronized void removeBad(String kdc) {
            if (DEBUG) {
                System.out.println(">>> KdcAccessibility: remove " + kdc);
            }
            bads.remove(kdc);
        }

        private static synchronized boolean isBad(String kdc) {
            return bads.contains(kdc);
        }

484
        private static synchronized void reset() {
485 486 487 488 489 490 491 492 493
            if (DEBUG) {
                System.out.println(">>> KdcAccessibility: reset");
            }
            bads.clear();
        }

        // Returns a preferred KDC list by putting the bad ones at the end
        private static synchronized String[] list(String kdcList) {
            StringTokenizer st = new StringTokenizer(kdcList);
494
            List<String> list = new ArrayList<>();
495
            if (badPolicy == BpType.TRY_LAST) {
496
                List<String> badkdcs = new ArrayList<>();
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                while (st.hasMoreTokens()) {
                    String t = st.nextToken();
                    if (bads.contains(t)) badkdcs.add(t);
                    else list.add(t);
                }
                // Bad KDCs are put at last
                list.addAll(badkdcs);
            } else {
                // All KDCs are returned in their original order,
                // This include TRY_LESS and NONE
                while (st.hasMoreTokens()) {
                    list.add(st.nextToken());
                }
            }
            return list.toArray(new String[list.size()]);
        }
    }
D
duke 已提交
514
}
515