会话cookie中缺少HttpOnly属性详解编程语言

项目经第三方机构进行安全扫描漏洞出现“会话cookie中缺少HttpOnly属性”问题

安全风险

可能会窃取或操纵客户会话和 cookie,它们可能用于模仿合法用户,从而使黑客能够以该用户身份查看或变更用户记录以及执行事务

可能原因

Web 应用程序设置了缺少 HttpOnly 属性的会话 cookie

技术描述

在应用程序测试过程中,检测到所测试的 Web 应用程序设置了不含“HttpOnly”属性的会话 cookie。由于此会话 cookie 不包含“HttpOnly”属性,因此注入站点的恶意脚本可能访问此 cookie,并窃取它的值。任何存储在会话令牌中的信息都可能被窃取,并在稍后用于身份盗窃或用户伪装。

解决方法加入一个拦截器即可:

package com.base.servlet; 
 
import java.io.IOException; 
 
import java.text.SimpleDateFormat; 
 
import java.util.Calendar; 
import java.util.Date; 
import java.util.Locale; 
 
import javax.servlet.Filter; 
import javax.servlet.FilterChain; 
import javax.servlet.FilterConfig; 
import javax.servlet.ServletException; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
 
/** 
 * 解决检测到会话 cookie 中缺少 HttpOnly 属性 
 * 
 */ 
public class CookieHttpOnlyFilter implements Filter { 
    public void destroy() { 
    } 
 
    public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain filterChain) throws IOException, ServletException { 
        // TODO Auto-generated method stub 
        HttpServletRequest req = (HttpServletRequest) request; 
        HttpServletResponse resp = (HttpServletResponse) response; 
        Cookie[] cookies = req.getCookies(); 
 
        if (cookies != null) { 
            for (Cookie cookie : cookies) { 
                String value = cookie.getValue(); 
                StringBuilder builder = new StringBuilder(); 
                builder.append("JSESSIONID=" + value + "; "); 
                builder.append("Secure; "); 
                builder.append("HttpOnly; "); 
 
                Calendar cal = Calendar.getInstance(); 
                cal.add(Calendar.HOUR, 1); 
 
                Date date = cal.getTime(); 
                Locale locale = Locale.CHINA; 
                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", 
                        locale); 
                builder.append("Expires=" + sdf.format(date)); 
                resp.setHeader("Set-Cookie", builder.toString()); 
            } 
 
            filterChain.doFilter(request, response); 
        } 
    } 
 
    public void init(FilterConfig arg0) throws ServletException { 
        // TODO Auto-generated method stub 
    } 
}

然后在配置文件web.xml中进行配置

<filter> 
    <filter-name>cookieHttpOnlyFilter</filter-name> 
    <filter-class>com.base.servlet.CookieHttpOnlyFilter</filter-class> 
</filter> 
 
<filter-mapping> 
    <filter-name>cookieHttpOnlyFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/14211.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论