Exemplo n.º 1
0
  /**
   * Performs a comparison of the contents of AND or OR filters.
   *
   * @param f1 The first filter for which to make the determination.
   * @param f2 The second filter for which to make the determination.
   * @return A negative value if the first filter should be ordered before the second, a positive
   *     value if the first filter should be ordered after the second, or zero if there is no
   *     difference in their relative orders.
   */
  private static int compareANDOrOR(final Filter f1, final Filter f2) {
    final TreeSet<Filter> set1 = new TreeSet<Filter>(INSTANCE);
    final TreeSet<Filter> set2 = new TreeSet<Filter>(INSTANCE);

    set1.addAll(Arrays.asList(f1.getComponents()));
    set2.addAll(Arrays.asList(f2.getComponents()));

    final Iterator<Filter> iterator1 = set1.iterator();
    final Iterator<Filter> iterator2 = set2.iterator();
    while (true) {
      final Filter comp1;
      if (iterator1.hasNext()) {
        comp1 = iterator1.next();
      } else if (iterator2.hasNext()) {
        return -1;
      } else {
        return 0;
      }

      final Filter comp2;
      if (iterator2.hasNext()) {
        comp2 = iterator2.next();
      } else {
        return 1;
      }

      final int compValue = INSTANCE.compare(comp1, comp2);
      if (compValue != 0) {
        return compValue;
      }
    }
  }
Exemplo n.º 2
0
 public List<ScopeDescription> getAllScopes() {
   try {
     return ldapEntryManager.findEntries(
         baseDn(), ScopeDescription.class, Filter.createPresenceFilter("inum"));
   } catch (Exception e) {
     log.error(e.getMessage(), e);
   }
   return Collections.emptyList();
 }
Exemplo n.º 3
0
  public boolean isUserInGroupOrMember(String groupDn, String personDn) {
    Filter ownerFilter = Filter.createEqualityFilter("owner", personDn);
    Filter memberFilter = Filter.createEqualityFilter("member", personDn);
    Filter searchFilter = Filter.createORFilter(ownerFilter, memberFilter);

    boolean isMemberOrOwner = false;
    try {
      isMemberOrOwner =
          ldapEntryManager.findEntries(groupDn, UserGroup.class, searchFilter, 1).size() > 0;

    } catch (EntryPersistenceException ex) {
      log.error(
          "Failed to determine if person '{0}' memeber or owner of group '{1}'",
          ex, personDn, groupDn);
    }

    return isMemberOrOwner;
  }
Exemplo n.º 4
0
  /**
   * Determines a relative order for the provided filter objects.
   *
   * @param f1 The first filter for which to make the determination.
   * @param f2 The second filter for which to make the determination.
   * @return A negative value if the first filter should be ordered before the second, a positive
   *     value if the first filter should be ordered after the second, or zero if there is no
   *     difference in their relative orders.
   */
  public int compare(final Filter f1, final Filter f2) {
    final byte type1 = f1.getFilterType();
    final byte type2 = f2.getFilterType();

    if (type1 != type2) {
      return ((type1 & 0x1F) - (type2 & 0x1F));
    }

    final String name1 = toLowerCase(f1.getAttributeName());
    final String name2 = toLowerCase(f2.getAttributeName());
    if ((name1 != null) && (name2 != null)) {
      final int cmpValue = name1.compareTo(name2);
      if (cmpValue != 0) {
        return cmpValue;
      }
    }

    final byte[] value1 = f1.getAssertionValueBytes();
    if (value1 != null) {
      final byte[] value2 = f2.getAssertionValueBytes();
      final int cmpValue = compare(value1, value2);
      if (cmpValue != 0) {
        return cmpValue;
      }
    }

    switch (type1) {
      case Filter.FILTER_TYPE_AND:
      case Filter.FILTER_TYPE_OR:
        return compareANDOrOR(f1, f2);

      case Filter.FILTER_TYPE_NOT:
        return compare(f1.getNOTComponent(), f2.getNOTComponent());

      case Filter.FILTER_TYPE_PRESENCE:
      case Filter.FILTER_TYPE_EQUALITY:
      case Filter.FILTER_TYPE_GREATER_OR_EQUAL:
      case Filter.FILTER_TYPE_LESS_OR_EQUAL:
      case Filter.FILTER_TYPE_APPROXIMATE_MATCH:
        // The necessary processing for these types has already been done.
        return 0;

      case Filter.FILTER_TYPE_SUBSTRING:
        return compareSubstring(f1, f2);

      case Filter.FILTER_TYPE_EXTENSIBLE_MATCH:
        return compareExtensible(f1, f2);

      default:
        // This should never happen.
        return 0;
    }
  }
Exemplo n.º 5
0
 public List<ScopeDescription> getScopes(UmaScopeType p_type) {
   try {
     if (p_type != null) {
       final Filter filter = Filter.create(String.format("&(oxType=%s)", p_type.getValue()));
       return ldapEntryManager.findEntries(baseDn(), ScopeDescription.class, filter);
     }
   } catch (Exception e) {
     log.error(e.getMessage(), e);
   }
   return Collections.emptyList();
 }
 public boolean authenticate(String pid, String pwd) throws LDAPException {
   Filter f = Filter.create("(mail=" + pid + ')');
   SearchRequest request = new SearchRequest(BASE_DN, SearchScope.SUB, f);
   SearchResult searchResult = mConnection.search(request);
   if (searchResult.getEntryCount() == 0) return false;
   SearchResultEntry e = searchResult.getSearchEntries().get(0);
   String uid = e.getAttribute("uid").getValue();
   Log.d(LOG_TAG, uid);
   BindRequest bindRequest = new SimpleBindRequest(e.getDN(), pwd);
   BindResult result = mConnection.bind(bindRequest);
   return result.getResultCode() == ResultCode.SUCCESS;
 }
Exemplo n.º 7
0
 @Override
 public Set<String> retrieveUserGroups(LdapUserContext userContext) throws LdapException {
   Set<String> groups = new HashSet<String>();
   try {
     Filter groupClassFilter;
     if (groupObjectClass != null && !groupObjectClass.isEmpty()) {
       groupClassFilter = Filter.createEqualityFilter("objectClass", groupObjectClass);
     } else {
       groupClassFilter = Filter.createPresenceFilter("objectClass");
     }
     Filter filter =
         Filter.createANDFilter(
             groupClassFilter,
             Filter.createEqualityFilter(groupMemberAttribute, userContext.getDn()));
     LOGGER.debug(filter.toString());
     SearchResult searchResult =
         ldapConnectionPool.search(
             StringUtils.join(groupBase, ','), SearchScope.SUB, filter, "cn");
     for (SearchResultEntry entry : searchResult.getSearchEntries()) {
       groups.add(entry.getAttributeValue("cn"));
     }
     return groups;
   } catch (com.unboundid.ldap.sdk.LDAPException e) {
     throw new LdapException(e);
   }
 }
 public ResourceSetPermission getResourceSetPermissionByConfigurationCode(
     String p_configurationCode, String clientDn) {
   try {
     final Filter filter =
         Filter.create(String.format("&(oxConfigurationCode=%s)", p_configurationCode));
     final List<ResourceSetPermission> entries =
         ldapEntryManager.findEntries(clientDn, ResourceSetPermission.class, filter);
     if (entries != null && !entries.isEmpty()) {
       return entries.get(0);
     }
   } catch (Exception e) {
     LOG.trace(e.getMessage(), e);
   }
   return null;
 }
 @Override
 public ResourceSetPermission getResourceSetPermissionByTicket(String p_ticket) {
   try {
     final String baseDn = staticConfiguration.getBaseDn().getClients();
     final Filter filter = Filter.create(String.format("&(oxTicket=%s)", p_ticket));
     final List<ResourceSetPermission> entries =
         ldapEntryManager.findEntries(baseDn, ResourceSetPermission.class, filter);
     if (entries != null && !entries.isEmpty()) {
       return entries.get(0);
     }
   } catch (Exception e) {
     LOG.trace(e.getMessage(), e);
   }
   return null;
 }
Exemplo n.º 10
0
  /**
   * Performs a comparison of the contents of substring filters.
   *
   * @param f1 The first filter for which to make the determination.
   * @param f2 The second filter for which to make the determination.
   * @return A negative value if the first filter should be ordered before the second, a positive
   *     value if the first filter should be ordered after the second, or zero if there is no
   *     difference in their relative orders.
   */
  private static int compareSubstring(final Filter f1, final Filter f2) {
    final byte[] sI1 = f1.getSubInitialBytes();
    final byte[] sI2 = f2.getSubInitialBytes();
    if (sI1 == null) {
      if (sI2 != null) {
        return -1;
      }
    } else if (sI2 == null) {
      return 1;
    } else {
      final int cmpValue = compare(sI1, sI2);
      if (cmpValue != 0) {
        return cmpValue;
      }
    }

    final byte[][] sA1 = f1.getSubAnyBytes();
    final byte[][] sA2 = f2.getSubAnyBytes();
    if (sA1.length == 0) {
      if (sA2.length > 0) {
        return -1;
      }
    } else if (sA2.length == 0) {
      return 1;
    } else {
      final int minLength = Math.min(sA1.length, sA2.length);
      for (int i = 0; i < minLength; i++) {
        final int cmpValue = compare(sA1[i], sA2[i]);
        if (cmpValue != 0) {
          return cmpValue;
        }
      }

      if (sA1.length < sA2.length) {
        return -1;
      } else if (sA2.length < sA1.length) {
        return 1;
      }
    }

    final byte[] sF1 = f1.getSubFinalBytes();
    final byte[] sF2 = f2.getSubFinalBytes();
    if (sF1 == null) {
      if (sF2 != null) {
        return -1;
      } else {
        return 0;
      }
    } else if (sF2 == null) {
      return 1;
    } else {
      return compare(sF1, sF2);
    }
  }
Exemplo n.º 11
0
  /** {@inheritDoc} */
  @Override
  public Filter toLDAPFilter(
      final SCIMFilter filter,
      final LDAPRequestInterface ldapInterface,
      final LDAPSearchResolver userResolver)
      throws InvalidResourceException {
    // Only the managerId sub-attribute will ever have a value so filter
    // must target that sub-attribute.
    String subAttribute = filter.getFilterAttribute().getSubAttributeName();
    if (subAttribute == null || !subAttribute.equals("managerId")) {
      return null;
    }

    final String ldapAttributeType = ATTR_MANAGER;
    final SCIMFilterType filterType = filter.getFilterType();
    final String filterValue = filter.getFilterValue();

    // Determine the DN for this member.
    try {
      switch (filterType) {
          // We don't have to worry about AND and OR filter types since they are
          // handled earlier by the resource mapper.
        case EQUALITY:
          {
            String dn;
            try {
              dn = userResolver.getDnFromId(ldapInterface, filterValue);
            } catch (ResourceNotFoundException e) {
              // Value is not a valid user. Will not match anything.
              return null;
            }
            return Filter.createEqualityFilter(ldapAttributeType, dn);
          }

        default:
          throw new InvalidResourceException(
              "Filter type "
                  + filterType
                  + " is not supported for attribute "
                  + getAttributeDescriptor().getName());
      }
    } catch (Exception e) {
      Debug.debugException(e);
      throw new InvalidResourceException(e.getMessage());
    }
  }
Exemplo n.º 12
0
  private void handleExternalScopes(List<String> p_scopeUrls, List<String> result)
      throws LDAPException {
    for (String scopeUrl : p_scopeUrls) {
      final Filter filter = Filter.create(String.format("&(oxUrl=%s)", scopeUrl));
      final List<ScopeDescription> entries =
          ldapEntryManager.findEntries(baseDn(), ScopeDescription.class, filter);
      if (entries != null && !entries.isEmpty()) {
        result.add(entries.get(0).getDn());
      } else { // scope is not in ldap, add it dynamically

        final Boolean addAutomatically =
            ConfigurationFactory.instance().getConfiguration().getUmaAddScopesAutomatically();

        if (addAutomatically != null && addAutomatically) {
          final String inum = inumService.generateInum();
          final ScopeDescription newScope = new ScopeDescription();
          newScope.setInum(inum);
          newScope.setUrl(scopeUrl);
          newScope.setDisplayName(
              scopeUrl); // temp solution : need extract info from scope description on resource
                         // server
          newScope.setId(
              UmaScopeType.EXTERNAL_AUTO
                  .getValue()); // dummy id : not sure what to put right now as id is required by
                                // @NotNull annotation
          newScope.setType(InternalExternal.EXTERNAL_AUTO);

          final boolean persisted = persist(newScope);
          if (persisted) {
            result.add(newScope.getDn());
          }
        } else {
          throw new WebApplicationException(
              Response.status(Response.Status.BAD_REQUEST)
                  .entity(
                      errorResponseFactory.getUmaJsonErrorResponse(
                          UmaErrorResponseType.INVALID_RESOURCE_SET_SCOPE))
                  .build());
        }
      }
    }
  }
Exemplo n.º 13
0
 private Filter createAnyFilterByUrls(List<String> p_scopeUrls) {
   try {
     if (p_scopeUrls != null && !p_scopeUrls.isEmpty()) {
       final StringBuilder sb = new StringBuilder("(|");
       for (String url : p_scopeUrls) {
         sb.append("(");
         sb.append("oxUrl=");
         sb.append(url);
         sb.append(")");
       }
       sb.append(")");
       final String filterAsString = sb.toString();
       log.trace("Uma scope urls: " + p_scopeUrls + ", ldapFilter: " + filterAsString);
       return Filter.create(filterAsString);
     }
   } catch (LDAPException e) {
     log.error(e.getMessage(), e);
   }
   return null;
 }
Exemplo n.º 14
0
  @Test
  @Ignore // only for experiment
  public void rdnUBID() throws Exception {
    // com.unboundid.ldap.sdk.RDN rdn = new com.unboundid.ldap.sdk.RDN("cn", "foo+/+/
    // \u4e2d\u6587");
    String rawValue = "## ,+\"\\<>;\u4e2d\u6587---createIdentity ";

    com.unboundid.ldap.sdk.RDN rdn = new com.unboundid.ldap.sdk.RDN("cn", rawValue);
    String minStr = rdn.toMinimallyEncodedString();
    String rdnStr = rdn.toNormalizedString();
    System.out.println(minStr);
    System.out.println(rdnStr);

    String escapedValue = com.unboundid.ldap.sdk.Filter.encodeValue(rawValue);
    System.out.println(escapedValue);

    /*
    String raw = "(&(objectclass=zimbraIdentity)(zimbraPrefIdentityName=## ,+\"\\<>;\u4e2d\u6587---createIdentity ))";
    String escaped = com.unboundid.ldap.sdk.Filter.encodeValue(raw);
    System.out.println(escaped);
    */

    /*
    com.unboundid.ldap.sdk.Filter filter =
        com.unboundid.ldap.sdk.Filter.create("(&(objectclass=zimbraIdentity)(zimbraPrefIdentityName=## ,+\"\\<>;\u4e2d\u6587---createIdentity ))");
    String norm = filter.toNormalizedString();
    System.out.println(norm);
    */
    /*
    String rdn = "cn=foo, bar";
    String norm = com.unboundid.ldap.sdk.RDN.normalize(rdn);
    com.unboundid.ldap.sdk.RDN RDN = new com.unboundid.ldap.sdk.RDN(norm);
    String min = RDN.toMinimallyEncodedString();
    System.out.println(rdn);
    System.out.println(norm);
    System.out.println(min);
    */

  }
Exemplo n.º 15
0
  public ScopeDescription getInternalScope(String p_scopeId) {
    try {
      final Filter filter =
          Filter.create(
              String.format("&(oxType=%s)(oxId=%s)", UmaScopeType.INTERNAL.getValue(), p_scopeId));
      final List<ScopeDescription> entries =
          ldapEntryManager.findEntries(baseDn(), ScopeDescription.class, filter);
      if (entries != null && !entries.isEmpty()) {

        // if more then one scope then it's problem, non-deterministic behavior, id must be unique
        if (entries.size() > 1) {
          log.error("Found more then one internal uma scope by input id: {0}" + p_scopeId);
          for (ScopeDescription s : entries) {
            log.error("Scope, Id: {0}, dn: {1}", s.getId(), s.getDn());
          }
        }
        return entries.get(0);
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    return null;
  }
Exemplo n.º 16
0
  private List<String> handleInternalScopes(List<String> p_scopeUrls, List<String> result) {
    List<String> notProcessedScopeUrls = new ArrayList<String>(p_scopeUrls);
    try {
      final Filter filter =
          Filter.create(String.format("&(oxType=%s)", InternalExternal.INTERNAL.getValue()));
      final List<ScopeDescription> entries =
          ldapEntryManager.findEntries(baseDn(), ScopeDescription.class, filter);
      if (entries != null && !entries.isEmpty()) {
        for (String scopeUrl : p_scopeUrls) {
          for (ScopeDescription scopeDescription : entries) {
            final String internalScopeUrl = getInternalScopeUrl(scopeDescription);
            if (internalScopeUrl.equals(scopeUrl) && !result.contains(internalScopeUrl)) {
              result.add(scopeDescription.getDn());
              notProcessedScopeUrls.remove(scopeUrl);
            }
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }

    return notProcessedScopeUrls;
  }
Exemplo n.º 17
0
  /**
   * Performs a comparison of the contents of substring filters.
   *
   * @param f1 The first filter for which to make the determination.
   * @param f2 The second filter for which to make the determination.
   * @return A negative value if the first filter should be ordered before the second, a positive
   *     value if the first filter should be ordered after the second, or zero if there is no
   *     difference in their relative orders.
   */
  private static int compareExtensible(final Filter f1, final Filter f2) {
    final String name1 = f1.getAttributeName();
    final String name2 = f2.getAttributeName();
    if (name1 == null) {
      if (name2 != null) {
        return -1;
      }
    } else if (name2 == null) {
      return 1;
    }

    final String mr1 = f1.getMatchingRuleID();
    final String mr2 = f2.getMatchingRuleID();
    if (mr1 == null) {
      if (mr2 != null) {
        return -1;
      }
    } else if (mr2 == null) {
      return 1;
    } else {
      final int cmpValue = mr1.compareTo(mr2);
      if (cmpValue != 0) {
        return cmpValue;
      }
    }

    if (f1.getDNAttributes()) {
      if (f2.getDNAttributes()) {
        return 0;
      } else {
        return 1;
      }
    } else if (f2.getDNAttributes()) {
      return -1;
    } else {
      return 0;
    }
  }
Exemplo n.º 18
0
 @Override
 public LdapUserContext findUser(String identityAttributeValue) throws LdapException {
   try {
     Filter userClassFilter;
     if (userObjectClass != null && !userObjectClass.isEmpty()) {
       userClassFilter = Filter.createEqualityFilter("objectClass", userObjectClass);
     } else {
       userClassFilter = Filter.createPresenceFilter("objectClass");
     }
     Filter filter =
         Filter.createANDFilter(
             userClassFilter,
             Filter.createEqualityFilter(userIdentityAttribute, identityAttributeValue));
     LOGGER.debug(filter.toString());
     String[] attributesToRetrieve;
     if (userAdditionalAttributes != null) {
       attributesToRetrieve = userAdditionalAttributes;
       if (!ArrayUtils.contains(attributesToRetrieve, "cn")
           || !ArrayUtils.contains(attributesToRetrieve, "CN")) {
         ArrayUtils.add(attributesToRetrieve, "cn");
       }
     } else {
       attributesToRetrieve = new String[] {"cn"};
     }
     SearchResult searchResult =
         ldapConnectionPool.search(
             StringUtils.join(userBase, ','), SearchScope.SUB, filter, attributesToRetrieve);
     if (searchResult.getEntryCount() != 1) {
       throw new UnknownAccountException();
     }
     SearchResultEntry searchResultEntry = searchResult.getSearchEntries().get(0);
     String dn = searchResultEntry.getDN();
     DefaultLdapUserContext ldapUserContext = internalCreateUser(dn);
     ldapUserContext.getKnownAttributes().put("cn", searchResultEntry.getAttributeValue("cn"));
     return ldapUserContext;
   } catch (com.unboundid.ldap.sdk.LDAPException e) {
     throw new LdapException(e);
   }
 }