Exemplo n.º 1
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);
     }
   }
 }
Exemplo n.º 2
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;
 }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
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);
  }
Exemplo n.º 5
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);
    }
  }
Exemplo n.º 6
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);
 }
Exemplo n.º 7
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;
  }
Exemplo n.º 8
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);
    }
  }
Exemplo n.º 9
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;
  }
Exemplo n.º 10
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);
    }
  }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
0
 static {
   adviceParams.add("module");
   adviceParams.add("authlevel");
   adviceParams.add("role");
   adviceParams.add("service");
   adviceParams.add("user");
   adviceParams.add("realm");
   adviceParams.add("org");
   adviceParams.add("sunamcompositeadvice");
   String invalidStrings = SystemPropertiesManager.get(Constants.INVALID_GOTO_STRINGS);
   if (invalidSet.isEmpty()) {
     debug.message("CDCServlet:static block: creating invalidSet");
     if (invalidStrings == null) {
       debug.message("CDCServlet: invalidStrings is null");
       invalidSet.add(LEFT_ANGLE);
       invalidSet.add(RIGHT_ANGLE);
       invalidSet.add(URLENC_LEFT_ANGLE);
       invalidSet.add(URLENC_RIGHT_ANGLE);
       invalidSet.add(JAVASCRIPT);
       invalidSet.add(URLENC_JAVASCRIPT);
     } else {
       debug.message("CDCServlet: invalidStrings is NOT null");
       StringTokenizer st = new StringTokenizer(invalidStrings, DELIM);
       while (st.hasMoreTokens()) {
         invalidSet.add((String) st.nextToken());
       }
     }
   }
 }
Exemplo n.º 13
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;
  }
Exemplo n.º 14
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);
      }
    }
  }
Exemplo n.º 15
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;
  }
Exemplo n.º 16
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);
    }
  }
Exemplo n.º 17
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);
   }
 }
Exemplo n.º 18
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)) {
      debug.message("CDCServlet:doGetPost():goto or target is not null");
      for (Iterator it = invalidSet.iterator(); it.hasNext(); ) {
        String invalidStr = (String) it.next();
        if ((gotoParameter != null) && (gotoParameter.toLowerCase().indexOf(invalidStr) != -1)) {
          showError(response, "GOTO parameter has invalid " + "characters");
          return;
        }
        if ((targetParameter != null)
            && (targetParameter.toLowerCase().indexOf(invalidStr) != -1)) {
          showError(response, "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);
    if (token == null) {
      policyAdviceList = null;
    }
    // collect advices in policyAdviceList String and rest of params
    // other than original goto url in "requestParams" String.
    parseRequestParams(request);
    if ((token == null) || (policyAdviceList != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }
Exemplo n.º 19
0
  private boolean getConfigParams() {
    // KDC realm in service principal must be uppercase.
    servicePrincipalName = getMapAttr(options, PRINCIPAL);
    keyTabFile = getMapAttr(options, KEYTAB);
    kdcRealm = getMapAttr(options, REALM);
    kdcServer = getMapAttr(options, KDC);
    authLevel = getMapAttr(options, AUTHLEVEL);
    returnRealm = Boolean.valueOf(getMapAttr(options, RETURNREALM)).booleanValue();

    if (debug.messageEnabled()) {
      debug.message(
          "WindowsDesktopSSO params: \n"
              + "principal: "
              + servicePrincipalName
              + "\nkeytab file: "
              + keyTabFile
              + "\nrealm : "
              + kdcRealm
              + "\nkdc server: "
              + kdcServer
              + "\ndomain principal: "
              + returnRealm
              + "\nauth level: "
              + authLevel);
    }

    confIndex = getRequestOrg() + "/" + options.get(ISAuthConstants.MODULE_INSTANCE_NAME);
    Map configMap = (Map) configTable.get(confIndex);
    if (configMap == null) {
      return false;
    }

    String principalName = (String) configMap.get(configAttributes[PRINCIPAL]);
    String tabFile = (String) configMap.get(configAttributes[KEYTAB]);
    String realm = (String) configMap.get(configAttributes[REALM]);
    String kdc = (String) configMap.get(configAttributes[KDC]);

    if (principalName == null
        || tabFile == null
        || realm == null
        || kdc == null
        || !servicePrincipalName.equalsIgnoreCase(principalName)
        || !keyTabFile.equals(tabFile)
        || !kdcRealm.equals(realm)
        || !kdcServer.equalsIgnoreCase(kdc)) {
      return false;
    }

    serviceSubject = (Subject) configMap.get(configAttributes[SUBJECT]);
    if (serviceSubject == null) {
      return false;
    }

    debug.message("Retrieved config params from cache.");
    return true;
  }
Exemplo n.º 20
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;
    }
  }
Exemplo n.º 21
0
  /**
   * Creates <code>AuthContextLocal</code> instance is obtained for a given organization name, or
   * sub organization name. <code>login</code> method is then used to start the authentication
   * process.
   *
   * @param orgName name of the user's organization.
   * @supported.api
   */
  public AuthContextLocal(String orgName) {
    authDebug.message("AuthContextLocal() constructor called");
    organizationName = orgName;

    amlc = new AMLoginContext(this);
    if (authDebug.messageEnabled()) {
      authDebug.message("AMLoginContext object is... " + amlc);
    }
    reset();
  }
 @Override
 public Map<String, String> getAMRAuthModuleMappings() throws ServerException {
   try {
     return getMapSetting(realm, OAuth2ProviderService.AMR_VALUE_MAPPING);
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
 @Override
 public boolean isOpenDynamicClientRegistrationAllowed() throws ServerException {
   try {
     return getBooleanSetting(realm, OAuth2ProviderService.OPEN_DYNAMIC_REGISTRATION_ALLOWED);
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
 @Override
 public boolean isRegistrationAccessTokenGenerationEnabled() throws ServerException {
   try {
     return getBooleanSetting(realm, OAuth2ProviderService.GENERATE_REGISTRATION_ACCESS_TOKENS);
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
Exemplo n.º 25
0
  /**
   * Gathers the parameters in the request as a HTTP URL string. to form request parameters and
   * policy advice String array. It collects all the parameters from the original request except the
   * original goto url and any advice parameters. Note: All the paramters will be url decoded by
   * default., we should make sure that these values are encoded again
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @return An String array, index 0 is policy advice, index 1 is rest of the request parameters
   */
  private String[] parseRequestParams(HttpServletRequest request) {
    StringBuilder adviceList = null;
    StringBuilder parameterString = new StringBuilder(100);
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
      String paramName = (String) e.nextElement();
      if (adviceParams.contains(paramName.toLowerCase())) {
        if (adviceList == null) {
          adviceList = new StringBuilder();
        } else {
          adviceList.append(AMPERSAND);
        }
        String[] values = request.getParameterValues(paramName);
        for (int i = 0; values != null && i < values.length; i++) {
          adviceList.append(paramName).append(EQUAL_TO).append(values[i]);
        }
      } else {
        if (!paramName.equals(GOTO_PARAMETER)) {
          String[] values = request.getParameterValues(paramName);
          for (int i = 0; values != null && i < values.length; i++) {
            parameterString
                .append(AMPERSAND)
                .append(paramName)
                .append(EQUAL_TO)
                .append(URLEncDec.encode(values[i]));
          }
        }
      }
    }
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.parseRequestParams:" + "Advice List is = " + adviceList);
      debug.message(
          "CDCClientServlet.parseRequestParams:"
              + "Parameter String is = "
              + parameterString.toString());
    }

    String policyAdviceList;
    String requestParams;

    if (adviceList == null) {
      policyAdviceList = null;
    } else {
      policyAdviceList = adviceList.toString();
    }

    if (parameterString.length() > 0) {
      requestParams = (parameterString.deleteCharAt(0).toString());
    } else {
      requestParams = parameterString.toString();
    }

    return new String[] {policyAdviceList, requestParams};
  }
Exemplo n.º 26
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;
  }
Exemplo n.º 27
0
 /**
  * Returns the session associated with a session ID.
  *
  * @param sessId Session ID.
  * @return the <code>InternalSession</code> associated with a session ID.
  */
 public static InternalSession getSession(String sessId) {
   if (debug.messageEnabled()) {
     debug.message("getSession for " + sessId);
   }
   InternalSession is = null;
   if (sessId != null) {
     SessionID sid = new SessionID(sessId);
     is = getSession(sid);
   }
   if (is == null) {
     debug.message("getSession returned null");
   }
   return is;
 }
Exemplo n.º 28
0
  /**
   * Terminates an ongoing <code>login</code> call that has not yet completed.
   *
   * @throws AuthLoginException if an error occurred during abort.
   * @supported.api
   */
  public void abort() throws AuthLoginException {
    authDebug.message("AuthContextLocal::abort()");

    try {
      amlc.abort();
    } catch (Exception e) {
      if (authDebug.messageEnabled()) {
        authDebug.message("Exception in AMLoginContext::abort() " + e.getMessage());
      }
      throw new AuthLoginException(amAuthContextLocal, "abortError", null, e);
    }

    loginStatus = AuthContext.Status.COMPLETED;
  }
Exemplo n.º 29
0
 /**
  * Gracefully shuts down the embedded OpenDJ instance.
  *
  * @param reason string representing reason why shutdown was called.
  * @throws Exception on encountering errors.
  */
 public static void shutdownServer(String reason) throws Exception {
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   if (isStarted()) {
     debug.message("EmbeddedOpenDS.shutdown server...");
     DirectoryServer.shutDown("com.sun.identity.setup.EmbeddedOpenDS", Message.EMPTY);
     int sleepcount = 0;
     while (DirectoryServer.isRunning() && (sleepcount < 60)) {
       sleepcount++;
       Thread.sleep(1000);
     }
     serverStarted = false;
     debug.message("EmbeddedOpenDS.shutdown server success.");
   }
 }
Exemplo n.º 30
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);
          }
        }
      }
    }
  }