Thinking and Practice of Separation of Front and Back Ends (4)

Original source:  Taobao UED - lorrylockie   

Security solution in front-end and back-end separation mode

foreword

In the development mode where the front-end and the back-end are separated, one of the most obvious changes in terms of the roles and functions of development is: in the past, the front-end students who were only responsible for the development in the browser environment need to go to the server-side level and write the server-side code. And a fundamental question before us is how to ensure Web security?

Under the framework of front-end and back-end separation mode, this paper proposes solutions for the security problems encountered in front-end web development, as well as countermeasures and precautions.

 

Defense against Cross-Site Scripting (XSS)

 

Problems and Solutions

Cross-site scripting (XSS, Cross-site scripting) is the most common and basic method of attacking Web sites. An attacker can post data containing offensive code on a web page, and when a browser sees this page, a specific script will be executed with the identity and permissions of the browser user. Through XSS, it is relatively easy to modify user data, steal user information and cause other types of attacks, such as CSRF attacks.

The basic way to prevent XSS attacks is to ensure that any data that is output to an HTML page is HTML escaped. For example the following template code:

The variables in this code are $descriptiontemplate variables (variable syntaxes defined in different templates are different, here is just an indication), the data submitted by the user, then the attacker can enter a piece of code containing "JavaScript" to make the result of the above template statement becomes the following result:

The above code, rendered in the browser, will execute the JavaScript code and alert hello on the screen. Of course this code is harmless, but an attacker can create a JavaScript to modify user data or steal cookie data.

The solution is very simple, which is $descriptionto html escape the value, and the escaped output code is as follows

The above escaped HTML code is harmless.

 

Midway's solution

 

Escape all user output data in the page

There are several situations and methods for escaping data:

 
1. Use the mechanism provided inside the template for escaping

Midway uses KISSY xtemplate internally as template language.

In the xtemplate implementation, two square brackets ( ) are used syntactically to  {{val}}parse template data, , which is HTML-escaping the data by default, so developers can write templates like this:

In xtemplate, if you do not want the output data to be escaped, you need to use three square brackets ( {{{val}}}).

 
2. Explicitly call escape functions in Midway

Developers can directly call the HTML escape method provided by Midway in the Node.js program or template to escape the displayed data, as follows:

Method 1: HTML Escape Data in Node.js Program

Method 2: HTML-escaping the HTML data in the template

Note: Use Security.escapeHtml to escape data only if the data is not escaped inside the template. Otherwise, the inside of the template and the program will be escaped twice, resulting in unexpected output.

Recommendation: If you use xtemplate, it is recommended to use the built-in template {{}}for escaping; if you use other templates, it is recommended to use Security.escapeHtmlit to escape.

 

Filter rich text output by the user in the page

You may think: "In fact, I just want to output rich text, such as some message boards, forums to provide users with some simple font size, color, background and other functions, so how do I deal with such rich text to prevent XSS?"

 
1. Use the richText function provided by Security in Midway

The richText method is provided in Midway, which is specially used to filter rich text to prevent vulnerabilities such as XSS, phishing, and cookie theft.

With a message board, the template code might look like this:

Because the message is the user's input data, the content of the message board contains rich text information, so here in xtemplate, three curly brackets are used, and HTML escaping is not performed by default; then the data input by the user is as follows:

If the above rich text data is directly output to the page, it will inevitably cause the js of the eval.com site to be injected into the current page, resulting in an XSS attack. In order to prevent this vulnerability, we only need to call the Security.richText method in the template or program to process the rich text input by the user.

The calling method is similar to escapeHtml, in the following two ways

Method 1: Call it directly in the Node.js program

Method 2: call in template

After calling Security's richText method, the final output is as follows:

It can be seen that, first of all: tags that can cause XSS attacks scriptare directly filtered; at the same time, the CSS attribute position:fixed;styles in the style tag are also filtered. Ended up outputting innocuous HTML rich text

 

Learn about other avenues that can lead to XSS attacks

In addition to the possibility of XSS attacks in the templates of pages, there are several other avenues in which web applications can be at risk.

 
1. Vulnerability of the error page

If a page cannot be found, the system may report a 404 Not Found error, for example: http://localhost/page/not/found

Obviously: an attacker can use this page to construct a link like this http://localhost/%3Cscript%3Ealert%28%27hello%27%29%3C%2Fscript%3E, and lure the victim to click; if the error page does not escape the output variable, then the hidden link  <script>alert('hello')</script> will be executed.

In express, the way to send a 404 page is as follows

Here, developers need to pay attention to how error pages (404 or other error states) are handled. If the return content of the error message has path information (in fact, it is more accurate, it is the user input information), it must be escapeHtml.

Subsequently, the security mechanism of error handling will be completed at the Midway framework level.

 

Additional Notes for Midway Solutions

 

Other template engines

Midway supports xtemplate templates by default, but may support other templates in the future: jade, mustache, ejs, etc. Currently, in mainstream templates, default escaped and unescaped output variable writing methods are provided, and developers need to pay special attention to their security.

 

Additional support for escape

In addition to the normal data and rich text data output on the page, some scenarios also contain other situations that may need to be escaped. Midway provides the following common escape methods for developers to use:

  • escapeHtml filters the characters in the specified HTML to prevent XSS vulnerabilities
  • jsEncode Escape the input String with JavaScript Escape Chinese with unicode, single quote, double quote
  • escapeJson does not destroy the escape function of the JSON structure, and only performs escapeHtml processing on the name and vaule in the json structure
  • escapeJsonForJsVar can be understood as jsEncode+escapeJson

Examples are as follows

 

Prevention of Cross-Site Request Forgery (CSRF)

 

Problems and Solutions

Explanation of terms:  Form: refers to the form used by the browser to submit data on the client side; including a tag, ajax submission data, form form submission data, etc., rather than the form tag in HTML.

Cross-site request forgery (CSRF) is another common attack. Attackers use various methods to forge a request and imitate the user's behavior of submitting a form, so as to modify the user's data or perform a specific task.

In order to impersonate a user's identity, CSRF attacks are often done in conjunction with XSS attacks, but can also be done by other means: for example, by tricking the user into clicking a link that contains the attack.

The idea of ​​solving CSRF attack is divided into the following two steps

  1. Increases the difficulty of the attack. GET requests are easy to create. Users can click a link to initiate GET requests, while POST requests are relatively difficult, and attackers often need to use JavaScript to implement them; therefore, make sure that the form or server interface only accepts POST requests. Submitting a request can increase the security of the system.
  2. Authenticate the request to ensure that the user fills in the form or initiates the request and submits the request, and is not forged by a third party.

The process for a normal user to modify website information is as follows

  • The user requests to modify the information (1) -> the website displays the form for the user to modify the information (2) -> the user modifies the information and submits (3) -> the website accepts the user's modified data and saves it (4)

And a CSRF attack will not take this route, but directly forge the information submitted by the user in step 2

  • 直接跳到第2步(1) -> 伪造要修改的信息并提交(2) -> 网站接受攻击者修改参数数据并保存(3)

只要能够区分这两种情况,就能够预防CSRF攻击。那么如何区分呢? 就是对第2步所提交的信息进行验证,确保数据源自第一步的表单。具体的验证过程如下:

  • 用户请求修改信息(1) -> 网站显示用于修改信息的空白表单,表单中包含特殊的token同时把token保存在session中(2) -> 用户修改信息并提交,同时发回token信息到服务端(3) -> 网站比对用户发回的token和session中的token,应该一致,则接受用户修改的数据,并保存

这样,如果攻击者伪造要修改的信息并提交,是没办法直接访问到session的,所以也没办法拿到实际的token值;请求发送到服务端,服务端进行token校验的时候,发现不一致,则直接拒绝此次请求。

 

Midway解决方案

 

禁用GET提交表单

如果服务端不接受GET方式提交的表单数据,那么将会给攻击者带来非常大的难度;因为在页面上构造一个a标签href属性或者img标签src属性来构造一个请求是非常容易的,但是如果要POST提交,就必须要通过脚本才可以实现。

 

用CSRF token验证请求

因为Midway不涉及到淘宝分布式session及token校验这一层面逻辑,所以在Midway框架中,只将token在server和客户端之间进行转发,本身不做实际的校验工作。流程如下:

T13dy0FNhcXXc3iaIJ-1432-994

后续:在Midway中,Node.js和淘宝的分布式session对接后,可以考虑在Midway这一层自动进行token校验;毕竟安全校验越早进行,成本也会更低。

建议:在Midway中,可以判断是否request中有token的值,如果一个修改操作,没有token,可以直接在Midway层认为是不安全的,将请求丢弃掉。

 

其他安全问题

关于常见的Web安全问题,还有如下几种,这里只做一些简介,后续会持续继承到Midway framework中。

  • HTTP Headers安全
    • CRLF Injection 攻击者想办法在响应头中注入两个CRLF特殊字符,导致响应数据格式异常,从而注入script等
    • 拒绝访问攻击 每个请求因为都会默认带上cookie,而服务器一般都会限制cookie的大小,这就导致了,如果用户客户端cookie被设置成了超过某个阀值,那么用户就再也无法访问网站了
    • cookie防窃取 一般cookie窃取都是通过JavaScript(XSS漏洞)获取到的,所以尽量将cookie设置成http only,并且加上cookie过期时间

关于cookie的安全问题,之前WebX已经有较好的解决方案;此次Midway不负责cookie的设置和校验等工作,只负责转发到WebX层面进行check

 

关于Node.js

XSS等注入性漏洞是所有漏洞中最容易被忽略,占互联网总攻击的70%以上;开发者编写Node.js代码时,要时刻提醒自己,永远不要相信用户的输入。

比如如下几个例子。

  • var mod = fs.readFileSync('path'); 如果path来源于用户输入,那么假设用户输入/etc/password,则会读取到不应该读取的内容,造成密码泄漏风险
  • var result = eval(jsonVal); 一定要确保jsonVal是json,而不是用户的输入
  • …… 其他可能包含用户输入的地方,一定要确认用户的输入是我们期望的值
 

总结

前后端分离模式下,可以让传统的前端开发人员开始编写后端代码,虽然从架构上讲,只负责模板这一层,但也会接触大量的后端代码;所以安全对于前端来说,这是一个不小的挑战。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325927120&siteId=291194637