private void doTestGetGroups(List<String> expectedGroups, int searchTimes) throws IOException, NamingException { Configuration conf = new Configuration(); // Set this, so we don't throw an exception conf.set(LdapGroupsMapping.LDAP_URL_KEY, "ldap://test"); mappingSpy.setConf(conf); // Username is arbitrary, since the spy is mocked to respond the same, // regardless of input List<String> groups = mappingSpy.getGroups("some_user"); Assert.assertEquals(expectedGroups, groups); // We should have searched for a user, and then two groups verify(mockContext, times(searchTimes)).search(anyString(), anyString(), any(Object[].class), any(SearchControls.class)); }
/** * Creates a {@link SearchParams} from JNDI search controls. * * @param searchControls the search controls * @param aliasDerefMode the alias deref mode * @return the search params */ public static SearchParams toSearchParams( SearchControls searchControls, AliasDerefMode aliasDerefMode ) { SearchParams searchParams = new SearchParams(); searchParams.setAliasDerefMode( aliasDerefMode ); searchParams.setTimeLimit( searchControls.getTimeLimit() ); searchParams.setSizeLimit( searchControls.getCountLimit() ); searchParams.setScope( SearchScope.getSearchScope( searchControls.getSearchScope() ) ); searchParams.setTypesOnly( searchControls.getReturningObjFlag() ); if ( searchControls.getReturningAttributes() != null ) { for ( String returningAttribute : searchControls.getReturningAttributes() ) { searchParams.addReturningAttributes( returningAttribute ); } } return searchParams; }
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(); }
protected ContextEnumerator(Context context, int scope, String contextName, boolean returnSelf) throws NamingException { if(context == null) { throw new IllegalArgumentException("null context passed"); } root = context; // No need to list children if we're only searching object if (scope != SearchControls.OBJECT_SCOPE) { children = getImmediateChildren(context); } this.scope = scope; this.contextName = contextName; // pretend root is processed, if we're not supposed to return ourself rootProcessed = !returnSelf; prepNextChild(); }
@SuppressWarnings("unchecked") @Before public void setup() throws Exception { bean = spy(new LdapAccessServiceBean()); dcMock = mock(DirContext.class); neMock = mock(NamingEnumeration.class); srMock = mock(SearchResult.class); aMock = mock(Attributes.class); doReturn(new Integer(5)).when(bean).getSearchLimit(); doReturn(dcMock).when(bean).getDirContext(any(Properties.class)); when(dcMock.search(anyString(), anyString(), any(SearchControls.class))) .thenReturn(neMock); when(Boolean.valueOf(neMock.hasMore())).thenReturn(Boolean.TRUE, Boolean.FALSE); when(neMock.next()).thenReturn(srMock); when(srMock.getAttributes()).thenReturn(aMock); }
public void queryVulnerableToInjection(LdapTemplate template, String jndiInjectMe, SearchControls searchControls, DirContextProcessor dirContextProcessor) throws NamingException { template.list(jndiInjectMe); template.list(jndiInjectMe, new DefaultNameClassPairMapper()); template.list(jndiInjectMe, new CountNameClassPairCallbackHandler()); template.lookup(jndiInjectMe); template.lookup(jndiInjectMe, new DefaultIncrementalAttributesMapper()); template.lookup(jndiInjectMe, new LdapEntryIdentificationContextMapper()); template.search(jndiInjectMe,"dn=1",searchControls,new CountNameClassPairCallbackHandler()); template.search(jndiInjectMe,"dn=1",searchControls,new DefaultIncrementalAttributesMapper(), dirContextProcessor); template.search(jndiInjectMe,"dn=1",searchControls,new LdapEntryIdentificationContextMapper(),dirContextProcessor); template.search(jndiInjectMe,"dn=1",searchControls,new CountNameClassPairCallbackHandler(),dirContextProcessor); template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,true,new CountNameClassPairCallbackHandler()); template.search(jndiInjectMe,"dn=1",new CountNameClassPairCallbackHandler()); template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new String[0],new DefaultIncrementalAttributesMapper()); template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new DefaultIncrementalAttributesMapper()); template.search(jndiInjectMe,"dn=1",new DefaultIncrementalAttributesMapper()); template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new String[0],new LdapEntryIdentificationContextMapper()); template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new LdapEntryIdentificationContextMapper()); template.search(jndiInjectMe,"dn=1",new LdapEntryIdentificationContextMapper()); template.search(jndiInjectMe,"dn=1",searchControls,new LdapEntryIdentificationContextMapper()); template.search(jndiInjectMe,"dn=1",searchControls, new DefaultIncrementalAttributesMapper()); }
/** * Adds {@code l} to list of listeners interested in {@code nm} * and filter. */ synchronized void addNamingListener(String nm, String filter, SearchControls ctls, NamingListener l) throws NamingException { if (l instanceof ObjectChangeListener || l instanceof NamespaceChangeListener) { NotifierArgs args = new NotifierArgs(nm, filter, ctls, l); NamingEventNotifier notifier = notifiers.get(args); if (notifier == null) { notifier = new NamingEventNotifier(this, ctx, args, l); notifiers.put(args, notifier); } else { notifier.addNamingListener(l); } } if (l instanceof UnsolicitedNotificationListener) { // Add listener to this's list of unsolicited notifiers if (unsolicited == null) { unsolicited = new Vector<>(3); } unsolicited.addElement((UnsolicitedNotificationListener)l); } }
/** * Adds <tt>l</tt> to list of listeners interested in <tt>nm</tt> * and filter. */ synchronized void addNamingListener(String nm, String filter, SearchControls ctls, NamingListener l) throws NamingException { if (l instanceof ObjectChangeListener || l instanceof NamespaceChangeListener) { NotifierArgs args = new NotifierArgs(nm, filter, ctls, l); NamingEventNotifier notifier = notifiers.get(args); if (notifier == null) { notifier = new NamingEventNotifier(this, ctx, args, l); notifiers.put(args, notifier); } else { notifier.addNamingListener(l); } } if (l instanceof UnsolicitedNotificationListener) { // Add listener to this's list of unsolicited notifiers if (unsolicited == null) { unsolicited = new Vector<>(3); } unsolicited.addElement((UnsolicitedNotificationListener)l); } }
@Test public void testGetGroups() throws IOException, NamingException { // The search functionality of the mock context is reused, so we will // return the user NamingEnumeration first, and then the group when(mockContext.search(anyString(), anyString(), any(Object[].class), any(SearchControls.class))) .thenReturn(mockUserNamingEnum, mockGroupNamingEnum); doTestGetGroups(Arrays.asList(testGroups), 2); }
/** * 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 void safe1() { new SearchControls(scope, countLimit, timeLimit, attributes, false, //OK deref); }
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); }
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; }
@Override public List<SearchResult> search(LDAPSettings settings, final String base, final String filter, final SearchControls ctls) { return new LDAP(settings, encryptionService).doAsAdmin(new InContext<List<SearchResult>>() { @Override public List<SearchResult> execute(DirContext ctx) throws NamingException { return Collections.list(ctx.search(base, filter, ctls)); } }); }
/** * @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 NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { DirContextStringPair res = getTargetContext(name); return res.getDirContext().search(res.getString(), filter, cons); }
public void unsafe1() { new SearchControls(scope, countLimit, timeLimit, attributes, true, //!! It will flag line 14 ... the beginning of the call deref); }
NotifierArgs(String name, int scope, NamingListener l) { this(name, "(objectclass=*)", null, l); // if scope is not default, create search ctl and set it if (scope != EventContext.ONELEVEL_SCOPE) { controls = new SearchControls(); controls.setSearchScope(scope); } }
NotifierArgs(String name, String filter, SearchControls ctls, NamingListener l) { this.name = name; this.filter = filter; this.controls = ctls; if (l instanceof NamespaceChangeListener) { mask |= ADDED_MASK|REMOVED_MASK|RENAMED_MASK; } if (l instanceof ObjectChangeListener) { mask |= CHANGED_MASK; } }
public Binding next() throws NamingException { if (!rootProcessed) { rootProcessed = true; return new Binding("", root.getClass().getName(), root, true); } if (scope != SearchControls.OBJECT_SCOPE && hasMoreDescendants()) { return getNextDescendant(); } throw new NoSuchElementException(); }
private void prepNextChild() throws NamingException { if(hasMoreChildren()) { try { currentChild = getNextChild(); currentReturned = false; } catch (NamingException e){ if (debug) System.out.println(e); if (debug) e.printStackTrace(); } } else { currentChild = null; return; } if(scope == SearchControls.SUBTREE_SCOPE && currentChild.getObject() instanceof Context) { currentChildEnum = newEnumerator( (Context)(currentChild.getObject()), scope, currentChild.getName(), false); currentChildExpanded = true; if(debug) {System.out.println("prepNextChild: expanded");} } else { currentChildExpanded = false; currentChildEnum = null; if(debug) {System.out.println("prepNextChild: normal");} } }
public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { DirContextNamePair res = getTargetContext(name); return res.getDirContext().search(res.getName(), filter, cons); }
@Test public void testGetGroupsWithLdapDown() throws IOException, NamingException { // This mocks the case where Ldap server is down, and always throws CommunicationException when(mockContext.search(anyString(), anyString(), any(Object[].class), any(SearchControls.class))) .thenThrow(new CommunicationException("Connection is closed")); // Ldap server is down, no groups should be retrieved doTestGetGroups(Arrays.asList(new String[] {}), 1 + LdapGroupsMapping.RECONNECT_RETRY_COUNT); // 1 is the first normal call }
/** * @param dn * @param filter * @return * @throws NamingException */ public NamingEnumeration searchChildren(String dn, String filter) throws NamingException { SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); return m_ctx.search(dn, filter, constraints); }
private boolean checkControls(SearchControls ctls) { if ((controls == null || ctls == null)) { return ctls == controls; } // ctls are nonempty return (controls.getSearchScope() == ctls.getSearchScope()) && (controls.getTimeLimit() == ctls.getTimeLimit()) && (controls.getDerefLinkFlag() == ctls.getDerefLinkFlag()) && (controls.getReturningObjFlag() == ctls.getReturningObjFlag()) && (controls.getCountLimit() == ctls.getCountLimit()) && checkStringArrays(controls.getReturningAttributes(), ctls.getReturningAttributes()); }
@ConditionalOnMissingBean(name = "ldapAttributeRepositories") @Bean @RefreshScope public List<IPersonAttributeDao> ldapAttributeRepositories() { final List<IPersonAttributeDao> list = new ArrayList<>(); final PrincipalAttributesProperties attrs = casProperties.getAuthn().getAttributeRepository(); attrs.getLdap().forEach(ldap -> { if (StringUtils.isNotBlank(ldap.getBaseDn()) && StringUtils.isNotBlank(ldap.getLdapUrl())) { final LdaptivePersonAttributeDao ldapDao = new LdaptivePersonAttributeDao(); LOGGER.debug("Configured LDAP attribute source for [{}] and baseDn [{}]", ldap.getLdapUrl(), ldap.getBaseDn()); ldapDao.setConnectionFactory(Beans.newLdaptivePooledConnectionFactory(ldap)); ldapDao.setBaseDN(ldap.getBaseDn()); LOGGER.debug("LDAP attributes are fetched from [{}] via filter [{}]", ldap.getLdapUrl(), ldap.getUserFilter()); ldapDao.setSearchFilter(ldap.getUserFilter()); final SearchControls constraints = new SearchControls(); if (ldap.getAttributes() != null && !ldap.getAttributes().isEmpty()) { LOGGER.debug("Configured result attribute mapping for [{}] to be [{}]", ldap.getLdapUrl(), ldap.getAttributes()); ldapDao.setResultAttributeMapping(ldap.getAttributes()); final String[] attributes = ldap.getAttributes().keySet().toArray(new String[ldap.getAttributes().keySet().size()]); constraints.setReturningAttributes(attributes); } else { LOGGER.debug("Retrieving all attributes as no explicit attribute mappings are defined for [{}]", ldap.getLdapUrl()); constraints.setReturningAttributes(null); } if (ldap.isSubtreeSearch()) { LOGGER.debug("Configured subtree searching for [{}]", ldap.getLdapUrl()); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } constraints.setDerefLinkFlag(true); ldapDao.setSearchControls(constraints); ldapDao.setOrder(ldap.getOrder()); LOGGER.debug("Initializing LDAP attribute source for [{}]", ldap.getLdapUrl()); ldapDao.initialize(); list.add(ldapDao); } }); return list; }
<T> List<T> search(String base, String filter, SearchControls controls, AttributesMapper<T> mapper, DirContextProcessor processor) throws NamingException;
@Override public <T> T searchForObject(String base, String filter, SearchControls searchControls, ContextMapper<T> mapper) { return null; }
public ContextEnumerator(Context context) throws NamingException { this(context, SearchControls.SUBTREE_SCOPE); }
private NamingEnumeration<SearchResult> getLDAPInformation(InitialDirContext context, String login) throws NamingException { SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.SUBTREE_SCOPE); cons.setDerefLinkFlag(false); return context.search(ldapValue.getUserSearchBase(), MessageFormat.format(ldapValue.getUserSearchFilter(), login), cons); }
@Override public <T> List<T> search(String base, String filter, SearchControls controls, AttributesMapper<T> mapper) throws NamingException { return null; }
@Override @SuppressWarnings("unchecked") public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return emptyEnum; }