Search in sources :

Example 91 with DirContext

use of javax.naming.directory.DirContext in project jmeter by apache.

the class LDAPExtSampler method singleBindOp.

/***************************************************************************
     * This will do the bind and unbind for the User defined TestCase
     *
     **************************************************************************/
private void singleBindOp(SampleResult res) throws NamingException {
    try {
        res.sampleStart();
        DirContext ctx = LdapExtClient.connect(getServername(), getPort(), getRootdn(), getUserDN(), getUserPw(), getConnTimeOut(), isSecure());
        LdapExtClient.disconnect(ctx);
    } finally {
        res.sampleEnd();
    }
}
Also used : DirContext(javax.naming.directory.DirContext)

Example 92 with DirContext

use of javax.naming.directory.DirContext in project jmeter by apache.

the class LDAPExtSampler method sample.

@Override
public SampleResult sample(Entry e) {
    XMLBuffer xmlBuffer = new XMLBuffer();
    // $NON-NLS-1$
    xmlBuffer.openTag("ldapanswer");
    SampleResult res = new SampleResult();
    res.setResponseData("successfull", null);
    // $NON-NLS-1$
    res.setResponseMessage("Success");
    // $NON-NLS-1$
    res.setResponseCode("0");
    // $NON-NLS-1$
    res.setContentType("text/xml");
    boolean isSuccessful = true;
    res.setSampleLabel(getName());
    DirContext dirContext = ldapContexts.get(getThreadName());
    try {
        // $NON-NLS-1$
        xmlBuffer.openTag("operation");
        final String testType = getTest();
        // $NON-NLS-1$
        xmlBuffer.tag("opertype", testType);
        log.debug("performing test: " + testType);
        if (testType.equals(UNBIND)) {
            res.setSamplerData("Unbind");
            // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn());
            // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN());
            unbindOp(dirContext, res);
        } else if (testType.equals(BIND)) {
            res.setSamplerData("Bind as " + getUserDN());
            // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn());
            // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN());
            // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut());
            bindOp(res);
        } else if (testType.equals(SBIND)) {
            res.setSamplerData("SingleBind as " + getUserDN());
            // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn());
            // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN());
            // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut());
            singleBindOp(res);
        } else if (testType.equals(COMPARE)) {
            res.setSamplerData("Compare " + getPropertyAsString(COMPAREFILT) + " " + getPropertyAsString(COMPAREDN));
            // $NON-NLS-1$
            xmlBuffer.tag("comparedn", getPropertyAsString(COMPAREDN));
            // $NON-NLS-1$
            xmlBuffer.tag("comparefilter", getPropertyAsString(COMPAREFILT));
            NamingEnumeration<SearchResult> cmp = null;
            try {
                res.sampleStart();
                cmp = LdapExtClient.compare(dirContext, getPropertyAsString(COMPAREFILT), getPropertyAsString(COMPAREDN));
                if (!cmp.hasMore()) {
                    // $NON-NLS-1$
                    res.setResponseCode("5");
                    res.setResponseMessage("compareFalse");
                    isSuccessful = false;
                }
            } finally {
                res.sampleEnd();
                if (cmp != null) {
                    cmp.close();
                }
            }
        } else if (testType.equals(ADD)) {
            res.setSamplerData("Add object " + getBaseEntryDN());
            // $NON-NLS-1$
            xmlBuffer.tag("attributes", getArguments().toString());
            // $NON-NLS-1$
            xmlBuffer.tag("dn", getBaseEntryDN());
            addTest(dirContext, res);
        } else if (testType.equals(DELETE)) {
            res.setSamplerData("Delete object " + getBaseEntryDN());
            // $NON-NLS-1$
            xmlBuffer.tag("dn", getBaseEntryDN());
            deleteTest(dirContext, res);
        } else if (testType.equals(MODIFY)) {
            res.setSamplerData("Modify object " + getBaseEntryDN());
            // $NON-NLS-1$
            xmlBuffer.tag("dn", getBaseEntryDN());
            // $NON-NLS-1$
            xmlBuffer.tag("attributes", getLDAPArguments().toString());
            modifyTest(dirContext, res);
        } else if (testType.equals(RENAME)) {
            res.setSamplerData("ModDN object " + getPropertyAsString(MODDDN) + " to " + getPropertyAsString(NEWDN));
            // $NON-NLS-1$
            xmlBuffer.tag("dn", getPropertyAsString(MODDDN));
            // $NON-NLS-1$
            xmlBuffer.tag("newdn", getPropertyAsString(NEWDN));
            renameTest(dirContext, res);
        } else if (testType.equals(SEARCH)) {
            final String scopeStr = getScope();
            final int scope = getScopeAsInt();
            final String searchFilter = getPropertyAsString(SEARCHFILTER);
            final String searchBase = getPropertyAsString(SEARCHBASE);
            final String timeLimit = getTimelim();
            final String countLimit = getCountlim();
            res.setSamplerData("Search with filter " + searchFilter);
            // $NON-NLS-1$
            xmlBuffer.tag("searchfilter", StringEscapeUtils.escapeXml10(searchFilter));
            // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn());
            // $NON-NLS-1$
            xmlBuffer.tag("searchbase", searchBase);
            // $NON-NLS-1$
            xmlBuffer.tag("scope", scopeStr);
            // $NON-NLS-1$
            xmlBuffer.tag("countlimit", countLimit);
            // $NON-NLS-1$
            xmlBuffer.tag("timelimit", timeLimit);
            NamingEnumeration<SearchResult> srch = null;
            try {
                res.sampleStart();
                srch = LdapExtClient.searchTest(dirContext, searchBase, searchFilter, scope, getCountlimAsLong(), getTimelimAsInt(), getRequestAttributes(getAttrs()), isRetobj(), isDeref());
                if (isParseFlag()) {
                    try {
                        // $NON-NLS-1$
                        xmlBuffer.openTag("searchresults");
                        writeSearchResults(xmlBuffer, srch);
                    } finally {
                        // $NON-NLS-1$
                        xmlBuffer.closeTag("searchresults");
                    }
                } else {
                    // $NON-NLS-1$
                    xmlBuffer.tag(// $NON-NLS-1$
                    "searchresults", // $NON-NLS-1$
                    "hasElements=" + srch.hasMoreElements());
                }
            } finally {
                if (srch != null) {
                    srch.close();
                }
                res.sampleEnd();
            }
        }
    } catch (NamingException ex) {
        // TODO: tidy this up
        String returnData = ex.toString();
        final int indexOfLDAPErrCode = returnData.indexOf("LDAP: error code");
        if (indexOfLDAPErrCode >= 0) {
            res.setResponseMessage(returnData.substring(indexOfLDAPErrCode + 21, returnData.indexOf(// $NON-NLS-1$
            ']')));
            res.setResponseCode(returnData.substring(indexOfLDAPErrCode + 17, indexOfLDAPErrCode + 19));
        } else {
            res.setResponseMessage(returnData);
            // $NON-NLS-1$
            res.setResponseCode("800");
        }
        isSuccessful = false;
    } finally {
        // $NON-NLS-1$
        xmlBuffer.closeTag("operation");
        // $NON-NLS-1$
        xmlBuffer.tag("responsecode", res.getResponseCode());
        // $NON-NLS-1$
        xmlBuffer.tag("responsemessage", res.getResponseMessage());
        res.setResponseData(xmlBuffer.toString(), null);
        res.setDataType(SampleResult.TEXT);
        res.setSuccessful(isSuccessful);
    }
    return res;
}
Also used : SampleResult(org.apache.jmeter.samplers.SampleResult) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) XMLBuffer(org.apache.jorphan.util.XMLBuffer)

Example 93 with DirContext

use of javax.naming.directory.DirContext in project karaf by apache.

the class LdapCacheTest method testAdminLogin.

@Test
public void testAdminLogin() throws Exception {
    Properties options = ldapLoginModuleOptions();
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new NamePasswordCallbackHandler("admin", "admin123");
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);
    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());
    assertEquals(2, subject.getPrincipals().size());
    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof UserPrincipal) {
            assertEquals("admin", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    assertTrue(foundRole);
    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
    DirContext context = new LDAPCache(new LDAPOptions(options)).open();
    // Make "admin" user a member of a new "another" group
    //        dn: cn=admin,ou=groups,dc=example,dc=com
    //        objectClass: top
    //        objectClass: groupOfNames
    //        cn: admin
    //        member: cn=admin,ou=people,dc=example,dc=com
    Attributes entry = new BasicAttributes();
    entry.put(new BasicAttribute("cn", "another"));
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("groupOfNames");
    entry.put(oc);
    Attribute mb = new BasicAttribute("member");
    mb.add("cn=admin,ou=people,dc=example,dc=com");
    entry.put(mb);
    context.createSubcontext("cn=another,ou=groups,dc=example,dc=com", entry);
    Thread.sleep(100);
    module = new LDAPLoginModule();
    subject = new Subject();
    module.initialize(subject, cb, null, options);
    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());
    assertEquals("Postcondition", 3, subject.getPrincipals().size());
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) BasicAttributes(javax.naming.directory.BasicAttributes) NamePasswordCallbackHandler(org.apache.karaf.jaas.modules.NamePasswordCallbackHandler) CallbackHandler(javax.security.auth.callback.CallbackHandler) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) DirContext(javax.naming.directory.DirContext) Properties(org.apache.felix.utils.properties.Properties) Subject(javax.security.auth.Subject) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) NamePasswordCallbackHandler(org.apache.karaf.jaas.modules.NamePasswordCallbackHandler) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal) Test(org.junit.Test)

Example 94 with DirContext

use of javax.naming.directory.DirContext in project nhin-d by DirectProject.

the class LdapCertUtilImpl method ldapSearch.

public Collection<X509Certificate> ldapSearch(String subjectName) {
    DirContext ctx = null;
    try {
        ctx = getInitialDirContext(ldapEnvironment.getEnv());
        final SearchControls ctls = getDefaultSearchControls();
        NamingEnumeration<SearchResult> searchResult = ctx.search(ldapEnvironment.getLdapSearchBase(), ldapEnvironment.getLdapSearchAttribute() + "=" + subjectName, ctls);
        ArrayList<X509Certificate> certificates = new ArrayList<X509Certificate>();
        while (searchResult != null && searchResult.hasMoreElements()) {
            final SearchResult certEntry = searchResult.nextElement();
            if (certEntry != null) {
                final Attributes certAttributes = certEntry.getAttributes();
                if (certAttributes != null) {
                    // get only the returning cert attribute (for now, ignore all other attributes)
                    final Attribute certAttribute = certAttributes.get(ldapEnvironment.getReturningCertAttribute());
                    if (certAttribute != null) {
                        NamingEnumeration<? extends Object> allValues = certAttribute.getAll();
                        // LDAP may contain a collection of certificates.
                        while (allValues.hasMoreElements()) {
                            String ksBytes = (String) allValues.nextElement();
                            Base64 base64 = new Base64();
                            byte[] decode = base64.decode(ksBytes.getBytes());
                            ByteArrayInputStream inputStream = new ByteArrayInputStream(decode);
                            if (certificateFormat.equalsIgnoreCase("pkcs12")) {
                                try {
                                    processPKCS12FileFormatAndAddToCertificates(inputStream, certificates);
                                } catch (Exception e) {
                                    closeDirContext(ctx);
                                    throw new NHINDException("", e);
                                }
                            } else {
                                if (certificateFormat.equalsIgnoreCase("X.509") || certificateFormat.equalsIgnoreCase("X509")) {
                                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                                    X509Certificate addCert = (X509Certificate) cf.generateCertificate(inputStream);
                                    certificates.add(addCert);
                                } else {
                                    closeDirContext(ctx);
                                    throw new NHINDException("Invalid certificate format requested");
                                }
                            }
                        }
                    }
                }
            }
        }
        return certificates;
    } catch (NamingException e) {
        closeDirContext(ctx);
        throw new NHINDException("", e);
    } catch (CertificateException e) {
        closeDirContext(ctx);
        throw new NHINDException("", e);
    }
}
Also used : Base64(org.apache.commons.codec.binary.Base64) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) CertificateException(java.security.cert.CertificateException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) NHINDException(org.nhindirect.stagent.NHINDException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) NamingException(javax.naming.NamingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NHINDException(org.nhindirect.stagent.NHINDException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayInputStream(java.io.ByteArrayInputStream) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException)

Example 95 with DirContext

use of javax.naming.directory.DirContext in project fess by codelibs.

the class LdapManager method validate.

protected boolean validate() {
    if (!isBind) {
        final Hashtable<String, String> env = createAdminEnv();
        try (DirContextHolder holder = getDirContext(() -> env)) {
            final DirContext context = holder.get();
            if (logger.isDebugEnabled()) {
                logger.debug("Logged in as Bind DN.", context);
            }
            isBind = true;
        } catch (final Exception e) {
            logger.warn("LDAP configuration is wrong.", e);
        }
    }
    return isBind;
}
Also used : InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) NamingException(javax.naming.NamingException) LdapOperationException(org.codelibs.fess.exception.LdapOperationException)

Aggregations

DirContext (javax.naming.directory.DirContext)111 NamingException (javax.naming.NamingException)51 InitialDirContext (javax.naming.directory.InitialDirContext)43 SearchResult (javax.naming.directory.SearchResult)27 SearchControls (javax.naming.directory.SearchControls)24 Attributes (javax.naming.directory.Attributes)21 Attribute (javax.naming.directory.Attribute)17 IOException (java.io.IOException)16 NamingEnumeration (javax.naming.NamingEnumeration)16 Hashtable (java.util.Hashtable)14 Test (org.junit.Test)14 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 ProxyDirContext (org.apache.naming.resources.ProxyDirContext)10 WebDirContext (org.apache.naming.resources.WebDirContext)9 ArrayList (java.util.ArrayList)8 BaseDirContext (org.apache.naming.resources.BaseDirContext)8 FileDirContext (org.apache.naming.resources.FileDirContext)8 WARDirContext (org.apache.naming.resources.WARDirContext)8 Name (javax.naming.Name)7 BasicAttribute (javax.naming.directory.BasicAttribute)7