예제 #1
0
  // We initialize these for each new AciHandler so that we can clear
  // out the stale references that can occur during an in-core restart.
  private static void initStatics() {
    if ((aciType = DirectoryServer.getAttributeType("aci")) == null) {
      aciType = DirectoryServer.getDefaultAttributeType("aci");
    }

    if ((globalAciType = DirectoryServer.getAttributeType(ATTR_AUTHZ_GLOBAL_ACI)) == null) {
      globalAciType = DirectoryServer.getDefaultAttributeType(ATTR_AUTHZ_GLOBAL_ACI);
    }

    if ((debugSearchIndex =
            DirectoryServer.getAttributeType(EntryContainer.ATTR_DEBUG_SEARCH_INDEX))
        == null) {
      debugSearchIndex =
          DirectoryServer.getDefaultAttributeType(EntryContainer.ATTR_DEBUG_SEARCH_INDEX);
    }

    if ((refAttrType = DirectoryServer.getAttributeType(ATTR_REFERRAL_URL)) == null) {
      refAttrType = DirectoryServer.getDefaultAttributeType(ATTR_REFERRAL_URL);
    }
    try {
      debugSearchIndexDN = DN.decode("cn=debugsearch");
    } catch (DirectoryException ex) {
      // Should never happen.
    }
  }
예제 #2
0
  /**
   * Once-only initialization.
   *
   * @throws Exception If an unexpected error occurred.
   */
  @BeforeClass
  public void setUp() throws Exception {
    // This test suite depends on having the schema available, so we'll
    // start the server.
    TestCaseUtils.startServer();

    // Initialize schema bits.
    OC_TOP = DirectoryServer.getObjectClass("top");
    OC_PERSON = DirectoryServer.getObjectClass("person");

    AT_OC = DirectoryServer.getObjectClassAttributeType();
    AT_CN = DirectoryServer.getAttributeType("cn");
    AT_SN = DirectoryServer.getAttributeType("sn");
    AT_DESCR = DirectoryServer.getAttributeType("description");
    AT_TELN = DirectoryServer.getAttributeType("telephonenumber");

    // Create a temporary file containing an attribute value.
    TEMP_FILE = File.createTempFile("tmp", "txt");
    OutputStream out = null;
    try {
      out = new FileOutputStream(TEMP_FILE);
      out.write(TEMP_FILE_STRING.getBytes("UTF-8"));
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
예제 #3
0
  /**
   * Generates an entry for a backup directory based on the provided DN. The DN must contain an RDN
   * component that specifies the path to the backup directory, and that directory must exist and be
   * a valid backup directory.
   *
   * @param entryDN The DN of the backup directory entry to retrieve.
   * @return The requested backup directory entry.
   * @throws DirectoryException If the specified directory does not exist or is not a valid backup
   *     directory, or if the DN does not specify any backup directory.
   */
  private Entry getBackupDirectoryEntry(DN entryDN) throws DirectoryException {
    // Make sure that the DN specifies a backup directory.
    AttributeType t = DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
    AttributeValue v = entryDN.getRDN().getAttributeValue(t);
    if (v == null) {
      Message message = ERR_BACKUP_DN_DOES_NOT_SPECIFY_DIRECTORY.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message, backupBaseDN, null);
    }

    // Get a handle to the backup directory and the information that it
    // contains.
    BackupDirectory backupDirectory;
    try {
      backupDirectory = BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
    } catch (ConfigException ce) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, ce);
      }

      Message message =
          ERR_BACKUP_INVALID_BACKUP_DIRECTORY.get(String.valueOf(entryDN), ce.getMessage());
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
    } catch (Exception e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }

      Message message = ERR_BACKUP_ERROR_GETTING_BACKUP_DIRECTORY.get(getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }

    // Construct the backup directory entry to return.
    LinkedHashMap<ObjectClass, String> ocMap = new LinkedHashMap<ObjectClass, String>(2);
    ocMap.put(DirectoryServer.getTopObjectClass(), OC_TOP);

    ObjectClass backupDirOC = DirectoryServer.getObjectClass(OC_BACKUP_DIRECTORY, true);
    ocMap.put(backupDirOC, OC_BACKUP_DIRECTORY);

    LinkedHashMap<AttributeType, List<Attribute>> opAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>(0);
    LinkedHashMap<AttributeType, List<Attribute>> userAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>(3);

    ArrayList<Attribute> attrList = new ArrayList<Attribute>(1);
    attrList.add(Attributes.create(t, v));
    userAttrs.put(t, attrList);

    t = DirectoryServer.getAttributeType(ATTR_BACKUP_BACKEND_DN, true);
    attrList = new ArrayList<Attribute>(1);
    attrList.add(
        Attributes.create(
            t, AttributeValues.create(t, backupDirectory.getConfigEntryDN().toString())));
    userAttrs.put(t, attrList);

    Entry e = new Entry(entryDN, ocMap, userAttrs, opAttrs);
    e.processVirtualAttributes();
    return e;
  }
  /** {@inheritDoc} */
  @Override
  public void initializeSASLMechanismHandler(ExternalSASLMechanismHandlerCfg configuration)
      throws ConfigException, InitializationException {
    configuration.addExternalChangeListener(this);
    currentConfig = configuration;

    // See if we should attempt to validate client certificates against those in
    // the corresponding user's entry.
    switch (configuration.getCertificateValidationPolicy()) {
      case NEVER:
        validationPolicy = CertificateValidationPolicy.NEVER;
        break;
      case IFPRESENT:
        validationPolicy = CertificateValidationPolicy.IFPRESENT;
        break;
      case ALWAYS:
        validationPolicy = CertificateValidationPolicy.ALWAYS;
        break;
    }

    // Get the attribute type to use for validating the certificates.  If none
    // is provided, then default to the userCertificate type.
    certificateAttributeType = configuration.getCertificateAttribute();
    if (certificateAttributeType == null) {
      certificateAttributeType =
          DirectoryServer.getAttributeType(DEFAULT_VALIDATION_CERT_ATTRIBUTE, true);
    }

    DirectoryServer.registerSASLMechanismHandler(SASL_MECHANISM_EXTERNAL, this);
  }
  /** {@inheritDoc} */
  public ConfigChangeResult applyConfigurationChange(
      ExternalSASLMechanismHandlerCfg configuration) {
    final ConfigChangeResult ccr = new ConfigChangeResult();

    // See if we should attempt to validate client certificates against those in
    // the corresponding user's entry.
    CertificateValidationPolicy newValidationPolicy = CertificateValidationPolicy.ALWAYS;
    switch (configuration.getCertificateValidationPolicy()) {
      case NEVER:
        newValidationPolicy = CertificateValidationPolicy.NEVER;
        break;
      case IFPRESENT:
        newValidationPolicy = CertificateValidationPolicy.IFPRESENT;
        break;
      case ALWAYS:
        newValidationPolicy = CertificateValidationPolicy.ALWAYS;
        break;
    }

    // Get the attribute type to use for validating the certificates.  If none
    // is provided, then default to the userCertificate type.
    AttributeType newCertificateType = configuration.getCertificateAttribute();
    if (newCertificateType == null) {
      newCertificateType =
          DirectoryServer.getAttributeType(DEFAULT_VALIDATION_CERT_ATTRIBUTE, true);
    }

    if (ccr.getResultCode() == ResultCode.SUCCESS) {
      validationPolicy = newValidationPolicy;
      certificateAttributeType = newCertificateType;
      currentConfig = configuration;
    }

    return ccr;
  }
예제 #6
0
  /**
   * Performs any initialization for this tag that may be needed while parsing a branch definition.
   *
   * @param templateFile The template file in which this tag is used.
   * @param branch The branch in which this tag is used.
   * @param arguments The set of arguments provided for this tag.
   * @param lineNumber The line number on which this tag appears in the template file.
   * @param warnings A list into which any appropriate warning messages may be placed.
   * @throws InitializationException If a problem occurs while initializing this tag.
   */
  public void initializeForBranch(
      TemplateFile templateFile,
      Branch branch,
      String[] arguments,
      int lineNumber,
      List<Message> warnings)
      throws InitializationException {
    if ((arguments.length < 1) || (arguments.length > 2)) {
      Message message =
          ERR_MAKELDIF_TAG_INVALID_ARGUMENT_RANGE_COUNT.get(
              getName(), lineNumber, 1, 2, arguments.length);
      throw new InitializationException(message);
    }

    String lowerName = toLowerCase(arguments[0]);
    AttributeType t = DirectoryServer.getAttributeType(lowerName, true);
    if (!branch.hasAttribute(t)) {
      Message message = ERR_MAKELDIF_TAG_UNDEFINED_ATTRIBUTE.get(arguments[0], lineNumber);
      throw new InitializationException(message);
    }

    if (arguments.length == 2) {
      assertionValue = arguments[1];
    } else {
      assertionValue = null;
    }
  }
예제 #7
0
  /** {@inheritDoc} */
  @Override
  public long getEntryCount() {
    int numEntries = 1;

    AttributeType backupPathType =
        DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);

    for (File f : backupDirectories) {
      try {
        // Check to see if the descriptor file exists.  If not, then skip this
        // backup directory.
        File descriptorFile = new File(f, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
        if (!descriptorFile.exists()) {
          continue;
        }

        DN backupDirDN = makeChildDN(backupBaseDN, backupPathType, f.getAbsolutePath());
        getBackupDirectoryEntry(backupDirDN);
        numEntries++;
      } catch (Exception e) {
      }
    }

    return numEntries;
  }
  /**
   * Make sure that the server is running.
   *
   * @throws Exception If an unexpected problem occurs.
   */
  @BeforeClass()
  public void startServer() throws Exception {
    TestCaseUtils.startServer();

    givenNameType = DirectoryServer.getAttributeType("givenname", false);
    assertNotNull(givenNameType);

    snType = DirectoryServer.getAttributeType("sn", false);
    assertNotNull(snType);

    aaccfJohnsonDN = DN.decode("uid=aaccf.johnson,dc=example,dc=com");
    aaronZimmermanDN = DN.decode("uid=aaron.zimmerman,dc=example,dc=com");
    albertSmithDN = DN.decode("uid=albert.smith,dc=example,dc=com");
    albertZimmermanDN = DN.decode("uid=albert.zimmerman,dc=example,dc=com");
    lowercaseMcGeeDN = DN.decode("uid=lowercase.mcgee,dc=example,dc=com");
    margaretJonesDN = DN.decode("uid=margaret.jones,dc=example,dc=com");
    maryJonesDN = DN.decode("uid=mary.jones,dc=example,dc=com");
    samZweckDN = DN.decode("uid=sam.zweck,dc=example,dc=com");
    zorroDN = DN.decode("uid=zorro,dc=example,dc=com");
  }
  /**
   * Returns {@code true} if this authentication policy state is associated with a user whose
   * account has been administratively disabled.
   *
   * <p>The default implementation is use the value of the "ds-pwp-account-disable" attribute in the
   * user's entry.
   *
   * @return {@code true} if this authentication policy state is associated with a user whose
   *     account has been administratively disabled.
   */
  public boolean isDisabled() {
    final AttributeType type = DirectoryServer.getAttributeType(OP_ATTR_ACCOUNT_DISABLED, true);
    try {
      isDisabled = getBoolean(userEntry, type);
    } catch (final Exception e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }

      isDisabled = ConditionResult.TRUE;
      if (debugEnabled()) {
        TRACER.debugWarning(
            "User %s is considered administratively "
                + "disabled because an error occurred while "
                + "attempting to make the determination: %s.",
            userEntry.getDN().toString(), stackTraceToSingleLineString(e));
      }

      return true;
    }

    if (isDisabled == ConditionResult.UNDEFINED) {
      isDisabled = ConditionResult.FALSE;
      if (debugEnabled()) {
        TRACER.debugInfo(
            "User %s is not administratively disabled since "
                + "the attribute \"%s\" is not present in the entry.",
            userEntry.getDN().toString(), OP_ATTR_ACCOUNT_DISABLED);
      }
      return false;
    }

    if (debugEnabled()) {
      TRACER.debugInfo(
          "User %s %s administratively disabled.",
          userEntry.getDN().toString(), ((isDisabled == ConditionResult.TRUE) ? " is" : " is not"));
    }

    return isDisabled == ConditionResult.TRUE;
  }
예제 #10
0
 /**
  * Check access on compare operations. Note that the attribute type is unavailable at this time,
  * so this method partially parses the raw attribute string to get the base attribute type.
  * Options are ignored.
  *
  * @param operation The compare operation to check access on.
  * @return True if access is allowed.
  */
 @Override
 public boolean isAllowed(LocalBackendCompareOperation operation) {
   AciLDAPOperationContainer operationContainer =
       new AciLDAPOperationContainer(operation, ACI_COMPARE);
   String baseName;
   String rawAttributeType = operation.getRawAttributeType();
   int semicolonPosition = rawAttributeType.indexOf(';');
   if (semicolonPosition > 0) {
     baseName = toLowerCase(rawAttributeType.substring(0, semicolonPosition));
   } else {
     baseName = toLowerCase(rawAttributeType);
   }
   AttributeType attributeType;
   if ((attributeType = DirectoryServer.getAttributeType(baseName)) == null) {
     attributeType = DirectoryServer.getDefaultAttributeType(baseName);
   }
   AttributeValue attributeValue =
       AttributeValues.create(attributeType, operation.getAssertionValue());
   operationContainer.setCurrentAttributeType(attributeType);
   operationContainer.setCurrentAttributeValue(attributeValue);
   return isAllowed(operationContainer, operation);
 }
  /** {@inheritDoc} */
  @Override
  public VirtualStaticGroup newInstance(ServerContext serverContext, Entry groupEntry)
      throws DirectoryException {
    ifNull(groupEntry);

    // Get the target group DN attribute from the entry, if there is one.
    DN targetDN = null;
    AttributeType targetType = DirectoryServer.getAttributeType(ATTR_TARGET_GROUP_DN, true);
    List<Attribute> attrList = groupEntry.getAttribute(targetType);
    if (attrList != null) {
      for (Attribute a : attrList) {
        for (ByteString v : a) {
          if (targetDN != null) {
            LocalizableMessage message =
                ERR_VIRTUAL_STATIC_GROUP_MULTIPLE_TARGETS.get(groupEntry.getName());
            throw new DirectoryException(ResultCode.OBJECTCLASS_VIOLATION, message);
          }

          try {
            targetDN = DN.decode(v);
          } catch (DirectoryException de) {
            logger.traceException(de);

            LocalizableMessage message =
                ERR_VIRTUAL_STATIC_GROUP_CANNOT_DECODE_TARGET.get(
                    v, groupEntry.getName(), de.getMessageObject());
            throw new DirectoryException(ResultCode.INVALID_ATTRIBUTE_SYNTAX, message, de);
          }
        }
      }
    }

    if (targetDN == null) {
      LocalizableMessage message = ERR_VIRTUAL_STATIC_GROUP_NO_TARGET.get(groupEntry.getName());
      throw new DirectoryException(ResultCode.OBJECTCLASS_VIOLATION, message);
    }

    return new VirtualStaticGroup(groupEntry.getName(), targetDN);
  }
예제 #12
0
  /** {@inheritDoc} */
  @Override
  public void search(SearchOperation searchOperation) throws DirectoryException {
    // Get the base entry for the search, if possible.  If it doesn't exist,
    // then this will throw an exception.
    DN baseDN = searchOperation.getBaseDN();
    Entry baseEntry = getEntry(baseDN);

    // Look at the base DN and see if it's the backup base DN, a backup
    // directory entry DN, or a backup entry DN.
    DN parentDN;
    SearchScope scope = searchOperation.getScope();
    SearchFilter filter = searchOperation.getFilter();
    if (backupBaseDN.equals(baseDN)) {
      if ((scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE)
          && filter.matchesEntry(baseEntry)) {
        searchOperation.returnEntry(baseEntry, null);
      }

      if (scope != SearchScope.BASE_OBJECT && !backupDirectories.isEmpty()) {
        AttributeType backupPathType =
            DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
        for (File f : backupDirectories) {
          // Check to see if the descriptor file exists.  If not, then skip this
          // backup directory.
          File descriptorFile = new File(f, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
          if (!descriptorFile.exists()) {
            continue;
          }

          DN backupDirDN = makeChildDN(backupBaseDN, backupPathType, f.getAbsolutePath());

          Entry backupDirEntry;
          try {
            backupDirEntry = getBackupDirectoryEntry(backupDirDN);
          } catch (Exception e) {
            if (debugEnabled()) {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }

            continue;
          }

          if (filter.matchesEntry(backupDirEntry)) {
            searchOperation.returnEntry(backupDirEntry, null);
          }

          if (scope != SearchScope.SINGLE_LEVEL) {
            List<Attribute> attrList = backupDirEntry.getAttribute(backupPathType);
            if (attrList != null && !attrList.isEmpty()) {
              for (AttributeValue v : attrList.get(0)) {
                try {
                  BackupDirectory backupDirectory =
                      BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
                  AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
                  for (String backupID : backupDirectory.getBackups().keySet()) {
                    DN backupEntryDN = makeChildDN(backupDirDN, idType, backupID);
                    Entry backupEntry = getBackupEntry(backupEntryDN);
                    if (filter.matchesEntry(backupEntry)) {
                      searchOperation.returnEntry(backupEntry, null);
                    }
                  }
                } catch (Exception e) {
                  if (debugEnabled()) {
                    TRACER.debugCaught(DebugLogLevel.ERROR, e);
                  }

                  continue;
                }
              }
            }
          }
        }
      }
    } else if (backupBaseDN.equals(parentDN = baseDN.getParentDNInSuffix())) {
      Entry backupDirEntry = getBackupDirectoryEntry(baseDN);

      if ((scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE)
          && filter.matchesEntry(backupDirEntry)) {
        searchOperation.returnEntry(backupDirEntry, null);
      }

      if (scope != SearchScope.BASE_OBJECT) {
        AttributeType t = DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
        List<Attribute> attrList = backupDirEntry.getAttribute(t);
        if (attrList != null && !attrList.isEmpty()) {
          for (AttributeValue v : attrList.get(0)) {
            try {
              BackupDirectory backupDirectory =
                  BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
              AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
              for (String backupID : backupDirectory.getBackups().keySet()) {
                DN backupEntryDN = makeChildDN(baseDN, idType, backupID);
                Entry backupEntry = getBackupEntry(backupEntryDN);
                if (filter.matchesEntry(backupEntry)) {
                  searchOperation.returnEntry(backupEntry, null);
                }
              }
            } catch (Exception e) {
              if (debugEnabled()) {
                TRACER.debugCaught(DebugLogLevel.ERROR, e);
              }

              continue;
            }
          }
        }
      }
    } else {
      if (parentDN == null || !backupBaseDN.equals(parentDN.getParentDNInSuffix())) {
        Message message = ERR_BACKUP_NO_SUCH_ENTRY.get(String.valueOf(backupBaseDN));
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
      }

      if (scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE) {
        Entry backupEntry = getBackupEntry(baseDN);
        if (backupEntry == null) {
          Message message = ERR_BACKUP_NO_SUCH_ENTRY.get(String.valueOf(backupBaseDN));
          throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
        }

        if (filter.matchesEntry(backupEntry)) {
          searchOperation.returnEntry(backupEntry, null);
        }
      }
    }
  }
예제 #13
0
  /**
   * Generates an entry for a backup based on the provided DN. The DN must have an RDN component
   * that specifies the backup ID, and the parent DN must have an RDN component that specifies the
   * backup directory.
   *
   * @param entryDN The DN of the backup entry to retrieve.
   * @return The requested backup entry.
   * @throws DirectoryException If the specified backup does not exist or is invalid.
   */
  private Entry getBackupEntry(DN entryDN) throws DirectoryException {
    // First, get the backup ID from the entry DN.
    AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
    AttributeValue idValue = entryDN.getRDN().getAttributeValue(idType);
    if (idValue == null) {
      Message message = ERR_BACKUP_NO_BACKUP_ID_IN_DN.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
    }
    String backupID = idValue.getValue().toString();

    // Next, get the backup directory from the parent DN.
    DN parentDN = entryDN.getParentDNInSuffix();
    if (parentDN == null) {
      Message message = ERR_BACKUP_NO_BACKUP_PARENT_DN.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
    }

    AttributeType t = DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
    AttributeValue v = parentDN.getRDN().getAttributeValue(t);
    if (v == null) {
      Message message = ERR_BACKUP_NO_BACKUP_DIR_IN_DN.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
    }

    BackupDirectory backupDirectory;
    try {
      backupDirectory = BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
    } catch (ConfigException ce) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, ce);
      }

      Message message =
          ERR_BACKUP_INVALID_BACKUP_DIRECTORY.get(String.valueOf(entryDN), ce.getMessageObject());
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
    } catch (Exception e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }

      Message message = ERR_BACKUP_ERROR_GETTING_BACKUP_DIRECTORY.get(getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }

    BackupInfo backupInfo = backupDirectory.getBackupInfo(backupID);
    if (backupInfo == null) {
      Message message = ERR_BACKUP_NO_SUCH_BACKUP.get(backupID, backupDirectory.getPath());
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message, parentDN, null);
    }

    // Construct the backup entry to return.
    LinkedHashMap<ObjectClass, String> ocMap = new LinkedHashMap<ObjectClass, String>(3);
    ocMap.put(DirectoryServer.getTopObjectClass(), OC_TOP);

    ObjectClass oc = DirectoryServer.getObjectClass(OC_BACKUP_INFO, true);
    ocMap.put(oc, OC_BACKUP_INFO);

    oc = DirectoryServer.getObjectClass(OC_EXTENSIBLE_OBJECT_LC, true);
    ocMap.put(oc, OC_EXTENSIBLE_OBJECT);

    LinkedHashMap<AttributeType, List<Attribute>> opAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>(0);
    LinkedHashMap<AttributeType, List<Attribute>> userAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>();

    ArrayList<Attribute> attrList = new ArrayList<Attribute>(1);
    attrList.add(Attributes.create(idType, idValue));
    userAttrs.put(idType, attrList);

    backupInfo.getBackupDirectory();
    attrList = new ArrayList<Attribute>(1);
    attrList.add(Attributes.create(t, v));
    userAttrs.put(t, attrList);

    Date backupDate = backupInfo.getBackupDate();
    if (backupDate != null) {
      t = DirectoryServer.getAttributeType(ATTR_BACKUP_DATE, true);
      attrList = new ArrayList<Attribute>(1);
      attrList.add(
          Attributes.create(
              t, AttributeValues.create(t, GeneralizedTimeSyntax.format(backupDate))));
      userAttrs.put(t, attrList);
    }

    t = DirectoryServer.getAttributeType(ATTR_BACKUP_COMPRESSED, true);
    attrList = new ArrayList<Attribute>(1);
    attrList.add(Attributes.create(t, BooleanSyntax.createBooleanValue(backupInfo.isCompressed())));
    userAttrs.put(t, attrList);

    t = DirectoryServer.getAttributeType(ATTR_BACKUP_ENCRYPTED, true);
    attrList = new ArrayList<Attribute>(1);
    attrList.add(Attributes.create(t, BooleanSyntax.createBooleanValue(backupInfo.isEncrypted())));
    userAttrs.put(t, attrList);

    t = DirectoryServer.getAttributeType(ATTR_BACKUP_INCREMENTAL, true);
    attrList = new ArrayList<Attribute>(1);
    attrList.add(
        Attributes.create(t, BooleanSyntax.createBooleanValue(backupInfo.isIncremental())));
    userAttrs.put(t, attrList);

    HashSet<String> dependencies = backupInfo.getDependencies();
    if (dependencies != null && !dependencies.isEmpty()) {
      t = DirectoryServer.getAttributeType(ATTR_BACKUP_DEPENDENCY, true);
      AttributeBuilder builder = new AttributeBuilder(t);
      for (String s : dependencies) {
        builder.add(AttributeValues.create(t, s));
      }
      attrList = new ArrayList<Attribute>(1);
      attrList.add(builder.toAttribute());
      userAttrs.put(t, attrList);
    }

    byte[] signedHash = backupInfo.getSignedHash();
    if (signedHash != null) {
      t = DirectoryServer.getAttributeType(ATTR_BACKUP_SIGNED_HASH, true);
      attrList = new ArrayList<Attribute>(1);
      attrList.add(Attributes.create(t, AttributeValues.create(t, ByteString.wrap(signedHash))));
      userAttrs.put(t, attrList);
    }

    byte[] unsignedHash = backupInfo.getUnsignedHash();
    if (unsignedHash != null) {
      t = DirectoryServer.getAttributeType(ATTR_BACKUP_UNSIGNED_HASH, true);
      attrList = new ArrayList<Attribute>(1);
      attrList.add(Attributes.create(t, AttributeValues.create(t, ByteString.wrap(unsignedHash))));
      userAttrs.put(t, attrList);
    }

    HashMap<String, String> properties = backupInfo.getBackupProperties();
    if (properties != null && !properties.isEmpty()) {
      for (Map.Entry<String, String> e : properties.entrySet()) {
        t = DirectoryServer.getAttributeType(toLowerCase(e.getKey()), true);
        attrList = new ArrayList<Attribute>(1);
        attrList.add(Attributes.create(t, AttributeValues.create(t, e.getValue())));
        userAttrs.put(t, attrList);
      }
    }

    Entry e = new Entry(entryDN, ocMap, userAttrs, opAttrs);
    e.processVirtualAttributes();
    return e;
  }
예제 #14
0
  /** {@inheritDoc} */
  @Override
  public long numSubordinates(DN entryDN, boolean subtree) throws DirectoryException {
    // If the requested entry was null, then return undefined.
    if (entryDN == null) {
      return -1;
    }

    // If the requested entry was the backend base entry, then return
    // the number of backup directories.
    if (backupBaseDN.equals(entryDN)) {
      long count = 0;
      for (File f : backupDirectories) {
        // Check to see if the descriptor file exists.  If not, then skip this
        // backup directory.
        File descriptorFile = new File(f, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
        if (!descriptorFile.exists()) {
          continue;
        }

        // If subtree is included, count the number of entries for each
        // backup directory.
        if (subtree) {
          try {
            BackupDirectory backupDirectory =
                BackupDirectory.readBackupDirectoryDescriptor(f.getPath());
            count += backupDirectory.getBackups().keySet().size();
          } catch (Exception e) {
            return -1;
          }
        }

        count++;
      }
      return count;
    }

    // See if the requested entry was one level below the backend base entry.
    // If so, then it must point to a backup directory.  Otherwise, it must be
    // two levels below the backup base entry and must point to a specific
    // backup.
    DN parentDN = entryDN.getParentDNInSuffix();
    if (parentDN == null) {
      return -1;
    } else if (backupBaseDN.equals(parentDN)) {
      long count = 0;
      Entry backupDirEntry = getBackupDirectoryEntry(entryDN);

      AttributeType t = DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
      List<Attribute> attrList = backupDirEntry.getAttribute(t);
      if (attrList != null && !attrList.isEmpty()) {
        for (AttributeValue v : attrList.get(0)) {
          try {
            BackupDirectory backupDirectory =
                BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
            count += backupDirectory.getBackups().keySet().size();
          } catch (Exception e) {
            return -1;
          }
        }
      }
      return count;
    } else if (backupBaseDN.equals(parentDN.getParentDNInSuffix())) {
      return 0;
    } else {
      return -1;
    }
  }
  @Test(enabled = true)
  public void testValidRequest() throws Exception {
    final CryptoManagerImpl cm = DirectoryServer.getCryptoManager();
    final String secretMessage = "zyxwvutsrqponmlkjihgfedcba";
    final String cipherTransformationName = "AES/CBC/PKCS5Padding";
    final int cipherKeyLength = 128;

    CryptoManagerImpl.publishInstanceKeyEntryInADS();

    // Initial encryption ensures a cipher key entry is in ADS.
    cm.encrypt(cipherTransformationName, cipherKeyLength, secretMessage.getBytes());

    // Retrieve all uncompromised cipher key entries corresponding to the
    // specified transformation and key length.
    final String baseDNStr // TODO: is this DN defined elsewhere as a constant?
        = "cn=secret keys," + ADSContext.getAdministrationSuffixDN();
    final DN baseDN = DN.decode(baseDNStr);
    final String FILTER_OC_INSTANCE_KEY =
        new StringBuilder("(objectclass=")
            .append(ConfigConstants.OC_CRYPTO_CIPHER_KEY)
            .append(")")
            .toString();
    final String FILTER_NOT_COMPROMISED =
        new StringBuilder("(!(")
            .append(ConfigConstants.ATTR_CRYPTO_KEY_COMPROMISED_TIME)
            .append("=*))")
            .toString();
    final String FILTER_CIPHER_TRANSFORMATION_NAME =
        new StringBuilder("(")
            .append(ConfigConstants.ATTR_CRYPTO_CIPHER_TRANSFORMATION_NAME)
            .append("=")
            .append(cipherTransformationName)
            .append(")")
            .toString();
    final String FILTER_CIPHER_KEY_LENGTH =
        new StringBuilder("(")
            .append(ConfigConstants.ATTR_CRYPTO_KEY_LENGTH_BITS)
            .append("=")
            .append(String.valueOf(cipherKeyLength))
            .append(")")
            .toString();
    final String searchFilter =
        new StringBuilder("(&")
            .append(FILTER_OC_INSTANCE_KEY)
            .append(FILTER_NOT_COMPROMISED)
            .append(FILTER_CIPHER_TRANSFORMATION_NAME)
            .append(FILTER_CIPHER_KEY_LENGTH)
            .append(")")
            .toString();
    final LinkedHashSet<String> requestedAttributes = new LinkedHashSet<String>();
    requestedAttributes.add(ConfigConstants.ATTR_CRYPTO_SYMMETRIC_KEY);
    final InternalClientConnection icc = InternalClientConnection.getRootConnection();
    InternalSearchOperation searchOp =
        icc.processSearch(
            baseDN,
            SearchScope.SINGLE_LEVEL,
            DereferencePolicy.NEVER_DEREF_ALIASES,
            /* size limit */ 0, /* time limit */
            0,
            /* types only */ false,
            SearchFilter.createFilterFromString(searchFilter),
            requestedAttributes);
    assertTrue(0 < searchOp.getSearchEntries().size());

    final InternalClientConnection internalConnection =
        InternalClientConnection.getRootConnection();
    final String instanceKeyID = cm.getInstanceKeyID();
    final AttributeType attrSymmetricKey =
        DirectoryServer.getAttributeType(ConfigConstants.ATTR_CRYPTO_SYMMETRIC_KEY);
    for (Entry e : searchOp.getSearchEntries()) {
      final String symmetricKeyAttributeValue =
          e.getAttributeValue(attrSymmetricKey, DirectoryStringSyntax.DECODER);
      final ByteString requestValue =
          GetSymmetricKeyExtendedOperation.encodeRequestValue(
              symmetricKeyAttributeValue, instanceKeyID);
      final ExtendedOperation extendedOperation =
          internalConnection.processExtendedOperation(
              ServerConstants.OID_GET_SYMMETRIC_KEY_EXTENDED_OP, requestValue);
      assertEquals(extendedOperation.getResultCode(), ResultCode.SUCCESS);
      // The key should be re-wrapped, and hence have a different binary
      // representation....
      final String responseValue = extendedOperation.getResponseValue().toString();
      assertFalse(symmetricKeyAttributeValue.equals(responseValue));
      // ... but the keyIDs should be equal (ideally, the validity of
      // the returned value would be checked by decoding the
      // returned ds-cfg-symmetric-key attribute value; however, there
      // is no non-private method to call.
      assertEquals(responseValue.split(":")[0], symmetricKeyAttributeValue.split(":")[0]);
    }
  }
예제 #16
0
  /**
   * Attempt to read multiple changes.
   *
   * @throws Exception If the test failed unexpectedly.
   */
  @Test(dependsOnMethods = {"testChangeRecordEmptyStream"})
  public void testReadChangeMultiple() throws Exception {
    LDIFReader reader = createLDIFReader(VALID_LDIF);

    try {
      ChangeRecordEntry change;
      AddChangeRecordEntry add;
      DeleteChangeRecordEntry delete;
      ModifyChangeRecordEntry modify;
      ModifyDNChangeRecordEntry modifyDN;
      DN dn;
      RDN rdn;
      Iterator<RawModification> i;
      Modification mod;
      Attribute attr;

      // Change record #1.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof AddChangeRecordEntry);
      add = (AddChangeRecordEntry) change;

      dn = DN.decode("cn=Fiona Jensen, ou=Marketing, dc=airius, dc=com");
      Assert.assertEquals(add.getDN(), dn);

      List<Attribute> attrs = new ArrayList<Attribute>();
      AttributeBuilder builder = new AttributeBuilder(AT_OC, "objectclass");
      builder.add(AttributeValues.create(AT_OC, "top"));
      builder.add(AttributeValues.create(AT_OC, "person"));
      builder.add(AttributeValues.create(AT_OC, "organizationalPerson"));

      attrs.add(builder.toAttribute());
      attrs.add(Attributes.create("cn", "Fiona Jensen"));
      attrs.add(Attributes.create("sn", "Jensen"));
      attrs.add(Attributes.create("uid", "fiona"));
      attrs.add(Attributes.create("telephonenumber", "+1 408 555 1212"));
      Assert.assertTrue(add.getAttributes().containsAll(attrs));

      // Change record #2.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof DeleteChangeRecordEntry);
      delete = (DeleteChangeRecordEntry) change;

      dn = DN.decode("cn=Robert Jensen, ou=Marketing, dc=airius, dc=com");
      Assert.assertEquals(delete.getDN(), dn);

      // Change record #3.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof ModifyDNChangeRecordEntry);
      modifyDN = (ModifyDNChangeRecordEntry) change;

      dn = DN.decode("cn=Paul Jensen, ou=Product Development, dc=airius, dc=com");
      Assert.assertEquals(modifyDN.getDN(), dn);

      rdn = RDN.decode("cn=paula jensen");
      Assert.assertEquals(modifyDN.getNewRDN(), rdn);
      Assert.assertNull(modifyDN.getNewSuperiorDN());
      Assert.assertTrue(modifyDN.deleteOldRDN());

      // Change record #4.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof ModifyDNChangeRecordEntry);
      modifyDN = (ModifyDNChangeRecordEntry) change;

      dn = DN.decode("ou=PD Accountants, ou=Product Development, dc=airius, dc=com");
      Assert.assertEquals(modifyDN.getDN(), dn);

      rdn = RDN.decode("ou=Product Development Accountants");
      Assert.assertEquals(modifyDN.getNewRDN(), rdn);
      dn = DN.decode("ou=Accounting, dc=airius, dc=com");
      Assert.assertEquals(modifyDN.getNewSuperiorDN(), dn);
      Assert.assertFalse(modifyDN.deleteOldRDN());

      // Change record #5.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof ModifyChangeRecordEntry);
      modify = (ModifyChangeRecordEntry) change;

      dn = DN.decode("cn=Paula Jensen, ou=Product Development, dc=airius, dc=com");
      Assert.assertEquals(modify.getDN(), dn);

      i = modify.getModifications().iterator();

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.ADD);
      attr = Attributes.create("postaladdress", "123 Anystreet $ Sunnyvale, CA $ 94086");
      Assert.assertEquals(mod.getAttribute(), attr);

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.DELETE);
      attr = Attributes.empty(AT_DESCR);
      Assert.assertEquals(mod.getAttribute(), attr);

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.REPLACE);
      builder = new AttributeBuilder(AT_TELN, "telephonenumber");
      builder.add(AttributeValues.create(AT_TELN, "+1 408 555 1234"));
      builder.add(AttributeValues.create(AT_TELN, "+1 408 555 5678"));
      Assert.assertEquals(mod.getAttribute(), builder.toAttribute());

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.DELETE);
      attr = Attributes.create("facsimiletelephonenumber", "+1 408 555 9876");
      Assert.assertEquals(mod.getAttribute(), attr);

      Assert.assertFalse(i.hasNext());

      // Change record #6.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof ModifyChangeRecordEntry);
      modify = (ModifyChangeRecordEntry) change;

      dn = DN.decode("cn=Ingrid Jensen, ou=Product Support, dc=airius, dc=com");
      Assert.assertEquals(modify.getDN(), dn);

      i = modify.getModifications().iterator();

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.REPLACE);
      attr = Attributes.empty(DirectoryServer.getAttributeType("postaladdress"));
      Assert.assertEquals(mod.getAttribute(), attr);

      // Change record #7.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof ModifyChangeRecordEntry);
      modify = (ModifyChangeRecordEntry) change;

      Assert.assertTrue(modify.getDN().isNullDN());

      i = modify.getModifications().iterator();

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.DELETE);
      attr = Attributes.empty(AT_DESCR);
      Assert.assertEquals(mod.getAttribute(), attr);

      // Change record #8.
      change = reader.readChangeRecord(false);
      Assert.assertTrue(change instanceof ModifyChangeRecordEntry);
      modify = (ModifyChangeRecordEntry) change;

      dn = DN.decode("uid=rogasawara, ou=\u55b6\u696d\u90e8, o=airius");
      Assert.assertEquals(modify.getDN(), dn);

      i = modify.getModifications().iterator();

      Assert.assertTrue(i.hasNext());
      mod = i.next().toModification();
      Assert.assertEquals(mod.getModificationType(), ModificationType.DELETE);
      attr = Attributes.empty(AT_DESCR);
      Assert.assertEquals(mod.getAttribute(), attr);

      Assert.assertFalse(i.hasNext());

      // Check final state.

      Assert.assertNull(reader.readChangeRecord(false));

      Assert.assertEquals(reader.getEntriesIgnored(), 0);
      Assert.assertEquals(reader.getEntriesRead(), 0);
      Assert.assertEquals(reader.getEntriesRejected(), 0);
      Assert.assertEquals(reader.getLastEntryLineNumber(), 72);
    } finally {
      reader.close();
    }
  }