KdcComm.java 18.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2012, 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");
D
duke 已提交
147
            timeout = parsePositiveIntString(temp);
W
weijun 已提交
148
            temp = cfg.get("libdefaults", "max_retries");
149
            max_retries = parsePositiveIntString(temp);
W
weijun 已提交
150
            temp = cfg.get("libdefaults", "udp_preference_limit");
151
            udp_pref_limit = parsePositiveIntString(temp);
D
duke 已提交
152
        } catch (Exception exc) {
153
           // ignore any exceptions; use default values
D
duke 已提交
154
           if (DEBUG) {
155 156
                System.out.println ("Exception in getting KDC communication " +
                                    "settings, using default value " +
D
duke 已提交
157 158 159
                                    exc.getMessage());
           }
        }
160 161 162
        defaultKdcTimeout = timeout > 0 ? timeout : 30*1000; // 30 seconds
        defaultKdcRetryLimit =
                max_retries > 0 ? max_retries : Krb5.KDC_RETRY_LIMIT;
163 164 165 166 167 168 169 170

        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 已提交
171

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

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

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

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

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

202
    private byte[] send(byte[] obuf, boolean useTCP)
D
duke 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        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);
        }
221 222 223 224 225
        // 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);
        }
226
        byte[] ibuf = null;
227
        try {
C
Merge  
chegar 已提交
228
            ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);
229 230
        } catch(Exception first) {
            while(tempKdc.hasNext()) {
231
                try {
C
Merge  
chegar 已提交
232 233 234 235
                    ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);
                    if (ibuf != null) {
                        return ibuf;
                    }
236
                } catch(Exception ignore) {}
D
duke 已提交
237
            }
238
            throw first;
D
duke 已提交
239
        }
240
        if (ibuf == null) {
C
Merge  
chegar 已提交
241
            throw new IOException("Cannot get a KDC reply");
D
duke 已提交
242
        }
243
        return ibuf;
D
duke 已提交
244 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
    // 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 已提交
270
            }
271 272
            KdcAccessibility.addBad(tempKdc);
            throw e;
D
duke 已提交
273 274 275 276 277
        }
    }

    // send the AS Request to the specified KDC

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

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

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

W
weijun 已提交
299 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
        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 已提交
329 330 331 332 333 334 335 336 337 338 339
            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 ="
340
                               + retries
D
duke 已提交
341 342 343 344
                               + ", #bytes=" + obuf.length);
        }

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

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

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

    /**
429 430 431 432 433 434 435 436 437 438
     * 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 已提交
439
     */
440 441
    private int getRealmSpecificValue(String realm, String key, int defValue) {
        int v = defValue;
D
duke 已提交
442

443
        if (realm == null) return v;
D
duke 已提交
444

445
        int temp = -1;
D
duke 已提交
446
        try {
447
            String value =
W
weijun 已提交
448
               Config.getInstance().get("realms", realm, key);
449
            temp = parsePositiveIntString(value);
D
duke 已提交
450
        } catch (Exception exc) {
451
            // Ignored, defValue will be picked up
D
duke 已提交
452 453
        }

454
        if (temp > 0) v = temp;
D
duke 已提交
455

456
        return v;
D
duke 已提交
457 458
    }

459
    private static int parsePositiveIntString(String intString) {
D
duke 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
        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;
    }
476 477 478 479 480 481 482 483 484 485 486 487

    /**
     * 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
488
        private static Set<String> bads = new HashSet<>();
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

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

508
        private static synchronized void reset() {
509 510 511 512 513 514 515
            if (DEBUG) {
                System.out.println(">>> KdcAccessibility: reset");
            }
            bads.clear();
        }

        // Returns a preferred KDC list by putting the bad ones at the end
516
        private static synchronized List<String> list(String kdcList) {
517
            StringTokenizer st = new StringTokenizer(kdcList);
518
            List<String> list = new ArrayList<>();
519
            if (badPolicy == BpType.TRY_LAST) {
520
                List<String> badkdcs = new ArrayList<>();
521 522 523 524 525 526 527 528 529 530 531 532 533 534
                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());
                }
            }
535
            return list;
536 537
        }
    }
D
duke 已提交
538
}
539