From f6231e56a0e42f5ba4786366726adf19377c6c6a Mon Sep 17 00:00:00 2001 From: mlbiam Date: Mon, 28 Jan 2019 09:25:20 -0500 Subject: [PATCH 1/5] for #51 updated libraries --- pom.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 05e34be..fd9c486 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ net.sourceforge.myvd myvd-server - 1.0.4 + 1.0.5 jar server @@ -136,7 +136,7 @@ net.sf.ehcache ehcache - 2.10.4 + 2.10.6 @@ -160,17 +160,17 @@ org.apache.logging.log4j log4j-api - 2.11.0 + 2.11.1 org.apache.logging.log4j log4j-core - 2.11.0 + 2.11.1 org.apache.logging.log4j log4j-1.2-api - 2.11.0 + 2.11.1 @@ -231,7 +231,7 @@ joda-time joda-time - 2.10 + 2.10.1 dnsjava From c80cc7e6e3ebdd60187329c85294957bf6fa8b68 Mon Sep 17 00:00:00 2001 From: mlbiam Date: Mon, 28 Jan 2019 09:55:55 -0500 Subject: [PATCH 2/5] for #51 updated version and build --- CHANGELOG.md | 5 +++++ src/main/java/net/sourceforge/myvd/server/Server.java | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 106ac13..f16a75e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 1.0.5 + +**tasks:** + - 1.0.5 Release [\#51](https://github.com/TremoloSecurity/MyVirtualDirectory/issues/51) + # 1.0.4 **enhancements:** diff --git a/src/main/java/net/sourceforge/myvd/server/Server.java b/src/main/java/net/sourceforge/myvd/server/Server.java index 36a51c2..3788e8f 100644 --- a/src/main/java/net/sourceforge/myvd/server/Server.java +++ b/src/main/java/net/sourceforge/myvd/server/Server.java @@ -86,7 +86,7 @@ public class Server { static Logger logger; - public final static String VERSION = "1.0.4"; + public final static String VERSION = "1.0.5"; String configFile; Properties props; From 02e46bb4a3be661d08c9c67f7870d8a6f05fee55 Mon Sep 17 00:00:00 2001 From: Tomas Tulka Date: Fri, 1 Feb 2019 14:56:13 +0100 Subject: [PATCH 3/5] Security and convenience enhancements (#44) * listerner host property * intellij files removed * required authorization parameter added * default value for server.globalChain property * trim of custom properties * doc added * dn=root general base added * property server.rootBase added * rootBase used when the search base is empty * root base in getLevel * debug added * env vars needed for testing * new env vars * debug as a parameter * bind auth required test added * host test added * host test added * root base test added * finally - close added * server folder back to the repo * test env var removed * plugin back * server.rootBase removed * disabling anonymous bind: tests for invalid credentials added * check 49 error code --- .gitignore | 2 + doc/myvd.asc | 36 +- myvd-server.iml | 50 - .../myvd/chain/jdbcLdapImpl/Delete.java | 206 +-- .../myvd/chain/jdbcLdapImpl/Insert.java | 276 ++-- .../chain/jdbcLdapImpl/RetrieveResults.java | 420 +++--- .../myvd/chain/jdbcLdapImpl/Update.java | 228 ++-- .../myvd/chain/jdbcLdapImpl/UpdateEntry.java | 320 ++--- .../sourceforge/myvd/inserts/RootObject.java | 0 .../inserts/kerberos/KerberosInterceptor.java | 0 .../myvd/inserts/ldap/LDAPSocketFactory.java | 0 .../myvd/test/router/SearchFromRoot.java | 0 .../myvd/inserts/ldap/LDAPInterceptor.java | 1131 ++++++++--------- .../net/sourceforge/myvd/router/Router.java | 348 +++-- .../net/sourceforge/myvd/server/Server.java | 813 ++++++------ .../sourceforge/myvd/server/ServerCore.java | 278 ++-- .../myvd/test/util/StartOpenLDAP.java | 8 +- .../directory/server/ldap/LdapServer.java | 51 +- .../handlers/request/BindRequestHandler.java | 414 +++--- .../Server/TestStartServerAuthRequired.java | 157 +++ .../myvd/test/Server/TestStartServerHost.java | 109 ++ test/TestServer/testconfig-host.props | 27 + .../TestServer/testconfig-required-auth.props | 27 + 23 files changed, 2471 insertions(+), 2430 deletions(-) delete mode 100644 myvd-server.iml mode change 100755 => 100644 server/src/main/java/net/sourceforge/myvd/inserts/RootObject.java mode change 100755 => 100644 server/src/main/java/net/sourceforge/myvd/inserts/kerberos/KerberosInterceptor.java mode change 100755 => 100644 server/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPSocketFactory.java mode change 100755 => 100644 server/src/test/java/net/sourceforge/myvd/test/router/SearchFromRoot.java create mode 100644 src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java create mode 100644 src/test/java/net/sourceforge/myvd/test/Server/TestStartServerHost.java create mode 100644 test/TestServer/testconfig-host.props create mode 100644 test/TestServer/testconfig-required-auth.props diff --git a/.gitignore b/.gitignore index 0ee403d..2912d4e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ /build/ /bin/ target/ +.idea +*.iml # OS Files # .DS_Store diff --git a/doc/myvd.asc b/doc/myvd.asc index ba1259e..45ba3c2 100644 --- a/doc/myvd.asc +++ b/doc/myvd.asc @@ -263,10 +263,15 @@ port or both. To configure a non secure port simply supply a port number. In addition to the port number, you can specify a maximum number of entries or a maximum time limit (in milli-seconds). If not configured, the default is unlimited. +The listener can be limited only on a particular host (default is `0.0.0.0`). +If authentication is required the simple authentication credential are +needed to bind the listener (default `false`). .... #Listen on port 389 +server.listener.host=localhost server.listener.port=389 +server.listener.authRequired=true server.listener.maxSizeLimit=1000 server.listener.maxTimeLimit=60000 .... @@ -347,7 +352,9 @@ flow of data through the system. Namespaces are separated by LDAP DNs. Like the global namespace, local namespaces contain chains of inserts. Unlike the global namespaces, local namespaces are separated by an LDAP DN and a weight to determine which namespace takes priority when there -is a conflict. To configure local namespaces: +is a conflict. + +To configure local namespaces: .... #First, list all the namespaces @@ -422,6 +429,33 @@ inserts. is because the routing insert in the global plugin explictly sets the namespace to be used. +.... +#List all the namespaces +server.namespaces=ns1,ns2 + +#Configure the ns1 namespace +server.ns1.chain=insert1 +server.ns1.nameSpace=ou=People,dc=mycomp1,dc=com +server.ns1.weight=100 +server.ns1.enabled=true + +#Configure insert1 +server.ns1.insert1.className=com.package.class1 +server.ns1.insert1.config.option1=value1 +server.ns1.insert1.config.option2=value2 + +#Configure the ns2 namespace +server.ns2.chain=insert2 +server.ns2.nameSpace=ou=Users,dc=mycomp2,dc=org +server.ns2.weight=100 +server.ns2.enabled=true + +#Configure insert2 +server.ns1.insert2.className=com.package.class2 +server.ns1.insert2.config.option1=value1 +server.ns1.insert2.config.option2=value2 +.... + [[complete-config]] Complete Config ^^^^^^^^^^^^^^^ diff --git a/myvd-server.iml b/myvd-server.iml deleted file mode 100644 index d8a3663..0000000 --- a/myvd-server.iml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Delete.java b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Delete.java index 79f9658..3afce51 100644 --- a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Delete.java +++ b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Delete.java @@ -1,103 +1,103 @@ -/* ************************************************************************** - * - * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. - * - * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND - * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT - * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS - * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" - * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION - * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP - * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., - * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. - ******************************************************************************/ - -/* - * Delete.java - * - * Created on March 13, 2002, 5:50 PM - */ - -package net.sourceforge.myvd.chain.jdbcLdapImpl; - - -import com.octetstring.jdbcLdap.backend.DirectoryDelete; -import com.octetstring.jdbcLdap.backend.DirectoryRetrieveResults; -import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; -import com.octetstring.jdbcLdap.jndi.SQLNamingException; -import com.octetstring.jdbcLdap.sql.statements.*; -import com.octetstring.jdbcLdap.sql.*; - -import java.sql.*; - -import net.sourceforge.myvd.chain.DeleteInterceptorChain; -import net.sourceforge.myvd.chain.InterceptorChain; -import net.sourceforge.myvd.types.DistinguishedName; - -import com.novell.ldap.*; -/** - *Deletes an entry - *@author Marc Boorshtein, OctetString - */ -public class Delete implements DirectoryDelete, ChainedImpl { - - InterceptorChain chain; - - - public int doDeleteJldap(JdbcLdapDelete del) throws SQLException { - DirectoryRetrieveResults res = (DirectoryRetrieveResults) del.getCon().getImplClasses().get(JndiLdapConnection.IMPL_RETRIEVE_RESULTS); - - - StringBuffer buf = new StringBuffer(); - SqlStore store = del.getSqlStore(); - int count = 0; - ////System.out.println("from : " + store.getFrom()); - if (store.getSimple()) { - try { - - DeleteInterceptorChain delChain = this.chain.createDeleteChain(); - delChain.nextDelete(new DistinguishedName(JndiLdapConnection.getRealBase(del)),new LDAPConstraints()); - } - catch (LDAPException ne) { - throw new SQLNamingException(ne); - } - - return 1; - } - else { - try { - - LDAPSearchResults enumer = res.searchUpInsJldap(del); - while (enumer.hasMore()) { - LDAPEntry entry = enumer.next(); - DeleteInterceptorChain delChain = this.chain.createDeleteChain(); - delChain.nextDelete(new DistinguishedName(entry.getDN()),new LDAPConstraints()); - count++; - } - - - - return count; - } - catch (LDAPException ne) { - throw new SQLNamingException(ne); - } - } - } - - - /* (non-Javadoc) - * @see net.sourceforge.myvd.chain.jdbcLdapImpl.ChainedImpl#getChain() - */ - public InterceptorChain getChain() { - return chain; - } - - - /* (non-Javadoc) - * @see net.sourceforge.myvd.chain.jdbcLdapImpl.ChainedImpl#setChain(net.sourceforge.myvd.chain.InterceptorChain) - */ - public void setChain(InterceptorChain chain) { - this.chain = chain; - } -} +/* ************************************************************************** + * + * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. + * + * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND + * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT + * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS + * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" + * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION + * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP + * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., + * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. + ******************************************************************************/ + +/* + * Delete.java + * + * Created on March 13, 2002, 5:50 PM + */ + +package net.sourceforge.myvd.chain.jdbcLdapImpl; + + +import com.octetstring.jdbcLdap.backend.DirectoryDelete; +import com.octetstring.jdbcLdap.backend.DirectoryRetrieveResults; +import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; +import com.octetstring.jdbcLdap.jndi.SQLNamingException; +import com.octetstring.jdbcLdap.sql.statements.*; +import com.octetstring.jdbcLdap.sql.*; + +import java.sql.*; + +import net.sourceforge.myvd.chain.DeleteInterceptorChain; +import net.sourceforge.myvd.chain.InterceptorChain; +import net.sourceforge.myvd.types.DistinguishedName; + +import com.novell.ldap.*; +/** + *Deletes an entry + *@author Marc Boorshtein, OctetString + */ +public class Delete implements DirectoryDelete, ChainedImpl { + + InterceptorChain chain; + + + public int doDeleteJldap(JdbcLdapDelete del) throws SQLException { + DirectoryRetrieveResults res = (DirectoryRetrieveResults) del.getCon().getImplClasses().get(JndiLdapConnection.IMPL_RETRIEVE_RESULTS); + + + StringBuffer buf = new StringBuffer(); + SqlStore store = del.getSqlStore(); + int count = 0; + ////System.out.println("from : " + store.getFrom()); + if (store.getSimple()) { + try { + + DeleteInterceptorChain delChain = this.chain.createDeleteChain(); + delChain.nextDelete(new DistinguishedName(JndiLdapConnection.getRealBase(del)),new LDAPConstraints()); + } + catch (LDAPException ne) { + throw new SQLNamingException(ne); + } + + return 1; + } + else { + try { + + LDAPSearchResults enumer = res.searchUpInsJldap(del); + while (enumer.hasMore()) { + LDAPEntry entry = enumer.next(); + DeleteInterceptorChain delChain = this.chain.createDeleteChain(); + delChain.nextDelete(new DistinguishedName(entry.getDN()),new LDAPConstraints()); + count++; + } + + + + return count; + } + catch (LDAPException ne) { + throw new SQLNamingException(ne); + } + } + } + + + /* (non-Javadoc) + * @see net.sourceforge.myvd.chain.jdbcLdapImpl.ChainedImpl#getChain() + */ + public InterceptorChain getChain() { + return chain; + } + + + /* (non-Javadoc) + * @see net.sourceforge.myvd.chain.jdbcLdapImpl.ChainedImpl#setChain(net.sourceforge.myvd.chain.InterceptorChain) + */ + public void setChain(InterceptorChain chain) { + this.chain = chain; + } +} diff --git a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Insert.java b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Insert.java index f20458a..7df66fd 100644 --- a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Insert.java +++ b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Insert.java @@ -1,138 +1,138 @@ -/* ************************************************************************** - * - * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. - * - * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND - * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT - * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS - * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" - * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION - * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP - * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., - * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. - ******************************************************************************/ - -/* - * Insert.java - * - * Created on March 13, 2002, 5:50 PM - */ - -package net.sourceforge.myvd.chain.jdbcLdapImpl; - -import javax.naming.*; -import java.util.*; -import javax.naming.directory.*; - -import net.sourceforge.myvd.chain.AddInterceptorChain; -import net.sourceforge.myvd.chain.InterceptorChain; -import net.sourceforge.myvd.types.*; - -import com.novell.ldap.*; -import com.octetstring.jdbcLdap.backend.DirectoryInsert; -import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; -import com.octetstring.jdbcLdap.jndi.SQLNamingException; -import com.octetstring.jdbcLdap.sql.statements.JdbcLdapInsert; -import com.octetstring.jdbcLdap.sql.*; -import java.sql.*; -import com.octetstring.jdbcLdap.util.*; -/** - *Inserts a new entry - *@author Marc Boorshtein, OctetString - */ -public class Insert implements ChainedImpl,DirectoryInsert { - InterceptorChain chain; - - /** - *Performs an insert based on an insert statement - */ - - public void doInsert(JdbcLdapInsert insert) throws SQLException { - - } - - /* (non-Javadoc) - * @see com.octetstring.jdbcLdap.jndi.DirectoryInsert#doInsertJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapInsert) - */ - public void doInsertJldap(JdbcLdapInsert insert) throws SQLException { - - Attributes atts = new BasicAttributes(); - SqlStore store = insert.getSqlStore(); - String[] fields = store.getFields(); - String[] vals = insert.getVals(); - LinkedList fieldsMap = store.getFieldsMap(); - Iterator it; - String field; - Pair p; - - - - LDAPEntry entry; - LDAPAttributeSet attribs = new LDAPAttributeSet(); - - LDAPAttribute attrib; - //take all attributes and add it to addition list - try { - it = fieldsMap.iterator(); - Set dontAdd = insert.getSqlStore().getDontAdd(); - - boolean usedOC = false; - - while (it.hasNext()) { - - p = (Pair) it.next(); - - - - if (dontAdd != null && dontAdd.contains(p.getNameUpperCase())) { - //this is an attribute that wont be added, most likely because - - continue; - } - - - - field = p.getName(); - - if (field.equalsIgnoreCase("objectClass")) { - usedOC = true; - } - - attrib = attribs.getAttribute(field); - - if (attrib == null) { - attrib = new LDAPAttribute(field); - attribs.add(attrib); - } - - - attrib.addValue(p.getValue()); - } - - if (! usedOC && insert.getSqlStore().getDefOC() != null) { - attrib = new LDAPAttribute("objectClass"); - attrib.addValue(insert.getSqlStore().getDefOC()); - attribs.add(attrib); - } - - - - AddInterceptorChain addChain = this.chain.createAddChain(); - addChain.nextAdd(new Entry(new LDAPEntry(JndiLdapConnection.getRealBase(insert),attribs)),new LDAPConstraints()); - - - - } - catch (LDAPException ne) { - throw new SQLNamingException(ne); - } - } - - public InterceptorChain getChain() { - return chain; - } - - public void setChain(InterceptorChain chain) { - this.chain = chain; - } -} +/* ************************************************************************** + * + * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. + * + * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND + * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT + * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS + * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" + * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION + * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP + * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., + * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. + ******************************************************************************/ + +/* + * Insert.java + * + * Created on March 13, 2002, 5:50 PM + */ + +package net.sourceforge.myvd.chain.jdbcLdapImpl; + +import javax.naming.*; +import java.util.*; +import javax.naming.directory.*; + +import net.sourceforge.myvd.chain.AddInterceptorChain; +import net.sourceforge.myvd.chain.InterceptorChain; +import net.sourceforge.myvd.types.*; + +import com.novell.ldap.*; +import com.octetstring.jdbcLdap.backend.DirectoryInsert; +import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; +import com.octetstring.jdbcLdap.jndi.SQLNamingException; +import com.octetstring.jdbcLdap.sql.statements.JdbcLdapInsert; +import com.octetstring.jdbcLdap.sql.*; +import java.sql.*; +import com.octetstring.jdbcLdap.util.*; +/** + *Inserts a new entry + *@author Marc Boorshtein, OctetString + */ +public class Insert implements ChainedImpl,DirectoryInsert { + InterceptorChain chain; + + /** + *Performs an insert based on an insert statement + */ + + public void doInsert(JdbcLdapInsert insert) throws SQLException { + + } + + /* (non-Javadoc) + * @see com.octetstring.jdbcLdap.jndi.DirectoryInsert#doInsertJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapInsert) + */ + public void doInsertJldap(JdbcLdapInsert insert) throws SQLException { + + Attributes atts = new BasicAttributes(); + SqlStore store = insert.getSqlStore(); + String[] fields = store.getFields(); + String[] vals = insert.getVals(); + LinkedList fieldsMap = store.getFieldsMap(); + Iterator it; + String field; + Pair p; + + + + LDAPEntry entry; + LDAPAttributeSet attribs = new LDAPAttributeSet(); + + LDAPAttribute attrib; + //take all attributes and add it to addition list + try { + it = fieldsMap.iterator(); + Set dontAdd = insert.getSqlStore().getDontAdd(); + + boolean usedOC = false; + + while (it.hasNext()) { + + p = (Pair) it.next(); + + + + if (dontAdd != null && dontAdd.contains(p.getNameUpperCase())) { + //this is an attribute that wont be added, most likely because + + continue; + } + + + + field = p.getName(); + + if (field.equalsIgnoreCase("objectClass")) { + usedOC = true; + } + + attrib = attribs.getAttribute(field); + + if (attrib == null) { + attrib = new LDAPAttribute(field); + attribs.add(attrib); + } + + + attrib.addValue(p.getValue()); + } + + if (! usedOC && insert.getSqlStore().getDefOC() != null) { + attrib = new LDAPAttribute("objectClass"); + attrib.addValue(insert.getSqlStore().getDefOC()); + attribs.add(attrib); + } + + + + AddInterceptorChain addChain = this.chain.createAddChain(); + addChain.nextAdd(new Entry(new LDAPEntry(JndiLdapConnection.getRealBase(insert),attribs)),new LDAPConstraints()); + + + + } + catch (LDAPException ne) { + throw new SQLNamingException(ne); + } + } + + public InterceptorChain getChain() { + return chain; + } + + public void setChain(InterceptorChain chain) { + this.chain = chain; + } +} diff --git a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/RetrieveResults.java b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/RetrieveResults.java index 609d44a..dba3b6b 100644 --- a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/RetrieveResults.java +++ b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/RetrieveResults.java @@ -1,210 +1,210 @@ -/* ************************************************************************** - * - * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. - * - * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND - * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT - * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS - * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" - * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION - * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP - * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., - * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. - ******************************************************************************/ - -/* - * RetrieveResults.java - * - * Created on March 13, 2002, 5:50 PM - */ - -package net.sourceforge.myvd.chain.jdbcLdapImpl; - - -import com.octetstring.jdbcLdap.backend.DirectoryRetrieveResults; -import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; -import com.octetstring.jdbcLdap.jndi.SQLNamingException; -import com.octetstring.jdbcLdap.sql.statements.*; - -import java.sql.*; -import java.util.*; - -import net.sourceforge.myvd.chain.InterceptorChain; -import net.sourceforge.myvd.chain.SearchInterceptorChain; -import net.sourceforge.myvd.types.Attribute; -import net.sourceforge.myvd.types.Bool; -import net.sourceforge.myvd.types.DistinguishedName; -import net.sourceforge.myvd.types.Filter; -import net.sourceforge.myvd.types.Int; -import net.sourceforge.myvd.types.Results; - -import com.novell.ldap.*; -import com.novell.ldap.controls.LDAPSortControl; -import com.novell.ldap.controls.LDAPSortKey; -/** - *Retrieves the results from a qeury - *@author Marc Boorshtein, OctetString - */ -public class RetrieveResults implements ChainedImpl,DirectoryRetrieveResults { - - public InterceptorChain chain; - - /** Creates new RetrieveResults */ - public RetrieveResults() { - } - - /* (non-Javadoc) - * @see com.octetstring.jdbcLdap.jndi.DirectoryRetrieveResults#searchJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapSelect) - */ - public Object searchJldap(JdbcLdapSelect select) throws SQLException { - try { - - String[] fields = select.getSearchAttributes(); - fields = fields != null ? fields : new String[0]; - - - ArrayList searchAttribs = new ArrayList(); - - if (fields.length == 1 && fields[0].equalsIgnoreCase("dn")) { - searchAttribs.add(new Attribute("1.1")); - - } - else { - for (int i=0,m=fields.length;i= 0) { - constraints = new LDAPSearchConstraints(); - constraints.setMaxResults(select.getJDBCConnection().getMaxSizeLimit()); - } - - if (select.getJDBCConnection().getMaxTimeLimit() >= 0) { - if (constraints == null) { - constraints = new LDAPSearchConstraints(); - } - - constraints.setTimeLimit(select.getJDBCConnection().getMaxTimeLimit()); - } - - - - LDAPSortKey[] keys = null; - - if (select.getSqlStore().getOrderby() != null) { - keys = new LDAPSortKey[select.getSqlStore().getOrderby().length]; - for (int i=0,m=keys.length;i attribs; - searchChain.nextSearch(new DistinguishedName(useBase),new Int(select.getSearchScope()),new Filter(filter),searchAttribs,new Bool(false),res,constraints); - - return new EntrySetSearchResults(res); - - } catch (LDAPException e) { - throw new SQLNamingException(e); - } - - } - - - - - /* (non-Javadoc) - * @see com.octetstring.jdbcLdap.jndi.DirectoryRetrieveResults#searchUpInsJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapSqlAbs) - */ - public LDAPSearchResults searchUpInsJldap(JdbcLdapSqlAbs sql) throws SQLException { - try { - LDAPConnection con = sql.getConnection(); - - - String useBase = JndiLdapConnection.getRealBase(sql); - - String filter = sql.getFilterWithParams(); - - LDAPSearchConstraints constraints = null; - - if (sql.getJDBCConnection().getMaxSizeLimit() >= 0) { - constraints = new LDAPSearchConstraints(); - constraints.setMaxResults(sql.getJDBCConnection().getMaxSizeLimit()); - } - - if (sql.getJDBCConnection().getMaxTimeLimit() >= 0) { - if (constraints == null) { - constraints = con.getSearchConstraints(); - } - - constraints.setTimeLimit(sql.getJDBCConnection().getMaxTimeLimit()); - } - -// //System.out.println("sql.getBaseContext() " + sql.getBaseContext()); -// //System.out.println("where : " + filter); -// //System.out.println("scope : " + sql.getSearchScope()); - - Results res = new Results(this.getChain().getInterceptors(),this.chain.getPos()); - SearchInterceptorChain searchChain = this.chain.createSearchChain(); - - ArrayList searchAttribs = new ArrayList(); - searchAttribs.add(new Attribute("1.1")); - - searchChain.nextSearch(new DistinguishedName(useBase),new Int(sql.getSearchScope()),new Filter(filter),searchAttribs,new Bool(false),res,constraints); - - - return new EntrySetSearchResults(res); - } - catch (LDAPException e) { - throw new SQLNamingException(e); - } - } - - private String getFieldName(String name,HashMap revMap) { - - if (revMap != null) { - String nname = (String) revMap.get(name); - if (nname != null) { - return nname; - } - } - - return name; - } - - public InterceptorChain getChain() { - return chain; - } - - public void setChain(InterceptorChain chain) { - this.chain = chain; - } - -} +/* ************************************************************************** + * + * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. + * + * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND + * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT + * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS + * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" + * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION + * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP + * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., + * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. + ******************************************************************************/ + +/* + * RetrieveResults.java + * + * Created on March 13, 2002, 5:50 PM + */ + +package net.sourceforge.myvd.chain.jdbcLdapImpl; + + +import com.octetstring.jdbcLdap.backend.DirectoryRetrieveResults; +import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; +import com.octetstring.jdbcLdap.jndi.SQLNamingException; +import com.octetstring.jdbcLdap.sql.statements.*; + +import java.sql.*; +import java.util.*; + +import net.sourceforge.myvd.chain.InterceptorChain; +import net.sourceforge.myvd.chain.SearchInterceptorChain; +import net.sourceforge.myvd.types.Attribute; +import net.sourceforge.myvd.types.Bool; +import net.sourceforge.myvd.types.DistinguishedName; +import net.sourceforge.myvd.types.Filter; +import net.sourceforge.myvd.types.Int; +import net.sourceforge.myvd.types.Results; + +import com.novell.ldap.*; +import com.novell.ldap.controls.LDAPSortControl; +import com.novell.ldap.controls.LDAPSortKey; +/** + *Retrieves the results from a qeury + *@author Marc Boorshtein, OctetString + */ +public class RetrieveResults implements ChainedImpl,DirectoryRetrieveResults { + + public InterceptorChain chain; + + /** Creates new RetrieveResults */ + public RetrieveResults() { + } + + /* (non-Javadoc) + * @see com.octetstring.jdbcLdap.jndi.DirectoryRetrieveResults#searchJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapSelect) + */ + public Object searchJldap(JdbcLdapSelect select) throws SQLException { + try { + + String[] fields = select.getSearchAttributes(); + fields = fields != null ? fields : new String[0]; + + + ArrayList searchAttribs = new ArrayList(); + + if (fields.length == 1 && fields[0].equalsIgnoreCase("dn")) { + searchAttribs.add(new Attribute("1.1")); + + } + else { + for (int i=0,m=fields.length;i= 0) { + constraints = new LDAPSearchConstraints(); + constraints.setMaxResults(select.getJDBCConnection().getMaxSizeLimit()); + } + + if (select.getJDBCConnection().getMaxTimeLimit() >= 0) { + if (constraints == null) { + constraints = new LDAPSearchConstraints(); + } + + constraints.setTimeLimit(select.getJDBCConnection().getMaxTimeLimit()); + } + + + + LDAPSortKey[] keys = null; + + if (select.getSqlStore().getOrderby() != null) { + keys = new LDAPSortKey[select.getSqlStore().getOrderby().length]; + for (int i=0,m=keys.length;i attribs; + searchChain.nextSearch(new DistinguishedName(useBase),new Int(select.getSearchScope()),new Filter(filter),searchAttribs,new Bool(false),res,constraints); + + return new EntrySetSearchResults(res); + + } catch (LDAPException e) { + throw new SQLNamingException(e); + } + + } + + + + + /* (non-Javadoc) + * @see com.octetstring.jdbcLdap.jndi.DirectoryRetrieveResults#searchUpInsJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapSqlAbs) + */ + public LDAPSearchResults searchUpInsJldap(JdbcLdapSqlAbs sql) throws SQLException { + try { + LDAPConnection con = sql.getConnection(); + + + String useBase = JndiLdapConnection.getRealBase(sql); + + String filter = sql.getFilterWithParams(); + + LDAPSearchConstraints constraints = null; + + if (sql.getJDBCConnection().getMaxSizeLimit() >= 0) { + constraints = new LDAPSearchConstraints(); + constraints.setMaxResults(sql.getJDBCConnection().getMaxSizeLimit()); + } + + if (sql.getJDBCConnection().getMaxTimeLimit() >= 0) { + if (constraints == null) { + constraints = con.getSearchConstraints(); + } + + constraints.setTimeLimit(sql.getJDBCConnection().getMaxTimeLimit()); + } + +// //System.out.println("sql.getBaseContext() " + sql.getBaseContext()); +// //System.out.println("where : " + filter); +// //System.out.println("scope : " + sql.getSearchScope()); + + Results res = new Results(this.getChain().getInterceptors(),this.chain.getPos()); + SearchInterceptorChain searchChain = this.chain.createSearchChain(); + + ArrayList searchAttribs = new ArrayList(); + searchAttribs.add(new Attribute("1.1")); + + searchChain.nextSearch(new DistinguishedName(useBase),new Int(sql.getSearchScope()),new Filter(filter),searchAttribs,new Bool(false),res,constraints); + + + return new EntrySetSearchResults(res); + } + catch (LDAPException e) { + throw new SQLNamingException(e); + } + } + + private String getFieldName(String name,HashMap revMap) { + + if (revMap != null) { + String nname = (String) revMap.get(name); + if (nname != null) { + return nname; + } + } + + return name; + } + + public InterceptorChain getChain() { + return chain; + } + + public void setChain(InterceptorChain chain) { + this.chain = chain; + } + +} diff --git a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Update.java b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Update.java index 31fa86b..7550dcb 100644 --- a/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Update.java +++ b/server/src/main/java/net/sourceforge/myvd/chain/jdbcLdapImpl/Update.java @@ -1,114 +1,114 @@ -/* ************************************************************************** - * - * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. - * - * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND - * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT - * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS - * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" - * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION - * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP - * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., - * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. - ******************************************************************************/ - -/* - * Update.java - * - * Created on May 24, 2002, 12:56 PM - */ - -package net.sourceforge.myvd.chain.jdbcLdapImpl; - -import com.octetstring.jdbcLdap.backend.DirectoryRetrieveResults; -import com.octetstring.jdbcLdap.backend.DirectoryUpdate; -import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; -import com.octetstring.jdbcLdap.jndi.SQLNamingException; -import com.octetstring.jdbcLdap.sql.statements.*; -import com.octetstring.jdbcLdap.sql.*; - -import java.sql.*; -import java.util.ArrayList; - -import net.sourceforge.myvd.chain.InterceptorChain; -import net.sourceforge.myvd.chain.ModifyInterceptorChain; -import net.sourceforge.myvd.types.DistinguishedName; - -import com.novell.ldap.*; -/** - *Contains logic for updating records in the directory - *@author Marc Boorshtein, OctetString - */ -public class Update implements ChainedImpl,DirectoryUpdate { - - - InterceptorChain chain; - - - /* (non-Javadoc) - * @see com.octetstring.jdbcLdap.jndi.DirectoryUpdate#doUpdateJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapUpdate) - */ - public int doUpdateJldap(JdbcLdapUpdate update) throws SQLException { - DirectoryRetrieveResults res = (DirectoryRetrieveResults) update.getCon().getImplClasses().get(JndiLdapConnection.IMPL_RETRIEVE_RESULTS); - - LDAPEntry seres; - StringBuffer buf = new StringBuffer(); - SqlStore store = update.getSqlStore(); - int count = 0; - ArrayList mods; - - String[] fields,vals; - //build ModificationItem array - mods = new ArrayList(store.getFields().length); - fields = store.getFields(); - vals = update.getVals(); - String name; - for (int i=0,m=fields.length;i mods; + + String[] fields,vals; + //build ModificationItem array + mods = new ArrayList(store.getFields().length); + fields = store.getFields(); + vals = update.getVals(); + String name; + for (int i=0,m=fields.length;i mods = new ArrayList(); - int paramnum = 0; - while (icmds.hasNext()) { - us = (UpdateSet) icmds.next(); - - - int modtype; - - if (us.getCmd().equalsIgnoreCase(JdbcLdapUpdateEntry.ADD)) { - modtype = LDAPModification.ADD; - } - else if (us.getCmd().equalsIgnoreCase(JdbcLdapUpdateEntry.DELETE)) { - modtype = LDAPModification.DELETE; - } - else { - modtype = LDAPModification.REPLACE; - } - - - - //ModificationItem[] mods = new ModificationItem[stmt.getAttribs().size()]; - Pair p; - String val,name; - Iterator it = us.getAttribs().iterator(); - int i = 0; - ArrayList al = new ArrayList(); - while (it.hasNext()) { - if (modtype == LDAPModification.ADD || modtype == LDAPModification.REPLACE) { - p = (Pair) it.next(); - name = p.getName(); - - if (p.getValue().equals("?")) { - ////System.out.println("paramnum : " + paramnum); - ////System.out.println("val : " + stmt.getArgVals()[paramnum]); - val = stmt.getArgVals()[paramnum]; - paramnum++; - //i++; - } - else { - val = p.getValue(); - } - - - ////System.out.println("moditem : " + modtype + ", " + name + "=" + val); - mods.add(new LDAPModification(modtype,new LDAPAttribute(name,val))); - } - else { - name = (String) it.next(); - ////System.out.println("moditem : " + modtype + ", " + name); - mods.add(new LDAPModification(modtype,new LDAPAttribute(name))); - } - i++; - } - } - - Object[] toCopy = mods.toArray(); - - - LDAPEntry entry; - StringBuffer buf = new StringBuffer(); - String name; - try { - int count = 0; - if (stmt.getSearchScope() != 0) { - LDAPSearchResults enumer = res.searchUpInsJldap(stmt); - while (enumer.hasMore()) { - entry = enumer.next(); - buf.setLength(0); - - name = entry.getDN(); - - ModifyInterceptorChain modChain = this.chain.createModifyChain(); - modChain.nextModify(new DistinguishedName(name),mods,new LDAPConstraints()); - - - count++; - ////System.out.println("count : " + count); - - } - } else { - ModifyInterceptorChain modChain = this.chain.createModifyChain(); - modChain.nextModify(new DistinguishedName(stmt.getBaseContext()),mods,new LDAPConstraints()); - - count++; - } - - - ////System.out.println("final count : " + count); - return count; - //stmt.getContext().modifyAttributes(dn.toString(),doMods); - } catch (LDAPException ne) { - throw new SQLNamingException(ne); - } - } - - - public InterceptorChain getChain() { - return chain; - } - - - public void setChain(InterceptorChain chain) { - this.chain = chain; - } - -} +/* ************************************************************************** + * + * Copyright (C) 2002-2005 Octet String, Inc. All Rights Reserved. + * + * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND + * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT + * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS + * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" + * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION + * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP + * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM OCTET STRING, INC., + * COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. + ******************************************************************************/ +package net.sourceforge.myvd.chain.jdbcLdapImpl; + +import java.util.*; + +import java.sql.*; + +import net.sourceforge.myvd.chain.InterceptorChain; +import net.sourceforge.myvd.chain.ModifyInterceptorChain; +import net.sourceforge.myvd.types.DistinguishedName; + +import com.octetstring.jdbcLdap.backend.DirectoryRetrieveResults; +import com.octetstring.jdbcLdap.backend.DirectoryUpdateEntry; +import com.octetstring.jdbcLdap.jndi.JndiLdapConnection; +import com.octetstring.jdbcLdap.jndi.SQLNamingException; +import com.octetstring.jdbcLdap.sql.statements.*; +import com.octetstring.jdbcLdap.util.*; +import com.novell.ldap.*; + +/** + * @author mlb + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class UpdateEntry implements ChainedImpl,DirectoryUpdateEntry { + + InterceptorChain chain; + + + /* (non-Javadoc) + * @see com.octetstring.jdbcLdap.jndi.DirectoryUpdateEntry#doUpdateEntryJldap(com.octetstring.jdbcLdap.sql.statements.JdbcLdapUpdateEntry) + */ + public int doUpdateEntryJldap(JdbcLdapUpdateEntry stmt) throws SQLException { + DirectoryRetrieveResults res = (DirectoryRetrieveResults) stmt.getJDBCConnection().getImplClasses().get(JndiLdapConnection.IMPL_RETRIEVE_RESULTS); + int argPos = 0; + StringBuffer dn = new StringBuffer(); + + + + Iterator icmds = stmt.getCmds().iterator(); + UpdateSet us; + ArrayList mods = new ArrayList(); + int paramnum = 0; + while (icmds.hasNext()) { + us = (UpdateSet) icmds.next(); + + + int modtype; + + if (us.getCmd().equalsIgnoreCase(JdbcLdapUpdateEntry.ADD)) { + modtype = LDAPModification.ADD; + } + else if (us.getCmd().equalsIgnoreCase(JdbcLdapUpdateEntry.DELETE)) { + modtype = LDAPModification.DELETE; + } + else { + modtype = LDAPModification.REPLACE; + } + + + + //ModificationItem[] mods = new ModificationItem[stmt.getAttribs().size()]; + Pair p; + String val,name; + Iterator it = us.getAttribs().iterator(); + int i = 0; + ArrayList al = new ArrayList(); + while (it.hasNext()) { + if (modtype == LDAPModification.ADD || modtype == LDAPModification.REPLACE) { + p = (Pair) it.next(); + name = p.getName(); + + if (p.getValue().equals("?")) { + ////System.out.println("paramnum : " + paramnum); + ////System.out.println("val : " + stmt.getArgVals()[paramnum]); + val = stmt.getArgVals()[paramnum]; + paramnum++; + //i++; + } + else { + val = p.getValue(); + } + + + ////System.out.println("moditem : " + modtype + ", " + name + "=" + val); + mods.add(new LDAPModification(modtype,new LDAPAttribute(name,val))); + } + else { + name = (String) it.next(); + ////System.out.println("moditem : " + modtype + ", " + name); + mods.add(new LDAPModification(modtype,new LDAPAttribute(name))); + } + i++; + } + } + + Object[] toCopy = mods.toArray(); + + + LDAPEntry entry; + StringBuffer buf = new StringBuffer(); + String name; + try { + int count = 0; + if (stmt.getSearchScope() != 0) { + LDAPSearchResults enumer = res.searchUpInsJldap(stmt); + while (enumer.hasMore()) { + entry = enumer.next(); + buf.setLength(0); + + name = entry.getDN(); + + ModifyInterceptorChain modChain = this.chain.createModifyChain(); + modChain.nextModify(new DistinguishedName(name),mods,new LDAPConstraints()); + + + count++; + ////System.out.println("count : " + count); + + } + } else { + ModifyInterceptorChain modChain = this.chain.createModifyChain(); + modChain.nextModify(new DistinguishedName(stmt.getBaseContext()),mods,new LDAPConstraints()); + + count++; + } + + + ////System.out.println("final count : " + count); + return count; + //stmt.getContext().modifyAttributes(dn.toString(),doMods); + } catch (LDAPException ne) { + throw new SQLNamingException(ne); + } + } + + + public InterceptorChain getChain() { + return chain; + } + + + public void setChain(InterceptorChain chain) { + this.chain = chain; + } + +} diff --git a/server/src/main/java/net/sourceforge/myvd/inserts/RootObject.java b/server/src/main/java/net/sourceforge/myvd/inserts/RootObject.java old mode 100755 new mode 100644 diff --git a/server/src/main/java/net/sourceforge/myvd/inserts/kerberos/KerberosInterceptor.java b/server/src/main/java/net/sourceforge/myvd/inserts/kerberos/KerberosInterceptor.java old mode 100755 new mode 100644 diff --git a/server/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPSocketFactory.java b/server/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPSocketFactory.java old mode 100755 new mode 100644 diff --git a/server/src/test/java/net/sourceforge/myvd/test/router/SearchFromRoot.java b/server/src/test/java/net/sourceforge/myvd/test/router/SearchFromRoot.java old mode 100755 new mode 100644 diff --git a/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPInterceptor.java b/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPInterceptor.java index fe0ef2c..4a51720 100644 --- a/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPInterceptor.java +++ b/src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPInterceptor.java @@ -20,8 +20,6 @@ import java.util.Iterator; import java.util.Properties; -import org.apache.logging.log4j.Logger; - import net.sourceforge.myvd.chain.AddInterceptorChain; import net.sourceforge.myvd.chain.BindInterceptorChain; import net.sourceforge.myvd.chain.CompareInterceptorChain; @@ -40,607 +38,572 @@ import net.sourceforge.myvd.types.Entry; import net.sourceforge.myvd.types.ExtendedOperation; import net.sourceforge.myvd.types.Filter; -import net.sourceforge.myvd.types.FilterNode; import net.sourceforge.myvd.types.Int; import net.sourceforge.myvd.types.Password; import net.sourceforge.myvd.types.Results; import net.sourceforge.myvd.types.SessionVariables; import net.sourceforge.myvd.util.NamingUtils; -import com.novell.ldap.LDAPAttribute; import com.novell.ldap.LDAPConnection; import com.novell.ldap.LDAPConstraints; import com.novell.ldap.LDAPControl; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPExtendedOperation; import com.novell.ldap.LDAPLocalException; import com.novell.ldap.LDAPModification; import com.novell.ldap.LDAPSearchConstraints; import com.novell.ldap.LDAPSearchResults; import com.novell.ldap.controls.LDAPPagedResultsControl; import com.novell.ldap.util.DN; -import com.novell.ldap.util.RDN; + +import org.apache.logging.log4j.Logger; public class LDAPInterceptor implements Insert { - public static final String NO_MAP_BIND_DN = "NO_MAP_BIND_DN_"; - static Logger logger = org.apache.logging.log4j.LogManager.getLogger(LDAPInterceptor.class); - String host; - int port; - String name; - DN remoteBase; - String[] explodedRemoteBase; - String[] explodedLocalBase; - - String proxyDN; - byte[] proxyPass; - - LDAPConnectionType type; - - String spmlImpl; - - boolean isSoap; - - boolean passThroughBindOnly; - boolean ignoreRefs; - - boolean usePaging; - int pageSize; - - NamingUtils utils; - - LDAPConnectionPool pool; - LDAPSocketFactory socketFactory; - - String noMapBindFlag; - - long maxIdleTime; - private int maxOpMillis; - private long maxStaleTime; - private DistinguishedName localBase; - - private long heartbeatIntervalMinis; - - private LDAPHeartBeat heartBeat; - public boolean useSrvDNS; - - public void configure(String name, Properties props,NameSpace nameSpace) throws LDAPException { - this.name = name; - this.host = props.getProperty("host"); - this.port = Integer.parseInt(props.getProperty("port")); - this.remoteBase = new DN(props.getProperty("remoteBase")); - this.explodedRemoteBase = this.remoteBase.explodeDN(false); - this.explodedLocalBase = nameSpace.getBase().getDN().explodeDN(false); - this.localBase = nameSpace.getBase(); - - this.usePaging = Boolean.parseBoolean(props.getProperty("usePaging", "false")); - if (this.usePaging) { - this.pageSize = Integer.parseInt(props.getProperty("pageSize","500")); - } - - logger.info("usePaging - '" + this.usePaging + "'"); - logger.info("pageSize - '" + this.pageSize + "'"); - - this.proxyDN = (String) props.getProperty("proxyDN",""); - - - this.proxyPass = props.getProperty("proxyPass","").getBytes(); - - String type = props.getProperty("type","LDAP"); - - if (type.equalsIgnoreCase("LDAP")) { - this.type = LDAPConnectionType.LDAP; - } else if (type.equalsIgnoreCase("DSMLV2")) { - this.type = LDAPConnectionType.DSMLV2; - this.isSoap = props.getProperty("useSOAP","true").equalsIgnoreCase("true"); - } else if (type.equalsIgnoreCase("SPML")) { - this.type = LDAPConnectionType.SPML; - this.spmlImpl = props.getProperty("spmlImpl","com.novell.ldap.spml.NoAuthImpl"); - - } else if (type.equalsIgnoreCase("ldaps")) { - this.type = LDAPConnectionType.LDAPS; - } else { - throw new LDAPLocalException("Unrecognized ldap interceptor type : " + type, LDAPException.OPERATIONS_ERROR); - } - - String socketFactoryClassName = props.getProperty("sslSocketFactory"); - - if (socketFactoryClassName != null) { - try { - this.socketFactory = (LDAPSocketFactory) Class.forName(socketFactoryClassName).newInstance(); - } catch (Exception e) { - throw new LDAPException("Could not initiate socket factory",LDAPException.OPERATIONS_ERROR,"Operations Error",e); - } - } else { - this.socketFactory = null; - } - - this.maxIdleTime = Long.parseLong(props.getProperty("maxIdle","0")); - - this.maxOpMillis = Integer.parseInt(props.getProperty("maxMillis","30000")); - - logger.info("Maximum Operations Time (millis); " + this.maxOpMillis); - - this.maxStaleTime = Long.parseLong(props.getProperty("maxStaleTimeMillis","60000")); - logger.info("Maximum stale connection time in millis : " + this.maxStaleTime); - - this.useSrvDNS = props.getProperty("useSrvDNS", "false").equalsIgnoreCase("true"); - - this.pool = new LDAPConnectionPool(this, Integer.parseInt(props.getProperty("minimumConnections","5")), Integer.parseInt(props.getProperty("maximumConnections","30")), Integer.parseInt(props.getProperty("maximumRetries","5")),this.type,this.spmlImpl,this.isSoap); - - - - - this.passThroughBindOnly = props.getProperty("passBindOnly","false").equalsIgnoreCase("true"); - this.ignoreRefs = props.getProperty("ignoreRefs","false").equalsIgnoreCase("true"); - - this.utils = new NamingUtils(); - - this.noMapBindFlag = LDAPInterceptor.NO_MAP_BIND_DN + this.name; - - this.heartbeatIntervalMinis = Long.parseLong(props.getProperty("heartbeatIntervalMillis","0")); - logger.info("Heartbeat Interval in Milliseconds : '" + this.heartbeatIntervalMinis + "'"); - - if (this.heartbeatIntervalMinis > 0) { - this.heartBeat = new LDAPHeartBeat(this); - new Thread(this.heartBeat).start(); - } - - - } - - private ConnectionWrapper getConnection(DN bindDN,Password pass,boolean force,DN base,HashMap session) throws LDAPException { - return this.getConnection(bindDN, pass, force, base, session, false); - } - - private ConnectionWrapper getConnection(DN bindDN,Password pass,boolean force,DN base,HashMap session,boolean forceBind) throws LDAPException { - ConnectionWrapper wrapper = null; - - if (logger.isDebugEnabled()) { - logger.debug("Bound inserts : " + session.get(SessionVariables.BOUND_INTERCEPTORS)); - } - - if (this.passThroughBindOnly && ! force) { - wrapper = pool.getConnection(new DN(this.proxyDN),new Password(this.proxyPass),force); - } else if (forceBind || (! this.passThroughBindOnly && ((ArrayList) session.get(SessionVariables.BOUND_INTERCEPTORS)).contains(this.name))) { - wrapper = pool.getConnection(bindDN,pass,force); - } else { - wrapper = pool.getConnection(new DN(this.proxyDN),new Password(this.proxyPass),force); - } - - if (wrapper == null) { - - throw new LDAPException("Could not get remote connection",LDAPException.SERVER_DOWN,base.toString()); - } else { - return wrapper; - } - } - - protected void returnLDAPConnection(ConnectionWrapper wrapper) { - pool.returnConnection(wrapper); - } - - protected DN getRemoteMappedDN(DN dn) { - - //if ((dn.getRDNs().size() < this.explodedLocalBase.length) || (dn.equals(this.localBase.getDN()) || dn.isDescendantOf(this.localBase.getDN()))) { - return utils.getRemoteMappedDN(dn,explodedLocalBase,explodedRemoteBase); - //} else { - // return dn; - //} - } - - protected DN getLocalMappedDN(DN dn) { - return utils.getLocalMappedDN(dn,explodedRemoteBase,explodedLocalBase); - - } - - public void add(AddInterceptorChain chain, Entry entry, - LDAPConstraints constraints) throws LDAPException { - - - - ConnectionWrapper wrapper; - - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,new DN(entry.getEntry().getDN()),chain.getSession()); - } else { - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,new DN(entry.getEntry().getDN()),chain.getSession()); - } - - - LDAPConnection con = wrapper.getConnection(); - - try { - LDAPEntry remoteEntry = new LDAPEntry(this.getRemoteMappedDN(new DN(entry.getEntry().getDN())).toString(),entry.getEntry().getAttributeSet()); - - if (this.maxOpMillis > 0) { - if (constraints == null) { - constraints = new LDAPConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - - - con.add(remoteEntry,constraints); - } finally { - this.returnLDAPConnection(wrapper); - } - - - - //TODO -- Add way to continue down the chain? - } - - public void bind(BindInterceptorChain chain, DistinguishedName dn, - Password pwd, LDAPConstraints constraints) throws LDAPException { - - - - - DN mappedDN; - - - if (chain.getSession().containsKey(noMapBindFlag)) { - mappedDN = dn.getDN(); - } else { - mappedDN = this.getRemoteMappedDN(dn.getDN()); - } - - - - - ConnectionWrapper wrapper = this.getConnection(mappedDN,pwd,true,dn.getDN(),chain.getSession(),true); - LDAPConnection con = wrapper.getConnection(); - - try { - wrapper.bind(mappedDN,pwd); - ArrayList bound = (ArrayList) chain.getSession().get(SessionVariables.BOUND_INTERCEPTORS); - bound.add(this.name); - } finally { - this.returnLDAPConnection(wrapper); - } - - - } - - public void compare(CompareInterceptorChain chain, DistinguishedName dn, - Attribute attrib, LDAPConstraints constraints) throws LDAPException { - - ConnectionWrapper wrapper; - - - - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } else { - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } - - LDAPConnection con = wrapper.getConnection(); - - try { - if (this.maxOpMillis > 0) { - if (constraints == null) { - constraints = new LDAPConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - con.compare(this.getRemoteMappedDN(dn.getDN()).toString(),attrib.getAttribute(),constraints); - } finally { - this.returnLDAPConnection(wrapper); - } - - } - - public void delete(DeleteInterceptorChain chain, DistinguishedName dn,LDAPConstraints constraints) throws LDAPException { - - ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } else { - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } - - - try { - - - LDAPConnection con = wrapper.getConnection(); - - if (this.maxOpMillis > 0) { - constraints.setTimeLimit(this.maxOpMillis); - } - - con.delete(this.getRemoteMappedDN(dn.getDN()).toString(),constraints); - } finally { - this.returnLDAPConnection(wrapper); - } - - } - - public void extendedOperation(ExetendedOperationInterceptorChain chain, - ExtendedOperation op, LDAPConstraints constraints) - throws LDAPException { - - ConnectionWrapper wrapper;// = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,new DN(),chain.getSession()); - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,op.getDn().getDN(),chain.getSession()); - } else { - - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,op.getDn().getDN(),chain.getSession()); - } - LDAPConnection con = wrapper.getConnection(); - - try { - if (this.maxOpMillis > 0) { - if (constraints == null) { - constraints = new LDAPConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - - con.extendedOperation(op.getOp(),constraints); - } finally { - this.returnLDAPConnection(wrapper); - } - - } - - public void modify(ModifyInterceptorChain chain, DistinguishedName dn, - ArrayList mods, LDAPConstraints constraints) throws LDAPException { - - - LDAPModification[] ldapMods = new LDAPModification[mods.size()]; - System.arraycopy(mods.toArray(),0,ldapMods,0,ldapMods.length); - - ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } else { - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } - LDAPConnection con = wrapper.getConnection(); - - try { - if (this.maxOpMillis > 0) { - if (constraints == null) { - constraints = new LDAPConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - - con.modify(this.getRemoteMappedDN(dn.getDN()).toString(),ldapMods,constraints); - } finally { - this.returnLDAPConnection(wrapper); - } - - } - - public void search(SearchInterceptorChain chain, DistinguishedName base, - Int scope, Filter filter, ArrayList attributes, Bool typesOnly, - Results results, LDAPSearchConstraints constraints) throws LDAPException { - - String[] attribs = new String[attributes.size()]; - - Iterator it = attributes.iterator(); - for (int i=0,m=attribs.length;i 0) { - if (constraints == null) { - constraints = new LDAPSearchConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - - LDAPSearchResults res = con.search(remoteBase,scope.getValue(),filterVal,attribs,typesOnly.getValue(),constraints); - chain.addResult(results,new LDAPEntrySet(this,wrapper,res,remoteBase, scope.getValue(), filter.getValue(), attribs, typesOnly.getValue(), constraints), base, scope, filter, attributes, typesOnly, constraints); - } finally { - - this.returnLDAPConnection(wrapper); - } - - - } - - public String getHost() { - return host; - } - - public String getName() { - return name; - } - - public int getPort() { - return port; - } - - public DN getRemoteBase() { - return remoteBase; - } - - public void rename(RenameInterceptorChain chain, DistinguishedName dn, DistinguishedName newRdn, Bool deleteOldRdn,LDAPConstraints constraints) throws LDAPException { - - String oldDN = this.getRemoteMappedDN(dn.getDN()).toString(); - - - ConnectionWrapper wrapper; //= this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } else { - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } - LDAPConnection con = wrapper.getConnection(); - - try { - if (this.maxOpMillis > 0) { - if (constraints == null) { - constraints = new LDAPConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - - con.rename(oldDN,newRdn.getDN().toString(),deleteOldRdn.getValue()); - } finally { - this.returnLDAPConnection(wrapper); - } - - - } - - public void rename(RenameInterceptorChain chain, DistinguishedName dn, DistinguishedName newRdn, DistinguishedName newParentDN, Bool deleteOldRdn,LDAPConstraints constraints) throws LDAPException { - String oldDN = this.getRemoteMappedDN(dn.getDN()).toString(); - String newPDN = this.getRemoteMappedDN(newParentDN.getDN()).toString(); - - ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - if (chain.getSession().containsKey(noMapBindFlag)) { - wrapper = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } else { - wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); - } - LDAPConnection con = wrapper.getConnection(); - - try { - - if (this.maxOpMillis > 0) { - if (constraints == null) { - constraints = new LDAPConstraints(); - } - constraints.setTimeLimit(this.maxOpMillis); - } - - con.rename(oldDN,newRdn.getDN().toString(),newPDN,deleteOldRdn.getValue()); - } finally { - this.returnLDAPConnection(wrapper); - } - - } - - public void postSearchEntry(PostSearchEntryInterceptorChain chain, Entry entry, DistinguishedName base, Int scope, Filter filter, ArrayList attributes, Bool typesOnly, LDAPSearchConstraints constraints) throws LDAPException { - // TODO Auto-generated method stub - - } - - public void postSearchComplete(PostSearchCompleteInterceptorChain chain, DistinguishedName base, Int scope, Filter filter, ArrayList attributes, Bool typesOnly, LDAPSearchConstraints constraints) throws LDAPException { - // TODO Auto-generated method stub - - } - - public boolean isIgnoreRefs() { - return this.ignoreRefs; - } - - public void shutdown() { - if (this.heartBeat != null) { - this.heartBeat.stop(); - } - - logger.info("Closing down all pools..."); - this.pool.shutDownPool(); - logger.info("Pool shutdown..."); - - } - - public LDAPSocketFactory getSocketFactory() { - return this.socketFactory; - } - - public long getMaxIdleTime() { - return maxIdleTime; - } - - public void setMaxIdleTime(long maxIdleTime) { - this.maxIdleTime = maxIdleTime; - } - - public boolean isUsePaging() { - return usePaging; - } - - public void setUsePaging(boolean usePaging) { - this.usePaging = usePaging; - } - - public int getPageSize() { - return pageSize; - } - - public void setPageSize(int pageSize) { - this.pageSize = pageSize; - } - - public int getMaxTimeoutMillis() { - return this.maxOpMillis; - } - - public long getMaxStailTime() { - return this.maxStaleTime; - } - - public LDAPConnectionPool getConnectionPool() { - return this.pool; - } - - public long getHeartBeatMillis() { - return this.heartbeatIntervalMinis; - } - - + public static final String NO_MAP_BIND_DN = "NO_MAP_BIND_DN_"; + static Logger logger = org.apache.logging.log4j.LogManager.getLogger(LDAPInterceptor.class); + String host; + int port; + String name; + DN remoteBase; + String[] explodedRemoteBase; + String[] explodedLocalBase; + + String proxyDN; + byte[] proxyPass; + + LDAPConnectionType type; + + String spmlImpl; + + boolean isSoap; + + boolean passThroughBindOnly; + boolean ignoreRefs; + + boolean usePaging; + int pageSize; + + NamingUtils utils; + + LDAPConnectionPool pool; + LDAPSocketFactory socketFactory; + + String noMapBindFlag; + + long maxIdleTime; + private int maxOpMillis; + private long maxStaleTime; + private DistinguishedName localBase; + + private long heartbeatIntervalMinis; + + private LDAPHeartBeat heartBeat; + public boolean useSrvDNS; + + public void configure(String name, Properties props, NameSpace nameSpace) throws LDAPException { + this.name = name; + this.host = props.getProperty("host"); + this.port = Integer.parseInt(props.getProperty("port")); + this.remoteBase = new DN(props.getProperty("remoteBase")); + this.explodedRemoteBase = this.remoteBase.explodeDN(false); + this.explodedLocalBase = nameSpace.getBase().getDN().explodeDN(false); + this.localBase = nameSpace.getBase(); + + this.usePaging = Boolean.parseBoolean(props.getProperty("usePaging", "false")); + if (this.usePaging) { + this.pageSize = Integer.parseInt(props.getProperty("pageSize", "500")); + } + + logger.info("usePaging - '" + this.usePaging + "'"); + logger.info("pageSize - '" + this.pageSize + "'"); + + this.proxyDN = (String) props.getProperty("proxyDN", ""); + + this.proxyPass = props.getProperty("proxyPass", "").getBytes(); + + String type = props.getProperty("type", "LDAP"); + + if (type.equalsIgnoreCase("LDAP")) { + this.type = LDAPConnectionType.LDAP; + } else if (type.equalsIgnoreCase("DSMLV2")) { + this.type = LDAPConnectionType.DSMLV2; + this.isSoap = props.getProperty("useSOAP", "true").equalsIgnoreCase("true"); + } else if (type.equalsIgnoreCase("SPML")) { + this.type = LDAPConnectionType.SPML; + this.spmlImpl = props.getProperty("spmlImpl", "com.novell.ldap.spml.NoAuthImpl"); + + } else if (type.equalsIgnoreCase("ldaps")) { + this.type = LDAPConnectionType.LDAPS; + } else { + throw new LDAPLocalException("Unrecognized ldap interceptor type : " + type, LDAPException.OPERATIONS_ERROR); + } + + String socketFactoryClassName = props.getProperty("sslSocketFactory"); + + if (socketFactoryClassName != null) { + try { + this.socketFactory = (LDAPSocketFactory) Class.forName(socketFactoryClassName).newInstance(); + } catch (Exception e) { + throw new LDAPException("Could not initiate socket factory", LDAPException.OPERATIONS_ERROR, "Operations Error", e); + } + } else { + this.socketFactory = null; + } + + this.maxIdleTime = Long.parseLong(props.getProperty("maxIdle", "0")); + + this.maxOpMillis = Integer.parseInt(props.getProperty("maxMillis", "30000")); + + logger.info("Maximum Operations Time (millis); " + this.maxOpMillis); + + this.maxStaleTime = Long.parseLong(props.getProperty("maxStaleTimeMillis", "60000")); + logger.info("Maximum stale connection time in millis : " + this.maxStaleTime); + + this.useSrvDNS = props.getProperty("useSrvDNS", "false").equalsIgnoreCase("true"); + + this.pool = new LDAPConnectionPool(this, Integer.parseInt(props.getProperty("minimumConnections", "5")), Integer.parseInt(props.getProperty("maximumConnections", "30")), Integer.parseInt(props.getProperty("maximumRetries", "5")), this.type, this.spmlImpl, this.isSoap); + + this.passThroughBindOnly = props.getProperty("passBindOnly", "false").equalsIgnoreCase("true"); + this.ignoreRefs = props.getProperty("ignoreRefs", "false").equalsIgnoreCase("true"); + + this.utils = new NamingUtils(); + + this.noMapBindFlag = LDAPInterceptor.NO_MAP_BIND_DN + this.name; + + this.heartbeatIntervalMinis = Long.parseLong(props.getProperty("heartbeatIntervalMillis", "0")); + logger.info("Heartbeat Interval in Milliseconds : '" + this.heartbeatIntervalMinis + "'"); + + if (this.heartbeatIntervalMinis > 0) { + this.heartBeat = new LDAPHeartBeat(this); + new Thread(this.heartBeat).start(); + } + + } + + private ConnectionWrapper getConnection(DN bindDN, Password pass, boolean force, DN base, HashMap session) throws LDAPException { + return this.getConnection(bindDN, pass, force, base, session, false); + } + + private ConnectionWrapper getConnection(DN bindDN, Password pass, boolean force, DN base, HashMap session, boolean forceBind) throws LDAPException { + ConnectionWrapper wrapper = null; + + if (logger.isDebugEnabled()) { + logger.debug("Bound inserts : " + session.get(SessionVariables.BOUND_INTERCEPTORS)); + } + + if (this.passThroughBindOnly && !force) { + wrapper = pool.getConnection(new DN(this.proxyDN), new Password(this.proxyPass), force); + } else if (forceBind || (!this.passThroughBindOnly && ((ArrayList) session.get(SessionVariables.BOUND_INTERCEPTORS)).contains(this.name))) { + wrapper = pool.getConnection(bindDN, pass, force); + } else { + wrapper = pool.getConnection(new DN(this.proxyDN), new Password(this.proxyPass), force); + } + + if (wrapper == null) { + + throw new LDAPException("Could not get remote connection", LDAPException.SERVER_DOWN, base.toString()); + } else { + return wrapper; + } + } + + protected void returnLDAPConnection(ConnectionWrapper wrapper) { + pool.returnConnection(wrapper); + } + + protected DN getRemoteMappedDN(DN dn) { + + //if ((dn.getRDNs().size() < this.explodedLocalBase.length) || (dn.equals(this.localBase.getDN()) || dn.isDescendantOf(this.localBase.getDN()))) { + return utils.getRemoteMappedDN(dn, explodedLocalBase, explodedRemoteBase); + //} else { + // return dn; + //} + } + + protected DN getLocalMappedDN(DN dn) { + return utils.getLocalMappedDN(dn, explodedRemoteBase, explodedLocalBase); + + } + + public void add(AddInterceptorChain chain, Entry entry, + LDAPConstraints constraints) throws LDAPException { + + ConnectionWrapper wrapper; + + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, new DN(entry.getEntry().getDN()), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, new DN(entry.getEntry().getDN()), chain.getSession()); + } + + LDAPConnection con = wrapper.getConnection(); + + try { + LDAPEntry remoteEntry = new LDAPEntry(this.getRemoteMappedDN(new DN(entry.getEntry().getDN())).toString(), entry.getEntry().getAttributeSet()); + + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + + con.add(remoteEntry, constraints); + } finally { + this.returnLDAPConnection(wrapper); + } + + //TODO -- Add way to continue down the chain? + } + + public void bind(BindInterceptorChain chain, DistinguishedName dn, + Password pwd, LDAPConstraints constraints) throws LDAPException { + + DN mappedDN; + + if (chain.getSession().containsKey(noMapBindFlag)) { + mappedDN = dn.getDN(); + } else { + mappedDN = this.getRemoteMappedDN(dn.getDN()); + } + + ConnectionWrapper wrapper = this.getConnection(mappedDN, pwd, true, dn.getDN(), chain.getSession(), true); + LDAPConnection con = wrapper.getConnection(); + + try { + wrapper.bind(mappedDN, pwd); + ArrayList bound = (ArrayList) chain.getSession().get(SessionVariables.BOUND_INTERCEPTORS); + bound.add(this.name); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void compare(CompareInterceptorChain chain, DistinguishedName dn, + Attribute attrib, LDAPConstraints constraints) throws LDAPException { + + ConnectionWrapper wrapper; + + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } + + LDAPConnection con = wrapper.getConnection(); + + try { + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + con.compare(this.getRemoteMappedDN(dn.getDN()).toString(), attrib.getAttribute(), constraints); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { + + ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); + + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } + + try { + + LDAPConnection con = wrapper.getConnection(); + + if (this.maxOpMillis > 0) { + constraints.setTimeLimit(this.maxOpMillis); + } + + con.delete(this.getRemoteMappedDN(dn.getDN()).toString(), constraints); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void extendedOperation(ExetendedOperationInterceptorChain chain, + ExtendedOperation op, LDAPConstraints constraints) + throws LDAPException { + + ConnectionWrapper wrapper;// = this.getConnection(chain.getBindDN().getDN(),chain.getBindPassword(),false,new DN(),chain.getSession()); + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, op.getDn().getDN(), chain.getSession()); + } else { + + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, op.getDn().getDN(), chain.getSession()); + } + LDAPConnection con = wrapper.getConnection(); + + try { + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + + con.extendedOperation(op.getOp(), constraints); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void modify(ModifyInterceptorChain chain, DistinguishedName dn, + ArrayList mods, LDAPConstraints constraints) throws LDAPException { + + LDAPModification[] ldapMods = new LDAPModification[mods.size()]; + System.arraycopy(mods.toArray(), 0, ldapMods, 0, ldapMods.length); + + ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } + LDAPConnection con = wrapper.getConnection(); + + try { + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + + con.modify(this.getRemoteMappedDN(dn.getDN()).toString(), ldapMods, constraints); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void search(SearchInterceptorChain chain, DistinguishedName base, + Int scope, Filter filter, ArrayList attributes, Bool typesOnly, + Results results, LDAPSearchConstraints constraints) throws LDAPException { + + String[] attribs = new String[attributes.size()]; + + Iterator it = attributes.iterator(); + for (int i = 0, m = attribs.length; i < m; i++) { + it.hasNext(); + attribs[i] = it.next().getAttribute().getName(); + } + + ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,base.getDN(),chain.getSession()); + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, base.getDN(), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, base.getDN(), chain.getSession()); + } + LDAPConnection con = wrapper.getConnection(); + + try { + String remoteBase = this.getRemoteMappedDN(base.getDN()).toString(); + if (remoteBase == null) { + remoteBase = ""; + } + + if (this.usePaging) { + if (constraints != null) { + + LDAPSearchConstraints lc = (LDAPSearchConstraints) constraints.clone(); + constraints = lc; + + if (constraints.getControls() == null) { + LDAPControl[] controls = new LDAPControl[1]; + controls[0] = new LDAPPagedResultsControl(this.pageSize, true); + constraints.setControls(controls); + } else { + LDAPControl[] controls = new LDAPControl[constraints.getControls().length + 1]; + for (int i = 0; i < constraints.getControls().length; i++) { + controls[i] = constraints.getControls()[i]; + } + + controls[constraints.getControls().length] = new LDAPPagedResultsControl(this.pageSize, true); + constraints.setControls(controls); + } + + } else { + constraints = new LDAPSearchConstraints(); + LDAPControl[] controls = new LDAPControl[1]; + controls[0] = new LDAPPagedResultsControl(this.pageSize, true); + constraints.setControls(controls); + } + } + + String filterVal = filter.getValue(); + if (filterVal.contains("\\,")) { + filterVal = filterVal.replaceAll("[\\\\][,]", "\\\\5C,"); + + } + + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPSearchConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + + LDAPSearchResults res = con.search(remoteBase, scope.getValue(), filterVal, attribs, typesOnly.getValue(), constraints); + chain.addResult(results, new LDAPEntrySet(this, wrapper, res, remoteBase, scope.getValue(), filter.getValue(), attribs, typesOnly.getValue(), constraints), base, scope, filter, attributes, typesOnly, constraints); + } finally { + + this.returnLDAPConnection(wrapper); + } + + } + + public String getHost() { + return host; + } + + public String getName() { + return name; + } + + public int getPort() { + return port; + } + + public DN getRemoteBase() { + return remoteBase; + } + + public void rename(RenameInterceptorChain chain, DistinguishedName dn, DistinguishedName newRdn, Bool deleteOldRdn, LDAPConstraints constraints) throws LDAPException { + + String oldDN = this.getRemoteMappedDN(dn.getDN()).toString(); + + ConnectionWrapper wrapper; //= this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } + LDAPConnection con = wrapper.getConnection(); + + try { + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + + con.rename(oldDN, newRdn.getDN().toString(), deleteOldRdn.getValue()); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void rename(RenameInterceptorChain chain, DistinguishedName dn, DistinguishedName newRdn, DistinguishedName newParentDN, Bool deleteOldRdn, LDAPConstraints constraints) throws LDAPException { + String oldDN = this.getRemoteMappedDN(dn.getDN()).toString(); + String newPDN = this.getRemoteMappedDN(newParentDN.getDN()).toString(); + + ConnectionWrapper wrapper;// = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()),chain.getBindPassword(),false,dn.getDN(),chain.getSession()); + if (chain.getSession().containsKey(noMapBindFlag)) { + wrapper = this.getConnection(chain.getBindDN().getDN(), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } else { + wrapper = this.getConnection(this.getRemoteMappedDN(chain.getBindDN().getDN()), chain.getBindPassword(), false, dn.getDN(), chain.getSession()); + } + LDAPConnection con = wrapper.getConnection(); + + try { + + if (this.maxOpMillis > 0) { + if (constraints == null) { + constraints = new LDAPConstraints(); + } + constraints.setTimeLimit(this.maxOpMillis); + } + + con.rename(oldDN, newRdn.getDN().toString(), newPDN, deleteOldRdn.getValue()); + } finally { + this.returnLDAPConnection(wrapper); + } + + } + + public void postSearchEntry(PostSearchEntryInterceptorChain chain, Entry entry, DistinguishedName base, Int scope, Filter filter, ArrayList attributes, Bool typesOnly, LDAPSearchConstraints constraints) throws LDAPException { + // TODO Auto-generated method stub + + } + + public void postSearchComplete(PostSearchCompleteInterceptorChain chain, DistinguishedName base, Int scope, Filter filter, ArrayList attributes, Bool typesOnly, LDAPSearchConstraints constraints) throws LDAPException { + // TODO Auto-generated method stub + + } + + public boolean isIgnoreRefs() { + return this.ignoreRefs; + } + + public void shutdown() { + if (this.heartBeat != null) { + this.heartBeat.stop(); + } + + logger.info("Closing down all pools..."); + this.pool.shutDownPool(); + logger.info("Pool shutdown..."); + + } + + public LDAPSocketFactory getSocketFactory() { + return this.socketFactory; + } + + public long getMaxIdleTime() { + return maxIdleTime; + } + + public void setMaxIdleTime(long maxIdleTime) { + this.maxIdleTime = maxIdleTime; + } + + public boolean isUsePaging() { + return usePaging; + } + + public void setUsePaging(boolean usePaging) { + this.usePaging = usePaging; + } + + public int getPageSize() { + return pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public int getMaxTimeoutMillis() { + return this.maxOpMillis; + } + + public long getMaxStailTime() { + return this.maxStaleTime; + } + + public LDAPConnectionPool getConnectionPool() { + return this.pool; + } + + public long getHeartBeatMillis() { + return this.heartbeatIntervalMinis; + } } diff --git a/src/main/java/net/sourceforge/myvd/router/Router.java b/src/main/java/net/sourceforge/myvd/router/Router.java index e9cdde0..c97a4f2 100644 --- a/src/main/java/net/sourceforge/myvd/router/Router.java +++ b/src/main/java/net/sourceforge/myvd/router/Router.java @@ -16,15 +16,11 @@ package net.sourceforge.myvd.router; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.TreeMap; -import javax.naming.NameNotFoundException; -import javax.naming.NamingException; - import org.apache.logging.log4j.Logger; import net.sourceforge.myvd.chain.AddInterceptorChain; @@ -38,7 +34,6 @@ import net.sourceforge.myvd.chain.SearchInterceptorChain; import net.sourceforge.myvd.core.InsertChain; import net.sourceforge.myvd.core.NameSpace; -import net.sourceforge.myvd.inserts.Insert; import net.sourceforge.myvd.types.Attribute; import net.sourceforge.myvd.types.Bool; import net.sourceforge.myvd.types.DNComparer; @@ -54,104 +49,100 @@ import com.novell.ldap.LDAPConstraints; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPExtendedOperation; import com.novell.ldap.LDAPModification; import com.novell.ldap.LDAPSearchConstraints; import com.novell.ldap.util.DN; import com.novell.ldap.util.RDN; - - public class Router { + static Logger logger = org.apache.logging.log4j.LogManager.getLogger(Router.class); - - /** the backends keyed by normalized suffix strings */ + + static final DN EMPTY_DN = new DN(); + + /** the backends keyed by normalized suffix strings */ LinkedHashMap backends = new LinkedHashMap(); - + /** Contains a mapping from a name to available contexts */ TreeMap subtree; - - + boolean writeAll; + InsertChain globalChain; - + NameSpace rootNS; - + boolean searchAll; - - + public Router(InsertChain globalChain) { - this.subtree = new TreeMap(new DNComparer()); - this.globalChain = globalChain; - if (this.globalChain.getNameSpace() != null) { - this.globalChain.getNameSpace().setIsGlobal(true); - this.globalChain.getNameSpace().setRouter(this); - } + this.subtree = new TreeMap(new DNComparer()); + this.globalChain = globalChain; + if (this.globalChain.getNameSpace() != null) { + this.globalChain.getNameSpace().setIsGlobal(true); + this.globalChain.getNameSpace().setRouter(this); + } } - - + public void add(AddInterceptorChain chain,Entry entry,LDAPConstraints constraints) throws LDAPException { NameSpace curr = null; curr = getLocalBackendsWrite(chain, entry.getEntry().getDN()); - + if (curr == null) { throw new LDAPException("No namespaces for " + entry.getEntry().getDN().toString(),LDAPException.NO_SUCH_OBJECT,entry.getEntry().getDN().toString()); } - + AddInterceptorChain localChain = new AddInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,curr.getChain(),chain.getSession(),chain.getRequest()); localChain.nextAdd(entry,constraints); - - - + + + } private NameSpace getLocalBackendsWrite(InterceptorChain chain, String dn) throws LDAPException { return this.getLocalBackendsWrite(chain,dn,false); } - + private NameSpace getLocalBackendsWrite(InterceptorChain chain, String dn, boolean isRename) throws LDAPException { NameSpace curr; String key = null; - + if (isRename) { key = RequestVariables.ROUTE_NAMESPACE_RENAME; } else { key = RequestVariables.ROUTE_NAMESPACE; } - + if (! chain.getRequest().containsKey(key)) { - - + + //logger.info("DN : " + dn); Level level = this.getLevel(new DN(dn)); - + if (level == null) { throw new LDAPException(LDAPException.resultCodeToString(LDAPException.NO_SUCH_OBJECT),LDAPException.NO_SUCH_OBJECT,""); } - + Iterator it = level.backends.iterator(); - + curr = it.next(); } else { curr = this.backends.get(chain.getRequest().get(key)); } return curr; } - + public void bind(BindInterceptorChain chain,DistinguishedName dn,Password pwd,LDAPConstraints constraints) throws LDAPException { - - //check for an anonymouse user if (pwd.getValue().length == 0) { //user has not bind DN - dn.setDN(new DN("")); + dn.setDN(EMPTY_DN); return; } - + ArrayList localBackends = getLocalLevels(chain, dn); int num = 0; - + Iterator it = localBackends.iterator(); while (it.hasNext()) { NameSpace curr = it.next(); @@ -165,7 +156,7 @@ public void bind(BindInterceptorChain chain,DistinguishedName dn,Password pwd,LD throw e; } } - + if (num == localBackends.size()) { throw new LDAPException("Could not bind to any services",LDAPException.INVALID_CREDENTIALS,dn.getDN().toString()); } @@ -175,50 +166,51 @@ public void bind(BindInterceptorChain chain,DistinguishedName dn,Password pwd,LD private ArrayList getLocalLevels(InterceptorChain chain, DistinguishedName dn) throws LDAPException { ArrayList localBackends; - + logger.debug("Is set namespace?"); - if (chain.getRequest().containsKey(RequestVariables.ROUTE_NAMESPACE)) { - logger.debug("namespace manually set"); - Object obj = chain.getRequest().get(RequestVariables.ROUTE_NAMESPACE); - if (obj instanceof ArrayList) { - ArrayList list = (ArrayList) obj; - localBackends = new ArrayList(); - Iterator it = list.iterator(); - while (it.hasNext()) { - NameSpace lns = this.backends.get(it.next()); - - if (lns.getBase().getDN().isDescendantOf(dn.getDN()) || dn.getDN().equals(lns.getBase().getDN()) || dn.getDN().isDescendantOf(lns.getBase().getDN())) { - localBackends.add(lns); - } - - - } - } else if (obj instanceof String) { - localBackends = new ArrayList(); - localBackends.add(this.backends.get((String) obj)); - } else { - throw new LDAPException("Invalid routing type",LDAPException.OPERATIONS_ERROR,""); - } + + if (chain.getRequest().containsKey(RequestVariables.ROUTE_NAMESPACE)) { + logger.debug("namespace manually set"); + Object obj = chain.getRequest().get(RequestVariables.ROUTE_NAMESPACE); + if (obj instanceof ArrayList) { + ArrayList list = (ArrayList) obj; + localBackends = new ArrayList(); + Iterator it = list.iterator(); + while (it.hasNext()) { + NameSpace lns = this.backends.get(it.next()); + + if (lns.getBase().getDN().isDescendantOf(dn.getDN()) || dn.getDN().equals(lns.getBase().getDN()) || dn.getDN().isDescendantOf(lns.getBase().getDN())) { + localBackends.add(lns); + } + + } + } else if (obj instanceof String) { + localBackends = new ArrayList(); + localBackends.add(this.backends.get((String) obj)); + } else { + throw new LDAPException("Invalid routing type", LDAPException.OPERATIONS_ERROR, ""); + } + } else { logger.debug("namespace set by router"); Level level = this.getLevel(dn.getDN()); logger.debug("namespace levels determined"); - + if (level == null) { logger.debug("no levels found"); throw new LDAPException(LDAPException.resultCodeToString(LDAPException.NO_SUCH_OBJECT),LDAPException.NO_SUCH_OBJECT,""); } - + localBackends = level.backends; } return localBackends; } - + public void compare(CompareInterceptorChain chain,DistinguishedName dn,Attribute attrib,LDAPConstraints constraints) throws LDAPException { ArrayList localBackends = getLocalLevels(chain, dn); - + int num = 0; - + Iterator it = localBackends.iterator(); while (it.hasNext()) { NameSpace curr = it.next(); @@ -234,119 +226,113 @@ public void compare(CompareInterceptorChain chain,DistinguishedName dn,Attribute throw e; } } - + if (num == localBackends.size()) { throw new LDAPException("Could not compare on any services",LDAPException.NO_SUCH_OBJECT,dn.getDN().toString()); } } } - + public void delete(DeleteInterceptorChain chain,DistinguishedName dn,LDAPConstraints constraints) throws LDAPException { NameSpace curr = null; curr = getLocalBackendsWrite(chain, dn.getDN().toString()); - + DeleteInterceptorChain localChain = new DeleteInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,curr.getChain(),chain.getSession(),chain.getRequest()); - + localChain.nextDelete(dn,constraints); - - - + + + } - + public void extendedOperation(ExetendedOperationInterceptorChain chain,ExtendedOperation op,LDAPConstraints constraints) throws LDAPException { Iterator itBase = null; Iterator> itNoBase = null; Iterator it; - + if (op.getDn() != null || chain.getRequest().containsKey(RequestVariables.ROUTE_NAMESPACE)) { if (chain.getRequest().containsKey(RequestVariables.ROUTE_NAMESPACE)) { itBase = this.getLocalLevels(chain,op.getDn()).iterator(); } else { itBase = this.getLevel(op.getDn().getDN()).backends.iterator(); } - + it = itBase; - + } else { itNoBase = this.backends.entrySet().iterator(); it = itNoBase; } - - + + int num = 0; - - + + while (it.hasNext()) { NameSpace curr = null; - + if (itBase != null) { curr = itBase.next(); } else { curr = itNoBase.next().getValue(); } - - + + ExetendedOperationInterceptorChain localChain = new ExetendedOperationInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,curr.getChain(),chain.getSession(),chain.getRequest()); try { localChain.nextExtendedOperations(op,constraints); } catch (LDAPException e) { if (e.getResultCode() == LDAPException.NO_SUCH_OBJECT) { num++; - } + } } - + if (! this.writeAll) { continue; } - + if (num == this.backends.size()) { throw new LDAPException("Could not compare on any services",LDAPException.NO_SUCH_OBJECT,""); } } } - + public void modify(ModifyInterceptorChain chain,DistinguishedName dn,ArrayList mods,LDAPConstraints constraints) throws LDAPException { NameSpace curr = this.getLocalBackendsWrite(chain,dn.getDN().toString()); ModifyInterceptorChain localChain = new ModifyInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,curr.getChain(),chain.getSession(),chain.getRequest()); localChain.nextModify(dn,mods,constraints); - + } - - - + + + public void search(SearchInterceptorChain chain,DistinguishedName base,Int scope,Filter filter,ArrayList attributes,Bool typesOnly,Results results,LDAPSearchConstraints constraints) throws LDAPException { - logger.debug("Entering router search"); - + int notFounds = 0; HashSet toExclude = (HashSet) chain.getRequest().get(RequestVariables.ROUTE_NAMESPACE_EXCLUDE); - - + logger.debug("Determining local levels"); - ArrayList localBackends = this.getLocalLevels(chain,base); + ArrayList localBackends = this.getLocalLevels(chain, base); logger.debug("Determined local levels"); Iterator it = localBackends.iterator(); - + logger.debug("Iterate over levels"); while (it.hasNext()) { - - NameSpace holder = it.next(); - + + NameSpace holder = it.next(); + if (toExclude != null && toExclude.contains(holder.getLabel())) { continue; } - - DN parentDN = holder.getBase().getDN().getParent(); - - + DN reqDN = new DN(base.toString()); - - + DistinguishedName searchBase = new DistinguishedName(reqDN.toString()); - + logger.debug("Determine scope"); Int localScope = new Int(scope.getValue()); - if (scope.getValue() != 0) { + if (holder != null && scope.getValue() != 0) { if (holder.getBase().getDN().countRDNs() == searchBase.getDN().countRDNs() && ! holder.getBase().getDN().equals(searchBase.getDN())) { continue; } else if (scope.getValue() == 1) { @@ -361,8 +347,7 @@ public void search(SearchInterceptorChain chain,DistinguishedName base,Int scope } } logger.debug("Base determined"); - - + try { logger.debug("create local chain"); SearchInterceptorChain localChain = new SearchInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,holder.getChain(),chain.getSession(),chain.getRequest()); @@ -376,33 +361,27 @@ public void search(SearchInterceptorChain chain,DistinguishedName base,Int scope } else { throw e; } - } - + } + if (scope.getValue() == 0) { break; } - - } - + if (notFounds == localBackends.size()) { throw new LDAPException("Could not find base",LDAPException.NO_SUCH_OBJECT,""); } - - } - - - + public void addBackend(String label,DN name, NameSpace namespace) { namespace.setRouter(this); this.backends.put(label,namespace); - + if (name.countRDNs() == 0) { this.rootNS = namespace; return; } - + DN curr = new DN(name.toString()); Level level; for (int i=0,m=name.countRDNs();i= namespace.getBase().getDN().countRDNs(); } - + private boolean newNamespaceEqualsCurrent(NameSpace namespace, NameSpace part) { return part.getBase().getDN().countRDNs() == namespace.getBase().getDN().countRDNs(); } @@ -489,86 +463,82 @@ private boolean newNamespaceEqualsCurrent(NameSpace namespace, NameSpace part) { public TreeMap getSubtree() { return subtree; } - + public void rename(RenameInterceptorChain chain,DistinguishedName dn,DistinguishedName newRdn,Bool deleteOldRdn,LDAPConstraints constraints) throws LDAPException { DN oldDN = new DN(dn.getDN().toString()); - - + + NameSpace ns = this.getLocalBackendsWrite(chain,dn.getDN().toString()); - + RenameInterceptorChain newChain = new RenameInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,ns.getChain(),chain.getSession(),chain.getRequest()); - + newChain.nextRename(dn,newRdn,deleteOldRdn,constraints); - - + + } - + public void rename(RenameInterceptorChain chain,DistinguishedName dn,DistinguishedName newRdn, DistinguishedName newParentDN, Bool deleteOldRdn,LDAPConstraints constraints) throws LDAPException { DN oldDN = new DN(dn.getDN().toString()); DN newPDN = new DN(newParentDN.getDN().toString()); - - - - - + NameSpace oldNs = this.getLocalBackendsWrite(chain,dn.getDN().toString()); NameSpace newNs = this.getLocalBackendsWrite(chain,newPDN.toString(),true); - + if (oldNs == newNs) { RenameInterceptorChain newChain = new RenameInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,oldNs.getChain(),chain.getSession(),chain.getRequest()); newChain.nextRename(dn,newRdn,newParentDN,deleteOldRdn,constraints); } else { - + SearchInterceptorChain searchChain = new SearchInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,oldNs.getChain(),chain.getSession(),chain.getRequest()); Results results = new Results(globalChain); searchChain.nextSearch(new DistinguishedName(dn.getDN().toString()),new Int(0),new Filter("(objectClass=*)"),new ArrayList(),new Bool(false),results,new LDAPSearchConstraints()); - + results.start(); if (! results.hasMore()) { throw new LDAPException("Old entry not found",LDAPException.NO_SUCH_OBJECT,""); } - + Entry entry = results.next(); - + results.finish(); - + AddInterceptorChain addChain = new AddInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,newNs.getChain(),chain.getSession(),chain.getRequest()); LDAPEntry newEntry = new LDAPEntry(newRdn.getDN().toString() + "," + newParentDN.getDN().toString(),entry.getEntry().getAttributeSet()); RDN rdn = new RDN(newRdn.getDN().toString()); RDN oldRDN = (RDN) dn.getDN().getRDNs().get(0); - - - + + + newEntry.getAttributeSet().getAttribute(rdn.getType()).removeValue(oldRDN.getValue()); newEntry.getAttributeSet().getAttribute(rdn.getType()).addValue(rdn.getValue()); - + entry = new Entry(newEntry); - + addChain.nextAdd(entry,new LDAPConstraints()); - + if (deleteOldRdn.getValue()) { DeleteInterceptorChain delChain = new DeleteInterceptorChain(chain.getBindDN(),chain.getBindPassword(),0,oldNs.getChain(),chain.getSession(),chain.getRequest()); delChain.nextDelete(dn,new LDAPConstraints()); } - - + + } - - + + } - + public InsertChain getGlobalChain() { return this.globalChain; } - + public void shutDownRouter() { - + logger.info("Shutting down the Global Chain..."); - + shutdownChain(this.globalChain); - + logger.info("Global Chain shut down complete"); - + Iterator it = this.backends.values().iterator(); while(it.hasNext()) { NameSpace ns = it.next(); @@ -576,17 +546,12 @@ public void shutDownRouter() { shutdownChain(ns.getChain()); logger.info(ns.getLabel() + " shut down complete"); } - } - private void shutdownChain(InsertChain chain) { - chain.shutdownChain(); - } - public void load(Router router) { this.backends = router.backends; this.globalChain = router.globalChain; @@ -594,7 +559,6 @@ public void load(Router router) { this.searchAll = router.searchAll; this.subtree = router.subtree; this.writeAll = router.writeAll; - } } diff --git a/src/main/java/net/sourceforge/myvd/server/Server.java b/src/main/java/net/sourceforge/myvd/server/Server.java index 3788e8f..a7f2e2c 100644 --- a/src/main/java/net/sourceforge/myvd/server/Server.java +++ b/src/main/java/net/sourceforge/myvd/server/Server.java @@ -24,7 +24,6 @@ import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; -import java.nio.charset.Charset; import java.security.KeyStore; import java.util.ArrayList; import java.util.HashSet; @@ -32,9 +31,6 @@ import java.util.Properties; import java.util.StringTokenizer; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; - import net.sf.ehcache.config.CacheConfiguration; import net.sourceforge.myvd.core.InsertChain; import net.sourceforge.myvd.router.Router; @@ -42,6 +38,9 @@ import net.sourceforge.myvd.server.apacheds.MyVDInterceptor; import net.sourceforge.myvd.server.apacheds.MyVDReferalManager; +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPException; + import org.apache.directory.api.ldap.model.entry.DefaultAttribute; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.schema.SchemaManager; @@ -60,94 +59,70 @@ import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition; import org.apache.directory.server.core.partition.ldif.LdifPartition; import org.apache.directory.server.core.shared.DefaultDnFactory; +import org.apache.directory.server.i18n.I18n; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.ldap.handlers.request.ExtendedRequestHandler; import org.apache.directory.server.protocol.shared.transport.TcpTransport; import org.apache.directory.server.protocol.shared.transport.Transport; -import org.apache.directory.server.i18n.I18n; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.Appender; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.appender.ConsoleAppender; -import org.apache.logging.log4j.core.config.AppenderRef; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.layout.PatternLayout; - -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPException; +public class Server { + static Logger logger; -public class Server { - - static Logger logger; - public final static String VERSION = "1.0.5"; - - String configFile; - Properties props; - private InsertChain globalChain; - private Router router; - - private ServerCore serverCore; + String configFile; + Properties props; + private InsertChain globalChain; + private Router router; - private DefaultDirectoryService directoryService; + private ServerCore serverCore; + private DefaultDirectoryService directoryService; - private LdapServer ldapServer; + private LdapServer ldapServer; private DnFactory dnFactory; - - public InsertChain getGlobalChain() { - return globalChain; - } - - public Router getRouter() { - return router; - } - - public Server(String configFile) throws FileNotFoundException, IOException { - this.configFile = configFile; - - - - this.props = new Properties(); - - props.load(new FileInputStream(this.configFile)); - - } - - - + + public InsertChain getGlobalChain() { + return globalChain; + } + + public Router getRouter() { + return router; + } + + public Server(String configFile) throws FileNotFoundException, IOException { + this.configFile = configFile; + + this.props = new Properties(); + + props.load(new FileInputStream(this.configFile)); + + } + /** * initialize the schema manager and add the schema partition to diectory service * * @throws Exception if the schema LDIF files are not found on the classpath */ - private void initSchemaPartition() throws Exception - { + private void initSchemaPartition() throws Exception { InstanceLayout instanceLayout = directoryService.getInstanceLayout(); - - File schemaPartitionDirectory = new File( instanceLayout.getPartitionsDirectory(), "schema" ); + + File schemaPartitionDirectory = new File(instanceLayout.getPartitionsDirectory(), "schema"); // Extract the schema on disk (a brand new one) and load the registries - if ( schemaPartitionDirectory.exists() ) - { - System.out.println( "schema partition already exists, skipping schema extraction" ); - } - else - { - SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( instanceLayout.getPartitionsDirectory() ); + if (schemaPartitionDirectory.exists()) { + System.out.println("schema partition already exists, skipping schema extraction"); + } else { + SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(instanceLayout.getPartitionsDirectory()); extractor.extractOrCopy(); } - SchemaLoader loader = new LdifSchemaLoader( schemaPartitionDirectory ); - SchemaManager schemaManager = new DefaultSchemaManager( loader ); + SchemaLoader loader = new LdifSchemaLoader(schemaPartitionDirectory); + SchemaManager schemaManager = new DefaultSchemaManager(loader); // We have to load the schema now, otherwise we won't be able // to initialize the Partitions, as we won't be able to parse @@ -156,382 +131,314 @@ private void initSchemaPartition() throws Exception List errors = schemaManager.getErrors(); - if ( errors.size() != 0 ) - { - throw new Exception( I18n.err( I18n.ERR_317, Exceptions.printErrors( errors ) ) ); + if (errors.size() != 0) { + throw new Exception(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors))); } - directoryService.setSchemaManager( schemaManager ); - + directoryService.setSchemaManager(schemaManager); + if (this.dnFactory == null) { - this.dnFactory = new DefaultDnFactory(schemaManager,new net.sf.ehcache.Cache(new CacheConfiguration("myvd-apacheds-dns",10000))); + this.dnFactory = new DefaultDnFactory(schemaManager, new net.sf.ehcache.Cache(new CacheConfiguration("myvd-apacheds-dns", 10000))); } - + // Init the LdifPartition with schema - LdifPartition schemaLdifPartition = new LdifPartition( schemaManager, this.dnFactory ); - schemaLdifPartition.setPartitionPath( schemaPartitionDirectory.toURI() ); + LdifPartition schemaLdifPartition = new LdifPartition(schemaManager, this.dnFactory); + schemaLdifPartition.setPartitionPath(schemaPartitionDirectory.toURI()); // The schema partition - SchemaPartition schemaPartition = new SchemaPartition( schemaManager ); - schemaPartition.setWrappedPartition( schemaLdifPartition ); - directoryService.setSchemaPartition( schemaPartition ); + SchemaPartition schemaPartition = new SchemaPartition(schemaManager); + schemaPartition.setWrappedPartition(schemaLdifPartition); + directoryService.setSchemaPartition(schemaPartition); } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + private void deleteDir(File d) { - if (d.isDirectory()) { - File[] subs = d.listFiles(); - for (File f : subs) { - deleteDir(f); - } - - if (! d.delete()) { - logger.error("Could not delete directory : '" + d.getAbsolutePath() + "'"); - } - } else { - if (! d.delete()) { - logger.error("Could not delete file : '" + d.getAbsolutePath() + "'"); - } - } + if (d.isDirectory()) { + File[] subs = d.listFiles(); + for (File f : subs) { + deleteDir(f); + } + + if (!d.delete()) { + logger.error("Could not delete directory : '" + d.getAbsolutePath() + "'"); + } + } else { + if (!d.delete()) { + logger.error("Could not delete file : '" + d.getAbsolutePath() + "'"); + } + } } - - - - - - public void startServer() throws Exception { - String portString; - - - - - - //this is a hack for testing. - if (logger == null) { - getDefaultLog(); - } - - String apachedsPath = this.configFile.substring(0,this.configFile.lastIndexOf(File.separator) + 1) + "apacheds-data"; - - logger.info("ApacheDS System Directory Path : '" + apachedsPath + "'"); - - - - File cfgPath = new File(apachedsPath); - - if (cfgPath.isDirectory()) { - logger.warn("ApacheDS system partition exists, deleting to clear it out"); - this.deleteDir(cfgPath); - } - - - this.serverCore = new ServerCore(this.props); - - this.serverCore.startService(); - - this.globalChain = serverCore.getGlobalChain(); - this.router = serverCore.getRouter(); - - - - - - this.directoryService = new DefaultDirectoryService(); + + public void startServer() throws Exception { + String portString; + + //this is a hack for testing. + if (logger == null) { + getDefaultLog(); + } + + String apachedsPath = this.configFile.substring(0, this.configFile.lastIndexOf(File.separator) + 1) + "apacheds-data"; + + logger.info("ApacheDS System Directory Path : '" + apachedsPath + "'"); + + File cfgPath = new File(apachedsPath); + + if (cfgPath.isDirectory()) { + logger.warn("ApacheDS system partition exists, deleting to clear it out"); + this.deleteDir(cfgPath); + } + + this.serverCore = new ServerCore(this.props); + + this.serverCore.startService(); + + this.globalChain = serverCore.getGlobalChain(); + this.router = serverCore.getRouter(); + + this.directoryService = new DefaultDirectoryService(); directoryService.setShutdownHookEnabled(false); directoryService.setAccessControlEnabled(false); directoryService.setAllowAnonymousAccess(true); directoryService.setInstanceLayout(new InstanceLayout(new File(apachedsPath))); directoryService.setReferralManager(new MyVDReferalManager()); - - - - + // first load the schema initSchemaPartition(); - - // then the system partition + + // then the system partition // this is a MANDATORY partition // DO NOT add this via addPartition() method, trunk code complains about duplicate partition // while initializing - JdbmPartition systemPartition = new JdbmPartition(directoryService.getSchemaManager(),this.dnFactory); - systemPartition.setId( "system" ); - systemPartition.setPartitionPath( new File( directoryService.getInstanceLayout().getPartitionsDirectory(), systemPartition.getId() ).toURI() ); - systemPartition.setSuffixDn( new Dn( ServerDNConstants.SYSTEM_DN ) ); - systemPartition.setSchemaManager( directoryService.getSchemaManager() ); - + JdbmPartition systemPartition = new JdbmPartition(directoryService.getSchemaManager(), this.dnFactory); + systemPartition.setId("system"); + systemPartition.setPartitionPath(new File(directoryService.getInstanceLayout().getPartitionsDirectory(), systemPartition.getId()).toURI()); + systemPartition.setSuffixDn(new Dn(ServerDNConstants.SYSTEM_DN)); + systemPartition.setSchemaManager(directoryService.getSchemaManager()); + // mandatory to call this method to set the system partition // Note: this system partition might be removed from trunk - directoryService.setSystemPartition( systemPartition ); - + directoryService.setSystemPartition(systemPartition); + // Disable the ChangeLog system - directoryService.getChangeLog().setEnabled( false ); - directoryService.setDenormalizeOpAttrsEnabled( true ); - - String binaryAttributes = this.props.getProperty("server.binaryAttribs",""); - StringTokenizer toker = new StringTokenizer(binaryAttributes); - - HashSet binaryAttrs = new HashSet(); - while (toker.hasMoreTokens()) { - String token = toker.nextToken().toLowerCase(); - binaryAttrs.add(token); - ApacheDSUtil.addBinaryAttributeToSchema(new DefaultAttribute(token), directoryService.getSchemaManager()); - } - - + directoryService.getChangeLog().setEnabled(false); + directoryService.setDenormalizeOpAttrsEnabled(true); + + String binaryAttributes = this.props.getProperty("server.binaryAttribs", ""); + StringTokenizer toker = new StringTokenizer(binaryAttributes); + + HashSet binaryAttrs = new HashSet(); + while (toker.hasMoreTokens()) { + String token = toker.nextToken().toLowerCase(); + binaryAttrs.add(token); + ApacheDSUtil.addBinaryAttributeToSchema(new DefaultAttribute(token), directoryService.getSchemaManager()); + } + List newlist = new ArrayList(); - newlist.add(new MyVDInterceptor(globalChain,router,directoryService.getSchemaManager(),binaryAttrs)); - + newlist.add(new MyVDInterceptor(globalChain, router, directoryService.getSchemaManager(), binaryAttrs)); + directoryService.setInterceptors(newlist); - + directoryService.startup(); - - - - - - + this.ldapServer = new LdapServer(); ldapServer.setDirectoryService(directoryService); - + + String authRequiredString = props.getProperty("server.listener.authRequired", "false").trim(); + ldapServer.setAuthRequired(Boolean.valueOf(authRequiredString)); + ArrayList transports = new ArrayList(); - - portString = props.getProperty("server.listener.port",""); - if (! portString.equals("")) { - TcpTransport ldapTransport = new TcpTransport(Integer.parseInt(portString)); - transports.add(ldapTransport); - } - - - - portString = props.getProperty("server.secure.listener.port",""); - - if (! portString.equals("")) { - String keyStorePath = props.getProperty("server.secure.keystore",""); - - if (! keyStorePath.startsWith(File.separator)) { - keyStorePath = this.configFile.substring(0,this.configFile.lastIndexOf(File.separator) + 1) + keyStorePath; - } - - - logger.debug("Key store : " + keyStorePath); - - String keyStorePass = props.getProperty("server.secure.keypass",""); - - String clientMode = props.getProperty("server.secure.clientmode","none"); - - ArrayList allowedNames = new ArrayList(); - String allowedNamesStr = props.getProperty("server.secure.allowedAliases",""); - toker = new StringTokenizer(allowedNamesStr,",",false); - - while (toker.hasMoreTokens()) { - allowedNames.add(toker.nextToken()); - } - - KeyStore keystore; - try { - if (clientMode.equalsIgnoreCase("want")) { - ldapServer.setTlsWantClientAuth(true); - } - - if (clientMode.equalsIgnoreCase("need")) { - ldapServer.setTlsNeedClientAuth(true); - } - - ldapServer.setTlsAllowedNames(allowedNames); - - - ldapServer.setKeystoreFile(keyStorePath); - ldapServer.setCertificatePassword(keyStorePass); - - TcpTransport ldapsTransport = new TcpTransport(Integer.parseInt(portString)); - ldapsTransport.enableSSL(true); - - if (clientMode.equalsIgnoreCase("want")) { - ldapsTransport.setWantClientAuth(true); - } - - if (clientMode.equalsIgnoreCase("need")) { - ldapsTransport.setNeedClientAuth(true); - } - - - transports.add(ldapsTransport); - - } catch (Throwable t) { - logger.error("Could not start LDAPS listener",t); - t.printStackTrace(); - } - - } - - Transport[] t = new Transport[transports.size()]; - - int i=0; - for (Transport tt : transports) { - t[i] = tt; - i++; - } - - long maxSizeLimit = Long.parseLong(props.getProperty("server.listener.maxSizeLimit","0")); - ldapServer.setMaxSizeLimit(maxSizeLimit); - - int maxTimeLimit = Integer.parseInt(props.getProperty("server.listener.maxTimeLimit","0")); - ldapServer.setMaxTimeLimit(maxTimeLimit); - - - ldapServer.setTransports(t); + + portString = props.getProperty("server.listener.port", "").trim(); + if (!portString.equals("")) { + String host = props.getProperty("server.listener.host", "").trim(); + + TcpTransport ldapTransport = host.equals("") + ? new TcpTransport(Integer.parseInt(portString)) + : new TcpTransport(host, Integer.parseInt(portString)); + ldapTransport.setNeedClientAuth(true); + transports.add(ldapTransport); + } + + portString = props.getProperty("server.secure.listener.port", "").trim(); + + if (!portString.equals("")) { + String keyStorePath = props.getProperty("server.secure.keystore", "").trim(); + + if (!keyStorePath.startsWith(File.separator)) { + keyStorePath = this.configFile.substring(0, this.configFile.lastIndexOf(File.separator) + 1) + keyStorePath; + } + + logger.debug("Key store : " + keyStorePath); + + String keyStorePass = props.getProperty("server.secure.keypass", ""); + + String clientMode = props.getProperty("server.secure.clientmode", "none"); + + ArrayList allowedNames = new ArrayList(); + String allowedNamesStr = props.getProperty("server.secure.allowedAliases", ""); + toker = new StringTokenizer(allowedNamesStr, ",", false); + + while (toker.hasMoreTokens()) { + allowedNames.add(toker.nextToken()); + } + + KeyStore keystore; + try { + if (clientMode.equalsIgnoreCase("want")) { + ldapServer.setTlsWantClientAuth(true); + } + + if (clientMode.equalsIgnoreCase("need")) { + ldapServer.setTlsNeedClientAuth(true); + } + + ldapServer.setTlsAllowedNames(allowedNames); + + ldapServer.setKeystoreFile(keyStorePath); + ldapServer.setCertificatePassword(keyStorePass); + + TcpTransport ldapsTransport = new TcpTransport(Integer.parseInt(portString)); + ldapsTransport.enableSSL(true); + + if (clientMode.equalsIgnoreCase("want")) { + ldapsTransport.setWantClientAuth(true); + } + + if (clientMode.equalsIgnoreCase("need")) { + ldapsTransport.setNeedClientAuth(true); + } + + transports.add(ldapsTransport); + + } catch (Throwable t) { + logger.error("Could not start LDAPS listener", t); + t.printStackTrace(); + } + + } + + Transport[] t = new Transport[transports.size()]; + + int i = 0; + for (Transport tt : transports) { + t[i] = tt; + i++; + } + + long maxSizeLimit = Long.parseLong(props.getProperty("server.listener.maxSizeLimit", "0")); + ldapServer.setMaxSizeLimit(maxSizeLimit); + + int maxTimeLimit = Integer.parseInt(props.getProperty("server.listener.maxTimeLimit", "0")); + ldapServer.setMaxTimeLimit(maxTimeLimit); + + ldapServer.setTransports(t); ldapServer.start(); ((ExtendedRequestHandler) ldapServer.getExtendedRequestHandler()).init(globalChain, router); - - final int shutdownPort = Integer.parseInt(props.getProperty("server.shutdown.port","-1")); - if (shutdownPort > 0) { - final String shutdownHost = props.getProperty("server.shutdown.host","127.0.0.1"); - final String shutdownCommand = props.getProperty("server.shutdown.command","shutdown"); - - final Server server = this; - - new Thread() { - public void run() { - logger.info("Starting shutdown socket listener"); - try { - ServerSocket socket = new ServerSocket(shutdownPort,0,InetAddress.getByName(shutdownHost)); - while (true) { - logger.info("shutdown waiting for input"); - Socket clientSocket = null; - try { - clientSocket = socket.accept(); - } catch (Throwable t) { - logger.warn("Could not accept connection",t); - continue; - } - logger.info("request received"); - //PrintWriter out = - // new PrintWriter(clientSocket.getOutputStream(), true); - BufferedReader in = new BufferedReader( - new InputStreamReader(clientSocket.getInputStream())); - logger.info("reading data"); - String command = in.readLine(); - logger.info("'" + command + "'"); - if (command != null) { - command.trim(); - } - logger.info("'" + command + "'"); - if (shutdownCommand.equalsIgnoreCase(command)) { - logger.info("Stopping threads"); - - try { - server.stopServer(); - } catch (Exception e1) { - logger.warn("Could not gracefully shutdown server",e1); - } - - logger.info("Closing input stream"); - - try { - in.close(); - } catch (Throwable t) {} + + final int shutdownPort = Integer.parseInt(props.getProperty("server.shutdown.port", "-1")); + if (shutdownPort > 0) { + final String shutdownHost = props.getProperty("server.shutdown.host", "127.0.0.1"); + final String shutdownCommand = props.getProperty("server.shutdown.command", "shutdown"); + + final Server server = this; + + new Thread() { + public void run() { + logger.info("Starting shutdown socket listener"); + try { + ServerSocket socket = new ServerSocket(shutdownPort, 0, InetAddress.getByName(shutdownHost)); + while (true) { + logger.info("shutdown waiting for input"); + Socket clientSocket = null; + try { + clientSocket = socket.accept(); + } catch (Throwable t) { + logger.warn("Could not accept connection", t); + continue; + } + logger.info("request received"); + //PrintWriter out = + // new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader( + new InputStreamReader(clientSocket.getInputStream())); + logger.info("reading data"); + String command = in.readLine(); + logger.info("'" + command + "'"); + if (command != null) { + command.trim(); + } + logger.info("'" + command + "'"); + if (shutdownCommand.equalsIgnoreCase(command)) { + logger.info("Stopping threads"); + + try { + server.stopServer(); + } catch (Exception e1) { + logger.warn("Could not gracefully shutdown server", e1); + } + + logger.info("Closing input stream"); + + try { + in.close(); + } catch (Throwable t) { + } /*try { - out.close(); + out.close(); } catch (Throwable t) {}*/ - logger.info("Closing client socket"); - try { - clientSocket.close(); - } catch (Throwable t) {} - - logger.info("Closing server socket"); - try { - socket.close(); - } catch (Throwable t) {} - - logger.info("Sleeping for 10 seconds"); - try { - Thread.sleep(10000); - logger.info("Exiting"); - System.exit(0); - return; - } catch (Exception e) {} - - } else { - command = null; - logger.info("invalid command"); - try { - in.close(); - } catch (Throwable t) {} + logger.info("Closing client socket"); + try { + clientSocket.close(); + } catch (Throwable t) { + } + + logger.info("Closing server socket"); + try { + socket.close(); + } catch (Throwable t) { + } + + logger.info("Sleeping for 10 seconds"); + try { + Thread.sleep(10000); + logger.info("Exiting"); + System.exit(0); + return; + } catch (Exception e) { + } + + } else { + command = null; + logger.info("invalid command"); + try { + in.close(); + } catch (Throwable t) { + } /*try { out.close(); } catch (Throwable t) {} */ - try { - clientSocket.close(); - } catch (Throwable t) {} + try { + clientSocket.close(); + } catch (Throwable t) { + } + + } + } + } catch (IOException e) { + logger.error("Could not start shutdown listener", e); + } + } + }.start(); + } - } - } - } catch (IOException e) { - logger.error("Could not start shutdown listener",e); - } - } - }.start(); - } - - - } - - private static void getDefaultLog() { - - - - - - - - - - - - - - - - logger = org.apache.logging.log4j.LogManager.getLogger(Server.class.getName()); - } + } + + private static void getDefaultLog() { + logger = org.apache.logging.log4j.LogManager.getLogger(Server.class.getName()); + } /*private void startLDAP(String portString,IoFilterChainBuilder chainBuilder) throws LdapNamingException, IOException { if (! portString.equals("")) { @@ -585,61 +492,56 @@ private static void getDefaultLog() { logger.debug("LDAP listener started"); } }*/ - - public void stopServer() throws Exception { - //this.minaRegistry.unbindAll(); - logger.info("Shutting down server"); - this.ldapServer.stop(); - this.directoryService.shutdown(); - - //this.stopLDAP0(Integer.parseInt(props.getProperty("server.listener.port","389"))); - for (int i=0,m=100;i links,InsertChain chain,NameSpace ns) throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { - Iterator it = links.iterator(); - int i=0; - - while (it.hasNext()) { - String name = it.next(); - chain.setInsert(i, chain.getInsertConfig(name,prefix + name + ".",chain,i)); - - i++; - } - - chain.configureChain(); - } - - private void buildGlobalChain() throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { - String links = props.getProperty("server.globalChain"); - ArrayList linkList = new ArrayList(); - - StringTokenizer toker = new StringTokenizer(links,","); - - while (toker.hasMoreTokens()) { - linkList.add(toker.nextToken()); - } - - Insert[] tchain = new Insert[linkList.size()]; - InsertChain chain = new InsertChain(tchain); - this.globalNS = new NameSpace("globalChain",new DistinguishedName("cn=root"),0,chain,true); - chain.setNameSpace(this.globalNS); - chain.setProps(this.props); - - this.configureChain("server.globalChain.",linkList,chain,this.globalNS); - - this.globalChain = chain; - - - - } - - private void buildNamespaces() throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { - String nss = props.getProperty("server.nameSpaces"); - StringTokenizer toker = new StringTokenizer(nss,","); - Router router = new Router(this.globalChain); - - - - while (toker.hasMoreTokens()) { - - - String nsName = toker.nextToken(); - - - - logger.debug("Loading namespace : " + nsName); - - String prefix = "server." + nsName + "."; - int weight = Integer.parseInt(props.getProperty(prefix + "weight","0")); - String nsBase = props.getProperty(prefix + "nameSpace"); - - boolean enabled = props.getProperty(prefix + "enabled","true").equalsIgnoreCase("true"); - - if (! enabled) { - logger.warn("Namespace " + nsName + " disabled"); - - } else { - - String nsChain = props.getProperty(prefix + "chain"); - StringTokenizer chainToker = new StringTokenizer(nsChain,","); - - ArrayList chainList = new ArrayList(); - - while (chainToker.hasMoreTokens()) { - chainList.add(chainToker.nextToken()); - } - - Insert[] tchain = new Insert[chainList.size()]; - InsertChain chain = new InsertChain(tchain); - chain.setProps(props); - - NameSpace ns = new NameSpace(nsName,new DistinguishedName(nsBase),weight,chain,false); - chain.setNameSpace(ns); - ns.setRouter(router); - this.configureChain(prefix,chainList,chain,ns); - - router.addBackend(nsName,new DN(nsBase),ns); - } - } - - - - - this.router = router; - } - - public void startService() throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { - logger.debug("Initializing Server wide config..."); - this.buildServerWideConfig(); - logger.debug("Loading global chain..."); - this.buildGlobalChain(); - logger.debug("Global chain loaded"); - logger.debug("Loading local chain..."); - this.buildNamespaces(); - logger.debug("Local chain loaded"); - } - - private void buildServerWideConfig() { - String binaryAttrs = props.getProperty("server.binaryAttributes","objectguid,orclguid,entryuuid"); - StringTokenizer toker = new StringTokenizer(binaryAttrs,",",false); - while (toker.hasMoreTokens()) { - SchemaUtil.getSchemaUtil().addBinaryAttribute(toker.nextToken().toLowerCase()); - } - - - - } - - + static Logger logger = org.apache.logging.log4j.LogManager.getLogger(ServerCore.class); + + Properties props; + private InsertChain globalChain; + private Router router; + + private NameSpace globalNS; + + public ServerCore(Properties props) { + this.props = props; + } + + public InsertChain getGlobalChain() { + return globalChain; + } + + public Properties getProps() { + return props; + } + + public Router getRouter() { + return router; + } + + private void configureChain(String prefix, ArrayList links, InsertChain chain, NameSpace ns) throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { + Iterator it = links.iterator(); + int i = 0; + + while (it.hasNext()) { + String name = it.next(); + chain.setInsert(i, chain.getInsertConfig(name, prefix + name + ".", chain, i)); + + i++; + } + + chain.configureChain(); + } + + private void buildGlobalChain() throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { + String links = props.getProperty("server.globalChain", ""); + ArrayList linkList = new ArrayList(); + + StringTokenizer toker = new StringTokenizer(links, ","); + + while (toker.hasMoreTokens()) { + linkList.add(toker.nextToken()); + } + + Insert[] tchain = new Insert[linkList.size()]; + InsertChain chain = new InsertChain(tchain); + this.globalNS = new NameSpace("globalChain", new DistinguishedName("cn=root"), 0, chain, true); + chain.setNameSpace(this.globalNS); + chain.setProps(this.props); + + this.configureChain("server.globalChain.", linkList, chain, this.globalNS); + + this.globalChain = chain; + + } + + private void buildNamespaces() throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { + final Router router = new Router(this.globalChain); + + String nss = props.getProperty("server.nameSpaces"); + StringTokenizer toker = new StringTokenizer(nss, ","); + + while (toker.hasMoreTokens()) { + String nsName = toker.nextToken(); + logger.debug("Loading namespace : " + nsName); + + String prefix = "server." + nsName + "."; + int weight = Integer.parseInt(props.getProperty(prefix + "weight", "0")); + String nsBase = props.getProperty(prefix + "nameSpace"); + + boolean enabled = props.getProperty(prefix + "enabled", "true").equalsIgnoreCase("true"); + + if (!enabled) { + logger.warn("Namespace " + nsName + " disabled"); + + } else { + + String nsChain = props.getProperty(prefix + "chain"); + StringTokenizer chainToker = new StringTokenizer(nsChain, ","); + + ArrayList chainList = new ArrayList(); + + while (chainToker.hasMoreTokens()) { + chainList.add(chainToker.nextToken()); + } + + Insert[] tchain = new Insert[chainList.size()]; + InsertChain chain = new InsertChain(tchain); + chain.setProps(props); + + NameSpace ns = new NameSpace(nsName, new DistinguishedName(nsBase), weight, chain, false); + chain.setNameSpace(ns); + ns.setRouter(router); + this.configureChain(prefix, chainList, chain, ns); + + router.addBackend(nsName, new DN(nsBase), ns); + } + } + + this.router = router; + } + + public void startService() throws InstantiationException, IllegalAccessException, ClassNotFoundException, LDAPException { + logger.debug("Initializing Server wide config..."); + this.buildServerWideConfig(); + logger.debug("Loading global chain..."); + this.buildGlobalChain(); + logger.debug("Global chain loaded"); + logger.debug("Loading local chain..."); + this.buildNamespaces(); + logger.debug("Local chain loaded"); + } + + private void buildServerWideConfig() { + String binaryAttrs = props.getProperty("server.binaryAttributes", "objectguid,orclguid,entryuuid"); + StringTokenizer toker = new StringTokenizer(binaryAttrs, ",", false); + while (toker.hasMoreTokens()) { + SchemaUtil.getSchemaUtil().addBinaryAttribute(toker.nextToken().toLowerCase()); + } + + } + } diff --git a/src/main/java/net/sourceforge/myvd/test/util/StartOpenLDAP.java b/src/main/java/net/sourceforge/myvd/test/util/StartOpenLDAP.java index 18d357f..e8c5980 100644 --- a/src/main/java/net/sourceforge/myvd/test/util/StartOpenLDAP.java +++ b/src/main/java/net/sourceforge/myvd/test/util/StartOpenLDAP.java @@ -197,10 +197,10 @@ public boolean startServer(String fullPath,int port,String adminDN,String adminP System.out.println(exec); process = Runtime.getRuntime().exec(execa); - - - StreamReader reader = new StreamReader(process.getInputStream(),false); - StreamReader errReader = new StreamReader(process.getErrorStream(),false); + boolean debug = Boolean.valueOf(System.getenv("DEBUG_SERVER")); + + StreamReader reader = new StreamReader(process.getInputStream(), debug); + StreamReader errReader = new StreamReader(process.getErrorStream(), debug); reader.start(); errReader.start(); diff --git a/src/main/java/org/apache/directory/server/ldap/LdapServer.java b/src/main/java/org/apache/directory/server/ldap/LdapServer.java index 6595d71..8e8fad9 100644 --- a/src/main/java/org/apache/directory/server/ldap/LdapServer.java +++ b/src/main/java/org/apache/directory/server/ldap/LdapServer.java @@ -19,7 +19,6 @@ */ package org.apache.directory.server.ldap; - import java.io.FileInputStream; import java.io.IOException; import java.security.KeyManagementException; @@ -36,8 +35,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -72,7 +69,6 @@ import org.apache.directory.api.ldap.model.message.UnbindRequest; import org.apache.directory.api.ldap.model.message.extended.NoticeOfDisconnect; import org.apache.directory.api.util.Strings; -import org.apache.directory.ldap.client.api.NoVerificationTrustManager; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.api.partition.PartitionNexus; import org.apache.directory.server.core.security.CoreKeyStoreSpi; @@ -213,6 +209,9 @@ public class LdapServer extends DirectoryBackedService /** The list of realms serviced by this host. */ private List saslRealms; + /** Is authentication required. */ + private boolean authRequired; + /** The protocol handlers */ // MessageReceived handlers private LdapRequestHandler abandonRequestHandler; @@ -321,7 +320,7 @@ private void installDefaultHandlers() if ( getBindRequestHandler() == null ) { - BindRequestHandler bindRequestHandler = new BindRequestHandler(); + BindRequestHandler bindRequestHandler = new BindRequestHandler( authRequired ); bindRequestHandler.setSaslMechanismHandlers( saslMechanismHandlers ); setBindHandlers( bindRequestHandler, new BindResponseHandler() ); @@ -402,26 +401,26 @@ public void loadKeyStore() throws Exception { keyStore.load( fis, null ); } - } - // Set up key manager factory to use our key store - String algorithm = Security.getProperty( "ssl.KeyManagerFactory.algorithm" ); + // Set up key manager factory to use our key store + String algorithm = Security.getProperty( "ssl.KeyManagerFactory.algorithm" ); - if ( algorithm == null ) - { - algorithm = KeyManagerFactory.getDefaultAlgorithm(); - } + if ( algorithm == null ) + { + algorithm = KeyManagerFactory.getDefaultAlgorithm(); + } - - keyManagerFactory = KeyManagerFactory.getInstance( algorithm ); - if ( Strings.isEmpty( certificatePassword ) ) - { - keyManagerFactory.init( keyStore, null ); - } - else - { - keyManagerFactory.init( keyStore, certificatePassword.toCharArray() ); + keyManagerFactory = KeyManagerFactory.getInstance( algorithm ); + + if ( Strings.isEmpty( certificatePassword ) ) + { + keyManagerFactory.init( keyStore, null ); + } + else + { + keyManagerFactory.init( keyStore, certificatePassword.toCharArray() ); + } } } @@ -524,7 +523,7 @@ public void start() throws Exception IoFilterChainBuilder chain; - if ( transport.isSSLEnabled() ) + if (transport.isSSLEnabled() ) { chain = LdapsInitializer.init( this, ( TcpTransport ) transport ); } @@ -1054,7 +1053,6 @@ public void setSaslPrincipal( String saslPrincipal ) this.saslPrincipal = saslPrincipal; } - /** * Returns the quality-of-protection, used by DIGEST-MD5 and GSSAPI. * @@ -1098,6 +1096,13 @@ public void setSaslRealms( List saslRealms ) this.saslRealms = saslRealms; } + public boolean isAuthRequired() { + return authRequired; + } + + public void setAuthRequired(boolean authRequired) { + this.authRequired = authRequired; + } /** */ diff --git a/src/main/java/org/apache/directory/server/ldap/handlers/request/BindRequestHandler.java b/src/main/java/org/apache/directory/server/ldap/handlers/request/BindRequestHandler.java index 96b3849..1b3302f 100644 --- a/src/main/java/org/apache/directory/server/ldap/handlers/request/BindRequestHandler.java +++ b/src/main/java/org/apache/directory/server/ldap/handlers/request/BindRequestHandler.java @@ -19,17 +19,14 @@ */ package org.apache.directory.server.ldap.handlers.request; - import java.util.Map; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import org.apache.commons.lang.exception.ExceptionUtils; -import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException; -import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.exception.LdapUnwillingToPerformException; import org.apache.directory.api.ldap.model.message.BindRequest; @@ -43,7 +40,6 @@ import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.api.LdapPrincipal; import org.apache.directory.server.core.api.OperationEnum; -import org.apache.directory.server.core.api.entry.ClonedServerEntry; import org.apache.directory.server.core.api.interceptor.context.BindOperationContext; import org.apache.directory.server.core.shared.DefaultCoreSession; import org.apache.directory.server.i18n.I18n; @@ -55,33 +51,36 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * A single reply MessageReceived handler for {@link BindRequest}s. - * + *

* Implements server-side of RFC 2222, sections 4.2 and 4.3. * * @author Apache Directory Project */ -public class BindRequestHandler extends LdapRequestHandler -{ - private static final Logger LOG = LoggerFactory.getLogger( BindRequestHandler.class ); +public class BindRequestHandler extends LdapRequestHandler { + private static final Logger LOG = LoggerFactory.getLogger(BindRequestHandler.class); + + private boolean authRequired = false; - /** A Hashed Adapter mapping SASL mechanisms to their handlers. */ + /** + * A Hashed Adapter mapping SASL mechanisms to their handlers. + */ private Map handlers; + public BindRequestHandler(boolean authRequired) { + this.authRequired = authRequired; + } /** * Set the mechanisms handler map. - * + * * @param handlers The associations btween a machanism and its handler */ - public void setSaslMechanismHandlers( Map handlers ) - { + public void setSaslMechanismHandlers(Map handlers) { this.handlers = handlers; } - /** * Handle the Simple authentication. * @@ -90,13 +89,13 @@ public void setSaslMechanismHandlers( Map handlers ) * @throws Exception If the authentication cannot be done */ // This will suppress PMD.EmptyCatchBlock warnings in this method - public void handleSimpleAuth( LdapSession ldapSession, BindRequest bindRequest ) throws Exception - { + public void handleSimpleAuth(LdapSession ldapSession, BindRequest bindRequest) throws Exception { + LOG.debug(String.format("handleSimpleAuth: %s", bindRequest.getDn().toString())); + DirectoryService directoryService = ldapServer.getDirectoryService(); // if the user is already bound, we have to unbind him - if ( ldapSession.isAuthenticated() ) - { + if (ldapSession.isAuthenticated()) { // We already have a bound session for this user. We have to // abandon it first. ldapSession.getCoreSession().unbind(); @@ -109,19 +108,18 @@ public void handleSimpleAuth( LdapSession ldapSession, BindRequest bindRequest ) // create a new Bind context, with a null session, as we don't have // any context yet. - BindOperationContext bindContext = new BindOperationContext( null ); + BindOperationContext bindContext = new BindOperationContext(null); // Stores the Dn of the user to check, and its password - bindContext.setDn( bindRequest.getDn() ); - bindContext.setCredentials( bindRequest.getCredentials() ); - bindContext.setIoSession( ldapSession.getIoSession() ); - bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) ); + bindContext.setDn(bindRequest.getDn()); + bindContext.setCredentials(bindRequest.getCredentials()); + bindContext.setIoSession(ldapSession.getIoSession()); + bindContext.setInterceptors(directoryService.getInterceptors(OperationEnum.BIND)); // Stores the request controls into the operation context - LdapProtocolUtils.setRequestControls( bindContext, bindRequest ); + LdapProtocolUtils.setRequestControls(bindContext, bindRequest); - try - { + try { /* * Referral handling as specified by RFC 3296 here: * @@ -175,220 +173,190 @@ else if ( ( ( ClonedServerEntry ) principalEntry ).getOriginalEntry().contains( // opContext.setEntry( principalEntry ); // And call the OperationManager bind operation. - bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) ); - directoryService.getOperationManager().bind( bindContext ); + bindContext.setInterceptors(directoryService.getInterceptors(OperationEnum.BIND)); + directoryService.getOperationManager().bind(bindContext); // As a result, store the created session in the Core Session CoreSession coreSession = bindContext.getSession(); - ldapSession.setCoreSession( coreSession ); + ldapSession.setCoreSession(coreSession); // Store the IoSession in the coreSession - ( ( DefaultCoreSession ) coreSession ).setIoSession( bindContext.getIoSession() ); + ((DefaultCoreSession) coreSession).setIoSession(bindContext.getIoSession()); - // And set the current state accordingly - if ( !ldapSession.getCoreSession().isAnonymous() ) - { - ldapSession.setAuthenticated(); - } - else - { - ldapSession.setAnonymous(); - } + if (authRequired && (bindRequest.getDn() == null || bindRequest.getDn().getNormName().isEmpty())) { + bindRequest.setSaslMechanism("Anonymous"); + sendAuthMethNotSupported(ldapSession, bindRequest); - // Return the successful response - bindRequest.getResultResponse().addAllControls( bindContext.getResponseControls() ); - sendBindSuccess( ldapSession, bindRequest, null ); - } - catch ( Exception e ) - { + } else { + if (!ldapSession.getCoreSession().isAnonymous()) { + ldapSession.setAuthenticated(); + + } else { + ldapSession.setAnonymous(); + } + + // Return the successful response + bindRequest.getResultResponse().addAllControls(bindContext.getResponseControls()); + sendBindSuccess(ldapSession, bindRequest, null); + } + } catch (Exception e) { // Something went wrong. Write back an error message // For BindRequest, it should be an InvalidCredentials, // no matter what kind of exception we got. ResultCodeEnum code = null; LdapResult result = bindRequest.getResultResponse().getLdapResult(); - if ( e instanceof LdapUnwillingToPerformException ) - { + if (e instanceof LdapUnwillingToPerformException) { code = ResultCodeEnum.UNWILLING_TO_PERFORM; - result.setResultCode( code ); - } - else if ( e instanceof LdapInvalidDnException ) - { + result.setResultCode(code); + } else if (e instanceof LdapInvalidDnException) { code = ResultCodeEnum.INVALID_DN_SYNTAX; - result.setResultCode( code ); - } - else - { + result.setResultCode(code); + } else { code = ResultCodeEnum.INVALID_CREDENTIALS; - result.setResultCode( code ); + result.setResultCode(code); } String msg = code.toString() + ": Bind failed: " + e.getLocalizedMessage(); - if ( LOG.isDebugEnabled() ) - { - msg += ":\n" + ExceptionUtils.getStackTrace( e ); + if (LOG.isDebugEnabled()) { + msg += ":\n" + ExceptionUtils.getStackTrace(e); msg += "\n\nBindRequest = \n" + bindRequest.toString(); } Dn dn = null; - if ( e instanceof LdapAuthenticationException ) - { - dn = ( ( LdapAuthenticationException ) e ).getResolvedDn(); + if (e instanceof LdapAuthenticationException) { + dn = ((LdapAuthenticationException) e).getResolvedDn(); } - if ( ( dn != null ) - && ( ( code == ResultCodeEnum.NO_SUCH_OBJECT ) || ( code == ResultCodeEnum.ALIAS_PROBLEM ) - || ( code == ResultCodeEnum.INVALID_DN_SYNTAX ) || ( code == ResultCodeEnum.ALIAS_DEREFERENCING_PROBLEM ) ) ) - { - result.setMatchedDn( dn ); + if ((dn != null) + && ((code == ResultCodeEnum.NO_SUCH_OBJECT) || (code == ResultCodeEnum.ALIAS_PROBLEM) + || (code == ResultCodeEnum.INVALID_DN_SYNTAX) || (code == ResultCodeEnum.ALIAS_DEREFERENCING_PROBLEM))) { + result.setMatchedDn(dn); } - result.setDiagnosticMessage( msg ); - bindRequest.getResultResponse().addAllControls( bindContext.getResponseControls() ); + result.setDiagnosticMessage(msg); + bindRequest.getResultResponse().addAllControls(bindContext.getResponseControls()); // Before writing the response, be sure the session is set to anonymous ldapSession.setAnonymous(); // Write the response - ldapSession.getIoSession().write( bindRequest.getResultResponse() ); - } - finally - { + ldapSession.getIoSession().write(bindRequest.getResultResponse()); + } finally { // Reset LDAP session bind status to anonymous if authentication failed - if ( !ldapSession.isAuthenticated() ) - { + if (!ldapSession.isAuthenticated()) { ldapSession.setAnonymous(); } } } - /** * Check if the mechanism exists. */ - private boolean checkMechanism( String saslMechanism ) throws Exception - { + private boolean checkMechanism(String saslMechanism) throws Exception { // Guard clause: Reject unsupported SASL mechanisms. - if ( !ldapServer.getSupportedMechanisms().contains( saslMechanism ) ) - { - LOG.error( I18n.err( I18n.ERR_160, saslMechanism ) ); + if (!ldapServer.getSupportedMechanisms().contains(saslMechanism)) { + LOG.error(I18n.err(I18n.ERR_160, saslMechanism)); return false; - } - else - { + } else { return true; } } - /** - * For challenge/response exchange, generate the challenge. - * If the exchange is complete then send bind success. + * For challenge/response exchange, generate the challenge. If the exchange is complete then send bind success. * * @param ldapSession * @param ss * @param bindRequest */ - private void generateSaslChallengeOrComplete( LdapSession ldapSession, SaslServer ss, - BindRequest bindRequest ) throws Exception - { + private void generateSaslChallengeOrComplete(LdapSession ldapSession, SaslServer ss, + BindRequest bindRequest) throws Exception { LdapResult result = bindRequest.getResultResponse().getLdapResult(); // SaslServer will throw an exception if the credentials are null. - if ( bindRequest.getCredentials() == null ) - { - bindRequest.setCredentials( StringConstants.EMPTY_BYTES ); + if (bindRequest.getCredentials() == null) { + bindRequest.setCredentials(StringConstants.EMPTY_BYTES); } - try - { + try { // Compute the challenge - byte[] tokenBytes = ss.evaluateResponse( bindRequest.getCredentials() ); + byte[] tokenBytes = ss.evaluateResponse(bindRequest.getCredentials()); - if ( ss.isComplete() ) - { + if (ss.isComplete()) { // This is the end of the C/R exchange - if ( tokenBytes != null ) - { + if (tokenBytes != null) { /* * There may be a token to return to the client. We set it here * so it will be returned in a SUCCESS message, after an LdapContext * has been initialized for the client. */ - ldapSession.putSaslProperty( SaslConstants.SASL_CREDS, tokenBytes ); + ldapSession.putSaslProperty(SaslConstants.SASL_CREDS, tokenBytes); } - LdapPrincipal ldapPrincipal = ( LdapPrincipal ) ldapSession - .getSaslProperty( SaslConstants.SASL_AUTHENT_USER ); + LdapPrincipal ldapPrincipal = (LdapPrincipal) ldapSession + .getSaslProperty(SaslConstants.SASL_AUTHENT_USER); - if ( ldapPrincipal != null ) - { + if (ldapPrincipal != null) { DirectoryService ds = ldapSession.getLdapServer().getDirectoryService(); String saslMechanism = bindRequest.getSaslMechanism(); byte[] password = null; - if ( ldapPrincipal.getUserPasswords() != null ) - { + if (ldapPrincipal.getUserPasswords() != null) { password = ldapPrincipal.getUserPasswords()[0]; } - CoreSession userSession = ds.getSession( ldapPrincipal.getDn(), - password, saslMechanism, null ); + CoreSession userSession = ds.getSession(ldapPrincipal.getDn(), + password, saslMechanism, null); // Set the user session into the ldap session - ldapSession.setCoreSession( userSession ); + ldapSession.setCoreSession(userSession); // Store the IoSession in the coreSession - ( ( DefaultCoreSession ) userSession ).setIoSession( ldapSession.getIoSession() ); + ((DefaultCoreSession) userSession).setIoSession(ldapSession.getIoSession()); } // Mark the user as authenticated ldapSession.setAuthenticated(); // Call the cleanup method for the selected mechanism - MechanismHandler handler = ( MechanismHandler ) ldapSession - .getSaslProperty( SaslConstants.SASL_MECH_HANDLER ); - handler.cleanup( ldapSession ); + MechanismHandler handler = (MechanismHandler) ldapSession + .getSaslProperty(SaslConstants.SASL_MECH_HANDLER); + handler.cleanup(ldapSession); // Return the successful response - sendBindSuccess( ldapSession, bindRequest, tokenBytes ); - } - else - { + sendBindSuccess(ldapSession, bindRequest, tokenBytes); + } else { // The SASL bind must continue, we are sending the computed challenge - LOG.info( "Continuation token had length " + tokenBytes.length ); + LOG.info("Continuation token had length " + tokenBytes.length); // Build the response - result.setResultCode( ResultCodeEnum.SASL_BIND_IN_PROGRESS ); - BindResponse resp = ( BindResponse ) bindRequest.getResultResponse(); + result.setResultCode(ResultCodeEnum.SASL_BIND_IN_PROGRESS); + BindResponse resp = (BindResponse) bindRequest.getResultResponse(); // Store the challenge - resp.setServerSaslCreds( tokenBytes ); + resp.setServerSaslCreds(tokenBytes); // Switch to SASLAuthPending ldapSession.setSaslAuthPending(); // And write back the response - ldapSession.getIoSession().write( resp ); + ldapSession.getIoSession().write(resp); - LOG.debug( "Returning final authentication data to client to complete context." ); + LOG.debug("Returning final authentication data to client to complete context."); } - } - catch ( SaslException se ) - { - sendInvalidCredentials( ldapSession, bindRequest, se ); + } catch (SaslException se) { + sendInvalidCredentials(ldapSession, bindRequest, se); } } - /** * Send back an AUTH-METH-NOT-SUPPORTED error message to the client */ - private void sendAuthMethNotSupported( LdapSession ldapSession, BindRequest bindRequest ) - { + private void sendAuthMethNotSupported(LdapSession ldapSession, BindRequest bindRequest) { // First, r-einit the state to Anonymous, and clear the // saslProperty map ldapSession.clearSaslProperties(); @@ -396,151 +364,120 @@ private void sendAuthMethNotSupported( LdapSession ldapSession, BindRequest bind // And send the response to the client LdapResult bindResult = bindRequest.getResultResponse().getLdapResult(); - bindResult.setResultCode( ResultCodeEnum.AUTH_METHOD_NOT_SUPPORTED ); - bindResult.setDiagnosticMessage( ResultCodeEnum.AUTH_METHOD_NOT_SUPPORTED.toString() + ": " - + bindRequest.getSaslMechanism() + " is not a supported mechanism." ); + bindResult.setResultCode(ResultCodeEnum.AUTH_METHOD_NOT_SUPPORTED); + bindResult.setDiagnosticMessage(ResultCodeEnum.AUTH_METHOD_NOT_SUPPORTED.toString() + ": " + + bindRequest.getSaslMechanism() + " is not a supported mechanism."); // Write back the error - ldapSession.getIoSession().write( bindRequest.getResultResponse() ); + ldapSession.getIoSession().write(bindRequest.getResultResponse()); } - /** - * Send back an INVALID-CREDENTIAL error message to the user. If we have an exception - * as a third argument, then send back the associated message to the client. + * Send back an INVALID-CREDENTIAL error message to the user. If we have an exception as a third argument, then send back the associated message to the + * client. */ - private void sendInvalidCredentials( LdapSession ldapSession, BindRequest bindRequest, Exception e ) - { + private void sendInvalidCredentials(LdapSession ldapSession, BindRequest bindRequest, Exception e) { LdapResult result = bindRequest.getResultResponse().getLdapResult(); String message = ""; - if ( e != null ) - { + if (e != null) { message = ResultCodeEnum.INVALID_CREDENTIALS + ": " + e.getLocalizedMessage(); - } - else - { + } else { message = ResultCodeEnum.INVALID_CREDENTIALS.toString(); } - LOG.error( message ); - result.setResultCode( ResultCodeEnum.INVALID_CREDENTIALS ); - result.setDiagnosticMessage( message ); + LOG.error(message); + result.setResultCode(ResultCodeEnum.INVALID_CREDENTIALS); + result.setDiagnosticMessage(message); // Reinitialize the state to Anonymous and clear the sasl properties ldapSession.clearSaslProperties(); ldapSession.setAnonymous(); // Write back the error response - ldapSession.getIoSession().write( bindRequest.getResultResponse() ); + ldapSession.getIoSession().write(bindRequest.getResultResponse()); } - /** * Send a SUCCESS message back to the client. */ - private void sendBindSuccess( LdapSession ldapSession, BindRequest bindRequest, byte[] tokenBytes ) - { + private void sendBindSuccess(LdapSession ldapSession, BindRequest bindRequest, byte[] tokenBytes) { // Return the successful response - BindResponse response = ( BindResponse ) bindRequest.getResultResponse(); - response.getLdapResult().setResultCode( ResultCodeEnum.SUCCESS ); - response.setServerSaslCreds( tokenBytes ); + BindResponse response = (BindResponse) bindRequest.getResultResponse(); + response.getLdapResult().setResultCode(ResultCodeEnum.SUCCESS); + response.setServerSaslCreds(tokenBytes); - if ( !ldapSession.getCoreSession().isAnonymous() ) - { + if (!ldapSession.getCoreSession().isAnonymous()) { // If we have not been asked to authenticate as Anonymous, authenticate the user ldapSession.setAuthenticated(); - } - else - { + } else { // Otherwise, switch back to Anonymous ldapSession.setAnonymous(); } // Clean the SaslProperties, we don't need them anymore - MechanismHandler handler = ( MechanismHandler ) ldapSession.getSaslProperty( SaslConstants.SASL_MECH_HANDLER ); + MechanismHandler handler = (MechanismHandler) ldapSession.getSaslProperty(SaslConstants.SASL_MECH_HANDLER); - if ( handler != null ) - { - handler.cleanup( ldapSession ); + if (handler != null) { + handler.cleanup(ldapSession); } - ldapSession.getIoSession().write( response ); + ldapSession.getIoSession().write(response); - LOG.debug( "Returned SUCCESS message: {}.", response ); + LOG.debug("Returned SUCCESS message: {}.", response); } - - private void handleSaslAuthPending( LdapSession ldapSession, BindRequest bindRequest ) throws Exception - { + private void handleSaslAuthPending(LdapSession ldapSession, BindRequest bindRequest) throws Exception { // First, check that we have the same mechanism String saslMechanism = bindRequest.getSaslMechanism(); // The empty mechanism is also a request for a new Bind session - if ( Strings.isEmpty( saslMechanism ) - || !ldapSession.getSaslProperty( SaslConstants.SASL_MECH ).equals( saslMechanism ) ) - { - sendAuthMethNotSupported( ldapSession, bindRequest ); + if (Strings.isEmpty(saslMechanism) + || !ldapSession.getSaslProperty(SaslConstants.SASL_MECH).equals(saslMechanism)) { + sendAuthMethNotSupported(ldapSession, bindRequest); return; } // We have already received a first BindRequest, and sent back some challenge. // First, check if the mechanism is the same - MechanismHandler mechanismHandler = handlers.get( saslMechanism ); + MechanismHandler mechanismHandler = handlers.get(saslMechanism); - if ( mechanismHandler == null ) - { - String message = I18n.err( I18n.ERR_161, saslMechanism ); + if (mechanismHandler == null) { + String message = I18n.err(I18n.ERR_161, saslMechanism); // Clear the saslProperties, and move to the anonymous state ldapSession.clearSaslProperties(); ldapSession.setAnonymous(); - LOG.error( message ); - throw new IllegalArgumentException( message ); + LOG.error(message); + throw new IllegalArgumentException(message); } // Get the previously created SaslServer instance - SaslServer ss = mechanismHandler.handleMechanism( ldapSession, bindRequest ); + SaslServer ss = mechanismHandler.handleMechanism(ldapSession, bindRequest); - generateSaslChallengeOrComplete( ldapSession, ss, bindRequest ); + generateSaslChallengeOrComplete(ldapSession, ss, bindRequest); } - /** - * Handle the SASL authentication. If the mechanism is known, we are - * facing three cases : - *

    - *
  • The user does not has a session yet
  • - *
  • The user already has a session
  • - *
  • The user has started a SASL negotiation
  • - *
    - * - * In the first case, we initiate a SaslBind session, which will be used all - * along the negotiation.
    - * In the second case, we first have to unbind the user, and initiate a new - * SaslBind session.
    - * In the third case, we have sub cases : - *
      - *
    • The mechanism is not provided : that means the user want to reset the - * current negotiation. We move back to an Anonymous state
    • - *
    • The mechanism is provided : the user is initializing a new negotiation - * with another mechanism. The current SaslBind session is reinitialized
    • - *
    • - *

    + * Handle the SASL authentication. If the mechanism is known, we are facing three cases :
    • The user does not has a session yet
    • The user + * already has a session
    • The user has started a SASL negotiation

    • + *

      + * In the first case, we initiate a SaslBind session, which will be used all along the negotiation.
      In the second case, we first have to unbind the + * user, and initiate a new SaslBind session.
      In the third case, we have sub cases :

      • The mechanism is not provided : that means the user want + * to reset the current negotiation. We move back to an Anonymous state
      • The mechanism is provided : the user is initializing a new negotiation with + * another mechanism. The current SaslBind session is reinitialized

      * * @param ldapSession The associated Session * @param bindRequest The BindRequest received * @throws Exception If the authentication cannot be done */ - public void handleSaslAuth( LdapSession ldapSession, BindRequest bindRequest ) throws Exception - { + public void handleSaslAuth(LdapSession ldapSession, BindRequest bindRequest) throws Exception { String saslMechanism = bindRequest.getSaslMechanism(); // Case #2 : the user does have a session. We have to unbind him - if ( ldapSession.isAuthenticated() ) - { + if (ldapSession.isAuthenticated()) { // We already have a bound session for this user. We have to // close the previous session first. ldapSession.getCoreSession().unbind(); @@ -555,84 +492,71 @@ public void handleSaslAuth( LdapSession ldapSession, BindRequest bindRequest ) t } // case #1 : The user does not have a session. - if ( ldapSession.isAnonymous() ) - { + if (ldapSession.isAnonymous()) { // fist check that the mechanism exists - if ( !checkMechanism( saslMechanism ) ) - { + if (!checkMechanism(saslMechanism)) { // get out ! - sendAuthMethNotSupported( ldapSession, bindRequest ); + sendAuthMethNotSupported(ldapSession, bindRequest); return; } // Store the mechanism in the ldap session - ldapSession.putSaslProperty( SaslConstants.SASL_MECH, saslMechanism ); + ldapSession.putSaslProperty(SaslConstants.SASL_MECH, saslMechanism); // Get the handler for this mechanism - MechanismHandler mechanismHandler = handlers.get( saslMechanism ); + MechanismHandler mechanismHandler = handlers.get(saslMechanism); // Store the mechanism handler in the salsProperties - ldapSession.putSaslProperty( SaslConstants.SASL_MECH_HANDLER, mechanismHandler ); + ldapSession.putSaslProperty(SaslConstants.SASL_MECH_HANDLER, mechanismHandler); // Initialize the mechanism specific data - mechanismHandler.init( ldapSession ); + mechanismHandler.init(ldapSession); // Get the SaslServer instance which manage the C/R exchange - SaslServer ss = mechanismHandler.handleMechanism( ldapSession, bindRequest ); + SaslServer ss = mechanismHandler.handleMechanism(ldapSession, bindRequest); // We have to generate a challenge - generateSaslChallengeOrComplete( ldapSession, ss, bindRequest ); + generateSaslChallengeOrComplete(ldapSession, ss, bindRequest); // And get back return; - } - else if ( ldapSession.isAuthPending() ) - { - try - { - handleSaslAuthPending( ldapSession, bindRequest ); - } - catch ( SaslException se ) - { - sendInvalidCredentials( ldapSession, bindRequest, se ); + } else if (ldapSession.isAuthPending()) { + try { + handleSaslAuthPending(ldapSession, bindRequest); + } catch (SaslException se) { + sendInvalidCredentials(ldapSession, bindRequest, se); } return; } } - /** * Deal with a received BindRequest - * + * * @param ldapSession The current session * @param bindRequest The received BindRequest * @throws Exception If the authentication cannot be handled */ - public void handle( LdapSession ldapSession, BindRequest bindRequest ) throws Exception - { - LOG.debug( "Received: {}", bindRequest ); + public void handle(LdapSession ldapSession, BindRequest bindRequest) throws Exception { + LOG.debug("Received: {}", bindRequest); // Guard clause: LDAP version 3 - if ( !bindRequest.getVersion3() ) - { - LOG.error( I18n.err( I18n.ERR_162 ) ); + if (!bindRequest.getVersion3()) { + LOG.error(I18n.err(I18n.ERR_162)); LdapResult bindResult = bindRequest.getResultResponse().getLdapResult(); - bindResult.setResultCode( ResultCodeEnum.PROTOCOL_ERROR ); - bindResult.setDiagnosticMessage( I18n.err( I18n.ERR_163 ) ); - ldapSession.getIoSession().write( bindRequest.getResultResponse() ); + bindResult.setResultCode(ResultCodeEnum.PROTOCOL_ERROR); + bindResult.setDiagnosticMessage(I18n.err(I18n.ERR_163)); + ldapSession.getIoSession().write(bindRequest.getResultResponse()); return; } // Deal with the two kinds of authentication : Simple and SASL - if ( bindRequest.isSimple() ) - { - handleSimpleAuth( ldapSession, bindRequest ); - } - else - { - handleSaslAuth( ldapSession, bindRequest ); + if (bindRequest.isSimple()) { + handleSimpleAuth(ldapSession, bindRequest); + } else { + handleSaslAuth(ldapSession, bindRequest); } } } diff --git a/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java b/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java new file mode 100644 index 0000000..8826c45 --- /dev/null +++ b/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java @@ -0,0 +1,157 @@ +/* + * Copyright 2008 Marc Boorshtein + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sourceforge.myvd.test.Server; + +import java.nio.charset.Charset; + +import net.sourceforge.myvd.test.util.OpenLDAPUtils; +import net.sourceforge.myvd.test.util.StartMyVD; +import net.sourceforge.myvd.test.util.StartOpenLDAP; + +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPException; +import com.novell.ldap.LDAPSearchResults; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.fail; + +public class TestStartServerAuthRequired { + + private static StartOpenLDAP baseServer; + private static StartOpenLDAP internalServer; + private static StartOpenLDAP externalServer; + private static StartMyVD server; + + @BeforeClass + public static void setUp() throws Exception { + OpenLDAPUtils.killAllOpenLDAPS(); + baseServer = new StartOpenLDAP(); + baseServer.startServer(System.getenv("PROJ_DIR") + "/test/Base", 10983, "cn=admin,dc=domain,dc=com", "manager"); + + internalServer = new StartOpenLDAP(); + internalServer.startServer(System.getenv("PROJ_DIR") + "/test/InternalUsers", 11983, + "cn=admin,ou=internal,dc=domain,dc=com", "manager"); + + externalServer = new StartOpenLDAP(); + externalServer.startServer(System.getenv("PROJ_DIR") + "/test/ExternalUsers", 12983, + "cn=admin,ou=external,dc=domain,dc=com", "manager"); + + server = new StartMyVD(); + server.startServer(System.getenv("PROJ_DIR") + "/test/TestServer/testconfig-required-auth.props", 50983); + + System.setProperty("javax.net.ssl.trustStore", System.getenv("PROJ_DIR") + "/test/TestServer/testconfig.jks"); + } + + @After + public void after() throws Exception { + baseServer.reloadAllData(); + internalServer.reloadAllData(); + externalServer.reloadAllData(); + } + + @Test + public void testStartServer_BindWithCredentialsShouldPass() throws Exception { + LDAPConnection con = new LDAPConnection(); + try { + con.connect("127.0.0.1", 50983); + + con.bind(3, "cn=admin,ou=internal,o=mycompany,c=us", "manager".getBytes(Charset.forName("UTF-8"))); + + LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false); + while (res.hasMore()) { + System.out.println(res.next().getDN()); + } + + } finally { + con.disconnect(); + } + } + + @Test + public void testStartServer_BindWithInvalidPasswordShouldFail() throws Exception { + LDAPConnection con = new LDAPConnection(); + try { + con.connect("127.0.0.1", 50983); + + con.bind(3, "cn=admin,ou=internal,o=mycompany,c=us", "xxx".getBytes(Charset.forName("UTF-8"))); + + LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false); + while (res.hasMore()) { + System.out.println(res.next().getDN()); + } + } catch (LDAPException e) { + if (e.getResultCode() != 49) { + fail(); + } + } finally { + con.disconnect(); + } + } + + @Test + public void testStartServer_BindWithInvalidUserShouldFail() throws Exception { + LDAPConnection con = new LDAPConnection(); + try { + con.connect("127.0.0.1", 50983); + + con.bind(3, "cn=xxx,ou=internal,o=mycompany,c=us", "xxx".getBytes(Charset.forName("UTF-8"))); + + LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false); + while (res.hasMore()) { + System.out.println(res.next().getDN()); + } + } catch (LDAPException e) { + if (e.getResultCode() != 49) { + fail(); + } + } finally { + con.disconnect(); + } + } + + @Test + public void testStartServer_BindWithoutCredentialsShouldFail() throws Exception { + LDAPConnection con = new LDAPConnection(); + try { + con.connect("127.0.0.1", 50983); + + con.bind(3, null, new byte[0]); + + LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false); + while (res.hasMore()) { + System.out.println(res.next().getDN()); + } + } catch (LDAPException e) { + if (e.getResultCode() != 49) { + fail(); + } + } finally { + con.disconnect(); + } + } + + @AfterClass + public static void tearDown() throws Exception { + baseServer.stopServer(); + internalServer.stopServer(); + externalServer.stopServer(); + server.stopServer(); + } +} \ No newline at end of file diff --git a/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerHost.java b/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerHost.java new file mode 100644 index 0000000..1aeab13 --- /dev/null +++ b/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerHost.java @@ -0,0 +1,109 @@ +/* + * Copyright 2008 Marc Boorshtein + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sourceforge.myvd.test.Server; + +import java.nio.charset.Charset; + +import net.sourceforge.myvd.test.util.OpenLDAPUtils; +import net.sourceforge.myvd.test.util.StartMyVD; +import net.sourceforge.myvd.test.util.StartOpenLDAP; + +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPSearchResults; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class TestStartServerHost { + + private static StartOpenLDAP baseServer; + private static StartOpenLDAP internalServer; + private static StartOpenLDAP externalServer; + private static StartMyVD server; + + @BeforeClass + public static void setUp() throws Exception { + OpenLDAPUtils.killAllOpenLDAPS(); + baseServer = new StartOpenLDAP(); + baseServer.startServer(System.getenv("PROJ_DIR") + "/test/Base", 10983, "cn=admin,dc=domain,dc=com", "manager"); + + internalServer = new StartOpenLDAP(); + internalServer.startServer(System.getenv("PROJ_DIR") + "/test/InternalUsers", 11983, + "cn=admin,ou=internal,dc=domain,dc=com", "manager"); + + externalServer = new StartOpenLDAP(); + externalServer.startServer(System.getenv("PROJ_DIR") + "/test/ExternalUsers", 12983, + "cn=admin,ou=external,dc=domain,dc=com", "manager"); + + server = new StartMyVD(); + server.startServer(System.getenv("PROJ_DIR") + "/test/TestServer/testconfig-host.props", 50983); + + System.setProperty("javax.net.ssl.trustStore", System.getenv("PROJ_DIR") + "/test/TestServer/testconfig.jks"); + } + + @After + public void after() throws Exception { + baseServer.reloadAllData(); + internalServer.reloadAllData(); + externalServer.reloadAllData(); + } + + @Test + public void testStartServer_BindWithCredentials() throws Exception { + LDAPConnection con = new LDAPConnection(); + try { + con.connect("127.0.0.1", 50983); + + con.bind(3, "cn=admin,ou=internal,o=mycompany,c=us", "manager".getBytes(Charset.forName("UTF-8"))); + + LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false); + while (res.hasMore()) { + System.out.println(res.next().getDN()); + } + + } finally { + con.disconnect(); + } + } + + @Test + public void testStartServer_BindWithoutCredentials() throws Exception { + LDAPConnection con = new LDAPConnection(); + try { + con.connect("127.0.0.1", 50983); + + con.bind(3, null, new byte[0]); + + LDAPSearchResults res = con.search("ou=internal,o=mycompany,c=us", 2, "(objectClass=*)", new String[0], false); + while (res.hasMore()) { + System.out.println(res.next().getDN()); + } + + } finally { + con.disconnect(); + } + } + + @AfterClass + public static void tearDown() throws Exception { + baseServer.stopServer(); + internalServer.stopServer(); + externalServer.stopServer(); + server.stopServer(); + } +} diff --git a/test/TestServer/testconfig-host.props b/test/TestServer/testconfig-host.props new file mode 100644 index 0000000..c59d580 --- /dev/null +++ b/test/TestServer/testconfig-host.props @@ -0,0 +1,27 @@ +server.listener.port=50983 +server.listener.host=127.0.0.1 + +server.nameSpaces=InternalServer,ExternalServer + +server.InternalServer.chain=LDAPInternalServer +server.InternalServer.nameSpace=ou=internal,o=mycompany,c=us +server.InternalServer.weight=10 + +server.InternalServer.LDAPInternalServer.className=net.sourceforge.myvd.inserts.ldap.LDAPInterceptor +server.InternalServer.LDAPInternalServer.config.host=127.0.0.1 +server.InternalServer.LDAPInternalServer.config.port=11983 +server.InternalServer.LDAPInternalServer.config.remoteBase=ou=internal,dc=domain,dc=com +server.InternalServer.LDAPInternalServer.config.proxyDN=cn=admin,ou=internal,dc=domain,dc=com +server.InternalServer.LDAPInternalServer.config.proxyPass=manager + + +server.ExternalServer.chain=LDAPExternalServer +server.ExternalServer.nameSpace=ou=external,o=mycompany,c=us +server.ExternalServer.weight=15 + +server.ExternalServer.LDAPExternalServer.className=net.sourceforge.myvd.inserts.ldap.LDAPInterceptor +server.ExternalServer.LDAPExternalServer.config.host=localhost +server.ExternalServer.LDAPExternalServer.config.port=12983 +server.ExternalServer.LDAPExternalServer.config.remoteBase=ou=external,dc=domain,dc=com +server.ExternalServer.LDAPExternalServer.config.proxyDN=cn=admin,ou=external,dc=domain,dc=com +server.ExternalServer.LDAPExternalServer.config.proxyPass=manager diff --git a/test/TestServer/testconfig-required-auth.props b/test/TestServer/testconfig-required-auth.props new file mode 100644 index 0000000..577f33c --- /dev/null +++ b/test/TestServer/testconfig-required-auth.props @@ -0,0 +1,27 @@ +server.listener.port=50983 +server.listener.authRequired=true + +server.nameSpaces=InternalServer,ExternalServer + +server.InternalServer.chain=LDAPInternalServer +server.InternalServer.nameSpace=ou=internal,o=mycompany,c=us +server.InternalServer.weight=10 + +server.InternalServer.LDAPInternalServer.className=net.sourceforge.myvd.inserts.ldap.LDAPInterceptor +server.InternalServer.LDAPInternalServer.config.host=127.0.0.1 +server.InternalServer.LDAPInternalServer.config.port=11983 +server.InternalServer.LDAPInternalServer.config.remoteBase=ou=internal,dc=domain,dc=com +server.InternalServer.LDAPInternalServer.config.proxyDN=cn=admin,ou=internal,dc=domain,dc=com +server.InternalServer.LDAPInternalServer.config.proxyPass=manager + + +server.ExternalServer.chain=LDAPExternalServer +server.ExternalServer.nameSpace=ou=external,o=mycompany,c=us +server.ExternalServer.weight=15 + +server.ExternalServer.LDAPExternalServer.className=net.sourceforge.myvd.inserts.ldap.LDAPInterceptor +server.ExternalServer.LDAPExternalServer.config.host=localhost +server.ExternalServer.LDAPExternalServer.config.port=12983 +server.ExternalServer.LDAPExternalServer.config.remoteBase=ou=external,dc=domain,dc=com +server.ExternalServer.LDAPExternalServer.config.proxyDN=cn=admin,ou=external,dc=domain,dc=com +server.ExternalServer.LDAPExternalServer.config.proxyPass=manager From e17a388092ae6640b94414de48600e0a4f542524 Mon Sep 17 00:00:00 2001 From: mlbiam Date: Fri, 1 Feb 2019 10:16:17 -0500 Subject: [PATCH 4/5] for #44 fixed test cases --- .../Server/TestStartServerAuthRequired.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java b/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java index 8826c45..0be0eb1 100644 --- a/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java +++ b/src/test/java/net/sourceforge/myvd/test/Server/TestStartServerAuthRequired.java @@ -30,6 +30,7 @@ import org.junit.BeforeClass; import org.junit.Test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class TestStartServerAuthRequired { @@ -96,10 +97,10 @@ public void testStartServer_BindWithInvalidPasswordShouldFail() throws Exception while (res.hasMore()) { System.out.println(res.next().getDN()); } + + fail(); } catch (LDAPException e) { - if (e.getResultCode() != 49) { - fail(); - } + assertEquals(LDAPException.INVALID_CREDENTIALS,e.getResultCode()); } finally { con.disconnect(); } @@ -117,10 +118,10 @@ public void testStartServer_BindWithInvalidUserShouldFail() throws Exception { while (res.hasMore()) { System.out.println(res.next().getDN()); } + + fail(); } catch (LDAPException e) { - if (e.getResultCode() != 49) { - fail(); - } + assertEquals(LDAPException.INVALID_CREDENTIALS,e.getResultCode()); } finally { con.disconnect(); } @@ -138,10 +139,9 @@ public void testStartServer_BindWithoutCredentialsShouldFail() throws Exception while (res.hasMore()) { System.out.println(res.next().getDN()); } + fail(); } catch (LDAPException e) { - if (e.getResultCode() != 49) { - fail(); - } + assertEquals(LDAPException.AUTH_METHOD_NOT_SUPPORTED,e.getResultCode()); } finally { con.disconnect(); } From dbb26b07f49698a3b7148a1ca0184be7dde3ffc9 Mon Sep 17 00:00:00 2001 From: mlbiam Date: Wed, 6 Feb 2019 07:01:39 -0500 Subject: [PATCH 5/5] for #51 removed flagged deps --- .factorypath | 32 ++ .vscode/launch.json | 41 ++ .vscode/launch.test.json | 30 ++ pom.xml | 4 +- .../proxy/myvd/inserts/util/UUIDtoText.java | 2 +- .../myvd/quickstart/ADQuickStart.java | 439 ------------------ .../myvd/quickstart/ADQuickStartJDBC.java | 435 ----------------- .../myvd/quickstart/util/GetSSLCert.java | 317 ------------- 8 files changed, 106 insertions(+), 1194 deletions(-) create mode 100644 .factorypath create mode 100644 .vscode/launch.json create mode 100644 .vscode/launch.test.json delete mode 100644 src/main/java/net/sourceforge/myvd/quickstart/ADQuickStart.java delete mode 100644 src/main/java/net/sourceforge/myvd/quickstart/ADQuickStartJDBC.java delete mode 100644 src/main/java/net/sourceforge/myvd/quickstart/util/GetSSLCert.java diff --git a/.factorypath b/.factorypath new file mode 100644 index 0000000..3ad879f --- /dev/null +++ b/.factorypath @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..a88c189 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,41 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "java", + "name": "JUnit", + "request": "launch", + "cwd": "${workspaceRoot}", + "projectName": "myvd-server", + "mainClass": "org.junit.runner.JUnitCore", + "args": "net.sourceforge.myvd.test.join.TestJoin", + "sourcePaths": [ + "${workspaceRoot}" + ], + "env": { + + "PROJ_DIR":"/home/mlb/git/MyVirtualDirectory", + "SCHEMA_DIR":"/etc/openldap", + "SLAPD_PATH":"/usr/sbin", + + "TMP_DIR":"/tmp/ldap" + }, + "vmArgs" : "-Dlog4j.configurationFile=/home/mlb/git/OpenUnison/unison/open-unison-webapp/src/main/webapp/WEB-INF/classes/log4j2.xml" + + + + + + }, + { + "type": "java", + "name": "Debug (Attach)", + "request": "attach", + "hostName": "localhost", + "port": 5005 + } + ] +} \ No newline at end of file diff --git a/.vscode/launch.test.json b/.vscode/launch.test.json new file mode 100644 index 0000000..12d7169 --- /dev/null +++ b/.vscode/launch.test.json @@ -0,0 +1,30 @@ +{ + "run": { + "default": "", + "items": [ + { + "name": "myvd-server", + "projectName": "myvd-server", + "workingDirectory": "/Users/mlb/git/MyVirtualDirectory", + "args": [], + "vmargs": [], + "env": {}, + "preLaunchTask": "" + } + ] + }, + "debug": { + "default": "", + "items": [ + { + "name": "myvd-server", + "projectName": "myvd-server", + "workingDirectory": "/Users/mlb/git/MyVirtualDirectory", + "args": [], + "vmargs": [], + "env": {}, + "preLaunchTask": "" + } + ] + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index fd9c486..771fcf0 100644 --- a/pom.xml +++ b/pom.xml @@ -69,11 +69,11 @@ - + hsqldb hsqldb diff --git a/src/main/java/com/tremolosecurity/proxy/myvd/inserts/util/UUIDtoText.java b/src/main/java/com/tremolosecurity/proxy/myvd/inserts/util/UUIDtoText.java index cc8675d..570578d 100644 --- a/src/main/java/com/tremolosecurity/proxy/myvd/inserts/util/UUIDtoText.java +++ b/src/main/java/com/tremolosecurity/proxy/myvd/inserts/util/UUIDtoText.java @@ -26,7 +26,7 @@ import java.util.Properties; import java.util.UUID; -import org.apache.commons.codec.binary.Hex; + import org.apache.logging.log4j.Logger; import com.novell.ldap.LDAPAttribute; diff --git a/src/main/java/net/sourceforge/myvd/quickstart/ADQuickStart.java b/src/main/java/net/sourceforge/myvd/quickstart/ADQuickStart.java deleted file mode 100644 index fe699cf..0000000 --- a/src/main/java/net/sourceforge/myvd/quickstart/ADQuickStart.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright 2008 Marc Boorshtein - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sourceforge.myvd.quickstart; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringReader; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.StringTokenizer; - -import javax.security.cert.CertificateEncodingException; -import javax.security.cert.X509Certificate; - -import net.sourceforge.myvd.quickstart.util.GetSSLCert; -import net.sourceforge.myvd.test.util.StreamReader; -import net.sourceforge.myvd.test.util.StreamWriter; - -public class ADQuickStart { - - /** - * @param args - * @throws IOException - * @throws ClassNotFoundException - * @throws IllegalAccessException - * @throws InstantiationException - * @throws SQLException - */ - public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - - String myVDHome = args[0]; - - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - String ksPath = myVDHome + "/conf/myvd-server.ks"; - String ksPass; - - String dnServer; - String dnOu; - String dnO; - String dnL; - String dnState; - String dnC; - - String dn; - String keyTool = System.getProperty("java.home") + File.separator + "bin" + File.separator + "keytool"; - System.err.println(keyTool); - String cacerts = System.getProperty("java.home") + File.separator + "lib" + File.separator + "security" + File.separator + "cacerts"; - - HashMap vars = new HashMap(); - - vars.put("MYVD_HOME", myVDHome); - - //System.out.println("MyVirtualDirectory Active Directory Quick-Start"); - //System.out.println("==============================================="); - - //System.out.println("This quick start will guide you through building out a virtual directory "); - //System.out.println("that will expose an Active Directory domain for use by a Linux system.\n\n"); - - //System.out.println("In order to move forward you will need:"); - //System.out.println("ActiveDirectory Domain Controller hostname or ip"); - //System.out.println("ActiveDirectory user with no search restrictions"); - - //System.out.println("Creating MyVirtualDirectory Keystore..."); - - String srcKsPwd = getPassword("CACERTS Password (usually 'changeit')",in); - ksPass = getPassword("MyVirtualDirectory Keystore Password",in); - - ProcessBuilder pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - ArrayList cmd = new ArrayList(); - cmd.add(keyTool); - cmd.add("-importkeystore"); - cmd.add("-srckeystore"); - cmd.add(cacerts); - cmd.add("-destkeystore"); - cmd.add(ksPath); - cmd.add("-deststorepass"); - cmd.add(ksPass); - cmd.add("-srcstorepass"); - cmd.add(srcKsPwd); - cmd.add("-noprompt"); - - - pb.command(cmd); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool -genkeypair -v -keystore /home/mlb/test.ks -alias selfsigned -keyalg rsa -keysize 1024 -validity 365"); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool"); - - Process process = pb.start(); - //Process process = Runtime.getRuntime().exec("/usr/java/jdk1.6.0_03/bin/keytool"); - - - //StreamReader errReader = new StreamReader(process.getErrorStream(),true); - StreamReader sr = new StreamReader(process.getInputStream(),true); - //StreamWriter sw = new StreamWriter(process.getInputStream(),new PrintWriter(process.getOutputStream())); - //sr.start(); - //errReader.start(); - sr.start(); - //System.setIn(process.getInputStream()); - - while (! sr.isDone()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - } - - //System.out.println("Keystore created"); - - String myvdBase = getInput("MyVirtualDirectory Base (ie ou=unix,o=mycompany)",in); - vars.put("VD_BASE", myvdBase); - - String myvdPort = getInput("MyVirtualDirectory Port (usualy 389)",in); - vars.put("VD_PORT", myvdPort); - - - - String adHost = getInput("Active Directroy Host",in); - vars.put("AD_HOST", adHost); - String adPort = getInput("Active Directroy Port (usualy 389)",in); - vars.put("AD_PORT", adPort); - String adIsSSL = getInput("Use SSL? (y/n)",in); - - String adDomain = getInput("Active Directory Domain Name",in); - String remoteBase = ""; - - StringTokenizer toker = new StringTokenizer(adDomain,".",false); - while (toker.hasMoreTokens()) { - remoteBase += "DC=" + toker.nextToken() + ","; - } - - remoteBase = remoteBase.substring(0,remoteBase.length() - 1); - - vars.put("AD_BASE", remoteBase); - - String adBase = getInput("User base (not including the domain, typically cn=users)",in); - vars.put("AD_USERS_BASE", adBase); - - String adSearchDN = getInput("Active Directory User DN (do not include the domain name, ie cn=MyVDUser,cn=Users)",in); - vars.put("AD_CRED", adSearchDN); - String adPassword = getPassword("Active Directory User Password",in); - vars.put("AD_PWD", adPassword); - - - if (adIsSSL.equalsIgnoreCase("y")) { - //System.out.println("Retrieving certificate parent from " + adHost + ":" + adPort + "..."); - X509Certificate cert = GetSSLCert.getCert(adHost, Integer.parseInt(adPort)); - - //System.out.println("Exporting certificate parent from " + adHost + ":" + adPort + "..."); - File f = new File(myVDHome + "/tmp.ad.der"); - FileOutputStream out = new FileOutputStream(f); - try { - out.write(cert.getEncoded()); - } catch (CertificateEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - out.flush(); - out.close(); - - //System.out.println("Import certificate parent from " + adHost + ":" + adPort + " into MyVirtualDirectory keystore..."); - - pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - cmd = new ArrayList(); - cmd.add(keyTool); - cmd.add("-importcert"); - cmd.add("-v"); - cmd.add("-keystore"); - cmd.add(ksPath); - cmd.add("-alias"); - cmd.add("ad-" + adHost + ":" + adPort); - cmd.add("-file"); - cmd.add(f.getAbsolutePath()); - cmd.add("-trustcacerts"); - cmd.add("-noprompt"); - cmd.add("-keypass"); - cmd.add(ksPass); - cmd.add("-storepass"); - cmd.add(ksPass); - - - pb.command(cmd); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool -genkeypair -v -keystore /home/mlb/test.ks -alias selfsigned -keyalg rsa -keysize 1024 -validity 365"); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool"); - - process = pb.start(); - //Process process = Runtime.getRuntime().exec("/usr/java/jdk1.6.0_03/bin/keytool"); - - - //StreamReader errReader = new StreamReader(process.getErrorStream(),true); - sr = new StreamReader(process.getInputStream(),true); - //StreamWriter sw = new StreamWriter(process.getInputStream(),new PrintWriter(process.getOutputStream())); - //sr.start(); - //errReader.start(); - sr.start(); - //System.setIn(process.getInputStream()); - - while (! sr.isDone()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - } - f.delete(); - //System.out.println("Import certificate parent from " + adHost + ":" + adPort + " into MyVirtualDirectory keystore complete"); - vars.put("AD_TYPE", "LDAPS"); - - } else { - vars.put("AD_TYPE", "LDAP"); - } - - String useKerb = getInput("Use Kerberos? (y/n)",in); - - if (useKerb.equalsIgnoreCase("y")) { - vars.put("AD_USE_KERB", "true"); - } else { - vars.put("AD_USE_KERB", "false"); - } - - - - - - - - - String createSelfSignedCert = getInput("Create a self signed certificate? (y/n)",in); - - - - - - if (createSelfSignedCert.equalsIgnoreCase("y")) { - //System.out.println("Creating a self signed SSL certificate..."); - - String myvdSecurePort = getInput("LDAPS Port (typically 636)",in); - - - - dnServer = getInput("Server Name",in); - dnOu = getInput("Org Unit",in); - dnO = getInput("Organization",in); - dnL = getInput("City/Locality",in); - dnState = getInput("State/Province",in); - dnC = getInput("2 Letter Country Code",in); - - dn = "CN=" + dnServer + ",OU=" + dnOu + ",O=" + dnO + ",L=" + dnL + ",ST=" + dnState + ",C=" + dnC; - - pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - cmd = new ArrayList(); - cmd.add(keyTool); - cmd.add("-genkeypair"); - cmd.add("-v"); - cmd.add("-keystore"); - cmd.add(ksPath); - cmd.add("-alias"); - cmd.add("selfsigned"); - cmd.add("-keyalg"); - cmd.add("rsa"); - cmd.add("-keysize"); - cmd.add("1024"); - cmd.add("-validity"); - cmd.add("365"); - cmd.add("-keypass"); - cmd.add(ksPass); - cmd.add("-storepass"); - cmd.add(ksPass); - - cmd.add("-dname"); - cmd.add(dn); - - pb.command(cmd); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool -genkeypair -v -keystore /home/mlb/test.ks -alias selfsigned -keyalg rsa -keysize 1024 -validity 365"); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool"); - - process = pb.start(); - //Process process = Runtime.getRuntime().exec("/usr/java/jdk1.6.0_03/bin/keytool"); - - - //StreamReader errReader = new StreamReader(process.getErrorStream(),true); - sr = new StreamReader(process.getInputStream(),true); - //StreamWriter sw = new StreamWriter(process.getInputStream(),new PrintWriter(process.getOutputStream())); - //sr.start(); - //errReader.start(); - sr.start(); - //System.setIn(process.getInputStream()); - - while (! sr.isDone()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - } - - vars.put("SSL_CFG", "#SSL Config\nserver.secure.listener.port=" + myvdSecurePort + "\nserver.secure.keystore=" + ksPath + "\nserver.secure.keypass=" + ksPass + "\n\n"); - - } else { - vars.put("SSL_CFG", ""); - } - - genConfig(myVDHome + "/quickStarts/ad2linux.conf",myVDHome + "/conf/myvd.conf",vars); - - File f = new File(myVDHome + "/derbyHome"); - f.mkdir(); - - System.getProperties().setProperty("derby.system.home", myVDHome + "/derbyHome"); - - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - Connection con = DriverManager.getConnection("jdbc:derby:myvdPosix;create=true"); - con.createStatement().execute("CREATE TABLE posixUsers (id int GENERATED ALWAYS AS IDENTITY (START WITH 500, INCREMENT BY 1),objectGuid varchar(255),homeDirectory varchar(255),loginShell varchar(255))"); - con.createStatement().execute("CREATE TABLE posixGroups (id int GENERATED ALWAYS AS IDENTITY (START WITH 500, INCREMENT BY 1),objectGuid varchar(255))"); - con.close(); - - try { - DriverManager.getConnection("jdbc:derby:myvdPosix;shutdown=true"); - } catch (Throwable t) { - //ignore? - } - - } - - public static String getInput(String label,BufferedReader in) throws IOException { - //System.out.print(label + " : "); - String data = in.readLine(); - - //System.out.print("Is \"" + data + "\" correct? (y/n) : "); - String resp = in.readLine(); - - while (! resp.equalsIgnoreCase("y")) { - //System.out.print(label + " : "); - data = in.readLine(); - - //System.out.print("Is \"" + data + "\" correct? (y/n) : "); - resp = in.readLine(); - } - - return data; - } - - public static String getPassword(String label,BufferedReader in) throws IOException { - //System.out.print(label + " : "); - String data = in.readLine(); - - //System.out.print("Please verify : "); - String resp = in.readLine(); - - while (! resp.equals(data)) { - //System.out.println("Passwords don't match"); - //System.out.print(label + " : "); - data = in.readLine(); - - //System.out.print("Please verify : "); - resp = in.readLine(); - } - - return data; - } - - public static void genConfig(String sourcePath,String resultPath,HashMap vars) throws IOException { - String cfgFile = ""; - BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sourcePath))); - String line; - - while ((line = br.readLine()) != null) { - cfgFile += line + "\n"; - } - - br.close(); - - Iterator keyIt = vars.keySet().iterator(); - - while (keyIt.hasNext()) { - String key = keyIt.next(); - String val = vars.get(key); - String skey = "%" + key + "%"; - boolean done = false; - - while (! done) { - int begin = cfgFile.indexOf(skey); - - if (begin == -1) { - done = true; - break; - } - - String tmp = cfgFile.substring(0,begin); - tmp += val; - tmp += cfgFile.substring(begin + skey.length()); - cfgFile = tmp; - } - - - - /*if (cfgFile.contains("%" + key + "%")) { - //System.out.println("key:" + key); - //System.out.println("val:" + val); - cfgFile = cfgFile.replaceAll("[%]" + key + "[%]", val); - }*/ - } - - PrintWriter out = new PrintWriter(new FileOutputStream(resultPath)); - - out.print(cfgFile); - out.flush(); - out.close(); - - } - -} diff --git a/src/main/java/net/sourceforge/myvd/quickstart/ADQuickStartJDBC.java b/src/main/java/net/sourceforge/myvd/quickstart/ADQuickStartJDBC.java deleted file mode 100644 index a4c8406..0000000 --- a/src/main/java/net/sourceforge/myvd/quickstart/ADQuickStartJDBC.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright 2008 Marc Boorshtein - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sourceforge.myvd.quickstart; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringReader; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.StringTokenizer; - -import javax.security.cert.CertificateEncodingException; -import javax.security.cert.X509Certificate; - -import net.sourceforge.myvd.quickstart.util.GetSSLCert; -import net.sourceforge.myvd.test.util.StreamReader; -import net.sourceforge.myvd.test.util.StreamWriter; - -public class ADQuickStartJDBC { - - /** - * @param args - * @throws IOException - * @throws ClassNotFoundException - * @throws IllegalAccessException - * @throws InstantiationException - * @throws SQLException - */ - public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - - String myVDHome = args[0]; - - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - String ksPath = myVDHome + "/conf/myvd-server.ks"; - String ksPass; - - String dnServer; - String dnOu; - String dnO; - String dnL; - String dnState; - String dnC; - - String dn; - String keyTool = System.getProperty("java.home") + File.separator + "bin" + File.separator + "keytool"; - System.err.println(keyTool); - String cacerts = System.getProperty("java.home") + File.separator + "lib" + File.separator + "security" + File.separator + "cacerts"; - - HashMap vars = new HashMap(); - - vars.put("MYVD_HOME", myVDHome); - - //System.out.println("MyVirtualDirectory Active Directory Quick-Start JDBC"); - //System.out.println("==============================================="); - - //System.out.println("This quick start will guide you through building out a virtual directory "); - //System.out.println("that will expose an Active Directory domain for use by a Linux system.\n\n"); - - //System.out.println("In order to move forward you will need:"); - //System.out.println("ActiveDirectory Domain Controller hostname or ip"); - //System.out.println("ActiveDirectory user with no search restrictions"); - //System.out.println("JDBC Driver"); - //System.out.println("JDBC URL"); - //System.out.println("JDBC User"); - //System.out.println("JDBC Password"); - - //System.out.println("Creating MyVirtualDirectory Keystore..."); - - String srcKsPwd = getPassword("CACERTS Password (usually 'changeit')",in); - ksPass = getPassword("MyVirtualDirectory Keystore Password",in); - - ProcessBuilder pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - ArrayList cmd = new ArrayList(); - cmd.add(keyTool); - cmd.add("-importkeystore"); - cmd.add("-srckeystore"); - cmd.add(cacerts); - cmd.add("-destkeystore"); - cmd.add(ksPath); - cmd.add("-deststorepass"); - cmd.add(ksPass); - cmd.add("-srcstorepass"); - cmd.add(srcKsPwd); - cmd.add("-noprompt"); - - - pb.command(cmd); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool -genkeypair -v -keystore /home/mlb/test.ks -alias selfsigned -keyalg rsa -keysize 1024 -validity 365"); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool"); - - Process process = pb.start(); - //Process process = Runtime.getRuntime().exec("/usr/java/jdk1.6.0_03/bin/keytool"); - - - //StreamReader errReader = new StreamReader(process.getErrorStream(),true); - StreamReader sr = new StreamReader(process.getInputStream(),true); - //StreamWriter sw = new StreamWriter(process.getInputStream(),new PrintWriter(process.getOutputStream())); - //sr.start(); - //errReader.start(); - sr.start(); - //System.setIn(process.getInputStream()); - - while (! sr.isDone()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - } - - //System.out.println("Keystore created"); - - String myvdBase = getInput("MyVirtualDirectory Base (ie ou=unix,o=mycompany)",in); - vars.put("VD_BASE", myvdBase); - - String myvdPort = getInput("MyVirtualDirectory Port (usualy 389)",in); - vars.put("VD_PORT", myvdPort); - - - - String adHost = getInput("Active Directroy Host",in); - vars.put("AD_HOST", adHost); - String adPort = getInput("Active Directroy Port (usualy 389)",in); - vars.put("AD_PORT", adPort); - String adIsSSL = getInput("Use SSL? (y/n)",in); - - String adDomain = getInput("Active Directory Domain Name",in); - String remoteBase = ""; - - StringTokenizer toker = new StringTokenizer(adDomain,".",false); - while (toker.hasMoreTokens()) { - remoteBase += "DC=" + toker.nextToken() + ","; - } - - remoteBase = remoteBase.substring(0,remoteBase.length() - 1); - - vars.put("AD_BASE", remoteBase); - - String adBase = getInput("User base (not including the domain, typically cn=users)",in); - vars.put("AD_USERS_BASE", adBase); - - String adSearchDN = getInput("Active Directory User DN (do not include the domain name, ie cn=MyVDUser,cn=Users)",in); - vars.put("AD_CRED", adSearchDN); - String adPassword = getPassword("Active Directory User Password",in); - vars.put("AD_PWD", adPassword); - - - if (adIsSSL.equalsIgnoreCase("y")) { - //System.out.println("Retrieving certificate parent from " + adHost + ":" + adPort + "..."); - X509Certificate cert = GetSSLCert.getCert(adHost, Integer.parseInt(adPort)); - - //System.out.println("Exporting certificate parent from " + adHost + ":" + adPort + "..."); - File f = new File(myVDHome + "/tmp.ad.der"); - FileOutputStream out = new FileOutputStream(f); - try { - out.write(cert.getEncoded()); - } catch (CertificateEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - out.flush(); - out.close(); - - //System.out.println("Import certificate parent from " + adHost + ":" + adPort + " into MyVirtualDirectory keystore..."); - - pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - cmd = new ArrayList(); - cmd.add(keyTool); - cmd.add("-importcert"); - cmd.add("-v"); - cmd.add("-keystore"); - cmd.add(ksPath); - cmd.add("-alias"); - cmd.add("ad-" + adHost + ":" + adPort); - cmd.add("-file"); - cmd.add(f.getAbsolutePath()); - cmd.add("-trustcacerts"); - cmd.add("-noprompt"); - cmd.add("-keypass"); - cmd.add(ksPass); - cmd.add("-storepass"); - cmd.add(ksPass); - - - pb.command(cmd); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool -genkeypair -v -keystore /home/mlb/test.ks -alias selfsigned -keyalg rsa -keysize 1024 -validity 365"); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool"); - - process = pb.start(); - //Process process = Runtime.getRuntime().exec("/usr/java/jdk1.6.0_03/bin/keytool"); - - - //StreamReader errReader = new StreamReader(process.getErrorStream(),true); - sr = new StreamReader(process.getInputStream(),true); - //StreamWriter sw = new StreamWriter(process.getInputStream(),new PrintWriter(process.getOutputStream())); - //sr.start(); - //errReader.start(); - sr.start(); - //System.setIn(process.getInputStream()); - - while (! sr.isDone()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - } - f.delete(); - //System.out.println("Import certificate parent from " + adHost + ":" + adPort + " into MyVirtualDirectory keystore complete"); - vars.put("AD_TYPE", "LDAPS"); - - } else { - vars.put("AD_TYPE", "LDAP"); - } - - String useKerb = getInput("Use Kerberos? (y/n)",in); - - if (useKerb.equalsIgnoreCase("y")) { - vars.put("AD_USE_KERB", "true"); - } else { - vars.put("AD_USE_KERB", "false"); - } - - - - - - - - - String createSelfSignedCert = getInput("Create a self signed certificate? (y/n)",in); - - - - - - if (createSelfSignedCert.equalsIgnoreCase("y")) { - //System.out.println("Creating a self signed SSL certificate..."); - - String myvdSecurePort = getInput("LDAPS Port (typically 636)",in); - - - - dnServer = getInput("Server Name",in); - dnOu = getInput("Org Unit",in); - dnO = getInput("Organization",in); - dnL = getInput("City/Locality",in); - dnState = getInput("State/Province",in); - dnC = getInput("2 Letter Country Code",in); - - dn = "CN=" + dnServer + ",OU=" + dnOu + ",O=" + dnO + ",L=" + dnL + ",ST=" + dnState + ",C=" + dnC; - - pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - cmd = new ArrayList(); - cmd.add(keyTool); - cmd.add("-genkeypair"); - cmd.add("-v"); - cmd.add("-keystore"); - cmd.add(ksPath); - cmd.add("-alias"); - cmd.add("selfsigned"); - cmd.add("-keyalg"); - cmd.add("rsa"); - cmd.add("-keysize"); - cmd.add("1024"); - cmd.add("-validity"); - cmd.add("365"); - cmd.add("-keypass"); - cmd.add(ksPass); - cmd.add("-storepass"); - cmd.add(ksPass); - - cmd.add("-dname"); - cmd.add(dn); - - pb.command(cmd); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool -genkeypair -v -keystore /home/mlb/test.ks -alias selfsigned -keyalg rsa -keysize 1024 -validity 365"); - //pb.command("/usr/java/jdk1.6.0_03/bin/keytool"); - - process = pb.start(); - //Process process = Runtime.getRuntime().exec("/usr/java/jdk1.6.0_03/bin/keytool"); - - - //StreamReader errReader = new StreamReader(process.getErrorStream(),true); - sr = new StreamReader(process.getInputStream(),true); - //StreamWriter sw = new StreamWriter(process.getInputStream(),new PrintWriter(process.getOutputStream())); - //sr.start(); - //errReader.start(); - sr.start(); - //System.setIn(process.getInputStream()); - - while (! sr.isDone()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - - } - } - - vars.put("SSL_CFG", "#SSL Config\nserver.secure.listener.port=" + myvdSecurePort + "\nserver.secure.keystore=" + ksPath + "\nserver.secure.keypass=" + ksPass + "\n\n"); - - } else { - vars.put("SSL_CFG", ""); - } - - - String jdbcDriver = getInput("JDBC Driver",in); - String jdbcUrl = getInput("JDBC URL",in); - String jdbcUser = getInput("JDBC User",in); - String jdbcPassword = getInput("JDBC Password",in); - - vars.put("JDBC_DRIVER", jdbcDriver); - vars.put("JDBC_URL", jdbcUrl); - vars.put("JDBC_USER", jdbcUser); - vars.put("JDBC_PASS", jdbcPassword); - - genConfig(myVDHome + "/quickStarts/ad2linuxjdbc.conf",myVDHome + "/conf/myvd.conf",vars); - - File f = new File(myVDHome + "/derbyHome"); - f.mkdir(); - - System.getProperties().setProperty("derby.system.home", myVDHome + "/derbyHome"); - - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - Connection con = DriverManager.getConnection("jdbc:derby:myvdPosix;create=true"); - con.createStatement().execute("CREATE TABLE posixUsers (id int GENERATED ALWAYS AS IDENTITY (START WITH 500, INCREMENT BY 1),objectGuid varchar(255),homeDirectory varchar(255),loginShell varchar(255))"); - con.createStatement().execute("CREATE TABLE posixGroups (id int GENERATED ALWAYS AS IDENTITY (START WITH 500, INCREMENT BY 1),objectGuid varchar(255))"); - con.close(); - - try { - DriverManager.getConnection("jdbc:derby:myvdPosix;shutdown=true"); - } catch (Throwable t) { - //ignore? - } - - } - - public static String getInput(String label,BufferedReader in) throws IOException { - //System.out.print(label + " : "); - String data = in.readLine(); - - //System.out.print("Is \"" + data + "\" correct? (y/n) : "); - String resp = in.readLine(); - - while (! resp.equalsIgnoreCase("y")) { - //System.out.print(label + " : "); - data = in.readLine(); - - //System.out.print("Is \"" + data + "\" correct? (y/n) : "); - resp = in.readLine(); - } - - return data; - } - - public static String getPassword(String label,BufferedReader in) throws IOException { - //System.out.print(label + " : "); - String data = in.readLine(); - - //System.out.print("Please verify : "); - String resp = in.readLine(); - - while (! resp.equals(data)) { - //System.out.println("Passwords don't match"); - //System.out.print(label + " : "); - data = in.readLine(); - - //System.out.print("Please verify : "); - resp = in.readLine(); - } - - return data; - } - - public static void genConfig(String sourcePath,String resultPath,HashMap vars) throws IOException { - String cfgFile = ""; - BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sourcePath))); - String line; - - while ((line = br.readLine()) != null) { - cfgFile += line + "\n"; - } - - br.close(); - - Iterator keyIt = vars.keySet().iterator(); - - while (keyIt.hasNext()) { - String key = keyIt.next(); - String val = vars.get(key); - if (cfgFile.contains("%" + key + "%")) { - //System.out.println("key:" + key); - //System.out.println("val:" + val); - - cfgFile = cfgFile.replaceAll("[%]" + key + "[%]", val); - } - } - - PrintWriter out = new PrintWriter(new FileOutputStream(resultPath)); - - out.print(cfgFile); - out.flush(); - out.close(); - - } - -} diff --git a/src/main/java/net/sourceforge/myvd/quickstart/util/GetSSLCert.java b/src/main/java/net/sourceforge/myvd/quickstart/util/GetSSLCert.java deleted file mode 100644 index 9f7a57b..0000000 --- a/src/main/java/net/sourceforge/myvd/quickstart/util/GetSSLCert.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright 2008 Marc Boorshtein - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sourceforge.myvd.quickstart.util; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.UnknownHostException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpClientError; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.params.HttpConnectionParams; -import org.apache.commons.httpclient.protocol.Protocol; -import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -public class GetSSLCert { - - public static javax.security.cert.X509Certificate getCert(String host, int port) { - GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory(); - Protocol myhttps = new Protocol("https", certFactory, port); - HttpClient httpclient = new HttpClient(); - httpclient.getHostConfiguration().setHost(host, port, myhttps); - GetMethod httpget = new GetMethod("/"); - try { - httpclient.executeMethod(httpget); - //System.out.println(httpget.getStatusLine()); - } catch (Throwable t) { - //do nothing - } - - finally { - httpget.releaseConnection(); - } - - return certFactory.getCertificate(); - } - - - public static void main(String[] args) throws Exception { - javax.security.cert.X509Certificate cert = getCert("test.mydomain.com",636); - if (cert != null) { - //System.out.println("Cert DN : " + cert.getIssuerDN()); - } else { - //System.out.println("No cert"); - } - - FileOutputStream fso = new FileOutputStream("/tmp/cert.der"); - fso.write(cert.getEncoded()); - fso.flush(); - fso.close(); - } - -} - -class GetCertSSLProtocolSocketFactory implements SecureProtocolSocketFactory { - - - javax.security.cert.X509Certificate cert; - - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(GetCertSSLProtocolSocketFactory.class); - - private SSLContext sslcontext = null; - - /** - * Constructor for GetCertSSLProtocolSocketFactory. - */ - public GetCertSSLProtocolSocketFactory() { - super(); - } - - - - private void getCert(SSLSocket socket) throws SSLPeerUnverifiedException { - SSLSession session = socket.getSession(); - - javax.security.cert.X509Certificate[] certs = session.getPeerCertificateChain(); - - if (this.cert == null) { - this.cert = certs[certs.length - 1]; - } - } - - private static SSLContext createEasySSLContext() { - try { - SSLContext context = SSLContext.getInstance("SSL"); - context.init( - null, - new TrustManager[] {new EasyX509TrustManager(null)}, - null); - return context; - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new HttpClientError(e.toString()); - } - } - - private SSLContext getSSLContext() { - if (this.sslcontext == null) { - this.sslcontext = createEasySSLContext(); - } - return this.sslcontext; - } - - /** - * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) - */ - public Socket createSocket( - String host, - int port, - InetAddress clientHost, - int clientPort) - throws IOException, UnknownHostException { - - SSLSocket socket = (SSLSocket) getSSLContext().getSocketFactory().createSocket( - host, - port, - clientHost, - clientPort - ); - - this.getCert(socket); - - return socket; - } - - /** - * Attempts to get a new socket connection to the given host within the given time limit. - *

      - * To circumvent the limitations of older JREs that do not support connect timeout a - * controller thread is executed. The controller thread attempts to create a new socket - * within the given limit of time. If socket constructor does not return until the - * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} - *

      - * - * @param host the host name/IP - * @param port the port on the host - * @param clientHost the local host name/IP to bind the socket to - * @param clientPort the port on the local machine - * @param params {@link HttpConnectionParams Http connection parameters} - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - public Socket createSocket( - final String host, - final int port, - final InetAddress localAddress, - final int localPort, - final HttpConnectionParams params - ) throws IOException, UnknownHostException, ConnectTimeoutException { - if (params == null) { - throw new IllegalArgumentException("Parameters may not be null"); - } - int timeout = params.getConnectionTimeout(); - SocketFactory socketfactory = getSSLContext().getSocketFactory(); - if (timeout == 0) { - - SSLSocket socket = (SSLSocket) socketfactory.createSocket(host, port, localAddress, localPort); - this.getCert(socket); - - return socket; - } else { - Socket socket = socketfactory.createSocket(); - SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); - SocketAddress remoteaddr = new InetSocketAddress(host, port); - socket.bind(localaddr); - socket.connect(remoteaddr, timeout); - this.getCert((SSLSocket) socket); - - - return socket; - } - } - - /** - * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) - */ - public Socket createSocket(String host, int port) - throws IOException, UnknownHostException { - SSLSocket socket = (SSLSocket) getSSLContext().getSocketFactory().createSocket( - host, - port - ); - - this.getCert(socket); - - return socket; - } - - /** - * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) - */ - public Socket createSocket( - Socket socket, - String host, - int port, - boolean autoClose) - throws IOException, UnknownHostException { - SSLSocket socket2 = (SSLSocket) getSSLContext().getSocketFactory().createSocket( - socket, - host, - port, - autoClose - ); - - this.getCert(socket2); - - return socket2; - } - - public boolean equals(Object obj) { - return ((obj != null) && obj.getClass().equals(GetCertSSLProtocolSocketFactory.class)); - } - - public int hashCode() { - return GetCertSSLProtocolSocketFactory.class.hashCode(); - } - - public javax.security.cert.X509Certificate getCertificate() { - return this.cert; - } - -} - -class EasyX509TrustManager implements X509TrustManager -{ - private X509TrustManager standardTrustManager = null; - - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class); - - /** - * Constructor for EasyX509TrustManager. - */ - public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { - super(); - TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - factory.init(keystore); - TrustManager[] trustmanagers = factory.getTrustManagers(); - if (trustmanagers.length == 0) { - throw new NoSuchAlgorithmException("no trust manager found"); - } - this.standardTrustManager = (X509TrustManager)trustmanagers[0]; - } - - /** - * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType) - */ - public void checkClientTrusted(X509Certificate[] certificates,String authType) throws CertificateException { - standardTrustManager.checkClientTrusted(certificates,authType); - } - - /** - * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType) - */ - public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException { - if ((certificates != null) && LOG.isDebugEnabled()) { - LOG.debug("Server certificate chain:"); - for (int i = 0; i < certificates.length; i++) { - LOG.debug("X509Certificate[" + i + "]=" + certificates[i]); - } - } - if ((certificates != null) && (certificates.length == 1)) { - certificates[0].checkValidity(); - } else { - standardTrustManager.checkServerTrusted(certificates,authType); - } - } - - /** - * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() - */ - public X509Certificate[] getAcceptedIssuers() { - return this.standardTrustManager.getAcceptedIssuers(); - } - - - -}