2023年12月1日发(作者:)

CORS跨域漏洞修复

漏洞介绍

概述:CORS,跨域资源共享(Cross-origin resource sharing),是H5提供的⼀种机制,WEB应⽤程序可以通过在HTTP增加字段来告诉

浏览器,哪些不同来源的服务器是有权访问本站资源的,当不同域的请求发⽣时,就出现了跨域的现象。当该配置不当的时候,就导致资源

被恶意操作

潜在危害:中

测试⽅法

1、可以通过浏览器的控制台的network,查看接⼝的请求包response头中Access-Control-Allow-Origin是否设置为*

2 也可以通过抓包⼯具,查看接⼝返回的response中是Access-Control-Allow-Origin是否设置为*

漏洞案例

1、配置Access-Control-Allow-Origin *

2、配置Access-Control-Allow-Origin 但是该值可控

修复⽅案

tomcat CORS的配置

使⽤过滤器进⾏配置,代码如下:

package filter;

import ption;

import ortedEncodingException;

import eDigest;

import AlgorithmException;

import ;

import ;

import Chain;

import Config;

import tException;

import tRequest;

import tResponse;

import ter;

import rvletRequest;

import rvletResponse;

import ception;

@WebFilter("/Cors")

public class CorsFilter implements Filter {

/**

* Default constructor.

*/

public FilterConfig config;

public CorsFilter() {

// TODO Auto-generated constructor stub

}

/**

* @see Filter#destroy()

*/

public void destroy() {

// TODO Auto-generated method stub

this.config = null;

}

/**

* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)

*/

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

//配置可信域名

String[] authhosts = {":8008",""};

String authost = "";

HttpServletRequest httprequest = (HttpServletRequest) request;

String origin = der("origin");

HttpServletResponse httpresponse = (HttpServletResponse) response;

if(origin != null && !(authhosts).contains(origin)) {

ror(403);

return;

}

else {

for(int i=0;i<;i++) {

if(i!= - 1) {

authost = authost + authhosts[i]+",";

}else {

authost = authost + authhosts[i];

}

nginx CORS配置

ocation / {

set $flag 0;

if ($http_origin = '')

{

set $flag "${flag}1";

}

if ($http_origin !~* ^(http|https)://$){

set $flag "${flag}1";

}

if ($flag = "01"){

return 403;

}

if ($http_origin ~* ^(http|https)://$) {

add_header Access-Control-Allow-Origin $http_origin;

add_header Access-Control-Allow-Methods GET,POST;

add_header Access-Control-Allow-Credentials true;

add_header Access-Control-Allow-Headers DNT,Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type;

}