Java Code Examples for javax.servlet.ServletRequest#getRemoteAddr()

The following examples show how to use javax.servlet.ServletRequest#getRemoteAddr() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogsearchTrustedProxyFilter.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  boolean skip = true;
  if (authPropsConfig.isTrustedProxy() && !isAuthenticated(authentication) ) {
    String doAsUserName = req.getParameter("doAs");
    String remoteAddr = req.getRemoteAddr();
    if (StringUtils.isNotEmpty(doAsUserName) && isTrustedProxySever(remoteAddr)
      && isTrustedHost(getXForwardHeader((HttpServletRequest) req))) {
      List<GrantedAuthority> grantedAuths = RoleDao.createDefaultAuthorities();
      if (!(isTrustedProxyUser(doAsUserName) || isTrustedProxyUserGroup(grantedAuths))) {
        skip = false;
      }
    }
  }
  if (skip) {
    chain.doFilter(req, res);
    return;
  }
  super.doFilter(req, res, chain);
}
 
Example 2
Source File: HostnameFilter.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves the requester hostname and delegates the request to the chain.
 * <p>
 * The requester hostname is available via the {@link #get} method.
 *
 * @param request servlet request.
 * @param response servlet response.
 * @param chain filter chain.
 *
 * @throws IOException thrown if an IO error occurrs.
 * @throws ServletException thrown if a servet error occurrs.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {
  try {
    String hostname;
    try {
      String address = request.getRemoteAddr();
      if (address != null) {
        hostname = InetAddress.getByName(address).getCanonicalHostName();
      } else {
        log.warn("Request remote address is NULL");
        hostname = "???";
      }
    } catch (UnknownHostException ex) {
      log.warn("Request remote address could not be resolved, {0}", ex.toString(), ex);
      hostname = "???";
    }
    HOSTNAME_TL.set(hostname);
    chain.doFilter(request, response);
  } finally {
    HOSTNAME_TL.remove();
  }
}
 
Example 3
Source File: HostnameFilter.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves the requester hostname and delegates the request to the chain.
 * <p>
 * The requester hostname is available via the {@link #get} method.
 *
 * @param request servlet request.
 * @param response servlet response.
 * @param chain filter chain.
 *
 * @throws IOException thrown if an IO error occurrs.
 * @throws ServletException thrown if a servet error occurrs.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {
  try {
    String hostname;
    try {
      String address = request.getRemoteAddr();
      if (address != null) {
        hostname = InetAddress.getByName(address).getCanonicalHostName();
      } else {
        log.warn("Request remote address is NULL");
        hostname = "???";
      }
    } catch (UnknownHostException ex) {
      log.warn("Request remote address could not be resolved, {0}", ex.toString(), ex);
      hostname = "???";
    }
    HOSTNAME_TL.set(hostname);
    chain.doFilter(request, response);
  } finally {
    HOSTNAME_TL.remove();
  }
}
 
Example 4
Source File: BlackListedIpFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // If Dropwizard HTTPConfiguration.useForwardedHeaders is set (as it is by default) then
    // request.getRemoteAddr() will be the X-Forwarded-For header set by Amazon ELB, if present.
    String userIpAddress = request.getRemoteAddr();

    // Skip the blacklist check if the IP addresses might be an illegal key for the ZK blacklist.
    if (userIpAddress != null && isBlackListed(userIpAddress))  {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                String.format("Requesting IP %s is blacklisted. Please try again later.", userIpAddress));
        return;
    }

    chain.doFilter(request, response);
}
 
Example 5
Source File: QueryIPRetriever.java    From micro-server with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	try {
		Optional<String> vipClientIP = getVipClientIP(request);
		if (vipClientIP.isPresent()) {
			ipAddress.set(vipClientIP.get());
		} else {
			String remoteAddr = request.getRemoteAddr();
			logger.debug( "remoteAddr: " + remoteAddr);
			ipAddress.set(remoteAddr);
		}
		chain.doFilter(request, response);
	} finally {
		ipAddress.remove();
	}
}
 
Example 6
Source File: ClientIpResolver.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public static String getClientIp(final ServletRequest request)
{
  String remoteAddr = null;
  if (request instanceof HttpServletRequest) {
    remoteAddr = ((HttpServletRequest) request).getHeader("X-Forwarded-For");
  }
  if (remoteAddr != null) {
    if (remoteAddr.contains(",")) {
      // sometimes the header is of form client ip,proxy 1 ip,proxy 2 ip,...,proxy n ip,
      // we just want the client
      remoteAddr = Strings.split(remoteAddr, ',')[0].trim();
    }
    try {
      // If ip4/6 address string handed over, simply does pattern validation.
      InetAddress.getByName(remoteAddr);
    } catch (final UnknownHostException e) {
      remoteAddr = request.getRemoteAddr();
    }
  } else {
    remoteAddr = request.getRemoteAddr();
  }
  return remoteAddr;
}
 
Example 7
Source File: BonJwtFilter.java    From bootshiro with MIT License 5 votes vote down vote up
private AuthenticationToken createJwtToken(ServletRequest request) {

        Map<String,String> maps = RequestResponseUtil.getRequestHeaders(request);
        String appId = maps.get("appId");
        String ipHost = request.getRemoteAddr();
        String jwt = maps.get("authorization");
        String deviceInfo = maps.get("deviceInfo");

        return new JwtToken(ipHost,deviceInfo,jwt,appId);
    }
 
Example 8
Source File: JrpipServlet.java    From jrpip with Apache License 2.0 5 votes vote down vote up
private JrpipRequestContext getJrpipRequestContext(ServletRequest request, RequestId requestId)
{
    JrpipRequestContext requestContext = null;
    if (request instanceof HttpServletRequest && this.methodInterceptor != null)
    {
        requestContext = new JrpipRequestContext(
                requestId,
                ((HttpServletRequest) request).getRemoteUser(),
                request.getRemoteAddr(),
                ((HttpServletRequest) request).getCookies());
    }
    return requestContext;
}
 
Example 9
Source File: HttpRequestUtil.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
public static String getClientString(ServletRequest request) {
    String remoteHost = request.getRemoteHost();
    String remoteAddr = request.getRemoteAddr();
    String result =  "Client " + remoteHost;
    if (!remoteAddr.equals(remoteHost)) {
        result = result + " (" + remoteAddr + ")";
    }
    return result;
}
 
Example 10
Source File: ContactController.java    From podcastpedia-web with MIT License 5 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public String processContactForm(
			@ModelAttribute("contactForm") ContactForm contactForm,
			BindingResult result, 
			Model model,
               @RequestParam("recaptcha_challenge_field") String challangeField,
               @RequestParam("recaptcha_response_field") String responseField,
               ServletRequest servletRequest, SessionStatus sessionStatus
	){
	
	LOG.debug("------ processContactForm : form is being validated and processed -----");
	contactFormValidator.validate(contactForm, result);

       String remoteAddress = servletRequest.getRemoteAddr();
       ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(
               remoteAddress, challangeField, responseField);

	if(!result.hasErrors() && reCaptchaResponse.isValid()){
		contactService.sendContactMessage(contactForm);
       	emailNotificationService.sendContactNotification(contactForm);
           sessionStatus.setComplete();

       	return "redirect:/contact?tks=true";			
	} else {
		List<String> topics = Utilities.getDisplayValues(ContactTopicType.class);
		model.addAttribute("topics", topics);			
		model.addAttribute("contactForm", contactForm);
           if (!reCaptchaResponse.isValid()) {
               result.rejectValue("invalidRecaptcha", "invalid.captcha");
               model.addAttribute("invalidRecaptcha", true);
           }
   		
		return "contact_form_def";	
	}		
	
}
 
Example 11
Source File: SuggestPodcastController.java    From podcastpedia-web with MIT License 5 votes vote down vote up
/**
 * 
 * @param addPodcastFormData
 * @param result
 * @param model
 * @param servletRequest
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String processAddPodcastForm(
		@ModelAttribute("addPodcastForm") SuggestedPodcast addPodcastFormData,
		BindingResult result, Model model,
		@RequestParam("recaptcha_challenge_field") String challangeField,
		@RequestParam("recaptcha_response_field") String responseField,
		ServletRequest servletRequest, SessionStatus sessionStatus) {

	LOG.debug("------ processAddPodcastForm : form is being validated and processed -----");
	suggestPodcastValidator.validate(addPodcastFormData, result);

	String remoteAddress = servletRequest.getRemoteAddr();
	ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(
			remoteAddress, challangeField, responseField);

	if (reCaptchaResponse.isValid() && !result.hasErrors()) {

		userInteractionService.addSuggestedPodcast(addPodcastFormData);
		emailNotificationService
				.sendSuggestPodcastNotification(addPodcastFormData);
		sessionStatus.setComplete();

		return "redirect:/how_can_i_help/add_podcast?tks=true";
	} else {
		model.addAttribute("addPodcastForm", addPodcastFormData);
		if (!reCaptchaResponse.isValid()) {
			result.rejectValue("invalidRecaptcha", "invalid.captcha");
			model.addAttribute("invalidRecaptcha", true);
		}
		return "add_podcast_form_def";
	}

}
 
Example 12
Source File: GatewayFilter.java    From knox with Apache License 2.0 5 votes vote down vote up
private String getRemoteAddress(ServletRequest servletRequest) {
  GatewayConfig gatewayConfig =
      (GatewayConfig) servletRequest.getServletContext().
      getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);

  String addrHeaderName = gatewayConfig.getHeaderNameForRemoteAddress();
  String addr = ((HttpServletRequest)servletRequest).getHeader(addrHeaderName);
  if (addr == null || addr.trim().isEmpty()) {
    addr = servletRequest.getRemoteAddr();
  }
  return addr;
}
 
Example 13
Source File: DoSFilter.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
private boolean isBanned(ServletRequest request) {
  String remoteIPAddressString = request.getRemoteAddr();
  if (bannedIPAddresses.contains(remoteIPAddressString)) {
    return true;
  }
  AtomicInteger count = numRecentAccesses.putIfAbsent(remoteIPAddressString, new AtomicInteger(0));
  if (count.incrementAndGet() > maxAccessPerHostPerMin) {
    bannedIPAddresses.add(remoteIPAddressString);
    return true;
  }
  return false;
}
 
Example 14
Source File: IdentityFilter.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    // Only require authentication from an identity provider if the NiFi registry is running securely.
    if (!servletRequest.isSecure()) {
        // Otherwise, requests will be "authenticated" by the AnonymousIdentityFilter
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (identityProvider == null) {
        logger.warn("Identity Filter configured with NULL identity provider. Credentials will not be extracted.");
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (credentialsAlreadyPresent()) {
        logger.debug("Credentials already extracted for [{}], skipping credentials extraction filter using {}",
                SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(),
                identityProvider.getClass().getSimpleName());
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    logger.debug("Attempting to extract user credentials using {}", identityProvider.getClass().getSimpleName());

    try {
        AuthenticationRequest authenticationRequest = identityProvider.extractCredentials((HttpServletRequest)servletRequest);
        if (authenticationRequest != null) {
            Authentication authentication = new AuthenticationRequestToken(authenticationRequest, identityProvider.getClass(), servletRequest.getRemoteAddr());
            logger.debug("Adding credentials claim to SecurityContext to be authenticated. Credentials extracted by {}: {}",
                    identityProvider.getClass().getSimpleName(),
                    authenticationRequest);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // This filter's job, which is merely to search for and extract an identity claim, is done.
            // The actual authentication of the identity claim will be handled by a corresponding IdentityAuthenticationProvider
        }
    } catch (Exception e) {
        logger.debug("Exception occurred while extracting credentials:", e);
    }

    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 15
Source File: RangerPDPKnoxFilter.java    From ranger with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {

	String sourceUrl = (String) request
			.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
	String topologyName = getTopologyName(sourceUrl);
	String serviceName = getServiceName();

	RangerPerfTracer perf = null;

	if(RangerPerfTracer.isPerfTraceEnabled(PERF_KNOXAUTH_REQUEST_LOG)) {
		perf = RangerPerfTracer.getPerfTracer(PERF_KNOXAUTH_REQUEST_LOG, "RangerPDPKnoxFilter.doFilter(url=" + sourceUrl + ", topologyName=" + topologyName + ")");
	}

	Subject subject = Subject.getSubject(AccessController.getContext());

	Principal primaryPrincipal = (Principal) subject.getPrincipals(
			PrimaryPrincipal.class).toArray()[0];
	String primaryUser = primaryPrincipal.getName();

	String impersonatedUser = null;
	Object[] impersonations = subject.getPrincipals(
			ImpersonatedPrincipal.class).toArray();
	if (impersonations != null && impersonations.length > 0) {
		impersonatedUser = ((Principal) impersonations[0]).getName();
	}

	String user = (impersonatedUser != null) ? impersonatedUser
			: primaryUser;
	if (LOG.isDebugEnabled()) {
		LOG.debug("Checking access primaryUser: " + primaryUser + ", impersonatedUser: "
				+ impersonatedUser + ", effectiveUser: " + user);
	}

	Object[] groupObjects = subject.getPrincipals(GroupPrincipal.class)
			.toArray();
	Set<String> groups = new HashSet<String>();
	for (Object obj : groupObjects) {
		groups.add(((Principal) obj).getName());
	}

	String clientIp = request.getRemoteAddr();
	List<String> forwardedAddresses = getForwardedAddresses(request);

	if (LOG.isDebugEnabled()) {
		LOG.debug("Checking access primaryUser: " + primaryUser
				+ ", impersonatedUser: " + impersonatedUser
				+ ", effectiveUser: " + user + ", groups: " + groups
				+ ", clientIp: " + clientIp + ", remoteIp: " + clientIp + ", forwardedAddresses: " + forwardedAddresses);
	}

	RangerAccessRequest accessRequest = new RequestBuilder()
		.service(serviceName)
		.topology(topologyName)
		.user(user)
		.groups(groups)
		.clientIp(clientIp)
		.remoteIp(clientIp)
		.forwardedAddresses(forwardedAddresses)
		.build();

	boolean accessAllowed = false;

	if (plugin != null) {
		RangerAccessResult result = plugin.isAccessAllowed(accessRequest);

		accessAllowed = result != null && result.getIsAllowed();
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("Access allowed: " + accessAllowed);
	}

	RangerPerfTracer.log(perf);

	if (accessAllowed) {
		chain.doFilter(request, response);
	} else {
		sendForbidden((HttpServletResponse) response);
	}
}
 
Example 16
Source File: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void doFilter(ContainerRequestContext context, Message m) {
    if (!"GET".equals(m.get(Message.HTTP_REQUEST_METHOD))) {
        return;
    }

    UriInfo ui = context.getUriInfo();
    if (!ui.getQueryParameters().containsKey(WADL_QUERY)) {
        if (stylesheetReference != null || !docLocationMap.isEmpty()) {
            String path = ui.getPath(false);
            if (path.startsWith("/") && path.length() > 0) {
                path = path.substring(1);
            }
            if (stylesheetReference != null && path.endsWith(".xsl")
                || docLocationMap.containsKey(path)) {
                context.abortWith(getExistingResource(m, ui, path));
            }
        }
        return;
    }

    if (ignoreRequests) {
        context.abortWith(Response.status(404).build());
        return;
    }

    if (whiteList != null && !whiteList.isEmpty()) {
        ServletRequest servletRequest = (ServletRequest)m.getContextualProperty(
            "HTTP.REQUEST");
        String remoteAddress = null;
        if (servletRequest != null) {
            remoteAddress = servletRequest.getRemoteAddr();
        } else {
            remoteAddress = "";
        }
        boolean foundMatch = false;
        for (String addr : whiteList) {
            if (addr.equals(remoteAddress)) {
                foundMatch = true;
                break;
            }
        }
        if (!foundMatch) {
            context.abortWith(Response.status(404).build());
            return;
        }
    }

    HttpHeaders headers = new HttpHeadersImpl(m);
    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    MediaType type = accepts.contains(WADL_TYPE) ? WADL_TYPE : accepts
        .contains(MediaType.APPLICATION_JSON_TYPE) ? MediaType.APPLICATION_JSON_TYPE
            : defaultWadlResponseMediaType;

    Response response = getExistingWadl(m, ui, type);
    if (response != null) {
        context.abortWith(response);
        return;
    }

    boolean isJson = isJson(type);

    StringBuilder sbMain = generateWADL(getBaseURI(m, ui), getResourcesList(m, ui), isJson, m, ui);

    m.getExchange().put(JAXRSUtils.IGNORE_MESSAGE_WRITERS, !isJson && ignoreMessageWriters);
    Response r = Response.ok().type(type).entity(createResponseEntity(m, ui, sbMain.toString(), isJson)).build();
    context.abortWith(r);
}