Java Code Examples for javax.naming.directory.InitialDirContext

The following are top voted examples for showing how to use javax.naming.directory.InitialDirContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Android_Code_Arbiter   File: JndiLdap.java   Source Code and License 9 votes vote down vote up
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();
}
 
Example 2
Project: open-rmbt   File: LookupService.java   Source Code and License 7 votes vote down vote up
String getDnsAttributes(String ip) {
	try {
		Hashtable<String, String> env = new Hashtable<>();
		env.put("java.naming.factory.initial",
				"com.sun.jndi.dns.DnsContextFactory");
		// TODO don't specify ws1, instead use ns servers for s.maxmind.com
		env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");

		DirContext ictx = new InitialDirContext(env);
		Attributes attrs = ictx.getAttributes(licenseKey + "." + ip
				+ ".s.maxmind.com", new String[] { "txt" });
		// System.out.println(attrs.get("txt").get());
		String str = attrs.get("txt").get().toString();
		return str;
	} catch (NamingException e) {
		// TODO fix this to handle exceptions
		System.out.println("DNS error");
		return null;
	}

}
 
Example 3
Project: ChronoBike   File: LdapUtil.java   Source Code and License 7 votes vote down vote up
public LdapUtil(String csUserId, String csPassword, String csServer)
  {
      try
{
          Hashtable<String, String> env = new Hashtable<String, String>();
          env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(Context.PROVIDER_URL, "ldap://"+csServer+"/");
          env.put(Context.SECURITY_AUTHENTICATION, "simple");
          env.put(Context.SECURITY_PRINCIPAL, csUserId);
          env.put(Context.SECURITY_CREDENTIALS, csPassword);        
          m_ctx = new InitialDirContext(env);
}
catch (NamingException e)
{
	e.printStackTrace();
	m_ctx = null ;
}
  }
 
Example 4
Project: sonar-activedirectory   File: ApacheDS.java   Source Code and License 7 votes vote down vote up
/**
 * This seems to be required for objectClass posixGroup.
 */
private ApacheDS activateNis() throws Exception {
  Preconditions.checkState(ldapServer.isStarted());

  Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
  Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
  ModificationItem[] mods = new ModificationItem[] {
    new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
    new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2)
  };

  Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, getUrl());

  DirContext ctx = new InitialDirContext(env);
  ctx.modifyAttributes("cn=nis,ou=schema", mods);

  return this;
}
 
Example 5
Project: alfresco-repository   File: ChainingUserRegistrySynchronizerTest.java   Source Code and License 6 votes vote down vote up
private LDAPInitialDirContextFactoryImpl getMockedLDAPSearchResult(boolean withEmail) throws NamingException
{
    @SuppressWarnings("unchecked")
    NamingEnumeration<SearchResult> mockedNamingEnumeration = mock(NamingEnumeration.class);
    when(mockedNamingEnumeration.hasMore()).thenReturn(true).thenReturn(false);

    BasicAttributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sAMAccountName", "U1"));
    attributes.put(new BasicAttribute("givenName", "U1"));
    if (withEmail)
    {
        attributes.put(new BasicAttribute("mail", "[email protected]"));
    }
    SearchResult mockedSearchResult = new SearchResult("CN:U1", null, attributes);
    mockedSearchResult.setNameInNamespace("CN:U1");

    when(mockedNamingEnumeration.next()).thenReturn(mockedSearchResult);

    InitialDirContext mockedInitialDirContext = mock(InitialDirContext.class);
    when(mockedInitialDirContext.search(any(String.class), any(String.class), any(SearchControls.class))).thenReturn(mockedNamingEnumeration);

    LDAPInitialDirContextFactoryImpl mockedLdapInitialDirContextFactory = mock(LDAPInitialDirContextFactoryImpl.class);
    when(mockedLdapInitialDirContextFactory.getDefaultIntialDirContext(0)).thenReturn(mockedInitialDirContext);
    return mockedLdapInitialDirContextFactory;
}
 
Example 6
Project: JenkinsHue   File: LDAPManager.java   Source Code and License 6 votes vote down vote up
public User getUserForLoginName(String login) {
	try {
		InitialDirContext ctx = createContext();

		User user = new User();
		SearchResult next = getLDAPInformation(ctx, login.toLowerCase()).nextElement();
		user.setLogin(login.toLowerCase());
		user.setSurname(next.getAttributes().get("sn").get().toString());
		user.setForename(next.getAttributes().get("givenName").get().toString());
		user.setEmail(next.getAttributes().get("mail").get().toString().toLowerCase());

		ctx.close();
		return user;
	} catch (Exception e) {
		log.info("Login " + login + " nicht gefunden!");
	}
	return null;
}
 
Example 7
Project: BaseClient   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 8
Project: BaseClient   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 9
Project: unitimes   File: LdapExternalUidLookup.java   Source Code and License 6 votes vote down vote up
public DirContext getDirContext() throws NamingException {
    Hashtable<String,String> env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
    env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
    env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
        env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
    env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
        env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
        System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
        System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
        System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));
	return new InitialDirContext(env);
}
 
Example 10
Project: unitimes   File: LdapExternalUidTranslation.java   Source Code and License 6 votes vote down vote up
public DirContext getDirContext() throws NamingException {
    Hashtable<String,String> env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
    env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
    env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
        env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
    env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
        env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
        System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
        System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
        System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));  
    return new InitialDirContext(env);
}
 
Example 11
Project: parabuild-ci   File: JNDIAuthenticator.java   Source Code and License 6 votes vote down vote up
/**
 * Open (if necessary) and return a connection to the configured
 * directory server for this Realm.
 *
 * @throws NamingException if a directory server error occurs
 */
private DirContext openContext() throws NamingException {
  if (log.isDebugEnabled()) {
    log.debug("opening context...");
  }
  final Hashtable environment = makeDirectoryContextEnvironment();
  if (log.isDebugEnabled()) {
    log.debug("environment: " + environment);
  }
  //noinspection UnnecessaryLocalVariable
  final InitialDirContext initialDirContext = new InitialDirContext(environment);
  if (log.isDebugEnabled()) {
    log.debug("initialDirContext: " + initialDirContext);
  }
  return initialDirContext;
}
 
Example 12
Project: Android_Code_Arbiter   File: JndiLdap.java   Source Code and License 6 votes vote down vote up
static boolean authenticate(String username, String password) {
    try {
        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");
        props.put(Context.SECURITY_PRINCIPAL, dnFromUser(username));
        props.put(Context.SECURITY_CREDENTIALS, password);

        new InitialDirContext(props);
        return true;
    } catch (NamingException e) {
        return false;
    }

}
 
Example 13
Project: Backmemed   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable<String, String> hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 14
Project: CustomWorldGen   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable<String, String> hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 15
Project: openjdk9   File: NamingManager.java   Source Code and License 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new InitialDirContext() {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example 16
Project: jk-util   File: ADAuthenticator.java   Source Code and License 6 votes vote down vote up
/**
 * Checks if is authenticed.
 *
 * @param host
 *            the host
 * @param port
 *            the port
 * @param userName
 *            the user name
 * @param password
 *            the password
 * @return true, if is authenticed
 * @throws NamingException
 *             the naming exception
 */
public static boolean isAuthenticed(String host, int port, String userName, String password) throws NamingException {
	log.info("isAuthenticed");
	// Set up the environment for creating the initial context
	Hashtable<String, String> env = new Hashtable<String, String>();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, userName + "@" + host);
	log.info(env.toString());
	env.put(Context.SECURITY_CREDENTIALS, password);
	// Create the initial context
	DirContext ctx = new InitialDirContext(env);
	log.info("DirContext Init Succ");
	boolean result = ctx != null;
	if (ctx != null) {
		log.info("Closing DirContext");
		ctx.close();
	}
	return result;
}
 
Example 17
Project: reladomo   File: JndiJdbcLdapDataSourceProvider.java   Source Code and License 6 votes vote down vote up
@Override
public DataSource createLdapDataSource(Properties loginProperties, String ldapName) throws NamingException
{
    DataSource ds;
    // borisv: this code stores all parameters in static baseEnvironment. So if you have multiple connections, next connection will get parameters from previous (unless overwriten by loginParamters).
    loginProperties.put(USE_JNDI_JDBC_CONNECTION_POOL_KEY, "false");
    if (loginProperties.getProperty(JAVA_NAMING_FACTORY_INITIAL) == null)
    {
        loginProperties.put(JAVA_NAMING_FACTORY_INITIAL, "com.sun.jndi.ldap.LdapCtxFactory");
    }
    InitialDirContext context = new JdbcInitialDirContext(loginProperties);

    Enumeration propKeys = loginProperties.keys();
    while(propKeys.hasMoreElements())
    {
        Object key = propKeys.nextElement();
        context.addToEnvironment((String)key, loginProperties.get(key));
    }

    ds = (DataSource) context.lookup(ldapName);
    return ds;
}
 
Example 18
Project: arz-ngs   File: DirContextPool.java   Source Code and License 6 votes vote down vote up
/**
 * Er zeugt einen neuen Connectionpool.
 * 
 * @param factory Die {@link PoolableObjectFactory}, die zum Erzeugen des Pools verwendet werden soll.
 * @param uri Die URI, die für die Verbindungen im Pool verwendet soll.
 * @param maxActive Die Zahl der maximal aktiven Verbindungen.
 * @param maxIdle Die Zahl der maximalen Idle-Verbindungen.
 * @param minIdle Die minimale Zahl der Idle-Verbindungen.
 * @param whenExhaustedAction -
 * @param maxWait -
 * @param timeBetweenEvictionRuns -
 * @param minEvictableIdleTime -
 */
public DirContextPool(	PoolableObjectFactory<InitialDirContext> factory,
						String uri,
						int maxActive,
						int maxIdle,
						int minIdle,
						byte whenExhaustedAction,
						int maxWait,
						long timeBetweenEvictionRuns,
						long minEvictableIdleTime) {
	super(factory);
	setMaxActive(maxActive);
	setMaxIdle(maxIdle);
	setMinIdle(minIdle);
	setWhenExhaustedAction(whenExhaustedAction);
	setMaxWait(maxWait);
	setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
	setMinEvictableIdleTimeMillis(minEvictableIdleTime);
	setTestOnBorrow(false);
	setTestOnReturn(true);
	setTestWhileIdle(false);

	this.uri = uri;
}
 
Example 19
Project: alfresco-mt-support   File: EnhancedLDAPUserRegistry.java   Source Code and License 6 votes vote down vote up
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query)
{
    LOGGER.debug("Building user searcher for query {}", query);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    userSearchCtls.setReturningAttributes(this.userKeys.getFirst());
    // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
    userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);

    return (ctx) -> {
        try
        {
            final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query, userSearchCtls);
            return results;
        }
        catch (final NamingException e)
        {
            throw new AlfrescoRuntimeException("Failed to import people.", e);
        }
    };
}
 
Example 20
Project: alfresco-mt-support   File: EnhancedLDAPUserRegistry.java   Source Code and License 6 votes vote down vote up
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query)
{
    LOGGER.debug("Building group searcher for query {}", query);

    final SearchControls groupSearchCtls = new SearchControls();
    groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst());
    // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
    groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);

    return (ctx) -> {
        try
        {
            final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query, groupSearchCtls);
            return results;
        }
        catch (final NamingException e)
        {
            throw new AlfrescoRuntimeException("Failed to import groups.", e);
        }
    };
}
 
Example 21
Project: mdw   File: LdapAdapter.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an LDAP connection based on the configured host, port and dn.
 */
@Override
protected Object openConnection() throws ConnectionException {
    try {
        String ldapHost = getAttributeValueSmart(LDAP_HOST);
        String ldapPort = getAttributeValueSmart(LDAP_PORT);
        String baseDn = getAttributeValueSmart(BASE_DN);;
        String appCuid = getAttributeValueSmart(APP_CUID);
        String appPassword = getAttributeValueSmart(APP_PASSWORD);
        String ldapUrl = "ldap://" + ldapHost + ":" + ldapPort + "/" + baseDn;

        Hashtable<String,String> env = new Hashtable<String,String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "uid=" + appCuid + ",ou=people," + baseDn);
        env.put(Context.SECURITY_CREDENTIALS, appPassword);
        return new InitialDirContext(env);
    }
    catch (Exception ex) {
        throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
    }
}
 
Example 22
Project: dorset-framework   File: LdapUserServiceTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = UserException.class)
public void testBadUsername() throws NamingException, UserException {
    String userName = "testUsername";
    Properties props = new Properties();
    props.setProperty("userName", userName);

    DirContext ctx = mock(InitialDirContext.class);
    String[] userAttributes = mockUserAttributes();
    LdapUserService lus = new LdapUserService(ctx, userAttributes);

    NamingEnumeration<SearchResult> mockSearchResults = mock(NamingEnumeration.class);

    when(ctx.search(any(String.class), any(String.class), any(SearchControls.class)))
                    .thenReturn(mockSearchResults);

    lus.retrieve(props);
}
 
Example 23
Project: vespa   File: IPAddressVerifier.java   Source Code and License 6 votes vote down vote up
protected String reverseLookUp(String ipAddress) throws NamingException {
    Hashtable<String, String> env = new Hashtable<>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String attributeName = ipAddress;
    DirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes(attributeName, new String[]{"PTR"});
    for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMoreElements(); ) {
        Attribute attr = ae.next();
        Enumeration<?> vals = attr.getAll();
        if (vals.hasMoreElements()) {
            String hostname = vals.nextElement().toString();
            ctx.close();
            return hostname.substring(0, hostname.length() - 1);
        }
    }
    ctx.close();
    return "";
}
 
Example 24
Project: hadoop-EAR   File: DNS.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.
 * 
 * @param hostIp
 *            The address to reverse lookup
 * @param ns
 *            The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException
 *             If a NamingException is encountered
 * @deprecated Reliance on DNS is not preferred
 */
@Deprecated
public static String reverseDns(InetAddress hostIp, String ns)
  throws NamingException {
  //
  // Builds the reverse IP lookup form
  // This is formed by reversing the IP numbers and appending in-addr.arpa
  //
  String[] parts = hostIp.getHostAddress().split("\\.");
  String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
    + parts[0] + ".in-addr.arpa";

  DirContext ictx = new InitialDirContext();
  Attributes attribute =
    ictx.getAttributes("dns://"               // Use "dns:///" if the default
                       + ((ns == null) ? "" : ns) + 
                       // nameserver is to be used
                       "/" + reverseIP, new String[] { "PTR" });
  ictx.close();
  
  return attribute.get("PTR").get().toString();
}
 
Example 25
Project: keystone4j   File: CRLVerifier.java   Source Code and License 6 votes vote down vote up
/**
 * Downloads a CRL from given LDAP url, e.g.
 * ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 */
private static X509CRL downloadCRLFromLDAP(String ldapURL) throws CertificateException, NamingException, CRLException,
		CertificateVerificationException {
	Map<String, String> env = new Hashtable<String, String>();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, ldapURL);

	DirContext ctx = new InitialDirContext((Hashtable<String, String>) env);
	Attributes avals = ctx.getAttributes("");
	Attribute aval = avals.get("certificateRevocationList;binary");
	byte[] val = (byte[]) aval.get();
	if ((val == null) || (val.length == 0)) {
		throw new CertificateVerificationException("Can not download CRL from: " + ldapURL);
	} else {
		InputStream inStream = new ByteArrayInputStream(val);
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		return (X509CRL) cf.generateCRL(inStream);
	}
}
 
Example 26
Project: geoip   File: LookupService.java   Source Code and License 6 votes vote down vote up
String getDnsAttributes(String ip) {
  try {
    Hashtable<String, String> env = new Hashtable<>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    // TODO don't specify ws1, instead use ns servers for s.maxmind.com
    env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");

    DirContext context = new InitialDirContext(env);
    try {
      Attributes attrs = context.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[]{"txt"});
      return attrs.get("txt").get().toString();
    }
    finally {
      context.close();
    }
  }
  catch (NamingException e) {
    // TODO fix this to handle exceptions
    System.out.println("DNS error");
    return null;
  }

}
 
Example 27
Project: FOXopen   File: LDAP.java   Source Code and License 6 votes vote down vote up
/**
 * Create a new instance of an LDAP connection
 *
 * @param pServerURL URL of the LDAP server: ldap://example.com
 * @param pUserDN User to authenticate with
 * @param pPassword Password to authenticate with
 */
public LDAP(String pServerURL, String pUserDN, String pPassword)
throws NamingException
{
  // Connect to LDAP server
  Hashtable<String, String> env = new Hashtable<>();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, pServerURL);

  //Auth code
  if (pUserDN != null) {
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, pUserDN);
    env.put(Context.SECURITY_CREDENTIALS, pPassword);
  }

  mServerContext = new InitialDirContext(env);
}
 
Example 28
Project: spring-boot-etcd   File: EtcdClientAutoConfiguration.java   Source Code and License 6 votes vote down vote up
private List<String> discoverNodes(String serviceName) throws NamingException {
	List<String> locations = new ArrayList<>();

	Hashtable<String, String> env = new Hashtable<String, String>();
	env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
	env.put("java.naming.provider.url", "dns:");

	DirContext context = new InitialDirContext(env);
	Attributes attributes = context.getAttributes(serviceName, new String[] { "SRV" });
	for (NamingEnumeration<? extends Attribute> records = attributes.getAll(); records.hasMore();) {
		Attribute record = records.next();
		NamingEnumeration<String> values = (NamingEnumeration<String>) record.getAll();
		while (values.hasMore()) {
			String dns = values.next();
			String[] split = dns.split(" ");
			String host = split[3];
			if (host.endsWith(".")) {
				host = host.substring(0, host.length() - 1);
			}

			String location = "http://" + host + ":2379";
			locations.add(location);
		}
	}
	return locations;
}
 
Example 29
Project: Lizard   File: LookupService.java   Source Code and License 6 votes vote down vote up
String getDnsAttributes(String ip) {
    try {
        Hashtable env = new Hashtable();
        env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
 // TODO don't specify ws1, instead use ns servers for s.maxmind.com
        env.put("java.naming.provider.url","dns://ws1.maxmind.com/");

        DirContext ictx = new InitialDirContext(env);
        Attributes attrs = ictx.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[] {"txt"});
        //System.out.println(attrs.get("txt").get());
        String str = attrs.get("txt").get().toString();
        return str;
    }
    catch(NamingException e) {
 // TODO fix this to handle exceptions
        System.out.println("DNS error");
        return null;
    }

}
 
Example 30
Project: AvunaHTTPD-Java   File: EmailRouter.java   Source Code and License 6 votes vote down vote up
private static String[] lookupMailHosts(String domainName) throws NamingException {
	InitialDirContext iDirC = new InitialDirContext();
	Attributes attributes = iDirC.getAttributes("dns:/" + domainName, new String[] { "MX" });
	Attribute attributeMX = attributes.get("MX");
	if (attributeMX == null) {
		return (new String[] { domainName });
	}
	String[][] pvhn = new String[attributeMX.size()][2];
	for (int i = 0; i < attributeMX.size(); i++) {
		pvhn[i] = ("" + attributeMX.get(i)).split("\\s+");
	}
	Arrays.sort(pvhn, new Comparator<String[]>() {
		public int compare(String[] o1, String[] o2) {
			return (Integer.parseInt(o1[0]) - Integer.parseInt(o2[0]));
		}
	});
	String[] sortedHostNames = new String[pvhn.length];
	for (int i = 0; i < pvhn.length; i++) {
		sortedHostNames[i] = pvhn[i][1].endsWith(".") ? pvhn[i][1].substring(0, pvhn[i][1].length() - 1) : pvhn[i][1];
	}
	return sortedHostNames;
}
 
Example 31
Project: openshift-ping   File: GetServicePort.java   Source Code and License 6 votes vote down vote up
private Set<DnsRecord> getDnsRecords(String serviceName) throws Exception {
    Set<DnsRecord> dnsRecords = new TreeSet<DnsRecord>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    env.put(Context.PROVIDER_URL, "dns:");
    env.put("com.sun.jndi.dns.recursion", "false");
    // default is one second, but os skydns can be slow
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    // retries handled by DnsPing
    //env.put("com.sun.jndi.dns.timeout.retries", "4");
    DirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes("_tcp." + serviceName, new String[]{"SRV"});
    if (attrs == null) {
        return dnsRecords;
    }
    NamingEnumeration<?> servers = attrs.get("SRV").getAll();
    while (servers.hasMore()) {
        DnsRecord record = DnsRecord.fromString((String)servers.next());
        dnsRecords.add(record);
    }
    return dnsRecords;
}
 
Example 32
Project: tempto   File: DefaultLdapObjectEntryManager.java   Source Code and License 6 votes vote down vote up
private DirContext createContext(String ldapUrl, String ldapAdminDistinguishedName, String ldapAdminPassword)
{
    Hashtable<String, String> environment = new Hashtable<>();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, ldapUrl);
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");
    environment.put(Context.SECURITY_PRINCIPAL, ldapAdminDistinguishedName);
    environment.put(Context.SECURITY_CREDENTIALS, ldapAdminPassword);
    try {
        return new InitialDirContext(environment);
    }
    catch (NamingException e) {
        throw new RuntimeException("Connection to LDAP server failed", e);
    }
}
 
Example 33
Project: report-cockpit-birt-web   File: LdapServerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testJndiSun() throws NamingException {
	Hashtable<String, String> contextParams = new Hashtable<>();
	contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389");
	contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP);
	contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP);
	contextParams.put(Context.INITIAL_CONTEXT_FACTORY,
			"com.sun.jndi.ldap.LdapCtxFactory");

	DirContext dirContext = new InitialDirContext(contextParams);

	Attributes attributes = dirContext.getAttributes("",
			new String[] { "namingContexts" });
	Attribute attribute = attributes.get("namingContexts");
	NamingEnumeration<?> all = attribute.getAll();
	while (all.hasMore()) {
		String next = (String) all.next();
		logger.info(next);
	}
}
 
Example 34
Project: msf4j   File: LDAPUserStoreManager.java   Source Code and License 6 votes vote down vote up
private DirContext getInitialContext(String hostname, int port,
                                     String username, String password)
        throws NamingException {

    String providerURL = "ldap://" + hostname + ":" + port;

    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, providerURL);

    if ((username != null) && (!username.equals(""))) {
        props.put(Context.SECURITY_AUTHENTICATION, "simple");
        props.put(Context.SECURITY_PRINCIPAL, username);
        props.put(Context.SECURITY_CREDENTIALS, (password == null) ? "" : password);
    }

    return new InitialDirContext(props);
}
 
Example 35
Project: daq-eclipse   File: LDAPLoginModule.java   Source Code and License 6 votes vote down vote up
protected DirContext open() throws NamingException {
    try {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(INITIAL_CONTEXT_FACTORY));
        if (isLoginPropertySet(CONNECTION_USERNAME)) {
            env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
        }
        if (isLoginPropertySet(CONNECTION_PASSWORD)) {
            env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
        }
        env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
        env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
        env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
        context = new InitialDirContext(env);

    } catch (NamingException e) {
        log.error(e.toString());
        throw e;
    }
    return context;
}
 
Example 36
Project: gerrit   File: Helper.java   Source Code and License 6 votes vote down vote up
private DirContext kerberosOpen(Properties env) throws LoginException, NamingException {
  LoginContext ctx = new LoginContext("KerberosLogin");
  ctx.login();
  Subject subject = ctx.getSubject();
  try {
    return Subject.doAs(
        subject,
        new PrivilegedExceptionAction<DirContext>() {
          @Override
          public DirContext run() throws NamingException {
            return new InitialDirContext(env);
          }
        });
  } catch (PrivilegedActionException e) {
    Throwables.throwIfInstanceOf(e.getException(), NamingException.class);
    Throwables.throwIfInstanceOf(e.getException(), RuntimeException.class);
    LdapRealm.log.warn("Internal error", e.getException());
    return null;
  } finally {
    ctx.logout();
  }
}
 
Example 37
Project: dorset-framework   File: LdapUserServiceTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = UserException.class)
public void testBadUsername() throws NamingException, UserException {
    String userName = "testUsername";
    Properties props = new Properties();
    props.setProperty("userName", userName);

    DirContext ctx = mock(InitialDirContext.class);
    String[] userAttributes = mockUserAttributes();
    LdapUserService lus = new LdapUserService(ctx, userAttributes);

    NamingEnumeration<SearchResult> mockSearchResults = mock(NamingEnumeration.class);

    when(ctx.search(any(String.class), any(String.class), any(SearchControls.class)))
                    .thenReturn(mockSearchResults);

    lus.retrieve(props);
}
 
Example 38
Project: unitime   File: LdapExternalUidLookup.java   Source Code and License 6 votes vote down vote up
public DirContext getDirContext() throws NamingException {
    Hashtable<String,String> env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
    env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
    env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
        env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
    env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
        env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
        System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
        System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
        System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));
	return new InitialDirContext(env);
}
 
Example 39
Project: unitime   File: LdapExternalUidTranslation.java   Source Code and License 6 votes vote down vote up
public DirContext getDirContext() throws NamingException {
    Hashtable<String,String> env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ctxFactory","com.sun.jndi.ldap.LdapCtxFactory"));
    env.put(Context.PROVIDER_URL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider"));
    env.put(Context.REFERRAL, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.referral","ignore"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version")!=null)
        env.put("java.naming.ldap.version", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.version"));
    env.put(Context.SECURITY_AUTHENTICATION, ApplicationProperties.getProperty("tmtbl.authenticate.ldap.security","simple"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory")!=null)
        env.put("java.naming.ldap.factory.socket",ApplicationProperties.getProperty("tmtbl.authenticate.ldap.socketFactory"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore")!=null)
        System.setProperty("javax.net.ssl.keyStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore")!=null)
        System.setProperty("javax.net.ssl.trustStore", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStore").replaceAll("%WEB-INF%", ApplicationProperties.getBasePath()));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.keyStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.keyStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword")!=null)
        System.setProperty("javax.net.ssl.trustStorePassword", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStorePassword"));
    if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType")!=null)
        System.setProperty("javax.net.ssl.trustStoreType", ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ssl.trustStoreType"));  
    return new InitialDirContext(env);
}
 
Example 40
Project: hops   File: LdapAuthenticationHandler.java   Source Code and License 6 votes vote down vote up
private void authenticateWithoutTlsExtension(String userDN, String password)
    throws AuthenticationException {
  Hashtable<String, Object> env = new Hashtable<String, Object>();
  env.put(Context.INITIAL_CONTEXT_FACTORY,
      "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, providerUrl);
  env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
  env.put(Context.SECURITY_PRINCIPAL, userDN);
  env.put(Context.SECURITY_CREDENTIALS, password);

  try {
    // Create initial context
    Context ctx = new InitialDirContext(env);
    ctx.close();
    logger.debug("Authentication successful for {}", userDN);

  } catch (NamingException e) {
    throw new AuthenticationException("Error validating LDAP user", e);
  }
}
 
Example 41
Project: activemq-artemis   File: LegacyLDAPSecuritySettingPluginTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRunning() throws Exception {
   Hashtable<String, String> env = new Hashtable<>();
   env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
   env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
   env.put(Context.SECURITY_AUTHENTICATION, "simple");
   env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
   env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
   DirContext ctx = new InitialDirContext(env);

   HashSet<String> set = new HashSet<>();

   NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

   while (list.hasMore()) {
      NameClassPair ncp = list.next();
      set.add(ncp.getName());
   }

   Assert.assertTrue(set.contains("uid=admin"));
   Assert.assertTrue(set.contains("ou=users"));
   Assert.assertTrue(set.contains("ou=groups"));
   Assert.assertTrue(set.contains("ou=configuration"));
   Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));
}
 
Example 42
Project: activemq-artemis   File: LegacyLDAPSecuritySettingPlugin.java   Source Code and License 6 votes vote down vote up
private DirContext createContext() throws NamingException {
   Hashtable<String, String> env = new Hashtable<>();
   env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
   if (connectionUsername != null && !"".equals(connectionUsername)) {
      env.put(Context.SECURITY_PRINCIPAL, connectionUsername);
   } else {
      throw new NamingException("Empty username is not allowed");
   }
   if (connectionPassword != null && !"".equals(connectionPassword)) {
      env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
   } else {
      throw new NamingException("Empty password is not allowed");
   }
   env.put(Context.SECURITY_PROTOCOL, connectionProtocol);
   env.put(Context.PROVIDER_URL, connectionURL);
   env.put(Context.SECURITY_AUTHENTICATION, authentication);
   return new InitialDirContext(env);
}
 
Example 43
Project: fiap-mba-java-projects   File: CertificadoValidador.java   Source Code and License 6 votes vote down vote up
private static X509CRL downloadCRLFromLDAP(String ldapURL) throws Exception {
	
	Hashtable<String, String> env = new Hashtable<String, String>();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
       env.put(Context.PROVIDER_URL, ldapURL);

       DirContext context = new InitialDirContext(env);
       Attributes attrs = context.getAttributes("");
       Attribute crlAttr = attrs.get("certificateRevocationList;binary");
       byte[] crlValue = (byte[]) crlAttr.get();
       
       if ((crlValue == null) || (crlValue.length == 0)) {
       	
       	throw new CRLException(
       			String.format("Can not download CRL from: %s", ldapURL));
       } else {
       
       	InputStream crlStream = new ByteArrayInputStream(crlValue);
           CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
       	X509CRL crl = (X509CRL) certFactory.generateCRL(crlStream);
       	return crl;
       }
}
 
Example 44
Project: Resilience-Client-Source   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String par0Str)
{
    try
    {
        String var1 = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable var2 = new Hashtable();
        var2.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        var2.put("java.naming.provider.url", "dns:");
        var2.put("com.sun.jndi.dns.timeout.retries", "1");
        InitialDirContext var3 = new InitialDirContext(var2);
        Attributes var4 = var3.getAttributes("_minecraft._tcp." + par0Str, new String[] {"SRV"});
        String[] var5 = var4.get("srv").get().toString().split(" ", 4);
        return new String[] {var5[3], var5[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {par0Str, Integer.toString(25565)};
    }
}
 
Example 45
Project: carbon-identity   File: ApacheLDAPServerTest.java   Source Code and License 6 votes vote down vote up
public void testKdcEnabledTest()
    throws Exception {
    addDummyPartition();

    DirContext ctx = new InitialDirContext(getEnvironmentProperties("secret"));

    // Get password attribute and check whether it is plain text.
    String[] attrIDs = {"userPassword"};

    /*Commenting out the following part because we moved creating user admin entry and group
     *entry to user core*/

    /*Attributes answer = ctx.getAttributes("uid=amilaj,ou=Users,dc=example,dc=com", attrIDs);

    for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
        Attribute attr = (Attribute)ae.next();

        NamingEnumeration e = attr.getAll();
        while (e.hasMore()) {
            String passwd = new String((byte[])e.next());
            assertEquals("iceage", passwd);
        }

    }*/

}
 
Example 46
Project: community-edition-old   File: ChainingUserRegistrySynchronizerTest.java   Source Code and License 6 votes vote down vote up
private LDAPInitialDirContextFactoryImpl getMockedLDAPSearchResult(boolean withEmail) throws NamingException
{
    @SuppressWarnings("unchecked")
    NamingEnumeration<SearchResult> mockedNamingEnumeration = mock(NamingEnumeration.class);
    when(mockedNamingEnumeration.hasMore()).thenReturn(true).thenReturn(false);

    BasicAttributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sAMAccountName", "U1"));
    attributes.put(new BasicAttribute("givenName", "U1"));
    if (withEmail)
    {
        attributes.put(new BasicAttribute("mail", "[email protected]"));
    }
    SearchResult mockedSearchResult = new SearchResult("CN:U1", null, attributes);
    mockedSearchResult.setNameInNamespace("CN:U1");

    when(mockedNamingEnumeration.next()).thenReturn(mockedSearchResult);

    InitialDirContext mockedInitialDirContext = mock(InitialDirContext.class);
    when(mockedInitialDirContext.search(any(String.class), any(String.class), any(SearchControls.class))).thenReturn(mockedNamingEnumeration);

    LDAPInitialDirContextFactoryImpl mockedLdapInitialDirContextFactory = mock(LDAPInitialDirContextFactoryImpl.class);
    when(mockedLdapInitialDirContextFactory.getDefaultIntialDirContext(0)).thenReturn(mockedInitialDirContext);
    return mockedLdapInitialDirContextFactory;
}
 
Example 47
Project: karaku   File: LDAPUtil.java   Source Code and License 6 votes vote down vote up
private DirContext createInitialDirContext() {

		Map<Object, String> env = new HashMap<Object, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, propertiesUtil.get(LDAP_SERVER_KEY) + "/"
				+ propertiesUtil.get(LDAP_DN_KEY));
		env.put(Context.SECURITY_PRINCIPAL, propertiesUtil.get(LDAP_ADMIN_KEY));
		env.put(Context.SECURITY_CREDENTIALS,
				propertiesUtil.get(LDAP_ADMIN_PASS_KEY));

		try {
			return new InitialDirContext(new Hashtable<Object, String>(env));

		} catch (NamingException e) {
			throw new KarakuRuntimeException(e.getMessage(), e);
		}

	}
 
Example 48
Project: karaku   File: LdapStressTest.java   Source Code and License 6 votes vote down vote up
private void getAll(InitialDirContext ctx, String uid) {

			try {
				Attributes matchAttrs = new BasicAttributes(true);
				matchAttrs.put(new BasicAttribute("member", user));

				NamingEnumeration<SearchResult> answer = ctx.search(
						"ou=permissions", matchAttrs, new String[] { "cn" });

				while (answer.hasMore()) {
					SearchResult searchResult = answer.next();
					Attributes attributes = searchResult.getAttributes();
					attributes.get("cn");
				}

			} catch (NamingException e) {
				e.printStackTrace();
			}
		}
 
Example 49
Project: openMAXIMS   File: Ldap.java   Source Code and License 6 votes vote down vote up
public static NamingEnumeration getLast() throws NamingException
{
	Hashtable env = new Hashtable(11);
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.SECURITY_PROTOCOL, "ssl");		
	env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDn);
	
	SearchControls controls = new SearchControls();
	controls.setReturningAttributes(returnAttributes);
	controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	DirContext searchContext = new InitialDirContext(env);
	searchResponse = searchContext.search(context, filter, controls);
				
	while (searchResponse != null && searchResponse.hasMoreElements())
	{
		SearchResult item = (SearchResult) searchResponse.next();
		searchResults = item.getAttributes().getAll();
	}
		
	return searchResults;
}
 
Example 50
Project: RDFS   File: DNS.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.
 * 
 * @param hostIp
 *            The address to reverse lookup
 * @param ns
 *            The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException
 *             If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, String ns)
  throws NamingException {
  //
  // Builds the reverse IP lookup form
  // This is formed by reversing the IP numbers and appending in-addr.arpa
  //
  String[] parts = hostIp.getHostAddress().split("\\.");
  String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
    + parts[0] + ".in-addr.arpa";

  DirContext ictx = new InitialDirContext();
  Attributes attribute =
    ictx.getAttributes("dns://"               // Use "dns:///" if the default
                       + ((ns == null) ? "" : ns) + 
                       // nameserver is to be used
                       "/" + reverseIP, new String[] { "PTR" });
  ictx.close();
  
  return attribute.get("PTR").get().toString();
}
 
Example 51
Project: emfstore-rest   File: LdapImportSource.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes the connection to the LDAP server, using the properties
 * field.
 * 
 * @throws CorruptedSourceException
 *             if no connection could be established to the given server.
 */
public void connect() throws CorruptedSourceException {
	properties.put("java.naming.ldap.version", "3");
	properties.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_CTX);

	// Create the connection to the LDAP-server
	// (Each time an initial context is created, a new LDAP connection is
	// created)
	try {
		dirContext = new InitialDirContext(properties);
	} catch (NamingException e) {
		WorkspaceUtil.logWarning(e.getMessage(), e);
		throw new CorruptedSourceException("Couldn't connect to server!");
	}

}
 
Example 52
Project: syncope   File: AbstractITCase.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" })
protected InitialDirContext getLdapResourceDirContext(final String bindDn, final String bindPwd)
        throws NamingException {
    ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP);
    ConnInstanceTO ldapConn = connectorService.read(ldapRes.getConnector(), Locale.ENGLISH.getLanguage());

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + ldapConn.getConf("host").get().getValues().get(0)
            + ":" + ldapConn.getConf("port").get().getValues().get(0) + "/");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
            bindDn == null ? ldapConn.getConf("principal").get().getValues().get(0) : bindDn);
    env.put(Context.SECURITY_CREDENTIALS,
            bindPwd == null ? ldapConn.getConf("credentials").get().getValues().get(0) : bindPwd);

    return new InitialDirContext(env);
}
 
Example 53
Project: AvunaHTTPD-Java   File: EmailRouter.java   Source Code and License 6 votes vote down vote up
private static String[] lookupMailHosts(String domainName) throws NamingException {
	InitialDirContext iDirC = new InitialDirContext();
	Attributes attributes = iDirC.getAttributes("dns:/" + domainName, new String[] { "MX" });
	Attribute attributeMX = attributes.get("MX");
	if (attributeMX == null) {
		return (new String[] { domainName });
	}
	String[][] pvhn = new String[attributeMX.size()][2];
	for (int i = 0; i < attributeMX.size(); i++) {
		pvhn[i] = ("" + attributeMX.get(i)).split("\\s+");
	}
	Arrays.sort(pvhn, new Comparator<String[]>() {
		public int compare(String[] o1, String[] o2) {
			return (Integer.parseInt(o1[0]) - Integer.parseInt(o2[0]));
		}
	});
	String[] sortedHostNames = new String[pvhn.length];
	for (int i = 0; i < pvhn.length; i++) {
		sortedHostNames[i] = pvhn[i][1].endsWith(".") ? pvhn[i][1].substring(0, pvhn[i][1].length() - 1) : pvhn[i][1];
	}
	return sortedHostNames;
}
 
Example 54
Project: ExpandedRailsMod   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable<String, String> hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 55
Project: cn1   File: LdapContextServerMockedTest.java   Source Code and License 6 votes vote down vote up
public void testConnectControls2() throws Exception {
    // set connect controls by property "java.naming.ldap.control.connect"
    env.put("java.naming.ldap.control.connect",
            new Control[] { new SortControl("", Control.NONCRITICAL) });

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });

    InitialDirContext initialDirContext = new InitialDirContext(env);

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_SEARCH_RESULT_DONE,
            new EncodableLdapResult(), null) });
    LdapContext context = (LdapContext) initialDirContext.lookup("");

    Control[] controls = context.getConnectControls();
    assertNotNull(controls);
    assertEquals(1, controls.length);
    Control c = controls[0];
    assertTrue(c instanceof SortControl);
    assertEquals(Control.NONCRITICAL, c.isCritical());
}
 
Example 56
Project: cn1   File: LdapContextServerMockedTest.java   Source Code and License 6 votes vote down vote up
public void testReferralFollow() throws Exception {
    env.put(Context.REFERRAL, "follow");
    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });
    DirContext context = new InitialDirContext(env);

    MockLdapServer referralServer = new MockLdapServer();
    referralServer.start();

    EncodableLdapResult result = new EncodableLdapResult(
            LdapResult.REFERRAL, "", "", new String[] { referralServer
                    .getURL() });

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_SEARCH_RESULT_DONE, result, null) });

    referralServer.setResponseSeq(new LdapMessage[] {
            new LdapMessage(LdapASN1Constant.OP_BIND_RESPONSE,
                    new BindResponse(), null),
            new LdapMessage(LdapASN1Constant.OP_SEARCH_RESULT_DONE,
                    new EncodableLdapResult(), null) });

    context.getAttributes("cn=test");

    referralServer.stop();
}
 
Example 57
Project: Cauldron   File: RealmsServerAddress.java   Source Code and License 6 votes vote down vote up
private static String[] lookupSrv(String p_lookupSrv_0_)
{
    try
    {
        String s1 = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        InitialDirContext initialdircontext = new InitialDirContext(hashtable);
        Attributes attributes = initialdircontext.getAttributes("_minecraft._tcp." + p_lookupSrv_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable throwable)
    {
        return new String[] {p_lookupSrv_0_, Integer.toString(25565)};
    }
}
 
Example 58
Project: Cauldron   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s1 = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        InitialDirContext initialdircontext = new InitialDirContext(hashtable);
        Attributes attributes = initialdircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable throwable)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 59
Project: Cauldron   File: RealmsServerAddress.java   Source Code and License 6 votes vote down vote up
private static String[] lookupSrv(String p_lookupSrv_0_)
{
    try
    {
        String s1 = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        InitialDirContext initialdircontext = new InitialDirContext(hashtable);
        Attributes attributes = initialdircontext.getAttributes("_minecraft._tcp." + p_lookupSrv_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable throwable)
    {
        return new String[] {p_lookupSrv_0_, Integer.toString(25565)};
    }
}
 
Example 60
Project: Cauldron   File: ServerAddress.java   Source Code and License 6 votes vote down vote up
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s1 = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        InitialDirContext initialdircontext = new InitialDirContext(hashtable);
        Attributes attributes = initialdircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable throwable)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}