private static String extractCN(final String subjectPrincipal) throws SSLException { if (subjectPrincipal == null) { return null; } try { final LdapName subjectDN = new LdapName(subjectPrincipal); final List<Rdn> rdns = subjectDN.getRdns(); for (int i = rdns.size() - 1; i >= 0; i--) { final Rdn rds = rdns.get(i); final Attributes attributes = rds.toAttributes(); final Attribute cn = attributes.get("cn"); if (cn != null) { try { final Object value = cn.get(); if (value != null) { return value.toString(); } } catch (final NoSuchElementException ignore) { // ignore exception } catch (final NamingException ignore) { // ignore exception } } } return null; } catch (final InvalidNameException e) { throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name"); } }
String description; try { name = ((String)((a.get(manager.getGroupNameField())).get())); description = ((String)((a.get(manager.getGroupDescriptionField())).get())); Attribute memberField = a.get(manager.getGroupMemberField()); if (memberField != null) { NamingEnumeration ne = memberField.getAll(); while (ne.hasMore()) { String username = (String) ne.next(); LdapName ldapName = new LdapName(username); userFilter.append(ldapName.get(ldapName.size() - 1)); userFilter.append(')'); userFilter.append(MessageFormat.format(manager.getSearchFilter(), "*")); NamingEnumeration usrAnswer = ctx.search("", userFilter.toString(), searchControls); if (usrAnswer != null && usrAnswer.hasMoreElements()) { SearchResult searchResult = null; while(usrAnswer.hasMoreElements()) { searchResult = (SearchResult) usrAnswer.nextElement(); Attributes attrs = searchResult.getAttributes(); if (isAD) { Attribute userdnAttr = attrs.get("distinguishedName");
private LdapSearch createLdapSearchByDn() { if ( ! name.regionMatches(true, 0, identityMapping.rdnIdentifier, 0, identityMapping.rdnIdentifier.length())) { return null; } // equal sign not checked here as whitespaces can be between yet try { LdapName ldapName = new LdapName(name); int rdnPosition = ldapName.size() - 1; Rdn rdnIdentifier = ldapName.getRdn(rdnPosition); if ( ! rdnIdentifier.getType().equalsIgnoreCase(identityMapping.rdnIdentifier)) { // uid=... log.tracef("Getting identity [%s] by DN skipped - RDN does not match [%s]", name, identityMapping.rdnIdentifier); return null; } if (identityMapping.searchDn != null) { List<Rdn> expectedStart = new LdapName(identityMapping.searchDn).getRdns(); if ( ! ldapName.startsWith(expectedStart)) { // ...,search-dn log.tracef("Getting identity [%s] by DN skipped - DN not in search-dn [%s]", name, identityMapping.searchDn); return null; } if ( ! identityMapping.searchRecursive && ldapName.size() != expectedStart.size() + 1) { log.tracef("Getting identity [%s] by DN skipped - DN not directly in search-dn and recursive search not enabled [%s]", name, identityMapping.searchDn); return null; } } return new LdapSearch(ldapName.toString(), SearchControls.OBJECT_SCOPE, 0, identityMapping.filterName, rdnIdentifier.getValue().toString()); } catch (InvalidNameException e) { log.tracef(e, "Getting identity [%s] by DN failed - will continue by name", name); } return null; }
public void setTempSearchBase(String tempSearchBase) { try { LdapName baseName = new LdapName(tempSearchBase); tempPrefixLength = baseName.size(); this.tempSearchBase = tempSearchBase; } catch (InvalidNameException e) { throw new IllegalArgumentException("Invalid base DN value " + tempSearchBase, e); } }
private List<String> getDnAttribute(LdapName rfc2253dn, String attribute) { final List<String> attrValues = new ArrayList<>(rfc2253dn.size()); final List<Rdn> reverseRdn = new ArrayList<>(rfc2253dn.getRdns()); Collections.reverse(reverseRdn); for (Rdn rdn : reverseRdn) { if (rdn.getType().equalsIgnoreCase(attribute)) { attrValues.add(rdn.getValue().toString()); } } return Collections.unmodifiableList(attrValues); } }
private List<String> getUserRolesFromLdap(SearchResult ldapUser) throws NamingException { List<String> groups = new ArrayList<>(); NamingEnumeration<?> groupAttributes = ldapUser.getAttributes().get("memberOf").getAll(); while (groupAttributes.hasMore()) { LdapName name = new LdapName((String) groupAttributes.next()); for (Rdn rdn : name.getRdns()) { if (rdn.getType().equalsIgnoreCase("cn")) { groups.add((String) rdn.getValue()); break; } } } return groups; } }
protected Set<GroupPrincipal> getACLs(String destinationBase, SearchControls constraints, String roleBase, String roleAttribute) { try { Set<GroupPrincipal> roles = new HashSet<GroupPrincipal>(); Set<String> acls = new HashSet<String>(); NamingEnumeration<?> results = context.search(destinationBase, roleBase, constraints); while (results.hasMore()) { SearchResult result = (SearchResult)results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) { continue; } acls = addAttributeValues(roleAttribute, attrs, acls); } for (Iterator<String> iter = acls.iterator(); iter.hasNext();) { String roleName = iter.next(); LdapName ldapname = new LdapName(roleName); Rdn rdn = ldapname.getRdn(ldapname.size() - 1); LOG.debug("Found role: [" + rdn.getValue().toString() + "]"); roles.add(new GroupPrincipal(rdn.getValue().toString())); } return roles; } catch (NamingException e) { LOG.error(e.toString()); return new HashSet<GroupPrincipal>(); } }
/** * Processes results from a directory query in the context of a given destination type and permission type. This * implementation should not be invoked concurrently. * * @param results * the results to process * @param destinationType * the type of the destination for which the directory results apply * @param permissionType * the type of the permission for which the directory results apply * * @throws Exception * if there is an error processing the results */ protected void processQueryResults(DefaultAuthorizationMap map, NamingEnumeration<SearchResult> results, DestinationType destinationType, PermissionType permissionType) throws Exception { while (results.hasMore()) { SearchResult result = results.next(); AuthorizationEntry entry = null; try { entry = getEntry(map, new LdapName(result.getNameInNamespace()), destinationType); } catch (Exception e) { LOG.error("Policy not applied! Error parsing authorization policy entry under {}", result.getNameInNamespace(), e); continue; } applyACL(entry, result, permissionType); } }
@Nullable static String getClientUniqueID (@Nonnull final X509Certificate aCert) { try { // subject principal name must be in the order CN=XX,O=YY,C=ZZ // In some JDK versions it is O=YY,CN=XX,C=ZZ instead (e.g. 1.6.0_45) final LdapName aLdapName = new LdapName (aCert.getSubjectX500Principal ().getName ()); // Make a map from type to name final ICommonsMap <String, Rdn> aParts = new CommonsHashMap <> (); for (final Rdn aRdn : aLdapName.getRdns ()) aParts.put (aRdn.getType (), aRdn); // Re-order - least important item comes first (=reverse order)! final String sSubjectName = new LdapName (new CommonsArrayList <> (aParts.get ("C"), aParts.get ("O"), aParts.get ("CN"))).toString (); // subject-name + ":" + serial number hexstring return sSubjectName + ':' + aCert.getSerialNumber ().toString (16); } catch (final Exception ex) { LOGGER.error ("Failed to parse '" + aCert.getSubjectX500Principal ().getName () + "'", ex); return null; } }
private LdapEntry parseRole(String dn, String groupNameAttribute, URI groupReferralAddress) { try { LdapName ldapName = new LdapName(Rdn.unescapeValue(dn).toString()); for (int i = ldapName.size() - 1; i >= 0; i--) { String rdnString = ldapName.get(i); Rdn rdn = new Rdn(rdnString); Attribute attr = rdn.toAttributes().get(groupNameAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { return new LdapEntry( (value instanceof byte[]) ? new String((byte[]) value, StandardCharsets.UTF_8) : value.toString(), dn, groupReferralAddress); } } } } catch (NamingException e) { SECURITY_LOGGER.tracef("Unable to parse role from DN (%s): %s", dn, e.getMessage()); } return null; }
private static String getGroupNameFromDn(String dnString, String groupNameAttribute) throws NamingException { LdapName dn = new LdapName(dnString); // may throw InvalidNameException Attribute attribute = dn.getRdn(dn.size()-1).toAttributes().get(groupNameAttribute); if (attribute == null) { // We were configured with the wrong group name attribute throw new IdentityStoreConfigurationException("Group name attribute '" + groupNameAttribute + "' not found for DN: " + dnString); } return attribute.get(0).toString(); }
/** * Returns Subject DN from X509Certificate * * @param cert * @return Subject DN as a user name */ @Override public String getUserName(Certificate cert) { X509Certificate certificate = (X509Certificate) cert; String dn = certificate.getSubjectDN().getName(); LdapName ldapDn = getLdapName(dn); if (key == null) { throw new IllegalArgumentException("Must set a key"); } for (Rdn rdn : ldapDn.getRdns()) { if (key.equalsIgnoreCase(rdn.getType())) { return (String)rdn.getValue(); } } throw new IllegalArgumentException("No " + key + " key found in certificate DN: " + dn); }
/** * Find the Rdn with the requested key in the supplied Name. * * @param name the Name in which to search for the key. * @param key the attribute key to search for. * @return the rdn corresponding to the <b>first</b> occurrence of the requested key. * @throws NoSuchElementException if no corresponding entry is found. * @since 2.0 */ public static Rdn getRdn(Name name, String key) { Assert.notNull(name, "name must not be null"); Assert.hasText(key, "key must not be blank"); LdapName ldapName = returnOrConstructLdapNameFromName(name); List<Rdn> rdns = ldapName.getRdns(); for (Rdn rdn : rdns) { NamingEnumeration<String> ids = rdn.toAttributes().getIDs(); while (ids.hasMoreElements()) { String id = ids.nextElement(); if(key.equalsIgnoreCase(id)) { return rdn; } } } throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'"); }
private void doDeleteChildrenRecursively(String distinguishName) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> ne = ctx.search(distinguishName, DEFAULT_FILTER, sc); while (ne.hasMore()) { SearchResult sr = (SearchResult) ne.next(); String childrenDn = rewriteBase(sr.getName() + "," + distinguishName); deleteChildrenRecursively(childrenDn); } ctx.destroySubcontext(new LdapName(distinguishName)); }
private void storeAttributes(String alias, List<ModificationItem> items) throws KeyStoreException { DirContext context = obtainDirContext(); try { SearchResult result = searchAlias(context, alias, null, new String[]{}); LdapName distinguishName; if (result == null) { // alias not exists yet - create if (createPath == null || createAttributes == null || createRdn == null) throw log.creationNotConfigured(alias); distinguishName = (LdapName) createPath.clone(); distinguishName.add(new Rdn(createRdn, alias)); log.debugf("Creating keystore alias [%s] with DN [%s] in LDAP", alias, distinguishName.toString()); context.createSubcontext(distinguishName, createAttributes); items.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(aliasAttribute, alias))); } else { distinguishName = new LdapName(result.getNameInNamespace()); } context.modifyAttributes(distinguishName, items.toArray(new ModificationItem[items.size()])); } catch (NamingException e) { throw log.ldapKeyStoreFailedToStore(alias, e); } finally { returnDirContext(context); } }
/** * Builds the Spring Authentication object using the supplied user name and groups looked up from LDAP. Groups are currently * mapped directly to Spring roles by converting to upper case and prepending the name with "ROLE_". * @param userName The username to build the Authentication object with. * @param httpRequest HttpServletRequest * @return Authentication object for the given user. */ protected Authentication getAuthentication(String userName, HttpServletRequest httpRequest) { String ldapName = LdapNameBuilder.newInstance().add(userSearchBase).add("uid", userName).build().toString(); // Search ldap for a user's groups and convert to a Spring role List<GrantedAuthority> grantedAuths = ldapTemplate.search(query() .where("objectclass") .is("groupOfNames") .and("member") .is(ldapName), (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get()) .stream() .map(group -> String.format("%s%s", SECURITY_ROLE_PREFIX, group.toUpperCase())) .map(SimpleGrantedAuthority::new).collect(Collectors.toList()); final UserDetails principal = new User(userName, "", grantedAuths); final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( principal, "", grantedAuths); WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); authentication.setDetails(webDetails); return authentication; }
LdapName oldName = new LdapName(oldBinding.getName()); ActiveMQDestination oldDest = formatDestination(oldName, destinationType); LdapName newName = new LdapName(newBinding.getName()); ActiveMQDestination newDest = formatDestination(newName, destinationType); NamingEnumeration<SearchResult> results = context.search(newName, getFilterForPermissionType(newPermissionType), controls); if (results.hasMore()) { objectAdded(namingEvent, destinationType, newPermissionType); matchedToType = true;
LdapName identityLdapName = new LdapName(identity.getDistinguishedName()); String renameTo = null; identity.getDirContext().modifyAttributes(identityLdapName, modItemsArray); if (renameTo != null && ! renameTo.equals(identityLdapName.getRdn(identityLdapName.size()-1).getValue())) { LdapName newLdapName = new LdapName(identityLdapName.getRdns().subList(0, identityLdapName.size()-1)); newLdapName.add(new Rdn(identityMapping.rdnIdentifier, renameTo)); identity.getDirContext().rename(identityLdapName, newLdapName);