static boolean checkMatchingSearchResult(
      NamingEnumeration<SearchResult> result, String attrName, Object expValue)
      throws NamingException {
    while ((result != null) && result.hasMore()) {
      SearchResult sr = result.nextElement();
      Attributes attrs = sr.getAttributes();

      NamingEnumeration<? extends Attribute> attrVals = attrs.getAll();
      try {
        while ((attrVals != null) && attrVals.hasMore()) {
          Attribute a = attrVals.next();
          String attrID = a.getID();
          if (!attrName.equalsIgnoreCase(attrID)) {
            continue;
          }

          Object attrVal = a.get();
          if (expValue.equals(attrVal)) {
            return true;
          }
        }
      } finally {
        if (attrVals != null) {
          attrVals.close();
        }
      }
    }

    return false;
  }
  public Map<String, String> getAttributes(User user) throws DataSourceException, ConfigException {
    try {
      String s =
          "(&(objectClass="
              + source.getUsersObjectClassValue()
              + ")("
              + source.getUsersIdKey()
              + "="
              + user.getUid()
              + "))";
      List<SearchResult> r = this.search(s, SecurityEntityType.USER);
      if (!r.isEmpty()) {
        Attributes attrs = r.get(0).getAttributes();
        Map<String, String> items = new HashMap<String, String>();
        NamingEnumeration<? extends Attribute> lst = attrs.getAll();
        while (lst.hasMoreElements()) {
          Attribute attr = lst.nextElement();
          if (attr.get() != null) {
            items.put(attr.getID(), attr.get().toString());
          }
        }

        return items;
      } else {
        return null;
      }
    } catch (javax.naming.AuthenticationException e) {
      throw new ConfigException(e, "LDAP connection failed, please check your settings");
    } catch (NamingException e) {
      throw new DataSourceException(e, "LDAP Exception : " + e.getMessage());
    }
  }
示例#3
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;
     }
   }
 }
  /* 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());
        }
      }
    }
  }
示例#5
0
 public List<Roles> getRoles(Roles roles) {
   LOG.info("Inside getRoles");
   List<Roles> rolesList = new ArrayList<Roles>();
   DirContext ctx = LDAPConstants.getLdapContext();
   String baseDN = PropertyFileReader.getProperty(IAMApplicationConstants.BASEDN_ROLES);
   SearchControls sc = new SearchControls();
   sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
   String retAttrs[] = {
     "whenCreated",
     "whenChanged",
     "cn",
     "name",
     "distinguishedName",
     "groupType",
     "ibRolesName",
     "ibRolesAppSelection",
     "ibRolesOwner",
     "ibRolesIsIBIS",
     "ibRolesReqBy",
     "ibRolesBusArea",
     "ibRolesStartDate",
     "ibRolesType",
     "ibRolesIsOwner",
     "ibRolesAuthBy",
     "ibRolesDescription",
     "member",
     "ibRolesStatus",
     "ibRolesCode",
     "ibRolesEndDate",
     "ibRolesCVReq"
   };
   sc.setReturningAttributes(retAttrs);
   String filter = buildFilter(roles);
   LOG.info("Filter--" + filter);
   NamingEnumeration results = null;
   try {
     results = ctx.search(baseDN, filter, sc);
     while (results.hasMore()) {
       SearchResult sr = (SearchResult) results.next();
       Attributes attrs = sr.getAttributes();
       NamingEnumeration e = attrs.getAll();
       Roles ioRoles = new Roles();
       while (e.hasMoreElements()) {
         Attribute attr = (Attribute) e.nextElement();
         ioRoles = (Roles) getResults(attr, ioRoles);
       }
       rolesList.add(ioRoles);
     }
     ctx.close();
   } catch (NamingException e) {
     e.printStackTrace();
   }
   return rolesList;
 }
  /* 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());
        }
      }
    }
  }
示例#7
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());
   }
 }
示例#8
0
 private void getAllAttributes() {
   System.out.println("Inside getAllAttributes");
   Attributes attrs = null;
   try {
     DirContext ctx = LDAPConstants.getLdapContext();
     attrs = ctx.getAttributes("");
     NamingEnumeration enm = attrs.getAll();
     while (enm.hasMore()) {
       System.out.println(enm.next());
     }
   } catch (NamingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
示例#9
0
 /**
  * Send anonymous email. Note that although we could give any address as from address, (for
  * example: <b>'[email protected]' is valid</b>), the from of MailMessage should always be the correct format
  * of email address(for example the <b>'aaaa' is invalid</b>). Otherwise an exception would be
  * thrown say that username is invalid.
  *
  * @param mail The MailMessage object which contains at least all the required attributes to be
  *     sent.
  */
 public static void sendAnonymousEmail(MailMessage mail) {
   String dns = "dns://";
   Hashtable<String, String> env = new Hashtable<String, String>();
   env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
   env.put(Context.PROVIDER_URL, dns);
   String[] tos = mail.getTos();
   try {
     DirContext ctx = new InitialDirContext(env);
     for (String to : tos) {
       String domain = to.substring(to.indexOf('@') + 1);
       // Get MX(Mail eXchange) records from DNS
       Attributes attrs = ctx.getAttributes(domain, new String[] {"MX"});
       if (attrs == null || attrs.size() <= 0) {
         throw new java.lang.IllegalStateException(
             "Error: Your DNS server has no Mail eXchange records!");
       }
       @SuppressWarnings("rawtypes")
       NamingEnumeration servers = attrs.getAll();
       String smtpHost = null;
       boolean isSend = false;
       StringBuffer buf = new StringBuffer();
       // try all the mail exchange server to send the email.
       while (servers.hasMore()) {
         Attribute hosts = (Attribute) servers.next();
         for (int i = 0; i < hosts.size(); ++i) {
           // sample: 20 mx2.qq.com
           smtpHost = (String) hosts.get(i);
           // parse the string to get smtpHost. sample: mx2.qq.com
           smtpHost = smtpHost.substring(smtpHost.lastIndexOf(' ') + 1);
           try {
             sendEmail(smtpHost, mail, true);
             isSend = true;
             return;
           } catch (Exception e) {
             LOGGER.error("", e);
             buf.append(e.toString()).append("\r\n");
             continue;
           }
         }
       }
       if (!isSend) {
         throw new java.lang.IllegalStateException("Error: Send email error." + buf.toString());
       }
     }
   } catch (NamingException e) {
     LOGGER.error("", e);
   }
 }
 /**
  * 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;
 }
  /* 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);
        }
      }
    }
  }
示例#12
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
  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);
        }
      }
    }
  }
示例#14
0
 /**
  * Constructs an Rdn from the given attribute set. See {@link javax.naming.directory.Attributes
  * Attributes}.
  *
  * <p>The string attribute values are not interpreted as <a
  * href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a> formatted RDN strings. That is, the
  * values are used literally (not parsed) and assumed to be unescaped.
  *
  * @param attrSet The non-null and non-empty attributes containing type/value mappings.
  * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot be used to construct a
  *     valid RDN.
  */
 public Rdn(Attributes attrSet) throws InvalidNameException {
   if (attrSet.size() == 0) {
     throw new InvalidNameException("Attributes cannot be empty");
   }
   entries = new ArrayList<>(attrSet.size());
   NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
   try {
     for (int nEntries = 0; attrs.hasMore(); nEntries++) {
       RdnEntry entry = new RdnEntry();
       Attribute attr = attrs.next();
       entry.type = attr.getID();
       entry.value = attr.get();
       entries.add(nEntries, entry);
     }
   } catch (NamingException e) {
     InvalidNameException e2 = new InvalidNameException(e.getMessage());
     e2.initCause(e);
     throw e2;
   }
   sort(); // arrange entries for comparison
 }
示例#15
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.");
  }
  /** {@inheritDoc} */
  @Override
  public void createEntry(LdapName dn, Attributes attributes) throws NamingException {
    Assert.assertFalse(alreadyAdded);
    Assert.assertEquals(dn, expectedDN);

    Map<String, List<String>> expected = new HashMap<String, List<String>>(this.attributes);
    NamingEnumeration<? extends Attribute> ne = attributes.getAll();
    while (ne.hasMore()) {
      Attribute attribute = ne.next();
      String attrID = attribute.getID();
      List<String> values = expected.remove(attrID);
      if (values == null) {
        Assert.fail("Unexpected attribute " + attrID);
      }
      assertAttributeEquals(attribute, values);
    }

    if (!expected.isEmpty()) {
      Assert.fail("Missing expected attributes: " + expected.keySet());
    }

    alreadyAdded = true;
  }
  /* 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());
        }
      }
    }
  }
  /** 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;
  }
示例#19
0
  public void produce(String name, Attributes attrs) throws SAXException, NamingException {
    AttributeListImpl attrList;
    Attribute attr;
    NamingEnumeration enumeration;
    NamingEnumeration values;
    Object value;

    leaveSchema();
    enterDirectory();

    // dsml:entry dn
    attrList = new AttributeListImpl();
    attrList.addAttribute(XML.Entries.Attributes.DN, "CDATA", name);
    // dsml:entry
    _docHandler.startElement(prefix(XML.Entries.Elements.Entry), attrList);

    if (attrs != null) {
      attr = attrs.get("objectclass");
      if (attr != null) {
        // dsml:objectclass
        attrList = new AttributeListImpl();
        _docHandler.startElement(prefix(XML.Entries.Elements.ObjectClass), attrList);
        values = attr.getAll();
        while (values.hasMore()) {
          char[] chars;

          // dsml:oc-value
          value = values.next();
          if (value != null) chars = value.toString().toCharArray();
          else chars = new char[0];
          attrList = new AttributeListImpl();
          _docHandler.startElement(prefix(XML.Entries.Elements.OCValue), attrList);
          _docHandler.characters(chars, 0, chars.length);
          _docHandler.endElement(prefix(XML.Entries.Elements.OCValue));
        }
        _docHandler.endElement(prefix(XML.Entries.Elements.ObjectClass));
      }

      enumeration = attrs.getAll();
      while (enumeration.hasMore()) {
        // dsml:attr
        attr = (Attribute) enumeration.next();
        if (attr.getID().equals("objectclass")) continue;
        attrList = new AttributeListImpl();
        attrList.addAttribute(XML.Entries.Attributes.Name, "CDATA", attr.getID());
        _docHandler.startElement(prefix(XML.Entries.Elements.Attribute), attrList);

        values = attr.getAll();
        while (values.hasMore()) {
          char[] chars = null;
          byte[] bytes = null;

          attrList = new AttributeListImpl();

          // dsml:value
          value = values.next();
          if (value == null) {
            chars = new char[0];
          } else if (value instanceof String) {
            chars = ((String) value).toCharArray();
          } else if (value instanceof byte[]) {
            bytes = (byte[]) value;
          } else {
            chars = value.toString().toCharArray();
          }
          if (chars != null) {
            boolean encode = false;
            boolean wchar = false;
            int i = 0;
            while (i < chars.length && !wchar) {
              char c = chars[i++];
              if (c >= '\u0100') encode = wchar = true;
              else if (c >= '\u0080' || (c < ' ' && c != '\n' && c != '\t')) encode = true;
            }
            if (encode) {
              if (wchar) {
                bytes = new byte[chars.length << 1];
                int j = 0;
                // bigendian
                for (i = 0; i < chars.length; i++) {
                  bytes[j++] = (byte) (chars[i] >> 8);
                  bytes[j++] = (byte) (0xff & chars[i]);
                }
              } else {
                bytes = new byte[chars.length];
                for (i = 0; i < chars.length; i++) {
                  bytes[i] = (byte) chars[i];
                }
              }
            }
          }

          if (bytes != null) {
            chars = Base64Encoder.encode(bytes);
            attrList.addAttribute(
                XML.Entries.Attributes.Encoding,
                "NMTOKEN",
                XML.Entries.Attributes.Encodings.Base64);
          }
          _docHandler.startElement(prefix(XML.Entries.Elements.Value), attrList);
          _docHandler.characters(chars, 0, chars.length);
          _docHandler.endElement(prefix(XML.Entries.Elements.Value));
        }
        _docHandler.endElement(prefix(XML.Entries.Elements.Attribute));
      }
    }
    _docHandler.endElement(prefix(XML.Entries.Elements.Entry));
  }
  /**
   * Handle a {@code Callback}
   *
   * @param c callback
   * @throws UnsupportedCallbackException If the callback is not supported by this handler
   * @throws NamingException
   */
  protected void handleCallBack(Callback c) throws UnsupportedCallbackException, NamingException {
    if (c instanceof VerifyPasswordCallback) {
      verifyPassword((VerifyPasswordCallback) c);
      return;
    }

    if (c instanceof PasswordCallback == false) return;

    PasswordCallback passwdCallback = (PasswordCallback) c;

    String bindDN = getBindDN();

    String bindCredential = getBindCredential();

    String tmp = options.get(PASSWORD_ATTRIBUTE_ID);
    if (tmp != null && tmp.length() > 0) {
      passwordAttributeID = tmp;
    }

    InitialLdapContext ctx;
    ClassLoader currentTCCL = SecurityActions.getContextClassLoader();
    try {
      if (currentTCCL != null) SecurityActions.setContextClassLoader(null);
      ctx = this.constructInitialLdapContext(bindDN, bindCredential);
    } catch (NamingException e) {
      throw new RuntimeException(e);
    }

    String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
    if (timeLimit != null) {
      try {
        searchTimeLimit = Integer.parseInt(timeLimit);
      } catch (NumberFormatException e) {
      }
    }
    if (searchTimeLimit == 0) searchTimeLimit = 10000;

    String baseDN = options.get(BASE_CTX_DN);
    String baseFilter = options.get(BASE_FILTER_OPT);

    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

    constraints.setTimeLimit(searchTimeLimit);

    NamingEnumeration<SearchResult> results = null;

    Object[] filterArgs = {userName};
    try {
      if (baseDN == null) throw PicketBoxMessages.MESSAGES.invalidNullBaseContextDN();
      results = ctx.search(baseDN, baseFilter, filterArgs, constraints);
      if (results.hasMore() == false) {
        safeClose(results);
        throw PicketBoxMessages.MESSAGES.failedToFindBaseContextDN(baseDN);
      }
      SearchResult sr = results.next();
      String name = sr.getName();
      String userDN = null;
      if (sr.isRelative() == true) userDN = name + "," + baseDN;
      else throw PicketBoxMessages.MESSAGES.unableToFollowReferralForAuth(name);
      ;

      safeClose(results);

      // Finished Authentication.  Lets look for the attributes
      filterArgs = new Object[] {userName, userDN};
      results = ctx.search(userDN, baseFilter, filterArgs, constraints);
      try {
        while (results.hasMore()) {
          sr = results.next();
          Attributes attributes = sr.getAttributes();
          NamingEnumeration<? extends javax.naming.directory.Attribute> ne = attributes.getAll();

          while (ne != null && ne.hasMoreElements()) {
            javax.naming.directory.Attribute ldapAtt = ne.next();
            if (passwordAttributeID.equalsIgnoreCase(ldapAtt.getID())) {
              Object thePass = ldapAtt.get();
              setPasswordCallbackValue(thePass, passwdCallback);
            }
          }
        }
      } finally {
        safeClose(results);
        safeClose(ctx);
        if (currentTCCL != null) SecurityActions.setContextClassLoader(currentTCCL);
      }
    } catch (NamingException ne) {
      PicketBoxLogger.LOGGER.error(ne);
    }
  }
示例#21
0
 public List<Users> getUsers(Users user) {
   LOG.info("Inside getUsers");
   List<Users> userList = new ArrayList<Users>();
   DirContext ctx = LDAPConstants.getLdapContext();
   String baseDN = PropertyFileReader.getProperty(IAMApplicationConstants.BASEDN_USERS);
   SearchControls sc = new SearchControls();
   sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
   String retAttrs[] = {
     "whenChanged",
     "whenCreated",
     "name",
     "distinguishedName",
     "givenName",
     "cn",
     "initials",
     "displayName",
     "iboIsEmail",
     "iboCountryOfCitizenship2",
     "iboCountryOfCitizenship1",
     "iboIsIBIS",
     "iboPrefCommunicationMethod",
     "iboAuthorizedDate",
     "iboIsNetwork",
     "iboUserStatus",
     "iboIBSchoolCode",
     "iboPrefCommunicationLang",
     "iboRoles",
     "iboUserName",
     "iboSex",
     "iboStartDate",
     "iboUserGUID",
     "iboCountryOfBirth",
     "iboLanguagesSpoken",
     "iboEndDate",
     "iboAuthorizedBy",
     "iboEmailHome",
     "iboCountryCode",
     "iboMobileWork",
     "iboSchoolConnections",
     "iboEmailWork",
     "iboPhoneWork",
     "iboIBRegion",
     "iboPreferredName",
     "iboMiddlename",
     "physicalDeliveryOfficeName",
     "iboSource"
   };
   sc.setReturningAttributes(retAttrs);
   String filter = buildFilter(user);
   LOG.info("Filter--" + filter);
   NamingEnumeration results = null;
   String isIboSource = null;
   try {
     results = ctx.search(baseDN, filter, sc);
     while (results.hasMore()) {
       SearchResult sr = (SearchResult) results.next();
       Attributes attrs = sr.getAttributes();
       if (null != attrs && null != attrs.get("iboSource"))
         isIboSource = attrs.get("iboSource").toString();
       if (null != isIboSource && isIboSource.length() > 0) {
         NamingEnumeration e = attrs.getAll();
         Users ioUser = new Users();
         while (e.hasMoreElements()) {
           Attribute attr = (Attribute) e.nextElement();
           if (attr.getID().toString().length() > 0
               && attr.getID().toString().equalsIgnoreCase("ibosource")) {
             if (attr.get().toString().length() > 0) {
               if (attr.get().toString().equalsIgnoreCase("sharepoint")) {
                 LOG.trace("External");
                 ioUser.setIboUserType(LDAPConstants.IBOUSERTYPE_EXTERNAL);
               } else if (attr.get().toString().equalsIgnoreCase("UserApp")
                   || attr.get().toString().equalsIgnoreCase("OracleHR")
                   || attr.get().toString().equalsIgnoreCase("userapp Generic")) {
                 LOG.trace("Internal");
                 ioUser.setIboUserType(LDAPConstants.IBOUSERTYPE_INTERNAL);
               }
             }
           }
           ioUser = (Users) getResults(attr, ioUser);
         }
         userList.add(ioUser);
       }
     }
     ctx.close();
   } catch (NamingException e) {
     e.printStackTrace();
   }
   return userList;
 }
  /* uses badsource and badsink */
  public void bad() throws Throwable {
    String data;
    if (IO.staticTrue) {
      data = ""; /* Initialize data */
      /* Read data using a listening tcp connection */
      {
        ServerSocket listener = null;
        Socket socket = null;
        BufferedReader readerBuffered = null;
        InputStreamReader readerInputStream = null;
        /* Read data using a listening tcp connection */
        try {
          listener = new ServerSocket(39543);
          socket = listener.accept();
          /* read input from socket */
          readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data using a listening tcp connection */
          data = readerBuffered.readLine();
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBuffered != null) {
              readerBuffered.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStream != null) {
              readerInputStream.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          /* Close socket objects */
          try {
            if (socket != null) {
              socket.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing Socket", exceptIO);
          }

          try {
            if (listener != null) {
              listener.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing ServerSocket", exceptIO);
          }
        }
      }
    } else {
      /* 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;
    }

    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);
        }
      }
    }
  }
  /**
   * This compares all but the named attributes allbut true => All must be equal except those on the
   * list
   *
   * @param that
   * @param attrIDs
   * @return boolean
   * @throws Throwable
   */
  public boolean equalsAllBut(DirRecord that, String[] attrIDs) throws Throwable {
    if (attrIDs == null) throw new Exception("DirectoryRecord: null attrID list");

    if (!dnEquals(that)) {
      return false;
    }

    int n = attrIDs.length;

    if (n == 0) return true;

    Attributes thisAttrs = getAttributes();
    Attributes thatAttrs = that.getAttributes();

    if (thisAttrs == null) {
      if (thatAttrs == null) return true;
      return false;
    }

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

    /**
     * We need to ensure that all attributes are checked. We init thatLeft to the number of
     * attributes in the source. We decrement for each checked attribute. We then decrement for each
     * ignored attribute present in that If the result is non-zero, then there are some extra
     * attributes in that so we return unequal.
     */
    int sz = thisAttrs.size();
    int thatLeft = sz;

    if ((sz == 0) && (thatAttrs.size() == 0)) {
      return true;
    }

    NamingEnumeration ne = thisAttrs.getAll();

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

    while (ne.hasMore()) {
      Attribute attr = (Attribute) ne.next();
      String id = attr.getID();
      boolean present = false;

      for (int i = 0; i < attrIDs.length; i++) {
        if (id.equalsIgnoreCase(attrIDs[i])) {
          present = true;
          break;
        }
      }
      if (present) {
        // We don't compare
        if (thatAttrs.get(id) != null) thatLeft--;
      } else {
        Attribute thatAttr = thatAttrs.get(id);
        if (thatAttr == null) {
          return false;
        }
        if (!thatAttr.contains(attr)) {
          return false;
        }
        thatLeft--;
      }
    }

    return (thatLeft == 0);
  }