@Before public void setupMocks() throws NamingException { SearchResult mockUserResult = mock(SearchResult.class); when(mockUserNamingEnum.nextElement()).thenReturn(mockUserResult); Attribute mockUidNumberAttr = mock(Attribute.class); Attribute mockGidNumberAttr = mock(Attribute.class); Attribute mockUidAttr = mock(Attribute.class); Attributes mockAttrs = mock(Attributes.class); when(mockUidAttr.get()).thenReturn("some_user"); when(mockUidNumberAttr.get()).thenReturn("700"); when(mockGidNumberAttr.get()).thenReturn("600"); when(mockAttrs.get(eq("uid"))).thenReturn(mockUidAttr); when(mockAttrs.get(eq("uidNumber"))).thenReturn(mockUidNumberAttr); when(mockAttrs.get(eq("gidNumber"))).thenReturn(mockGidNumberAttr); when(mockUserResult.getAttributes()).thenReturn(mockAttrs); }
/** * Performs the actual sync of the specified user. * @param ctx a DirContext * @param qm the AlpineQueryManager to use * @param sc the SearchControls to use * @param user the LdapUser instance to sync * @throws NamingException when a problem with the connection with the directory */ private void sync(DirContext ctx, AlpineQueryManager qm, SearchControls sc, LdapUser user) throws NamingException { final String searchFor = LDAP_ATTRIBUTE_NAME + "=" + formatPrincipal(user.getUsername()); LOGGER.debug("Syncing: " + user.getUsername()); final List<SearchResult> results = Collections.list(ctx.search(BASE_DN, searchFor, sc)); if (results.size() > 0) { // Should only return 1 result, but just in case, get the very first one final SearchResult result = results.get(0); user.setDN(result.getNameInNamespace()); final Attribute mail = result.getAttributes().get(ATTRIBUTE_MAIL); if (mail != null) { // user.setMail(mail.get()); //todo } } else { // This is an invalid user - a username that exists in the database that does not exist in LDAP user.setDN("INVALID"); // user.setMail(null); //todo } qm.updateLdapUser(user); }
private static String dnFromUser(String username) throws NamingException { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, "ldap://ldap.example.com"); props.put(Context.REFERRAL, "ignore"); InitialDirContext context = new InitialDirContext(props); SearchControls ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[]{"givenName", "sn"}); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> answers = context.search("dc=People,dc=example,dc=com", "(uid=" + username + ")", ctrls); SearchResult result = answers.next(); return result.getNameInNamespace(); }
@Override public void process(SearchResult result) throws NamingException, ParseException { try { doProcess(result); } finally { Object obj = result.getObject(); if (obj != null && obj instanceof Context) { try { ((Context)obj).close(); } catch (NamingException e) { logger.debug("error when closing result block context", e); } obj = null; } result = null; } }
@Test public void retrieveName_notRelative() { // given SearchResult searchResult = new SearchResult(null, null, null, false); searchResult.setNameInNamespace("cn=ldap01"); searchResult .setName("ldap://estdevmail1.dev.est.fujitsu.com:389/cn=ldap01"); ldapProps.put(Context.PROVIDER_URL, ""); // when String name = realmImpl.retrieveName(ldapProps, searchResult); // then assertEquals("cn=ldap01", name); assertEquals("ldap://estdevmail1.dev.est.fujitsu.com:389", ldapProps.getProperty(Context.PROVIDER_URL)); }
String retrieveName(Properties ldapProps, SearchResult res) { String name = ""; if (res.isRelative()) { name = res.getName(); } else { name = res.getNameInNamespace(); String urlName = res.getName(); int index = urlName.lastIndexOf("/"); if (index > 0) { ldapProps.put(Context.PROVIDER_URL, urlName.substring(0, index)); } } return name; }
@SuppressWarnings("rawtypes") private List<String> formatUserEnName(SearchResult sResult) { if (null == sResult) { return Collections.emptyList(); } List<String> result = new ArrayList<String>(); try { String memberKey = ldapConfig.get("memberKey"); NamingEnumeration namingEnumeration = sResult.getAttributes().getAll(); while (namingEnumeration.hasMoreElements()) { Attribute attr = (Attribute) namingEnumeration.next(); String attrId = attr.getID(); if (memberKey.equals(attrId)) { List<String> userEnNames = formatUserEnName(attr); result.addAll(userEnNames); } } } catch (Exception e) { loggerError("formatUserEnName 619", "", e); } return result; }
public void ldapInjectionSunApi(String input) throws NamingException { //Stub instances Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, "ldap://ldap.example.com"); props.put(Context.REFERRAL, "ignore"); SearchControls ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[]{"givenName", "sn"}); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); //Two context instances mostly usable with sun specific API LdapCtx context5 = null; EventDirContext context6 = null; //LdapCtx is the only known class to implements to this interface NamingEnumeration<SearchResult> answers; answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls); answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls); answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls); answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls); answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls); answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls); answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls); answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls); }
public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName, String principalDomain, String... attributeNames) throws NamingException { if (StringUtils.isBlank(userName)) { throw new IllegalArgumentException("Username and password can not be blank."); } if (attributeNames.length == 0) { return Collections.emptyMap(); } Attributes matchAttr = new BasicAttributes(true); BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain); matchAttr.put(basicAttr); NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames); if (ctx != null) { ctx.close(); } Map<String, String> result = new HashMap<>(); if (searchResult.hasMore()) { NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll(); while (attributes.hasMore()) { Attribute attr = attributes.next(); String attrId = attr.getID(); String attrValue = (String) attr.get(); result.put(attrId, attrValue); } } return result; }
@Before public void setupMocksBase() throws NamingException { mockContext = mock(DirContext.class); doReturn(mockContext).when(mappingSpy).getDirContext(); // We only ever call hasMoreElements once for the user NamingEnum, so // we can just have one return value when(mockUserNamingEnum.hasMoreElements()).thenReturn(true); SearchResult mockGroupResult = mock(SearchResult.class); // We're going to have to define the loop here. We want two iterations, // to get both the groups when(mockGroupNamingEnum.hasMoreElements()).thenReturn(true, true, false); when(mockGroupNamingEnum.nextElement()).thenReturn(mockGroupResult); // Define the attribute for the name of the first group Attribute group1Attr = new BasicAttribute("cn"); group1Attr.add(testGroups[0]); Attributes group1Attrs = new BasicAttributes(); group1Attrs.put(group1Attr); // Define the attribute for the name of the second group Attribute group2Attr = new BasicAttribute("cn"); group2Attr.add(testGroups[1]); Attributes group2Attrs = new BasicAttributes(); group2Attrs.put(group2Attr); // This search result gets reused, so return group1, then group2 when(mockGroupResult.getAttributes()).thenReturn(group1Attrs, group2Attrs); }
public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] args, SearchControls cons) throws NamingException { DirContextNamePair res = getTargetContext(name); return res.getDirContext().search(res.getName(), filterExpr, args, cons); }
/** * Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the * specified username. */ protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException { LdapContext ctx = null; try { // Binds using the system username and password. ctx = ldapContextFactory.getSystemLdapContext(); final SearchControls ctrl = new SearchControls(); ctrl.setCountLimit(1); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setTimeLimit(searchTimeoutMillis); final String filter = searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter) .replaceAll(username) : username; final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl); try { if (!result.hasMore()) { throw new AuthenticationException("No username: " + username); } return result.next().getNameInNamespace(); } finally { result.close(); } } finally { LdapUtils.closeContext(ctx); } }
public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { DirContextNamePair res = getTargetContext(name); return res.getDirContext().search(res.getName(), matchingAttributes, attributesToReturn); }
@Override protected Map<String, String> getUserByLoginImpl(String loginId, String password) { String suffix = ldapConfig.get("suffix"); if (loginId.indexOf(suffix) == -1) { loginId += suffix; } boolean login = ldapApiCheck(loginId, password); String primaryKey = ldapConfig.get("primaryKey"); if (!login) { return Collections.emptyMap(); } String action = "login"; String filter = primaryKey + "=" + loginId; List<SearchResult> sResultList = ldapApiQuery(action, "", filter); // filter userPrincipalName= 只能查询到一个结果 SearchResult sResult = sResultList.get(0); String groupIdStr = formatGroupId(sResult); String emailListStr = formatEmailList(sResult); Map<String, String> result = new HashMap<String, String>(); result.put("loginId", loginId); result.put("groupId", groupIdStr); result.put("emailList", emailListStr); return result; }
private DirContext mockDirContext(NamingEnumeration<SearchResult> namingEnumeration) throws NamingException { DirContext dirContext = EasyMock.createNiceMock(InitialDirContext.class); EasyMock.expect(dirContext.search(EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject(SearchControls.class))) .andReturn(namingEnumeration) .times(2); EasyMock.expect(dirContext.getNameParser("")) .andReturn(new NameParserImpl()).times(2); EasyMock.expect(dirContext.getNameInNamespace()) .andReturn("ANY NAME") .times(2); EasyMock.replay(dirContext); return dirContext; }
@Test public void retrieveName_relative() { // given SearchResult searchResult = new SearchResult(null, null, null, true); searchResult.setName("cn=ldap01"); // when String name = realmImpl.retrieveName(ldapProps, searchResult); // then assertEquals("cn=ldap01", name); }
@Test public void retrieveName_notRelative_Empty() { // given SearchResult searchResult = new SearchResult(null, null, null, false); searchResult.setNameInNamespace("cn=ldap01"); searchResult.setName(""); ldapProps.put(Context.PROVIDER_URL, "a"); // when String name = realmImpl.retrieveName(ldapProps, searchResult); // then assertEquals("cn=ldap01", name); assertEquals("a", ldapProps.getProperty(Context.PROVIDER_URL)); }
private boolean hasMoreEnum(NamingEnumeration<SearchResult> namingEnum) throws NamingException { boolean hasMore = true; try { if (!namingEnum.hasMore()) { hasMore = false; } } catch (PartialResultException e) { hasMore = false; logger.logWarn(Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.WARN_LDAP_PARTIAL_EXCEPTION); } return hasMore; }
/** * @return null if there are zero results */ private NamingEnumeration<SearchResult> search(DirContext ctx, Name base, String[] returnAttributes, Filter filter, boolean recurse) { SearchControls ctls = new SearchControls(); ctls.setCountLimit(filter.getLimit()); ctls.setReturningAttributes(returnAttributes); ctls.setSearchScope(recurse ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE); try { // Search for objects using the filter String query = filter.toFilter(); if( LOGGER.isDebugEnabled() ) { LOGGER.debug("Query:" + query + " Base:" + base); } NamingEnumeration<SearchResult> ne = ctx.search(base, query, ctls); if( ne.hasMore() ) { return ne; } } catch( PartialResultException pre ) { LOGGER.info(pre); } catch( SizeLimitExceededException slee ) { LOGGER.info(slee); } catch( Exception e ) { LOGGER.warn(e); } return null; }
public <T> T searchFirstResult(DirContext ctx, Name base, Filter filter, HitsCollector<T> collector, boolean recurse) throws NamingException { collector.setup(ctx, this); NamingEnumeration<SearchResult> ne = search(ctx, base, collector.getReturnAttributes(), filter, recurse); // The above returns null if there are no results, so assume if not null // that there is a first result if( ne != null ) { try { collector.addResult(ne.next(), base); return collector.getResults().get(0); } finally { // Because we're not going all the way to the end of the // enumeration, we have to manually close it. ne.close(); } } return null; }
public <T> List<T> search(DirContext ctx, Name base, Filter filter, HitsCollector<T> collector, boolean recurse) { collector.setup(ctx, this); NamingEnumeration<SearchResult> ne = search(ctx, base, collector.getReturnAttributes(), filter, recurse); try { while( ne != null && ne.hasMore() ) { SearchResult sr = ne.next(); collector.addResult(sr, base); } } catch( PartialResultException pre ) { LOGGER.info(pre); } catch( SizeLimitExceededException slee ) { LOGGER.info(slee); } catch( Exception e ) { LOGGER.error("Error searching", e); } return collector.getResults(); }
@Override public void addResult(SearchResult sr, Name base) throws NamingException { GroupBean gb = ldap.getGroupBeanFromResult(parse(sr.getNameInNamespace()), sr.getAttributes()); if( gb != null ) { results.add(gb); } }
public LDAPResult(SearchResult sr, Name base) throws InvalidNameException { attributes = sr.getAttributes(); // getNameInNamespace, otherwise you get parsing problems fullName = parse(sr.getNameInNamespace()); this.baseName = base; }
/** * Returns the distinguished name of a search result. * * @param context Our DirContext * @param base The base DN * @param result The search result * @return String containing the distinguished name */ protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException { // Get the entry's distinguished name NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(base); // Bugzilla 32269 Name entryName = parser.parse(new CompositeName(result.getName()).get(0)); Name name = contextName.addAll(baseName); name = name.addAll(entryName); return name.toString(); }
public NamingEnumeration<SearchResult> search(final String baseDN, final String filter) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); LdapContext ctx = new InitialLdapContext(env, null); NamingEnumeration<SearchResult> result = ctx.search(baseDN, filter, searchControls); ctx.close(); return result; }
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { DirContextStringPair res = getTargetContext(name); return res.getDirContext().search(res.getString(), matchingAttributes, attributesToReturn); }
public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] args, SearchControls cons) throws NamingException { DirContextStringPair res = getTargetContext(name); return res.getDirContext().search(res.getString(), filterExpr, args, cons); }
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { DirContextStringPair res = getTargetContext(name); return res.getDirContext().search(res.getString(), matchingAttributes); }
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { DirContextStringPair res = getTargetContext(name); return res.getDirContext().search(res.getString(), filter, cons); }
/** * @param csUser: specific user we want to login * @param csPassword: specific password * @param bUseGenericUser: true if connecting using generic user, not the specific user (csUser / csPassword); in that case csUser/csPassword is ignored * @return String UserDN; set to null or empty if user did not login correctly. */ public String getUserLogin(String csUser, String csPassword, boolean bUseGenericUser) { String csUserLogin = csUser; String csPasswordLogin = csPassword; if (bUseGenericUser) { csUserLogin = m_csLDAPGenericUser; csPasswordLogin = m_csLDAPGenericPassword; } if (!validateLogin(csUserLogin, csPasswordLogin)) { return null ; } if (m_ldap == null) { return null ; } NamingEnumeration enumer = m_ldap.searchSubtree(m_csLDAPRootOU, "sAMAccountName="+csUser) ; if (enumer.hasMoreElements()) { SearchResult res = (SearchResult)enumer.nextElement() ; String name = res.getNameInNamespace() ; return name ; } return null; }
@SuppressWarnings ( "unchecked" ) public static Enumeration<?> makeLazySearchEnumeration ( String codebase, String clazz ) throws Exception { DirContext ctx = makeContinuationContext(codebase, clazz); NamingEnumeration<?> inner = Reflections.createWithoutConstructor(LazySearchEnumerationImpl.class); Reflections.setFieldValue(inner, "nextMatch", new SearchResult("foo", ctx, null)); return new LazySearchEnumerationImpl((NamingEnumeration<Binding>) inner, null, null); }
@Before public void setupMocks() throws NamingException { mockContext = mock(DirContext.class); doReturn(mockContext).when(mappingSpy).getDirContext(); SearchResult mockUserResult = mock(SearchResult.class); // We only ever call hasMoreElements once for the user NamingEnum, so // we can just have one return value when(mockUserNamingEnum.hasMoreElements()).thenReturn(true); when(mockUserNamingEnum.nextElement()).thenReturn(mockUserResult); when(mockUserResult.getNameInNamespace()).thenReturn("CN=some_user,DC=test,DC=com"); SearchResult mockGroupResult = mock(SearchResult.class); // We're going to have to define the loop here. We want two iterations, // to get both the groups when(mockGroupNamingEnum.hasMoreElements()).thenReturn(true, true, false); when(mockGroupNamingEnum.nextElement()).thenReturn(mockGroupResult); // Define the attribute for the name of the first group Attribute group1Attr = new BasicAttribute("cn"); group1Attr.add(testGroups[0]); Attributes group1Attrs = new BasicAttributes(); group1Attrs.put(group1Attr); // Define the attribute for the name of the second group Attribute group2Attr = new BasicAttribute("cn"); group2Attr.add(testGroups[1]); Attributes group2Attrs = new BasicAttributes(); group2Attrs.put(group2Attr); // This search result gets reused, so return group1, then group2 when(mockGroupResult.getAttributes()).thenReturn(group1Attrs, group2Attrs); }
@Override @SuppressWarnings("unchecked") public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return emptyEnum; }
List<String> doGetGroups(String user) throws NamingException { List<String> groups = new ArrayList<String>(); DirContext ctx = getDirContext(); // Search for the user. We'll only ever need to look at the first result NamingEnumeration<SearchResult> results = ctx.search(baseDN, userSearchFilter, new Object[]{user}, SEARCH_CONTROLS); if (results.hasMoreElements()) { SearchResult result = results.nextElement(); String userDn = result.getNameInNamespace(); NamingEnumeration<SearchResult> groupResults = null; if (isPosix) { String gidNumber = null; String uidNumber = null; Attribute gidAttribute = result.getAttributes().get(posixGidAttr); Attribute uidAttribute = result.getAttributes().get(posixUidAttr); if (gidAttribute != null) { gidNumber = gidAttribute.get().toString(); } if (uidAttribute != null) { uidNumber = uidAttribute.get().toString(); } if (uidNumber != null && gidNumber != null) { groupResults = ctx.search(baseDN, "(&"+ groupSearchFilter + "(|(" + posixGidAttr + "={0})" + "(" + groupMemberAttr + "={1})))", new Object[] { gidNumber, uidNumber }, SEARCH_CONTROLS); } } else { groupResults = ctx.search(baseDN, "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))", new Object[]{userDn}, SEARCH_CONTROLS); } if (groupResults != null) { while (groupResults.hasMoreElements()) { SearchResult groupResult = groupResults.nextElement(); Attribute groupName = groupResult.getAttributes().get(groupNameAttr); groups.add(groupName.get().toString()); } } } return groups; }
@Override public List<Map<String, String>> getUserByQuery(String email) { if (StringHelper.isEmpty(email)) { return Collections.emptyList(); } String suffix = ldapConfig.get("suffix"); String userCNField = "cn"; String userQueryField = ldapConfig.get("userQueryField"); String email1 = email + suffix; String filter = "(|(" + userCNField + "=" + email + ")(" + userQueryField + "=" + email + ")(" + userQueryField + "=" + email1 + "))"; String action = "query"; /** * 查询ldap 获取list信息 */ List<Map<String, String>> result = new ArrayList<Map<String, String>>(); List<SearchResult> sResultList = ldapApiQuery(action, "", filter); if (sResultList.isEmpty()) { Map<String, String> msg = new HashMap<String, String>(); msg.put("msg", "email query,result is empty."); result.add(msg); return result; } for (SearchResult sResult : sResultList) { /** * 遍历格式化用户信息 */ Map<String, String> emailInfoMap = formatEmailInfo(sResult, userQueryField); String groupIdStr = formatGroupId(sResult); String emailListStr = formatEmailList(sResult); Map<String, String> info = new HashMap<String, String>(); info.put("email", emailInfoMap.get("email")); info.put("name", emailInfoMap.get("name")); info.put("groupId", groupIdStr); info.put("emailList", emailListStr); result.add(info); } return result; }
public Collection<String> getPersonNames() { final List<String> personNames = new LinkedList<String>(); processQuery(new AbstractSearchCallback() { protected void doProcess(SearchResult result) throws NamingException, ParseException { Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.userIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingUID) { Object[] params = {result.getNameInNamespace(), LDAPUserRegistry.this.userIdAttributeName}; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.user.id.missing", params); } else { LDAPUserRegistry.logger.warn("User missing user id attribute DN =" + result.getNameInNamespace() + " att = " + LDAPUserRegistry.this.userIdAttributeName); } } else { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Person DN recognized: " + nameAttribute.get()); } personNames.add((String) nameAttribute.get()); } } public void close() throws NamingException { } }, this.userSearchBase, this.personQuery, new String[] { this.userIdAttributeName }); return personNames; }