Tornado Web 防止XSS攻击,即对变量进行特殊字符过滤

网站开发使用Tornado作为服务器,本以为其自带的对数据库进行处理的方法(insert,update)等会自动对异常字符进行检测,便没有人工进行异常字符过滤。

之后甲方请了专业的公司对网站进行了安全评估,发现大部分的input标签都可以发起XSS攻击,即在input中输入<script>alert(1);</script>,存进数据库之后再取出将会调用这段javascript代码,有着很大的安全隐患。因此需对插入数据库的变量进行字符检测。

在将数据插入数据库之前,先进行字符替换。即先重写一个get_escaped_argument方法,调用tornado自带的xhtml_escape方法将以下这些字符进行转义

_XHTML_ESCAPE_DICT = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;'}
    def escape_string(self, s):
        return tornado.escape.xhtml_escape(s)

    def get_escaped_argument(self, key, default = None):
        if default is not None:
            return self.escape_string(self.get_argument(key, default))
        else:
            return self.escape_string(self.get_argument(key))

然后在写rest接口时,调用以上的方法,就可将所有异常字符进行处理,避免了执行script脚本的问题。

@Route(r"/rest/mgr/group/add")
class _(MgrHandler):
    @coroutinedef post(self):
        group_id = self.get_escaped_argument('group_id','')

 

从数据库中取数据时,input里面的数据显示的是替换后的字符,因此重写了jQuery,在val显示之前先进行字符的替换。

val: function(e) {            var n, r, i, o = this[0]; {
                if (typeof e == 'string') {
                    e = e.replace(/&lt;/g, "<");
                    e = e.replace(/&gt;/g, ">");
                    e = e.replace(/&quot;/g, '"');
                    e = e.replace(/&#39;/g, "'");
                }
                if (arguments.length) return i = x.isFunction(e), this.each(function(n) {
                    var o;
                    1 === this.nodeType && (o = i ? e.call(this, n, x(this).val()) : e, null == o ? o = "" : "number" == typeof o ? o += "" : x.isArray(o) && (o = x.map(o, function(e) {
                        return null == e ? "" : e + ""
                    })), r = x.valHooks[this.type] || x.valHooks[this.nodeName.toLowerCase()], r && "set" in r && r.set(this, o, "value") !== t || (this.value = o))
                });

                if (o) return r = x.valHooks[o.type] || x.valHooks[o.nodeName.toLowerCase()], r && "get" in r && (n = r.get(o, "value")) !== t ? n : (n = o.value, "string" == typeof n ? n.replace(V, "") : null == n ? "" : n)
            }
        }
    })

 同时可参考 http://demo.pythoner.com/itt2zh/ch6.html ,里面有更为详细的tornado安全应用开发。 

posted on 2016-01-05 16:09  吴芳雪  阅读(1053)  评论(0编辑  收藏  举报