Package com.adito.webforwards

Examples of com.adito.webforwards.ReverseProxyWebForward


            this.authenticationPassword = spwf.getAuthenticationPassword();
            this.preferredAuthenticationScheme = spwf.getPreferredAuthenticationScheme();
            this.formParameters = spwf.getFormParameters();
            this.formType = spwf.getFormType();
        } else if (this.type == WebForward.TYPE_PATH_BASED_REVERSE_PROXY || this.type == WebForward.TYPE_HOST_BASED_REVERSE_PROXY) {
            ReverseProxyWebForward rpwf = (ReverseProxyWebForward) webForward;
            this.paths = rpwf.getPaths();
            this.activeDNS = rpwf.getActiveDNS();
            this.customHeaders = rpwf.getCustomHeaders();
            this.authenticationUsername = rpwf.getAuthenticationUsername();
            this.authenticationPassword = rpwf.getAuthenticationPassword();
            this.preferredAuthenticationScheme = rpwf.getPreferredAuthenticationScheme();
            this.hostHeader = rpwf.getHostHeader();
            this.formParameters = rpwf.getFormParameters();
            this.formType = rpwf.getFormType();
            this.encoding = rpwf.getCharset();
        }
    }
View Full Code Here


    }
   
    try {
      // Perhaps this is a reverse proxy?
      String host = request.getHost();
      ReverseProxyWebForward wf = null;

      // Active Proxy

      if (host != null && !host.equals("") && host.indexOf('.') > -1) {
        int idx = host.indexOf('.');
        if (idx != -1) {
          try {
            String uniqueId = host.substring(0, idx);
            launchSession = LaunchSessionFactory.getInstance().getLaunchSession(session, uniqueId);
            if (launchSession != null) {
              wf = (ReverseProxyWebForward) launchSession.getResource();
              launchSession.checkAccessRights(null, session);
              if (!((ReverseProxyWebForward) wf).getActiveDNS()) {
                throw new Exception("Appears to be an active DNS request but the associated web forward is not active DNS. Is someone trying something funny???");
              }
                          LogonControllerFactory.getInstance().addCookies(request, response, session.getLogonTicket(), session);
              return handleReverseProxy(pathInContext, pathParams, request, response, launchSession);
            }

          } catch (Exception ex) {
            if (log.isDebugEnabled())
              log.debug("Active DNS web forward lookup failed", ex);
          }
        } else {
          if (log.isDebugEnabled())
            log.debug("Not active DNS.");
        }
      }

      String hostHeader = request.getHost();
      int idx = hostHeader.indexOf(':');
      if (idx > -1)
        hostHeader = hostHeader.substring(0, idx);

      /* Ordinary reverse proxy? There can only ever be one launch session per reverse proxy
       * as there is no way of maintaining the session across requests. If a user launches the
       * resource more than once, the old launch session will be removed
       */

      for (LaunchSession rs : LaunchSessionFactory.getInstance().getLaunchSessionsForType(session,
        WebForwardPlugin.WEBFORWARD_RESOURCE_TYPE)) {
        if (rs.getResource() instanceof ReverseProxyWebForward) {
          wf = (ReverseProxyWebForward) rs.getResource();
          // Check that its not reverseProxyRedirect.jsp because if we don't it breaks access after first attempt in same session
          if (wf.isValidPath(pathInContext) || (wf.getHostHeader() != null && wf.getHostHeader().equals(hostHeader) && !pathInContext.startsWith("/reverseProxyRedirect.jsp"))) {
            rs.checkAccessRights(null, session);
            return handleReverseProxy(pathInContext, pathParams, request, response, rs);
          }
        }
      }
View Full Code Here

  }

  private boolean handleReverseProxy(String path, String params, RequestHandlerRequest request, RequestHandlerResponse response,
                    LaunchSession launchSession) throws IOException {

    ReverseProxyWebForward webForward = (ReverseProxyWebForward) launchSession.getResource();
    boolean connectionError = true;
   
    /* Because we are in a request handler, the session's last access time
     * does not get updated by the container
     */
    launchSession.getSession().access();

    /***
     * LDP - DO NOT use request parameter map until the encoding has been set. If you
     * call getParameters it decodes the parameters so this can only be done once the
     * character set has been set.
     */

    try {
      URL target = getTarget(launchSession, request);
      setRequestEncoding(launchSession, target, request);
      HttpClient client = getClient(launchSession, target);
      ProxiedHttpMethod method = getMethod(client, launchSession, request, target);
      processPortsAndXForwarding(method, request);
      checkProcessedContent(launchSession, method, request);
      addCustomHeaders(webForward, method);
     
      /* If this webforward has JavaScript form authentication and this hasn't
       * yet been processed, then we make sure the content that comes back from
       * the target is not encoded using gzip or any other compression methods.
       * This is because we will be tacking on some content and its easy to
       * deal with unencoded.
       *
       * TODO We may want to support at least Gzip at some point
       */
      if (webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_JAVASCRIPT)
          && !Boolean.TRUE.equals(launchSession.getAttribute(LAUNCH_ATTR_AUTH_POSTED))) {
        method.getProxiedRequest().removeFields("Accept-Encoding");
      }
     
      com.maverick.http.HttpResponse clientResponse = doExecute(client, method);
      connectionError = false;
      checkInsecureIIS(webForward, clientResponse);
      filterUnsupportedAuthMethods(clientResponse);
      processStatus(clientResponse, response);
      processRedirects(clientResponse, request, response);
      processHeaders(clientResponse, response);

      /*
       * If the content type is HTML, this webforward is configured for
       * automatic JavaScript authentication and authentication has not
       * yet been performed, then tack the JavaScript on to the end of the
       * content. This requires that the content is read into memory and
       * the content length adjusted
       */
      if (clientResponse.getStatus() == 200 && webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_JAVASCRIPT)
        && "text/html".equals(clientResponse.getContentTypeWithoutParameter())
        && !Boolean.TRUE.equals(launchSession.getAttribute(LAUNCH_ATTR_AUTH_POSTED))) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Util.copy(clientResponse.getInputStream(), baos, -1, 16384);
        addJavaScriptAuthenticationCode(launchSession, baos, 0);
View Full Code Here

    }
    return client.execute(method);
  }

  URL getTarget(LaunchSession launchSession, RequestHandlerRequest request) throws MalformedURLException {
    ReverseProxyWebForward webForward = (ReverseProxyWebForward) launchSession.getResource();
    VariableReplacement r = new VariableReplacement();
    r.setRequest(request);
    r.setSession(launchSession.getSession());
    r.setPolicy(launchSession.getPolicy());

    URL target = new URL(r.replace(webForward.getDestinationURL()));

    if (log.isDebugEnabled()) {
      log.debug("Reverse proxy target  " + target.toExternalForm());
    }
    return target;
View Full Code Here

    }
  }

  ProxiedHttpMethod getMethod(HttpClient client, LaunchSession launchSession, RequestHandlerRequest request, URL target) {

    ReverseProxyWebForward webForward = (ReverseProxyWebForward) launchSession.getResource();
    ProxiedHttpMethod method;

    VariableReplacement v = new VariableReplacement();
    v.setRequest(request);
    v.setSession(launchSession.getSession());
    v.setPolicy(launchSession.getPolicy());
   
    /**
     * POST parameters are now not being
     */

    if (!webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_NONE)
        && !webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_NONE)
        && !webForward.getFormType().equals("")
        && !webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_JAVASCRIPT)
        && !Boolean.TRUE.equals(launchSession.getAttribute(LAUNCH_ATTR_AUTH_POSTED))) {

      /**
       * This code will automatically submit form parameters. If it is a post,
       * then we ignore the parameters request and use the webforward target.
       */
      method = new ProxiedHttpMethod(webForward.getFormType(),
              target.getFile(),
              webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST) new MultiMap() : new MultiMap(request.getParameters()),
              launchSession.getSession(),
              webForward.getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST));

      if (webForward.getCharset() != null
          && !webForward.getCharset().equals("")
          && !webForward.getCharset().equals(WebForwardTypes.DEFAULT_ENCODING))
        method.setCharsetEncoding(webForward.getCharset());

      StringTokenizer tokens = new StringTokenizer(webForward.getFormParameters(), "\n");
      int idx;
      String param;
     
      while (tokens.hasMoreTokens()) {
        param = v.replace(tokens.nextToken().trim());
        idx = param.indexOf('=');
        if (idx > -1) {
          method.addParameter(param.substring(0, idx), param.substring(idx + 1));
        } else
          method.addParameter(param, "");
      }
     
      launchSession.setAttribute(LAUNCH_ATTR_AUTH_POSTED, Boolean.TRUE);
      processRequestHeaders(request, method);
     
      // Do not send through any cookies on the authentication request
      method.getProxiedRequest().removeFields(HttpConstants.HDR_COOKIE);
      client.removeAllCookies();

    } else {
      method = new ProxiedHttpMethod(request.getMethod(),
              request.getURIEncoded(),
              new MultiMap(request.getParameters()),
              launchSession.getSession(),
              request.getContentType() != null && request.getContentType()
                      .toLowerCase()
                      .startsWith("application/x-www-form-urlencoded"));
      if (webForward.getCharset() != null
          && !webForward.getCharset().equals("")
          && !webForward.getCharset().equals(WebForwardTypes.DEFAULT_ENCODING))
        method.setCharsetEncoding(webForward.getCharset());
      processRequestHeaders(request, method);
    }

    return method;
  }
View Full Code Here

    return method;
  }

  HttpClient getClient(LaunchSession launchSession, URL target) {

    ReverseProxyWebForward webForward = (ReverseProxyWebForward) launchSession.getResource();

    String hostname = target.getHost();
    boolean isSecure = target.getProtocol().equalsIgnoreCase("https");
    int connectPort = target.getPort() == -1 ? (isSecure ? 443 : 80) : target.getPort();

    HttpClient client;

    SessionClients clients = null;
    // CookieMap cookieMap = null;
    synchronized (launchSession.getSession().getHttpSession()) {
      clients = (SessionClients) launchSession.getSession().getHttpSession().getAttribute(Constants.HTTP_CLIENTS);
      if (clients == null) {
        clients = new SessionClients();
        launchSession.getSession().getHttpSession().setAttribute(Constants.HTTP_CLIENTS, clients);
      }
    }

    synchronized (clients) {
      String key = hostname + ":"
        + connectPort
        + ":"
        + isSecure
        + ":"
        + webForward.getResourceId()
        + ":"
        + Thread.currentThread().getName()
        + ":"
        + launchSession.getSession().getId();
      client = (HttpClient) clients.get(key);

      if (client == null) {
        client = new HttpClient(hostname, connectPort, isSecure);
        client.setIncludeCookies(false);
       
        if (!webForward.getPreferredAuthenticationScheme().equals(HttpAuthenticatorFactory.NONE) && !webForward.getAuthenticationUsername()
                .equals("")
          && !webForward.getAuthenticationPassword().equals("")) {
          PasswordCredentials pwd = new PasswordCredentials();
          pwd.setUsername(SessionInfoReplacer.replace(launchSession.getSession(), webForward.getAuthenticationUsername()));
          pwd.setPassword(SessionInfoReplacer.replace(launchSession.getSession(), webForward.getAuthenticationPassword()));
          client.setCredentials(pwd);
        }

        // Set the preferred scheme
        client.setPreferredAuthentication(webForward.getPreferredAuthenticationScheme());

        // If we're using basic authentication then preempt the 401
        // response
        client.setPreemtiveAuthentication(webForward.getPreferredAuthenticationScheme().equalsIgnoreCase("BASIC"));

        clients.put(key, client);
      }
    }
View Full Code Here

    return client;
  }

  void setRequestEncoding(LaunchSession launchSession, URL target, RequestHandlerRequest request) {

    ReverseProxyWebForward webForward = (ReverseProxyWebForward) launchSession.getResource();

    /**
     * This code sets the character encoding of the request. This may be
     * overridden because some servers assume the character set and there is
     * no way for us work this.
     */
    try {
      if (webForward.getCharset() != null
          && !webForward.getCharset().equals("")
          && !webForward.getCharset().equals(WebForwardTypes.DEFAULT_ENCODING))
        request.setCharacterEncoding(webForward.getCharset());
    } catch (UnsupportedEncodingException ex) {
      log.error("Java runtime does not support encoding", ex);
    }
  }
View Full Code Here

    if (Util.isNullOrTrimmedBlank(launchId)) {
      throw new Exception("No launch ID supplied.");
    }

    LaunchSession launchSession = LaunchSessionFactory.getInstance().getLaunchSession(launchId);
    ReverseProxyWebForward wf = (ReverseProxyWebForward) launchSession.getResource();
   
    /* Remove all other launch sessions for this resource, we can only ever have
     * one at a time
     */
    Collection<LaunchSession> sessions = LaunchSessionFactory.getInstance().getLaunchSessionsForType(launchSession.getSession(),
        WebForwardPlugin.WEBFORWARD_RESOURCE_TYPE);
    for (LaunchSession rs : sessions) {
      if (rs != launchSession && rs.getResource() instanceof ReverseProxyWebForward && rs.getResource().getResourceId() == wf.getResourceId()) {
        LaunchSessionFactory.getInstance().removeLaunchSession(rs);
      }
    }

    if (wf.getActiveDNS() && !isValidForActiveDNS(request.getServerName()))
      throw new Exception("Invalid host '" + request.getServerName() + "'; only FQDNs are valid for Active DNS forwarding");

    String path;
    String url = wf.getDestinationURL();
    String hostField = request.getHeader("Host");
    HostService hostService = hostField == null ? null : new HostService(hostField);
    SessionInfo session = getSessionInfo(request);

    try {
      launchSession.checkAccessRights(null, session);

      /*
       * This requires more thought.
       *
       * 1. We can only have on launch session per resource
       * 2. This doesn't take into account other features of reverse proxy
       *    (authentication, encoding, host headers etc)
       *
       */
     
      /**
       * Setup other reverse proxies so they have access to each other. Only
       * reverse proxies with the same policy attached will be allowed.
      List resources = ResourceUtil.getGrantedResource(launchSession.getSession(), WebForwardPlugin.WEBFORWARD_RESOURCE_TYPE);
     
      Resource resource;
      for(Iterator it = resources.iterator(); it.hasNext();) {
        resource = (Resource) it.next();
        if(resource instanceof ReverseProxyWebForward && resource.getResourceId()!=launchSession.getResource().getResourceId()) {
          if(PolicyDatabaseFactory.getInstance().isResourceAttachedToPolicy(resource, launchSession.getPolicy(), launchSession.getSession().getRealm())) {
            LaunchSession ls = LaunchSessionFactory.getInstance().createLaunchSession(launchSession.getSession(), resource, launchSession.getPolicy());
            ls.checkAccessRights(null, session);
          }
         
        }
      }
       */
     
      VariableReplacement r = new VariableReplacement();
      r.setServletRequest(request);
      r.setLaunchSession(launchSession);
      url = r.replace(url);

      CoreEvent evt = new ResourceAccessEvent(this,
                            WebForwardEventConstants.WEB_FORWARD_STARTED,
              wf,
              launchSession.getPolicy(),
              launchSession.getSession(),
              CoreEvent.STATE_SUCCESSFUL).addAttribute(WebForwardEventConstants.EVENT_ATTR_WEB_FORWARD_TYPE,
        ((WebForwardTypeItem) WebForwardTypes.WEB_FORWARD_TYPES.get(wf.getType())).getName())
              .addAttribute(WebForwardEventConstants.EVENT_ATTR_WEB_FORWARD_URL, url);

      CoreServlet.getServlet().fireCoreEvent(evt);

      // Get the URL to redirect to
      if (wf.getActiveDNS()) {
        URL u = new URL(url);
        URL adu;
        if (Property.getPropertyInt(new SystemConfigKey("webforward.activeDNSFormat")) == 1) {
          adu = new URL("https", launchSession.getId() + "." + hostService.getHost(), hostService.getPort() == 0 ? -1
            : hostService.getPort(), u.getFile());
        } else {
          int idx = hostService.getHost().indexOf('.');
          adu = new URL("https",
                  launchSession.getId() + "." + hostService.getHost().substring(idx + 1),
                  hostService.getPort() == 0 ? -1 : hostService.getPort(),
                  u.getFile());
        }
        path = adu.toExternalForm();

      } else if (wf.getHostHeader() != null && !wf.getHostHeader().equals("")) {
        URL u = new URL(url);

        URL adu = new URL("https", wf.getHostHeader(), hostService.getPort() == 0 ? -1 : hostService.getPort(), u.getFile());

        path = adu.toExternalForm();

        if (adu.getQuery() == null || adu.getQuery().equals("")) {
          path += "?" + LaunchSession.LAUNCH_ID + "=" + launchSession.getId();
        } else {
          path += "&" + LaunchSession.LAUNCH_ID + "=" + launchSession.getId();
        }

        /**
         * Why do we need to use a JSP redirect? Because the new host
         * will be created in a new session and we need the JSESSIONID
         * which is only set once the first response has been returned
         * to the browser. This redirect allows the browser to load a
         * page on the new host and set the session cookie before an
         * automatic redirect takes the user to the correct reverse
         * proxy page.
         */
        URL adu2 = new URL("https",
            /**
             * LDP Not sure why this was using hostService.getHost because my comment above
             * clearly indicates that we have to redirect from the new host
             */
            wf.getHostHeader(),
            hostService.getPort() == 0 ? -1 : hostService.getPort(),
            "/reverseProxyRedirect.jsp?redirectURL=" + Util.urlEncode(path));

        return new ActionForward(adu2.toExternalForm(), true);

      } else {
        URL u = new URL(url);
        path = u.getPath();
        if (u.getQuery() == null || u.getQuery().equals("")) {
          path += "?" + LaunchSession.LONG_LAUNCH_ID + "=" + launchSession.getId();
        } else {
          path += "?" + u.getQuery() + "&" + LaunchSession.LONG_LAUNCH_ID + "=" + launchSession.getId();
        }
       
        URL redir = new URL("https",
          hostService.getHost(),
          hostService.getPort() == 0 ? -1 : hostService.getPort(),
          path);
        path = redir.toExternalForm();
      }
    } catch (NoPermissionException npe) {

      CoreEvent evt = new ResourceAccessEvent(this,
                            WebForwardEventConstants.WEB_FORWARD_STARTED,
              wf,
              launchSession.getPolicy(),
              launchSession.getSession(),
              npe).addAttribute(WebForwardEventConstants.EVENT_ATTR_WEB_FORWARD_TYPE,
        ((WebForwardTypeItem) WebForwardTypes.WEB_FORWARD_TYPES.get(wf.getType())).getName())
              .addAttribute(WebForwardEventConstants.EVENT_ATTR_WEB_FORWARD_URL, url);
      CoreServlet.getServlet().fireCoreEvent(evt);

      throw npe;
    }
View Full Code Here

TOP

Related Classes of com.adito.webforwards.ReverseProxyWebForward

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.