Tornado-应用安全

这篇讲什么

  • Cookie 这一层:普通 cookie 怎么种、怎么读、怎么清,安全 cookie 的字符串长什么样、签名怎么挡住篡改,以及 expires_days 和 max_age_days 的区别。
  • XSRF 这一层:跨站请求伪造是怎么发生的,开启 xsrf_cookies 之后 token 从哪来、表单/请求头两种带法各自怎么过校验,以及 6.x 里怎么给某个接口豁免。
  • 登录这一层:get_current_user + @authenticated + login_url 的跳转细节,以及老笔记那套「用 URL 参数当登录态」的写法为什么不能要(含开放重定向的实测)。
  • 设置接口的真实签名(6.6 实测):

    1
    2
    set_cookie(name, value, domain=None, expires=None, path='/', expires_days=None, *,
    max_age=None, httponly=False, secure=False, samesite=None, **kwargs)
    • expires 可以传时间戳整数、time.gmtime() 那种元组、或 datetime,都是 UTC。
    • expires_days 是「从今天起多少天」的便捷写法,和 expires 同时给时以 expires 为准。
    • max_age / httponly / secure / samesite 是只能按关键字传的参数(老笔记的签名里还没有它们)。
    views/index.py
    1
    2
    3
    4
    5
    6
    7
    8
    class SetCookieHandler(RequestHandler):
    def get(self):
    self.set_cookie("sunck", "good")
    self.set_cookie("expdays", "x", expires_days=3)
    self.set_cookie("exp_ts", "y", expires=int(time.time()) + 3600)
    self.set_cookie("hronly", "z", httponly=True, samesite="Lax",
    secure=True, max_age=600)
    self.write("ok")

    实测下发的响应头:

    1
    2
    3
    4
    Set-Cookie: sunck="good"; Path=/
    Set-Cookie: expdays="x"; expires=Mon, 09 Nov 2026 ...; Path=/
    Set-Cookie: exp_ts="y"; expires=Fri, 06 Nov 2026 12:03:25 GMT; Path=/
    Set-Cookie: hronly="z"; Max-Age=600; Path=/; Expires=...; HttpOnly; Secure; SameSite=Lax
  • 原理就是 Set-Cookie 头,所以手写这个头也能种上,实测两种写法效果一样:

    1
    2
    self.set_cookie("kaige", "nice")
    self.set_header("Set-Cookie", "kaige=nice; Path=/")

    但推荐用 set_cookie:set_header 会覆盖同名头,一次只能种一个。

  • 读取与清除:

    1
    2
    3
    4
    5
    6
    get_cookie(name, default=None)          # 不存在时返回 default
    实测:带 Cookie: sunck=good -> sunck='good' default='未登录'
    不带任何 cookie -> sunck=None default='未登录'

    clear_cookie(name, path='/', domain=None)
    实测下发:Set-Cookie: sunck=""; expires=Thu, 06 Nov 2025 ...; Path=/
    • 老笔记那句「清除不是真删,是把值置空、期限设成过去」是对的,实测响应头就是空值 + 一年前的 expires。浏览器收到后才会在本地丢掉它;关闭浏览器清理的是会话 cookie(没写 expires/max-age 的那种)。
    • clear_all_cookies(path='/', domain=None) 是把服务端本次要下发的所有 cookie 都置空,不是把浏览器里所有 cookie 都删干净——浏览器还留着别的域、别的 path 的 cookie。
  • 有个容易撞的小坑:cookie 名不能用 httponly、expires、path、domain 这些保留字,实测 set_cookie("httponly", "z") 直接 http.cookies.CookieError: Attempt to set a reserved key 'httponly'。

  • 普通 cookie 客户端随便改,所以登录态不能直接存普通 cookie。Tornado 的 set_secure_cookie 会带上版本、时间戳和签名,实测种下去的值:

    views/index.py
    1
    2
    3
    4
    class SCookieHandler(RequestHandler):
    def get(self):
    self.set_secure_cookie("zhangmanyu", "nice")
    self.write("ok")
    1
    Set-Cookie: zhangmanyu="2|1:0|10:1793963026|10:zhangmanyu|8:bmljZQ==|b4949b01..."; expires=...; Path=/

    分段读法(| 分隔,除了签名那段,前面每段都是「长度:值」):

    • 2:安全 cookie 的格式版本,默认就是 2。
    • 1:0:签名密钥的版本号,1 是长度、0 是值(配合 cookie_secret 的 dict 形式做多版本轮换)。
    • 10:1793963026:签发时间戳(10 位)。
    • 10:zhangmanyu:cookie 名(10 位长)。
    • 8:bmljZQ==:base64 后的 cookie 值(nice → bmljZQ==)。
    • 最后那段不带长度的是签名。
  • 读回来是 bytes,不是 str,实测:

    1
    get_secure_cookie('zhangmanyu') -> type=bytes value=b'nice'

    所以要么 decode(),要么存的时候就用字符串再自己转。签名不过或过期都返回 None。

  • 篡改立刻被挡,实测把值里的 nice 换成 evil 再发回去:

    1
    2
    收到原始 cookie = '2|1:0|10:...|8:bmlj'(被截断的假值)
    get_secure_cookie(...) -> None
  • expires_days 与 max_age_days 是两回事,老笔记这点讲对了,补上实测:

    • set_secure_cookie(..., expires_days=30):浏览器里这个 cookie 存 30 天(默认 30)。
    • get_secure_cookie(..., max_age_days=31):服务端只接受时间戳在 31 天之内的 cookie(默认 31)。
    • 实测把 max_age_days 设成 0,刚签发的 cookie 也立刻算过期:max_age_days=0 -> None。
    • 两者要配套:浏览器留 30 天但服务端只认 1 天,那第 2 天起就是「有 cookie 但没登录态」,别让用户莫名其妙。
  • version=1 是老格式,实测长这样:

    1
    v1="bmljZQ==|1793963026|23c017d6b65862a2403f8733a4f682da8a185969"

    没有前面的长度前缀,但同样带签名。新代码用默认的 2 就行;get_secure_cookie(..., min_version=2) 可以拒绝旧格式。

  • 密钥必须配 cookie_secret,生成方式老笔记那段仍然可用,实测:

    config.py
    1
    2
    3
    4
    import base64
    import uuid

    secret = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
    1
    长度: 64  样例: 'wtsaTrAfTBuZTx5f9yBh...'

    两点要补:

    • 这个串别写死进代码仓库,走环境变量(password 那类凭据也一样,不要把明文写进代码)。
    • 换密钥时不想把所有人踢下线,就用 dict 形式的 cookie_secret 做多版本轮换,见下面单独一节。
  • 安全 cookie 只是「防篡改」,不是加密——值只是 base64,肉眼就能解出来。所以别往里放敏感数据,这条老笔记也写对了。要放就放用户 id 之类的间接标识。

密钥轮换

  • cookie_secret 除了字符串还能写成字典 {密钥版本号: 密钥},老笔记没提。它的用法是「新旧两把密钥同时在字典里,签发只用手头那把,验签按 cookie 里记的号取」,实测:

    config.py
    1
    2
    3
    4
    settings = {
    "cookie_secret": {1: OLD_SECRET, 2: NEW_SECRET},
    "key_version": 2, # 签发时用字典里的哪一把
    }
    1
    2
    3
    只给字典、不给 key_version  -> 500,服务端:Exception: key_version setting must be used for secret_key dicts
    key_version=2 签发的 cookie -> 2|1:2|10:1793964274|1:k|4:dg==|3efd1b80...
    get_signed_cookie_key_version("k") -> 2
    • 字典形式必须同时配 key_version,漏了不会在启动时报错,而是每个签发请求 500。

    • cookie 第二段 1:2 就是「第 2 把密钥签的」(1 是长度、2 是值)。验签时按这个号去字典里取密钥,所以两把都在字典里时,新旧 cookie 都能通过:

      1
      2
      key_version=1 签的旧 cookie -> 在新应用上读回 b'v',key_version=1
      把 1 从字典里删掉再读同一枚 -> None(这才是真正「踢下线」的动作)
    • 所以轮换的正确顺序是:新密钥加成 2、key_version 指到 2(旧 cookie 照常能用)→ 等旧 cookie 都过期 → 再把 1 从字典删掉。

    • set_secure_cookie(..., version=...) 里的 version 是格式版本(1 或 2),跟密钥版本没关系,别混。实测 version=1 的老格式碰上字典密钥直接 500(decode_signed_value 里 assert not isinstance(secret, dict)):v1 不携带密钥版本号,两者天生不兼容。

XSRF 是怎么回事

  • 老笔记的「cookie 计数器 + 别站 <img src>」这个演示很直观,保留思路:

    views/index.py
    1
    2
    3
    4
    5
    6
    class CookieNumHandler(RequestHandler):
    def get(self):
    count = self.get_cookie("count", "0")
    count = int(count) + 1
    self.set_cookie("count", str(count))
    self.render("cookienum.html", count=count)
    evil.html
    1
    <img src="http://127.0.0.1:8848/cookienum">

    访问「搞事情」那个页面时,浏览器带着本站 cookie 自动发了这个 GET,服务端分不清是谁发起的。

  • 关键点:浏览器发请求时会自动附上目标域的 cookie,所以「攻击者能不能让浏览器发出这个请求」取决于请求方法和同源策略:

    • <img>、<script>、表单跳转这类标签级请求,跨站也能发出去,GET 接口就有风险。

    • 跨站的 fetch/XMLHttpRequest 受同源策略限制(协议、域名、端口三者同源才能带 cookie 读写),所以老笔记说「原理是同源策略」——它挡住的是脚本级跨站请求,挡不住标签级。

      同源分析

  • 所以两条防线:

    • 会改状态的操作不要用 GET(老笔记这条对,但别把它当主要防线,<form method="post"> 一样能跨站提交)。
    • 主要防线是 XSRF token,下面这段就是它。

开启 XSRF 保护

  • 打开开关:

    config.py
    1
    2
    3
    4
    SETTINGS = {
    "xsrf_cookies": True,
    "cookie_secret": os.environ["COOKIE_SECRET"], # 走环境变量,不要把明文写进代码
    }

    开了之后所有 POST/PUT/DELETE/PATCH 都要带 token,GET/HEAD/OPTIONS 不检查。实测不带 token 的 POST:

    1
    2
    POST /post(不带任何 token) -> 403
    服务端日志:403 POST /post: '_xsrf' argument missing from POST
  • token 从 xsrf_token 这个属性来,第一次读它就会同时种 _xsrf cookie。模板里用模块输出隐藏域:

    templates/form.html
    1
    2
    3
    4
    <form method="post" action="/post">
    {% module xsrf_form_html() %}
    <input name="username">
    </form>

    实测渲染与响应头:

    1
    <input type="hidden" name="_xsrf" value="2|dba6ba0d|b76b54c59aeeb5d7c275446248ba6e28|1793963041"/>
    1
    Set-Cookie: _xsrf=2|dba6ba0d|b76b54c59aeeb5d7c275446248ba6e28|1793963041; Path=/

    两者值相同,校验时比对「cookie 里的」和「请求里带的」是否一致——攻击者的页面能提交表单,但读不到你域下的 cookie,所以带不上正确的 token。

  • 三种带法实测(同一个服务端,token 都从响应头里取):

    1
    2
    3
    4
    5
    6
    ① 表单域 _xsrf=<token>            -> 200
    ② 请求头 X-XSRFToken: <token> -> 200
    ③ JSON 体 + 请求头 X-XSRFToken -> 200
    ④ JSON 体但不带请求头 -> 403 '_xsrf' argument missing from POST
    ⑤ 请求里的 token 与 cookie 不一致 -> 403 XSRF cookie does not match POST argument
    ⑥ 什么都不带 -> 403

    也就是说:普通表单走 _xsrf 字段;AJAX/JSON 一律走 X-XSRFToken 请求头(Content-Type: application/json 时服务端没有表单可解析,只能靠头)。

  • 前端拿 cookie 的老写法仍然有效,但不必引 jQuery:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function getCookie(name) {
    const m = document.cookie.match("(^|;)\\s*" + name + "\\s*=\\s*([^;]+)");
    return m ? m.pop() : "";
    }

    fetch("/post", {
    method: "POST",
    headers: {"X-XSRFToken": getCookie("_xsrf"),
    "Content-Type": "application/json"},
    body: JSON.stringify({username: "sunck"}),
    });

    老笔记那三段(手写 hidden 域 + $.post + $.ajax)思路都对,只是现在不需要 jQuery;$.post 那种把 _xsrf= 拼进 body 的写法仍然属于第①种。

  • 模板里没有 xsrf_token 这个名字,实测 {{ xsrf_token }} 会 NameError: name 'xsrf_token' is not defined(模板能拿到的是 xsrf_form_html())。要在 Python 侧读,用 self.xsrf_token。

  • 想给某个接口豁免:6.x 没有 @tornado.web.xsrf_exempt 装饰器(实测 AttributeError: module 'tornado.web' has no attribute 'xsrf_exempt',5.0 起就删了),改成覆盖方法:

    views/index.py
    1
    2
    3
    4
    5
    6
    class ExemptHandler(RequestHandler):
    def check_xsrf_cookie(self):
    pass # 这个接口不校验 XSRF

    def post(self):
    self.write("exempt ok")

    实测这样确实放行(POST /exempt → 200)。豁免等于放弃保护,只给「本来就没有 cookie 会话的公开接口」用。

用户验证

  • 三件套:get_current_user() 写「这个人是谁」,@tornado.web.authenticated 标在需要登录的方法上,login_url 指定跳去哪。返回真值算通过,假值(None/False)算未登录。

    views/index.py
    1
    2
    3
    4
    5
    6
    7
    8
    class PrivateHandler(RequestHandler):
    def get_current_user(self):
    user_id = self.get_secure_cookie("user")
    return user_id.decode() if user_id else None

    @tornado.web.authenticated
    def get(self):
    self.write("secret")
  • 实测未登录的跳转:

    1
    2
    3
    GET /private          -> 302 Location=/login?next=%2Fprivate
    GET /none(返回 None) -> 302 Location=/login?next=%2Fnone
    GET /false(返回 False)-> 302 Location=/login?next=%2Ffalse

    跳转是 302,并且自动把原地址 next= 带上了(URL 编码过)。

  • next 会被二次编码,实测从 /private?next=/cart 进去时:

    1
    Location=/login?next=%2Fprivate%3Fnext%3D%2Fcart

    也就是登录成功后要按这个 next 跳回去时,得知道它已经被编码过一层,别自己再拼一遍。

  • 登录 / 登出的完整写法(用安全 cookie 存登录态,而不是 URL 参数):

    views/index.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class LoginHandler(RequestHandler):
    def get(self):
    self.render("login.html", next=self.get_argument("next", "/"))

    def post(self):
    name = self.get_body_argument("username")
    passwd = self.get_body_argument("passwd")
    if check_password(name, passwd):
    self.set_secure_cookie("user", name.encode())
    self.redirect(self.get_argument("next", "/"))
    else:
    self.redirect("/login")


    class LogoutHandler(RequestHandler):
    def get(self):
    self.clear_cookie("user")
    self.write("bye")

    实测这一轮:

    1
    2
    3
    4
    5
    POST /login (username=1, next=/private) -> 302 Location=/private
    Set-Cookie: user="2|1:0|10:1793963191|4:user|8:YWRtaW4=|8f2a43ca..."
    GET /private(带上这个 cookie) -> 200 secret
    GET /logout -> 200,Set-Cookie: user=""; expires=一年前
    POST /login(密码错) -> 302 Location=/login
  • 老笔记用 ?flag=logined 当登录态是错的示范:get_current_user 读 URL 参数,等于任何人敲一个参数就登录成功;而且参数会留在浏览器历史、服务器日志和 Referer 里。登录态只能来自服务端可验证的东西(签名 cookie、session、token)。

  • 顺带一个真漏洞:直接 self.redirect(self.get_argument("next")) 是开放重定向,实测:

    1
    2
    GET /open?next=http://evil.example/  -> 302 Location=http://evil.example/
    GET /open?next=//evil.example/ -> 302 Location=//evil.example/

    // 开头会被浏览器当成「换主机」,所以只判断「以 / 开头」不够。可用的最小校验,实测有效:

    1
    2
    3
    4
    5
    nxt = self.get_argument("next", "/")
    if nxt.startswith("/") and not nxt.startswith("//"):
    self.redirect(nxt)
    else:
    self.redirect("/")
    1
    2
    3
    白名单版 next=http://evil.example/ -> Location=/
    白名单版 next=//evil.example/ -> Location=/
    白名单版 next=/good -> Location=/good
  • login_url 之外还有一个 auth_redirect 设置可以指定「用哪个方法去做跳转」,一般不用动。

参考