javax.security.auth.kerberos.KerberosTicket Java Examples

The following examples show how to use javax.security.auth.kerberos.KerberosTicket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KerberosTixDateTest.java    From jdk8u-jdk with GNU General Public License v2.0 7 votes vote down vote up
private static void testDateImmutability(KerberosTicket t, long origTime)
    throws Exception {
    // test the constructor
    System.out.println("Testing constructor...");
    checkTime(t, origTime);

    // test the getAuth/Start/EndTime() & getRenewTill() methods
    System.out.println("Testing getAuth/Start/EndTime() & getRenewTill()...");
    t.getAuthTime().setTime(0);
    t.getStartTime().setTime(0);
    t.getEndTime().setTime(0);
    t.getRenewTill().setTime(0);
    checkTime(t, origTime);

    System.out.println("DateImmutability Test Passed");
}
 
Example #2
Source File: KerberosTixDateTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    byte[] asn1Bytes = "asn1".getBytes();
    KerberosPrincipal client = new KerberosPrincipal("client");
    KerberosPrincipal server = new KerberosPrincipal("server");
    byte[] keyBytes = "sessionKey".getBytes();
    long originalTime = 12345678L;
    Date inDate = new Date(originalTime);
    boolean[] flags = new boolean[9];
    flags[8] = true; // renewable
    KerberosTicket t = new KerberosTicket(asn1Bytes, client, server,
            keyBytes, 1 /*keyType*/, flags, inDate /*authTime*/,
            inDate /*startTime*/, inDate /*endTime*/,
            inDate /*renewTill*/, null /*clientAddresses*/);
    inDate.setTime(0); // for testing the constructor

    testDateImmutability(t, originalTime);
    testS11nCompatibility(t); // S11n: Serialization
}
 
Example #3
Source File: Krb5Util.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the ticket corresponding to the client/server principal
 * pair from the Subject in the specified AccessControlContext.
 * If the ticket can not be found in the Subject, and if
 * useSubjectCredsOnly is false, then obtain ticket from
 * a LoginContext.
 */
static KerberosTicket getTicket(GSSCaller caller,
    String clientPrincipal, String serverPrincipal,
    AccessControlContext acc) throws LoginException {

    // Try to get ticket from acc's Subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket =
        SubjectComber.find(accSubj, serverPrincipal, clientPrincipal,
              KerberosTicket.class);

    // Try to get ticket from Subject obtained from GSSUtil
    if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        ticket = SubjectComber.find(subject,
            serverPrincipal, clientPrincipal, KerberosTicket.class);
    }
    return ticket;
}
 
Example #4
Source File: Krb5Util.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static KerberosTicket credsToTicket(Credentials serviceCreds) {
    EncryptionKey sessionKey =  serviceCreds.getSessionKey();
    return new KerberosTicket(
        serviceCreds.getEncoded(),
        new KerberosPrincipal(serviceCreds.getClient().getName()),
        new KerberosPrincipal(serviceCreds.getServer().getName(),
                            KerberosPrincipal.KRB_NT_SRV_INST),
        sessionKey.getBytes(),
        sessionKey.getEType(),
        serviceCreds.getFlags(),
        serviceCreds.getAuthTime(),
        serviceCreds.getStartTime(),
        serviceCreds.getEndTime(),
        serviceCreds.getRenewTill(),
        serviceCreds.getClientAddresses());
}
 
Example #5
Source File: Krb5ProxyCredential.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static Krb5CredElement tryImpersonation(GSSCaller caller,
        Krb5InitCredential initiator) throws GSSException {

    try {
        KerberosTicket proxy = initiator.proxyTicket;
        if (proxy != null) {
            Credentials proxyCreds = Krb5Util.ticketToCreds(proxy);
            return new Krb5ProxyCredential(initiator,
                    Krb5NameElement.getInstance(proxyCreds.getClient()),
                    proxyCreds.getTicket());
        } else {
            return initiator;
        }
    } catch (KrbException | IOException e) {
        throw new GSSException(GSSException.DEFECTIVE_CREDENTIAL, -1,
                "Cannot create proxy credential");
    }
}
 
Example #6
Source File: SecurityContext.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private synchronized long calculateRenewalTime(KerberosTicket kerberosTicket) {
  long start = kerberosTicket.getStartTime().getTime();
  long end = kerberosTicket.getEndTime().getTime();
  long renewTime = getRenewalTime(start, end);
  if (LOG.isDebugEnabled()) {
    LOG.trace(
        "Ticket: {}, numPrivateCredentials: {}, ticketStartTime: {}, ticketEndTime: {}, now: {}, renewalTime: {}",
        System.identityHashCode(kerberosTicket),
        getSubject().getPrivateCredentials(KerberosTicket.class).size(),
        new Date(start),
        new Date(end),
        new Date(),
        new Date(renewTime)
    );
  }
  return Math.max(1, renewTime - System.currentTimeMillis());
}
 
Example #7
Source File: Krb5Util.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the initial TGT corresponding to the client principal
 * from the Subject in the specified AccessControlContext.
 * If the ticket can not be found in the Subject, and if
 * useSubjectCredsOnly is false, then obtain ticket from
 * a LoginContext.
 */
static KerberosTicket getInitialTicket(GSSCaller caller,
        String clientPrincipal,
        AccessControlContext acc) throws LoginException {

    // Try to get ticket from acc's Subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket =
            SubjectComber.find(accSubj, null, clientPrincipal,
                    KerberosTicket.class);

    // Try to get ticket from Subject obtained from GSSUtil
    if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        ticket = SubjectComber.find(subject,
                null, clientPrincipal, KerberosTicket.class);
    }
    return ticket;
}
 
Example #8
Source File: KerberosClientKeyExchangeImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of KerberosClientKeyExchange consisting of the
 * Kerberos service ticket, authenticator and encrypted premaster secret.
 * Called by client handshaker.
 *
 * @param serverName name of server with which to do handshake;
 *             this is used to get the Kerberos service ticket
 * @param protocolVersion Maximum version supported by client (i.e,
 *          version it requested in client hello)
 * @param rand random number generator to use for generating pre-master
 *          secret
 */
@Override
public void init(String serverName,
    AccessControlContext acc, ProtocolVersion protocolVersion,
    SecureRandom rand) throws IOException {

     // Get service ticket
     KerberosTicket ticket = getServiceTicket(serverName, acc);
     encodedTicket = ticket.getEncoded();

     // Record the Kerberos principals
     peerPrincipal = ticket.getServer();
     localPrincipal = ticket.getClient();

     // Optional authenticator, encrypted using session key,
     // currently ignored

     // Generate premaster secret and encrypt it using session key
     EncryptionKey sessionKey = new EncryptionKey(
                                    ticket.getSessionKeyType(),
                                    ticket.getSessionKey().getEncoded());

     preMaster = new KerberosPreMasterSecret(protocolVersion,
         rand, sessionKey);
}
 
Example #9
Source File: Krb5KeyExchangeService.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
ExchangerImpl(String serverName, AccessControlContext acc,
        ProtocolVersion protocolVersion, SecureRandom rand) throws IOException {

    // Get service ticket
    KerberosTicket ticket = getServiceTicket(serverName, acc);
    encodedTicket = ticket.getEncoded();

    // Record the Kerberos principals
    peerPrincipal = ticket.getServer();
    localPrincipal = ticket.getClient();

    // Optional authenticator, encrypted using session key,
    // currently ignored

    // Generate premaster secret and encrypt it using session key
    EncryptionKey sessionKey = new EncryptionKey(
            ticket.getSessionKeyType(),
            ticket.getSessionKey().getEncoded());

    preMaster = new KerberosPreMasterSecret(protocolVersion,
            rand, sessionKey);
}
 
Example #10
Source File: Krb5Util.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static KerberosTicket credsToTicket(Credentials serviceCreds) {
    EncryptionKey sessionKey =  serviceCreds.getSessionKey();
    return new KerberosTicket(
        serviceCreds.getEncoded(),
        new KerberosPrincipal(serviceCreds.getClient().getName()),
        new KerberosPrincipal(serviceCreds.getServer().getName(),
                            KerberosPrincipal.KRB_NT_SRV_INST),
        sessionKey.getBytes(),
        sessionKey.getEType(),
        serviceCreds.getFlags(),
        serviceCreds.getAuthTime(),
        serviceCreds.getStartTime(),
        serviceCreds.getEndTime(),
        serviceCreds.getRenewTill(),
        serviceCreds.getClientAddresses());
}
 
Example #11
Source File: KerberosClientKeyExchangeImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of KerberosClientKeyExchange consisting of the
 * Kerberos service ticket, authenticator and encrypted premaster secret.
 * Called by client handshaker.
 *
 * @param serverName name of server with which to do handshake;
 *             this is used to get the Kerberos service ticket
 * @param protocolVersion Maximum version supported by client (i.e,
 *          version it requested in client hello)
 * @param rand random number generator to use for generating pre-master
 *          secret
 */
@Override
public void init(String serverName,
    AccessControlContext acc, ProtocolVersion protocolVersion,
    SecureRandom rand) throws IOException {

     // Get service ticket
     KerberosTicket ticket = getServiceTicket(serverName, acc);
     encodedTicket = ticket.getEncoded();

     // Record the Kerberos principals
     peerPrincipal = ticket.getServer();
     localPrincipal = ticket.getClient();

     // Optional authenticator, encrypted using session key,
     // currently ignored

     // Generate premaster secret and encrypt it using session key
     EncryptionKey sessionKey = new EncryptionKey(
                                    ticket.getSessionKeyType(),
                                    ticket.getSessionKey().getEncoded());

     preMaster = new KerberosPreMasterSecret(protocolVersion,
         rand, sessionKey);
}
 
Example #12
Source File: GssClient.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
public void traceServiceTickets() {

            if (subject == null)
                return;
            Set<Object> creds = subject.getPrivateCredentials();
            if (creds.size() == 0) {
                log.debug("[" + getName() + "] No service tickets");
            }

            synchronized (creds) {
                // The Subject's private credentials is a synchronizedSet
                // We must manually synchronize when iterating through the set.
                for (Object cred : creds) {
                    if (cred instanceof KerberosTicket) {
                        KerberosTicket ticket = (KerberosTicket) cred;
                        log.debug("[" + getName() + "] Service ticket " + "belonging to client principal ["
                                  + ticket.getClient().getName() + "] for server principal ["
                                  + ticket.getServer().getName() + "] End time=[" + ticket.getEndTime()
                                  + "] isCurrent=" + ticket.isCurrent());
                    }
                }
            }
        }
 
Example #13
Source File: KerberosTixDateTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void testDestroy(KerberosTicket t) throws Exception {
    t.destroy();
    if (!t.isDestroyed()) {
        throw new RuntimeException("ticket should have been destroyed");
    }
    // Although these methods are meaningless, they can be called
    for (Method m: KerberosTicket.class.getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers())
                && m.getParameterCount() == 0) {
            System.out.println("Testing " + m.getName() + "...");
            try {
                m.invoke(t);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof RefreshFailedException ||
                        cause instanceof IllegalStateException) {
                    // this is OK
                } else {
                    throw e;
                }
            }
        }
    }
    System.out.println("Destroy Test Passed");
}
 
Example #14
Source File: KerberosClientKeyExchangeImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of KerberosClientKeyExchange consisting of the
 * Kerberos service ticket, authenticator and encrypted premaster secret.
 * Called by client handshaker.
 *
 * @param serverName name of server with which to do handshake;
 *             this is used to get the Kerberos service ticket
 * @param protocolVersion Maximum version supported by client (i.e,
 *          version it requested in client hello)
 * @param rand random number generator to use for generating pre-master
 *          secret
 */
@Override
public void init(String serverName,
    AccessControlContext acc, ProtocolVersion protocolVersion,
    SecureRandom rand) throws IOException {

     // Get service ticket
     KerberosTicket ticket = getServiceTicket(serverName, acc);
     encodedTicket = ticket.getEncoded();

     // Record the Kerberos principals
     peerPrincipal = ticket.getServer();
     localPrincipal = ticket.getClient();

     // Optional authenticator, encrypted using session key,
     // currently ignored

     // Generate premaster secret and encrypt it using session key
     EncryptionKey sessionKey = new EncryptionKey(
                                    ticket.getSessionKeyType(),
                                    ticket.getSessionKey().getEncoded());

     preMaster = new KerberosPreMasterSecret(protocolVersion,
         rand, sessionKey);
}
 
Example #15
Source File: KrbTicket.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // define principals
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);

    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);

    // start a local KDC instance
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc,
            "forwardable = true", "proxiable = true");

    // create JAAS config
    Files.write(Paths.get(JAAS_CONF), Arrays.asList(
            "Client {",
            "    com.sun.security.auth.module.Krb5LoginModule required;",
            "};"
    ));
    System.setProperty("java.security.auth.login.config", JAAS_CONF);
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    long startTime = Instant.now().getEpochSecond() * 1000;

    LoginContext lc = new LoginContext("Client",
            new Helper.UserPasswordHandler(USER, PASSWORD));
    lc.login();

    Subject subject = lc.getSubject();
    System.out.println("subject: " + subject);

    Set creds = subject.getPrivateCredentials(
            KerberosTicket.class);

    if (creds.size() > 1) {
        throw new RuntimeException("Multiple credintials found");
    }

    Object o = creds.iterator().next();
    if (!(o instanceof KerberosTicket)) {
        throw new RuntimeException("Instance of KerberosTicket expected");
    }
    KerberosTicket krbTkt = (KerberosTicket) o;

    System.out.println("forwardable = " + krbTkt.isForwardable());
    System.out.println("proxiable   = " + krbTkt.isProxiable());
    System.out.println("renewable   = " + krbTkt.isRenewable());
    System.out.println("current     = " + krbTkt.isCurrent());

    if (!krbTkt.isForwardable()) {
        throw new RuntimeException("Forwardable ticket expected");
    }

    if (!krbTkt.isProxiable()) {
        throw new RuntimeException("Proxiable ticket expected");
    }

    if (!krbTkt.isCurrent()) {
        throw new RuntimeException("Ticket is not current");
    }

    if (krbTkt.isRenewable()) {
        throw new RuntimeException("Not renewable ticket expected");
    }
    try {
        krbTkt.refresh();
        throw new RuntimeException(
                "Expected RefreshFailedException not thrown");
    } catch(RefreshFailedException e) {
        System.out.println("Expected exception: " + e);
    }

    if (!checkTime(krbTkt, startTime)) {
        throw new RuntimeException("Wrong ticket life time");
    }

    krbTkt.destroy();
    if (!krbTkt.isDestroyed()) {
        throw new RuntimeException("Ticket not destroyed");
    }

    System.out.println("Test passed");
}
 
Example #16
Source File: KerberosTixDateTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void testDateImmutability(KerberosTicket t, long origTime)
    throws Exception {
    // test the constructor
    System.out.println("Testing constructor...");
    checkTime(t, origTime);

    // test the getAuth/Start/EndTime() & getRenewTill() methods
    System.out.println("Testing getAuth/Start/EndTime() & getRenewTill()...");
    t.getAuthTime().setTime(0);
    t.getStartTime().setTime(0);
    t.getEndTime().setTime(0);
    t.getRenewTill().setTime(0);
    checkTime(t, origTime);

    System.out.println("DateImmutability Test Passed");
}
 
Example #17
Source File: Krb5ProxyCredential.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static Krb5CredElement tryImpersonation(GSSCaller caller,
        Krb5InitCredential initiator) throws GSSException {

    try {
        KerberosTicket proxy = initiator.proxyTicket;
        if (proxy != null) {
            Credentials proxyCreds = Krb5Util.ticketToCreds(proxy);
            return new Krb5ProxyCredential(initiator,
                    Krb5NameElement.getInstance(proxyCreds.getClient()),
                    proxyCreds.getTicket());
        } else {
            return initiator;
        }
    } catch (KrbException | IOException e) {
        throw new GSSException(GSSException.DEFECTIVE_CREDENTIAL, -1,
                "Cannot create proxy credential");
    }
}
 
Example #18
Source File: Krb5Util.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the ticket corresponding to the client/server principal
 * pair from the Subject in the specified AccessControlContext.
 * If the ticket can not be found in the Subject, and if
 * useSubjectCredsOnly is false, then obtain ticket from
 * a LoginContext.
 */
static KerberosTicket getTicket(GSSCaller caller,
    String clientPrincipal, String serverPrincipal,
    AccessControlContext acc) throws LoginException {

    // Try to get ticket from acc's Subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket =
        SubjectComber.find(accSubj, serverPrincipal, clientPrincipal,
              KerberosTicket.class);

    // Try to get ticket from Subject obtained from GSSUtil
    if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        ticket = SubjectComber.find(subject,
            serverPrincipal, clientPrincipal, KerberosTicket.class);
    }
    return ticket;
}
 
Example #19
Source File: KerberosClientKeyExchangeImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of KerberosClientKeyExchange consisting of the
 * Kerberos service ticket, authenticator and encrypted premaster secret.
 * Called by client handshaker.
 *
 * @param serverName name of server with which to do handshake;
 *             this is used to get the Kerberos service ticket
 * @param protocolVersion Maximum version supported by client (i.e,
 *          version it requested in client hello)
 * @param rand random number generator to use for generating pre-master
 *          secret
 */
@Override
public void init(String serverName,
    AccessControlContext acc, ProtocolVersion protocolVersion,
    SecureRandom rand) throws IOException {

     // Get service ticket
     KerberosTicket ticket = getServiceTicket(serverName, acc);
     encodedTicket = ticket.getEncoded();

     // Record the Kerberos principals
     peerPrincipal = ticket.getServer();
     localPrincipal = ticket.getClient();

     // Optional authenticator, encrypted using session key,
     // currently ignored

     // Generate premaster secret and encrypt it using session key
     EncryptionKey sessionKey = new EncryptionKey(
                                    ticket.getSessionKeyType(),
                                    ticket.getSessionKey().getEncoded());

     preMaster = new KerberosPreMasterSecret(protocolVersion,
         rand, sessionKey);
}
 
Example #20
Source File: Krb5Util.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the ticket corresponding to the client/server principal
 * pair from the Subject in the specified AccessControlContext.
 * If the ticket can not be found in the Subject, and if
 * useSubjectCredsOnly is false, then obtain ticket from
 * a LoginContext.
 */
static KerberosTicket getTicket(GSSCaller caller,
    String clientPrincipal, String serverPrincipal,
    AccessControlContext acc) throws LoginException {

    // Try to get ticket from acc's Subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket =
        SubjectComber.find(accSubj, serverPrincipal, clientPrincipal,
              KerberosTicket.class);

    // Try to get ticket from Subject obtained from GSSUtil
    if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        ticket = SubjectComber.find(subject,
            serverPrincipal, clientPrincipal, KerberosTicket.class);
    }
    return ticket;
}
 
Example #21
Source File: Renewal.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void checkLogin(
        String s1,      // ticket_lifetime in krb5.conf, null if none
        String s2,      // renew_lifetime in krb5.conf, null if none
        int t1, int t2  // expected lifetimes, -1 of unexpected
            ) throws Exception {
    KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
            s1 != null ? ("ticket_lifetime = " + s1) : "",
            s2 != null ? ("renew_lifetime = " + s2) : "");
    Config.refresh();

    Context c;
    c = Context.fromJAAS("client");

    Set<KerberosTicket> tickets =
            c.s().getPrivateCredentials(KerberosTicket.class);
    if (tickets.size() != 1) {
        throw new Exception();
    }
    KerberosTicket ticket = tickets.iterator().next();

    checkRough(ticket.getEndTime(), t1);
    checkRough(ticket.getRenewTill(), t2);
}
 
Example #22
Source File: KerberosClientKeyExchangeImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an instance of KerberosClientKeyExchange consisting of the
 * Kerberos service ticket, authenticator and encrypted premaster secret.
 * Called by client handshaker.
 *
 * @param serverName name of server with which to do handshake;
 *             this is used to get the Kerberos service ticket
 * @param protocolVersion Maximum version supported by client (i.e,
 *          version it requested in client hello)
 * @param rand random number generator to use for generating pre-master
 *          secret
 */
@Override
public void init(String serverName,
    AccessControlContext acc, ProtocolVersion protocolVersion,
    SecureRandom rand) throws IOException {

     // Get service ticket
     KerberosTicket ticket = getServiceTicket(serverName, acc);
     encodedTicket = ticket.getEncoded();

     // Record the Kerberos principals
     peerPrincipal = ticket.getServer();
     localPrincipal = ticket.getClient();

     // Optional authenticator, encrypted using session key,
     // currently ignored

     // Generate premaster secret and encrypt it using session key
     EncryptionKey sessionKey = new EncryptionKey(
                                    ticket.getSessionKeyType(),
                                    ticket.getSessionKey().getEncoded());

     preMaster = new KerberosPreMasterSecret(protocolVersion,
         rand, sessionKey);
}
 
Example #23
Source File: KerberosTixDateTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void testDateImmutability(KerberosTicket t, long origTime)
    throws Exception {
    // test the constructor
    System.out.println("Testing constructor...");
    checkTime(t, origTime);

    // test the getAuth/Start/EndTime() & getRenewTill() methods
    System.out.println("Testing getAuth/Start/EndTime() & getRenewTill()...");
    t.getAuthTime().setTime(0);
    t.getStartTime().setTime(0);
    t.getEndTime().setTime(0);
    t.getRenewTill().setTime(0);
    checkTime(t, origTime);

    System.out.println("DateImmutability Test Passed");
}
 
Example #24
Source File: Krb5Util.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the ticket corresponding to the client/server principal
 * pair from the Subject in the specified AccessControlContext.
 * If the ticket can not be found in the Subject, and if
 * useSubjectCredsOnly is false, then obtain ticket from
 * a LoginContext.
 */
static KerberosTicket getTicket(GSSCaller caller,
    String clientPrincipal, String serverPrincipal,
    AccessControlContext acc) throws LoginException {

    // Try to get ticket from acc's Subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket =
        SubjectComber.find(accSubj, serverPrincipal, clientPrincipal,
              KerberosTicket.class);

    // Try to get ticket from Subject obtained from GSSUtil
    if (ticket == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        ticket = SubjectComber.find(subject,
            serverPrincipal, clientPrincipal, KerberosTicket.class);
    }
    return ticket;
}
 
Example #25
Source File: AutoTGT.java    From jstorm with Apache License 2.0 6 votes vote down vote up
@Override
public void renew(Map<String, String> credentials, Map topologyConf) {
    KerberosTicket tgt = getTGT(credentials);
    if (tgt != null) {
        long refreshTime = getRefreshTime(tgt);
        long now = System.currentTimeMillis();
        if (now >= refreshTime) {
            try {
                LOG.info("Renewing TGT for " + tgt.getClient());
                tgt.refresh();
                saveTGT(tgt, credentials);
            } catch (RefreshFailedException e) {
                LOG.warn("Failed to refresh TGT", e);
            }
        }
    }
}
 
Example #26
Source File: KerberosTixDateTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    byte[] asn1Bytes = "asn1".getBytes();
    KerberosPrincipal client = new KerberosPrincipal("client");
    KerberosPrincipal server = new KerberosPrincipal("server");
    byte[] keyBytes = "sessionKey".getBytes();
    long originalTime = 12345678L;
    Date inDate = new Date(originalTime);
    boolean[] flags = new boolean[9];
    flags[8] = true; // renewable
    KerberosTicket t = new KerberosTicket(asn1Bytes, client, server,
            keyBytes, 1 /*keyType*/, flags, inDate /*authTime*/,
            inDate /*startTime*/, inDate /*endTime*/,
            inDate /*renewTill*/, null /*clientAddresses*/);
    inDate.setTime(0); // for testing the constructor

    testDateImmutability(t, originalTime);
    testS11nCompatibility(t); // S11n: Serialization
    testDestroy(t);
}
 
Example #27
Source File: TicketSName.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        new OneKDC(null).writeJAASConf();

        Context c, s;
        c = Context.fromJAAS("client");
        s = Context.fromJAAS("server");

        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
        s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);

        Context.handshake(c, s);

        String expected = OneKDC.SERVER + "@" + OneKDC.REALM;
        if (!c.s().getPrivateCredentials(KerberosTicket.class)
                .stream()
                .anyMatch(t -> t.getServer().toString().equals(expected))) {
            c.status();
            throw new Exception("no " + expected);
        }
    }
 
Example #28
Source File: TestSecurityContext.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetKerberosTicket() {
  long now = System.currentTimeMillis();
  Date v1 = new Date(now + TimeUnit.DAYS.toMillis(1));
  Date v2 = new Date(now + TimeUnit.DAYS.toMillis(12));
  Date v3 = new Date(now + TimeUnit.DAYS.toMillis(5));
  KerberosTicket ticket = createMockTGT("short", v1, v1);
  KerberosTicket ticket2 = createMockTGT("long", v2, v2);
  KerberosTicket ticket3 = createMockTGT("medium", v3, v3);

  Configuration conf = new Configuration();
  SecurityContext context = new SecurityContext(getMockRuntimeInfo(), conf);
  context = Mockito.spy(context);
  Mockito.doReturn(now).when(context).getTimeNow();

  Subject subject = new Subject();
  Mockito.doReturn(subject).when(context).getSubject();
  subject.getPrivateCredentials().add(ticket);
  subject.getPrivateCredentials().add(ticket2);
  subject.getPrivateCredentials().add(ticket3);

  Assert.assertEquals(ticket2, context.getNewestTGT());
}
 
Example #29
Source File: BurpExtender.java    From Berserko with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean checkTgtForwardableFlag(Subject sub) {
	for (Object ob : sub.getPrivateCredentials()) {
		if (ob instanceof KerberosTicket) {
			KerberosTicket kt = (KerberosTicket) ob;
			boolean[] flags = kt.getFlags();
			return flags[1];
		}
	}

	return false;
}
 
Example #30
Source File: KerberosTixDateTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testS11nCompatibility(KerberosTicket t)
    throws Exception {

    System.out.println("Testing against KerberosTicket from JDK6...");
    byte[] serializedBytes =
        Base64.getMimeDecoder().decode(serializedKerberosTix);
    checkEqualsAndHashCode(serializedBytes, t);

    System.out.println("Testing against KerberosTicket from current rel...");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ObjectOutputStream(baos).writeObject(t);
    checkEqualsAndHashCode(baos.toByteArray(), t);

    System.out.println("S11nCompatibility Test Passed");
}