Beispiel #1
0
 /** Gets list of replicated servers from local OpenDJ directory. */
 public static Set getServerSet(LDAPConnection lc) {
   final String[] attrs = {"uniqueMember"};
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   try {
     if (lc != null) {
       LDAPEntry le = lc.read(replDN, attrs);
       if (le != null) {
         Set hostSet = new HashSet();
         LDAPAttribute la = le.getAttribute(attrs[0]);
         if (la != null) {
           Enumeration en = la.getStringValues();
           while (en != null && en.hasMoreElements()) {
             String val = (String) en.nextElement();
             // strip "cn="
             hostSet.add(val.substring(3, val.length()));
           }
         }
         return hostSet;
       } else {
         debug.error(
             "EmbeddedOpenDS:syncOpenDSServer():" + "Could not find trustkey for:" + replDN);
       }
     } else {
       debug.error(
           "EmbeddedOpenDS:syncOpenDSServer():" + "Could not connect to local opends instance.");
     }
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting replication key:", ex);
   }
   return null;
 }
  /** {@inheritDoc} */
  public AMIdentity searchUser(AMIdentityRepository idrepo, Map<String, Set<String>> attr) {
    AMIdentity identity = null;

    if (attr == null || attr.isEmpty()) {
      debug.warning("DefaultAccountMapper.searchUser: empty search");
      return null;
    }

    IdSearchControl ctrl = getSearchControl(IdSearchOpModifier.OR, attr);
    IdSearchResults results;
    try {
      results = idrepo.searchIdentities(IdType.USER, "*", ctrl);
      Iterator<AMIdentity> iter = results.getSearchResults().iterator();
      if (iter.hasNext()) {
        identity = iter.next();
        if (debug.messageEnabled()) {
          debug.message("getUser: user found : " + identity.getName());
        }
      }
    } catch (IdRepoException ex) {
      debug.error(
          "DefaultAccountMapper.searchUser: Problem while searching for the user. IdRepo", ex);
    } catch (SSOException ex) {
      debug.error(
          "DefaultAccountMapper.searchUser: Problem while searching for the user. SSOExc", ex);
    }

    return identity;
  }
  /** {@inheritDoc} */
  public AMIdentity provisionUser(AMIdentityRepository idrepo, Map<String, Set<String>> attributes)
      throws AuthLoginException {

    AMIdentity identity = null;
    try {
      String userId;
      Set<String> idAttribute = attributes.get(idNameAttribute);
      if (idAttribute != null && !idAttribute.isEmpty()) {
        userId = idAttribute.iterator().next();
      } else {
        userId = UUID.randomUUID().toString();
      }
      identity = idrepo.createIdentity(IdType.USER, userId, attributes);
    } catch (IdRepoException ire) {
      debug.error("DefaultAccountMapper.getAccount: IRE ", ire);
      debug.error("LDAPERROR Code = " + ire.getLDAPErrorCode());
      if (ire.getLDAPErrorCode() != null && !ire.getLDAPErrorCode().equalsIgnoreCase("68")) {
        throw new AuthLoginException("Failed to create user");
      }
    } catch (SSOException ex) {
      debug.error(
          "DefaultAccountMapper.getAttributes: Problem while creating the user. SSOExc", ex);
      throw new AuthLoginException("Failed to create user");
    }

    return identity;
  }
  /**
   * Method which creates a DC Tree for the given org, if the <code>sunPreferredDomain</code>
   * attribute is present and has a fully qualified domain name as value.
   *
   * @param token SSOToken
   * @param orgGuid identifiication of Organization entry to be mapped from dctree to organization
   *     DIT organization
   * @param domainName set the domain this organization belongs to.
   * @param attrSet the AttrSet of the organization
   * @exception AMException if unsuccessful in creating a dc tree for the organization or
   *     unsuccessful in setting the mapping between dc tree and the organization
   */
  protected void createDomain(SSOToken token, Guid orgGuid, String domainName, AttrSet attrSet)
      throws AMException {
    if (DCTREE_START_DN == null) {
      throw new AMException(AMSDKBundle.getString("355"), "355");
    }

    // Create a DC tree for specified domain.
    if ((domainName != null) && (domainName != "")) {
      try {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        dcTree.addDomain(domainName);
        // Set the domain mapping
        dcTree.setDomainMapping(domainName, orgGuid);
        String status = attrSet.getValue(INET_DOMAIN_STATUS_ATTR);
        if (status != null) {
          dcTree.setDomainStatus(domainName, status);
        }
      } catch (InvalidDCRootException ie) {
        debug.error("DCTree.createDomain(): ", ie);
        throw new AMException(AMSDKBundle.getString("343"), "343");
      } catch (UMSException ue) {
        debug.error("DCTree.createDomain(): ", ue);
        throw new AMException(AMSDKBundle.getString("344"), "344");
      }
    }
  }
 private Map<String, Object> createRSAJWK(RSAPublicKey key, KeyUse use, String alg)
     throws ServerException {
   String alias = null;
   try {
     alias = getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.KEYSTORE_ALIAS);
   } catch (SSOException | SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
   if (StringUtils.isBlank(alias)) {
     logger.error("Alias of ID Token Signing Key not set.");
     throw new ServerException("Alias of ID Token Signing Key not set.");
   } else if ("test".equals(alias)) {
     logger.warning("Alias of ID Token Signing Key should be changed from default, 'test'.");
   }
   String kid =
       Hash.hash(alias + key.getModulus().toString() + key.getPublicExponent().toString());
   return json(object(
           field("kty", "RSA"),
           field(OAuth2Constants.JWTTokenParams.KEY_ID, kid),
           field("use", use.toString()),
           field("alg", alg),
           field("n", Base64url.encode(key.getModulus().toByteArray())),
           field("e", Base64url.encode(key.getPublicExponent().toByteArray()))))
       .asMap();
 }
 protected AttrSet getDomainAttributes(SSOToken token, String orgDN, String[] attrNames)
     throws AMException, SSOException {
   String domainName = null;
   try {
     AttrSet domAttrSet;
     domainName = getCanonicalDomain(token, orgDN);
     if (domainName == null) {
       debug.error("DCTree.getDomainAttributes-> " + "Domain not found for:  " + orgDN);
       return null;
     }
     DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
     DomainComponent dcNode = dcTree.getDomainComponent(domainName);
     if (attrNames != null) {
       domAttrSet = dcNode.getAttributes(attrNames);
     } else {
       domAttrSet = dcNode.getAttributes(dcNode.getAttributeNames());
     }
     AttrSet[] attrArray = splitAttrSet(null, domAttrSet);
     return attrArray[1];
   } catch (UMSException umse) {
     debug.error(
         "DCTree.getDomainAttributes: " + " error getting attributes for domain " + domainName);
   }
   return null;
 }
 private Set<String> getWithoutTranslations(String key, Set<String> cached)
     throws ServerException {
   if (cached != null) {
     return cached;
   }
   Set<String> claims = new HashSet<>();
   try {
     synchronized (attributeCache) {
       for (String claim : getSetting(realm, key)) {
         int pipe = claim.indexOf('|');
         if (pipe > -1) {
           claims.add(claim.substring(0, pipe));
         } else {
           claims.add(claim);
         }
       }
       return claims;
     }
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
  /** {@inheritDoc} */
  public Map<String, ResponseTypeHandler> getAllowedResponseTypes()
      throws UnsupportedResponseTypeException, ServerException {
    try {
      Set<String> responseTypeSet = getSetting(realm, OAuth2ProviderService.RESPONSE_TYPE_LIST);
      if (responseTypeSet == null || responseTypeSet.isEmpty()) {
        return Collections.emptyMap();
      }
      Map<String, ResponseTypeHandler> responseTypes = new HashMap<String, ResponseTypeHandler>();
      for (String responseType : responseTypeSet) {
        String[] parts = responseType.split("\\|");
        if (parts.length != 2) {
          logger.error("Response type wrong format for realm: " + realm);
          continue;
        }
        responseTypes.put(parts[0], wrap(parts[0], parts[1]));
      }
      return responseTypes;

    } catch (SMSException e) {
      logger.error(e.getMessage());
      throw new ServerException(e);
    } catch (SSOException e) {
      logger.error(e.getMessage());
      throw new ServerException(e);
    }
  }
  /**
   * Method which creates a <Code>Domain Component Tree </Code> for the given organization, if the
   * <code>sunPreferredDomain</code> attribute is present and has a fully qualified domain name as
   * value.
   *
   * @param token SSO Token
   * @param orgGuid identifiication of organization entry to be mapped from <Code>dctree</Code> to
   *     organization DIT organization
   * @param attrSet the attributes to be set on creation of domain.
   * @exception AMException if unsuccessful in creating a dc tree for the organization or
   *     unsuccessful in setting the mapping between dc tree and the organization
   */
  protected void createDomain(SSOToken token, Guid orgGuid, AttrSet attrSet)
      throws AMException, SSOException {
    if (DCTREE_START_DN == null) {
      throw new AMException(AMSDKBundle.getString("355"), "355");
    }

    // Create a DC tree is value is specified for
    // sunPreferredDomain attribute
    String domainName = attrSet.getValue(IPLANET_DOMAIN_NAME_ATTR);
    // remove the attribute from the attribute set.
    attrSet.remove(IPLANET_DOMAIN_NAME_ATTR);
    if ((domainName != null) && (domainName != "")) {
      try {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        dcTree.addDomain(domainName);
        // Set the domain mapping
        dcTree.setDomainMapping(domainName, orgGuid);
        String status = attrSet.getValue(INET_DOMAIN_STATUS_ATTR);
        if (status != null) {
          dcTree.setDomainStatus(domainName, status);
        }
        AttrSet[] attrSetArray = splitAttrSet(orgGuid.getDn(), attrSet);
        if (attrSetArray[1] != null) {
          setDomainAttributes(token, orgGuid.getDn(), attrSetArray[1]);
        }
      } catch (InvalidDCRootException ie) {
        debug.error("DCTree.createDomain(): ", ie);
        throw new AMException(AMSDKBundle.getString("343"), "343");
      } catch (UMSException ue) {
        debug.error("DCTree.createDomain(): ", ue);
        throw new AMException(AMSDKBundle.getString("344"), "344");
      }
    }
  }
  /** {@inheritDoc} */
  public AuthorizationCode readAuthorizationCode(OAuth2Request request, String code)
      throws InvalidGrantException, ServerException, NotFoundException {
    if (logger.messageEnabled()) {
      logger.message("Reading Authorization code: " + code);
    }
    final JsonValue token;

    // Read from CTS
    try {
      token = tokenStore.read(code);
    } catch (CoreTokenException e) {
      logger.error("Unable to read authorization code corresponding to id: " + code, e);
      throw new ServerException("Could not read token from CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read authorization code corresponding to id: " + code);
      throw new InvalidGrantException("The provided access grant is invalid, expired, or revoked.");
    }

    OpenAMAuthorizationCode authorizationCode = new OpenAMAuthorizationCode(token);
    validateTokenRealm(authorizationCode.getRealm(), request);

    request.setToken(AuthorizationCode.class, authorizationCode);
    return authorizationCode;
  }
Beispiel #11
0
  /**
   * Converts a JAXB object to a <code>org.w3c.dom.Element</code>.
   *
   * @param jaxbObj a JAXB object
   * @return a <code>org.w3c.dom.Element</code>
   * @throws JAXBException if an error occurs while converting JAXB object.
   * @supported.api
   */
  public static Element convertJAXBToElement(Object jaxbObj, boolean checkIdref)
      throws JAXBException {
    Marshaller m = jc.createMarshaller();
    try {
      m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());

    } catch (PropertyException ex) {
      debug.error("Utils.convertJAXBToElement", ex);
    }

    if (!checkIdref) {
      m.setEventHandler(
          new DefaultValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
              if (event instanceof NotIdentifiableEvent) {
                return true;
              }
              return super.handleEvent(event);
            }
          });
    }

    Document doc = null;
    try {
      doc = XMLUtils.newDocument();
    } catch (Exception ex) {
      debug.error("Utils.convertJAXBToElement:", ex);
    }
    m.marshal(jaxbObj, doc);
    return doc.getDocumentElement();
  }
 @Override
 public void updateRefreshToken(RefreshToken refreshToken) {
   try {
     deleteRefreshToken(refreshToken.getTokenId());
     tokenStore.create(refreshToken);
   } catch (CoreTokenException e) {
     logger.error(
         "DefaultOAuthTokenStoreImpl::Unable to create refresh token " + refreshToken.getTokenId(),
         e);
     throw new OAuthProblemException(
         Status.SERVER_ERROR_INTERNAL.getCode(),
         "Internal error",
         "Could not create token in CTS",
         null);
   } catch (InvalidRequestException e) {
     logger.error(
         "DefaultOAuthTokenStoreImpl::Unable to delete refresh token " + refreshToken.getTokenId(),
         e);
     throw new OAuthProblemException(
         Status.SERVER_ERROR_INTERNAL.getCode(),
         "Internal error",
         "Could not delete token in CTS",
         null);
   }
 }
Beispiel #13
0
  /**
   * Creates Organization within OpenAM
   *
   * @param ocm Organization Configuration Manager
   * @param jVal JSONvalue that contains the payload
   * @param realm Name of the realm to be created
   * @throws SMSException
   * @throws Exception
   */
  private void createOrganization(
      OrganizationConfigManager ocm, JsonValue jVal, String realm, String realmPath)
      throws Exception {

    Map defaultValues = null;
    OrganizationConfigManager realmCreatedOcm;
    if (realmPath != null && !realmPath.endsWith("/")) {
      realmPath = realmPath + "/";
    }
    try {
      JsonValue realmDetails = jVal;
      if (jVal != null) {
        defaultValues = createServicesMap(jVal);
      }
      ocm.createSubOrganization(realm, defaultValues);
      // Get the Organization Configuration Manager for the new Realm
      realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realmPath + realm);
      List newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
      if (newServiceNames != null && !newServiceNames.isEmpty()) {
        // assign services to realm
        assignServices(realmCreatedOcm, newServiceNames);
      }
    } catch (SMSException smse) {
      debug.error("RealmResource.createOrganization()", smse);
      throw smse;
    } catch (Exception e) {
      debug.error("RealmResource.createOrganization()", e);
      throw e;
    }
  }
  /** {@inheritDoc} */
  public AccessToken readAccessToken(OAuth2Request request, String tokenId)
      throws ServerException, InvalidGrantException, NotFoundException {

    logger.message("Reading access token");

    JsonValue token;

    // Read from CTS
    try {
      token = tokenStore.read(tokenId);
    } catch (CoreTokenException e) {
      logger.error("Unable to read access token corresponding to id: " + tokenId, e);
      throw new ServerException("Could not read token in CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read access token corresponding to id: " + tokenId);
      throw new InvalidGrantException("Could not read token in CTS");
    }

    OpenAMAccessToken accessToken = new OpenAMAccessToken(token);
    validateTokenRealm(accessToken.getRealm(), request);

    request.setToken(AccessToken.class, accessToken);
    return accessToken;
  }
Beispiel #15
0
  /** Log Logout status */
  public void logLogout(SSOToken ssot) {
    try {
      String logLogout = bundle.getString("logout");
      List dataList = new ArrayList();
      dataList.add(logLogout);
      StringBuilder messageId = new StringBuilder();
      messageId.append("LOGOUT");
      String indexType = ssot.getProperty(ISAuthConstants.INDEX_TYPE);
      if (indexType != null) {
        messageId.append("_").append(indexType.toString().toUpperCase());
        dataList.add(indexType.toString());
        if (indexType.equals(AuthContext.IndexType.USER.toString())) {
          dataList.add(ssot.getProperty(ISAuthConstants.PRINCIPAL));
        } else if (indexType.equals(AuthContext.IndexType.ROLE.toString())) {
          dataList.add(ssot.getProperty(ISAuthConstants.ROLE));
        } else if (indexType.equals(AuthContext.IndexType.SERVICE.toString())) {
          dataList.add(ssot.getProperty(ISAuthConstants.SERVICE));
        } else if (indexType.equals(AuthContext.IndexType.LEVEL.toString())) {
          dataList.add(ssot.getProperty(ISAuthConstants.AUTH_LEVEL));
        } else if (indexType.equals(AuthContext.IndexType.MODULE_INSTANCE.toString())) {
          dataList.add(ssot.getProperty(ISAuthConstants.AUTH_TYPE));
        }
      }

      Hashtable props = new Hashtable();
      String client = ssot.getProperty(ISAuthConstants.HOST);
      if (client != null) {
        props.put(LogConstants.IP_ADDR, client);
      }
      String userDN = ssot.getProperty(ISAuthConstants.PRINCIPAL);
      if (userDN != null) {
        props.put(LogConstants.LOGIN_ID, userDN);
      }
      String orgDN = ssot.getProperty(ISAuthConstants.ORGANIZATION);
      if (orgDN != null) {
        props.put(LogConstants.DOMAIN, orgDN);
      }
      String authMethName = ssot.getProperty(ISAuthConstants.AUTH_TYPE);
      if (authMethName != null) {
        props.put(LogConstants.MODULE_NAME, authMethName);
      }
      String contextId = null;
      contextId = ssot.getProperty(Constants.AM_CTX_ID);
      if (contextId != null) {
        props.put(LogConstants.CONTEXT_ID, contextId);
      }
      props.put(LogConstants.LOGIN_ID_SID, ssot.getTokenID().toString());

      String[] data = (String[]) dataList.toArray(new String[0]);
      this.logIt(data, this.LOG_ACCESS, messageId.toString(), props);
    } catch (SSOException ssoExp) {
      debug.error("AuthD.logLogout: SSO Error", ssoExp);
    } catch (Exception e) {
      debug.error("AuthD.logLogout: Error ", e);
    }
  }
 /** {@inheritDoc} */
 public boolean issueRefreshTokens() throws ServerException {
   try {
     return getBooleanSetting(realm, OAuth2ProviderService.ISSUE_REFRESH_TOKEN);
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
 private Set<String> getSettingStrings(String key) throws ServerException {
   try {
     return getSetting(realm, key);
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
 /** {@inheritDoc} */
 public KeyPair getServerKeyPair() throws ServerException {
   try {
     return getServerKeyPair(realm);
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
Beispiel #19
0
 private void createOAuth2Provider(
     SSOToken token, String realm, Map<String, Set<String>> attrValues) throws WorkflowException {
   try {
     new ServiceConfigManager(SERVICE_NAME, token).createOrganizationConfig(realm, attrValues);
   } catch (SMSException e) {
     DEBUG.error("An error occurred while trying to create the OAuth2 Provider.", e);
     throw new WorkflowException("oauth2.provider.create.error", null);
   } catch (SSOException e) {
     DEBUG.error("An error occurred while trying to create the OAuth2 Provider.", e);
     throw new WorkflowException("oauth2.provider.create.error", null);
   }
 }
  @Override
  public boolean getClaimsParameterSupported() throws ServerException {
    try {
      return getBooleanSetting(realm, OAuth2ProviderService.CLAIMS_PARAMETER_SUPPORTED);
    } catch (SSOException e) {
      logger.error(e.getMessage());
      throw new ServerException(e);
    } catch (SMSException e) {
      logger.error(e.getMessage());
    }

    return false;
  }
Beispiel #21
0
  /**
   * Returns names of all realms included in the subtree rooted by the realm indicated in the query
   * url.
   *
   * <p>Names are unsorted and given as full paths.
   *
   * <p>Filtering, sorting, and paging of results is not supported.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public void queryCollection(
      final ServerContext context, final QueryRequest request, final QueryResultHandler handler) {

    final String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
    final RealmContext realmContext = context.asContext(RealmContext.class);
    final String realmPath = realmContext.getResolvedRealm();

    try {

      final SSOTokenManager mgr = SSOTokenManager.getInstance();
      final SSOToken ssoToken = mgr.createSSOToken(getCookieFromServerContext(context));

      final OrganizationConfigManager ocm = new OrganizationConfigManager(ssoToken, realmPath);
      final List<String> realmsInSubTree = new ArrayList<String>();
      realmsInSubTree.add(realmPath);
      for (final Object subRealmRelativePath : ocm.getSubOrganizationNames("*", true)) {
        if (realmPath.endsWith("/")) {
          realmsInSubTree.add(realmPath + subRealmRelativePath);
        } else {
          realmsInSubTree.add(realmPath + "/" + subRealmRelativePath);
        }
      }

      debug.message("RealmResource :: QUERY : performed by " + principalName);

      for (final Object realmName : realmsInSubTree) {
        JsonValue val = new JsonValue(realmName);
        Resource resource = new Resource((String) realmName, "0", val);
        handler.handleResource(resource);
      }
      handler.handleResult(new QueryResult());

    } catch (SSOException ex) {
      debug.error("RealmResource :: QUERY by " + principalName + " failed : " + ex);
      handler.handleError(ResourceException.getException(ResourceException.FORBIDDEN));

    } catch (SMSException ex) {
      debug.error("RealmResource :: QUERY by " + principalName + " failed :" + ex);
      switch (ex.getExceptionCode()) {
        case STATUS_NO_PERMISSION:
          // This exception will be thrown if permission to read realms from SMS has not been
          // delegated
          handler.handleError(ResourceException.getException(ResourceException.FORBIDDEN));
          break;
        default:
          handler.handleError(ResourceException.getException(ResourceException.INTERNAL_ERROR));
          break;
      }
    }
  }
  /**
   * Constructs an instance for the cluster service
   *
   * @param localServerId id of the server instance in which this ClusterStateService instance is
   *     running
   * @param timeout timeout for waiting on an individual server (millisec)
   * @param period checking cycle period (millisecs)
   * @param members map if server id - > url for all cluster members
   * @throws Exception
   */
  protected ClusterStateService(
      SessionService sessionService,
      String localServerId,
      int timeout,
      long period,
      Map<String, String> members)
      throws Exception {
    if ((localServerId == null) || (localServerId.isEmpty())) {
      String message =
          "ClusterStateService: Local Server Id argument is null, unable to instantiate Cluster State Service!";
      sessionDebug.error(message);
      throw new IllegalArgumentException(message);
    }
    // Ensure we Synchronize this Instantiation.
    synchronized (this) {
      this.sessionService = sessionService;
      this.localServerId = localServerId;
      this.timeout = timeout;
      this.period = period;
      serverSelectionList = new ServerInfo[members.size()];

      for (Map.Entry<String, String> entry : members.entrySet()) {
        ServerInfo info = new ServerInfo();
        info.id = entry.getKey();
        URL url = new URL(entry.getValue() + "/namingservice");
        info.url = url;
        info.protocol = url.getProtocol();
        info.address = new InetSocketAddress(url.getHost(), url.getPort());
        // Fix for Deadlock. If this is our server, set to true, else false.
        info.isUp = isLocalServerId(info.id);
        info.isLocal = info.isUp; // Set our Local Server Indicator, per above interrogation.

        // Check for Down Servers.
        if (!info.isUp) {
          downServers.add(info.id);
        }

        // Add Server to Server List.
        servers.put(info.id, info);
        // Associate to a Server Selection Bucket.
        serverSelectionList[getNextSelected()] = info;
        if (sessionDebug.messageEnabled()) {
          sessionDebug.error("Added Server to ClusterStateService: " + info.toString());
        }
      } // End of For Loop.

      // to ensure that ordering in different server instances is identical
      Arrays.sort(serverSelectionList);
      SystemTimer.getTimer().schedule(this, new Date((System.currentTimeMillis() / 1000) * 1000));
    } // End of Synchronized Block.
  }
  /** {@inheritDoc} */
  public void deleteAuthorizationCode(String authorizationCode) {
    if (logger.messageEnabled()) {
      logger.message(
          "DefaultOAuthTokenStoreImpl::Deleting Authorization code: " + authorizationCode);
    }
    JsonValue oAuthToken;

    // Read from CTS
    try {
      oAuthToken = tokenStore.read(authorizationCode);
    } catch (CoreTokenException e) {
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to read authorization code corresponding to id: "
              + authorizationCode,
          e);
      throw new OAuthProblemException(
          Status.SERVER_ERROR_INTERNAL.getCode(),
          "Internal error",
          "Could not read token from CTS: " + e.getMessage(),
          null);
    }

    if (oAuthToken == null) {
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to read authorization code corresponding to id: "
              + authorizationCode);
      throw new OAuthProblemException(
          Status.CLIENT_ERROR_NOT_FOUND.getCode(),
          "Not found",
          "Could not find token using CTS",
          null);
    }

    // Delete the code
    try {
      tokenStore.delete(authorizationCode);
    } catch (CoreTokenException e) {
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to delete authorization code corresponding to id: "
              + authorizationCode,
          e);
      throw new OAuthProblemException(
          Status.SERVER_ERROR_INTERNAL.getCode(),
          "Internal error",
          "Could not delete token from CTS: " + e.getMessage(),
          null);
    }
  }
Beispiel #24
0
 /** Removes host:port from OpenDJ replication */
 public static void delOpenDSServer(LDAPConnection lc, String delServer) {
   String replServerDN = "cn=" + delServer + ",cn=Servers,cn=admin data";
   final String[] attrs = {"ds-cfg-key-id"};
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   if (lc == null) {
     debug.error(
         "EmbeddedOpenDS:syncOpenDSServer():"
             + "Could not connect to local OpenDJ instance."
             + replServerDN);
     return;
   }
   String trustKey = null;
   try {
     LDAPEntry le = lc.read(replServerDN, attrs);
     if (le != null) {
       LDAPAttribute la = le.getAttribute(attrs[0]);
       if (la != null) {
         Enumeration en = la.getStringValues();
         if (en != null && en.hasMoreElements()) {
           trustKey = (String) en.nextElement();
         }
       }
       String keyDN = "ds-cfg-key-id=" + trustKey + ",cn=instance keys,cn=admin data";
       lc.delete(keyDN);
     } else {
       debug.error(
           "EmbeddedOpenDS:syncOpenDSServer():" + "Could not find trustkey for:" + replServerDN);
     }
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting replication key:", ex);
   }
   try {
     lc.delete(replServerDN);
   } catch (Exception ex) {
     debug.error(
         "EmbeddedOpenDS.syncOpenDSServer()."
             + " Error getting deleting server entry:"
             + replServerDN,
         ex);
   }
   try {
     LDAPAttribute attr = new LDAPAttribute("uniqueMember", "cn=" + delServer);
     LDAPModification mod = new LDAPModification(LDAPModification.DELETE, attr);
     lc.modify(replDN, mod);
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting removing :" + replDN, ex);
   }
 }
Beispiel #25
0
  /**
   * Removes all the SMS cached entries. This method should be called to clear the cache for
   * example, if ACIs for the SMS entries are changed in the directory. Also, this clears the SMS
   * entries only in this JVM instance. If multiple instances (of JVM) are running this method must
   * be called within each instance.
   *
   * @supported.api
   */
  public synchronized void clearCache() {
    // Clear the local caches
    serviceNameAndOCs = new CaseInsensitiveHashMap();
    serviceVersions = new CaseInsensitiveHashMap();
    serviceNameDefaultVersion = new CaseInsensitiveHashMap();
    accessManagerServers = null;
    amsdkChecked = false;

    // Call respective Impl classes
    CachedSMSEntry.clearCache();
    CachedSubEntries.clearCache();
    ServiceSchemaManagerImpl.clearCache();
    PluginSchemaImpl.clearCache();
    ServiceInstanceImpl.clearCache();
    ServiceConfigImpl.clearCache();
    ServiceConfigManagerImpl.clearCache();
    OrganizationConfigManagerImpl.clearCache();
    OrgConfigViaAMSDK.clearCache();

    // Re-initialize the flags
    try {
      checkFlags(token);
      OrganizationConfigManager.initializeFlags();
      DNMapper.clearCache();
    } catch (Exception e) {
      debug.error("ServiceManager::clearCache unable to " + "re-initialize global flags", e);
    }
  }
  /** {@inheritDoc} */
  public void updateAuthorizationCode(AuthorizationCode authorizationCode) {
    deleteAuthorizationCode(authorizationCode.getTokenId());

    // Store in CTS
    try {
      tokenStore.create(authorizationCode);
      if (auditLogger.isAuditLogEnabled()) {
        String[] obs = {"UPDATED_AUTHORIZATION_CODE", authorizationCode.toString()};
        auditLogger.logAccessMessage("CREATED_AUTHORIZATION_CODE", obs, null);
      }
    } catch (CoreTokenException e) {
      if (auditLogger.isAuditLogEnabled()) {
        String[] obs = {"FAILED_UPDATE_AUTHORIZATION_CODE", authorizationCode.toString()};
        auditLogger.logErrorMessage("FAILED_UPDATE_AUTHORIZATION_CODE", obs, null);
      }
      logger.error(
          "DefaultOAuthTokenStoreImpl::Unable to create authorization code "
              + authorizationCode.getTokenInfo(),
          e);
      throw new OAuthProblemException(
          Status.SERVER_ERROR_INTERNAL.getCode(),
          "Internal error",
          "Could not create token in CTS",
          null);
    }
  }
Beispiel #27
0
  public static int rebuildIndex(Map map) throws Exception {
    int ret = 0;
    shutdownServer("Rebuild index");
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);

    String[] args = {
      "--configClass",
      "org.opends.server.extensions.ConfigFileHandler",
      "--configFile",
      getOpenDJConfigFile(map),
      "--baseDN",
      (String) map.get(SetupConstants.CONFIG_VAR_ROOT_SUFFIX),
      "--rebuildAll"
    };
    OutputStream bos = new ByteArrayOutputStream();
    OutputStream boe = new ByteArrayOutputStream();
    TimeThread.start();
    ret = RebuildIndex.mainRebuildIndex(args, true, bos, boe);
    TimeThread.stop();
    String outStr = bos.toString();
    String errStr = boe.toString();
    if (errStr.length() != 0) {
      debug.error("EmbeddedOpenDS:rebuildIndex:stderr=" + errStr);
    }
    if (debug.messageEnabled()) {
      String msg = "msg=Rebuild complete.";
      int idx = outStr.indexOf(msg);
      if (idx >= 0) {
        debug.message("EmbeddedOpenDS:rebuildIndex: " + "Rebuild Status: " + outStr.substring(idx));
      }
      debug.message("EmbeddedOpenDS:rebuildIndex:Result:" + outStr);
    }
    startServer(getOpenDJBaseDir(map));
    return ret;
  }
Beispiel #28
0
 static {
   try {
     saml2MetaManager = new SAML2MetaManager();
   } catch (SAML2MetaException sme) {
     debug.error("Error retreiving metadata", sme);
   }
 }
Beispiel #29
0
  /**
   * Verify the signature in <code>Response</code>.
   *
   * @param pepEntityID entity identifier of PEP.
   * @param pdpEntityID entity identifier of PDP.
   * @param response <code>Response</code> to be verified
   * @return true if signature is valid.
   * @throws <code>SAML2Exception</code> if error in verifying the signature.
   */
  public static boolean verifySignedResponse(
      String pepEntityID, String pdpEntityID, Response response) throws SAML2Exception {
    String classMethod = "QueryClient:verifySignedResponse: ";

    String realm = "/";
    XACMLAuthzDecisionQueryConfigElement pepConfig = getPEPConfig(realm, pepEntityID);

    String wantResponseSigned =
        getAttributeValueFromPEPConfig(pepConfig, "wantXACMLAuthzDecisionResponseSigned");

    boolean valid = false;
    if (wantResponseSigned != null && wantResponseSigned.equalsIgnoreCase("true")) {
      XACMLPDPDescriptorElement pdpDescriptor =
          saml2MetaManager.getPolicyDecisionPointDescriptor(null, pdpEntityID);
      X509Certificate signingCert = KeyUtil.getPDPVerificationCert(pdpDescriptor, pdpEntityID);
      if (signingCert != null) {
        valid = response.isSignatureValid(signingCert);
        if (debug.messageEnabled()) {
          debug.message(classMethod + "Signature is valid :" + valid);
        }
      } else {
        debug.error(classMethod + "Incorrect configuration for Signing Certificate.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
      }
    } else {
      if (debug.messageEnabled()) {
        debug.message(classMethod + "Response doesn't need to be verified.");
      }
      valid = true;
    }
    return valid;
  }
Beispiel #30
0
  static void initialize(SSOToken token) throws SMSException, SSOException {
    // Validate SSOToken
    SMSEntry.validateToken(token);

    // Check if already initialized
    if (initialized) return;
    // Initilaize the parameters
    try {
      // Get the service names and cache it
      serviceNames = CachedSubEntries.getInstance(token, serviceDN);
      if (serviceNames.getSMSEntry().isNewEntry()) {
        if (debug.warningEnabled()) {
          debug.warning("SeviceManager:: Root service node " + "does not exists: " + serviceDN);
        }
        String[] msgs = new String[1];
        msgs[0] = serviceDN;
        throw (new SMSException(
            IUMSConstants.UMS_BUNDLE_NAME, IUMSConstants.SMS_services_node_does_not_exist, msgs));
      }
    } catch (SMSException e) {
      debug.error("ServiceManager::unable to get " + "services node: " + serviceDN, e);
      throw (e);
    }
    // Check if realm is enabled and set appropriate flags
    checkFlags(token);
    initialized = true;
  }