public boolean isAllowed(HttpServletRequest request) {
    boolean allowed = hostAcl.shouldAllowAll();

    if (!allowed) {
      try {
        final InetAddress remoteClient = InetAddress.getByName(request.getRemoteHost());

        for (InetAddress allowedAddress : hostAcl.getAllowedHosts()) {
          if (remoteClient.equals(allowedAddress)) {
            allowed = true;
            break;
          }
        }
      } catch (UnknownHostException uhe) {
        LOG.error(
            "Unknown host exception caught while trying to resolve host: "
                + request.getRemoteHost()
                + " Reason: "
                + uhe.getMessage(),
            uhe);
      }
    }

    return allowed;
  }
  @Override
  public CashRegister getCashRegister(HttpServletRequest request) {
    CashRegister cashRegister = this.cashRegisterRepository.findOne(request.getRemoteHost());

    if (cashRegister != null) {
      return cashRegister;
    }

    return this.cashRegisterRepository.save(
        new CashRegister(request.getRemoteHost(), request.getRemoteAddr()));
  }
Exemplo n.º 3
0
  /**
   * Validate the form.
   *
   * @param mapping_ The action map from struts-config.xml.
   * @param request_ The servlet request object.
   * @return ActionErrors when an error is found, otherwise null.
   */
  public ActionErrors validate(ActionMapping mapping_, HttpServletRequest request_) {
    ActionErrors errors = new ActionErrors();

    HttpSession session = request_.getSession();
    if (session == null) {
      _logger.info("No session exists. [" + this.getClass().getName() + "]");
      errors.add("bean", new ActionMessage("error.nobean"));
      return errors;
    }

    AlertBean ub = (AlertBean) session.getAttribute(AlertBean._SESSIONNAME);
    if (ub == null) {
      _logger.info("No session bean exists. [" + this.getClass().getName() + "]");
      errors.add("bean", new ActionMessage("error.nobean"));
      return errors;
    }

    if (!ub.getKey().equals(_sessionKey)) {
      _logger.error(
          "Sessionkeys do not match. ["
              + ub.getUser()
              + "] ["
              + this.getClass().getName()
              + "] [Page "
              + _sessionKey
              + "] [Bean "
              + ub.getKey()
              + "]");
      errors.add("bean", new ActionMessage("error.nobean"));
      return errors;
    }

    if (!ub.checkHost(request_.getRemoteHost())) {
      _logger.error(
          "Request is made from a host other than the creator. ["
              + ub.getUser()
              + "] ["
              + this.getClass().getName()
              + "] [Creator "
              + ub.getRemoteHost()
              + "] [Requestor "
              + request_.getRemoteHost()
              + "]");
      errors.add("bean", new ActionMessage("error.nobean"));
      return errors;
    }

    return validate(mapping_, request_, ub, errors);
  }
Exemplo n.º 4
0
 /**
  * Static Service Method for testing spiders against existing spider files.
  *
  * @param request
  * @return true|false if the request was detected to be from a spider.
  */
 public static boolean isSpider(HttpServletRequest request) {
   return isSpider(
       request.getRemoteAddr(),
       request.getHeader("X-Forwarded-For"),
       request.getRemoteHost(),
       request.getHeader("User-Agent"));
 }
Exemplo n.º 5
0
 /**
  * 发卡
  *
  * @author cai.yc 2012-11-20
  * @param model
  * @param query query.createCount : 生成数量,为必填项目,最大不能超过50000<br>
  *     query.cityCode : 六位城市代码,如201000<br>
  *     query.typeCode : 四位类型服务级别代码,如0102表示类型为01,服务级别为02<br>
  * @param req
  * @param res
  * @return 返回"c"含义:<br>
  *     "A0000" : 成功<br>
  *     "A0001" : 卡号剩余数量不够<br>
  *     "A0002" : 输入的发卡数量不合法可能为0,或超过500000<br>
  */
 @RequestMapping("/doCreateCard.html")
 public String doCreateCardAction(
     ModelMap model, CardQueryModel query, HttpServletRequest req, HttpServletResponse res) {
   int leftCount = cardBO.cardIdLeft(query);
   if (query.getCreateCount() == null) {
     model.put("c", "A0003");
   } else if (query.getCreateCount() <= 0 || query.getCreateCount() > 500000) {
     // 发卡数量不合法
     model.put("c", "A0002");
   } else if (leftCount < query.getCreateCount()) {
     // 剩余数量不足
     model.put("c", "A0001");
     model.put("d", leftCount);
   } else {
     // 参数合法,生成卡、激活码
     query.setCreateIp(req.getRemoteHost());
     query.setCreateUserId((String) req.getSession().getAttribute("MY120_MARKET_LOGIN_USER_INFO"));
     int result = cardBO.createCard(query);
     model.put("timestamp", query.getGmtCreate());
     model.put("cardTypeName", cardTypeBO.getCardTypeName(query.getTypeCode()));
     model.put("d", result);
     model.put("c", "A0000");
   }
   return "card/do_create_card.html";
 }
Exemplo n.º 6
0
  public boolean performAction(HttpServletRequest request, ServletContext context)
      throws ApplicationException {
    try {

      if (request.getParameter("yes") != null) {
        MugenCaller caller = (MugenCaller) request.getSession().getAttribute("caller");
        Workflow wf = (Workflow) request.getAttribute("workflow");
        int gaid = new Integer(wf.getAttribute("gaid")).intValue();
        modelManager.removeGene(gaid, caller);

        projectManager.log(
            "user " + caller.getName() + " removed gene " + gaid,
            getName(),
            caller.getName(),
            request.getRemoteAddr(),
            request.getRemoteHost());
      }

      return true;
    } catch (ApplicationException e) {
      throw e;
    } catch (Exception e) {
      throw new ApplicationException("RemoveGeneAction Failed To Perform Action", e);
    }
  }
Exemplo n.º 7
0
  /**
   * Determine the host name that the client targeted with their {@code request}. If {@code
   * considerHostHeader} is {@code true}, and a HTTP {@code Host} header is present, the value of
   * the header will be used as the host name. If the header is not present, or if {@code
   * considerHostHeader} is {@code false}, the host name will be determined using {@link
   * javax.servlet.http.HttpServletRequest#getRemoteHost()}. If {@code
   * performLocalhostIpTranslation} is {@code true}, and the host name is {@code LOCAL_HOST_IPV4} or
   * {@code LOCAL_HOST_IPV6}, then the host name will be set to {@code LOCAL_HOST_NAME}.
   *
   * @param request the request
   * @return the host name targeted by the {@code request}
   */
  private String determineHostName(HttpServletRequest request) {

    String hostName = null;

    // If there is a 'Host' header with the request, and if
    // we are supposed to consider it when determining the host name,
    // then use it.

    // This is the best way to go, because the client is indicating
    // what host and port they targeted
    final String hostHeader = request.getHeader(HOST_HEADER);
    if (considerHostHeader && hostHeader != null && hostHeader.trim().length() != 0) {
      hostName = parseHostHeader(hostHeader)[0];
    }

    // Either the 'Host' header wasn't considered, or parsing it failed for some reason.
    // So we fall back on request.getRemoteHost()
    if (hostName == null) {
      hostName = request.getRemoteHost();
    }

    if (performLocalhostIpTranslation) {
      if (LOCAL_HOST_IPV4.equals(hostName) || LOCAL_HOST_IPV6.equals(hostName)) {
        hostName = LOCAL_HOST_NAME;
      }
    }

    return hostName;
  }
Exemplo n.º 8
0
 @RequestMapping(value = "saveRole", method = RequestMethod.POST)
 public String save(
     @ModelAttribute @Valid RoleDomain roleDomain,
     BindingResult bindingResult,
     HttpServletRequest request,
     HttpSession session) {
   if (Strings.isNullOrEmpty(roleDomain.getName())) {
     bindingResult.rejectValue("name", "", "角色名称不能为空");
     return "";
   }
   OsRole osRole = new OsRole();
   osRole.setName(roleDomain.getName());
   osRole.setRemark(roleDomain.getRemark());
   iRoleService.save(osRole, roleDomain.getOsPermissions());
   String user =
       null != session.getAttribute("account")
           ? String.valueOf(session.getAttribute("account"))
           : "admin";
   StringBuilder stringBuilder =
       new StringBuilder("管理员[")
           .append(user)
           .append("]")
           .append("创建了角色[")
           .append(roleDomain.getName())
           .append("]");
   applicationContext.publishEvent(
       new LogEvent(this, stringBuilder.toString(), user, request.getRemoteHost()));
   return "redirect:roles";
 }
Exemplo n.º 9
0
  @POST
  public Response doPost(@Context HttpServletRequest req) {
    if (log.isDebugEnabled())
      log.debug(
          " ****** (POST) Connected from: " + req.getRemoteAddr() + " " + req.getRemoteHost());

    // Read the request
    String inputString = "";

    try (BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); ) {
      String line;
      StringBuffer sb = new StringBuffer();
      while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
      }
      br.close();
      inputString = sb.toString();

      // discard "request="
      if (inputString.startsWith("request=")) {
        inputString = inputString.substring(8, inputString.length());
        inputString = java.net.URLDecoder.decode(inputString, "UTF-8");
      }
    } catch (Exception e) {
      log.error("Exception reading input stream.", e);
    }

    ISirResponse sirResp = this.requestOperator.doPostOperation(inputString);
    return doResponse(sirResp);
  }
  @Test
  public void testInvokeNotAllowedRemoteAddr() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setRemoteAddr("not-allowed-internal-proxy");
    request.setRemoteHost("not-allowed-internal-proxy-host");
    request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request);

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertEquals(
        "x-forwarded-for must be unchanged", "140.211.11.130, proxy1, proxy2", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertNull("x-forwarded-by must be null", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "not-allowed-internal-proxy", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "not-allowed-internal-proxy-host", actualRemoteHost);
  }
  @Test
  public void testInvokeAllProxiesAreInternal() throws Exception {

    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.addHeader("x-forwarded-for", "140.211.11.130, 192.168.0.10, 192.168.0.11");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request);

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertNull("all proxies are internal, x-forwarded-for must be null", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertNull("all proxies are internal, x-forwarded-by must be null", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
  }
  @Test
  public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithDefaultValues()
      throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setSecure(true);
    request.setScheme("https");
    request.setHeader("x-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request);

    // VERIFY
    boolean actualSecure = actualRequest.isSecure();
    assertFalse(
        "request must be unsecured as header x-forwarded-proto said it is http", actualSecure);

    String actualScheme = actualRequest.getScheme();
    assertEquals(
        "scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
  }
Exemplo n.º 13
0
  /** @see junit.framework.TestCase#setUp() */
  @Before
  public void setUp() throws Exception {
    super.setUp();
    trustedLoginFilter = new TrustedLoginFilter();
    when(componentManager.get(ServerConfigurationService.class))
        .thenReturn(serverConfigurationService);
    when(componentManager.get(SessionManager.class)).thenReturn(sessionManager);
    when(componentManager.get(UserDirectoryService.class)).thenReturn(userDirectoryService);
    when(serverConfigurationService.getBoolean(
            TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_ENABLED, true))
        .thenReturn(true);
    when(serverConfigurationService.getString(
            TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_SHARED_SECRET, null))
        .thenReturn("e2KS54H35j6vS5Z38nK40");
    when(serverConfigurationService.getString(
            TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_SAFE_HOSTS,
            trustedLoginFilter.safeHosts))
        .thenReturn(trustedLoginFilter.safeHosts);
    when(request.getRemoteHost()).thenReturn("localhost");
    when(request.getHeader("x-sakai-token"))
        .thenReturn("sw9TTTqlEbGQkELqQuQPq92ydr4=;username;nonce");
    // default to non-existing session to exercise more code
    when(existingSession.getUserEid()).thenReturn(null);
    when(sessionManager.getCurrentSession()).thenReturn(existingSession);
    when(sessionManager.startSession()).thenReturn(newSession);
    when(user.getEid()).thenReturn("username");
    when(user.getId()).thenReturn("uuid1234567890");
    when(userDirectoryService.getUserByEid("username")).thenReturn(user);

    trustedLoginFilter.setupTestCase(componentManager);
    trustedLoginFilter.init(config);
  }
Exemplo n.º 14
0
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   try {
     String password = WebUtils.getCleanParam(request, PASSWORD);
     String username = WebUtils.getCleanParam(request, USERNAME);
     boolean rememberMe = WebUtils.isTrue(request, REMEMBER_ME);
     String host = request.getRemoteHost();
     UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe, host);
     try {
       Subject subject = SecurityUtils.getSubject();
       loginWithNewSession(token, subject);
       // subject.login(token);
       issueJson(response, HTTP_STATUS_OK, MESSAGE, "ok");
     } catch (AuthenticationException e) {
       issue(
           MIME_TEXT_PLAIN,
           HTTP_STATUS_NOT_FOUND,
           "cannot authorize " + username + ": " + e.getMessage(),
           response);
     }
   } catch (Exception e) {
     issue(
         MIME_TEXT_PLAIN,
         HTTP_STATUS_INTERNAL_SERVER_ERROR,
         "Internal error: " + e.getMessage(),
         response);
   }
 }
Exemplo n.º 15
0
  protected void _init(PageContext pc, Map<String, String> arguments) {
    this.pc = pc;

    // header
    HttpServletRequest req = pc.getHttpServletRequest();

    header = new StringBuffer();
    createHeader(header, "context-path", req.getContextPath());
    createHeader(header, "remote-user", req.getRemoteUser());
    createHeader(header, "remote-addr", req.getRemoteAddr());
    createHeader(header, "remote-host", req.getRemoteHost());
    createHeader(
        header,
        "script-name",
        StringUtil.emptyIfNull(req.getContextPath())
            + StringUtil.emptyIfNull(req.getServletPath()));
    createHeader(header, "server-name", req.getServerName());
    createHeader(header, "protocol", req.getProtocol());
    createHeader(header, "server-port", Caster.toString(req.getServerPort()));
    createHeader(
        header,
        "path-info",
        StringUtil.replace(
            StringUtil.emptyIfNull(req.getRequestURI()),
            StringUtil.emptyIfNull(req.getServletPath()),
            "",
            true));
    // createHeader(header,"path-translated",pc.getBasePageSource().getDisplayPath());
    createHeader(header, "query-string", req.getQueryString());
    createHeader(header, "unit", unitShortToString(unit));
    createHeader(header, "min-time-nano", min + "");

    content = new StringBuffer();

    // directory
    String strDirectory = arguments.get("directory");
    if (dir == null) {
      if (StringUtil.isEmpty(strDirectory)) {
        dir = getTemp(pc);
      } else {
        try {
          dir = ResourceUtil.toResourceNotExisting(pc, strDirectory, false);
          if (!dir.exists()) {
            dir.createDirectory(true);
          } else if (dir.isFile()) {
            err(
                pc,
                "can not create directory [" + dir + "], there is already a file with same name.");
          }
        } catch (Throwable t) {
          err(pc, t);
          dir = getTemp(pc);
        }
      }
    }
    file = dir.getRealResource((pc.getId()) + "-" + CreateUUID.call(pc) + ".exl");
    file.createNewFile();
    start = System.currentTimeMillis();
  }
Exemplo n.º 16
0
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) {

    JSONObject response = new JSONObject();
    response.put("host", req.getRemoteHost());
    response.put("address", req.getRemoteAddr());
    return response;
  }
Exemplo n.º 17
0
 private void initResult(HttpServletRequest request, JUnitResult result) {
   result.setAgent(request.getHeader("User-Agent"));
   result.setHost(request.getRemoteHost());
   Throwable throwable = result.getException();
   if (throwable != null) {
     deobfuscateStackTrace(throwable);
   }
 }
Exemplo n.º 18
0
 /**
  * Test method for {@link
  * org.sakaiproject.hybrid.util.TrustedLoginFilter#doFilter(javax.servlet.ServletRequest,
  * javax.servlet.ServletResponse, javax.servlet.FilterChain)} .
  *
  * @throws ServletException
  * @throws IOException
  */
 @Test
 public void testDoFilterUnsafeHost() throws IOException, ServletException {
   when(request.getRemoteHost()).thenReturn("big.bad.hacker.com");
   trustedLoginFilter.doFilter(request, response, chain);
   verify(sessionManager, never()).startSession();
   verify(sessionManager, never()).setCurrentSession(newSession);
   verify(sessionManager, never()).setCurrentSession(existingSession);
   verify(chain).doFilter(request, response);
 }
Exemplo n.º 19
0
  /*
   * While pinning files this requestId value "qos" will be stored for the pin.
   * Storing requestId insures the possibility to filter files being pinned by Qos or SRM.
   */
  public void pin(FileAttributes fileAttributes, CellStub cellStub) throws URISyntaxException {

    HttpProtocolInfo protocolInfo =
        new HttpProtocolInfo(
            "Http",
            1,
            1,
            new InetSocketAddress(request.getRemoteHost(), 0),
            null,
            null,
            null,
            new URI("http", request.getRemoteHost(), null, null));

    PinManagerPinMessage message =
        new PinManagerPinMessage(fileAttributes, protocolInfo, requestId, -1);

    cellStub.notify(message);
  }
  @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
  public @ResponseBody Error save(@RequestBody Error error, HttpServletRequest request) {
    error.setIp(request.getRemoteAddr());
    error.setHostname(request.getRemoteHost());
    error.setAgent(request.getHeader("User-Agent"));
    error.setTimestamp(new Date());

    return this.errorService.save(error);
  }
Exemplo n.º 21
0
  /**
   * Build a InMessage from an HttpServletrequest
   *
   * @param request The HttpservletRequest
   */
  public InMessage(HttpServletRequest request) {

    // TODO : Check this code : WSDL request are not well recorded !
    this.method = request.getMethod();
    // Set the headers
    this.headers = new Headers();
    Enumeration<String> headerNameEnum = request.getHeaderNames();
    while (headerNameEnum.hasMoreElements()) {
      String headerName = headerNameEnum.nextElement();
      this.headers.addHeader(new Header(headerName, request.getHeader(headerName)));
    }
    // Set protocol, server, port, path
    this.protocol = request.getProtocol().substring(0, request.getProtocol().indexOf('/'));
    this.protocolVersion = request.getProtocol().substring(request.getProtocol().indexOf('/') + 1);
    this.server = request.getServerName();
    this.port = request.getServerPort();
    this.path = request.getRequestURI();
    this.remoteHost = request.getRemoteHost();
    // this.completeUrl = request.getRequestURL().toString();
    // Set url parameters
    this.queryString = new QueryString();
    Enumeration<String> parametersNameEnum = request.getParameterNames();
    while (parametersNameEnum.hasMoreElements()) {
      String parameterName = parametersNameEnum.nextElement();
      for (String parameterValue : request.getParameterValues(parameterName)) {
        this.queryString.addQueryParam(new QueryParam(parameterName, parameterValue));
      }
    }
    this.messageContent = new MessageContent();
    StringBuffer requestBody = new StringBuffer();
    BufferedReader requestBodyReader = null;
    CharBuffer buffer = CharBuffer.allocate(512);
    try {
      requestBodyReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
      while (requestBodyReader.read(buffer) >= 0) {
        requestBody.append(buffer.flip());
        buffer.clear();
      }
      this.messageContent.setRawContent(requestBody.toString());
      this.messageContent.setSize(requestBody.length());
      this.messageContent.setMimeType(request.getContentType());
    } catch (Exception ex) {
      logger.warn("Error while reading request body !", ex);
    } finally {
      try {
        if (requestBodyReader != null) {
          requestBodyReader.close();
        }
      } catch (IOException ex) {
        // logger.warn("Error while closing the requestBodyReader !",
        // ex);
      }
    }
    this.comment = "";
  }
  /*
   * Test {@link RemoteIpFilter} in Tomcat standalone server
   */
  @Test
  public void testWithTomcatServer() throws Exception {

    // mostly default configuration : enable "x-forwarded-proto"
    Map<String, String> remoteIpFilterParameter = new HashMap<>();
    remoteIpFilterParameter.put("protocolHeader", "x-forwarded-proto");

    // SETUP
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);

    FilterDef filterDef = new FilterDef();
    filterDef.getParameterMap().putAll(remoteIpFilterParameter);
    filterDef.setFilterClass(RemoteIpFilter.class.getName());
    filterDef.setFilterName(RemoteIpFilter.class.getName());

    root.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(RemoteIpFilter.class.getName());
    filterMap.addURLPattern("*");
    root.addFilterMap(filterMap);

    MockHttpServlet mockServlet = new MockHttpServlet();

    Tomcat.addServlet(root, mockServlet.getClass().getName(), mockServlet);
    root.addServletMapping("/test", mockServlet.getClass().getName());

    getTomcatInstance().start();

    // TEST
    HttpURLConnection httpURLConnection =
        (HttpURLConnection)
            new URL("http://localhost:" + tomcat.getConnector().getLocalPort() + "/test")
                .openConnection();
    String expectedRemoteAddr = "my-remote-addr";
    httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
    httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

    // VALIDATE

    Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
    HttpServletRequest request = mockServlet.getRequest();
    Assert.assertNotNull(request);

    // VALIDATE X-FOWARDED-FOR
    Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
    Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

    // VALIDATE X-FORWARDED-PROTO
    Assert.assertTrue(request.isSecure());
    Assert.assertEquals("https", request.getScheme());
    Assert.assertEquals(443, request.getServerPort());
  }
Exemplo n.º 23
0
  private void processOpen(
      String aSessionId, String aConnectorId, HttpServletRequest aReq, HttpServletResponse aResp)
      throws IOException {
    try {
      String lOrigin = aReq.getScheme() + "://" + aReq.getRemoteHost();
      if (!EngineUtils.isOriginValid(lOrigin, mEngine.getConfiguration().getDomains())) {
        sendMessage(401, "Origin not allowed!", aResp);
        return;
      }

      mConnectorsManager.add(aSessionId, aConnectorId);
      HTTPConnector lConnector = getConnector(aConnectorId, aReq, aResp);
      lConnector.setRemoteHost(InetAddress.getByName(aReq.getRemoteHost()));

      // starting connector on request thread intentionally
      lConnector.startConnector();
    } catch (Exception lEx) {
      sendMessage(500, lEx.getLocalizedMessage(), aResp);
    }
  }
Exemplo n.º 24
0
 public void autoSetLocation(HttpServletRequest request) {
   DbDao db = new DbDao();
   System.out.println("RemAddr: " + request.getRemoteAddr());
   System.out.println("RemHost: " + request.getRemoteHost());
   String ipAddress = request.getRemoteAddr();
   location = null; // db.getLocationByIp("24.68.70.242");
   if (location == null) {
     int[] tempLoc = {-1, -1, -1, -1};
     location = tempLoc;
   }
 }
Exemplo n.º 25
0
  @Override
  public String getRemoteHost() {
    HttpServletRequest request = (HttpServletRequest) getRequest();
    String headerValue;

    headerValue = request.getHeader(headerPrefix + "REMOTE_HOST");
    if (headerValue != null) {
      return headerValue;
    } else {
      return request.getRemoteHost();
    }
  }
Exemplo n.º 26
0
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String action = request.getParameter("action");
    String name = request.getParameter("name");

    String redirect = "/user.jsp?name=" + name;
    Client client = ClientRepository.getInstance().getClient(name);

    if ("kick".equals(action)) {
      logger.info(
          client.getUser().getName()
              + " ("
              + client.getInetAddress()
              + ") has been kicked by "
              + request.getRemoteUser()
              + " ("
              + request.getRemoteHost()
              + ")");
    } else if ("ban".equals(action)) {
      Banlist banlist = Banlist.getInstance();
      banlist.ban(client.getInetAddress().getHostAddress());

      logger.info(
          client.getUser().getName()
              + " ("
              + client.getInetAddress()
              + ") has been banned by "
              + request.getRemoteUser()
              + " ("
              + request.getRemoteHost()
              + ")");

      // save the server configuration
      Server.getInstance().getConfig().save();
    }

    client.disconnect();

    response.sendRedirect("/channel.jsp?name=" + client.getChannel().getConfig().getName());
  }
Exemplo n.º 27
0
 private UserGroup getIpGroup(HttpServletRequest request) {
   UserGroup ipUserGroup = null;
   HttpSession session = ((HttpServletRequest) request).getSession(true);
   if (session.getAttribute("isIpGroupChecked") == null) {
     ipUserGroup = groupService.findIpGroupUser(request.getRemoteHost());
     if (ipUserGroup != null) {
       session.setAttribute("ipUserGroup", ipUserGroup);
       session.setAttribute("isIpGroupChecked", true);
     }
   } else {
     ipUserGroup = (UserGroup) session.getAttribute("ipUserGroup");
   }
   return ipUserGroup;
 }
Exemplo n.º 28
0
  HTTPConnector getConnector(
      String aConnectorId,
      HttpServletRequest aReq,
      HttpServletResponse aResp,
      boolean aStartupConnection)
      throws Exception {
    HTTPConnector lConnector =
        (HTTPConnector) mConnectorsManager.getConnectorById(aConnectorId, aStartupConnection);
    lConnector.setRemoteHost(InetAddress.getByName(aReq.getRemoteHost()));
    lConnector.setSSL(aReq.getScheme().equals("https"));
    lConnector.setHttpResponse(aResp);

    return lConnector;
  }
Exemplo n.º 29
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
    resp.setHeader("Pragma", "no-cache");
    resp.setDateHeader("Expires", 0);
    resp.setContentType("text/html; charset=UTF-8");

    if (API.allowedBotHosts != null && !API.allowedBotHosts.contains(req.getRemoteHost())) {
      resp.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    try (PrintWriter writer = resp.getWriter()) {
      writer.print(header1);
      writer.print(buildLinks(req));
      writer.print(header2);
      String requestType = Convert.nullToEmpty(req.getParameter("requestType"));
      APIServlet.APIRequestHandler requestHandler = APIServlet.apiRequestHandlers.get(requestType);
      StringBuilder bufJSCalls = new StringBuilder();
      if (requestHandler != null) {
        writer.print(
            form(
                requestType,
                true,
                requestHandler.getClass().getName(),
                requestHandler.getParameters(),
                requestHandler.requirePost()));
        bufJSCalls.append("apiCalls.push(\"").append(requestType).append("\");\n");
      } else {
        String requestTag = Convert.nullToEmpty(req.getParameter("requestTag"));
        Set<String> taggedTypes = requestTags.get(requestTag);
        for (String type : (taggedTypes != null ? taggedTypes : allRequestTypes)) {
          requestHandler = APIServlet.apiRequestHandlers.get(type);
          writer.print(
              form(
                  type,
                  false,
                  requestHandler.getClass().getName(),
                  APIServlet.apiRequestHandlers.get(type).getParameters(),
                  APIServlet.apiRequestHandlers.get(type).requirePost()));
          bufJSCalls.append("apiCalls.push(\"").append(type).append("\");\n");
        }
      }
      writer.print(footer1);
      writer.print(bufJSCalls.toString());
      writer.print(footer2);
    }
  }
Exemplo n.º 30
0
 public static String getIpAddr(HttpServletRequest request) {
   String ip = request.getHeader("x-forwarded-for");
   if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
     return ip;
   } else if (null != request.getHeader("Proxy-Client-IP")
       && request.getHeader("Proxy-Client-IP").length() > 0
       && !"unknown".equalsIgnoreCase(request.getHeader("Proxy-Client-IP"))) {
     return request.getHeader("Proxy-Client-IP");
   } else if (null != request.getHeader("WL-Proxy-Client-IP")
       && request.getHeader("WL-Proxy-Client-IP").length() > 0
       && !"unknown".equalsIgnoreCase(request.getHeader("WL-Proxy-Client-IP"))) {
     return request.getHeader("WL-Proxy-Client-IP");
   } else {
     return request.getRemoteHost();
   }
 }