Esempio n. 1
0
  /**
   * Method which removes the DC Tree corresponding to the Org
   *
   * @param token SSOToken
   * @param orgDN String representing the DN correponding to the organization
   * @exception AMException if error occured in accessing the org corresponding to orgDN or during
   *     the removal of the dc tree corresponding to the orgDN
   */
  protected void removeDomain(SSOToken token, String orgDN) throws AMException {

    // String orgAttribute[] = {IPLANET_DOMAIN_NAME_ATTR};
    try {
      PersistentObject po = UMSObject.getObject(token, new Guid(orgDN));
      if (!(po instanceof com.iplanet.ums.Organization)) {
        if (debug.messageEnabled()) {
          debug.message("DCTree.removeDomain-> " + orgDN + " is not an organization");
        }
        return;
      }
      String domainName = getCanonicalDomain(token, orgDN);
      if (debug.messageEnabled()) {
        debug.message("DCTree.removeDomain-> " + "Obtained canon domain " + domainName);
      }
      if ((domainName != null) && (domainName.length() > 0)) {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        if (debug.messageEnabled()) {
          debug.message("DCTree.removeDomain: removing domain: " + domainName);
        }
        dcTree.removeDomain(domainName);
      } else {
        if (debug.warningEnabled()) {
          debug.warning("DCTree.removeDomain(): " + " unable to get domain for " + orgDN);
        }
      }
    } catch (UMSException ue) {
      if (debug.warningEnabled()) {
        debug.warning("DCTree.removeDomain(): ", ue);
      }
    }
  }
Esempio n. 2
0
  /**
   * Constructs a ThreadPoolConfig.
   *
   * @param core -the core number of threads required.
   * @param max - the max number of threads to be used by the thread pool
   * @param queueSize - the size of the queue
   * @param keepAliveSeconds - when the number of threads is greater than the core, this is the
   *     maximum time that excess idle threads will wait for new tasks before terminating.
   */
  public ThreadPoolConfig(int core, int max, int queueSize, int keepAliveSeconds) {
    if (core < 2) {
      this.coreThreads = defaultCoreThreads;
      logger.warning(
          "System configured to used invalid Radius Thread Pool Core size of "
              + core
              + ". Using the value of "
              + defaultCoreThreads
              + " instead.");
    } else {
      this.coreThreads = core;
    }

    if (max < this.coreThreads) {
      this.maxThreads = coreThreads;
      logger.warning(
          "System configured to use Radius Server 'Thread Pool Max Size' that is less than 'Thread "
              + "Pool Core Size. Using size equal to Core Size - i.e. a static pool of size "
              + coreThreads);
    } else {
      this.maxThreads = max;
    }

    if (queueSize < 1 || queueSize > 1000) {
      this.queueSize = defaultQueueSize;
      logger.warning(
          "System configured to use an invalid Radius Server 'Thread Pool Queue Size' value of '"
              + queueSize
              + "'. Using the default value of '"
              + defaultQueueSize
              + "' instead.");
    } else {
      this.queueSize = queueSize;
    }

    if (keepAliveSeconds < 1 || keepAliveSeconds > 3600) {
      this.keepAliveSeconds = defaultKeepAliveSeconds;
      logger.warning(
          "System configured to use an invalid Radius Server 'Thread Pool Keep-Alive Seconds' value of"
              + " '"
              + keepAliveSeconds
              + "'. Using the default value of '"
              + defaultKeepAliveSeconds
              + "' instead.");
    } else {
      this.keepAliveSeconds = keepAliveSeconds;
    }
  }
  /** {@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;
  }
Esempio n. 4
0
 /**
  * This method parses out the local_attribute=source_attributes as they are encapsulated in the
  * authN module configurations into a more usable, Map<String, String> format.
  *
  * @param configuredMappings The set of local=source mappings.
  * @return The derived Map instance.
  */
 public static Map<String, String> parseMappings(Set<String> configuredMappings) {
   Map<String, String> parsedMappings = new HashMap<String, String>();
   for (String mapping : configuredMappings) {
     if (mapping.indexOf(EQUALS) == -1) {
       continue;
     }
     StringTokenizer tokenizer = new StringTokenizer(mapping, EQUALS);
     final String key = tokenizer.nextToken();
     final String value = tokenizer.nextToken();
     /*
     The ldap_attr=spource_attr mapping is user-generated, so I want to warn about duplicate entries. In a
     HashMap, repeated insertion of the same key will over-write previous entries, but I want to warn about
     duplicate entries, and will persist the first entry.
      */
     if (!parsedMappings.containsKey(key)) {
       parsedMappings.put(key, value);
     } else {
       if (debug.warningEnabled()) {
         debug.warning(
             "In MappingUtils.parseMappings, the user-entered attribute mappings contain "
                 + "duplicate entries. The first entry will be preserved: "
                 + configuredMappings);
       }
     }
   }
   if (parsedMappings.isEmpty()) {
     throw new IllegalArgumentException(
         "The mapping Set does not contain any mappings in format "
             + "local_attribute=source_attribute.");
   }
   return Collections.unmodifiableMap(parsedMappings);
 }
 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();
 }
  private ResponseTypeHandler wrap(String responseTypeName, String responseTypeHandlerClassName)
      throws UnsupportedResponseTypeException {

    if (responseTypeHandlerClassName == null || responseTypeHandlerClassName.isEmpty()) {
      logger.warning(
          "Requested a response type that is not configured. response_type=" + responseTypeName);
      throw new UnsupportedResponseTypeException("Response type is not supported");
    } else if (responseTypeHandlerClassName.equalsIgnoreCase("none")) {
      return new NoneResponseTypeHandler();
    }
    try {
      final Class<?> responseTypeHandlerClass = Class.forName(responseTypeHandlerClassName);
      if (ResponseType.class.isAssignableFrom(responseTypeHandlerClass)) {
        ResponseType responseType =
            InjectorHolder.getInstance(responseTypeHandlerClass.asSubclass(ResponseType.class));
        return new LegacyResponseTypeHandler(
            responseType, realm, getSSOCookieName(), cookieExtractor);
      }

      return InjectorHolder.getInstance(
          responseTypeHandlerClass.asSubclass(ResponseTypeHandler.class));

    } catch (ClassNotFoundException e) {
      logger.error(e.getMessage());
      throw new UnsupportedResponseTypeException("Response type is not supported");
    }
  }
Esempio n. 7
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;
  }
Esempio n. 8
0
 /**
  * removes the listener from the list of Persistent Search listeners of the asynchronous seach for
  * the given search ID.
  *
  * @param request The request returned by the addListener
  * @supported.api
  */
 protected void removeListener(Request request) {
   LDAPConnection connection = request.getLDAPConnection();
   if (connection != null) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.removeListener(): Removing "
               + "listener requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener());
     }
     try {
       if ((connection != null) && (connection.isConnected())) {
         connection.abandon(request.getId());
         connection.disconnect();
       }
     } catch (LDAPException le) {
       // Might have to check the reset codes and try to reset
       if (debugger.warningEnabled()) {
         debugger.warning(
             "EventService.removeListener(): " + "LDAPException, when trying to remove listener",
             le);
       }
     }
   }
 }
 private void populateContextFromTokenId(String tokenId) {
   try {
     SSOToken token = SSOTokenManager.getInstance().createSSOToken(tokenId);
     AuditRequestContext.putProperty(USER_ID, getUserId(token));
     AuditRequestContext.putProperty(SESSION.toString(), getContextFromSSOToken(token));
   } catch (SSOException e) {
     debug.warning("No SSO Token found when trying to audit an authentication request.");
   }
 }
 private static String getSSOTokenProperty(SSOToken ssoToken, String name, String defaultValue) {
   if (ssoToken != null) {
     try {
       return ssoToken.getProperty(name);
     } catch (SSOException e) {
       debug.warning("Unable to obtain property '{}' from SSOToken.", name, e);
     }
   }
   return defaultValue;
 }
Esempio n. 11
0
 /**
  * Returns connection for AM store. Only used for backward compatibilty support, for retrieving
  * user container DN and usernaming attr.
  *
  * @return connection for AM store
  */
 public AMStoreConnection getSDK() {
   if (dpStore == null) {
     try {
       dpStore = new AMStoreConnection(ssoAuthSession);
     } catch (SSOException e) {
       debug.warning("AuthD.getSDK", e);
     }
   }
   return dpStore;
 }
Esempio n. 12
0
 /**
  * Returns localized string.
  *
  * @param key resource string key.
  * @return localized string.
  */
 public String getLocalizedString(String key) {
   String i18nString = key;
   try {
     ResourceBundle rb =
         PPResetResBundleCacher.getBundle("amPasswordResetModuleMsgs", getLoginLocale());
     i18nString = rb.getString(key);
   } catch (MissingResourceException e) {
     debug.warning("Error loading resource bundle: ", e);
   }
   return i18nString;
 }
 /**
  * Adds Compliance Mode Filters to the original filter if running in Compliance mode. The addition
  * of filters can be by-passed by setting the ignoreComplianceFilter to true.
  */
 private static String addComplianceModeFilters(
     String originalFilter, int objectType, boolean ignoreComplianceFilter) {
   try {
     // Modify search filters if complaince user deletion enabled
     // Ignore if explicitly specified.
     String modifiedFilter = originalFilter;
     if (!ignoreComplianceFilter && AMCompliance.isComplianceUserDeletionEnabled()) {
       StringBuilder sb = new StringBuilder();
       switch (objectType) {
         case AMObject.USER:
           sb.append("(&").append(originalFilter);
           sb.append("(!(inetuserstatus=deleted)))");
           modifiedFilter = sb.toString();
           break;
         case AMObject.ORGANIZATION:
           sb.append("(&").append(originalFilter);
           sb.append("(!(inetdomainstatus=deleted)))");
           modifiedFilter = sb.toString();
           break;
         case AMObject.STATIC_GROUP:
         case AMObject.DYNAMIC_GROUP:
         case AMObject.ASSIGNABLE_DYNAMIC_GROUP:
         case AMObject.GROUP:
           sb.append("(&").append(originalFilter);
           sb.append("(!(inetgroupstatus=deleted)))");
           modifiedFilter = sb.toString();
           break;
       }
       if (debug.messageEnabled()) {
         debug.message(
             "AMSearchFilterManager."
                 + ""
                 + "addComplainceModeFilters() - objectType = "
                 + objectType
                 + ", Original Filter = "
                 + originalFilter
                 + ", Modified Filter = "
                 + modifiedFilter);
       }
       return modifiedFilter;
     }
   } catch (AMException ae) {
     if (debug.warningEnabled()) {
       debug.warning(
           "AMSearchFilterManager."
               + "addComplianceModeFilters() Unable to determine if "
               + "\"User Compliance deletion mode\" is enabled or "
               + "disabled. Exception : ",
           ae);
     }
   }
   return originalFilter;
 }
 private String getAuthModulesFromSSOToken(OAuth2Request request) {
   String authModules = null;
   try {
     SSOToken token =
         ssoTokenManager.createSSOToken(ServletUtils.getRequest(request.<Request>getRequest()));
     if (token != null) {
       authModules = token.getProperty(ISAuthConstants.AUTH_TYPE);
     }
   } catch (SSOException e) {
     logger.warning("Could not get list of auth modules from authentication", e);
   }
   return authModules;
 }
Esempio n. 15
0
  /**
   * Returns the attribute value configured in the given entity SP or IDP configuration.
   *
   * @param realm realm name.
   * @param entityID hosted <code>EntityID</code>.
   * @param attributeName name of the attribute.
   */
  protected String getAttribute(String realm, String entityID, String attributeName) {

    if (realm == null || entityID == null || attributeName == null) {
      if (debug.messageEnabled()) {
        debug.message("DefaultAccountMapper.getAttribute: " + "null input parameters.");
      }
      return null;
    }

    try {
      BaseConfigType config = null;
      if (role.equals(IDP)) {
        config = WSFederationUtils.getMetaManager().getIDPSSOConfig(realm, entityID);
      } else {
        config = WSFederationUtils.getMetaManager().getSPSSOConfig(realm, entityID);
      }
      Map attributes = WSFederationMetaUtils.getAttributes(config);

      if (attributes == null || attributes.isEmpty()) {
        if (debug.messageEnabled()) {
          debug.message(
              "DefaultAccountMapper.getAttribute:"
                  + " attribute configuration is not defined for "
                  + "Entity "
                  + entityID
                  + " realm ="
                  + realm
                  + " role="
                  + role);
        }
        return null;
      }

      List list = (List) attributes.get(attributeName);
      if (list != null && list.size() > 0) {
        return (String) list.iterator().next();
      }

      if (debug.messageEnabled()) {
        debug.message(
            "DefaultSPAccountMapper.getAttribute: " + attributeName + " is not configured.");
      }
      return null;

    } catch (WSFederationMetaException sme) {
      if (debug.warningEnabled()) {
        debug.warning("DefaultSPAccountMapper.getAttribute:" + "Meta Exception", sme);
      }
    }
    return null;
  }
Esempio n. 16
0
 /**
  * Returns all AM Server instance. Read the configured servers from platform service's <code>
  * iplanet-am-platform-server-list</code>
  */
 public static Set getAMServerInstances() {
   // Check cache
   if (accessManagerServers == null) {
     // Get AdminToken
     try {
       SSOToken token = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
       accessManagerServers = ServerConfiguration.getServers(token);
       if (debug.messageEnabled()) {
         debug.message(
             "ServiceManager.getAMServerInstances: " + "server list: " + accessManagerServers);
       }
     } catch (SMSException e) {
       if (debug.warningEnabled()) {
         debug.warning("ServiceManager.getAMServerInstances: " + "Unable to get server list", e);
       }
     } catch (SSOException e) {
       if (debug.warningEnabled()) {
         debug.warning("ServiceManager.getAMServerInstances: " + "Unable to get server list", e);
       }
     }
   }
   return (accessManagerServers == null ? new HashSet() : new HashSet(accessManagerServers));
 }
  private void populateContextFromAuthId(String authId) {
    try {
      String sessionId =
          authIdHelper.reconstructAuthId(authId).getClaimsSet().getClaim(SESSION_ID, String.class);
      if (isEmpty(sessionId)) {
        return;
      }

      String contextId = getContextIdFromSessionId(sessionId);
      if (isNotEmpty(contextId)) {
        AuditRequestContext.putProperty(AUTH.toString(), contextId);
      }
    } catch (RestAuthException e) {
      debug.warning("No session ID found when trying to audit an authentication request.");
    }
  }
  protected void setValues(String value) {
    try {
      URL url = new URL(value);
      propertySheetModel.setValue(ATTR_PROTOCOL, url.getProtocol());
      propertySheetModel.setValue(ATTR_TARGET, url.getHost());
      propertySheetModel.setValue(ATTR_PATH, url.getPath());
      int port = url.getPort();

      if (port == -1) {
        propertySheetModel.setValue(ATTR_PORT, "");
      } else {
        propertySheetModel.setValue(ATTR_PORT, Integer.toString(port));
      }
    } catch (MalformedURLException e) {
      debug.warning("FSSAMLTargetURLsViewBeanBase.setValues", e);
    }
  }
  /** Adds filters to eliminate admin groups if the Admin Group option is not enabled. */
  private static String addAdminGroupFilters(String originalFilter, String orgDN, int objectType) {
    try {
      // Filter out Admin Groups if the option is NOT enabled
      if (!AMCompliance.isAdminGroupsEnabled(orgDN)) {
        String modifiedFilter = originalFilter;
        switch (objectType) {
          case AMObject.STATIC_GROUP:
          case AMObject.DYNAMIC_GROUP:
          case AMObject.ASSIGNABLE_DYNAMIC_GROUP:
          case AMObject.GROUP:
            StringBuilder sb = new StringBuilder();
            sb.append("(&").append(originalFilter).append("(!(");
            sb.append(AMNamingAttrManager.getNamingAttr(AMObject.ASSIGNABLE_DYNAMIC_GROUP));
            sb.append("=serviceadministrators))").append("(!(");
            sb.append(AMNamingAttrManager.getNamingAttr(AMObject.ASSIGNABLE_DYNAMIC_GROUP));
            sb.append("=servicehelpdeskadministrators)))");
            modifiedFilter = sb.toString();
        }

        if (debug.messageEnabled()) {
          debug.message(
              "AMSearchFilterManager."
                  + "addAdminGroupFilters() - objectType = "
                  + objectType
                  + ", orgDN = "
                  + orgDN
                  + ", Original filter: "
                  + originalFilter
                  + ", Modified filter = "
                  + modifiedFilter);
        }
        return modifiedFilter;
      }
    } catch (AMException ae) {
      if (debug.warningEnabled()) {
        debug.warning(
            "AMSearchFilterManager.addAdminGroupFilters() "
                + "Unable to determine if \"Admin Groups\" "
                + "option is enabled or disabled. Exception : ",
            ae);
      }
    }
    return originalFilter;
  }
Esempio n. 20
0
  public static String getOpenDSVersion() {
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    String odsRoot = AMSetupServlet.getBaseDir() + "/" + SetupConstants.SMS_OPENDS_DATASTORE;
    String version = "unknown";

    File configLdif = new File(odsRoot + OPENDS_UPGRADE_DIR);

    File buildInfo = new File(odsRoot + "/" + "config" + "/" + SetupConstants.OPENDJ_BUILDINFO);

    if (configLdif.exists() && configLdif.isDirectory()) {
      String[] configFile =
          configLdif.list(
              new FilenameFilter() {
                // @Override -- Not Allowed Here.
                public boolean accept(File dir, String name) {
                  return name.startsWith(OPENDS_CONFIG_LDIF);
                }
              });

      if (configFile.length != 0) {
        version = configFile[0].substring(configFile[0].lastIndexOf('.') + 1);
      } else {
        debug.error("Unable to determine OpenDJ version");
      }
    } else if (buildInfo.exists() && buildInfo.canRead() && buildInfo.isFile()) {
      String buildInfoVersionText = getOpenDJBuildInfo(buildInfo);
      if ((buildInfoVersionText != null) && (!buildInfoVersionText.isEmpty())) {
        version = buildInfoVersionText.trim();
      } else {
        debug.error("Unable to determine OpenDJ version");
      }
    } else {
      if (debug.warningEnabled()) {
        debug.warning("Unable to determine OpenDJ version; could be pre-config");
      }
    }

    if (debug.messageEnabled()) {
      debug.message("Found OpenDJ version: " + version);
    }

    return version;
  }
Esempio n. 21
0
 /**
  * Method which update attribute inetdomainstatus of the DC Tree corresponding to the Org
  *
  * @param token SSOToken
  * @param orgDN String representing the DN correponding to the organization
  * @param status inetdomainstatus value
  * @exception AMException if error occured in accessing the org corresponding to orgDN or during
  *     the attribute change of the dc tree corresponding to the orgDN
  */
 protected void updateDomainStatus(SSOToken token, String orgDN, String status)
     throws AMException {
   try {
     String domainName = getCanonicalDomain(token, orgDN);
     if ((domainName != null) && (domainName.length() > 0)) {
       DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
       dcTree.setDomainStatus(domainName, status);
     } else {
       debug.warning(
           "DCTree.updateDomainStatus(): value for "
               + IPLANET_DOMAIN_NAME_ATTR
               + " attribute "
               + "null or empty");
     }
     // }
   } catch (UMSException ue) {
     debug.error("DCTree.removeDomain(): ", ue);
     throw new AMException(AMSDKBundle.getString("356"), "356");
   }
 }
Esempio n. 22
0
  /**
   * Helper function to retrieve a field from the provided request's query parameters. This exists
   * for the old-style interfaces, and takes the parameter name as an argument also.
   *
   * <p>If the queryParameters contain the "encoded" parameter, then the result is Base64 decoded
   * before being returned.
   *
   * @param request Request containing the parameters to retrieve.
   * @param paramName The name of the parameter whose value to (possibly decode) return.
   * @return The (possibly decoded) value of the paramName's key within the requests's query
   *     parameters.
   */
  public String getAndDecodeParameter(HttpServletRequest request, String paramName) {
    String value = request.getParameter(paramName);

    if (value == null) {
      return null;
    }

    String encoded = request.getParameter("encoded");
    if (Boolean.parseBoolean(encoded)) {
      String decodedParameterValue = Base64.decodeAsUTF8String(value);
      if (decodedParameterValue == null && DEBUG.warningEnabled()) {
        DEBUG.warning(
            "As parameter 'encoded' is true, parameter ['{}']='{}' should be base64 encoded",
            paramName,
            value);
      }
      return decodedParameterValue;

    } else {
      return value;
    }
  }
Esempio n. 23
0
  /** Pushes off to our logging subsystem. */
  private void logAccess(String resource, String operation, ServerContext context) {

    if (!context.containsContext(SSOTokenContext.class)) {
      context = new SSOTokenContext(context);
    }

    SSOTokenContext ssoTokenContext = context.asContext(SSOTokenContext.class);

    try {
      restLog.auditAccessMessage(resource, operation, ssoTokenContext.getCallerSSOToken());
    } catch (SSOException e) {
      if (debug.warningEnabled()) {
        debug.warning(
            "LoggingFluentRouter :: "
                + "Error retrieving SSO Token from provided context, forced to log user as 'null'.",
            e);
        restLog.auditAccessMessage(resource, operation, null);
      }
    }

    restLog.debugOperationAttemptAsPrincipal(resource, operation, context, null, debug);
  }
Esempio n. 24
0
  private static int getPropertyIntValue(String key, int defaultValue) {
    int value = defaultValue;
    String valueStr = SystemProperties.get(key);
    if (valueStr != null && valueStr.trim().length() > 0) {
      try {
        value = Integer.parseInt(valueStr);
      } catch (NumberFormatException e) {
        value = defaultValue;
        if (debugger.warningEnabled()) {
          debugger.warning(
              "EventService.getPropertyIntValue(): "
                  + "Invalid value for property: "
                  + EVENT_CONNECTION_NUM_RETRIES
                  + " Defaulting to value: "
                  + defaultValue);
        }
      }
    }

    if (debugger.messageEnabled()) {
      debugger.message("EventService.getPropertyIntValue(): " + key + " = " + value);
    }
    return value;
  }
Esempio n. 25
0
  /**
   * Performs the Login for the given AuthContext
   *
   * @param type authentication index type
   * @param indexName authentication index name
   * @param principal principal name of the user to be authenticated
   * @param password password for the user
   * @param subject authentication subject
   * @param pCookieMode <code>true</code>persistent Cookie exists, <code>false</code> otherwise
   * @param envMap Environment map, this is applicable only when the type is <code>
   *     AuthContext.IndexType.RESOURCE</code>
   * @param locale locale setting
   * @throws AuthLoginException if error occurs during login
   */
  protected void login(
      AuthContext.IndexType type,
      String indexName,
      Principal principal,
      char[] password,
      Subject subject,
      boolean pCookieMode,
      Map envMap,
      String locale)
      throws AuthLoginException {
    try {
      /*if (!getStatus().equals(AuthContext.Status.NOT_STARTED)) {
          if (authDebug.messageEnabled()) {
              authDebug.message("AuthContextLocal::login called " +
              "when the current login status is : " + getStatus());
          }
          throw new AuthLoginException(amAuthContextLocal,
              "invalidMethod", new Object[]{getStatus()});
      }*/

      // switch the login status
      loginStatus = AuthContext.Status.IN_PROGRESS;

      String redirectUrl = null;
      // specially processing for resouce/IP/Environement based auth
      if ((type != null) && type.equals(AuthContext.IndexType.RESOURCE)) {
        // this is resouce/IP/Env based authentication
        // call Policy Decision Util to find out the actual auth type
        // required by policy
        List result = Collections.EMPTY_LIST;
        try {
          result = PolicyDecisionUtils.doResourceIPEnvAuth(indexName, organizationName, envMap);
        } catch (PolicyException pe) {
          // ignore, continue to default realm based authentication
          // may need to revisit this in the future
          authDebug.warning(
              "AuthContextLocal.login() policy error " + "indexName=" + indexName, pe);
          type = null;
          indexName = null;
        }
        if (authDebug.messageEnabled()) {
          authDebug.message("AuthContextLocal.login: policy decision=" + result);
        }
        if (result.size() == 2) {
          type = (AuthContext.IndexType) result.get(0);
          indexName = (String) result.get(1);
        } else if (result.size() == 1) {
          // this is the redirection case (Policy Redirection Advice)
          redirectUrl = (String) result.get(0);
          // append goto parameter for federation case
          Set tmp = (Set) envMap.get(ISAuthConstants.GOTO_PARAM);
          if ((tmp != null) && !tmp.isEmpty()) {
            String gotoParam = (String) tmp.iterator().next();
            if ((gotoParam != null) && (gotoParam.length() != 0)) {
              if ((redirectUrl != null) && (redirectUrl.indexOf("?") != -1)) {
                redirectUrl =
                    redirectUrl
                        + "&"
                        + ISAuthConstants.GOTO_PARAM
                        + "="
                        + URLEncDec.encode(gotoParam);
              } else {
                redirectUrl =
                    redirectUrl
                        + "?"
                        + ISAuthConstants.GOTO_PARAM
                        + "="
                        + URLEncDec.encode(gotoParam);
              }
            }
          }
          type = null;
          indexName = null;
        } else {
          // no policy decision, use default realm login
          type = null;
          indexName = null;
        }
      }
      HashMap loginParamsMap = new HashMap();

      loginParamsMap.put(INDEX_TYPE, type);
      loginParamsMap.put(INDEX_NAME, indexName);
      loginParamsMap.put(PRINCIPAL, principal);
      loginParamsMap.put(PASSWORD, password);
      loginParamsMap.put(SUBJECT, subject);
      loginParamsMap.put(PCOOKIE, Boolean.valueOf(pCookieMode));
      loginParamsMap.put(LOCALE, locale);
      if (redirectUrl != null) {
        loginParamsMap.put(REDIRECT_URL, redirectUrl);
      }

      if (authDebug.messageEnabled()) {
        authDebug.message("loginParamsMap : " + loginParamsMap.toString());
      }

      authDebug.message("calling AMLoginContext::exceuteLogin : "******"after AMLoginContext::exceuteLogin : "******"Status at the end of login() : " + loginStatus);
      }
    } catch (AuthLoginException e) {
      if (authDebug.messageEnabled()) {
        authDebug.message("Exception in ac.login : " + e.toString());
      }
      throw e;
    }
  }
Esempio n. 26
0
  static {
    bundle = Locale.getInstallResourceBundle("libSOAPBinding");
    faultStringServerError = bundle.getString("ServerError");
    debug = Debug.getInstance("libIDWSF");

    try {
      messageFactory = MessageFactory.newInstance();
    } catch (Exception ex) {
      debug.error("Utils.static: Unable to create SOAP Message Factory", ex);
    }

    String tmpNSPre = SystemPropertiesManager.get(NAMESPACE_PREFIX_MAPPING_LIST_PROP);
    if (tmpNSPre != null && tmpNSPre.length() > 0) {
      StringTokenizer stz = new StringTokenizer(tmpNSPre, "|");
      while (stz.hasMoreTokens()) {
        String token = stz.nextToken().trim();
        int index = token.indexOf('=');
        if (index != -1 && index != 0 && index != token.length() - 1) {
          String prefix = token.substring(0, index);
          String ns = token.substring(index + 1);
          if (debug.messageEnabled()) {
            debug.message("Utils.static: add ns = " + ns + ", prefix = " + prefix);
          }
          nsPrefix.put(ns, prefix);
        } else {
          if (debug.warningEnabled()) {
            debug.warning(
                "Utils.static: Invalid syntax " + "for Namespace Prefix Mapping List: " + token);
          }
        }
      }
    }

    String tmpJaxbPkgs = SystemPropertiesManager.get(JAXB_PACKAGE_LIST_PROP);
    if (tmpJaxbPkgs != null && tmpJaxbPkgs.length() > 0) {
      jaxbPackages = DEFAULT_JAXB_PACKAGES + ":" + tmpJaxbPkgs;
    } else {
      jaxbPackages = DEFAULT_JAXB_PACKAGES;
    }
    if (debug.messageEnabled()) {
      debug.message("Utils.static: jaxbPackages = " + jaxbPackages);
    }

    try {
      jc = JAXBContext.newInstance(jaxbPackages);
    } catch (JAXBException jaxbe) {
      Utils.debug.error("Utils.static:", jaxbe);
    }

    String tmpstr = SystemPropertiesManager.get(STALE_TIME_LIMIT_PROP);
    if (tmpstr != null) {
      try {
        stale_time_limit = Integer.parseInt(tmpstr);
      } catch (Exception ex) {
        if (debug.warningEnabled()) {
          debug.warning(
              "Utils.static: Unable to get stale time " + "limit. Default value will be used");
        }
      }
    }

    tmpstr = SystemPropertiesManager.get(SUPPORTED_ACTORS_PROP);
    if (tmpstr != null) {
      StringTokenizer stz = new StringTokenizer(tmpstr, "|");
      while (stz.hasMoreTokens()) {
        String token = stz.nextToken();
        if (token.length() > 0) {
          supportedActors.add(token);
        }
      }
    }
    tmpstr = SystemPropertiesManager.get(MESSAGE_ID_CACHE_CLEANUP_INTERVAL_PROP);
    if (tmpstr != null) {
      try {
        message_ID_cleanup_interval = Integer.parseInt(tmpstr);
      } catch (Exception ex) {
        if (debug.warningEnabled()) {
          debug.warning(
              "Utils.CleanUpThread.static: Unable to"
                  + " get stale time limit. Default value "
                  + "will be used");
        }
      }
    }
    messageIDMap = new PeriodicCleanUpMap(message_ID_cleanup_interval, stale_time_limit);
    SystemTimerPool.getTimerPool()
        .schedule(
            (TaskRunnable) messageIDMap,
            new Date(((System.currentTimeMillis() + message_ID_cleanup_interval) / 1000) * 1000));
  }
Esempio n. 27
0
  /**
   * This the main method of this servlet which takes in the request opens a URLConnection to the
   * CDCServlet endpoint in the OpenAM, and tunnels the request content to it. It parses the
   * Response received and if the HTTP_STATUS is "HTTP_OK" or "HTTP_MOVED_TEMP" POSTs the received
   * Liberty Authn Response to the goto URL specified in the original request.
   */
  private void sendAuthnRequest(
      HttpServletRequest request, HttpServletResponse response, SSOToken token)
      throws ServletException, IOException {
    SessionID sessid = new SessionID(request);
    URL CDCServletURL = null;
    URL sessionServiceURL = null;
    try {
      sessionServiceURL = Session.getSessionServiceURL(sessid);
    } catch (SessionException se) {
      debug.error(
          "CDCClientServlet.sendAuthnRequest: Cannot locate" + " OpenAM instance to forward to.",
          se);
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    if (sessionServiceURL == null) {
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    // replace "sessionservice" by cdcservlet in obtained URL
    // we use naming so that we get the URL of the exact server
    // where the session is located and get the right deployment
    // descriptor.
    String sessionServiceURLString = sessionServiceURL.toString();
    int serviceNameIndex =
        sessionServiceURLString.lastIndexOf(
            "/", sessionServiceURLString.length() - 2); // avoiding trailing "/"
    // if any
    StringBuilder buffer = new StringBuilder(150);
    buffer
        .append(sessionServiceURLString.substring(0, serviceNameIndex))
        .append(CDCURI)
        .append(QUESTION_MARK)
        .append(request.getQueryString()); // add query string to
    // CDCServletURL

    CDCServletURL = new URL(buffer.toString());

    // save the go to URL of the agent side to ultimately
    // POST to.
    try {
      HttpURLConnection connection = HttpURLConnectionManager.getConnection(CDCServletURL);
      connection.setRequestMethod("GET");
      connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      // replay cookies
      String strCookies = getCookiesFromRequest(request);
      if (strCookies != null) {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.sendAuthnRequest:Setting " + "cookies = " + strCookies);
        }
        connection.setRequestProperty("Cookie", strCookies);
      }
      // dont wish to follow redirect to agent, since
      // the response needs to go via the CDCClientServlet.
      HttpURLConnection.setFollowRedirects(false);

      // Receiving input from CDCServlet on the AM server instance
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Getting " + "response back from  " + CDCServletURL);
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response " + "Code " + connection.getResponseCode());
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response "
                + "Message= "
                + connection.getResponseMessage());
      }

      // Check response code
      if ((connection.getResponseCode() == HttpURLConnection.HTTP_OK)
          || (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)) {
        /**
         * Read the response back from CDCServlet, got a redirect since this response contains the
         * "LARES" ( Liberty authn response, which needs to be posted back to the dest url (agent).
         */
        StringBuilder inBuf = new StringBuilder();
        BufferedReader in =
            new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
          inBuf.append(buf, 0, len);
        }
        String inString = inBuf.toString();
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.sendAuthnRequest:" + "Received response data = " + inString);
        }
        // put the received Liberty Auth Response
        // in the servlet's response.
        sendAuthnResponse(request, response, inString);
      } else {
        debug.error("CDCClientServlet.sendAuthnRequest: Response " + "code NOT OK/MOVED_TEMP ");
        showError(
            response,
            "ERROR: Received HTTP error code "
                + connection.getResponseCode()
                + " from "
                + CDCServletURL);
      }
    } catch (ConnectException ce) {
      // Debug the exception
      if (debug.warningEnabled()) {
        debug.warning(
            "CDCClientServlet.sendAuthnRequest: " + "Connection Exception to " + CDCServletURL, ce);
      }
      showError(
          response, "Could not connect to CDCServlet at " + CDCServletURL + ":" + ce.getMessage());
    }
  }
Esempio n. 28
0
  /**
   * Main monitor thread loop. Wait for persistent search change notifications
   *
   * @supported.api
   */
  public void run() {
    try {
      if (debugger.messageEnabled()) {
        debugger.message(
            "EventService.run(): Event Thread is running! "
                + "No Idle timeout Set: "
                + _idleTimeOut
                + " minutes.");
      }

      boolean successState = true;
      LDAPMessage message = null;
      while (successState) {
        try {
          if (debugger.messageEnabled()) {
            debugger.message("EventService.run(): Waiting for " + "response");
          }
          synchronized (this) {
            if (_requestList.isEmpty()) {
              wait();
            }
          }
          message = _msgQueue.getResponse();
          successState = processResponse(message);
        } catch (LDAPInterruptedException ex) {
          if (_shutdownCalled) {
            break;
          } else {
            if (debugger.warningEnabled()) {
              debugger.warning("EventService.run() " + "LDAPInterruptedException received:", ex);
            }
          }
        } catch (LDAPException ex) {
          if (_shutdownCalled) {
            break;
          } else {
            int resultCode = ex.getLDAPResultCode();
            if (debugger.warningEnabled()) {
              debugger.warning("EventService.run() LDAPException " + "received:", ex);
            }
            _retryErrorCodes = getPropertyRetryErrorCodes(EVENT_CONNECTION_ERROR_CODES);

            // Catch special error codition in
            // LDAPSearchListener.getResponse
            String msg = ex.getLDAPErrorMessage();
            if ((resultCode == LDAPException.OTHER)
                && (msg != null)
                && msg.equals("Invalid response")) {
              // We should not try to resetError and retry
              processNetworkError(ex);
            } else {
              if (_retryErrorCodes.contains("" + resultCode)) {
                resetErrorSearches(true);
              } else { // Some other network error
                processNetworkError(ex);
              }
            }
          }
        }
      } // end of while loop
    } catch (InterruptedException ex) {
      if (!_shutdownCalled) {
        if (debugger.warningEnabled()) {
          debugger.warning("EventService.run(): Interrupted exception" + " caught.", ex);
        }
      }
    } catch (RuntimeException ex) {
      if (debugger.warningEnabled()) {
        debugger.warning("EventService.run(): Runtime exception " + "caught.", ex);
      }
      // rethrow the Runtime exception to let the container handle the
      // exception.
      throw ex;
    } catch (Exception ex) {
      if (debugger.warningEnabled()) {
        debugger.warning("EventService.run(): Unknown exception " + "caught.", ex);
      }
      // no need to rethrow.
    } catch (Throwable t) {
      // Catching Throwable to prevent the thread from exiting.
      if (debugger.warningEnabled()) {
        debugger.warning(
            "EventService.run(): Unknown exception " + "caught. Sleeping for a while.. ", t);
      }
      // rethrow the Error to let the container handle the error.
      throw new Error(t);
    } finally {
      synchronized (this) {
        if (!_shutdownCalled) {
          // try to restart the monitor thread.
          _monitorThread = null;
          startMonitorThread();
        }
      }
    }
  } // end of thread
Esempio n. 29
0
  /**
   * Determine the listener list based on the diable list property and SMS DataStore notification
   * property in Realm mode
   */
  private static void getListenerList() {
    String list = SystemProperties.get(EVENT_LISTENER_DISABLE_LIST, "");
    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.getListenerList(): " + EVENT_LISTENER_DISABLE_LIST + ": " + list);
    }

    boolean enableDataStoreNotification =
        Boolean.parseBoolean(SystemProperties.get(Constants.SMS_ENABLE_DB_NOTIFICATION));
    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.getListenerList(): "
              + "com.sun.identity.sm.enableDataStoreNotification: "
              + enableDataStoreNotification);
    }

    boolean configTime =
        Boolean.parseBoolean(SystemProperties.get(Constants.SYS_PROPERTY_INSTALL_TIME));
    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.getListenerList(): "
              + Constants.SYS_PROPERTY_INSTALL_TIME
              + ": "
              + configTime);
    }

    // Copy the default listeners
    String[] tmpListeners = new String[ALL_LISTENERS.length];
    System.arraycopy(ALL_LISTENERS, 0, tmpListeners, 0, ALL_LISTENERS.length);

    // Process the configured disabled list first
    boolean disableACI = false, disableUM = false, disableSM = false;
    if (list.length() != 0) {
      StringTokenizer st = new StringTokenizer(list, ",");
      String listener = "";
      while (st.hasMoreTokens()) {
        listener = st.nextToken().trim();
        if (listener.equalsIgnoreCase("aci")) {
          disableACI = true;
        } else if (listener.equalsIgnoreCase("um")) {
          disableUM = true;
        } else if (listener.equalsIgnoreCase("sm")) {
          disableSM = true;
        } else {
          debugger.error(
              "EventService.getListenerList() - " + "Invalid listener name: " + listener);
        }
      }
    }

    if (!disableUM || !disableACI) {
      // Check if AMSDK is configured
      boolean disableAMSDK = true;
      if (!configTime) {
        try {
          ServiceSchemaManager scm =
              new ServiceSchemaManager(getSSOToken(), IdConstants.REPO_SERVICE, "1.0");
          ServiceSchema idRepoSubSchema = scm.getOrganizationSchema();
          Set idRepoPlugins = idRepoSubSchema.getSubSchemaNames();
          if (idRepoPlugins.contains("amSDK")) {
            disableAMSDK = false;
          }
        } catch (SMSException ex) {
          if (debugger.warningEnabled()) {
            debugger.warning(
                "EventService.getListenerList() - " + "Unable to obtain idrepo service", ex);
          }
        } catch (SSOException ex) {
          // Should not happen, ignore the exception
        }
      }
      if (disableAMSDK) {
        disableUM = true;
        disableACI = true;
        if (debugger.messageEnabled()) {
          debugger.message(
              "EventService.getListener"
                  + "List(): AMSDK is not configured or config time. "
                  + "Disabling UM and ACI event listeners");
        }
      }
    }

    // Verify if SMSnotification should be enabled
    if (configTime || ServiceManager.isRealmEnabled()) {
      disableSM = !enableDataStoreNotification;
      if (debugger.messageEnabled()) {
        debugger.message(
            "EventService.getListenerList(): In realm "
                + "mode or config time, SMS listener is set to datastore "
                + "notification flag: "
                + enableDataStoreNotification);
      }
    }

    // Disable the selected listeners
    if (disableACI) {
      tmpListeners[0] = null;
    }
    if (disableUM) {
      tmpListeners[1] = null;
    }
    if (disableSM) {
      tmpListeners[2] = null;
    }
    listeners = tmpListeners;

    // if all disabled, signal to not start the thread
    if (disableACI && disableUM && disableSM) {
      if (debugger.messageEnabled()) {
        debugger.message(
            "EventService.getListenerList() - "
                + "all listeners are disabled, EventService won't start");
      }
      _allDisabled = true;
    } else {
      _allDisabled = false;
    }
  }