CredentialsUtil.java 23.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2019, 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 34
 */

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

package sun.security.krb5.internal;

import sun.security.krb5.*;
M
mbalao 已提交
35 36
import sun.security.util.DerValue;

D
duke 已提交
37
import java.io.IOException;
38 39
import java.util.LinkedList;
import java.util.List;
D
duke 已提交
40 41 42 43 44 45 46 47 48 49

/**
 * This class is a utility that contains much of the TGS-Exchange
 * protocol. It is used by ../Credentials.java for service ticket
 * acquisition in both the normal and the x-realm case.
 */
public class CredentialsUtil {

    private static boolean DEBUG = sun.security.krb5.internal.Krb5.DEBUG;

M
mbalao 已提交
50 51 52 53
    private static enum S4U2Type {
        NONE, SELF, PROXY
    }

54 55 56 57 58 59 60 61 62
    /**
     * Used by a middle server to acquire credentials on behalf of a
     * client to itself using the S4U2self extension.
     * @param client the client to impersonate
     * @param ccreds the TGT of the middle service
     * @return the new creds (cname=client, sname=middle)
     */
    public static Credentials acquireS4U2selfCreds(PrincipalName client,
            Credentials ccreds) throws KrbException, IOException {
M
mbalao 已提交
63 64 65 66
        if (!ccreds.isForwardable()) {
            throw new KrbException("S4U2self needs a FORWARDABLE ticket");
        }
        PrincipalName sname = ccreds.getClient();
67 68 69
        String uRealm = client.getRealmString();
        String localRealm = ccreds.getClient().getRealmString();
        if (!uRealm.equals(localRealm)) {
M
mbalao 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
            // Referrals will be required because the middle service
            // and the client impersonated are on different realms.
            if (Config.DISABLE_REFERRALS) {
                throw new KrbException("Cross-realm S4U2Self request not" +
                        " possible when referrals are disabled.");
            }
            if (ccreds.getClientAlias() != null) {
                // If the name was canonicalized, the user pick
                // has preference. This gives the possibility of
                // using FQDNs that KDCs may use to return referrals.
                // I.e.: a SVC/host.realm-2.com@REALM-1.COM name
                // may be used by REALM-1.COM KDC to return a
                // referral to REALM-2.COM.
                sname = ccreds.getClientAlias();
            }
            sname = new PrincipalName(sname.getNameType(),
                    sname.getNameStrings(), new Realm(uRealm));
87
        }
M
mbalao 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100
        Credentials creds = serviceCreds(
                KDCOptions.with(KDCOptions.FORWARDABLE),
                ccreds, ccreds.getClient(), sname, null,
                new PAData[] {
                        new PAData(Krb5.PA_FOR_USER,
                                new PAForUserEnc(client,
                                        ccreds.getSessionKey()).asn1Encode()),
                        new PAData(Krb5.PA_PAC_OPTIONS,
                                new PaPacOptions()
                                        .setResourceBasedConstrainedDelegation(true)
                                        .setClaims(true)
                                        .asn1Encode())
                        }, S4U2Type.SELF);
101 102 103
        if (!creds.getClient().equals(client)) {
            throw new KrbException("S4U2self request not honored by KDC");
        }
104 105 106
        if (!creds.isForwardable()) {
            throw new KrbException("S4U2self ticket must be FORWARDABLE");
        }
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        return creds;
    }

    /**
     * Used by a middle server to acquire a service ticket to a backend
     * server using the S4U2proxy extension.
     * @param backend the name of the backend service
     * @param second the client's service ticket to the middle server
     * @param ccreds the TGT of the middle server
     * @return the creds (cname=client, sname=backend)
     */
    public static Credentials acquireS4U2proxyCreds(
                String backend, Ticket second,
                PrincipalName client, Credentials ccreds)
            throws KrbException, IOException {
M
mbalao 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        PrincipalName backendPrincipal = new PrincipalName(backend);
        String backendRealm = backendPrincipal.getRealmString();
        String localRealm = ccreds.getClient().getRealmString();
        if (!backendRealm.equals(localRealm)) {
            // The middle service and the backend service are on
            // different realms, so referrals will be required.
            if (Config.DISABLE_REFERRALS) {
                throw new KrbException("Cross-realm S4U2Proxy request not" +
                        " possible when referrals are disabled.");
            }
            backendPrincipal = new PrincipalName(
                    backendPrincipal.getNameType(),
                    backendPrincipal.getNameStrings(),
                    new Realm(localRealm));
        }
137 138
        Credentials creds = serviceCreds(KDCOptions.with(
                KDCOptions.CNAME_IN_ADDL_TKT, KDCOptions.FORWARDABLE),
M
mbalao 已提交
139 140 141 142 143 144 145 146
                ccreds, ccreds.getClient(), backendPrincipal,
                new Ticket[] {second}, new PAData[] {
                        new PAData(Krb5.PA_PAC_OPTIONS,
                                new PaPacOptions()
                                        .setResourceBasedConstrainedDelegation(true)
                                        .setClaims(true)
                                        .asn1Encode())
                        }, S4U2Type.PROXY);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        if (!creds.getClient().equals(client)) {
            throw new KrbException("S4U2proxy request not honored by KDC");
        }
        return creds;
    }

    /**
     * Acquires credentials for a specified service using initial
     * credential. When the service has a different realm from the initial
     * credential, we do cross-realm authentication - first, we use the
     * current credential to get a cross-realm credential from the local KDC,
     * then use that cross-realm credential to request service credential
     * from the foreign KDC.
     *
     * @param service the name of service principal
     * @param ccreds client's initial credential
     */
D
duke 已提交
164 165
    public static Credentials acquireServiceCreds(
                String service, Credentials ccreds)
166
            throws KrbException, IOException {
167 168 169
        PrincipalName sname = new PrincipalName(service,
                PrincipalName.KRB_NT_SRV_HST);
        return serviceCreds(sname, ccreds);
170 171 172 173 174
    }

    /**
     * Gets a TGT to another realm
     * @param localRealm this realm
175
     * @param serviceRealm the other realm, cannot equals to localRealm
176 177 178 179 180 181 182 183 184
     * @param ccreds TGT in this realm
     * @param okAsDelegate an [out] argument to receive the okAsDelegate
     * property. True only if all realms allow delegation.
     * @return the TGT for the other realm, null if cannot find a path
     * @throws KrbException if something goes wrong
     */
    private static Credentials getTGTforRealm(String localRealm,
            String serviceRealm, Credentials ccreds, boolean[] okAsDelegate)
            throws KrbException {
D
duke 已提交
185 186 187 188 189 190

        // Get a list of realms to traverse
        String[] realms = Realm.getRealmsList(localRealm, serviceRealm);

        int i = 0, k = 0;
        Credentials cTgt = null, newTgt = null, theTgt = null;
191
        PrincipalName tempService = null;
192
        String newTgtRealm = null;
D
duke 已提交
193

194 195
        okAsDelegate[0] = true;
        for (cTgt = ccreds, i = 0; i < realms.length;) {
196
            tempService = PrincipalName.tgsService(serviceRealm, realms[i]);
D
duke 已提交
197

198 199 200 201
            if (DEBUG) {
                System.out.println(
                        ">>> Credentials acquireServiceCreds: main loop: ["
                        + i +"] tempService=" + tempService);
D
duke 已提交
202 203 204 205 206 207 208 209
            }

            try {
                newTgt = serviceCreds(tempService, cTgt);
            } catch (Exception exc) {
                newTgt = null;
            }

210 211 212
            if (newTgt == null) {
                if (DEBUG) {
                    System.out.println(">>> Credentials acquireServiceCreds: "
213
                            + "no tgt; searching thru capath");
D
duke 已提交
214 215 216
                }

                /*
217
                 * No tgt found. Let's go thru the realms list one by one.
D
duke 已提交
218
                 */
219 220
                for (newTgt = null, k = i+1;
                        newTgt == null && k < realms.length; k++) {
221
                    tempService = PrincipalName.tgsService(realms[k], realms[i]);
222 223 224 225 226
                    if (DEBUG) {
                        System.out.println(
                                ">>> Credentials acquireServiceCreds: "
                                + "inner loop: [" + k
                                + "] tempService=" + tempService);
D
duke 已提交
227 228 229 230 231 232 233 234 235
                    }
                    try {
                        newTgt = serviceCreds(tempService, cTgt);
                    } catch (Exception exc) {
                        newTgt = null;
                    }
                }
            } // Ends 'if (newTgt == null)'

236 237 238 239
            if (newTgt == null) {
                if (DEBUG) {
                    System.out.println(">>> Credentials acquireServiceCreds: "
                            + "no tgt; cannot get creds");
D
duke 已提交
240 241 242 243 244 245 246 247 248
                }
                break;
            }

            /*
             * We have a tgt. It may or may not be for the target.
             * If it's for the target realm, we're done looking for a tgt.
             */
            newTgtRealm = newTgt.getServer().getInstanceComponent();
249 250
            if (okAsDelegate[0] && !newTgt.checkDelegate()) {
                if (DEBUG) {
W
weijun 已提交
251 252 253 254
                    System.out.println(">>> Credentials acquireServiceCreds: " +
                            "global OK-AS-DELEGATE turned off at " +
                            newTgt.getServer());
                }
255
                okAsDelegate[0] = false;
W
weijun 已提交
256
            }
D
duke 已提交
257

258 259 260
            if (DEBUG) {
                System.out.println(">>> Credentials acquireServiceCreds: "
                        + "got tgt");
D
duke 已提交
261 262
            }

263
            if (newTgtRealm.equals(serviceRealm)) {
D
duke 已提交
264 265 266 267 268 269 270 271 272 273
                /* We got the right tgt */
                theTgt = newTgt;
                break;
            }

            /*
             * The new tgt is not for the target realm.
             * See if the realm of the new tgt is in the list of realms
             * and continue looking from there.
             */
274 275
            for (k = i+1; k < realms.length; k++) {
                if (newTgtRealm.equals(realms[k])) {
D
duke 已提交
276 277 278 279
                    break;
                }
            }

280
            if (k < realms.length) {
D
duke 已提交
281 282 283 284 285 286 287
                /*
                 * (re)set the counter so we start looking
                 * from the realm we just obtained a tgt for.
                 */
                i = k;
                cTgt = newTgt;

288 289 290
                if (DEBUG) {
                    System.out.println(">>> Credentials acquireServiceCreds: "
                            + "continuing with main loop counter reset to " + i);
D
duke 已提交
291 292 293
                }
                continue;
            }
294
            else {
D
duke 已提交
295
                /*
296
                 * The new tgt's realm is not in the hierarchy of realms.
D
duke 已提交
297 298 299 300 301 302 303 304
                 * It's probably not safe to get a tgt from
                 * a tgs that is outside the known list of realms.
                 * Give up now.
                 */
                break;
            }
        } // Ends outermost/main 'for' loop

305
        return theTgt;
D
duke 已提交
306 307 308 309 310 311
    }

   /*
    * This method does the real job to request the service credential.
    */
    private static Credentials serviceCreds(
312
            PrincipalName service, Credentials ccreds)
D
duke 已提交
313
            throws KrbException, IOException {
314
        return serviceCreds(new KDCOptions(), ccreds,
M
mbalao 已提交
315 316
                ccreds.getClient(), service, null, null,
                S4U2Type.NONE);
317 318 319 320 321 322 323 324 325 326 327
    }

    /*
     * Obtains credentials for a service (TGS).
     * Cross-realm referrals are handled if enabled. A fallback scheme
     * without cross-realm referrals supports is used in case of server
     * error to maintain backward compatibility.
     */
    private static Credentials serviceCreds(
            KDCOptions options, Credentials asCreds,
            PrincipalName cname, PrincipalName sname,
M
mbalao 已提交
328 329
            Ticket[] additionalTickets, PAData[] extraPAs,
            S4U2Type s4u2Type)
330 331 332
            throws KrbException, IOException {
        if (!Config.DISABLE_REFERRALS) {
            try {
M
mbalao 已提交
333 334
                return serviceCredsReferrals(options, asCreds, cname, sname,
                        s4u2Type, additionalTickets, extraPAs);
335 336 337 338 339
            } catch (KrbException e) {
                // Server may raise an error if CANONICALIZE is true.
                // Try CANONICALIZE false.
            }
        }
340
        return serviceCredsSingle(options, asCreds, cname,
M
mbalao 已提交
341 342
                asCreds.getClientAlias(), sname, sname, s4u2Type,
                additionalTickets, extraPAs);
343 344 345 346 347 348 349 350 351
    }

    /*
     * Obtains credentials for a service (TGS).
     * May handle and follow cross-realm referrals as defined by RFC 6806.
     */
    private static Credentials serviceCredsReferrals(
            KDCOptions options, Credentials asCreds,
            PrincipalName cname, PrincipalName sname,
M
mbalao 已提交
352 353 354
            S4U2Type s4u2Type, Ticket[] additionalTickets,
            PAData[] extraPAs)
                    throws KrbException, IOException {
355 356 357
        options = new KDCOptions(options.toBooleanArray());
        options.set(KDCOptions.CANONICALIZE, true);
        PrincipalName cSname = sname;
358
        PrincipalName refSname = sname; // May change with referrals
359 360 361
        Credentials creds = null;
        boolean isReferral = false;
        List<String> referrals = new LinkedList<>();
362
        PrincipalName clientAlias = asCreds.getClientAlias();
363 364
        while (referrals.size() <= Config.MAX_REFERRALS) {
            ReferralsCache.ReferralCacheEntry ref =
365
                    ReferralsCache.get(cname, sname, refSname.getRealmString());
366 367
            String toRealm = null;
            if (ref == null) {
368
                creds = serviceCredsSingle(options, asCreds, cname,
M
mbalao 已提交
369 370
                        clientAlias, refSname, cSname, s4u2Type,
                        additionalTickets, extraPAs);
371
                PrincipalName server = creds.getServer();
372
                if (!refSname.equals(server)) {
373 374 375 376
                    String[] serverNameStrings = server.getNameStrings();
                    if (serverNameStrings.length == 2 &&
                        serverNameStrings[0].equals(
                                PrincipalName.TGS_DEFAULT_SRV_NAME) &&
M
mbalao 已提交
377 378
                        !refSname.getRealmAsString().equals(
                                serverNameStrings[1])) {
379 380
                        // Server Name (sname) has the following format:
                        //      krbtgt/TO-REALM.COM@FROM-REALM.COM
M
mbalao 已提交
381 382 383 384 385 386 387 388 389
                        if (s4u2Type == S4U2Type.NONE) {
                            // Do not store S4U2Self or S4U2Proxy referral
                            // TGTs in the cache. Caching such tickets is not
                            // defined in MS-SFU and may cause unexpected
                            // results when using them in a different context.
                            ReferralsCache.put(cname, sname,
                                    server.getRealmString(),
                                    serverNameStrings[1], creds);
                        }
390 391 392 393 394
                        toRealm = serverNameStrings[1];
                        isReferral = true;
                    }
                }
            } else {
M
mbalao 已提交
395
                creds = ref.getCreds();
396 397 398 399
                toRealm = ref.getToRealm();
                isReferral = true;
            }
            if (isReferral) {
M
mbalao 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
                if (s4u2Type == S4U2Type.PROXY) {
                    Credentials[] credsInOut =
                            new Credentials[] {creds, null};
                    toRealm = handleS4U2ProxyReferral(asCreds,
                            credsInOut, sname);
                    creds = credsInOut[0];
                    if (additionalTickets == null ||
                            additionalTickets.length == 0 ||
                            credsInOut[1] == null) {
                        throw new KrbException("Additional tickets expected" +
                                " for S4U2Proxy.");
                    }
                    additionalTickets[0] = credsInOut[1].getTicket();
                } else if (s4u2Type == S4U2Type.SELF) {
                    handleS4U2SelfReferral(extraPAs, asCreds, creds);
                }
416 417 418 419
                if (referrals.contains(toRealm)) {
                    // Referrals loop detected
                    return null;
                }
M
mbalao 已提交
420
                asCreds = creds;
421 422
                refSname = new PrincipalName(refSname.getNameString(),
                        refSname.getNameType(), toRealm);
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                referrals.add(toRealm);
                isReferral = false;
                continue;
            }
            break;
        }
        return creds;
    }

    /*
     * Obtains credentials for a service (TGS).
     * If the service realm is different than the one in the TGT, a new TGT for
     * the service realm is obtained first (see getTGTforRealm call). This is
     * not expected when following cross-realm referrals because the referral
     * TGT realm matches the service realm.
     */
    private static Credentials serviceCredsSingle(
            KDCOptions options, Credentials asCreds,
441 442
            PrincipalName cname, PrincipalName clientAlias,
            PrincipalName refSname, PrincipalName sname,
M
mbalao 已提交
443 444 445
            S4U2Type s4u2Type, Ticket[] additionalTickets,
            PAData[] extraPAs)
                    throws KrbException, IOException {
446 447 448 449
        Credentials theCreds = null;
        boolean[] okAsDelegate = new boolean[]{true};
        String[] serverAsCredsNames = asCreds.getServer().getNameStrings();
        String tgtRealm = serverAsCredsNames[1];
450
        String serviceRealm = refSname.getRealmString();
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        if (!serviceRealm.equals(tgtRealm)) {
            // This is a cross-realm service request
            if (DEBUG) {
                System.out.println(">>> serviceCredsSingle:" +
                        " cross-realm authentication");
                System.out.println(">>> serviceCredsSingle:" +
                        " obtaining credentials from " + tgtRealm +
                        " to " + serviceRealm);
            }
            Credentials newTgt = getTGTforRealm(tgtRealm, serviceRealm,
                    asCreds, okAsDelegate);
            if (newTgt == null) {
                throw new KrbApErrException(Krb5.KRB_AP_ERR_GEN_CRED,
                        "No service creds");
            }
            if (DEBUG) {
                System.out.println(">>> Cross-realm TGT Credentials" +
                        " serviceCredsSingle: ");
                Credentials.printDebug(newTgt);
            }
M
mbalao 已提交
471 472 473
            if (s4u2Type == S4U2Type.SELF) {
                handleS4U2SelfReferral(extraPAs, asCreds, newTgt);
            }
474 475 476 477 478 479
            asCreds = newTgt;
            cname = asCreds.getClient();
        } else if (DEBUG) {
            System.out.println(">>> Credentials serviceCredsSingle:" +
                    " same realm");
        }
480 481
        KrbTgsReq req = new KrbTgsReq(options, asCreds, cname, clientAlias,
                refSname, sname, additionalTickets, extraPAs);
482 483 484 485 486 487 488 489 490 491 492
        theCreds = req.sendAndGetCreds();
        if (theCreds != null) {
            if (DEBUG) {
                System.out.println(">>> TGS credentials serviceCredsSingle:");
                Credentials.printDebug(theCreds);
            }
            if (!okAsDelegate[0]) {
                theCreds.resetDelegate();
            }
        }
        return theCreds;
D
duke 已提交
493
    }
M
mbalao 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

    /**
     * PA-FOR-USER may need to be regenerated if credentials
     * change. This may happen when obtaining a TGT for a
     * different realm or when using a referral TGT.
     */
    private static void handleS4U2SelfReferral(PAData[] pas,
            Credentials oldCeds, Credentials newCreds)
                    throws Asn1Exception, KrbException, IOException {
        if (DEBUG) {
            System.out.println(">>> Handling S4U2Self referral");
        }
        for (int i = 0; i < pas.length; i++) {
            PAData pa = pas[i];
            if (pa.getType() == Krb5.PA_FOR_USER) {
                PAForUserEnc paForUser = new PAForUserEnc(
                        new DerValue(pa.getValue()),
                        oldCeds.getSessionKey());
                pas[i] = new PAData(Krb5.PA_FOR_USER,
                        new PAForUserEnc(paForUser.getName(),
                                newCreds.getSessionKey()).asn1Encode());
                break;
            }
        }
    }

    /**
     * This method is called after receiving the first realm referral for
     * a S4U2Proxy request. The credentials and tickets needed for the
     * final S4U2Proxy request (in the referrals chain) are returned.
     *
     * Referrals are handled as described by MS-SFU (section 3.1.5.2.2
     * Receives Referral).
     *
     * @param asCreds middle service credentials used for the first S4U2Proxy
     *        request
     * @param credsInOut (in/out parameter):
     *         * input: first S4U2Proxy referral TGT received, null
     *         * output: referral TGT for final S4U2Proxy service request,
     *                   client referral TGT for final S4U2Proxy service request
     *                   (to be sent as additional-ticket)
     * @param sname the backend service name
     * @param additionalTickets (out parameter): the additional ticket for the
     *        last S4U2Proxy request is returned
     * @return the backend realm for the last S4U2Proxy request
     */
    private static String handleS4U2ProxyReferral(Credentials asCreds,
            Credentials[] credsInOut, PrincipalName sname)
                    throws KrbException, IOException {
        if (DEBUG) {
            System.out.println(">>> Handling S4U2Proxy referral");
        }
        Credentials refTGT = null;
        // Get a credential for the middle service to the backend so we know
        // the backend realm, as described in MS-SFU (section 3.1.5.2.2).
        Credentials middleSvcCredsInBackendRealm =
                serviceCreds(sname, asCreds);
        String backendRealm =
                middleSvcCredsInBackendRealm.getServer().getRealmString();
        String toRealm = credsInOut[0].getServer().getNameStrings()[1];
        if (!toRealm.equals(backendRealm)) {
            // More than 1 hop. Follow the referrals chain and obtain a
            // TGT for the backend realm.
            refTGT = getTGTforRealm(toRealm, backendRealm, credsInOut[0],
                    new boolean[1]);
        } else {
            // There was only 1 hop. The referral TGT received is already
            // for the backend realm.
            refTGT = credsInOut[0];
        }
        credsInOut[0] = getTGTforRealm(asCreds.getClient().getRealmString(),
                backendRealm, asCreds, new boolean[1]);
        credsInOut[1] = refTGT;
        return backendRealm;
    }
D
duke 已提交
569
}