/**
   * after a user has successfully logged in we want to build an access object for use in the
   * scheduling system
   *
   * @param String username
   * @param String group a group name to check for username in (via memberUid string)
   * @return boolean yes or no in the group
   * @throws NamingException when the search fails by DN this will be thrown
   */
  private boolean userInGroup(String username, String group) throws NamingException {
    // assume they are not
    boolean inGroup = false;

    // Specify the attributes to match
    Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
    // set the common name for the group using defined prefix ie 'cn' or 'ou'
    matchAttrs.put(
        new BasicAttribute(
            this.GROUPS_LOC.substring(0, this.GROUPS_LOC.indexOf("=")),
            group)); // named group for access rights

    // Search for objects that have those matching attributes in the specified group location
    NamingEnumeration answer = ctx.search(this.GROUPS_LOC + this.BASE_DN, matchAttrs);

    // search for that user id in the member list
    while (answer.hasMore()) {
      SearchResult sr = (SearchResult) answer.next();
      if ((sr.getAttributes().get("memberuid").toString()).indexOf(username) >= 0) {
        // this user is in the specified group
        inGroup = true;
      }
    }
    System.err.println(username + " in " + group + ": " + new Boolean(inGroup).toString());
    return inGroup;
  }
  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;
  }
  @Test
  public void testLdapExample2() throws Exception {
    System.out.println("testLdapExample2");

    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String[] attrIDs = {"cn"};
    constraints.setReturningAttributes(attrIDs);
    Hashtable<String, Object> options = new Hashtable<String, Object>();
    options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    options.put("java.naming.provider.url", "ldap://127.0.0.1:10389/");
    options.put("java.naming.security.authentication", "simple");
    options.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    options.put(Context.SECURITY_CREDENTIALS, "secret");

    LdapContext ctx = new InitialLdapContext(options, null);
    String username = "******";

    NamingEnumeration<SearchResult> answer =
        ctx.search("ou=users,o=jtogaf", "uid=" + username, constraints);
    assertTrue("There is att: ", answer.hasMore());

    if (answer.hasMore()) {
      Attributes attrs = ((SearchResult) answer.next()).getAttributes();
      Attribute attr = (Attribute) attrs.get("cn");
      System.out.print(attr.get(0));
    }
  }
Beispiel #4
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;
  }
  /**
   * Retrieve the input attributes from the Active Directory for the given search query
   *
   * <p>Method getAttributes.
   *
   * @param searchBase String
   * @return List<User>
   * @throws NamingException
   */
  private final List<User> getAttributes(String searchBase) throws NamingException {
    LOGGER.info(">> getAttributes()");

    NamingEnumeration<SearchResult> results =
        localInitialLdapContext.search(searchBase, searchFilter, searchctls);

    List<User> users = new ArrayList<User>();
    User user = null;

    while (results.hasMoreElements()) {
      user = new User();
      SearchResult searchResult = results.next();
      Attributes attrs = searchResult.getAttributes();

      if (attrs != null && attrs.size() != 0) {
        Attribute attribute = null;

        String[] retrieveAttributes = parameters.getRetrieveAttributes();
        String[] attributesValues = new String[retrieveAttributes.length];
        for (int i = 0; i < retrieveAttributes.length; i++) {
          attribute = attrs.get(retrieveAttributes[i]);
          if (attribute != null && attribute.get() != null) {
            if (!isNullOrEmpty(attribute.get().toString())) {
              attributesValues[i] = attribute.get().toString();
            }
          }
        }
        user.setAttributeValues(attributesValues);
      }
      users.add(user);
    }

    LOGGER.info("<< getAttributes()");
    return users;
  }
  /**
   * 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;
    }
  }
  /**
   * @param attributes
   * @return
   * @throws NamingException
   */
  protected final Map<String, List<String>> convertToStringAttributesMap(Attributes attributes)
      throws NamingException {
    Map<String, List<String>> attributesMap = new HashMap<String, List<String>>();

    NamingEnumeration<String> attributeNames = attributes.getIDs();
    while (attributeNames.hasMore()) {
      String attributeName = attributeNames.next();
      if (ldapAttributesKey.getPasswordAttributeName().equalsIgnoreCase(attributeName)) {
        // skip
        continue;
      }
      Attribute attribute = attributes.get(attributeName);
      int numberOfValues = attribute.size();
      for (int i = 0; i < numberOfValues; i++) {
        String value = (String) attribute.get(i);
        if (null != value) {
          value = value.trim();
        }

        List<String> list = safeGetAttributeList(attributesMap, attributeName.toLowerCase());
        list.add(value);
      }
    }
    return attributesMap;
  }
  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());
    }
  }
  /* 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());
        }
      }
    }
  }
Beispiel #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;
  }
Beispiel #11
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();
    }
  }
  private User getUserBasicAttributes(String username, LdapContext ctx) {
    User user = null;
    try {

      SearchControls constraints = new SearchControls();
      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String[] attrIDs = {"distinguishedName", "sn", "givenname", "mail", "telephonenumber"};
      constraints.setReturningAttributes(attrIDs);
      // First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
      // Second Attribute can be uid=username
      NamingEnumeration answer =
          ctx.search("DC=YourDomain,DC=com", "sAMAccountName=" + username, constraints);
      if (answer.hasMore()) {
        Attributes attrs = ((SearchResult) answer.next()).getAttributes();
        System.out.println("distinguishedName " + attrs.get("distinguishedName"));
        System.out.println("givenname " + attrs.get("givenname"));
        System.out.println("sn " + attrs.get("sn"));
        System.out.println("mail " + attrs.get("mail"));
      } else {
        throw new Exception("Invalid User");
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return user;
  }
  /** Returns the name of the specified header field. */
  @Override
  public String getHeaderField(String name) {

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

    if (attributes == null) return (null);

    NamingEnumeration<String> attributeEnum = attributes.getIDs();
    try {
      while (attributeEnum.hasMore()) {
        String attributeID = attributeEnum.next();
        if (attributeID.equalsIgnoreCase(name)) {
          Attribute attribute = attributes.get(attributeID);
          if (attribute == null) return null;
          Object attrValue = attribute.get(attribute.size() - 1);
          return getHeaderValueAsString(attrValue);
        }
      }
    } catch (NamingException ne) {
      // Shouldn't happen
    }

    return (null);
  }
Beispiel #14
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");
  }
Beispiel #15
0
 public Operator_Ldap mapFromAttributes(Attributes attrs) throws javax.naming.NamingException {
   Operator_Ldap p = new Operator_Ldap();
   p.setSn(attrs.get("sn").get().toString());
   p.setCn(attrs.get("cn").get().toString());
   p.setUserPassword(attrs.get("userPassword").get().toString());
   return p;
 }
Beispiel #16
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;
     }
   }
 }
    private LdapEntry convertToLdapEntry(SearchResult searchResult, Attributes attributes)
        throws NamingException {
      String simpleName = null;
      String distinguishedName = null;

      if (groupNameAttribute != null) {
        SECURITY_LOGGER.tracef("Getting groupNameAttribute=%s", groupNameAttribute);
        Attribute groupNameAttr = attributes.get(groupNameAttribute);
        if (groupNameAttr != null) {
          simpleName = (String) groupNameAttr.get();
        }
      }

      if (groupDnAttribute != null) {
        if ("dn".equals(groupDnAttribute)) {
          SECURITY_LOGGER.trace("Obtaining dn using getNameInNamespace()");
          distinguishedName = searchResult.getNameInNamespace();
        } else {
          SECURITY_LOGGER.tracef("Getting groupDnAttribute=%s", groupDnAttribute);
          Attribute groupDnAttr = attributes.get(groupDnAttribute);
          if (groupDnAttr != null) {
            distinguishedName = (String) groupDnAttr.get();
          }
        }
      }

      return new LdapEntry(simpleName, distinguishedName);
    }
    @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()]);
    }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getHeader("vector");
    if (param == null) param = "";

    String bar;

    // Simple ? condition that assigns constant to bar on true condition
    int num = 106;

    bar = (7 * 18) + num > 200 ? "This_should_always_happen" : param;

    org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
    try {
      response.setContentType("text/html");
      String base = "ou=users,ou=system";
      javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
      sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
      String filter = "(&(objectclass=person))(|(uid=" + bar + ")(street={0}))";
      Object[] filters = new Object[] {"The streetz 4 Ms bar"};

      javax.naming.directory.DirContext ctx = ads.getDirContext();
      javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
      javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
          idc.search(base, filter, filters, sc);
      while (results.hasMore()) {
        javax.naming.directory.SearchResult sr =
            (javax.naming.directory.SearchResult) results.next();
        javax.naming.directory.Attributes attrs = sr.getAttributes();

        javax.naming.directory.Attribute attr = attrs.get("uid");
        javax.naming.directory.Attribute attr2 = attrs.get("street");
        if (attr != null) {
          response
              .getWriter()
              .write(
                  "LDAP query results:<br>"
                      + " Record found with name "
                      + attr.get()
                      + "<br>"
                      + "Address: "
                      + attr2.get()
                      + "<br>");
          System.out.println("record found " + attr.get());
        }
      }
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    } finally {
      try {
        ads.closeDirContext();
      } catch (Exception e) {
        throw new ServletException(e);
      }
    }
  }
 @Override
 protected void loadFrom(Device device, Attributes attrs)
     throws NamingException, CertificateException {
   super.loadFrom(device, attrs);
   if (!(device instanceof ArchiveDevice)) return;
   ArchiveDevice arcdev = (ArchiveDevice) device;
   arcdev.setFuzzyAlgorithmClass(stringValue(attrs.get("dcmFuzzyAlgorithmClass")));
   arcdev.setConfigurationStaleTimeout(intValue(attrs.get("dcmConfigurationStaleTimeout"), 0));
 }
  /* Return all groups for principal == null or all groups for which principal
   * is a member
   *
   */
  private Collection<BwGroup> getGroups(
      final DirConfigProperties dirProps, final BwPrincipal principal) throws CalFacadeException {
    LdapConfigProperties props = (LdapConfigProperties) dirProps;
    InitialLdapContext ctx = null;
    String member = null;

    if (principal != null) {
      if (principal.getKind() == WhoDefs.whoTypeUser) {
        member = getUserEntryValue(props, principal);
      } else if (principal.getKind() == WhoDefs.whoTypeGroup) {
        member = getGroupEntryValue(props, principal);
      }
    }

    try {
      ctx = createLdapInitContext(props);

      BasicAttributes matchAttrs = new BasicAttributes(true);

      if (member != null) {
        matchAttrs.put(props.getGroupMemberAttr(), member);
      }

      String[] idAttr = {props.getGroupIdAttr()};

      ArrayList<BwGroup> groups = new ArrayList<BwGroup>();
      NamingEnumeration response = ctx.search(props.getGroupContextDn(), matchAttrs, idAttr);
      while (response.hasMore()) {
        SearchResult sr = (SearchResult) response.next();
        Attributes attrs = sr.getAttributes();

        Attribute nmAttr = attrs.get(props.getGroupIdAttr());
        if (nmAttr.size() != 1) {
          throw new CalFacadeException("org.bedework.ldap.groups.multiple.result");
        }

        BwGroup group = new BwGroup();
        group.setAccount(nmAttr.get(0).toString());
        group.setPrincipalRef(makePrincipalUri(group.getAccount(), WhoDefs.whoTypeGroup));

        groups.add(group);
      }

      return groups;
    } catch (Throwable t) {
      if (debug) {
        error(t);
      }
      throw new CalFacadeException(t);
    } finally {
      // Close the context to release the connection
      if (ctx != null) {
        closeContext(ctx);
      }
    }
  }
  /**
   * Compare this with that only looking at the named attributes. For this method, the dns must be
   * equal and the values of the named attributes must be equal but their names may differ. The two
   * arrays of attrIDs must be non-null and of the same length or an exception is raised.
   *
   * <p>If there are no attributes in both records they are considered equal. If there are no
   * attributes in only one record they are unequal.
   *
   * <p>Zero length attrID lists means only the dn is compared.
   *
   * @param that
   * @param thisAttrIDs
   * @param thatAttrIDs
   * @return boolean
   * @throws Throwable
   */
  public boolean equals(DirRecord that, String[] thisAttrIDs, String[] thatAttrIDs)
      throws Throwable {
    if ((thisAttrIDs == null) || (thatAttrIDs == null)) {
      throw new Exception("DirectoryRecord: null attrID list");
    }

    if (thisAttrIDs.length != thatAttrIDs.length) {
      throw new Exception("DirectoryRecord: unequal length attrID lists");
    }

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

    int n = thisAttrIDs.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;
    }

    for (int i = 0; i < n; i++) {
      Attribute thisAttr = thisAttrs.get(thisAttrIDs[i]);
      Attribute thatAttr = thatAttrs.get(thatAttrIDs[i]);

      if (thisAttr == null) {
        if (thatAttr == null) {
          return true;
        }
        return false;
      }

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

      if (!attrEquals(thisAttr, thatAttr)) {
        return false;
      }
    }

    return true;
  }
Beispiel #23
0
 /**
  * Update a given field of a contact in LDAP.
  *
  * @param contactDTO
  */
 public void updateContact(ContactDTO contactDTO) {
   Attributes personAttributes = new BasicAttributes();
   BasicAttribute personBasicAttribute = new BasicAttribute("objectclass");
   personBasicAttribute.add("person");
   personAttributes.put(personBasicAttribute);
   personAttributes.put("cn", contactDTO.getCommonName());
   personAttributes.put("sn", contactDTO.getSurname());
   personAttributes.put("description", contactDTO.getDescription());
   ldapTemplate.rebind("cn=" + contactDTO.getCommonName(), null, personAttributes);
 }
 private RejectionNote loadRejectionNoteFrom(Attributes attrs) throws NamingException {
   RejectionNote rn =
       new RejectionNote(
           stringValue(attrs.get("dcmCodeValue")),
           stringValue(attrs.get("dcmCodingSchemeDesignator")),
           stringValue(attrs.get("dcmCodingSchemeVersion")),
           stringValue(attrs.get("dcmCodeMeaning")));
   loadRejectionActionsFrom(rn, attrs.get("dcmRejectionAction"));
   return rn;
 }
 /**
  * Map the properties from LDAP to the {@link UserDetails}
  *
  * @param serverKey the LDAP index so we use the correct {@link LdapUserMapping}
  * @return If no exceptions are thrown, a {@link UserDetails} object containing the values from
  *     LDAP.
  * @throws NamingException In case the communication or mapping to the LDAP server fails.
  */
 private UserDetails mapUserDetails(String serverKey, SearchResult searchResult)
     throws NamingException {
   Attributes attributes = searchResult.getAttributes();
   UserDetails details;
   details = new UserDetails();
   details.setName(
       getAttributeValue(attributes.get(userMappings.get(serverKey).getRealNameAttribute())));
   details.setEmail(
       getAttributeValue(attributes.get(userMappings.get(serverKey).getEmailAttribute())));
   return details;
 }
  /* 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());
        }
      }
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getParameter("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
    try {
      response.setContentType("text/html");
      String base = "ou=users,ou=system";
      javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
      sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
      String filter = "(&(objectclass=person)(uid=" + bar + "))";

      javax.naming.directory.DirContext ctx = ads.getDirContext();
      javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
      javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
          idc.search(base, filter, sc);

      while (results.hasMore()) {
        javax.naming.directory.SearchResult sr =
            (javax.naming.directory.SearchResult) results.next();
        javax.naming.directory.Attributes attrs = sr.getAttributes();

        javax.naming.directory.Attribute attr = attrs.get("uid");
        javax.naming.directory.Attribute attr2 = attrs.get("street");
        if (attr != null) {
          response
              .getWriter()
              .write(
                  "LDAP query results:<br>"
                      + " Record found with name "
                      + attr.get()
                      + "<br>"
                      + "Address: "
                      + attr2.get()
                      + "<br>");
          System.out.println("record found " + attr.get());
        }
      }
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    } finally {
      try {
        ads.closeDirContext();
      } catch (Exception e) {
        throw new ServletException(e);
      }
    }
  } // end doPost
Beispiel #28
0
 /** Définition et setting des attributs de l'entrée */
 private Attributes buildAttributes(Operator_Ldap o) {
   Attributes attrs = new BasicAttributes();
   BasicAttribute ocattr = new BasicAttribute("objectClass");
   ocattr.add("top");
   ocattr.add("Person");
   attrs.put(ocattr);
   attrs.put("cn", o.getCn());
   attrs.put("sn", o.getSn());
   attrs.put("userPassword", o.getUserPassword());
   return attrs;
 }
Beispiel #29
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;
 }
Beispiel #30
0
  static LdapType guessType(final DirContext ctx) throws NamingException {
    final Attributes rootAtts = ctx.getAttributes("");
    Attribute supported = rootAtts.get("supportedCapabilities");
    if (supported != null
        && (supported.contains("1.2.840.113556.1.4.800")
            || supported.contains("1.2.840.113556.1.4.1851"))) {
      return new ActiveDirectory();
    }

    return RFC_2307;
  }