private String remove_from_ldap(String dn) { CMS.debug("UpdateDomainXML: delete_from_ldap: starting dn: " + dn); String status = SUCCESS; ILdapConnFactory connFactory = null; LDAPConnection conn = null; IConfigStore cs = CMS.getConfigStore(); try { IConfigStore ldapConfig = cs.getSubStore("internaldb"); connFactory = CMS.getLdapBoundConnFactory("UpdateDomainXML"); connFactory.init(ldapConfig); conn = connFactory.getConn(); conn.delete(dn); } catch (LDAPException e) { int resultCode = e.getLDAPResultCode(); if (resultCode != LDAPException.NO_SUCH_OBJECT) { status = FAILED; CMS.debug("Failed to delete entry" + e.toString()); } } catch (Exception e) { CMS.debug("Failed to delete entry" + e.toString()); } finally { try { if ((conn != null) && (connFactory != null)) { CMS.debug("Releasing ldap connection"); connFactory.returnConn(conn); } } catch (Exception e) { CMS.debug("Error releasing the ldap connection" + e.toString()); } } return status; }
/** * Invoked when the registry shuts down, giving services a chance to perform any final operations. * Service implementations should not attempt to invoke methods on other services (via proxies) as * the service proxies may themselves be shutdown. */ public void shutdown() { try { if (ldapConnection != null && ldapConnection.isConnected()) { if (logger.isDebugEnabled()) logger.debug("disconnecting from server {}", ldapHostName); ldapConnection.disconnect(); } } catch (LDAPException e) { throw new RuntimeException(e); } }
/** * connect and/or authenticate at LDAP server. * * @throws LDAPException */ private synchronized void checkAndconnect() throws LDAPException { if (!ldapConnection.isConnected()) { if (logger.isDebugEnabled()) logger.debug("connecting server: {}", ldapHostName); ldapConnection.connect(ldapVersion, ldapHostName, ldapPort, ldapAuthDN, ldapPwd); } if (!ldapConnection.isAuthenticated()) { if (logger.isDebugEnabled()) logger.debug("authenticate at server: {}", ldapHostName); ldapConnection.authenticate(ldapVersion, ldapAuthDN, ldapPwd); } }
public LDAPSourceImpl( Logger logger, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_VERSION) int ldapVersion, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_HOSTNAME) String ldapHostName, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_HOSTPORT) int ldapPort, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_AUTHDN) String ldapAuthDN, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_AUTHPWD) String ldapPwd, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_SIZELIMIT) String sizeLimit, @Inject @Symbol(ChenilleKitLDAPConstants.LDAP_TIMELIMIT) String timeLimit) { this.logger = logger; this.ldapVersion = ldapVersion; if (ldapHostName == null || ldapHostName.trim().length() < 1) throw new RuntimeException( "property '" + ChenilleKitLDAPConstants.LDAP_HOSTNAME + "' cant be empty!"); this.ldapHostName = ldapHostName; this.ldapPort = ldapPort; this.ldapAuthDN = ldapAuthDN; this.ldapPwd = ldapPwd; ldapConnection = new LDAPConnection(); try { ldapConnection.setOption(LDAPv2.SIZELIMIT, new Integer(sizeLimit)); ldapConnection.setOption(LDAPv2.TIMELIMIT, new Integer(timeLimit)); } catch (LDAPException le) { logger.error(le.getMessage(), le); throw new RuntimeException(le); } }
/** * Constructs a virtual list. * * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be * version 3 and upper param base the base distinguished name to search from param filter search * filter specifying the search criteria param attrs list of attributes that you want returned in * the search results param sortKey the attribute to sort by param pageSize the size of a page. * There is a 3*pageSize buffer maintained so pageUp and pageDown won't invoke fetch from ldap * server */ public DBVirtualList( IDBRegistry registry, LDAPConnection c, String base, String filter, String attrs[], String sortKey, int pageSize) throws EBaseException { CMS.debug( "In DBVirtualList filter attrs sortKey pageSize filter: " + filter + " attrs: " + Arrays.toString(attrs) + " pageSize " + pageSize); mRegistry = registry; mFilter = filter; try { mConn = (LDAPConnection) c.clone(); } catch (Exception e) { throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString())); } mBase = base; mAttrs = attrs; mPageControls = new LDAPControl[2]; setSortKey(sortKey); setPageSize(pageSize); }
private String add_to_ldap(LDAPEntry entry, String dn) { CMS.debug("UpdateDomainXML: add_to_ldap: starting"); String status = SUCCESS; ILdapConnFactory connFactory = null; LDAPConnection conn = null; IConfigStore cs = CMS.getConfigStore(); try { IConfigStore ldapConfig = cs.getSubStore("internaldb"); connFactory = CMS.getLdapBoundConnFactory("UpdateDomainXML"); connFactory.init(ldapConfig); conn = connFactory.getConn(); conn.add(entry); } catch (LDAPException e) { if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) { CMS.debug("UpdateDomainXML: Entry already exists"); try { conn.delete(dn); conn.add(entry); } catch (LDAPException ee) { CMS.debug("UpdateDomainXML: Error when replacing existing entry " + ee.toString()); status = FAILED; } } else { CMS.debug("UpdateDomainXML: Failed to update ldap domain info. Exception: " + e.toString()); status = FAILED; } } catch (Exception e) { CMS.debug("Failed to add entry" + e.toString()); } finally { try { if ((conn != null) && (connFactory != null)) { CMS.debug("Releasing ldap connection"); connFactory.returnConn(conn); } } catch (Exception e) { CMS.debug("Error releasing the ldap connection" + e.toString()); } } return status; }
public Vector<LDAPUser> getUserListLDAP() throws LDAPException { LDAPConnection connection = connectionPool.getConnection(); /*patron para la busqueda de todos los usuarios*/ String attb = "(" + atributoRol + "=" + rol + ")"; /*buequeda de todos los usuarios que cumplan el patron*/ LDAPSearchResults results = connection.search(base, LDAPv3.SCOPE_SUB, attb, null, false); LDAPAttribute ldapAttribute = null; LDAPUser usuario = null; LDAPEntry ldapEntry = null; Vector<LDAPUser> listUsers = new Vector<LDAPUser>(); /*guardamos los usuarios en un array de usuarios con la información que nos interesa*/ while (results.hasMoreElements()) { usuario = new LDAPUser(); usuario = inicilizaUsuario(usuario); ldapEntry = (LDAPEntry) results.next(); ldapAttribute = ldapEntry.getAttribute("uid"); usuario.setName(ldapAttribute.getStringValues().nextElement().toString().toUpperCase()); ldapAttribute = ldapEntry.getAttribute("cn"); usuario.setNombreCompleto(ldapAttribute.getStringValues().nextElement().toString()); ldapAttribute = ldapEntry.getAttribute("sn"); usuario.setNombre(ldapAttribute.getStringValues().nextElement().toString()); ldapAttribute = ldapEntry.getAttribute("mail"); if (ldapAttribute != null) { usuario.setMail(ldapAttribute.getStringValues().nextElement().toString()); } listUsers.add(usuario); } connectionPool.close(connection); return listUsers; }
/** * Devuleve si un usuario dado con su password se autentica correctamente y posee el rol de la * aplicacion correspondiente * * @param user, usuario para validar * @param password, del usuario * @return true/false si se autentica correctamente o no * @throws LDAPException */ public boolean isValidUser(String user, String password) throws LDAPException { LDAPConnection connection = connectionPool.getConnection(); String attributeName = "uid"; String filter = "uid=" + user + "," + base; /* Se realiza la autenticacion del usuario con la password*/ connection.authenticate(filter, password); /* si es correcta se obtienen los atributos del usuario*/ LDAPSearchResults results = connection.search( base, LDAPv3.SCOPE_SUB, "(" + attributeName + "=" + user + ")", null, false); /* Se obtienen los valores para el atributo rol*/ LDAPAttribute ldapAttribute = null; LDAPEntry ldapEntry = null; while (results.hasMoreElements()) { ldapEntry = (LDAPEntry) results.next(); ldapAttribute = ldapEntry.getAttribute(atributoRol); } // ahora no vendrian en lista separadas por coma si no la lista String[] lista = ldapAttribute.getStringValueArray(); /* se cierra la conexion*/ connectionPool.close(connection); /* si comprueba si pertenece al rol correspondiente para la aplicacion*/ boolean resultado = perteneceGrupo(lista, rol); if (resultado) { logger.info("Autenticacion Ldap correcta"); } else { logger.info("Error de autenticación contra ldap"); } return resultado; }
/** Contructor por defecto privado para implementar el patrón Singleton */ private LDAPManager() { String prefixLog = "LDAPManager: "; logger.debug(prefixLog + "Inicializando LDAPManager"); // Se cargan las propiedades de fichero cargarPropiedades(); /* * Se inicializa el pool */ try { LDAPConnection connection = new LDAPConnection(); connection.connect(3, host, Integer.parseInt(port), rootdn, passwroot); connectionPool = new ConnectionPool( Integer.parseInt(minSizePool), Integer.parseInt(maxSizePool), connection); } catch (LDAPException e) { logger.error(prefixLog + "No se ha podido conectar con el LDAP", e); } logger.debug(prefixLog + "LDAPManager inicializado correctamente"); }
/** * Constructs a virtual list. Be sure to setPageSize() later if your pageSize is not the default * 10 Be sure to setSortKey() before fetchs * * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be * version 3 and upper param base the base distinguished name to search from param filter search * filter specifying the search criteria param attrs list of attributes that you want returned in * the search results */ public DBVirtualList( IDBRegistry registry, LDAPConnection c, String base, String filter, String attrs[]) throws EBaseException { mRegistry = registry; mFilter = filter; mBase = base; mAttrs = attrs; CMS.debug( "In DBVirtualList filter attrs filter: " + filter + " attrs: " + Arrays.toString(attrs)); mPageControls = new LDAPControl[2]; try { mConn = (LDAPConnection) c.clone(); } catch (Exception e) { throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString())); } }
private synchronized boolean getJumpToPage() { try { // Get the actual entries if (!getEntries()) return false; // Check if we have a control returned LDAPControl[] c = mConn.getResponseControls(); LDAPVirtualListResponse nextCont = null; if (c != null) { for (LDAPControl control : c) { if (control instanceof LDAPVirtualListResponse) { nextCont = (LDAPVirtualListResponse) control; break; } } } if (nextCont != null) { mSelectedIndex = nextCont.getFirstPosition() - 1; mTop = Math.max(0, mSelectedIndex - mBeforeCount); CMS.debug("DBVirtualList: top: " + mTop); if (mJumpTo != null) { mJumpToInitialIndex = mTop; } // Now we know the total size of the virtual list box mSize = nextCont.getContentCount(); ((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize); mInitialized = true; // System.out.println( "Virtual window: " + mTop + // ".." + (mTop+mEntries.size()-1) + // " of " + mSize ); } else { mLogger.log( ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE")); } return true; } catch (Exception e) { // happens when connection is not available return false; } }
public DBVirtualList( IDBRegistry registry, LDAPConnection c, String base, String filter, String attrs[], String startFrom, String sortKey, int pageSize) throws EBaseException { CMS.debug( "In DBVirtualList filter attrs startFrom sortKey pageSize " + "filter: " + filter + " attrs: " + Arrays.toString(attrs) + " pageSize " + pageSize + " startFrom " + startFrom); mRegistry = registry; mFilter = filter; try { mConn = (LDAPConnection) c.clone(); } catch (Exception e) { throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString())); } mBase = base; mAttrs = attrs; mPageControls = new LDAPControl[2]; mJumpTo = startFrom; setSortKey(sortKey); // setPageSize(pageSize); if (pageSize < 0) { mJumpToDirection = -1; } mPageSize = pageSize; mBeforeCount = 0; mAfterCount = mPageSize; }
/** Fetch a buffer */ private boolean getPage() { // Get the actual entries if (!getEntries()) return false; // Check if we have a control returned LDAPControl[] c = mConn.getResponseControls(); LDAPVirtualListResponse nextCont = null; if (c != null) { for (LDAPControl control : c) { if (control instanceof LDAPVirtualListResponse) { nextCont = (LDAPVirtualListResponse) control; break; } } } if (nextCont != null) { mSelectedIndex = nextCont.getFirstPosition() - 1; mTop = Math.max(0, mSelectedIndex - mBeforeCount); // CMS.debug("New mTop: " + mTop + " mSelectedIndex " + mSelectedIndex); // Now we know the total size of the virtual list box mSize = nextCont.getContentCount(); ((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize); mInitialized = true; // System.out.println( "Virtual window: " + mTop + // ".." + (mTop+mEntries.size()-1) + // " of " + mSize ); } else { /*LogDoc * * @phase local ldap search */ mLogger.log( ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE")); } return true; }
private synchronized boolean getEntries() { CMS.debug("DBVirtualList.getEntries()"); // Specify necessary controls for vlist // LDAPSearchConstraints cons = mConn.getSearchConstraints(); LDAPSearchConstraints cons = new LDAPSearchConstraints(); cons.setMaxResults(0); if (mPageControls != null) { cons.setServerControls(mPageControls); // System.out.println( "setting vlist control" ); } // Empty the buffer mEntries.removeAllElements(); // Do a search try { // what happen if there is no matching? String ldapFilter = mRegistry.getFilter(mFilter); String ldapAttrs[] = null; LDAPSearchResults result; if (mAttrs != null) { ldapAttrs = mRegistry.getLDAPAttributes(mAttrs); /* LDAPv2.SCOPE_BASE: (search only the base DN) LDAPv2.SCOPE_ONE: (search only entries under the base DN) LDAPv2.SCOPE_SUB: (search the base DN and all entries within its subtree) */ result = mConn.search(mBase, LDAPConnection.SCOPE_ONE, ldapFilter, ldapAttrs, false, cons); } else { result = mConn.search(mBase, LDAPConnection.SCOPE_ONE, ldapFilter, null, false, cons); } if (result == null) { return false; } int damageCounter = 0; while (result.hasMoreElements()) { LDAPEntry entry = (LDAPEntry) result.nextElement(); try { // maintain mEntries as vector of LDAPEntry @SuppressWarnings("unchecked") E o = (E) mRegistry.createObject(entry.getAttributeSet()); mEntries.addElement(o); } catch (Exception e) { CMS.debug("Exception " + e); /*LogDoc * * @phase local ldap search * @reason Failed to get enties. * @message DBVirtualList: <exception thrown> */ mLogger.log( ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_DBS_VL_ADD", e.toString())); // #539044 damageCounter++; if (damageCounter > 100) { mLogger.log( ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE, CMS.getLogMessage( "CMSCORE_DBS_VL_CORRUPTED_ENTRIES", Integer.toString(damageCounter))); return false; } } } } catch (Exception e) { /*LogDoc * * @phase local ldap search * @reason Failed to get enties. * @message DBVirtualList: <exception thrown> */ CMS.debug("getEntries: exception " + e); mLogger.log( ILogger.EV_SYSTEM, ILogger.S_DB, ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.toString())); } // System.out.println( "Returning " + mEntries.size() + // " entries" ); CMS.debug("DBVirtualList: entries: " + mEntries.size()); return true; }
public static void main(String[] args) { String host = null; String binddn = null; String baseDN = "mds-vo-name=local, o=grid"; String filter = "(objectclass=*)"; String qop = "auth-conf, auth"; boolean debug = false; int port = 389; int version = 3; for (int i = 0; i < args.length; i++) { if (args[i].equals("-h")) { host = args[++i]; } else if (args[i].equals("-p")) { port = Integer.parseInt(args[++i]); } else if (args[i].equals("-ver")) { version = Integer.parseInt(args[++i]); } else if (args[i].equals("-d")) { debug = true; } else if (args[i].equals("-D")) { binddn = args[++i]; } else if (args[i].equals("-b")) { baseDN = args[++i]; } else if (args[i].equals("-qop")) { qop = args[++i]; } else if (args[i].equalsIgnoreCase("-usage") || args[i].equalsIgnoreCase("-help")) { System.err.println("Usage: NetscapeTest -h [host] -p [port] -D [binddn] [-d] -b [baseDN]"); System.err.println("\tExample: NetscapeTest -h mds.globus.org -p 389 -r o=globus,c=us"); System.exit(1); } else { System.err.println("Invalid argument: " + args[i]); System.exit(1); } } if (host == null) { System.err.println("Error: hostname not specified!"); System.exit(1); } LDAPConnection ld = null; ld = new LDAPConnection(); Hashtable props = new Hashtable(); /* This property specifies where the implementation of * the GSI SASL mechanism for Netscape Directory SDK * can be found. */ props.put("javax.security.sasl.client.pkgs", "org.globus.mds.gsi.netscape"); /* This property specifies the quality of protection * value. It can be a comma separated list of protection * values in preference order. There are three possible * qop values: * "auth" - authentication only, * "auth-int" - authentication with integrity protection * (GSI without encryption) * "auth-conf" - authentication with integrity and privacy * protections. (GSI with encryption) * If not specified, defaults to "auth" */ props.put("javax.security.sasl.qop", qop); /* This property can be used to pass a specific * set of credentials for the GSI SASL mechanism * to use. It must be a GSSCredential object. * If not set, the defaut credential will be * used. */ // env.put(GSIMechanism.SECURITY_CREDENTIALS, cred); try { if (debug) { // to enable debugging ld.setProperty("debug", "true"); ld.setProperty(LDAPConnection.TRACE_PROPERTY, System.out); } ld.setOption(LDAPv2.PROTOCOL_VERSION, new Integer(version)); ld.connect(host, port); /* Authenticate to the server over SASL. * Use GSIMechanism.NAME for the GSI SASL mechanism. */ ld.authenticate(binddn, new String[] {GSIMechanism.NAME}, props, null); LDAPSearchResults myResults = null; myResults = ld.search(baseDN, LDAPv2.SCOPE_ONE, filter, null, false); while (myResults.hasMoreElements()) { LDAPEntry myEntry = myResults.next(); String nextDN = myEntry.getDN(); System.out.println(nextDN + ":"); LDAPAttributeSet entryAttrs = myEntry.getAttributeSet(); System.out.println(entryAttrs); System.out.println(); } } catch (Exception e) { System.err.println("NetscapeTest failed: " + e.getMessage()); e.printStackTrace(); } finally { try { ld.disconnect(); } catch (Exception ee) { } } }