예제 #1
0
  void addGroup(Hashtable<String, String> ldapEnv, String cn, ArrayList members, String owner) {
    Attributes attributes = new BasicAttributes(true);
    attributes.put(new BasicAttribute("objectClass", "groupOfNames"));
    attributes.put(new BasicAttribute("cn", cn));
    attributes.put(
        new BasicAttribute(
            "owner", "cn=" + owner + "," + Play.configuration.getProperty("ldap.dn")));
    Iterator memberIterator = members.iterator();
    BasicAttribute membersAttribute =
        new BasicAttribute(
            "member", "cn=" + owner + "," + Play.configuration.getProperty("ldap.dn"));
    while (memberIterator.hasNext()) {
      String specificMember =
          "cn=" + memberIterator.next() + "," + Play.configuration.getProperty("ldap.dn");
      if (!membersAttribute.contains(specificMember)) membersAttribute.add(specificMember);
    }
    attributes.put(membersAttribute);
    DirContext ldapContext = null;
    try {
      ldapContext = new InitialDirContext(ldapEnv);
      ldapContext.bind(
          "cn=" + cn + "," + Play.configuration.getProperty("ldap.dn"), null, attributes);
      ldapContext.close();

    } catch (Exception e) {
      System.err.println("Erreur lors de l'acces au serveur LDAP " + e);
      e.printStackTrace();
    }
    System.out.println("fin des traitements");
  }
예제 #2
0
  public void addUser(
      Hashtable ldapEnv, String mail, String givenName, String sn, String cn, String userPassword) {

    Attributes attributes = new BasicAttributes(true);
    attributes.put(new BasicAttribute("mail", mail));
    attributes.put(new BasicAttribute("objectClass", "inetOrgPerson"));
    // attributes.put(new BasicAttribute("objectClass","simpleSecurityObject"));
    attributes.put(new BasicAttribute("givenName", givenName));
    attributes.put(new BasicAttribute("sn", sn));
    attributes.put(new BasicAttribute("cn", cn));
    attributes.put(new BasicAttribute("userPassword", userPassword));

    DirContext ldapContext = null;
    try {
      ldapContext = new InitialDirContext(ldapEnv);
      // MonObjet objet = new MonObjet("valeur1","valeur2");
      ldapContext.bind(
          "cn=" + cn + "," + Play.configuration.getProperty("ldap.dn"), null, attributes);
      ldapContext.close();

    } catch (Exception e) {
      System.err.println("Erreur lors de l'acces au serveur LDAP " + e);
      e.printStackTrace();
    }
    System.out.println("fin des traitements");
  }
예제 #3
0
  public Attributes getGroupInfo(Hashtable<String, String> ldapEnv, String groupName) {
    try {
      DirContext ldapContext = null;
      ldapContext = new InitialDirContext(ldapEnv);
      System.out.println("LDAP : Bind Ok = ");
      SearchControls controle = new SearchControls();
      controle.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String critere = "(cn=" + groupName + ")";
      NamingEnumeration<SearchResult> e =
          ldapContext.search(Play.configuration.getProperty("ldap.dn"), critere, controle);
      while (e.hasMore()) {
        SearchResult r = e.next();
        System.out.println("name: " + r.getName());
        System.out.println("object: " + r.getClassName());
        System.out.println("getAttributes: " + r.getAttributes());
        return r.getAttributes();
      }

    } catch (AuthenticationException error) {
      return null;

    } catch (NamingException ex) {
      Logger.getLogger(Ldap.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389");
    DirContext ctx = new InitialDirContext(env);

    String search =
        "(cn=" + data + ")"; /* POTENTIAL FLAW: unsanitized data from untrusted source */

    NamingEnumeration<SearchResult> answer = ctx.search("", search, null);
    while (answer.hasMore()) {
      SearchResult sr = answer.next();
      Attributes a = sr.getAttributes();
      NamingEnumeration<?> attrs = a.getAll();
      while (attrs.hasMore()) {
        Attribute attr = (Attribute) attrs.next();
        NamingEnumeration<?> values = attr.getAll();
        while (values.hasMore()) {
          response.getWriter().println(" Value: " + values.next().toString());
        }
      }
    }
  }
  private void checkAuthentication(
      String rootDn, ActiveDirectoryLdapAuthenticationProvider provider) throws NamingException {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");

    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    @SuppressWarnings("deprecation")
    DistinguishedName searchBaseDn = new DistinguishedName(rootDn);
    when(ctx.search(
            eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
        .thenReturn(new MockNamingEnumeration(sr))
        .thenReturn(new MockNamingEnumeration(sr));

    provider.contextFactory = createContextFactoryReturning(ctx);

    Authentication result = provider.authenticate(joe);

    assertEquals(0, result.getAuthorities().size());

    dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu");

    result = provider.authenticate(joe);

    assertEquals(1, result.getAuthorities().size());
  }
예제 #6
0
  public static void main(String[] args) {
    // set up environment to access the server
    Properties env = new Properties();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + ldapServerName + "/" + rootContext);
    env.put(Context.SECURITY_PRINCIPAL, rootdn);
    env.put(Context.SECURITY_CREDENTIALS, rootpass);

    try {
      // obtain initial directory context using the environment
      DirContext ctx = new InitialDirContext(env);

      // create some random number to add to the directory
      Integer i = new Integer(28420);

      System.out.println("Adding " + i + " to directory...");
      ctx.bind("cn=myRandomInt", i);

      i = new Integer(98765);
      System.out.println("i is now: " + i);

      i = (Integer) ctx.lookup("cn=myRandomInt");
      System.out.println("Retrieved i from directory with value: " + i);

    } catch (NameAlreadyBoundException nabe) {
      System.err.println("value has already been bound!");
    } catch (Exception e) {
      System.err.println(e);
    }
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Returns a
   * <code>java.util.List<String></code> with the Distinguished names of the entries that match. You
   * can specify a match limit
   *
   * @param q DirectoryQuery
   * @param limit An <code>Integer</code> with the limit of matches
   * @return List<String>
   * @exception LDAPException
   */
  public List<String> searchDN(final LDAPDirectoryQuery q, final Integer limit)
      throws LDAPException {
    List<String> results = new ArrayList<String>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      if (limit != null) {
        ctls.setCountLimit(limit.intValue());
      }
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        results.add(sr.getNameInNamespace());
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "searchDN() null pointer");
      throw new LDAPException("search DN null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "searchDN() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return results;
  }
  public boolean loginAdminOk(String login, String password) throws Exception {
    String activeDirectoryIP = configuration.getActiveDirectoryIP();
    String activeDirectoryPort = configuration.getActiveDirectoryPort();
    String activeDirectoryDomain = configuration.getActiveDirectoryDomain();
    String activeDirectoryDC = configuration.getActiveDirectoryDC();

    java.util.Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    properties.setProperty(
        Context.PROVIDER_URL, "ldap://" + activeDirectoryIP + ":" + activeDirectoryPort + "/");
    properties.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    properties.setProperty(Context.SECURITY_PRINCIPAL, login + "@" + activeDirectoryDomain);
    properties.setProperty(Context.SECURITY_CREDENTIALS, password);
    properties.setProperty(Context.REFERRAL, "follow");
    DirContext ctx = new InitialDirContext(properties);
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> results =
        ctx.search(activeDirectoryDC, "(sAMAccountName=" + login + ")", constraints);
    if (results != null && results.hasMore()) {
      SearchResult sr = (SearchResult) results.next();
      String dn = sr.getName();
      log.info("Usuario " + dn + " autenticado correctamente");
      return true;
    }
    return false;
  }
  /**
   * Connect to the DirContext, and retrieve the bound object, as well as its attributes. If no
   * object is bound with the name specified in the URL, then an IOException is thrown.
   *
   * @throws IOException Object not found
   */
  @Override
  public void connect() throws IOException {

    if (!connected) {

      try {
        date = System.currentTimeMillis();
        String path = URL_DECODER.convert(getURL().getFile(), false);
        if (context instanceof ProxyDirContext) {
          ProxyDirContext proxyDirContext = (ProxyDirContext) context;
          String hostName = proxyDirContext.getHostName();
          String contextPath = proxyDirContext.getContextPath();
          if (hostName != null) {
            if (!path.startsWith("/" + hostName + "/")) return;
            path = path.substring(hostName.length() + 1);
          }
          if (contextPath != null) {
            if (!path.startsWith(contextPath + "/")) {
              return;
            }
            path = path.substring(contextPath.length());
          }
        }
        object = context.lookup(path);
        attributes = context.getAttributes(path);
        if (object instanceof Resource) resource = (Resource) object;
        if (object instanceof DirContext) collection = (DirContext) object;
      } catch (NamingException e) {
        // Object not found
      }

      connected = true;
    }
  }
예제 #10
0
  public UserDTO doLdapAuthentication(UserDTO dto) throws Exception {
    log.info("INSIDE LDAP AUTHENTICATION 2");
    UserDTO ldapDTO = null;
    String url = "ldap://172.18.20.0:10389";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {
      ldapDTO = new UserDTO();
      DirContext ctx = new InitialDirContext(env);
      Attributes attrs = ctx.getAttributes("cn=" + dto.getUsername() + ",ou=users,ou=system");
      Attribute userPassword = attrs.get("userPassword");
      String ldapPasswordFromDB = new String((byte[]) userPassword.get());
      String md5EncryptedPassword = encryptLdapPassword("md5", dto.getPassword());
      if (md5EncryptedPassword.equalsIgnoreCase(ldapPasswordFromDB)) {
        ldapDTO.setEmployeeId((String) (attrs.get("employeeNumber").get()));
        ldapDTO.setEmployeeType((String) (attrs.get("employeeType").get()));
        ldapDTO.setUsername((String) (attrs.get("cn").get()));
      }
      ctx.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return ldapDTO;
  }
예제 #11
0
    @Override
    public LdapEntry[] groupSearch(DirContext dirContext, LdapEntry entry)
        throws IOException, NamingException {
      Set<LdapEntry> foundEntries = new HashSet<LdapEntry>();
      // Load the list of group.
      Attributes groups =
          dirContext.getAttributes(entry.getDistinguishedName(), new String[] {groupAttribute});
      Attribute groupRef = groups.get(groupAttribute);
      if (groupRef != null && groupRef.size() > 0) {
        NamingEnumeration<String> groupRefValues = (NamingEnumeration<String>) groupRef.getAll();
        while (groupRefValues.hasMore()) {
          String distingushedName = groupRefValues.next();
          SECURITY_LOGGER.tracef("Group found with distinguishedName=%s", distingushedName);
          String simpleName = null;
          if (groupNameAttribute != null) {
            // Load the Name
            Attributes groupNameAttrs =
                dirContext.getAttributes(distingushedName, new String[] {groupNameAttribute});
            Attribute groupNameAttr = groupNameAttrs.get(groupNameAttribute);
            simpleName = (String) groupNameAttr.get();
            SECURITY_LOGGER.tracef(
                "simpleName %s loaded for group with distinguishedName=%s",
                simpleName, distingushedName);
          } else {
            SECURITY_LOGGER.trace("No groupNameAttribute to load simpleName");
          }
          foundEntries.add(new LdapEntry(simpleName, distingushedName));
        }
      } else {
        SECURITY_LOGGER.tracef("No groups found for %s", entry);
      }

      return foundEntries.toArray(new LdapEntry[foundEntries.size()]);
    }
예제 #12
0
  private LdapUser looukupByFilter(String filter) {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext ctxt;
    try {
      ctxt = connect();
      NamingEnumeration<SearchResult> results = ctxt.search(basedn, filter, sc);
      if (results.hasMore()) {
        SearchResult result = results.next();
        Attributes attrs = result.getAttributes();
        String firstName = attrs.get("givenName").get().toString();
        String lastName = attrs.get("sn").get().toString();
        String cn = attrs.get("cn").get().toString();
        String dn = result.getNameInNamespace();
        String forwardAddress = attrs.get("forward").get().toString();
        String mailAdress = attrs.get("mail").get().toString();
        Attribute addrAttr = attrs.get("privateMail");
        if (addrAttr == null) {
          addrAttr = attrs.get("forward");
        }
        String privateMailAdress = addrAttr.get().toString();

        LdapUser user =
            new LdapUser(
                dn, firstName, lastName, forwardAddress, mailAdress, privateMailAdress, cn);
        return user;
      }
    } catch (NamingException e) {
      log.fatal(e);
      throw new RuntimeException(e);
    }
    return null;
  }
예제 #13
0
  /** Search criteria based on sn(surname) */
  private void searchUsingSubTree() {
    System.out.println("Inside searchUsingSubTree");
    DirContext ctx = LDAPConstants.getLdapContext();
    String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org";
    SearchControls sc = new SearchControls();
    String[] attributeFilter = {"cn", "givenName"};
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "sn=X*";
    // String filter = "(&(sn=R*)(givenName=Sinduja))";   //Examples for search Filters
    // String filter = "(|(sn=R*)(givenName=Sinduja))";

    NamingEnumeration results = null;
    try {
      results = ctx.search(baseDN, filter, sc);
      while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();

        Attribute attr = attrs.get("cn");
        System.out.print("cn : " + attr.get() + "\n");
        attr = attrs.get("givenName");
        System.out.print("givenName: " + attr.get() + "\n");
        ctx.close();
      }
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Infer the root DN.
   *
   * @return null if not found.
   */
  private String inferRootDN(String server) {
    try {
      Hashtable<String, String> props = new Hashtable<String, String>();
      if (managerDN != null) {
        props.put(Context.SECURITY_PRINCIPAL, managerDN);
        props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
      }
      props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      props.put(Context.PROVIDER_URL, toProviderUrl(fixNull(getServerUrl()), ""));

      DirContext ctx = new InitialDirContext(props);
      Attributes atts = ctx.getAttributes("");
      Attribute a = atts.get("defaultNamingContext");
      if (a != null
          && a.get()
              != null) { // this entry is available on Active Directory. See
                         // http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
        return a.get().toString();
      }

      a = atts.get("namingcontexts");
      if (a == null) {
        LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
        return null;
      }
      return a.get().toString();
    } catch (NamingException e) {
      LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
      return null;
    }
  }
예제 #15
0
  private void searchUsingObject() {
    System.out.println("Inside searchUsingObject");
    DirContext ctx = LDAPConstants.getLdapContext();
    // String baseDN = "CN=sindujar,OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org"; //To serach
    // for a particular user
    String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org";
    SearchControls sc = new SearchControls();

    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "objectclass=*";
    // String filter = "(&(sn=R*)(givenName=Sinduja))";   //Examples for search Filters
    // String filter = "(|(sn=R*)(givenName=Sinduja))";

    NamingEnumeration results = null;
    try {
      results = ctx.search(baseDN, filter, sc);
      while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        System.out.println(sr.toString() + "\n");
        ctx.close();
      }
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
예제 #16
0
  /**
   * Return the URL to the resource that is mapped to a specified path. The path must begin with a
   * "/" and is interpreted as relative to the current context root.
   *
   * @param path The path to the desired resource
   * @exception MalformedURLException if the path is not given in the correct form
   */
  public URL getResource(String path) throws MalformedURLException {

    DirContext resources = context.getResources();
    if (resources != null) {
      String fullPath = context.getName() + path;

      // this is the problem. Host must not be null
      String hostName = context.getParent().getName();

      try {
        resources.lookup(path);
        if (System.getSecurityManager() != null) {
          try {
            PrivilegedGetResource dp = new PrivilegedGetResource(hostName, fullPath, resources);
            return (URL) AccessController.doPrivileged(dp);
          } catch (PrivilegedActionException pe) {
            throw pe.getException();
          }
        } else {
          return new URL(
              "jndi",
              null,
              0,
              getJNDIUri(hostName, fullPath),
              new DirContextURLStreamHandler(resources));
        }
      } catch (Exception e) {
        // e.printStackTrace();
      }
    }
    return (null);
  }
예제 #17
0
  public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    // Authenticate as S. User and password "mysecret"
    env.put(Context.SECURITY_AUTHENTICATION, "custom");
    env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "mysecret");

    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);

      System.out.println(ctx.lookup("ou=NewHires"));

      // do something useful with ctx

      // Close the context when we're done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
예제 #18
0
  /**
   * Clear the directory sub-tree starting with the node represented by the supplied distinguished
   * name.
   *
   * @param ctx The DirContext to use for cleaning the tree.
   * @param name the distinguished name of the root node.
   * @throws NamingException if anything goes wrong removing the sub-tree.
   */
  public static void clearSubContexts(DirContext ctx, Name name) throws NamingException {

    NamingEnumeration enumeration = null;
    try {
      enumeration = ctx.listBindings(name);
      while (enumeration.hasMore()) {
        Binding element = (Binding) enumeration.next();
        Name childName = LdapUtils.newLdapName(element.getName());
        childName = LdapUtils.prepend(childName, name);

        try {
          ctx.destroySubcontext(childName);
        } catch (ContextNotEmptyException e) {
          clearSubContexts(ctx, childName);
          ctx.destroySubcontext(childName);
        }
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } finally {
      try {
        enumeration.close();
      } catch (Exception e) {
        // Never mind this
      }
    }
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testRunning() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
    DirContext ctx = new InitialDirContext(env);

    HashSet set = new HashSet();

    NamingEnumeration list = ctx.list("ou=system");

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

    assertTrue(set.contains("uid=admin"));
    assertTrue(set.contains("ou=users"));
    assertTrue(set.contains("ou=groups"));
    assertTrue(set.contains("ou=configuration"));
    assertTrue(set.contains("prefNodeName=sysPrefRoot"));
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions
   *
   * @param q DirectoryQuery
   * @return List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> search(final LDAPDirectoryQuery q) throws LDAPException {
    List<Identity> results = new ArrayList<Identity>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      List<String> _aux = new ArrayList<String>();
      _aux.add("modifyTimestamp");
      _aux.add("*");
      ctls.setReturningAttributes(_aux.toArray(new String[_aux.size()]));
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = null;
        if (sr.getName().isEmpty()) {
          _e = new LDAPDirectoryEntry(baseDN);
        } else {
          _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
          /*
           * _e = new LDAPEntry(sr.getName() + "," + this.baseDN); if(_e.getID().matches(
           * "^(ldap|ldaps)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9\\-]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&amp;%\\$#\\=~])*[^\\.\\,\\)\\(\\s]$"
           * )) { URL _url = new URL(_e.getID()); _e.setID(_url.getPath()); }
           */
        }
        @SuppressWarnings("unchecked")
        NamingEnumeration<Attribute> ne =
            (NamingEnumeration<Attribute>) sr.getAttributes().getAll();
        while (ne.hasMore()) {
          Attribute att = ne.next();
          Object[] attrs = new Object[att.size()];
          @SuppressWarnings("unchecked")
          NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
          for (int i = 0; nea.hasMore(); i++) {
            attrs[i] = nea.next();
          }
          _e.setAttribute(att.getID(), attrs);
        }
        results.add(_e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "search() null pointer");
      throw new LDAPException("search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "search() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return results;
  }
    public FormValidation doServerCheck(
        @QueryParameter final String server,
        @QueryParameter final String managerDN,
        @QueryParameter final String managerPassword) {

      if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) return FormValidation.ok();

      try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null && managerDN.trim().length() > 0 && !"undefined".equals(managerDN)) {
          props.put(Context.SECURITY_PRINCIPAL, managerDN);
        }
        if (managerPassword != null
            && managerPassword.trim().length() > 0
            && !"undefined".equals(managerPassword)) {
          props.put(Context.SECURITY_CREDENTIALS, managerPassword);
        }

        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, toProviderUrl(server, ""));

        DirContext ctx = new InitialDirContext(props);
        ctx.getAttributes("");
        return FormValidation.ok(); // connected
      } catch (NamingException e) {
        // trouble-shoot
        Matcher m =
            Pattern.compile(
                    "(ldaps?://)?([^:]+)(?:\\:(\\d+))?(\\s+(ldaps?://)?([^:]+)(?:\\:(\\d+))?)*")
                .matcher(server.trim());
        if (!m.matches())
          return FormValidation.error(
              hudson.security.Messages.LDAPSecurityRealm_SyntaxOfServerField());

        try {
          InetAddress adrs = InetAddress.getByName(m.group(2));
          int port = m.group(1) != null ? 636 : 389;
          if (m.group(3) != null) port = Integer.parseInt(m.group(3));
          Socket s = new Socket(adrs, port);
          s.close();
        } catch (UnknownHostException x) {
          return FormValidation.error(
              hudson.security.Messages.LDAPSecurityRealm_UnknownHost(x.getMessage()));
        } catch (IOException x) {
          return FormValidation.error(
              x,
              hudson.security.Messages.LDAPSecurityRealm_UnableToConnect(server, x.getMessage()));
        }

        // otherwise we don't know what caused it, so fall back to the general error report
        // getMessage() alone doesn't offer enough
        return FormValidation.error(
            e, hudson.security.Messages.LDAPSecurityRealm_UnableToConnect(server, e));
      } catch (NumberFormatException x) {
        // The getLdapCtxInstance method throws this if it fails to parse the port number
        return FormValidation.error(hudson.security.Messages.LDAPSecurityRealm_InvalidPortNumber());
      }
    }
예제 #22
0
  /**
   * @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String,
   *     java.util.Map)
   */
  public User validateLogin(String username, String password, Map extraParams) {
    Hashtable environment = this.prepareEnvironment();

    StringBuffer principal =
        new StringBuffer(256)
            .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX))
            .append(username)
            .append(',')
            .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX));

    environment.put(Context.SECURITY_PRINCIPAL, principal.toString());
    environment.put(Context.SECURITY_CREDENTIALS, password);

    DirContext dir = null;

    try {
      dir = new InitialDirContext(environment);

      String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX);
      String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX);

      if (lookupPrefix == null || lookupPrefix.length() == 0) {
        lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX);
      }

      if (lookupSuffix == null || lookupSuffix.length() == 0) {
        lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX);
      }

      String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix;

      Attribute att =
          dir.getAttributes(lookupPrincipal)
              .get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL));

      SSOUtils utils = new SSOUtils();

      if (!utils.userExists(username)) {
        String email = att != null ? (String) att.get() : "noemail";
        utils.register("ldap", email);
      }

      return utils.getUser();
    } catch (AuthenticationException e) {
      return null;
    } catch (NamingException e) {
      return null;
    } finally {
      if (dir != null) {
        try {
          dir.close();
        } catch (NamingException e) {
          // close jndi context
        }
      }
    }
  }
 public DirContext createSubcontext(String name, Attributes attrs) throws NamingException {
   ResolveResult res = getRootURLContext(name, myEnv);
   DirContext ctx = (DirContext) res.getResolvedObj();
   try {
     return ctx.createSubcontext(res.getRemainingName(), attrs);
   } finally {
     ctx.close();
   }
 }
 public void rebind(String name, Object obj, Attributes attrs) throws NamingException {
   ResolveResult res = getRootURLContext(name, myEnv);
   DirContext ctx = (DirContext) res.getResolvedObj();
   try {
     ctx.rebind(res.getRemainingName(), obj, attrs);
   } finally {
     ctx.close();
   }
 }
 @Test
 public void testMissingProviderUrlLdapSearches() throws NamingException {
   DirContext context = new TestLdapContext(new Hashtable<Object, Object>());
   try {
     runNonLdapSearchControlsActions(context);
   } finally {
     context.close();
   }
 }
 public DirContext getSchemaClassDefinition(String name) throws NamingException {
   ResolveResult res = getRootURLContext(name, myEnv);
   DirContext ctx = (DirContext) res.getResolvedObj();
   try {
     return ctx.getSchemaClassDefinition(res.getRemainingName());
   } finally {
     ctx.close();
   }
 }
 public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException {
   ResolveResult res = getRootURLContext(name, myEnv);
   DirContext ctx = (DirContext) res.getResolvedObj();
   try {
     ctx.modifyAttributes(res.getRemainingName(), mod_op, attrs);
   } finally {
     ctx.close();
   }
 }
예제 #28
0
  /**
   * Returns a list of AD Groups using the service account
   *
   * @return list of AD Groups
   */
  public static List<String> getADGroupsByServiceAccount() {

    String username = MessageUtils.getMessage("ldap.service.account.username");
    String password = MessageUtils.getMessage("ldap.service.account.password");
    List<String> awsAllGroups = null;

    logger.debug("Starting.....");
    if (username == null || password == null) {
      return new ArrayList<String>();
    }
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, MessageUtils.getMessage("ldap.service.account.url"));
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    DirContext ctx = null;

    try {
      logger.debug("Getting AWS groups using service account");
      ctx = new InitialDirContext(env);
      logger.debug("After InitialDirContext");
      SearchControls controls = new SearchControls();
      controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String attr[] = {"samaccountname"};
      controls.setReturningAttributes(attr);
      NamingEnumeration<SearchResult> result =
          ctx.search(
              MessageUtils.getMessage("ldap.service.account.conf.name"),
              MessageUtils.getMessage("ldap.service.account.conf.filter"),
              controls);
      awsAllGroups = new ArrayList<String>();

      SearchResult sr = null;
      // Loop through the search results
      while (result.hasMoreElements()) {
        sr = (SearchResult) result.next();
        awsAllGroups.add(sr.getName().substring(3));
      }

      return awsAllGroups;
    } catch (AuthenticationException e) {
      logger.error("Service account details are not correct." + e.getMessage());
      return null;
    } catch (NamingException e) {
      logger.error("Unable to connect" + e.getMessage());
      return new ArrayList<String>();
    } finally {
      if (ctx != null) {
        try {
          ctx.close();
        } catch (NamingException e) {

        }
      }
    }
  }
 public Attributes getAttributes(String name, String[] attrIds) throws NamingException {
   ResolveResult res = getRootURLContext(name, myEnv);
   DirContext ctx = (DirContext) res.getResolvedObj();
   try {
     return ctx.getAttributes(res.getRemainingName(), attrIds);
   } finally {
     ctx.close();
   }
 }
 public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons)
     throws NamingException {
   ResolveResult res = getRootURLContext(name, myEnv);
   DirContext ctx = (DirContext) res.getResolvedObj();
   try {
     return ctx.search(res.getRemainingName(), filter, cons);
   } finally {
     ctx.close();
   }
 }