/** * Method tries to resolve the {@link Credentials} used for login. It takes * authentication-extension of an already authenticated {@link Subject} into account. * * <p>Therefore the credentials are retrieved as follows: * * <ol> * <li>Test if the shared state contains credentials. * <li>Ask CallbackHandler for Credentials with using a {@link CredentialsCallback}. Expects * {@link CredentialsCallback#getCredentials} to return an instance of {@link Credentials}. * <li>Ask the Subject for its public <code>SimpleCredentials</code> see {@link * Subject#getPublicCredentials(Class)}, thus enabling to pre-authenticate the Subject. * </ol> * * @return Credentials or null if not found * @see #login() */ protected Credentials getCredentials() { Credentials credentials = null; if (sharedState.containsKey(KEY_CREDENTIALS)) { credentials = (Credentials) sharedState.get(KEY_CREDENTIALS); } else { try { CredentialsCallback callback = new CredentialsCallback(); callbackHandler.handle(new Callback[] {callback}); credentials = callback.getCredentials(); if (credentials != null && supportsCredentials(credentials)) { sharedState.put(KEY_CREDENTIALS, credentials); } } catch (UnsupportedCallbackException e) { log.warn("Credentials-Callback not supported try Name-Callback"); } catch (IOException e) { log.error("Credentials-Callback failed: " + e.getMessage() + ": try Name-Callback"); } } // if still no credentials -> try to retrieve them from the subject. if (null == credentials) { // try if subject contains SimpleCredentials Set<SimpleCredentials> preAuthCreds = subject.getPublicCredentials(SimpleCredentials.class); if (!preAuthCreds.isEmpty()) { credentials = preAuthCreds.iterator().next(); } } if (null == credentials) { // try if subject contains GuestCredentials Set<GuestCredentials> preAuthCreds = subject.getPublicCredentials(GuestCredentials.class); if (!preAuthCreds.isEmpty()) { credentials = preAuthCreds.iterator().next(); } } return credentials; }
/** * Merges the two {@link Subject}s in to a new {@link Subject}. The new subjects contains all the * {@link Principal}s from both subjects. If {@link #retainSubjectsPrivateCredentials} is true * then the new subject will contain all the private credentials from both subjects, if not the * new subject will not contain private credentials. If {@link #retainSubjectsPublicCredentials} * is true then the new subject will contain all the public credentials from both subjects, if not * the new subject will not contain public credentials. * * @param subject1 first subject to merge, may be null * @param subject2 second subject to merge, may be null * @return subject containing the merged information */ protected Subject mergeSubjects(Subject subject1, Subject subject2) { if (subject1 == null && subject2 == null) { return new Subject(); } if (subject1 == null) { return subject2; } if (subject2 == null) { return subject1; } Set<Principal> principals = new HashSet<Principal>(3); principals.addAll(subject1.getPrincipals()); principals.addAll(subject2.getPrincipals()); Set<Object> publicCredentials = new HashSet<Object>(3); if (retainSubjectsPublicCredentials) { LOG.debug("Merging in subjects public credentials"); publicCredentials.addAll(subject1.getPublicCredentials()); publicCredentials.addAll(subject2.getPublicCredentials()); } Set<Object> privateCredentials = new HashSet<Object>(3); if (retainSubjectsPrivateCredentials) { LOG.debug("Merging in subjects private credentials"); privateCredentials.addAll(subject1.getPrivateCredentials()); privateCredentials.addAll(subject2.getPrivateCredentials()); } return new Subject(false, principals, publicCredentials, privateCredentials); }
/** * @return <code>true</code> if this method succeeded, or <code>false</code> if this <code> * LoginModule</code> should be ignored. * @throws LoginException if the logout fails * @see javax.security.auth.spi.LoginModule#logout() */ public boolean logout() throws LoginException { if (subject.getPrincipals().isEmpty() || subject.getPublicCredentials(Credentials.class).isEmpty()) { return false; } else { // clear subject if not readonly if (!subject.isReadOnly()) { subject.getPrincipals().clear(); subject.getPublicCredentials().clear(); } return true; } }
protected void sendResponse(HttpSession session, Subject subject, PrintWriter out) { Map<String, Object> answer = new HashMap<String, Object>(); List<Object> principals = new ArrayList<Object>(); for (Principal principal : subject.getPrincipals()) { Map<String, String> data = new HashMap<String, String>(); data.put("type", principal.getClass().getName()); data.put("name", principal.getName()); principals.add(data); } List<Object> credentials = new ArrayList<Object>(); for (Object credential : subject.getPublicCredentials()) { Map<String, Object> data = new HashMap<String, Object>(); data.put("type", credential.getClass().getName()); data.put("credential", credential); } answer.put("principals", principals); answer.put("credentials", credentials); ServletHelpers.writeObject(converters, options, out, answer); }
/** * Method to commit the authentication process (phase 2). * * <p>This method is called if the LoginContext's overall authentication succeeded (the relevant * REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded). * * <p>If this LoginModule's own authentication attempt succeeded (checked by retrieving the * private state saved by the <code>login</code> method), then this method associates relevant * Principals and Credentials with the <code>Subject</code> located in the <code>LoginModule * </code>. If this LoginModule's own authentication attempted failed, then this method * removes/destroys any state that was originally saved. * * <p>The login is considered as succeeded if there is a principal set. * * <p>The implementation stores the principal associated to the UserID and all the Groups it is * member of with the Subject and in addition adds an instance of (#link SimpleCredentials} to the * Subject's public credentials. * * @return true if this method succeeded, or false if this <code>LoginModule</code> should be * ignored. * @throws LoginException if the commit fails * @see javax.security.auth.spi.LoginModule#commit() */ public boolean commit() throws LoginException { if (!isInitialized() || principal == null) { return false; } Set<Principal> principals = getPrincipals(); subject.getPrincipals().addAll(principals); subject.getPublicCredentials().add(credentials); return true; }
/* (non-Javadoc) * @see org.apache.servicemix.components.util.TransformComponentSupport#transform(javax.jbi.messaging.MessageExchange, javax.jbi.messaging.NormalizedMessage, javax.jbi.messaging.NormalizedMessage) */ @Override protected boolean transform( MessageExchange exchange, NormalizedMessage inMsg, NormalizedMessage outMsg) throws Exception { boolean success = false; try { Subject subject = inMsg.getSecuritySubject(); // Get principal Principal principal = null; Set<GridIdentifierPrincipal> principals = subject.getPrincipals(GridIdentifierPrincipal.class); if (principals == null || principals.size() == 0) { throw new RuntimeException("No GridIdentifierPrincipal found!"); } else if (principals.size() > 1) { throw new RuntimeException(principals.size() + " GridIdentifierPrincipals found!"); } principal = principals.iterator().next(); System.out.println("## Principal is: " + principal.getName()); // Get cert chain X509Certificate[] chain = null; Set<X509Certificate[]> chains = subject.getPublicCredentials(X509Certificate[].class); if (chains == null || chains.size() == 0) { throw new RuntimeException("No X509Certificate[] found!"); } else if (chains.size() > 1) { throw new RuntimeException(chains.size() + " X509Certificate[]s found!"); } chain = chains.iterator().next(); // Get private key PrivateKey privateKey = null; Set<PrivateKey> privateKeys = subject.getPrivateCredentials(PrivateKey.class); if (privateKeys == null || privateKeys.size() == 0) { throw new RuntimeException("No PrivateKey found!"); } else if (privateKeys.size() > 1) { throw new RuntimeException(chains.size() + " PrivateKeys found!"); } privateKey = privateKeys.iterator().next(); GlobusCredential cred = new GlobusCredential(privateKey, chain); System.out.println("## Identity is: " + cred.getIdentity()); String inMsgXml = new SourceTransformer().contentToString(inMsg); outMsg.setContent(new StreamSource(new ByteArrayInputStream(inMsgXml.getBytes()))); success = true; } catch (Exception ex) { ex.printStackTrace(); } return success; }
/** * Create an SSLSocketfactory from the credentials in the specified Subject. This method extracts * a X509CertificateChain from the public credentials and uses the certificate chain and private * key found there to set up a KeyStore for the SSLSocketFactory. * * @param s * @return an SSLSocketFactory, or null if no X509CertificateChain can be found */ public static SSLSocketFactory getSocketFactory(Subject s) { X509CertificateChain chain = null; if (s != null) { Set<X509CertificateChain> certs = s.getPublicCredentials(X509CertificateChain.class); for (X509CertificateChain cc : certs) { if (cc.getKey() != null) { chain = cc; break; } } } if (chain == null) return null; return getSocketFactory(chain); }
/** * Checks whether the subject's certificate credentials are valid at a given date. If date is * missing, current time is used as reference. * * @param subject Subject to check * @param date Date the certificate is verified against. If null, the credentials are verified * against current time. * @throws CertificateException Subject has no associated certificate credentials or there is a * problem with the existing certificate. * @throws CertificateExpiredException Certificate is expired. * @throws CertificateNotYetValidException Certificate not valid yet. */ public static void validateSubject(Subject subject, Date date) throws CertificateException, CertificateExpiredException, CertificateNotYetValidException { if (subject != null) { Set<X509CertificateChain> certs = subject.getPublicCredentials(X509CertificateChain.class); if (certs.size() == 0) { // subject without certs throw new CertificateException("No certificates associated with subject"); } X509CertificateChain chain = certs.iterator().next(); for (X509Certificate c : chain.getChain()) { if (date != null) { c.checkValidity(date); } else { c.checkValidity(); } } } }
private String getSecurityToken() { try { Class<?> wsSubjectClass = ClassLoaderUtil.loadClass("com.ibm.websphere.security.auth.WSSubject"); Class<?> wsCredentialClass = ClassLoaderUtil.loadClass("com.ibm.websphere.security.cred.WSCredential"); // Get current security subject Method m = wsSubjectClass.getMethod("getRunAsSubject", new Class[0]); Subject securitySubject = (Subject) m.invoke(null, new Object[0]); if (securitySubject != null) { // Get all security credentials from the security subject Set<?> securityCredentials = securitySubject.getPublicCredentials(wsCredentialClass); // Get the first credential Object securityCredential = securityCredentials.iterator().next(); String user = invokeSecurityCredentialMethod( wsCredentialClass, securityCredential, "getSecurityName"); if (user.equalsIgnoreCase("UNAUTHENTICATED")) { if (LOG.isDebugEnabled()) { LOG.debug("User = UNAUTHENTICATED"); } return null; } byte[] token = invokeSecurityCredentialMethod( wsCredentialClass, securityCredential, "getCredentialToken"); if (token == null) { return null; } return Base64.encodeBytes(token); } } catch (Exception e) { throw new CmisRuntimeException("Could not build SOAP header: " + e.getMessage(), e); } return null; }
/** * Returns <code>SubjectDecision</code> of <code>EntitlementSubject</code> evaluation * * @param realm Realm name. * @param subject EntitlementSubject who is under evaluation. * @param resourceName Resource name. * @param environment Environment parameters. * @return <code>SubjectDecision</code> of <code>EntitlementSubject</code> evaluation * @throws EntitlementException if any errors ocurr. */ public SubjectDecision evaluate( String realm, SubjectAttributesManager mgr, Subject subject, String resourceName, Map<String, Set<String>> environment) throws EntitlementException { boolean satified = false; Set publicCreds = subject.getPublicCredentials(); if ((publicCreds != null) && !publicCreds.isEmpty()) { Map<String, Set<String>> attributes = (Map<String, Set<String>>) publicCreds.iterator().next(); Set<String> values = attributes.get(SubjectAttributesCollector.NAMESPACE_MEMBERSHIP + ROLE_NAME); satified = (values != null) ? values.contains(getID()) : false; } satified = satified ^ isExclusive(); return new SubjectDecision(satified, Collections.EMPTY_MAP); }
@Override public UserGroupInformation cloneUgi(UserGroupInformation baseUgi) throws IOException { // Based on UserGroupInformation::createProxyUser. // TODO: use a proper method after we can depend on HADOOP-13081. if (getSubjectMethod == null) { throw new IOException("The UGI method was not found: " + ugiCloneError); } try { Subject origSubject = (Subject) getSubjectMethod.invoke(baseUgi); Subject subject = new Subject( false, origSubject.getPrincipals(), origSubject.getPublicCredentials(), origSubject.getPrivateCredentials()); return ugiCtor.newInstance(subject); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new IOException(e); } }
public void testEvaluateCombinativePermissionCollection() throws Throwable { PermissionUtils.setCachesEnabled(true); PermissionUtils.createCaches(); Subject subject = new Subject(); JGuardCredential nameA = new JGuardCredential(NAME, USER_A); JGuardCredential nameB = new JGuardCredential(NAME, USER_B); JGuardCredential companyA = new JGuardCredential(COMPANY, COMPANY_A); JGuardCredential companyB = new JGuardCredential(COMPANY, COMPANY_B); JGuardCredential age = new JGuardCredential(AGE, DUMMY_AGE); subject.getPublicCredentials().add(nameA); subject.getPublicCredentials().add(nameB); subject.getPublicCredentials().add(companyA); subject.getPublicCredentials().add(companyB); subject.getPublicCredentials().add(age); if (logger.isDebugEnabled()) { logger.debug("---- logging subject ----"); logger.debug(subject.toString()); } UserPrincipal userPrincipal = new UserPrincipal(subject); ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions(), null, new Principal[] {userPrincipal}); PermissionCollection pc = new Permissions(); Permission p1 = new FilePermission("file://home", "read"); Permission p2 = new FilePermission("file://home/user/${subject.publicCredentials.name}", "read"); Permission p3 = new FilePermission("file://home/user/${subject.publicCredentials.company}", "read"); Permission p4 = new FilePermission( "file://home/user/${subject.publicCredentials.name}/" + "${subject.publicCredentials.company}/${subject.publicCredentials.age}", "read"); Permission p5 = new FilePermission( "file://home/user/${subject.publicCredentials.company}/${subject.publicCredentials.company}", "read"); Permission p6 = new URLPermission( "index", "http://www.website.com/index.html?name=${subject.publicCredentials.name}&company=${subject.publicCredentials.company}&age=${subject.publicCredentials.age}"); pc.add(p1); pc.add(p2); pc.add(p3); pc.add(p4); pc.add(p5); pc.add(p6); if (logger.isDebugEnabled()) { logger.debug("---- logging unresolved permissions ----"); Enumeration unresolvedPermEnum = pc.elements(); while (unresolvedPermEnum.hasMoreElements()) { logger.debug(unresolvedPermEnum.nextElement().toString()); } } PermissionCollection expectedPc = new Permissions(); Permission expectedP1 = new FilePermission("file://home", "read"); Permission expectedP2a = new FilePermission("file://home/user/userA", "read"); Permission expectedP2b = new FilePermission("file://home/user/userB", "read"); Permission expectedP3a = new FilePermission("file://home/user/companyA", "read"); Permission expectedP3b = new FilePermission("file://home/user/companyB", "read"); Permission expectedP4a = new FilePermission("file://home/user/userA/companyA/100", "read"); Permission expectedP4b = new FilePermission("file://home/user/userA/companyB/100", "read"); Permission expectedP4c = new FilePermission("file://home/user/userB/companyA/100", "read"); Permission expectedP4d = new FilePermission("file://home/user/userB/companyB/100", "read"); Permission expectedP5a = new FilePermission("file://home/user/companyA/companyA", "read"); Permission expectedP5b = new FilePermission("file://home/user/companyA/companyB", "read"); Permission expectedP5c = new FilePermission("file://home/user/companyB/companyA", "read"); Permission expectedP5d = new FilePermission("file://home/user/companyB/companyB", "read"); Permission expectedP6a = new URLPermission( "index", "http://www.website.com/index.html?name=userA&company=companyA&age=100"); Permission expectedP6b = new URLPermission( "index", "http://www.website.com/index.html?name=userA&company=companyB&age=100"); Permission expectedP6c = new URLPermission( "index", "http://www.website.com/index.html?name=userB&company=companyA&age=100"); Permission expectedP6d = new URLPermission( "index", "http://www.website.com/index.html?name=userB&company=companyB&age=100"); expectedPc.add(expectedP1); expectedPc.add(expectedP2a); expectedPc.add(expectedP2b); expectedPc.add(expectedP3a); expectedPc.add(expectedP3b); expectedPc.add(expectedP4a); expectedPc.add(expectedP4b); expectedPc.add(expectedP4c); expectedPc.add(expectedP4d); expectedPc.add(expectedP5a); expectedPc.add(expectedP5b); expectedPc.add(expectedP5c); expectedPc.add(expectedP5d); expectedPc.add(expectedP6a); expectedPc.add(expectedP6b); expectedPc.add(expectedP6c); expectedPc.add(expectedP6d); // getting resolved permissions PermissionCollection resolvedPc = PrincipalUtils.evaluatePermissionCollection(protectionDomain, pc); if (logger.isDebugEnabled()) { logger.debug("---- logging expected permissions ----"); Enumeration expectedPermEnum = expectedPc.elements(); while (expectedPermEnum.hasMoreElements()) { logger.debug(expectedPermEnum.nextElement().toString()); } logger.debug("---- logging resolved permissions ----"); } int collectionSize = 0; Enumeration permEnum = resolvedPc.elements(); while (permEnum.hasMoreElements()) { Permission resolvedPerm = (Permission) permEnum.nextElement(); logger.debug("verify implies for " + resolvedPerm.toString()); System.out.println("verify implies for " + resolvedPerm.toString()); assertTrue(expectedPc.implies(resolvedPerm)); collectionSize++; } assertEquals(17, collectionSize); System.out.println("END EVALUATE COMBINATIVE PERMISSION TEST"); }
public void testEvaluatePermissionCollection() throws Throwable { PermissionUtils.setCachesEnabled(true); PermissionUtils.createCaches(); Subject subjectA = new Subject(); JGuardCredential nameA = new JGuardCredential(NAME, USER_A); JGuardCredential companyA = new JGuardCredential(COMPANY, COMPANY_A); subjectA.getPublicCredentials().add(nameA); subjectA.getPublicCredentials().add(companyA); if (logger.isDebugEnabled()) { logger.debug("---- logging subject ----"); logger.debug(subjectA.toString()); } UserPrincipal userPrincipal = new UserPrincipal(subjectA); ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions(), null, new Principal[] {userPrincipal}); PermissionCollection pc = new Permissions(); Permission p1 = new FilePermission("file://home", "read"); Permission p2 = new FilePermission("file://home/user/${subject.publicCredentials.name}", "read"); Permission p3 = new FilePermission("file://home/user/${subject.publicCredentials.company}", "read"); Permission p4 = new FilePermission( "file://home/user/${subject.publicCredentials.name}/" + "${subject.publicCredentials.company}/${subject.publicCredentials.name}/" + "${subject.publicCredentials.name}/${subject.publicCredentials.company}", "read"); Permission p5 = new FilePermission("file://home/user/${subject.publicCredentials.age}", "read"); Permission p6 = new URLPermission( "index", "http://www.website.com/index.html?name=${subject.publicCredentials.name}"); Permission p7 = new URLPermission( "index2", "http://www.web�site.com/index.html?name=${subject.publicCredentials.name}"); pc.add(p1); pc.add(p2); pc.add(p3); pc.add(p4); pc.add(p5); pc.add(p6); pc.add(p7); if (logger.isDebugEnabled()) { logger.debug("---- logging unresolved permissions ----"); Enumeration unresolvedPermEnum = pc.elements(); while (unresolvedPermEnum.hasMoreElements()) { logger.debug(unresolvedPermEnum.nextElement().toString()); } } PermissionCollection expectedPc = new Permissions(); Permission expectedP1 = new FilePermission("file://home", "read"); Permission expectedP2 = new FilePermission("file://home/user/userA", "read"); Permission expectedP3 = new FilePermission("file://home/user/companyA", "read"); Permission expectedP4 = new FilePermission("file://home/user/userA/companyA/userA/userA/companyA", "read"); Permission expectedP6 = new URLPermission("index", "http://www.website.com/index.html?name=userA"); Permission expectedP7 = new URLPermission("index2", "http://www.web�site.com/index.html?name=userA"); expectedPc.add(expectedP1); expectedPc.add(expectedP2); expectedPc.add(expectedP3); expectedPc.add(expectedP4); expectedPc.add(expectedP6); expectedPc.add(expectedP7); // getting resolved permissions PermissionCollection resolvedPc = PrincipalUtils.evaluatePermissionCollection(protectionDomain, pc); if (logger.isDebugEnabled()) { logger.debug("---- logging expected permissions ----"); Enumeration expectedPermEnum = expectedPc.elements(); while (expectedPermEnum.hasMoreElements()) { logger.debug(expectedPermEnum.nextElement().toString()); } logger.debug("---- logging resolved permissions ----"); } int collectionSize = 0; Enumeration permEnum = resolvedPc.elements(); while (permEnum.hasMoreElements()) { Permission resolvedPerm = (Permission) permEnum.nextElement(); logger.debug("verify implies for " + resolvedPerm.toString()); System.out.println("verify implies for " + resolvedPerm.toString()); assertTrue(expectedPc.implies(resolvedPerm)); collectionSize++; } assertEquals(6, collectionSize); System.out.println("END EVALUATE PERMISSION TEST"); }
/** * Returns the attribute values of the given user represented by <class>Subject</class> object. * * @param subject identity of the user * @param attrNames requested attribute names * @return a map of attribute names and their values * @throws com.sun.identity.entitlement.EntitlementException if this operation failed. */ public Map<String, Set<String>> getAttributes(Subject subject, Set<String> attrNames) throws EntitlementException { String uuid = SubjectUtils.getPrincipalId(subject); try { Map<String, Set<String>> results = new HashMap<String, Set<String>>(); Map<String, Set<String>> pubCreds = new HashMap<String, Set<String>>(); SSOToken adminToken = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance()); AMIdentity amid = new AMIdentity(adminToken, uuid); Set<String> set = new HashSet<String>(2); set.add(getIDWithoutOrgName(amid)); results.put(NAMESPACE_IDENTITY, set); set = new HashSet<String>(2); set.add(uuid); pubCreds.put(NAMESPACE_IDENTITY, set); Set<String> primitiveAttrNames = getAttributeNames(attrNames, NAMESPACE_ATTR); if (!primitiveAttrNames.isEmpty()) { Map<String, Set<String>> primitiveAttrValues = amid.getAttributes(primitiveAttrNames); for (String name : primitiveAttrValues.keySet()) { Set<String> values = primitiveAttrValues.get(name); if (values != null) { results.put(NAMESPACE_ATTR + name, values); pubCreds.put(NAMESPACE_ATTR + name, values); } } } Set<String> membershipAttrNames = getAttributeNames(attrNames, NAMESPACE_MEMBERSHIP); if (!membershipAttrNames.isEmpty()) { for (String m : membershipAttrNames) { IdType type = IdUtils.getType(m); if (type != null) { Set<AMIdentity> memberships = amid.getMemberships(type); if (memberships != null) { Set<String> setMemberships = new HashSet<String>(); Set<String> membershipsCred = new HashSet<String>(); for (AMIdentity a : memberships) { setMemberships.add(getIDWithoutOrgName(a)); membershipsCred.add(a.getUniversalId()); } results.put(NAMESPACE_MEMBERSHIP + m, setMemberships); pubCreds.put(NAMESPACE_MEMBERSHIP + m, membershipsCred); } } } } Set<Object> publicCreds = subject.getPublicCredentials(); publicCreds.add(pubCreds); return results; } catch (SSOException e) { Object[] params = {uuid}; throw new EntitlementException(600, params, e); } catch (IdRepoException e) { Object[] params = {uuid}; throw new EntitlementException(600, params, e); } }
/** * Get the set of TokenIdentifiers belonging to this UGI * * @return the set of TokenIdentifiers belonging to this UGI */ public synchronized Set<TokenIdentifier> getTokenIdentifiers() { return subject.getPublicCredentials(TokenIdentifier.class); }
/** * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been authenticated by the * RPC layer as belonging to the user represented by this UGI. * * @param tokenId tokenIdentifier to be added * @return true on successful add of new tokenIdentifier */ public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) { return subject.getPublicCredentials().add(tokenId); }