/* 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());
        }
      }
    }
  }
Пример #2
0
  /**
   * @param thisA
   * @param that
   * @return boolean
   * @throws Throwable
   */
  public boolean attrEquals(Attribute thisA, Attribute that) throws Throwable {
    int sz = thisA.size();

    if (sz != that.size()) {
      return false;
    }

    if (sz == 0) {
      return true;
    }

    NamingEnumeration ne = thisA.getAll();

    if (ne == null) {
      return false;
    }

    while (ne.hasMore()) {
      if (!that.contains(ne.next())) {
        return false;
      }
    }

    return true;
  }
Пример #3
0
  protected Map<String, ArrayList<String>> convertAttributes(
      NamingEnumeration<? extends Attribute> attributesEnumeration) {
    Map<String, ArrayList<String>> userInfo = new HashMap<String, ArrayList<String>>();
    try {
      while (attributesEnumeration.hasMore()) {
        Attribute attr = attributesEnumeration.next();
        String id = attr.getID();

        ArrayList<String> values = userInfo.get(id);
        if (values == null) {
          values = new ArrayList<String>();
          userInfo.put(id, values);
        }

        // --- loop on all attribute's values
        NamingEnumeration<?> valueEnum = attr.getAll();

        while (valueEnum.hasMore()) {
          Object value = valueEnum.next();
          // Only retrieve String attribute
          if (value instanceof String) {
            values.add((String) value);
          }
        }
      }
    } catch (NamingException e) {
      e.printStackTrace();
    }
    return userInfo;
  }
Пример #4
0
  /**
   * Compare the given single value with the attribute value(s).
   *
   * @param val
   * @param that
   * @param ignoreCase
   * @return -2 for not equal or not present in multi-valued attribute -1 for val &lt; that 0 for
   *     val = that 1 for val &gt; that 2 for val present in multi-valued attr
   * @throws Throwable
   */
  public int attrValCompare(Object val, Attribute that, boolean ignoreCase) throws Throwable {
    if (that.size() != 1) {
      NamingEnumeration ne = that.getAll();

      if (ne == null) {
        return -2;
      }

      while (ne.hasMore()) {
        Object o = ne.next();
        if (val instanceof String) {
          if (compareVal(o, (String) val, ignoreCase) == 0) {
            return 2;
          }
        } else if (o.equals(val)) {
          return 2;
        }
      }
      return -2;
    }

    /** that is a single valued attribute. */
    Object o = that.get();

    if (val instanceof String) {
      return compareVal(o, (String) val, ignoreCase);
    }

    if (o.equals(val)) {
      return 0;
    }

    return -2;
  }
Пример #5
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()]);
    }
Пример #6
0
 public static int verifyMaliciousPassword(String login, String mail) {
   String mailAdresse = "";
   Ldap adminConnection = new Ldap();
   adminConnection.SetEnv(
       Play.configuration.getProperty("ldap.host"),
       Play.configuration.getProperty("ldap.admin.dn"),
       Play.configuration.getProperty("ldap.admin.password"));
   Attributes f = adminConnection.getUserInfo(adminConnection.getLdapEnv(), login);
   try {
     NamingEnumeration e = f.getAll();
     while (e.hasMore()) {
       javax.naming.directory.Attribute a = (javax.naming.directory.Attribute) e.next();
       String attributeName = a.getID();
       String attributeValue = "";
       Enumeration values = a.getAll();
       while (values.hasMoreElements()) {
         attributeValue = values.nextElement().toString();
       }
       if (attributeName.equals("mail")) {
         mailAdresse = attributeValue;
       }
     }
   } catch (javax.naming.NamingException e) {
     System.out.println(e.getMessage());
     return 0;
   } finally {
     if (mailAdresse.equals("")) {
       return Invitation.USER_NOTEXIST;
     } else if (mailAdresse.equals(mail)) {
       return Invitation.ADDRESSES_MATCHE;
     } else {
       return Invitation.ADDRESSES_NOTMATCHE;
     }
   }
 }
Пример #7
0
  /**
   * Returns the host name and port that the specified XMPP server can be reached at for
   * client-to-server communication. A DNS lookup for a SRV record in the form
   * "_xmpp-client._tcp.example.com" is attempted, according to section 14.4 of RFC 3920. If that
   * lookup fails, a lookup in the older form of "_jabber._tcp.example.com" is attempted since
   * servers that implement an older version of the protocol may be listed using that notation. If
   * that lookup fails as well, it's assumed that the XMPP server lives at the host resolved by a
   * DNS lookup at the specified domain on the default port of 5222.
   *
   * <p>As an example, a lookup for "example.com" may return "im.example.com:5269".
   *
   * <p>Note on SRV record selection. We now check priority and weight, but we still don't do this
   * correctly. The missing behavior is this: if we fail to reach a host based on its SRV record
   * then we need to select another host from the other SRV records. In Smack 3.1.1 we're not going
   * to be able to do the major system redesign to correct this.
   *
   * @param domain the domain.
   * @return a HostAddress, which encompasses the hostname and port that the XMPP server can be
   *     reached at for the specified domain.
   */
  public static HostAddress resolveXMPPDomain(String domain) {
    if (context == null) {
      return new HostAddress(domain, 5222);
    }
    String key = "c" + domain;
    // Return item from cache if it exists.
    if (cache.containsKey(key)) {
      HostAddress address = (HostAddress) cache.get(key);
      if (address != null) {
        return address;
      }
    }
    String bestHost = domain;
    int bestPort = 5222;
    int bestPriority = 0;
    int bestWeight = 0;
    try {
      Attributes dnsLookup =
          context.getAttributes("_xmpp-client._tcp." + domain, new String[] {"SRV"});
      Attribute srvAttribute = dnsLookup.get("SRV");
      NamingEnumeration srvRecords = srvAttribute.getAll();
      while (srvRecords.hasMore()) {
        String srvRecord = (String) srvRecords.next();
        String[] srvRecordEntries = srvRecord.split(" ");
        int priority = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 4]);
        int port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 2]);
        int weight = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 3]);
        String host = srvRecordEntries[srvRecordEntries.length - 1];

        // Randomize the weight.
        weight *= Math.random() * weight;

        if ((bestPriority == 0) || (priority < bestPriority)) {
          // Choose a server with the lowest priority.
          bestPriority = priority;
          bestWeight = weight;
          bestHost = host;
          bestPort = port;
        } else if (priority == bestPriority) {
          // When we have like priorities then randomly choose a server based on its weight
          // The weights were randomized above.
          if (weight > bestWeight) {
            bestWeight = weight;
            bestHost = host;
            bestPort = port;
          }
        }
      }
    } catch (Exception e) {
      // Ignore.
    }
    // Host entries in DNS should end with a ".".
    if (bestHost.endsWith(".")) {
      bestHost = bestHost.substring(0, bestHost.length() - 1);
    }
    HostAddress address = new HostAddress(bestHost, bestPort);
    // Add item to cache.
    cache.put(key, address);
    return address;
  }
  protected List<User> findUsersByGroupId(LdapUserQueryImpl query) {
    String baseDn = getDnForGroup(query.getGroupId());

    // compose group search filter
    String groupSearchFilter = "(& " + ldapConfiguration.getGroupSearchFilter() + ")";

    NamingEnumeration<SearchResult> enumeration = null;
    try {
      enumeration =
          initialContext.search(baseDn, groupSearchFilter, ldapConfiguration.getSearchControls());

      List<String> groupMemberList = new ArrayList<String>();

      // first find group
      while (enumeration.hasMoreElements()) {
        SearchResult result = enumeration.nextElement();
        Attribute memberAttribute =
            result.getAttributes().get(ldapConfiguration.getGroupMemberAttribute());
        if (null != memberAttribute) {
          NamingEnumeration<?> allMembers = memberAttribute.getAll();

          // iterate group members
          while (allMembers.hasMoreElements() && groupMemberList.size() < query.getMaxResults()) {
            groupMemberList.add((String) allMembers.nextElement());
          }
        }
      }

      List<User> userList = new ArrayList<User>();
      String userBaseDn =
          composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn());
      for (String memberId : groupMemberList) {
        if (ldapConfiguration.isUsePosixGroups()) {
          query.userId(memberId);
        }
        List<User> users =
            ldapConfiguration.isUsePosixGroups()
                ? findUsersWithoutGroupId(query, userBaseDn)
                : findUsersWithoutGroupId(query, memberId);
        if (users.size() > 0) {
          userList.add(users.get(0));
        }
      }

      return userList;

    } catch (NamingException e) {
      throw new IdentityProviderException("Could not query for users", e);

    } finally {
      try {
        if (enumeration != null) {
          enumeration.close();
        }
      } catch (Exception e) {
        // ignore silently
      }
    }
  }
  /**
   * 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;
  }
Пример #10
0
  /**
   * Retrieve an enumeration of the named attribute's values. The behaviour of this enumeration is
   * unspecified if the the attribute's values are added, changed, or removed while the enumeration
   * is in progress. If the attribute values are ordered, the enumeration's items will be ordered.
   *
   * <p>Each element of the enumeration is a possibly null Object. The object's class is the class
   * of the attribute value. The element is null if the attribute's value is null. If the attribute
   * has zero values, an empty enumeration is returned.
   *
   * @param attr
   * @return NamingEnumeration
   * @throws NamingException
   */
  public NamingEnumeration attrElements(String attr) throws NamingException {
    Attribute a = findAttr(attr);

    if (a == null) {
      return null;
    }

    return a.getAll();
  }
    @Override
    public void processValues(Attributes attributes, String attributeName) throws NamingException {
      Attribute attribute = attributes.get(attributeName);
      NamingEnumeration<?> valueEnum = attribute.getAll();

      initValuesIfApplicable();
      while (valueEnum.hasMore()) {
        values.add(valueEnum.next());
      }
    }
  /* uses badsource and badsink - see how tools report flaws that don't always occur */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      /* retrieve the property */
      Properties props = new Properties();
      FileInputStream finstr = null;
      try {
        finstr = new FileInputStream("../common/config.properties");
        props.load(finstr);
        data = props.getProperty("data");
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (finstr != null) {
            finstr.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        }
      }
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    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());
        }
      }
    }
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Results will
   * be order using the values of a specific attribute
   *
   * @param q DirectoryQuery
   * @param attribute Name of the attribute that determines the order
   * @return java.util.List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> sortedSearch(final LDAPDirectoryQuery q, final String attribute)
      throws LDAPException {
    TreeMap<String, Identity> results =
        new TreeMap<String, Identity>(Collator.getInstance(new Locale("es")));
    try {
      LdapContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("Directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());
      ctx.setRequestControls(new Control[] {new SortControl(attribute, Control.NONCRITICAL)});

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
        @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);
        }
        String _value = String.valueOf(_e.getAttribute(attribute)[0]);
        while (results.containsKey(_value)) {
          _value = _value.concat("0");
        }
        results.put(_value, _e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() null pointer");
      throw new LDAPException("sorted search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } catch (IOException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return new ArrayList<Identity>(results.values());
  }
Пример #14
0
 public static void listerAttributs(Attributes atts) {
   try {
     for (NamingEnumeration e = atts.getAll(); e.hasMore(); ) {
       Attribute a = (Attribute) e.next();
       System.out.println(a.getID() + ":");
       Enumeration values = a.getAll();
       while (values.hasMoreElements()) {
         System.out.println("valeur : " + values.nextElement().toString());
       }
     }
   } catch (javax.naming.NamingException e) {
     System.out.println(e.getMessage());
   }
 }
Пример #15
0
  public Object getObjectInstance(
      Object obj, Name name, Context ctx, Hashtable<?, ?> env, Attributes inAttrs)
      throws Exception {

    if (obj instanceof DirContext) {
      Attribute objectClass = inAttrs.get("objectClass");
      NamingEnumeration<?> ne = objectClass.getAll();
      while (ne.hasMore()) {
        if (ne.next().equals("Service")) {
          return new Service(inAttrs);
        }
      }
    }

    return null;
  }
  /* goodG2B1() - use goodsource and badsink by changing IO.staticTrue to IO.staticFalse */
  private void goodG2B1() throws Throwable {
    String data;
    if (IO.staticFalse) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

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

    try {
      directoryContext = new InitialDirContext(environmentHashTable);
      /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection */
      String search = "(cn=" + data + ")";

      NamingEnumeration<SearchResult> answer = directoryContext.search("", search, null);
      while (answer.hasMore()) {
        SearchResult searchResult = answer.next();
        Attributes attributes = searchResult.getAttributes();
        NamingEnumeration<?> allAttributes = attributes.getAll();
        while (allAttributes.hasMore()) {
          Attribute attribute = (Attribute) allAttributes.next();
          NamingEnumeration<?> allValues = attribute.getAll();
          while (allValues.hasMore()) {
            IO.writeLine(" Value: " + allValues.next().toString());
          }
        }
      }
    } catch (NamingException exceptNaming) {
      IO.logger.log(Level.WARNING, "The LDAP service was not found or login failed.", exceptNaming);
    } finally {
      if (directoryContext != null) {
        try {
          directoryContext.close();
        } catch (NamingException exceptNaming) {
          IO.logger.log(Level.WARNING, "Error closing DirContext", exceptNaming);
        }
      }
    }
  }
 /**
  * Gets an <code>LDAPDirectoryEntry</code> object that represent an entry on directory. You can
  * provide a list of attributes to be ignored when load the entry data. Look for attribute matches
  * using a map of values
  *
  * @param DN Distinguished Name of the entry
  * @param ignore_attributes You can indicate here a list of attribute to be ignored when load all
  *     entry data. this is useful if you have some big data in some attributes and do you want to
  *     ignore that
  * @param attribute_matches Map with attribute names and values to match
  * @return LDAPDirectoryEntry
  * @exception LDAPException
  */
 public LDAPDirectoryEntry getEntry(
     final String DN,
     final List<String> ignore_attributes,
     final Map<String, String> attribute_matches)
     throws LDAPException {
   LDAPDirectoryEntry _e = null;
   try {
     _e = new LDAPDirectoryEntry(DN);
     DirContext ctx = connection.connect();
     if (ctx == null) {
       throw new LDAPException("directory service not available");
     }
     Attributes atts = ctx.getAttributes(DN);
     if (atts == null) {
       return null;
     }
     @SuppressWarnings("unchecked")
     NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) atts.getAll();
     while (ne.hasMore()) {
       Attribute att = ne.next();
       if (ignore_attributes == null || !ignore_attributes.contains(att.getID())) {
         List<Object> _values = new ArrayList<Object>();
         @SuppressWarnings("unchecked")
         NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
         while (nea.hasMore()) {
           Object _value = nea.next();
           if (attribute_matches == null || !attribute_matches.containsKey(att.getID())) {
             _values.add(_value);
           } else if (attribute_matches.get(att.getID()) != null
               && String.valueOf(_value).contains(attribute_matches.get(att.getID()))) {
             _values.add(_value);
           }
         }
         _e.setAttribute(att.getID(), _values.toArray());
       }
     }
   } catch (NullPointerException e) {
     _log.log(java.util.logging.Level.ALL, "getEntry() null pointer");
     throw new LDAPException("get entry null pointer");
   } catch (NamingException e) {
     _log.log(java.util.logging.Level.ALL, "getEntry() - " + e.getMessage());
     throw new LDAPException(e.getMessage());
   } finally {
     connection.disconnect();
   }
   return _e;
 }
Пример #18
0
  /**
   * This looks through a list of object classes in an attribute until it finds a unique editor
   * corresponding to a particular value. If no editor is found 'null' is returned. Note that If
   * multiple unique editors exist, which one is returned is undefined.
   *
   * <p>
   *
   * @param oc the objectClass attribute; a list of object classes
   * @return the unique pluggable editor corresponding to one particular object class value, or null
   *     if none is found.
   */
  public PluggableEditor getUniqueEditor(Attribute oc) {
    try {
      Enumeration values = oc.getAll();
      while (values.hasMoreElements()) {
        String objectClassName = (String) values.nextElement();

        PluggableEditor editor = getEditor(objectClassName);
        if (editor != null) {
          if (editor.isUnique()) return editor;
        }
      }
      return null;
    } catch (Exception e) {
      log.log(Level.FINE, "Unable to find unique pluggable editor: ", e);
      return null;
    }
  }
Пример #19
0
 private ArrayImpl getArray(
     Class<?> componentType, Attribute resultAttr, Column modelElement, String modelAttrName)
     throws NamingException, TranslatorException {
   ArrayList<Object> multivalList = new ArrayList<Object>();
   NamingEnumeration<?> attrNE = resultAttr.getAll();
   int length = 0;
   while (attrNE.hasMore()) {
     try {
       multivalList.add(
           convertSingleValue(modelElement, modelAttrName, componentType, attrNE.next()));
       length++;
     } catch (InvalidNameException e) {
       // just ignore
     }
   }
   Object[] values = (Object[]) Array.newInstance(componentType, length);
   ArrayImpl value = new ArrayImpl(multivalList.toArray(values));
   return value;
 }
Пример #20
0
 /**
  * Print Attributes to System.out
  *
  * @param attrs
  */
 private static void dump(Attributes attrs) {
   if (attrs == null) {
     System.out.println("No attributes");
   } else {
     /* Print each attribute */
     try {
       for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMore(); ) {
         Attribute attr = ae.next();
         System.out.println("attribute: " + attr.getID());
         /* print each value */
         for (NamingEnumeration<?> e = attr.getAll();
             e.hasMore();
             System.out.println("    value: " + e.next())) ;
       }
     } catch (NamingException e) {
       e.printStackTrace();
     }
   }
 } //	dump
Пример #21
0
  private List<String> addAttributeValues(String attrId, Attributes attrs, List<String> values)
      throws NamingException {

    if (attrId == null || attrs == null) {
      return values;
    }
    if (values == null) {
      values = new ArrayList<String>();
    }
    Attribute attr = attrs.get(attrId);
    if (attr == null) {
      return values;
    }
    NamingEnumeration<?> e = attr.getAll();
    while (e.hasMore()) {
      String value = (String) e.next();
      values.add(value);
    }
    return values;
  }
  public void bad() throws Throwable {
    String data;

    badPrivate = true;
    data = bad_source();

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

    try {
      directoryContext = new InitialDirContext(environmentHashTable);
      /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection */
      String search = "(cn=" + data + ")";

      NamingEnumeration<SearchResult> answer = directoryContext.search("", search, null);
      while (answer.hasMore()) {
        SearchResult searchResult = answer.next();
        Attributes attributes = searchResult.getAttributes();
        NamingEnumeration<?> allAttributes = attributes.getAll();
        while (allAttributes.hasMore()) {
          Attribute attribute = (Attribute) allAttributes.next();
          NamingEnumeration<?> allValues = attribute.getAll();
          while (allValues.hasMore()) {
            IO.writeLine(" Value: " + allValues.next().toString());
          }
        }
      }
    } catch (NamingException exceptNaming) {
      IO.logger.log(Level.WARNING, "The LDAP service was not found or login failed.", exceptNaming);
    } finally {
      if (directoryContext != null) {
        try {
          directoryContext.close();
        } catch (NamingException exceptNaming) {
          IO.logger.log(Level.WARNING, "Error closing DirContext", exceptNaming);
        }
      }
    }
  }
Пример #23
0
  /**
   * Return true if the record contains all of the values of the given attribute.
   *
   * @param attr Attribute we're looking for
   * @return boolean true if we found it
   * @throws Throwable
   */
  public boolean contains(Attribute attr) throws Throwable {
    if (attr == null) {
      return false; // protect
    }

    Attribute recAttr = getAttributes().get(attr.getID());

    if (recAttr == null) {
      return false;
    }

    NamingEnumeration ne = attr.getAll();

    while (ne.hasMore()) {
      if (!recAttr.contains(ne.next())) {
        return false;
      }
    }

    return true;
  }
  /**
   * Gets values of an entry attribute using a Distinguished Name and the name of the attribute
   *
   * @param DN Distinguished Name of the entry
   * @param attribute name of the attribute
   * @return List<Object>
   * @exception LDAPException
   */
  public List<Object> getEntryAttribute(final String DN, final String attribute)
      throws LDAPException {
    List<Object> _values = new ArrayList<Object>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      Attributes _atts = null;
      if ("modifyTimestamp".equals(attribute)) {
        String[] _attributeName = new String[1];
        _attributeName[0] = attribute;
        _atts = ctx.getAttributes(DN, _attributeName);
      } else {
        _atts = ctx.getAttributes(DN);
        if (_atts == null) {
          throw new LDAPException("entry not found [" + DN + "]");
        }
      }
      Attribute _att = _atts.get(attribute);
      if (_att == null) {
        throw new LDAPException("attribute [" + attribute + "] not found in entry");
      }

      @SuppressWarnings("unchecked")
      NamingEnumeration<Object> _ne = (NamingEnumeration<Object>) _att.getAll();
      while (_ne.hasMore()) {
        _values.add(_ne.next());
      }
      return _values;
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "getEntryAttribute() null pointer");
      throw new LDAPException("get entry attribute null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "getEntryAttribute() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
  }
Пример #25
0
  /**
   * LDAP属性 定义 o Organization:组织 ou Organization unit:组织单元 uid Userid:用户id cn Common name:常见名称 sn 姓
   * givenname 首名 dn Distinguished Name:区分名称
   *
   * @param username
   * @throws NamingException
   */
  public void search(String username) throws NamingException {
    System.out.println("Searching...");
    SearchControls searchCtls = new SearchControls();

    // Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // specify the LDAP search filter
    String searchFilter = "uid=" + username;

    // Specify the Base for the search
    String searchBase = LDAP_BASE;

    // Specify the attributes to return
    String returnedAtts[] = {"cn"};
    searchCtls.setReturningAttributes(returnedAtts);

    // Search for objects using the filter
    NamingEnumeration<SearchResult> entries = ds.search(searchBase, searchFilter, searchCtls);

    // Loop through the search results
    while (entries.hasMoreElements()) {
      SearchResult entry = entries.next();
      System.out.println(">>>" + entry.getName());
      // Print out the groups
      Attributes attrs = entry.getAttributes();
      if (attrs != null) {
        for (NamingEnumeration<? extends Attribute> names = attrs.getAll(); names.hasMore(); ) {
          Attribute attr = names.next();
          System.out.println("AttributeID: " + attr.getID());

          for (NamingEnumeration<?> e = attr.getAll(); e.hasMore(); ) {
            System.out.println("Attributes:" + e.next());
          }
        }
      }
    }
    System.out.println("Search complete.");
  }
  /** Returns an unmodifiable Map of the header fields. */
  @Override
  public Map<String, List<String>> getHeaderFields() {

    if (!connected) {
      // Try to connect (silently)
      try {
        connect();
      } catch (IOException e) {
        // Ignore
      }
    }

    if (attributes == null) return (Collections.emptyMap());

    HashMap<String, List<String>> headerFields =
        new HashMap<String, List<String>>(attributes.size());
    NamingEnumeration<String> attributeEnum = attributes.getIDs();
    try {
      while (attributeEnum.hasMore()) {
        String attributeID = attributeEnum.next();
        Attribute attribute = attributes.get(attributeID);
        if (attribute == null) continue;
        ArrayList<String> attributeValueList = new ArrayList<String>(attribute.size());
        NamingEnumeration<?> attributeValues = attribute.getAll();
        while (attributeValues.hasMore()) {
          Object attrValue = attributeValues.next();
          attributeValueList.add(getHeaderValueAsString(attrValue));
        }
        attributeValueList.trimToSize(); // should be a no-op if attribute.size() didn't lie
        headerFields.put(attributeID, Collections.unmodifiableList(attributeValueList));
      }
    } catch (NamingException ne) {
      // Shouldn't happen
    }

    return Collections.unmodifiableMap(headerFields);
  }
  /* goodG2B() - use goodsource and badsink by changing the "if" so that
  both branches use the GoodSource */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    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());
        }
      }
    }
  }
Пример #28
0
  /** Parse Definition Attributes for a LDAP matching rule */
  static LDAPMatchingRuleSchema parseDefAttributes(Attributes attrs) throws NamingException {
    String name = null, oid = null, desc = null, syntax = null;
    boolean obsolete = false;
    Vector applies = new Vector();

    for (Enumeration attrEnum = attrs.getAll(); attrEnum.hasMoreElements(); ) {
      Attribute attr = (Attribute) attrEnum.nextElement();
      String attrName = attr.getID();
      if (attrName.equals(NAME)) {
        name = getSchemaAttrValue(attr);
      } else if (attrName.equals(NUMERICOID)) {
        oid = getSchemaAttrValue(attr);
      } else if (attrName.equals(SYNTAX)) {
        syntax = getSchemaAttrValue(attr);
      } else if (attrName.equals(DESC)) {
        desc = getSchemaAttrValue(attr);
      } else if (attrName.equals(APPLIES)) {
        for (Enumeration valEnum = attr.getAll(); valEnum.hasMoreElements(); ) {
          applies.addElement((String) valEnum.nextElement());
        }
      } else if (attrName.equals(OBSOLETE)) {
        obsolete = parseTrueFalseValue(attr);
      } else {
        throw new NamingException(
            "Invalid schema attribute type for matching rule definition " + attrName);
      }
    }

    LDAPMatchingRuleSchema mrule =
        new LDAPMatchingRuleSchema(name, oid, desc, vectorToStringAry(applies), syntax);

    if (obsolete) {
      mrule.setQualifier(OBSOLETE, "");
    }
    return mrule;
  }
Пример #29
0
  /**
   * Authenticated a user and returns a list of groups that the user belongs to
   *
   * @param username
   * @param password
   * @return list of groups
   */
  public static List<String> authenticate(String username, String password) {
    logger.debug("Starting.....");
    if (username == null || password == null) {
      return null;
    }
    List<String> awsList = null;
    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;
    String defaultSearchBase = MessageUtils.getMessage("ldap.service.account.conf.search_base");

    try {
      logger.debug("In the try block");
      ctx = new InitialDirContext(env);
      logger.debug("After InitialDirContext");

      // userName is SAMAccountName
      SearchResult sr =
          executeSearchSingleResult(
              ctx,
              SearchControls.SUBTREE_SCOPE,
              defaultSearchBase,
              MessageFormat.format(MAIL, new Object[] {username}),
              new String[] {DISTINGUISHED_NAME, CN, MEMBER_OF});
      logger.debug("Search results :" + sr.getName());

      // Look for and process memberOf
      Attribute memberOf = sr.getAttributes().get(MEMBER_OF);

      logger.debug("Member of :" + memberOf);
      NamingEnumeration<?> ne = memberOf.getAll();

      awsList = new ArrayList<String>();

      while (ne.hasMoreElements()) {
        String member = (String) ne.nextElement();

        if (member != null && member.startsWith("CN=AWS")) {
          member = member.substring(3, member.indexOf(","));
          awsList.add(member);
        }
      }
      logger.debug("Size in auth method: " + awsList.size());

      return awsList;
    } catch (AuthenticationException e) {
      logger.info(username + " is NOT authenticated");
      return null;
    } catch (NamingException e) {
      logger.info("Unable to connect");
      logger.fatal(e.getStackTrace());
      return null;
    } finally {
      if (ctx != null) {
        try {
          ctx.close();
        } catch (NamingException e) {

        }
      }
    }
  }
Пример #30
0
  public LDAPAuthenticationUser getUserAttributes(LdapSearch search, String[] attributes)
      throws SecurityException {
    LDAPAuthenticationUser ldapAUser = new LDAPAuthenticationUser();
    if (search.getM_srAttrs() == null) {
      throw new SecurityException(SecurityException.ERROR_CAN_NOT_FIND_USER_ATTRIBUTES_LDAP);
    } else {
      try {
        Object object = null;
        for (NamingEnumeration enum1 = search.getM_srAttrs().getAll(); enum1.hasMore(); ) {
          Attribute attrib = (Attribute) enum1.next();

          for (NamingEnumeration e = attrib.getAll(); e.hasMore(); ) {
            object = e.next();
            try {
              if (attrib.getID().equals(attributes[0])) {
                ldapAUser.setGuid(object);
              }
              if (attrib.getID().equals(attributes[1])) {
                ldapAUser.setDn((String) object);
              }

              if (attrib.getID().equals(attributes[2])) {
                String obj = (String) object;
                if (attributes[2].equals("CN")) {
                  if (obj != null && !obj.equals("")) {
                    ldapAUser.setFullName((String) object);
                  }
                } else {
                  if (ldapAUser.getFullName() == null && obj != null && !obj.equals("")) {
                    ldapAUser.setFullName((String) object);
                  }
                }
              }

              if (attrib.getID().equals(attributes[3])) {
                String obj = (String) object;
                if (attributes[3].equals("cn")) {
                  if (obj != null && !obj.equals("")) {
                    ldapAUser.setFullName((String) object);
                  }
                } else {
                  if (ldapAUser.getFullName() == null && obj != null && !obj.equals("")) {
                    ldapAUser.setFullName((String) object);
                  }
                }
              }

              if (attrib.getID().equals(attributes[4])) {
                String obj = (String) object;
                if (ldapAUser.getFullName() == null && obj != null && !obj.equals("")) {
                  ldapAUser.setFullName((String) object);
                }
              }
              if (attrib.getID().equals(attributes[5])) {
                ldapAUser.setGroups((String) object);
              }
            } catch (Exception ex) {
            }
          }
        }

      } catch (NamingException e) {
        throw new SecurityException(SecurityException.ERROR_CAN_NOT_FIND_USER_ATTRIBUTES_LDAP);
      } catch (Exception e) {
        throw new SecurityException(SecurityException.ERROR_CAN_NOT_FIND_USER_ATTRIBUTES_LDAP);
      }
    }

    return ldapAUser;
  }