插件窝 干货文章 Codeql如何分析cookie未启用httponly的问题

Codeql如何分析cookie未启用httponly的问题

Cookie HttpOnly 识别 hasQualifiedName 236    来源:    2025-04-24

使用CodeQL分析Cookie未启用HttpOnly的问题

HttpOnly是Cookie的一个重要安全属性,可以防止XSS攻击获取Cookie。下面介绍如何使用CodeQL来分析代码中未设置HttpOnly标志的Cookie。

基本分析思路

  1. 识别所有设置Cookie的代码位置
  2. 检查这些Cookie是否缺少HttpOnly标志
  3. 识别潜在的安全风险点

CodeQL查询示例

1. 识别Java Servlet中不安全的Cookie设置

import java

from Constructor call, MethodAccess setCookieCall
where
  call.getConstructedType().hasQualifiedName("javax.servlet.http", "Cookie") and
  setCookieCall.getMethod().getName() = "addCookie" and
  setCookieCall.getMethod().getDeclaringType().hasQualifiedName("javax.servlet.http", "HttpServletResponse") and
  not exists(FieldRead fr | 
    fr.getField().hasQualifiedName("javax.servlet.http", "Cookie", "setHttpOnly") and
    fr.getQualifier() = call
  )
select setCookieCall, "Cookie created here is missing HttpOnly flag"

2. 识别ASP.NET中不安全的Cookie设置

import csharp

from ObjectCreation cookieCreation, MethodAccess addCookieCall
where
  cookieCreation.getType().hasQualifiedName("System.Web", "HttpCookie") and
  addCookieCall.getMethod().getName() = "Add" and
  addCookieCall.getMethod().getDeclaringType().hasQualifiedName("System.Web", "HttpResponse") and
  not exists(PropertyAssignment pa |
    pa.getProperty().getName() = "HttpOnly" and
    pa.getTarget() = cookieCreation
  )
select addCookieCall, "Cookie created here is missing HttpOnly flag"

3. 识别Node.js Express中不安全的Cookie设置

import javascript

from CallExpr cookieCall
where
  (cookieCall.getCalleeName() = "cookie" or cookieCall.getCalleeName() = "setCookie") and
  not exists(Obj obj |
    obj = cookieCall.getArgument(1) and
    exists(PropWrite pw |
      pw.getObject() = obj and
      pw.getPropertyName() = "httpOnly" and
      pw.getValue().asExpr().getValue().toBoolean() = true
    )
  )
select cookieCall, "Cookie set here may be missing HttpOnly flag"

高级分析技巧

  1. 识别敏感Cookie:可以扩展查询来识别包含敏感信息(如session、token等)但未设置HttpOnly的Cookie
import java

from Constructor call, MethodAccess setCookieCall, string name
where
  call.getConstructedType().hasQualifiedName("javax.servlet.http", "Cookie") and
  setCookieCall.getMethod().getName() = "addCookie" and
  name = call.getArgument(0).(Literal).getValue() and
  (name.matches("%session%") or name.matches("%token%")) and
  not exists(FieldRead fr | 
    fr.getField().hasQualifiedName("javax.servlet.http", "Cookie", "setHttpOnly") and
    fr.getQualifier() = call
  )
select setCookieCall, "Sensitive cookie '"+name+"' is missing HttpOnly flag"
  1. 识别框架特定的Cookie设置方式:不同框架可能有不同的Cookie设置方式,需要针对性地分析

  2. 结合XSS漏洞分析:可以将HttpOnly缺失分析与XSS漏洞分析结合,找出最危险的组合

使用建议

  1. 将此类查询纳入持续集成流程,在代码提交时自动检查
  2. 对于遗留系统,可以先识别最敏感的Cookie(如会话Cookie)进行修复
  3. 结合其他安全标志(如Secure、SameSite)一起分析

通过CodeQL的这些查询,您可以系统地识别代码中所有未设置HttpOnly标志的Cookie,从而有针对性地加强应用程序的安全性。