Package com.novell.ldap

Examples of com.novell.ldap.LDAPConnection


    String sService = sConnStr.substring(0, sConnStr.indexOf('/'));
    String[] aService = Gadgets.split2(sService, ':');

    try {
      oConn = new LDAPConnection();
      if (aService.length<2)
        oConn.connect(aService[0].trim(), 389);
      else
        oConn.connect(aService[0].trim(), Integer.parseInt(aService[1]));
      setPartitionName(sConnStr.substring(sConnStr.indexOf('/')+1));
View Full Code Here


            logger.debug("Anonymous bind is not currently allowed by the LDAP authentication provider.");
            return null;
        }

        // Connect to LDAP server
        LDAPConnection ldapConnection;
        try {

            ldapConnection = new LDAPConnection();
            ldapConnection.connect(
                    GuacamoleProperties.getRequiredProperty(LDAPGuacamoleProperties.LDAP_HOSTNAME),
                    GuacamoleProperties.getRequiredProperty(LDAPGuacamoleProperties.LDAP_PORT)
            );

        }
        catch (LDAPException e) {
            throw new GuacamoleServerException("Unable to connect to LDAP server.", e);
        }

        // Get username attribute
        String username_attribute = GuacamoleProperties.getRequiredProperty(
            LDAPGuacamoleProperties.LDAP_USERNAME_ATTRIBUTE
        );

        // Get user base DN
        String user_base_dn = GuacamoleProperties.getRequiredProperty(
                LDAPGuacamoleProperties.LDAP_USER_BASE_DN
        );

        // Construct user DN
        String user_dn =
            escapeDN(username_attribute) + "=" + escapeDN(credentials.getUsername())
            + "," + user_base_dn;

        try {

            // Bind as user
            try {
                ldapConnection.bind(
                        LDAPConnection.LDAP_V3,
                        user_dn,
                        credentials.getPassword().getBytes("UTF-8")
                );
            }
            catch (UnsupportedEncodingException e) {
                throw new GuacamoleException(e);
            }

        }
        catch (LDAPException e) {
            logger.debug("LDAP bind failed.", e);
            return null;
        }

        // Get config base DN
        String config_base_dn = GuacamoleProperties.getRequiredProperty(
                LDAPGuacamoleProperties.LDAP_CONFIG_BASE_DN
        );

        // Pull all connections
        try {

            // Find all guac configs for this user
            LDAPSearchResults results = ldapConnection.search(
                    config_base_dn,
                    LDAPConnection.SCOPE_SUB,
                    "(&(objectClass=guacConfigGroup)(member=" + escapeLDAPSearchFilter(user_dn) + "))",
                    null,
                    false
            );

            // Add all configs
            Map<String, GuacamoleConfiguration> configs = new TreeMap<String, GuacamoleConfiguration>();
            while (results.hasMore()) {

                LDAPEntry entry = results.next();

                // New empty configuration
                GuacamoleConfiguration config = new GuacamoleConfiguration();

                // Get CN
                LDAPAttribute cn = entry.getAttribute("cn");
                if (cn == null)
                    throw new GuacamoleException("guacConfigGroup without cn");

                // Get protocol
                LDAPAttribute protocol = entry.getAttribute("guacConfigProtocol");
                if (protocol == null)
                    throw new GuacamoleException("guacConfigGroup without guacConfigProtocol");

                // Set protocol
                config.setProtocol(protocol.getStringValue());

                // Get parameters, if any
                LDAPAttribute parameterAttribute = entry.getAttribute("guacConfigParameter");
                if (parameterAttribute != null) {

                    // For each parameter
                    Enumeration<String> parameters = parameterAttribute.getStringValues();
                    while (parameters.hasMoreElements()) {

                        String parameter = parameters.nextElement();

                        // Parse parameter
                        int equals = parameter.indexOf('=');
                        if (equals != -1) {

                            // Parse name
                            String name = parameter.substring(0, equals);
                            String value = parameter.substring(equals+1);

                            config.setParameter(name, value);

                        }

                    }

                }

                // Store config by CN
                configs.put(cn.getStringValue(), config);

            }

            // Disconnect
            ldapConnection.disconnect();
            return configs;

        }
        catch (LDAPException e) {
            throw new GuacamoleServerException("Error while querying for connections.", e);
View Full Code Here

   * @param user
   * @param password
   */
  public static User authenticate(String user, String password){

    LDAPConnection connection = new LDAPConnection();
    try {
      // Se establece la conexion con el servidor LDAP
      connection.connect(config.getString(IP), new Integer(config.getString(PORT)));
     
      // Se autentica el usuario
      byte[] encryptPassword = password.getBytes(UTF8);
      connection.bind(LDAPConnection.LDAP_V3, config.getString(DOMAIN)+ DOUBLE_BAR + user, encryptPassword);
     
      return searchUser(user, encryptPassword);
        } catch (Exception e) {
          logger.error(Tools.getStackTrace(e));
            throw new RuntimeException(e);
View Full Code Here

 
  public static Collection<LDAPGroup> searchGroups(String user,  byte[] password){
   
    Set<LDAPGroup> groups = new HashSet<LDAPGroup>();
   
    LDAPConnection connection = new LDAPConnection();
    try {
      // Se establece la conexion con el servidor LDAP
      connection.connect(config.getString(IP), new Integer(config.getString(PORT)));
     
      // Se autentica el usuario
      connection.bind(LDAPConnection.LDAP_V3, config.getString(DOMAIN)+ DOUBLE_BAR + user, password);
     
      LDAPSearchResults ldapSearchResults = connection.search("CN=Users,DC=" + config.getString(DOMAIN)+ ",DC=local",
          LDAPConnection.SCOPE_SUB, "(&(objectCategory=person)(objectClass=user))", null, Boolean.FALSE);

      while (ldapSearchResults.hasMore()){
        LDAPEntry ldapEntry = ldapSearchResults.next();
       
View Full Code Here

 
  public static User searchUser(String user, byte[] password){
   
    Collection<User> users = new ArrayList<User>();
   
    LDAPConnection connection = new LDAPConnection();
    try {
      // Se establece la conexion con el servidor LDAP
      connection.connect(config.getString(IP), new Integer(config.getString(PORT)));
     
      // Se autentica el usuario
      connection.bind(LDAPConnection.LDAP_V3, config.getString(DOMAIN)+ DOUBLE_BAR + user, password);
     
      LDAPSearchResults ldapSearchResults = connection.search("CN=Users,DC=" + config.getString(DOMAIN)+ ",DC=local", LDAPConnection.SCOPE_SUB, "(&(objectCategory=person)(objectClass=user))", null, Boolean.FALSE);

      while (ldapSearchResults.hasMore()){
        LDAPEntry ldapEntry = ldapSearchResults.next();
        if (user.equals(getValue(ldapEntry, "sAMAccountName"))){
          User searched = getUser(ldapEntry);
View Full Code Here

 
  public static Collection<User> search(String user, byte[] password){
   
    Collection<User> users = new ArrayList<User>();
   
    LDAPConnection connection = new LDAPConnection();
    try {
      // Se establece la conexion con el servidor LDAP
      connection.connect(config.getString(IP), new Integer(config.getString(PORT)));
     
      // Se autentica el usuario
      connection.bind(LDAPConnection.LDAP_V3, config.getString(DOMAIN)+ DOUBLE_BAR + user, password);
     
      LDAPSearchResults ldapSearchResults = connection.search("CN=Users,DC=" + config.getString(DOMAIN)+ ",DC=local", LDAPConnection.SCOPE_SUB, "(&(objectCategory=person)(objectClass=user))", null, Boolean.FALSE);

      while (ldapSearchResults.hasMore()){
        LDAPEntry ldapEntry = ldapSearchResults.next();
        User userActual = getUser(ldapEntry);
        // Solamente lista los usuarios que tienen un perfil asignado valido en iEvenTask
View Full Code Here

     * @return the full DN of the user
     */
  static public String getSubjectDNFromUserInAD(String serverAddress, int port, boolean useSSL,
      String connectionDN, String connectionPassword, String baseDN, String username) {
    String requestedDN = null;
    LDAPConnection lc = getNewConnection(serverAddress, port, useSSL, connectionDN, connectionPassword);
    if (lc == null) {
      return null;
    }
    LDAPEntry entry = null;
    try {
      String searchFilter = "(&(objectClass=person)(sAMAccountName=" + username + "))";
          String[] attrs = { LDAPConnection.NO_ATTRS };
          // Search recursively, but don't return any attributes for found objects
      LDAPSearchResults searchResults = lc.search(baseDN, LDAPConnection.SCOPE_SUB, searchFilter, attrs, true);
      if (searchResults.hasMore()) {
        // Re-read the object to get the attributes now
        requestedDN = searchResults.next().getDN();
        // List all props just for fun.. (TODO: Remove this..)
        entry = lc.read(requestedDN);
        if (entry != null) {
          Iterator iter = entry.getAttributeSet().iterator();
          while (iter.hasNext()) {
            log.info(".. " + iter.next().toString().replaceAll("[^A-Za-z]", ""));
          }
View Full Code Here

  /**
   * Create new LDAP connection to Active Directory server.
   * @param port can be set to 0 to use the default port (389 or 636 for SSL)
   */
  private static LDAPConnection getNewConnection(String serverAddress, int port, boolean useSSL, String connectionDN, String connectionPassword) {
    LDAPConnection lc = null;
    int ldapPort = port;
    if (useSSL) {
      lc = new LDAPConnection(new LDAPJSSESecureSocketFactory());
      if (ldapPort == 0) {
        ldapPort = LDAPConnection.DEFAULT_SSL_PORT;  // Port 636
      }
    } else {
      lc = new LDAPConnection();
      if (ldapPort == 0) {
        ldapPort = LDAPConnection.DEFAULT_PORT;  // Port 389
      }
    }
    try {
      // connect to the server
      lc.connect(serverAddress, ldapPort);
      // authenticate to the server
      lc.bind(LDAPConnection.LDAP_V3, connectionDN, connectionPassword.getBytes());
    } catch (LDAPException e) {
      log.error("Error during AD bind", e);
      disconnect(lc);
      lc = null;
    }
View Full Code Here

          // Call separate script for revocation
          revokeCertificate(admin, incert, username, revocationReason, userDN);
        } else if (status == SecConst.CERT_ACTIVE) {
            // Don't publish non-active certificates
        int ldapVersion = LDAPConnection.LDAP_V3;
        LDAPConnection lc = createLdapConnection();

        final String dn;
        final String certdn;
        try {
          // Extract the users DN from the cert.
          certdn = CertTools.getSubjectDN(incert);
          if (log.isDebugEnabled()) {
            log.debug( "Constructing DN for: " + username);
          }
          dn = constructLDAPDN(certdn, userDN);
          if (log.isDebugEnabled()) {
            log.debug("LDAP DN for user " +username +" is '" + dn+"'");
          }
        } catch (Exception e) {
          String msg = intres.getLocalizedMessage("publisher.errorldapdecode", "certificate");
          log.error(msg, e);           
          throw new PublisherException(msg);           
        }

        // Extract the users email from the cert.
        String email = CertTools.getEMailAddress(incert);

        // Check if the entry is already present, we will update it with the new certificate.
        // To work well with the LdapSearchPublisher we need to pass the full certificate DN to the
        // search function, and not only the LDAP DN. The regular publisher should only use the LDAP DN though,
        // but the searchOldEntity function will take care of that.
        LDAPEntry oldEntry = searchOldEntity(username, ldapVersion, lc, certdn, userDN, email);

        // PART 2: Create LDAP entry
        LDAPEntry newEntry = null;
        ArrayList<LDAPModification> modSet = new ArrayList<LDAPModification>();
        LDAPAttributeSet attributeSet = null;
        String attribute = null;
        String objectclass = null;

        if (type == SecConst.CERTTYPE_ENDENTITY) {
          if (log.isDebugEnabled()) {
            log.debug("Publishing end user certificate to first available server of " + getHostnames());
          }
          if (oldEntry != null) {
            modSet = getModificationSet(oldEntry, certdn, email, ADD_MODIFICATION_ATTRIBUTES, true, password);
          } else {
            objectclass = getUserObjectClass(); // just used for logging
            attributeSet = getAttributeSet(incert, getUserObjectClass(), certdn, email, true, true, password, extendedinformation);
          }

          try {
            attribute = getUserCertAttribute();
            LDAPAttribute certAttr = new LDAPAttribute(getUserCertAttribute(), incert.getEncoded());
            if (oldEntry != null) {
              String oldDn = oldEntry.getDN();
              if (getAddMultipleCertificates()) {
                modSet.add(new LDAPModification(LDAPModification.ADD, certAttr));                       
                if (log.isDebugEnabled()) {
                  log.debug("Appended new certificate in user entry; " + username+": "+oldDn);
                }
              } else {
                modSet.add(new LDAPModification(LDAPModification.REPLACE, certAttr));                                           
                if (log.isDebugEnabled()) {
                  log.debug("Replaced certificate in user entry; " + username+": "+oldDn);
                }
              }
            } else {
              attributeSet.add(certAttr);
              if (log.isDebugEnabled()) {
                log.debug("Added new certificate to user entry; " + username+": "+dn);
              }
            }
          } catch (CertificateEncodingException e) {
            String msg = intres.getLocalizedMessage("publisher.errorldapencodestore", "certificate");
            log.error(msg, e);
            throw new PublisherException(msg);               
          }
        } else if ((type == SecConst.CERTTYPE_SUBCA) || (type == SecConst.CERTTYPE_ROOTCA)) {
          if (log.isDebugEnabled()) {
            log.debug("Publishing CA certificate to first available server of " + getHostnames());
          }
          if (oldEntry != null) {
            modSet = getModificationSet(oldEntry, certdn, null, false, false, password);
          } else {
            objectclass = getCAObjectClass(); // just used for logging
            attributeSet = getAttributeSet(incert, getCAObjectClass(), certdn, null, true, false, password, extendedinformation);
          }
          try {
            attribute = getCACertAttribute();
            LDAPAttribute certAttr = new LDAPAttribute(getCACertAttribute(), incert.getEncoded());
            if (oldEntry != null) {
              modSet.add(new LDAPModification(LDAPModification.REPLACE, certAttr));
            } else {
              attributeSet.add(certAttr);
              // Also create using the crlattribute, it may be required
              LDAPAttribute crlAttr = new LDAPAttribute(getCRLAttribute(), getFakeCRL());
              attributeSet.add(crlAttr);
              // Also create using the arlattribute, it may be required
              LDAPAttribute arlAttr = new LDAPAttribute(getARLAttribute(), getFakeCRL());
              attributeSet.add(arlAttr);
              if (log.isDebugEnabled()) {
                log.debug("Added (fake) attribute for CRL and ARL.");
              }
            }
          } catch (CertificateEncodingException e) {
            String msg = intres.getLocalizedMessage("publisher.errorldapencodestore", "certificate");
            log.error(msg, e);
            throw new PublisherException(msg);           
          }
        } else {
          String msg = intres.getLocalizedMessage("publisher.notpubltype", Integer.valueOf(type));
          log.info(msg);
          throw new PublisherException(msg);                     
        }

        // PART 3: MODIFICATION AND ADDITION OF NEW USERS
        // Try all the listed servers
        Iterator servers = getHostnameList().iterator();
        boolean connectionFailed;
        do {
          connectionFailed = false;
          String currentServer = (String) servers.next();
          try {
            TCPTool.probeConnectionLDAP(currentServer, Integer.parseInt(getPort()), getConnectionTimeOut())// Avoid waiting for halfdead-servers
            lc.connect(currentServer, Integer.parseInt(getPort()));
            // authenticate to the server
            lc.bind(ldapVersion, getLoginDN(), getLoginPassword().getBytes("UTF8"), ldapBindConstraints);           
            // Add or modify the entry
            if (oldEntry != null && getModifyExistingUsers()) {
              LDAPModification[] mods = new LDAPModification[modSet.size()];
              mods = (LDAPModification[])modSet.toArray(mods);
              String oldDn = oldEntry.getDN();
              if (log.isDebugEnabled()) {
                log.debug("Writing modification to DN: "+oldDn);
              }
              lc.modify(oldDn, mods, ldapStoreConstraints);
              String msg = intres.getLocalizedMessage("publisher.ldapmodify", "CERT", oldDn);
              log.info(msg)
            } else {
              if(this.getCreateNonExistingUsers()){    
                if (oldEntry == null) {          
                  // Check if the intermediate parent node is present, and if it is not
                  // we can create it, of allowed to do so by the publisher configuration
                  if(getCreateIntermediateNodes()) {
                    final String parentDN = new String(dn.substring(dn.indexOf(',') + 1));
                    try {
                      lc.read(parentDN, ldapSearchConstraints);
                    } catch(LDAPException e) {
                      if(e.getResultCode() == LDAPException.NO_SUCH_OBJECT) {
                        this.createIntermediateNodes(lc, dn);
                        String msg = intres.getLocalizedMessage("publisher.ldapaddedintermediate", "CERT", parentDN);
                        log.info(msg);
                      }
                    }
                  }
                  newEntry = new LDAPEntry(dn, attributeSet);
                  if (log.isDebugEnabled()) {
                    log.debug("Adding DN: "+dn);
                  }
                  lc.add(newEntry, ldapStoreConstraints);
                  String msg = intres.getLocalizedMessage("publisher.ldapadd", "CERT", dn);
                  log.info(msg);
                }
              } 
            }
          } catch (LDAPException e) {
            connectionFailed = true;
            if (servers.hasNext()) {
              log.warn("Failed to publish to " + currentServer + ". Trying next in list.");
            } else {
              String msg = intres.getLocalizedMessage("publisher.errorldapstore", "certificate", attribute, objectclass, dn, e.getMessage());
              log.error(msg, e)
              throw new PublisherException(msg);           
            }
          } catch (UnsupportedEncodingException e) {
            String msg = intres.getLocalizedMessage("publisher.errorpassword", getLoginPassword());
            log.error(msg, e);
            throw new PublisherException(msg);           
          } finally {
            // disconnect with the server
            try {
              lc.disconnect(ldapDisconnectConstraints);
            } catch (LDAPException e) {
              String msg = intres.getLocalizedMessage("publisher.errordisconnect", getLoginPassword());
              log.error(msg, e);
            }
          }
View Full Code Here

      String msg = intres.getLocalizedMessage("publisher.errorldapdecode", "CRL");
      log.error(msg, e);         
      throw new PublisherException(msg);           
    }

    LDAPConnection lc = createLdapConnection();

    // Check if the entry is already present, we will update it with the new CRL.
    LDAPEntry oldEntry = searchOldEntity(null, ldapVersion, lc, crldn, userDN, null);

    LDAPEntry newEntry = null;
    ArrayList modSet = new ArrayList();
    LDAPAttributeSet attributeSet = null;

    if (oldEntry != null) {
      modSet = getModificationSet(oldEntry, crldn, null, false, false, null);
    } else {
      attributeSet = getAttributeSet(null, this.getCAObjectClass(), crldn, null, true, false, null,null);
    }

    if(isDeltaCRL) {
      // It's a delta CRL.
      LDAPAttribute attr = new LDAPAttribute(getDeltaCRLAttribute(), incrl);
      if (oldEntry != null) {
        modSet.add(new LDAPModification(LDAPModification.REPLACE, attr));
      } else {
        attributeSet.add(attr);
      }
    } else {
      // It's a CRL
      LDAPAttribute crlAttr = new LDAPAttribute(getCRLAttribute(), incrl);
      LDAPAttribute arlAttr = new LDAPAttribute(getARLAttribute(), incrl);
      if (oldEntry != null) {
        modSet.add(new LDAPModification(LDAPModification.REPLACE, crlAttr));
        modSet.add(new LDAPModification(LDAPModification.REPLACE, arlAttr));
      } else {
        attributeSet.add(crlAttr);
        attributeSet.add(arlAttr);
      }
    }
    if (oldEntry == null) {
      newEntry = new LDAPEntry(dn, attributeSet);
    }
    // Try all the listed servers
    Iterator servers = getHostnameList().iterator();
    boolean connectionFailed;
    do {
      connectionFailed = false;
      String currentServer = (String) servers.next();
      try {
        TCPTool.probeConnectionLDAP(currentServer, Integer.parseInt(getPort()), getConnectionTimeOut())// Avoid waiting for halfdead-servers
        // connect to the server
        lc.connect(currentServer, Integer.parseInt(getPort()));
        // authenticate to the server
        lc.bind(ldapVersion, getLoginDN(), getLoginPassword().getBytes("UTF8"), ldapBindConstraints);
        // Add or modify the entry
        if (oldEntry != null) {
          LDAPModification[] mods = new LDAPModification[modSet.size()];
          mods = (LDAPModification[])modSet.toArray(mods);
          lc.modify(dn, mods, ldapStoreConstraints);
          String msg = intres.getLocalizedMessage("publisher.ldapmodify", "CRL", dn);
          log.info(msg)
        } else {
          lc.add(newEntry, ldapStoreConstraints);
          String msg = intres.getLocalizedMessage("publisher.ldapadd", "CRL", dn);
          log.info(msg)
        }
      } catch (LDAPException e) {
        connectionFailed = true;
        if (servers.hasNext()) {
          log.warn("Failed to publish to " + currentServer + ". Trying next in list.");
        } else {
          String msg = intres.getLocalizedMessage("publisher.errorldapstore", "CRL", getCRLAttribute(), getCAObjectClass(), dn, e.getMessage());
          log.error(msg, e)
          throw new PublisherException(msg);           
        }
      } catch (UnsupportedEncodingException e) {
        String msg = intres.getLocalizedMessage("publisher.errorpassword", getLoginPassword());
        log.error(msg, e);
        throw new PublisherException(msg);           
      } finally {
        // disconnect with the server
        try {
          lc.disconnect(ldapDisconnectConstraints);
        } catch (LDAPException e) {
          String msg = intres.getLocalizedMessage("publisher.errordisconnect");
          log.error(msg, e);
        }
      }
View Full Code Here

TOP

Related Classes of com.novell.ldap.LDAPConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.