예제 #1
0
 /**
  * Returns the SSOToken of the user. If user has not authenticated re-directs the user to login
  * page
  */
 private SSOToken getSSOToken(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   SSOToken token = null;
   try {
     /* SSOTokenManager.createSSOToken() throws an SSOException if the
      * token is not valid, so for a invalid token manager.isValidToken()
      * will never get executed for an invalid token.
      */
     if (((token = tokenManager.createSSOToken(request)) == null)
         || !tokenManager.isValidToken(token)) {
       if (debug.messageEnabled()) {
         debug.message(
             "CDCClientServlet.getSSOToken:SSOToken is "
                 + "either null or not valid: "
                 + token
                 + "\nRedirecting for authentication");
       }
       token = null;
     }
   } catch (com.iplanet.sso.SSOException e) {
     if (debug.messageEnabled()) {
       debug.message("CDCClientServlet.getSSOToken:SSOException " + "caught= " + e);
     }
     token = null;
   }
   return (token);
 }
예제 #2
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);
      }
    }
  }
예제 #3
0
  /**
   * Perform a remote setProperty on the Session using the remote Service URL.
   *
   * <p>{@inheritDoc}
   */
  public void setProperty(Session session, String name, String value) throws SessionException {
    if (debug.messageEnabled()) {
      debug.message(MessageFormat.format("Remote setProperty {0} {1}={2}", session, name, value));
    }

    SessionID sessionID = session.getID();
    SessionRequest sreq =
        new SessionRequest(SessionRequest.SetProperty, sessionID.toString(), false);
    sreq.setPropertyName(name);
    sreq.setPropertyValue(value);
    if (SystemProperties.isServerMode() && InternalSession.isProtectedProperty(name)) {
      try {
        SSOToken admSSOToken = SessionUtils.getAdminToken();
        sreq.setRequester(RestrictedTokenContext.marshal(admSSOToken));
      } catch (SSOException e) {
        throw new SessionException(e);
      } catch (Exception e) {
        throw new SessionException(e);
      }

      if (debug.messageEnabled()) {
        debug.message(
            "Session.setProperty: "
                + "added admSSOToken in sreq to set "
                + "externalProtectedProperty in remote server");
      }
    }
    requests.sendRequestWithRetry(session.getSessionServiceURL(), sreq, session);
  }
예제 #4
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;
  }
예제 #5
0
 /**
  * Returns the Policy Decision Point End Point (PDP) URL.
  *
  * @param pdpEntityID entity Identifier of the PDP.
  * @return the PDP endpoint URL.
  * @exception if there is an error retreiving the endpoint from the configuration.
  */
 private static String getPDPEndPoint(String pdpEntityID) throws SAML2Exception {
   String endPoint = null;
   String classMethod = "QueryClient:getPDPEndPoint";
   if (saml2MetaManager != null) {
     try {
       XACMLPDPDescriptorElement pdpDescriptor =
           saml2MetaManager.getPolicyDecisionPointDescriptor(null, pdpEntityID);
       if (pdpDescriptor != null) {
         List xacmlPDP = pdpDescriptor.getXACMLAuthzService();
         if (xacmlPDP != null) {
           Iterator i = xacmlPDP.iterator();
           while (i.hasNext()) {
             Object o = (Object) i.next();
             if (o instanceof XACMLAuthzServiceElement) {
               XACMLAuthzServiceElement xType = (XACMLAuthzServiceElement) o;
               endPoint = xType.getLocation();
               if (debug.messageEnabled()) {
                 debug.message(classMethod + "EndPoint :" + endPoint);
               }
             }
             break;
           }
         }
       }
     } catch (SAML2MetaException sme) {
       if (debug.messageEnabled()) {
         debug.message(classMethod + "Error retreiving PDP Meta", sme);
       }
       String[] args = {pdpEntityID};
       LogUtil.error(Level.INFO, LogUtil.PDP_METADATA_ERROR, args);
       throw new SAML2Exception(SAML2SDKUtils.BUNDLE_NAME, "pdpMetaRetreivalError", args);
     }
   }
   return endPoint;
 }
예제 #6
0
  /**
   * Returns Replication Status by invoking OpenDJ <code>dsreplication</code> CLI
   *
   * @param port LDAP port number of embedded OpenDJ
   * @param passwd Directory Manager password
   * @param oo Standard output
   * @param err : Standard error
   * @return <code>dsreplication</code> CLI exit code.
   */
  public static int getReplicationStatus(
      String port, String passwd, OutputStream oo, OutputStream err) {
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    String baseDir = SystemProperties.get(SystemProperties.CONFIG_PATH);

    String[] statusCmd = {
      "status",
      "--no-prompt",
      "-h",
      "localhost",
      "-p",
      port,
      "--adminUID",
      "admin",
      "--adminPassword",
      passwd,
      "-s",
      "--configFile",
      baseDir + "/opends/config/config.ldif"
    };
    if (debug.messageEnabled()) {
      String dbgcmd = concat(statusCmd).replaceAll(passwd, "****");
      debug.message("EmbeddedOpenDS:getReplicationStatus:exec dsreplication :" + dbgcmd);
    }
    int ret = ReplicationCliMain.mainCLI(statusCmd, false, oo, err, null);
    if (debug.messageEnabled()) {
      debug.message("EmbeddedOpenDS:getReplicationStatus:dsreplication ret:" + ret);
    }
    return ret;
  }
예제 #7
0
  /**
   * Returns <code>true</code> if distinguished user name is a special user DN.
   *
   * @param dn Distinguished name of user.
   * @return <code>true</code> if user is a special user.
   */
  public boolean isSpecialUser(String dn) {
    // dn in all the invocation is normalized.
    boolean isSpecialUser = false;
    String nDN = DNUtils.normalizeDN(dn);
    if ((nDN != null) && (specialUser != null)) {
      StringTokenizer st = new StringTokenizer(specialUser, "|");
      while (st.hasMoreTokens()) {
        String specialAdminDN = (String) st.nextToken();
        if (specialAdminDN != null) {
          String normSpecialAdmin = DNUtils.normalizeDN(specialAdminDN);

          if (debug.messageEnabled()) {
            debug.message("normalized special dn is :" + normSpecialAdmin);
          }
          if (nDN.equals(normSpecialAdmin)) {
            isSpecialUser = true;
            break;
          }
        }
      }
    }
    if (debug.messageEnabled()) {
      debug.message("is Special User :" + isSpecialUser);
    }
    return isSpecialUser;
  }
예제 #8
0
  void printProfileAttrs() {
    if (!debug.messageEnabled()) {
      return;
    }
    debug.message("Authd Profile Attributes");

    String adminAuthName = adminAuthModule;
    int index = adminAuthModule.lastIndexOf(".");
    if (index > 0) {
      adminAuthName = adminAuthModule.substring(index + 1);
    }
    if (debug.messageEnabled()) {
      debug.message(
          "adminAuthModule->"
              + adminAuthModule
              + "\nadminAuthName->"
              + adminAuthName
              + "\ndefaultOrg->"
              + defaultOrg
              + "\nlocale->"
              + platformLocale
              + "\ncharset>"
              + platformCharset);
    }
  }
예제 #9
0
  /**
   * Returns the organization DN.
   *
   * <p>If the organization name matches the root suffix or has the root suffix in it then the DN
   * will be returned as string. Otherwise the DN will be constructed from the organization Name DN
   * and the root suffix DN.
   *
   * @param userOrg Organization Name
   * @return Organization DN of the organization
   */
  public String getOrgDN(String userOrg) {
    DN userOrgDN = new DN(userOrg);
    DN rootSuffixDN = new DN(rootSuffix);
    String orgDN = null;

    if (debug.messageEnabled()) {
      debug.message("userOrg is : " + userOrg);
      debug.message("rootSuffix is : " + rootSuffix);
      debug.message("rootSuffixDN is : " + rootSuffixDN);
      debug.message("userOrgDN is : " + userOrgDN);
    }

    if ((userOrgDN.equals(rootSuffixDN)) || (userOrgDN.isDescendantOf(rootSuffixDN))) {
      orgDN = userOrgDN.toString();
    } else {
      orgDN =
          (new StringBuffer(50))
              .append(userOrgDN.toString())
              .append(",")
              .append(rootSuffixDN)
              .toString();
    }

    if (debug.messageEnabled()) {
      debug.message("Returning OrgDN is : " + orgDN);
    }
    return orgDN.toString();
  }
예제 #10
0
  /**
   * The method redirects the user to the authentication module if he is not authenticated; else
   * redirects him back to the original referrer.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  private void doGetPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.doGetPost:Query String received= " + request.getQueryString());
    }
    String gotoParameter = request.getParameter(GOTO_PARAMETER);
    String targetParameter = request.getParameter(TARGET_PARAMETER);
    if (targetParameter == null) {
      targetParameter = request.getParameter(TARGET_PARAMETER.toLowerCase());
    }
    // if check if goto ot target have invalid strings, to avoid
    // accepting invalid injected javascript.

    if ((gotoParameter != null) || (targetParameter != null)) {
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet:doGetPost():validating goto: "
                + gotoParameter
                + " and target: "
                + targetParameter);
      }
      for (String invalidStr : INVALID_SET) {
        if (gotoParameter != null && gotoParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "GOTO parameter has invalid characters");
          return;
        }
        if (targetParameter != null && targetParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "TARGET parameter has invalid characters");
          return;
        }
      }
    }

    /* Steps to be done
     * 1. If no SSOToken or policy advice present , forward to
     *    authentication.
     * 2. If SSOToken is valid tunnel request to the backend AM's
     *    CDCServlet and Form POST the received response to the agent.
     */
    // Check for a valid SSOToken in the request. If SSOToken is not found
    // or if the token is invalid, redirect the user for authentication.
    // Also re-direct if there are policy advices in the query string
    SSOToken token = getSSOToken(request, response);
    // collect advices in parsedRequestParams[0] String and rest of params
    // other than original goto url in parsedRequestParams[1] String.
    String[] parsedRequestParams = parseRequestParams(request);

    if ((token == null) || (parsedRequestParams[0] != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response, parsedRequestParams[0], parsedRequestParams[1]);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }
예제 #11
0
 protected void setDomainAttributes(SSOToken token, String orgDN, AttrSet attrSet)
     throws AMException {
   String domainName = null;
   try {
     domainName = getCanonicalDomain(token, orgDN);
     DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
     if (domainName == null) {
       if (debug.messageEnabled()) {
         debug.message("DCTree.setDomainAttrs: " + "No domain found for org : " + orgDN);
       }
       return;
     }
     DomainComponent dcNode = dcTree.getDomainComponent(domainName);
     if (attrSet != null) {
       if (debug.messageEnabled()) {
         debug.message(
             "DCTree.setDomainAttrs: "
                 + " setting attributes on domain "
                 + domainName
                 + ": "
                 + attrSet.toString());
       }
       Attr ocAttr = attrSet.getAttribute("objectclass");
       if (ocAttr != null) {
         Attr oldOCAttr = dcNode.getAttribute("objectclass");
         if (oldOCAttr != null) {
           ocAttr.addValues(oldOCAttr.getStringValues());
         }
         if (debug.messageEnabled()) {
           debug.message(
               "DCTree.setDomainAttrs-> " + "objectclasses to be set " + ocAttr.toString());
         }
         if (ocAttr.size() == 0) dcNode.modify(ocAttr, ModSet.DELETE);
         else dcNode.modify(ocAttr, ModSet.REPLACE);
         dcNode.save();
         attrSet.remove("objectclass");
       }
       int size = attrSet.size();
       for (int i = 0; i < size; i++) {
         Attr attr = attrSet.elementAt(i);
         if (attr.size() == 0) {
           // remove attribute
           dcNode.modify(attr, ModSet.DELETE);
         } else {
           // replace attribute
           dcNode.modify(attr, ModSet.REPLACE);
         }
       }
       dcNode.save();
     }
   } catch (UMSException umse) {
     debug.error(
         "DCTree.setDomainAttributes: "
             + " error setting "
             + " attribute for domain "
             + domainName,
         umse);
   }
 }
예제 #12
0
  /** This is a private method to update cache */
  private String updateCacheAndReturnDomain(SSOToken token, String canonOrgDN) throws AMException {
    try {
      DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));

      SearchControl scontrol = new SearchControl();
      scontrol.setSearchScope(SearchControl.SCOPE_SUB);
      PersistentObject po = UMSObject.getObject(token, new Guid(DCTREE_START_DN));
      String searchFilter = "(inetDomainBaseDN=" + canonOrgDN + ")";
      if (debug.messageEnabled()) {
        debug.message("DCTree.updateCache-> " + "searchFilter= " + searchFilter);
      }
      SearchResults results = po.search(searchFilter, null);

      int count = 0;
      String domainName = null;
      String canonDomain = null;
      while (results.hasMoreElements()) {
        DomainComponent dcNode = (DomainComponent) results.next();
        count++;
        domainName = dcTree.mapDCToDomainName(dcNode);
        if (debug.messageEnabled()) {
          debug.message("DCTree:updateCache-> " + "domainName= " + domainName);
        }
        Attr isCanonical = dcNode.getAttribute(INET_CANONICAL_DOMAIN);
        if (isCanonical != null) {
          /*
           * if (AMCacheManager.isCachingEnabled()) {
           * synchronized(canonicalDomainMap) {
           * canonicalDomainMap.put(canonOrgDN, domainName); } }
           */
          canonDomain = domainName;
        }
        /*
         * if (AMCacheManager.isCachingEnabled()) {
         * synchronized(domainMap) { domainMap.put(canonOrgDN,
         * domainName); } }
         */
      }
      results.abandon();
      if (count == 1) {
        canonDomain = domainName;
        /*
         * if (AMCacheManager.isCachingEnabled()) {
         * canonicalDomainMap.put(canonOrgDN, domainName); }
         */
      }
      if (debug.messageEnabled()) {
        debug.message("DCTree.updateCache-> " + "returning domain= " + canonDomain);
      }
      return canonDomain;

    } catch (UMSException umse) {
      debug.error("DCTree:updateCache: UMSException", umse);
      return null;
    }
  }
예제 #13
0
  private static void initConfig() {
    adviceParams.add("module");
    adviceParams.add("authlevel");
    adviceParams.add("role");
    adviceParams.add("service");
    adviceParams.add("user");
    adviceParams.add("realm");
    adviceParams.add("org");
    adviceParams.add("resource");
    adviceParams.add("sunamcompositeadvice");
    String invalidStrings = SystemPropertiesManager.get(Constants.INVALID_GOTO_STRINGS);
    if (INVALID_SET.isEmpty()) {
      debug.message("CDCClientServlet.initConfig: creating invalidSet");
      if (invalidStrings == null) {
        debug.message("CDCClientServlet.initConfig: invalidStrings is null");
        INVALID_SET.add(LEFT_ANGLE);
        INVALID_SET.add(RIGHT_ANGLE);
        INVALID_SET.add(URLENC_LEFT_ANGLE);
        INVALID_SET.add(URLENC_RIGHT_ANGLE);
        INVALID_SET.add(JAVASCRIPT);
        INVALID_SET.add(URLENC_JAVASCRIPT);
      } else {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.initConfig: invalidStrings is: " + invalidStrings);
        }
        StringTokenizer st = new StringTokenizer(invalidStrings, DELIM);
        while (st.hasMoreTokens()) {
          INVALID_SET.add(st.nextToken());
        }
      }
      debug.message("CDCClientServlet.initConfig: created invalidSet " + INVALID_SET);
    }

    String urlFromProps = SystemProperties.get(Constants.CDCSERVLET_LOGIN_URL);
    cdcAuthURI = (urlFromProps != null) ? urlFromProps : AUTHURI;

    String validLoginURIStrings = SystemPropertiesManager.get(Constants.VALID_LOGIN_URIS);
    debug.message("CDCClientServlet.initConfig: creating validLoginURISet");
    if (validLoginURIStrings == null) {
      debug.message(
          "CDCClientServlet.initConfig: validLoginURIStrings is null, creating default set");
      VALID_LOGIN_URIS.add(cdcAuthURI);
    } else {
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.initConfig: validLoginURIStrings is: " + validLoginURIStrings);
      }
      StringTokenizer st = new StringTokenizer(validLoginURIStrings, DELIM);
      while (st.hasMoreTokens()) {
        VALID_LOGIN_URIS.add(st.nextToken());
      }
    }
    debug.message("CDCClientServlet.initConfig: created validLoginURISet " + VALID_LOGIN_URIS);
  }
예제 #14
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;
  }
예제 #15
0
  /** Process change notification attached as the change control to the message */
  protected void processSearchResultMessage(LDAPSearchResult res, Request req) {
    LDAPEntry modEntry = res.getEntry();

    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.processSearchResultMessage() - " + "Changed " + modEntry.getDN());
    }

    /* Get any entry change controls. */
    LDAPControl[] ctrls = res.getControls();

    // Can not create event without change control
    if (ctrls == null) {
      Exception ex =
          new Exception("EventService - Cannot create " + "NamingEvent, no change control info");
      dispatchException(ex, req);
    } else {
      // Multiple controls might be in the message
      for (int i = 0; i < ctrls.length; i++) {
        LDAPEntryChangeControl changeCtrl = null;

        if (ctrls[i].getType() == LDAPControl.LDAP_ENTRY_CHANGE_CONTROL) {
          changeCtrl = (LDAPEntryChangeControl) ctrls[i];
          if (debugger.messageEnabled()) {
            debugger.message(
                "EventService."
                    + "processSearchResultMessage() changeCtrl = "
                    + changeCtrl.toString());
          }

          // Can not create event without change control
          if (changeCtrl.getChangeType() == -1) {
            Exception ex =
                new Exception(
                    "EventService - Cannot " + "create NamingEvent, no change control info");
            dispatchException(ex, req);
          }

          // Convert control into a DSEvent and dispatch to listeners
          try {
            DSEvent event = createDSEvent(modEntry, changeCtrl, req);
            dispatchEvent(event, req);
          } catch (Exception ex) {
            dispatchException(ex, req);
          }
        }
      }
    }
  }
예제 #16
0
 private AuthD() {
   debug.message("AuthD initializing");
   try {
     rootSuffix = defaultOrg = ServiceManager.getBaseDN();
     initAuthSessions();
     initAuthServiceGlobalSettings();
     initPlatformServiceGlobalSettings();
     initSessionServiceDynamicSettings();
     initAuthConfigGlobalSettings();
     bundle = com.sun.identity.shared.locale.Locale.getInstallResourceBundle(BUNDLE_NAME);
     ResourceBundle platBundle =
         com.sun.identity.shared.locale.Locale.getInstallResourceBundle("amPlatform");
     platformCharset = platBundle.getString(ISAuthConstants.PLATFORM_CHARSET_ATTR);
     printProfileAttrs();
     // Initialize AuthXMLHandler so that AdminTokenAction can
     // generate DPro Session's SSOToken
     new com.sun.identity.authentication.server.AuthXMLHandler();
     authInitFailed = false;
   } catch (Exception ex) {
     debug.error("AuthD init()", ex);
     authInitFailed = true;
   }
   try {
     enforceJAASThread =
         Boolean.valueOf(SystemProperties.get(Constants.ENFORCE_JAAS_THREAD)).booleanValue();
   } catch (Exception e) {
     if (debug.messageEnabled()) {
       debug.message("Wrong format of " + Constants.ENFORCE_JAAS_THREAD);
     }
   }
 }
예제 #17
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;
  }
예제 #18
0
  /**
   * Returns the <code>NameIDInfoKey</code> key value pair that can be used for searching the user.
   *
   * @param nameID <code>NameID</code> object.
   * @param hostEntityID hosted <code>EntityID</code>.
   * @param remoteEntityID remote <code>EntityID</code>.
   * @exception <code>WSFederationException</code> if any failure.
   */
  protected Map getSearchParameters(
      NameIdentifier nameID, String realm, String hostEntityID, String remoteEntityID)
      throws WSFederationException {

    if (nameID == null) {
      throw new WSFederationException(bundle.getString("nullNameID"));
    }

    NameIDInfoKey infoKey = null;
    try {
      infoKey = new NameIDInfoKey(nameID.getName(), hostEntityID, remoteEntityID);
    } catch (SAML2Exception se) {
      throw new WSFederationException(se);
    }

    HashSet set = new HashSet();
    set.add(infoKey.toValueString());

    Map keyMap = new HashMap();
    keyMap.put(AccountUtils.getNameIDInfoKeyAttribute(), set);

    if (debug.messageEnabled()) {
      debug.message("DefaultAccountMapper.getNameIDKeyMap: " + keyMap);
    }
    return keyMap;
  }
예제 #19
0
 private void setServletRequest(HttpServletRequest servletRequest, AuthContextLocal authContext) {
   LoginState theLoginState = AuthUtils.getLoginState(authContext);
   theLoginState.setHttpServletRequest(servletRequest);
   if (debug.messageEnabled()) {
     debug.message("AuthXMLHandler.setServletRequest(): Setting servlet request.");
   }
 }
예제 #20
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);
       }
     }
   }
 }
예제 #21
0
  /** Create naming event from a change control */
  private DSEvent createDSEvent(LDAPEntry entry, LDAPEntryChangeControl changeCtrl, Request req)
      throws Exception {
    DSEvent dsEvent = new DSEvent();

    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.createDSEvent() - Notifying event " + "to: " + req.getListener());
    }

    // Get the dn from the entry
    String dn = entry.getDN();
    dsEvent.setID(dn);

    // Get information on the type of change made
    int changeType = changeCtrl.getChangeType();
    dsEvent.setEventType(changeType);

    // Pass the search ID as the event's change info
    dsEvent.setSearchID(req.getRequestID());

    // set the object class name
    String className = entry.getAttribute("objectclass").toString();
    dsEvent.setClassName(className);

    return dsEvent;
  }
예제 #22
0
 /**
  * Response message carries a LDAP error. Response with the code 0 (SUCCESS), should never be
  * received as persistent search never completes, it has to be abandon. Referral messages are
  * ignored
  */
 protected boolean processResponseMessage(LDAPResponse rsp, Request request) {
   _retryErrorCodes = getPropertyRetryErrorCodes(EVENT_CONNECTION_ERROR_CODES);
   int resultCode = rsp.getResultCode();
   if (_retryErrorCodes.contains("" + resultCode)) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.processResponseMessage() - "
               + "received LDAP Response for requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener()
               + "Need restarting");
     }
     resetErrorSearches(false);
   } else if (resultCode != 0 || resultCode != LDAPException.REFERRAL) {
     // If not neither of the cases then
     if (resultCode == LDAPException.BUSY) {
       debugger.error(
           "EventService.processResponseMessage() - received error BUSY, call retryManager");
       return retryManager(false);
     }
     LDAPException ex =
         new LDAPException(
             "Error result", rsp.getResultCode(), rsp.getErrorMessage(), rsp.getMatchedDN());
     dispatchException(ex, request);
   }
   return true;
 }
예제 #23
0
  private synchronized void serviceLogin() throws AuthLoginException {
    debug.message("New Service Login ...");
    System.setProperty("java.security.krb5.realm", kdcRealm);
    System.setProperty("java.security.krb5.kdc", kdcServer);
    System.setProperty("java.security.auth.login.config", "/dev/null");

    try {
      Configuration config = Configuration.getConfiguration();
      WindowsDesktopSSOConfig wtc = null;
      if (config instanceof WindowsDesktopSSOConfig) {
        wtc = (WindowsDesktopSSOConfig) config;
        wtc.setRefreshConfig("true");
      } else {
        wtc = new WindowsDesktopSSOConfig(config);
      }
      wtc.setPrincipalName(servicePrincipalName);
      wtc.setKeyTab(keyTabFile);
      Configuration.setConfiguration(wtc);

      // perform service authentication using JDK Kerberos module
      LoginContext lc = new LoginContext(WindowsDesktopSSOConfig.defaultAppName);
      lc.login();

      serviceSubject = lc.getSubject();
      debug.message("Service login succeeded.");
    } catch (Exception e) {
      debug.error("Service Login Error: ");
      if (debug.messageEnabled()) {
        debug.message("Stack trace: ", e);
      }
      throw new AuthLoginException(amAuthWindowsDesktopSSO, "serviceAuth", null, e);
    }
  }
예제 #24
0
  static {
    String status = SystemProperties.get(Constants.AM_LOGSTATUS, "INACTIVE");
    if ("ACTIVE".equalsIgnoreCase(status)) {
      logStatus = true;
    }

    // Get Directory Port value
    try {
      directoryPort = Integer.parseInt(SystemProperties.get(Constants.AM_DIRECTORY_PORT));
    } catch (java.lang.NumberFormatException nfex) {
      directoryPort = 0;
    }

    // Get Session store
    String useHttpSessionStr = SystemProperties.get(ISAuthConstants.SESSION_STORE);
    if (useHttpSessionStr != null && useHttpSessionStr.equalsIgnoreCase("HttpSession")) {
      useHttpSession = true;
    }

    debug = Debug.getInstance(BUNDLE_NAME);
    if (debug.messageEnabled()) {
      debug.message("Directory Host: " + directoryHostName + "\nDirectory PORT : " + directoryPort);
      debug.message("Session store using " + useHttpSessionStr);
    }
  }
예제 #25
0
 /**
  * Constructor
  *
  * @param alias certificate alias for client certificate used in the https connection if client
  *     auth is required
  */
 public Handler(String alias) {
   super();
   Https.init(alias);
   if (debug.messageEnabled()) {
     debug.message("certAlias --> " + alias);
   }
 }
예제 #26
0
 // Get cookies string from HTTP request object
 private String getCookiesFromRequest(HttpServletRequest request) {
   Cookie cookies[] = CookieUtils.getCookieArrayFromReq(request);
   // above call would return pure sid in iPlanetDirectoryPro cookie
   // independent of container encoding
   StringBuilder cookieStr = null;
   String strCookies = null;
   if (cookies != null) {
     for (int nCookie = 0; nCookie < cookies.length; nCookie++) {
       String cookieName = cookies[nCookie].getName();
       String cookieVal = cookies[nCookie].getValue();
       if (cookieName.equals(CookieUtils.getAmCookieName()) && cookieEncoding) {
         cookieVal = URLEncDec.encode(cookieVal);
       }
       if (debug.messageEnabled()) {
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie name = " + cookieName);
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie val= " + cookieVal);
       }
       if (cookieStr == null) {
         cookieStr = new StringBuilder();
       } else {
         cookieStr.append(SEMI_COLON).append(SPACE);
       }
       cookieStr.append(cookieName).append(EQUAL_TO).append(cookieVal);
     }
   }
   if (cookieStr != null) {
     strCookies = cookieStr.toString();
   }
   return strCookies;
 }
  @Override
  public boolean action(InternalSession is, Map<String, Long> sessions) {

    String nextExpiringSessionID = null;
    long smallestExpTime = Long.MAX_VALUE;
    for (Map.Entry<String, Long> entry : sessions.entrySet()) {
      String sid = entry.getKey();
      long expirationTime = entry.getValue();
      if (expirationTime < smallestExpTime) {
        smallestExpTime = expirationTime;
        nextExpiringSessionID = sid;
      }
    }
    if (nextExpiringSessionID != null) {
      SessionID sessID = new SessionID(nextExpiringSessionID);
      try {
        Session s = sessionCache.getSession(sessID);
        s.destroySession(s);
      } catch (SessionException e) {
        if (debug.messageEnabled()) {
          debug.message("Failed to destroy the next " + "expiring session.", e);
        }
        // deny the session activation request
        // in this case
        return true;
      }
    }
    return false;
  }
예제 #28
0
  /** {@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;
  }
  /** {@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;
  }
예제 #30
0
  /**
   * Update the AuthService global and organization settings. most of the code is moved in from
   * AuthenticatorManager.java.
   *
   * @param scm <code>ServiceSchemaManager</code> to be used for update
   * @throws SMSException if it fails to update auth service
   * @throws Exception
   */
  synchronized void updateAuthServiceGlobals(ServiceSchemaManager scm)
      throws SMSException, Exception {

    ServiceSchema schema = scm.getOrganizationSchema();
    Map attrs = schema.getAttributeDefaults();

    // get Global type attributes for iPlanetAMAuthService
    schema = scm.getGlobalSchema();

    attrs.putAll(schema.getAttributeDefaults());
    if (debug.messageEnabled()) {
      debug.message("attrs : " + attrs);
    }

    defaultAuthLocale = CollectionHelper.getMapAttr(attrs, ISAuthConstants.AUTH_LOCALE_ATTR);
    adminAuthModule = CollectionHelper.getMapAttr(attrs, ISAuthConstants.ADMIN_AUTH_MODULE);
    defaultAuthLevel =
        CollectionHelper.getMapAttr(attrs, ISAuthConstants.DEFAULT_AUTH_LEVEL, DEFAULT_AUTH_LEVEL);

    Set s = (Set) attrs.get(ISAuthConstants.AUTHENTICATORS);
    Iterator iter = s.iterator();
    while (iter.hasNext()) {
      String name = (String) iter.next();
      int dot = name.lastIndexOf('.');
      if (dot > -1) {
        String tmp = name.substring(dot + 1, name.length());
        authMethods.put(tmp, name);
      } else {
        authMethods.put(name, name);
      }
    }
    if (debug.messageEnabled()) {
      debug.message("AM.update authMethods = " + authMethods.toString());
    }

    defaultSuccessURLSet = (Set) attrs.get(ISAuthConstants.LOGIN_SUCCESS_URL);
    defaultFailureURLSet = (Set) attrs.get(ISAuthConstants.LOGIN_FAILURE_URL);

    if (debug.messageEnabled()) {
      debug.message("Default Success URL Set = " + defaultSuccessURLSet);
      debug.message("Default Failure URL Set = " + defaultFailureURLSet);
    }

    Integer sleepTime =
        new Integer(CollectionHelper.getMapAttr(attrs, ISAuthConstants.SLEEP_INTERVAL));
    defaultSleepTime = sleepTime.longValue();
  }