KdcComm.java 19.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2014, 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 java.util.Iterator;
50
import sun.security.krb5.internal.KRBError;
D
duke 已提交
51

52 53 54 55 56
/**
 * 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 已提交
57

58 59 60
    // 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 已提交
61 62

    /**
63 64 65 66 67 68 69 70 71
     * 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 已提交
72
     */
73
    private static int defaultUdpPrefLimit;
D
duke 已提交
74 75 76

    private static final boolean DEBUG = Krb5.DEBUG;

77 78 79 80 81
    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.
82
     * Possible values can be TRY_LAST or TRY_LESS. Reloaded when refreshed.
83 84 85 86 87 88 89
     */
    private enum BpType {
        NONE, TRY_LAST, TRY_LESS
    }
    private static int tryLessMaxRetries = 1;
    private static int tryLessTimeout = 5000;

90
    private static BpType badPolicy;
91

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

    /**
     * Read global settings
     */
    public static void initStatic() {
100 101 102 103 104 105 106 107 108 109 110 111
        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(",");
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
                    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");
                        }
127 128 129 130 131 132 133 134 135 136 137
                    }
                }
                badPolicy = BpType.TRY_LESS;
            } else if ("trylast".equals(ss[0])) {
                badPolicy = BpType.TRY_LAST;
            } else {
                badPolicy = BpType.NONE;
            }
        } else {
            badPolicy = BpType.NONE;
        }
D
duke 已提交
138 139 140


        int timeout = -1;
141
        int max_retries = -1;
142
        int udp_pref_limit = -1;
143

D
duke 已提交
144 145
        try {
            Config cfg = Config.getInstance();
W
weijun 已提交
146
            String temp = cfg.get("libdefaults", "kdc_timeout");
147 148
            timeout = parseTimeString(temp);

W
weijun 已提交
149
            temp = cfg.get("libdefaults", "max_retries");
150
            max_retries = parsePositiveIntString(temp);
W
weijun 已提交
151
            temp = cfg.get("libdefaults", "udp_preference_limit");
152
            udp_pref_limit = parsePositiveIntString(temp);
D
duke 已提交
153
        } catch (Exception exc) {
154
           // ignore any exceptions; use default values
D
duke 已提交
155
           if (DEBUG) {
156 157
                System.out.println ("Exception in getting KDC communication " +
                                    "settings, using default value " +
D
duke 已提交
158 159 160
                                    exc.getMessage());
           }
        }
161 162 163
        defaultKdcTimeout = timeout > 0 ? timeout : 30*1000; // 30 seconds
        defaultKdcRetryLimit =
                max_retries > 0 ? max_retries : Krb5.KDC_RETRY_LIMIT;
164 165 166 167 168 169 170 171

        if (udp_pref_limit < 0) {
            defaultUdpPrefLimit = Krb5.KDC_DEFAULT_UDP_PREF_LIMIT;
        } else if (udp_pref_limit > Krb5.KDC_HARD_UDP_LIMIT) {
            defaultUdpPrefLimit = Krb5.KDC_HARD_UDP_LIMIT;
        } else {
            defaultUdpPrefLimit = udp_pref_limit;
        }
D
duke 已提交
172

173
        KdcAccessibility.reset();
D
duke 已提交
174 175 176
    }

    /**
177
     * The instance fields
D
duke 已提交
178
     */
179 180 181 182 183 184 185 186 187 188 189 190
    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 已提交
191

192
    public byte[] send(byte[] obuf)
D
duke 已提交
193
        throws IOException, KrbException {
194 195 196
        int udpPrefLimit = getRealmSpecificValue(
                realm, "udp_preference_limit", defaultUdpPrefLimit);

D
duke 已提交
197 198 199
        boolean useTCP = (udpPrefLimit > 0 &&
             (obuf != null && obuf.length > udpPrefLimit));

200
        return send(obuf, useTCP);
D
duke 已提交
201 202
    }

203
    private byte[] send(byte[] obuf, boolean useTCP)
D
duke 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        throws IOException, KrbException {

        if (obuf == null)
            return 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);
        }
222 223 224 225 226
        // tempKdc may include the port number also
        Iterator<String> tempKdc = KdcAccessibility.list(kdcList).iterator();
        if (!tempKdc.hasNext()) {
            throw new KrbException("Cannot get kdc for realm " + realm);
        }
227
        byte[] ibuf = null;
228
        try {
C
Merge  
chegar 已提交
229
            ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);
230
        } catch(Exception first) {
W
weijun 已提交
231
            boolean ok = false;
232
            while(tempKdc.hasNext()) {
233
                try {
C
Merge  
chegar 已提交
234
                    ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);
W
weijun 已提交
235 236
                    ok = true;
                    break;
237
                } catch(Exception ignore) {}
D
duke 已提交
238
            }
W
weijun 已提交
239
            if (!ok) throw first;
D
duke 已提交
240
        }
241
        if (ibuf == null) {
C
Merge  
chegar 已提交
242
            throw new IOException("Cannot get a KDC reply");
D
duke 已提交
243
        }
244
        return ibuf;
D
duke 已提交
245 246
    }

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    // send the AS Request to the specified KDC
    // failover to using TCP if useTCP is not set and response is too big
    private byte[] sendIfPossible(byte[] obuf, String tempKdc, boolean useTCP)
        throws IOException, KrbException {

        try {
            byte[] 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);
            }
            KdcAccessibility.removeBad(tempKdc);
            return ibuf;
        } catch(Exception e) {
            if (DEBUG) {
                System.out.println(">>> KrbKdcReq send: error trying " +
                        tempKdc);
                e.printStackTrace(System.out);
D
duke 已提交
271
            }
272 273
            KdcAccessibility.addBad(tempKdc);
            throw e;
D
duke 已提交
274 275 276 277 278
        }
    }

    // send the AS Request to the specified KDC

279
    private byte[] send(byte[] obuf, String tempKdc, boolean useTCP)
D
duke 已提交
280 281 282
        throws IOException, KrbException {

        if (obuf == null)
283
            return null;
D
duke 已提交
284

285
        int port = Krb5.KDC_INET_DEFAULT_PORT;
286 287 288 289
        int retries = getRealmSpecificValue(
                realm, "max_retries", defaultKdcRetryLimit);
        int timeout = getRealmSpecificValue(
                realm, "kdc_timeout", defaultKdcTimeout);
290 291 292 293 294 295 296 297 298 299
        if (badPolicy == BpType.TRY_LESS &&
                KdcAccessibility.isBad(tempKdc)) {
            if (retries > tryLessMaxRetries) {
                retries = tryLessMaxRetries; // less retries
            }
            if (timeout > tryLessTimeout) {
                timeout = tryLessTimeout; // less time
            }
        }

W
weijun 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        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 已提交
330 331 332 333 334 335 336 337 338 339 340
            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 ="
341
                               + retries
D
duke 已提交
342 343 344 345
                               + ", #bytes=" + obuf.length);
        }

        KdcCommunication kdcCommunication =
346
            new KdcCommunication(kdc, port, useTCP, timeout, retries, obuf);
D
duke 已提交
347
        try {
348
            byte[] ibuf = AccessController.doPrivileged(kdcCommunication);
D
duke 已提交
349 350 351 352
            if (DEBUG) {
                System.out.println(">>> KrbKdcReq send: #bytes read="
                        + (ibuf != null ? ibuf.length : 0));
            }
353
            return ibuf;
D
duke 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
        } 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;
371
        private int retries;
D
duke 已提交
372 373 374
        private byte[] obuf;

        public KdcCommunication(String kdc, int port, boolean useTCP,
375
                                int timeout, int retries, byte[] obuf) {
D
duke 已提交
376 377 378 379
            this.kdc = kdc;
            this.port = port;
            this.useTCP = useTCP;
            this.timeout = timeout;
380
            this.retries = retries;
D
duke 已提交
381 382 383 384 385 386 387 388 389 390
            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;

391 392
            for (int i=1; i <= retries; i++) {
                String proto = useTCP?"TCP":"UDP";
393 394
                try (NetClient kdcClient = NetClient.getInstance(
                        proto, kdc, port, timeout)) {
D
duke 已提交
395
                    if (DEBUG) {
396 397 398 399 400 401
                        System.out.println(">>> KDCCommunication: kdc=" + kdc
                            + " " + proto + ":"
                            +  port +  ", timeout="
                            + timeout
                            + ",Attempt =" + i
                            + ", #bytes=" + obuf.length);
D
duke 已提交
402
                    }
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
                    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 已提交
422 423 424 425 426 427 428
                    }
                }
            }
            return ibuf;
        }
    }

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    /**
     * Parses a time value string. If it ends with "s", parses as seconds.
     * Otherwise, parses as milliseconds.
     * @param s the time string
     * @return the integer value in milliseconds, or -1 if input is null or
     * has an invalid format
     */
    private static int parseTimeString(String s) {
        if (s == null) {
            return -1;
        }
        if (s.endsWith("s")) {
            int seconds = parsePositiveIntString(s.substring(0, s.length()-1));
            return (seconds < 0) ? -1 : (seconds*1000);
        } else {
            return parsePositiveIntString(s);
        }
    }

D
duke 已提交
448
    /**
449
     * Returns krb5.conf setting of {@code key} for a specific realm,
450 451 452 453 454 455 456 457 458
     * 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 已提交
459
     */
460 461
    private int getRealmSpecificValue(String realm, String key, int defValue) {
        int v = defValue;
D
duke 已提交
462

463
        if (realm == null) return v;
D
duke 已提交
464

465
        int temp = -1;
D
duke 已提交
466
        try {
467
            String value =
W
weijun 已提交
468
               Config.getInstance().get("realms", realm, key);
469 470 471 472 473
            if (key.equals("kdc_timeout")) {
                temp = parseTimeString(value);
            } else {
                temp = parsePositiveIntString(value);
            }
D
duke 已提交
474
        } catch (Exception exc) {
475
            // Ignored, defValue will be picked up
D
duke 已提交
476 477
        }

478
        if (temp > 0) v = temp;
D
duke 已提交
479

480
        return v;
D
duke 已提交
481 482
    }

483
    private static int parsePositiveIntString(String intString) {
D
duke 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        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;
    }
500 501 502 503 504 505 506 507 508 509 510 511

    /**
     * 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
512
        private static Set<String> bads = new HashSet<>();
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

        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);
        }

532
        private static synchronized void reset() {
533 534 535 536 537 538 539
            if (DEBUG) {
                System.out.println(">>> KdcAccessibility: reset");
            }
            bads.clear();
        }

        // Returns a preferred KDC list by putting the bad ones at the end
540
        private static synchronized List<String> list(String kdcList) {
541
            StringTokenizer st = new StringTokenizer(kdcList);
542
            List<String> list = new ArrayList<>();
543
            if (badPolicy == BpType.TRY_LAST) {
544
                List<String> badkdcs = new ArrayList<>();
545 546 547 548 549 550 551 552 553 554 555 556 557 558
                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());
                }
            }
559
            return list;
560 561
        }
    }
D
duke 已提交
562
}
563