Credentials.java 20.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 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 35 36 37 38
 */

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

package sun.security.krb5;

import sun.security.krb5.internal.*;
import sun.security.krb5.internal.ccache.CredentialsCache;
import sun.security.krb5.internal.crypto.EType;
import java.io.IOException;
import java.util.Date;
39
import java.util.Locale;
D
duke 已提交
40 41 42 43 44 45 46 47 48 49 50
import java.net.InetAddress;

/**
 * This class encapsulates the concept of a Kerberos service
 * credential. That includes a Kerberos ticket and an associated
 * session key.
 */
public class Credentials {

    Ticket ticket;
    PrincipalName client;
51
    PrincipalName clientAlias;
D
duke 已提交
52
    PrincipalName server;
53
    PrincipalName serverAlias;
D
duke 已提交
54 55 56 57 58 59 60
    EncryptionKey key;
    TicketFlags flags;
    KerberosTime authTime;
    KerberosTime startTime;
    KerberosTime endTime;
    KerberosTime renewTill;
    HostAddresses cAddr;
61
    AuthorizationData authzData;
D
duke 已提交
62 63 64 65
    private static boolean DEBUG = Krb5.DEBUG;
    private static CredentialsCache cache;
    static boolean alreadyLoaded = false;
    private static boolean alreadyTried = false;
66

67 68 69 70 71 72 73 74 75 76 77
    private Credentials proxy = null;

    public Credentials getProxy() {
        return proxy;
    }

    public Credentials setProxy(Credentials proxy) {
        this.proxy = proxy;
        return this;
    }

78 79
    // Read native ticket with session key type in the given list
    private static native Credentials acquireDefaultNativeCreds(int[] eTypes);
D
duke 已提交
80

81 82
    public Credentials(Ticket new_ticket,
                       PrincipalName new_client,
83
                       PrincipalName new_client_alias,
84
                       PrincipalName new_server,
85
                       PrincipalName new_server_alias,
86 87 88 89 90 91 92 93
                       EncryptionKey new_key,
                       TicketFlags new_flags,
                       KerberosTime authTime,
                       KerberosTime new_startTime,
                       KerberosTime new_endTime,
                       KerberosTime renewTill,
                       HostAddresses cAddr,
                       AuthorizationData authzData) {
94 95 96
        this(new_ticket, new_client, new_client_alias, new_server,
                new_server_alias, new_key, new_flags, authTime,
                new_startTime, new_endTime, renewTill, cAddr);
97 98 99
        this.authzData = authzData;
    }

D
duke 已提交
100 101
    public Credentials(Ticket new_ticket,
                       PrincipalName new_client,
102
                       PrincipalName new_client_alias,
D
duke 已提交
103
                       PrincipalName new_server,
104
                       PrincipalName new_server_alias,
D
duke 已提交
105 106 107 108 109 110 111 112 113
                       EncryptionKey new_key,
                       TicketFlags new_flags,
                       KerberosTime authTime,
                       KerberosTime new_startTime,
                       KerberosTime new_endTime,
                       KerberosTime renewTill,
                       HostAddresses cAddr) {
        ticket = new_ticket;
        client = new_client;
114
        clientAlias = new_client_alias;
D
duke 已提交
115
        server = new_server;
116
        serverAlias = new_server_alias;
D
duke 已提交
117 118 119 120 121 122 123 124 125 126 127
        key = new_key;
        flags = new_flags;
        this.authTime = authTime;
        startTime = new_startTime;
        endTime = new_endTime;
        this.renewTill = renewTill;
        this.cAddr = cAddr;
    }

    public Credentials(byte[] encoding,
                       String client,
128
                       String clientAlias,
D
duke 已提交
129
                       String server,
130
                       String serverAlias,
D
duke 已提交
131 132 133 134 135 136 137 138 139 140
                       byte[] keyBytes,
                       int keyType,
                       boolean[] flags,
                       Date authTime,
                       Date startTime,
                       Date endTime,
                       Date renewTill,
                       InetAddress[] cAddrs) throws KrbException, IOException {
        this(new Ticket(encoding),
             new PrincipalName(client, PrincipalName.KRB_NT_PRINCIPAL),
141 142
             (clientAlias == null? null : new PrincipalName(clientAlias,
                     PrincipalName.KRB_NT_PRINCIPAL)),
D
duke 已提交
143
             new PrincipalName(server, PrincipalName.KRB_NT_SRV_INST),
144 145
             (serverAlias == null? null : new PrincipalName(serverAlias,
                     PrincipalName.KRB_NT_SRV_INST)),
D
duke 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
             new EncryptionKey(keyType, keyBytes),
             (flags == null? null: new TicketFlags(flags)),
             (authTime == null? null: new KerberosTime(authTime)),
             (startTime == null? null: new KerberosTime(startTime)),
             (endTime == null? null: new KerberosTime(endTime)),
             (renewTill == null? null: new KerberosTime(renewTill)),
             null); // caddrs are in the encoding at this point
    }

    /**
     * Acquires a service ticket for the specified service
     * principal. If the service ticket is not already available, it
     * obtains a new one from the KDC.
     */
    /*
    public Credentials(Credentials tgt, PrincipalName service)
        throws KrbException {
    }
    */

    public final PrincipalName getClient() {
        return client;
    }

170 171 172 173
    public final PrincipalName getClientAlias() {
        return clientAlias;
    }

D
duke 已提交
174 175 176 177
    public final PrincipalName getServer() {
        return server;
    }

178 179 180 181
    public final PrincipalName getServerAlias() {
        return serverAlias;
    }

D
duke 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    public final EncryptionKey getSessionKey() {
        return key;
    }

    public final Date getAuthTime() {
        if (authTime != null) {
            return authTime.toDate();
        } else {
            return null;
        }
    }

    public final Date getStartTime() {
        if (startTime != null)
            {
                return startTime.toDate();
            }
        return null;
    }

    public final Date getEndTime() {
        if (endTime != null)
            {
                return endTime.toDate();
            }
        return null;
    }

    public final Date getRenewTill() {
        if (renewTill != null)
            {
                return renewTill.toDate();
            }
        return null;
    }

    public final boolean[] getFlags() {
        if (flags == null) // Can be in a KRB-CRED
        return null;
        return flags.toBooleanArray();
    }

    public final InetAddress[] getClientAddresses() {

        if (cAddr == null)
        return null;

        return cAddr.getInetAddresses();
    }

    public final byte[] getEncoded() {
        byte[] retVal = null;
        try {
            retVal = ticket.asn1Encode();
        } catch (Asn1Exception e) {
            if (DEBUG)
            System.out.println(e);
        } catch (IOException ioe) {
            if (DEBUG)
            System.out.println(ioe);
        }
        return retVal;
    }

    public boolean isForwardable() {
        return flags.get(Krb5.TKT_OPTS_FORWARDABLE);
    }

    public boolean isRenewable() {
        return flags.get(Krb5.TKT_OPTS_RENEWABLE);
    }

    public Ticket getTicket() {
        return ticket;
    }

    public TicketFlags getTicketFlags() {
        return flags;
    }

262 263 264
    public AuthorizationData getAuthzData() {
        return authzData;
    }
D
duke 已提交
265 266 267 268 269 270
    /**
     * Checks if the service ticket returned by the KDC has the OK-AS-DELEGATE
     * flag set
     * @return true if OK-AS_DELEGATE flag is set, otherwise, return false.
     */
    public boolean checkDelegate() {
W
weijun 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283
        return flags.get(Krb5.TKT_OPTS_DELEGATE);
    }

    /**
     * Reset TKT_OPTS_DELEGATE to false, called at credentials acquirement
     * when one of the cross-realm TGTs does not have the OK-AS-DELEGATE
     * flag set. This info must be preservable and restorable through
     * the Krb5Util.credsToTicket/ticketToCreds() methods so that even if
     * the service ticket is cached it still remembers the cross-realm
     * authentication result.
     */
    public void resetDelegate() {
        flags.set(Krb5.TKT_OPTS_DELEGATE, false);
D
duke 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296
    }

    public Credentials renew() throws KrbException, IOException {
        KDCOptions options = new KDCOptions();
        options.set(KDCOptions.RENEW, true);
        /*
         * Added here to pass KrbKdcRep.check:73
         */
        options.set(KDCOptions.RENEWABLE, true);

        return new KrbTgsReq(options,
                             this,
                             server,
297
                             serverAlias,
D
duke 已提交
298 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
                             null, // from
                             null, // till
                             null, // rtime
                             null, // eTypes
                             cAddr,
                             null,
                             null,
                             null).sendAndGetCreds();
    }

    /**
     * Returns a TGT for the given client principal from a ticket cache.
     *
     * @param princ the client principal. A value of null means that the
     * default principal name in the credentials cache will be used.
     * @param ticketCache the path to the tickets file. A value
     * of null will be accepted to indicate that the default
     * path should be searched
     * @returns the TGT credentials or null if none were found. If the tgt
     * expired, it is the responsibility of the caller to determine this.
     */
    public static Credentials acquireTGTFromCache(PrincipalName princ,
                                                  String ticketCache)
        throws KrbException, IOException {

        if (ticketCache == null) {
324
            // The default ticket cache on Windows and Mac is not a file.
D
duke 已提交
325 326
            String os = java.security.AccessController.doPrivileged(
                        new sun.security.action.GetPropertyAction("os.name"));
327
            if (os.toUpperCase(Locale.ENGLISH).startsWith("WINDOWS") ||
328
                    os.toUpperCase(Locale.ENGLISH).contains("OS X")) {
D
duke 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
                Credentials creds = acquireDefaultCreds();
                if (creds == null) {
                    if (DEBUG) {
                        System.out.println(">>> Found no TGT's in LSA");
                    }
                    return null;
                }
                if (princ != null) {
                    if (creds.getClient().equals(princ)) {
                        if (DEBUG) {
                            System.out.println(">>> Obtained TGT from LSA: "
                                               + creds);
                        }
                        return creds;
                    } else {
                        if (DEBUG) {
                            System.out.println(">>> LSA contains TGT for "
                                               + creds.getClient()
                                               + " not "
                                               + princ);
                        }
                        return null;
                    }
                } else {
                    if (DEBUG) {
                        System.out.println(">>> Obtained TGT from LSA: "
                                           + creds);
                    }
                    return creds;
                }
            }
        }

        /*
         * Returns the appropriate cache. If ticketCache is null, it is the
         * default cache otherwise it is the cache filename contained in it.
         */
        CredentialsCache ccache =
            CredentialsCache.getInstance(princ, ticketCache);

369
        if (ccache == null) {
D
duke 已提交
370
            return null;
371
        }
D
duke 已提交
372

373
        Credentials tgtCred = ccache.getInitialCreds();
D
duke 已提交
374

375 376 377 378
        if (tgtCred == null) {
            return null;
        }

379 380
        if (EType.isSupported(tgtCred.key.getEType())) {
            return tgtCred;
D
duke 已提交
381 382 383 384
        } else {
            if (DEBUG) {
                System.out.println(
                    ">>> unsupported key type found the default TGT: " +
385
                    tgtCred.key.getEType());
D
duke 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            }
            return null;
        }
    }

    /**
     * Acquires default credentials.
     * <br>The possible locations for default credentials cache is searched in
     * the following order:
     * <ol>
     * <li> The directory and cache file name specified by "KRB5CCNAME" system.
     * property.
     * <li> The directory and cache file name specified by "KRB5CCNAME"
     * environment variable.
     * <li> A cache file named krb5cc_{user.name} at {user.home} directory.
     * </ol>
     * @return a <code>KrbCreds</code> object if the credential is found,
     * otherwise return null.
     */

    // this method is intentionally changed to not check if the caller's
    // principal name matches cache file's principal name.
    // It assumes that the GSS call has
    // the privilege to access the default cache file.

411 412
    // This method is only called on Windows and Mac OS X, the native
    // acquireDefaultNativeCreds is also available on these platforms.
D
duke 已提交
413 414 415 416 417 418 419
    public static synchronized Credentials acquireDefaultCreds() {
        Credentials result = null;

        if (cache == null) {
            cache = CredentialsCache.getInstance();
        }
        if (cache != null) {
420
            Credentials temp = cache.getInitialCreds();
421
            if (temp != null) {
D
duke 已提交
422
                if (DEBUG) {
423 424 425
                    System.out.println(">>> KrbCreds found the default ticket"
                            + " granting ticket in credential cache.");
                }
426 427
                if (EType.isSupported(temp.key.getEType())) {
                    result = temp;
428 429 430 431
                } else {
                    if (DEBUG) {
                        System.out.println(
                            ">>> unsupported key type found the default TGT: " +
432
                            temp.key.getEType());
433
                    }
D
duke 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
                }
            }
        }
        if (result == null) {
            // Doesn't seem to be a default cache on this system or
            // TGT has unsupported encryption type

            if (!alreadyTried) {
                // See if there's any native code to load
                try {
                    ensureLoaded();
                } catch (Exception e) {
                    if (DEBUG) {
                        System.out.println("Can not load credentials cache");
                        e.printStackTrace();
                    }
                    alreadyTried = true;
                }
            }
            if (alreadyLoaded) {
                // There is some native code
455 456 457 458 459 460 461 462 463
                if (DEBUG) {
                    System.out.println(">> Acquire default native Credentials");
                }
                try {
                    result = acquireDefaultNativeCreds(
                            EType.getDefaults("default_tkt_enctypes"));
                } catch (KrbException ke) {
                    // when there is no default_tkt_enctypes.
                }
D
duke 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
            }
        }
        return result;
    }

    /**
     * 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 foreigh KDC.
     *
     * @param service the name of service principal using format
     * components@realm
     * @param ccreds client's initial credential.
     * @exception IOException if an error occurs in reading the credentials
     * cache
     * @exception KrbException if an error occurs specific to Kerberos
     * @return a <code>Credentials</code> object.
     */

    public static Credentials acquireServiceCreds(String service,
                                                  Credentials ccreds)
        throws KrbException, IOException {
        return CredentialsUtil.acquireServiceCreds(service, ccreds);
    }

493 494 495 496 497 498 499 500 501 502 503 504
    public static Credentials acquireS4U2selfCreds(PrincipalName user,
            Credentials ccreds) throws KrbException, IOException {
        return CredentialsUtil.acquireS4U2selfCreds(user, ccreds);
    }

    public static Credentials acquireS4U2proxyCreds(String service,
            Ticket second, PrincipalName client, Credentials ccreds)
        throws KrbException, IOException {
        return CredentialsUtil.acquireS4U2proxyCreds(
                service, second, client, ccreds);
    }

D
duke 已提交
505 506 507 508 509 510 511 512 513 514
    public CredentialsCache getCache() {
        return cache;
    }

    /*
     * Prints out debug info.
     */
    public static void printDebug(Credentials c) {
        System.out.println(">>> DEBUG: ----Credentials----");
        System.out.println("\tclient: " + c.client.toString());
515 516
        if (c.clientAlias != null)
            System.out.println("\tclient alias: " + c.clientAlias.toString());
D
duke 已提交
517
        System.out.println("\tserver: " + c.server.toString());
518 519
        if (c.serverAlias != null)
            System.out.println("\tserver alias: " + c.serverAlias.toString());
520
        System.out.println("\tticket: sname: " + c.ticket.sname.toString());
D
duke 已提交
521 522 523 524 525 526 527 528 529 530 531 532
        if (c.startTime != null) {
            System.out.println("\tstartTime: " + c.startTime.getTime());
        }
        System.out.println("\tendTime: " + c.endTime.getTime());
        System.out.println("        ----Credentials end----");
    }


    static void ensureLoaded() {
        java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction<Void> () {
                        public Void run() {
533
                                if (System.getProperty("os.name").contains("OS X")) {
534 535 536 537
                                    System.loadLibrary("osxkrb5");
                                } else {
                                    System.loadLibrary("w2k_lsa_auth");
                                }
D
duke 已提交
538 539 540 541 542 543 544 545
                                return null;
                        }
                });
        alreadyLoaded = true;
    }

    public String toString() {
        StringBuffer buffer = new StringBuffer("Credentials:");
546
        buffer.append(    "\n      client=").append(client);
547 548
        if (clientAlias != null)
            buffer.append(    "\n      clientAlias=").append(clientAlias);
549
        buffer.append(    "\n      server=").append(server);
550 551
        if (serverAlias != null)
            buffer.append(    "\n      serverAlias=").append(serverAlias);
D
duke 已提交
552
        if (authTime != null) {
553
            buffer.append("\n    authTime=").append(authTime);
D
duke 已提交
554 555
        }
        if (startTime != null) {
556
            buffer.append("\n   startTime=").append(startTime);
D
duke 已提交
557
        }
558 559 560 561 562
        buffer.append(    "\n     endTime=").append(endTime);
        buffer.append(    "\n   renewTill=").append(renewTill);
        buffer.append(    "\n       flags=").append(flags);
        buffer.append(    "\nEType (skey)=").append(key.getEType());
        buffer.append(    "\n   (tkt key)=").append(ticket.encPart.eType);
D
duke 已提交
563 564 565
        return buffer.toString();
    }

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    public sun.security.krb5.internal.ccache.Credentials toCCacheCreds() {
        return new sun.security.krb5.internal.ccache.Credentials(
                getClient(), getServer(),
                getSessionKey(),
                date2kt(getAuthTime()),
                date2kt(getStartTime()),
                date2kt(getEndTime()),
                date2kt(getRenewTill()),
                false,
                flags,
                new HostAddresses(getClientAddresses()),
                getAuthzData(),
                getTicket(),
                null);
    }

    private static KerberosTime date2kt(Date d) {
        return d == null ? null : new KerberosTime(d);
    }
D
duke 已提交
585
}