Java Code Examples for javax.security.auth.Subject#getPrivateCredentials()

The following examples show how to use javax.security.auth.Subject#getPrivateCredentials() . 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: Krb5ProxyImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 7 votes vote down vote up
@Override
public boolean isRelated(Subject subject, Principal princ) {
    if (princ == null) return false;
    Set<Principal> principals =
            subject.getPrincipals(Principal.class);
    if (principals.contains(princ)) {
        // bound to this principal
        return true;
    }
    for (KeyTab pc: subject.getPrivateCredentials(KeyTab.class)) {
        if (!pc.isBound()) {
            return true;
        }
    }
    return false;
}
 
Example 2
Source File: KerberosJdkProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public KerberosTicket gssCredentialToKerberosTicket(KerberosTicket kerberosTicket, GSSCredential gssCredential) {
    try {
        Class<?> gssUtil = Class.forName("com.sun.security.jgss.GSSUtil");
        Method createSubject = gssUtil.getMethod("createSubject", GSSName.class, GSSCredential.class);
        Subject subject = (Subject) createSubject.invoke(null, null, gssCredential);
        Set<KerberosTicket> kerberosTickets = subject.getPrivateCredentials(KerberosTicket.class);
        Iterator<KerberosTicket> iterator = kerberosTickets.iterator();
        if (iterator.hasNext()) {
            return iterator.next();
        } else {
            throw new KerberosSerializationUtils.KerberosSerializationException("Not available kerberosTicket in subject credentials. Subject was: " + subject.toString());
        }
    } catch (KerberosSerializationUtils.KerberosSerializationException ke) {
        throw ke;
    } catch (Exception e) {
        throw new KerberosSerializationUtils.KerberosSerializationException("Unexpected error during convert GSSCredential to KerberosTicket", e);
    }
}
 
Example 3
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 4
Source File: Synch2.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 5
Source File: SecurityActions.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the PasswordCredential from the Subject
 * @param subject The subject
 * @return The instances
 */
static Set<PasswordCredential> getPasswordCredentials(final Subject subject)
{
   if (System.getSecurityManager() == null)
      return subject.getPrivateCredentials(PasswordCredential.class);

   return AccessController.doPrivileged(new PrivilegedAction<Set<PasswordCredential>>() 
   {
      public Set<PasswordCredential> run()
      {
         return subject.getPrivateCredentials(PasswordCredential.class);
      }
   });
}
 
Example 6
Source File: UnifiedSecurityManagedConnectionMetaData.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the PasswordCredential from the Subject
 *
 * @param subject The subject
 * @return The instances
 */
private Set<PasswordCredential> getPasswordCredentials(final Subject subject)
{
   if (System.getSecurityManager() == null)
      return subject.getPrivateCredentials(PasswordCredential.class);

   return AccessController.doPrivileged(
         (PrivilegedAction<Set<PasswordCredential>>) () -> subject.getPrivateCredentials(PasswordCredential.class));
}
 
Example 7
Source File: SubjectTestCase.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the PasswordCredential from the Subject
 *
 * @param subject The subject
 * @return The instances
 */
private Set<PasswordCredential> getPasswordCredentials(final Subject subject)
{
   if (System.getSecurityManager() == null)
      return subject.getPrivateCredentials(PasswordCredential.class);

   return AccessController.doPrivileged(
         (PrivilegedAction<Set<PasswordCredential>>) () -> subject.getPrivateCredentials(PasswordCredential.class));
}
 
Example 8
Source File: Synch2.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 9
Source File: Synch2.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 10
Source File: Synch2.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 11
Source File: Synch2.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 12
Source File: UnifiedSecurityManagedConnection.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the PasswordCredential from the Subject
 *
 * @param subject The subject
 * @return The instances
 */
private Set<PasswordCredential> getPasswordCredentials(final Subject subject)
{
   if (System.getSecurityManager() == null)
      return subject.getPrivateCredentials(PasswordCredential.class);

   return AccessController.doPrivileged(
         (PrivilegedAction<Set<PasswordCredential>>) () -> subject.getPrivateCredentials(PasswordCredential.class));
}
 
Example 13
Source File: JaasCallbackHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
   for (Callback callback : callbacks) {
      if (callback instanceof PasswordCallback) {
         PasswordCallback passwordCallback = (PasswordCallback) callback;
         if (password == null) {
            passwordCallback.setPassword(null);
         } else {
            passwordCallback.setPassword(password.toCharArray());
         }
      } else if (callback instanceof NameCallback) {
         NameCallback nameCallback = (NameCallback) callback;
         if (username == null) {
            nameCallback.setName(null);
         } else {
            nameCallback.setName(username);
         }
      } else if (callback instanceof CertificateCallback) {
         CertificateCallback certCallback = (CertificateCallback) callback;

         certCallback.setCertificates(getCertsFromConnection(remotingConnection));
      } else if (callback instanceof Krb5Callback) {
         Krb5Callback krb5Callback = (Krb5Callback) callback;

         Subject peerSubject = remotingConnection.getSubject();
         if (peerSubject != null) {
            for (Principal principal : peerSubject.getPrivateCredentials(KerberosPrincipal.class)) {
               krb5Callback.setPeerPrincipal(principal);
               return;
            }
         }

         krb5Callback.setPeerPrincipal(getPeerPrincipalFromConnection(remotingConnection));
      } else {
         throw new UnsupportedCallbackException(callback);
      }
   }
}
 
Example 14
Source File: Synch2.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 15
Source File: Kerb5Context.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
Key searchSessionKey ( Subject subject ) throws GSSException {
    MIEName src = new MIEName(this.gssContext.getSrcName().export());
    MIEName targ = new MIEName(this.gssContext.getTargName().export());

    ASN1ObjectIdentifier mech = ASN1ObjectIdentifier.getInstance(this.gssContext.getMech().getDER());
    for ( KerberosTicket ticket : subject.getPrivateCredentials(KerberosTicket.class) ) {
        MIEName client = new MIEName(mech, ticket.getClient().getName());
        MIEName server = new MIEName(mech, ticket.getServer().getName());
        if ( src.equals(client) && targ.equals(server) ) {
            return ticket.getSessionKey();
        }
    }
    return null;
}
 
Example 16
Source File: SecurityActions.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the PasswordCredential from the Subject
 * @param subject The subject
 * @return The instances
 */
static Set<PasswordCredential> getPasswordCredentials(final Subject subject)
{
   if (System.getSecurityManager() == null)
      return subject.getPrivateCredentials(PasswordCredential.class);

   return AccessController.doPrivileged(new PrivilegedAction<Set<PasswordCredential>>() 
   {
      public Set<PasswordCredential> run()
      {
         return subject.getPrivateCredentials(PasswordCredential.class);
      }
   });
}
 
Example 17
Source File: ReferralsTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static void testSubjectCredentials() throws Exception {
    Subject clientSubject = new Subject();
    Context clientContext = Context.fromUserPass(clientSubject,
            clientKDC1Name, password, false);

    Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    if (clientPrincipals.size() != 1) {
        throw new Exception("Only one client subject principal expected");
    }
    Principal clientPrincipal = clientPrincipals.iterator().next();
    if (DEBUG) {
        System.out.println("Client subject principal: " +
                clientPrincipal.getName());
    }
    if (!clientPrincipal.getName().equals(clientKDC1Name)) {
        throw new Exception("Unexpected client subject principal.");
    }

    clientContext.startAsClient(serviceName, GSSUtil.GSS_KRB5_MECH_OID);
    clientContext.take(new byte[0]);
    Set<KerberosTicket> clientTickets =
            clientSubject.getPrivateCredentials(KerberosTicket.class);
    boolean tgtFound = false;
    boolean tgsFound = false;
    for (KerberosTicket clientTicket : clientTickets) {
        String cname = clientTicket.getClient().getName();
        String sname = clientTicket.getServer().getName();
        if (cname.equals(clientKDC2Name)) {
            if (sname.equals(PrincipalName.TGS_DEFAULT_SRV_NAME +
                    PrincipalName.NAME_COMPONENT_SEPARATOR_STR +
                    realmKDC2 + PrincipalName.NAME_REALM_SEPARATOR_STR +
                    realmKDC2)) {
                tgtFound = true;
            } else if (sname.equals(serviceKDC2Name)) {
                tgsFound = true;
            }
        }
        if (DEBUG) {
            System.out.println("Client subject KerberosTicket:");
            System.out.println(clientTicket);
        }
    }
    if (!tgtFound || !tgsFound) {
        throw new Exception("client subject tickets (TGT/TGS) not found.");
    }
    int numOfTickets = clientTickets.size();
    clientContext.startAsClient(serviceName, GSSUtil.GSS_KRB5_MECH_OID);
    clientContext.take(new byte[0]);
    clientContext.status();
    int newNumOfTickets =
            clientSubject.getPrivateCredentials(KerberosTicket.class).size();
    if (DEBUG) {
        System.out.println("client subject number of tickets: " +
                numOfTickets);
        System.out.println("client subject new number of tickets: " +
                newNumOfTickets);
    }
    if (numOfTickets != newNumOfTickets) {
        throw new Exception("Useless client subject TGS request because" +
                " TGS was not found in private credentials.");
    }
}
 
Example 18
Source File: KrbTicket.java    From openjdk-jdk8u with GNU General Public License v2.0 4 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 19
Source File: TestProxyUserSpnegoHttpServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
public void testProxy(String clientPrincipal, String doAs, int responseCode, String statusLine) throws Exception {
  // Create the subject for the client
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(WHEEL_PRINCIPAL, wheelKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse(clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
          clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse(privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull(tgt);

  // The name of the principal
  final String principalName = clientPrincipals.iterator().next().getName();

  // Run this code, logged in as the subject (the client)
  HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
      @Override
      public HttpResponse run() throws Exception {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient,
            GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

        HttpClientContext context = HttpClientContext.create();
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
            .build();

        HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                .build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

        URL url = new URL(getServerURL(server), "/echo?doAs=" + doAs + "&a=b");
        context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthSchemeRegistry(authRegistry);

        HttpGet get = new HttpGet(url.toURI());
        return client.execute(get, context);
      }
  });

  assertNotNull(resp);
  assertEquals(responseCode, resp.getStatusLine().getStatusCode());
  if(responseCode == HttpURLConnection.HTTP_OK) {
      assertTrue(EntityUtils.toString(resp.getEntity()).trim().contains("a:b"));
  } else {
      assertTrue(resp.getStatusLine().toString().contains(statusLine));
  }
}
 
Example 20
Source File: MoreThenOnePrincipals.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Policy file grants access to the private Credential,belonging to a
 * Subject with at least two associated Principals:"com.sun.security.auth
 * .NTUserPrincipal", with the name,"NTUserPrincipal-1", and
 * "com.sun.security.auth.UnixPrincipal", with the name, "UnixPrincipals-1".
 *
 * For test1 and test2, subjects are associated with none or only one of
 * principals mentioned above, SecurityException is expected.
 * For test 3 and test 4, subjects are associated with two or more
 * Principals (above principals are included), no exception is expected.
 *
 */

@Test(dataProvider = "Provider1", expectedExceptions = SecurityException.class)
public void test1(Subject s) {
    s.getPrivateCredentials(String.class);
}