javax.security.auth.kerberos.KerberosPrincipal Java Examples

The following examples show how to use javax.security.auth.kerberos.KerberosPrincipal. 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: SimpleLDAPAuthenticationManagerTest.java    From qpid-broker-j with Apache License 2.0 7 votes vote down vote up
private void setUpKerberos() throws Exception
{
    final LdapServer ldapServer = LDAP.getLdapServer();
    final KdcServer kdcServer =
            ServerAnnotationProcessor.getKdcServer(LDAP.getDirectoryService(), ldapServer.getPort() + 1);
    kdcServer.getConfig().setPaEncTimestampRequired(false);

    final int port = kdcServer.getTransports()[0].getPort();
    final String krb5confPath = createKrb5Conf(port);
    SYSTEM_PROPERTY_SETTER.setSystemProperty("java.security.krb5.conf", krb5confPath);
    SYSTEM_PROPERTY_SETTER.setSystemProperty("java.security.krb5.realm", null);
    SYSTEM_PROPERTY_SETTER.setSystemProperty("java.security.krb5.kdc", null);

    final KerberosPrincipal servicePrincipal =
            new KerberosPrincipal(LDAP_SERVICE_NAME + "/" + HOSTNAME + "@" + REALM,
                                  KerberosPrincipal.KRB_NT_SRV_HST);
    final String servicePrincipalName = servicePrincipal.getName();
    ldapServer.setSaslHost(servicePrincipalName.substring(servicePrincipalName.indexOf("/") + 1,
                                                          servicePrincipalName.indexOf("@")));
    ldapServer.setSaslPrincipal(servicePrincipalName);
    ldapServer.setSearchBaseDn(USERS_DN);

    createPrincipal("KDC", "KDC", "krbtgt", UUID.randomUUID().toString(), "krbtgt/" + REALM + "@" + REALM);
    createPrincipal("Service", "LDAP Service", "ldap", UUID.randomUUID().toString(), servicePrincipalName);
}
 
Example #2
Source File: KerberosTixDateTest.java    From dragonwell8_jdk 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 #3
Source File: Implies.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 {
    X500Principal duke = new X500Principal("CN=Duke");
    // should not throw NullPointerException
    testImplies(duke, (Subject)null, false);

    Set<Principal> principals = new HashSet<>();
    principals.add(duke);
    testImplies(duke, principals, true);

    X500Principal tux = new X500Principal("CN=Tux");
    principals.add(tux);
    testImplies(duke, principals, true);

    principals.add(new KerberosPrincipal("[email protected]"));
    testImplies(duke, principals, true);

    principals.clear();
    principals.add(tux);
    testImplies(duke, principals, false);

    System.out.println("test passed");
}
 
Example #4
Source File: Implies.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    X500Principal duke = new X500Principal("CN=Duke");
    // should not throw NullPointerException
    testImplies(duke, (Subject)null, false);

    Set<Principal> principals = new HashSet<>();
    principals.add(duke);
    testImplies(duke, principals, true);

    X500Principal tux = new X500Principal("CN=Tux");
    principals.add(tux);
    testImplies(duke, principals, true);

    principals.add(new KerberosPrincipal("[email protected]"));
    testImplies(duke, principals, true);

    principals.clear();
    principals.add(tux);
    testImplies(duke, principals, false);

    System.out.println("test passed");
}
 
Example #5
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 #6
Source File: KerberosAuthenticationManagerTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSaslNegotiator() throws Exception
{
    final SaslSettings saslSettings = mock(SaslSettings.class);
    when(saslSettings.getLocalFQDN()).thenReturn(HOST_NAME);
    final SaslNegotiator negotiator = _kerberosAuthenticationProvider.createSaslNegotiator(GSSAPI_MECHANISM,
                                                                                           saslSettings,
                                                                                           null);
    assertNotNull("Could not create SASL negotiator", negotiator);
    try
    {
        final AuthenticationResult result = authenticate(negotiator);
        assertEquals(AuthenticationResult.AuthenticationStatus.SUCCESS, result.getStatus());
        assertEquals(new KerberosPrincipal(CLIENT_PRINCIPAL_FULL_NAME).getName(),
                     result.getMainPrincipal().getName());
    }
    finally
    {
        negotiator.dispose();
    }
}
 
Example #7
Source File: KerberosTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static KerberosTicket getKerberosTicket ( KerberosPrincipal principal, String password, Long expire ) throws Exception {
    PrincipalName principalName = convertPrincipal(principal);
    KrbAsReqBuilder builder = new KrbAsReqBuilder(principalName, password != null ? password.toCharArray() : new char[0]);

    if ( expire != null ) {
        System.out.println("Request expires " + expire);
        KerberosTime till = new KerberosTime(expire);
        Field tillF = builder.getClass().getDeclaredField("till");
        tillF.setAccessible(true);
        tillF.set(builder, till);
    }

    Credentials creds = builder.action().getCreds();
    builder.destroy();

    KerberosTicket ticket = Krb5Util.credsToTicket(creds);
    System.out.println("Ends " + ticket.getEndTime().getTime());
    return ticket;
}
 
Example #8
Source File: Krb5Util.java    From jdk8u-dev-jdk 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 #9
Source File: KerberosTixDateTest.java    From hottub 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 #10
Source File: KerberosTixDateTest.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 {
    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 #11
Source File: Krb5Util.java    From openjdk-jdk8u-backup 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 #12
Source File: KerberosTixDateTest.java    From jdk8u-dev-jdk 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 #13
Source File: ServiceCreds.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets EKeys for a principal.
 * @param princ the target name initiator requests. Not null.
 * @return keys for the princ, never null, might be empty
 */
public EncryptionKey[] getEKeys(PrincipalName princ) {
    if (destroyed) {
        throw new IllegalStateException("This object is destroyed");
    }
    KerberosKey[] kkeys = getKKeys(new KerberosPrincipal(princ.getName()));
    if (kkeys.length == 0) {
        // Fallback: old JDK does not perform real name checking. If the
        // acceptor has host.sun.com but initiator requests for host,
        // as long as their keys match (i.e. keys for one can decrypt
        // the other's service ticket), the authentication is OK.
        // There are real customers depending on this to use different
        // names for a single service.
        kkeys = getKKeys();
    }
    EncryptionKey[] ekeys = new EncryptionKey[kkeys.length];
    for (int i=0; i<ekeys.length; i++) {
        ekeys[i] =  new EncryptionKey(
                    kkeys[i].getEncoded(), kkeys[i].getKeyType(),
                    new Integer(kkeys[i].getVersionNumber()));
    }
    return ekeys;
}
 
Example #14
Source File: KerberosUserIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupClass() throws Exception {
    kdc = new KDCServer(tmpDir.newFolder("mini-kdc_"));
    kdc.setMaxTicketLifetime("15"); // set ticket lifetime to 15 seconds so we can test relogin
    kdc.start();

    principal1 = new KerberosPrincipal("user1@" + kdc.getRealm());
    principal1KeytabFile = tmpDir.newFile("user1.keytab");
    kdc.createKeytabPrincipal(principal1KeytabFile, "user1");

    principal2 = new KerberosPrincipal("user2@" + kdc.getRealm());
    principal2KeytabFile = tmpDir.newFile("user2.keytab");
    kdc.createKeytabPrincipal(principal2KeytabFile, "user2");

    principal3 = new KerberosPrincipal("user3@" + kdc.getRealm());
    kdc.createPasswordPrincipal("user3", principal3Password);
}
 
Example #15
Source File: ServiceCreds.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets EKeys for a principal.
 * @param princ the target name initiator requests. Not null.
 * @return keys for the princ, never null, might be empty
 */
public EncryptionKey[] getEKeys(PrincipalName princ) {
    if (destroyed) {
        throw new IllegalStateException("This object is destroyed");
    }
    KerberosKey[] kkeys = getKKeys(new KerberosPrincipal(princ.getName()));
    if (kkeys.length == 0) {
        // Fallback: old JDK does not perform real name checking. If the
        // acceptor has host.sun.com but initiator requests for host,
        // as long as their keys match (i.e. keys for one can decrypt
        // the other's service ticket), the authentication is OK.
        // There are real customers depending on this to use different
        // names for a single service.
        kkeys = getKKeys();
    }
    EncryptionKey[] ekeys = new EncryptionKey[kkeys.length];
    for (int i=0; i<ekeys.length; i++) {
        ekeys[i] =  new EncryptionKey(
                    kkeys[i].getEncoded(), kkeys[i].getKeyType(),
                    kkeys[i].getVersionNumber());
    }
    return ekeys;
}
 
Example #16
Source File: KerberosTixDateTest.java    From openjdk-jdk9 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("[email protected]");
    KerberosPrincipal server = new KerberosPrincipal("[email protected]");
    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 #17
Source File: ServiceCreds.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets EKeys for a principal.
 * @param princ the target name initiator requests. Not null.
 * @return keys for the princ, never null, might be empty
 */
public EncryptionKey[] getEKeys(PrincipalName princ) {
    if (destroyed) {
        throw new IllegalStateException("This object is destroyed");
    }
    KerberosKey[] kkeys = getKKeys(new KerberosPrincipal(princ.getName()));
    if (kkeys.length == 0) {
        // Fallback: old JDK does not perform real name checking. If the
        // acceptor has host.sun.com but initiator requests for host,
        // as long as their keys match (i.e. keys for one can decrypt
        // the other's service ticket), the authentication is OK.
        // There are real customers depending on this to use different
        // names for a single service.
        kkeys = getKKeys();
    }
    EncryptionKey[] ekeys = new EncryptionKey[kkeys.length];
    for (int i=0; i<ekeys.length; i++) {
        ekeys[i] =  new EncryptionKey(
                    kkeys[i].getEncoded(), kkeys[i].getKeyType(),
                    new Integer(kkeys[i].getVersionNumber()));
    }
    return ekeys;
}
 
Example #18
Source File: KrbCredSubKey.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        // We don't care about clock difference
        new FileOutputStream("krb5.conf").write(
                "[libdefaults]\nclockskew=999999999".getBytes());
        System.setProperty("java.security.krb5.conf", "krb5.conf");
        Config.refresh();

        Subject subj = new Subject();
        KerberosPrincipal kp = new KerberosPrincipal(princ);
        KerberosKey kk = new KerberosKey(
                kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0);
        subj.getPrincipals().add(kp);
        subj.getPrivateCredentials().add(kk);

        Subject.doAs(subj, new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                GSSManager man = GSSManager.getInstance();
                GSSContext ctxt = man.createContext(man.createCredential(
                        null, GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY));
                return ctxt.acceptSecContext(token, 0, token.length);
            }
        });
    }
 
Example #19
Source File: TestKMS.java    From big-c with Apache License 2.0 6 votes vote down vote up
private <T> T doAs(String user, final PrivilegedExceptionAction<T> action)
    throws Exception {
  Set<Principal> principals = new HashSet<Principal>();
  principals.add(new KerberosPrincipal(user));

  //client login
  Subject subject = new Subject(false, principals,
      new HashSet<Object>(), new HashSet<Object>());
  LoginContext loginContext = new LoginContext("", subject, null,
      KerberosConfiguration.createClientConfig(user, keytab));
  try {
    loginContext.login();
    subject = loginContext.getSubject();
    UserGroupInformation ugi =
        UserGroupInformation.getUGIFromSubject(subject);
    return ugi.doAs(action);
  } finally {
    loginContext.logout();
  }
}
 
Example #20
Source File: AbstractTestWithStaticConfiguration.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
/**
 * Get sentry client with authenticated Subject
 * (its security-related attributes(for example, kerberos principal and key)
 * @param clientShortName
 * @param clientKeyTabDir
 * @return client's Subject
 */
public static Subject getClientSubject(String clientShortName, String clientKeyTabDir) {
  String clientKerberosPrincipal = clientShortName + "@" + REALM;
  File clientKeyTabFile = new File(clientKeyTabDir);
  Subject clientSubject = new Subject(false, Sets.newHashSet(
          new KerberosPrincipal(clientKerberosPrincipal)), new HashSet<Object>(),
          new HashSet<Object>());
  try {
    clientLoginContext = new LoginContext("", clientSubject, null,
            KerberosConfiguration.createClientConfig(clientKerberosPrincipal, clientKeyTabFile));
    clientLoginContext.login();
  } catch (Exception ex) {
    LOGGER.error("Exception: " + ex);
  }
  clientSubject = clientLoginContext.getSubject();
  return clientSubject;
}
 
Example #21
Source File: Implies.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 {
    X500Principal duke = new X500Principal("CN=Duke");
    // should not throw NullPointerException
    testImplies(duke, (Subject)null, false);

    Set<Principal> principals = new HashSet<>();
    principals.add(duke);
    testImplies(duke, principals, true);

    X500Principal tux = new X500Principal("CN=Tux");
    principals.add(tux);
    testImplies(duke, principals, true);

    principals.add(new KerberosPrincipal("[email protected]"));
    testImplies(duke, principals, true);

    principals.clear();
    principals.add(tux);
    testImplies(duke, principals, false);

    System.out.println("test passed");
}
 
Example #22
Source File: Kerb5Authenticator.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String getUserDomain () {
    if ( this.realm == null && this.getSubject() != null ) {
        Set<Principal> pr = this.getSubject().getPrincipals();
        for ( Iterator<Principal> ite = pr.iterator(); ite.hasNext(); ) {
            try {
                KerberosPrincipal entry = (KerberosPrincipal) ite.next();
                return entry.getRealm();
            }
            catch ( Exception e ) {
                continue;
            }
        }
    }

    if ( this.realm != null ) {
        return this.realm;
    }

    return super.getUserDomain();
}
 
Example #23
Source File: Krb5Util.java    From openjdk-jdk9 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 #24
Source File: TestWebDelegationToken.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static <T> T doAsKerberosUser(String principal, String keytab,
    final Callable<T> callable) throws Exception {
  LoginContext loginContext = null;
  try {
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject = new Subject(false, principals, new HashSet<Object>(),
        new HashSet<Object>());
    loginContext = new LoginContext("", subject, null,
        new KerberosConfiguration(principal, keytab));
    loginContext.login();
    subject = loginContext.getSubject();
    return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
      @Override
      public T run() throws Exception {
        return callable.call();
      }
    });
  } catch (PrivilegedActionException ex) {
    throw ex.getException();
  } finally {
    if (loginContext != null) {
      loginContext.logout();
    }
  }
}
 
Example #25
Source File: KerberosTestUtils.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static <T> T doAs(String principal, final Callable<T> callable) throws Exception {
  LoginContext loginContext = null;
  try {
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(KerberosTestUtils.getClientPrincipal()));
    Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal));
    loginContext.login();
    subject = loginContext.getSubject();
    return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
      @Override
      public T run() throws Exception {
        return callable.call();
      }
    });
  } catch (PrivilegedActionException ex) {
    throw ex.getException();
  } finally {
    if (loginContext != null) {
      loginContext.logout();
    }
  }
}
 
Example #26
Source File: Implies.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    X500Principal duke = new X500Principal("CN=Duke");
    // should not throw NullPointerException
    testImplies(duke, (Subject)null, false);

    Set<Principal> principals = new HashSet<>();
    principals.add(duke);
    testImplies(duke, principals, true);

    X500Principal tux = new X500Principal("CN=Tux");
    principals.add(tux);
    testImplies(duke, principals, true);

    principals.add(new KerberosPrincipal("[email protected]"));
    testImplies(duke, principals, true);

    principals.clear();
    principals.add(tux);
    testImplies(duke, principals, false);

    System.out.println("test passed");
}
 
Example #27
Source File: TestKMS.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private <T> T doAs(String user, final PrivilegedExceptionAction<T> action)
    throws Exception {
  Set<Principal> principals = new HashSet<Principal>();
  principals.add(new KerberosPrincipal(user));

  //client login
  Subject subject = new Subject(false, principals,
      new HashSet<Object>(), new HashSet<Object>());
  LoginContext loginContext = new LoginContext("", subject, null,
      KerberosConfiguration.createClientConfig(user, keytab));
  try {
    loginContext.login();
    subject = loginContext.getSubject();
    UserGroupInformation ugi =
        UserGroupInformation.getUGIFromSubject(subject);
    return ugi.doAs(action);
  } finally {
    loginContext.logout();
  }
}
 
Example #28
Source File: Krb5Util.java    From jdk8u60 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 #29
Source File: UnsupportedKeyType.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = new byte[aes.length()/2];
        KerberosPrincipal kp = new KerberosPrincipal("u1@K1");

        // aes128
        for (int i=0; i<data.length; i++) {
            data[i] = Integer.valueOf(
                    aes.substring(2*i,2*i+2), 16).byteValue();
        }
        Files.write(Paths.get("aes"), data);
        if(KeyTab.getInstance(kp, new File("aes")).getKeys(kp).length == 0) {
            throw new Exception("AES key not read");
        }

        // camellia128
        for (int i=0; i<data.length; i++) {
            data[i] = Integer.valueOf(
                    camellia.substring(2*i,2*i+2), 16).byteValue();
        }
        Files.write(Paths.get("camellia"), data);
        if(KeyTab.getInstance(kp, new File("camellia")).getKeys(kp).length != 0) {
            throw new Exception("Unknown key read");
        }
    }
 
Example #30
Source File: UnsupportedKeyType.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 {

        byte[] data = new byte[aes.length()/2];
        KerberosPrincipal kp = new KerberosPrincipal("u1@K1");

        // aes128
        for (int i=0; i<data.length; i++) {
            data[i] = Integer.valueOf(
                    aes.substring(2*i,2*i+2), 16).byteValue();
        }
        Files.write(Paths.get("aes"), data);
        if(KeyTab.getInstance(kp, new File("aes")).getKeys(kp).length == 0) {
            throw new Exception("AES key not read");
        }

        // camellia128
        for (int i=0; i<data.length; i++) {
            data[i] = Integer.valueOf(
                    camellia.substring(2*i,2*i+2), 16).byteValue();
        }
        Files.write(Paths.get("camellia"), data);
        if(KeyTab.getInstance(kp, new File("camellia")).getKeys(kp).length != 0) {
            throw new Exception("Unknown key read");
        }
    }