前兩天在寫代碼的時候,突然收到警告說項目代碼中存在 XSS 漏洞,遂立即根據報告的 URL 排查頁面代碼,雖然很快就修復了,而且同樣問題的討論兩年前就有了,一般來說相對有經驗的同學也應該都知道這個點,但是還是覺得有必要寫出來,再次提醒一下其他小伙伴,避免踩坑。
問題根源
其中,在找到的漏洞出現的地方,都存在類似以下這樣的 slim 代碼:
input class='xxx' value==params[:account]
問題就出在雙等號 == 上,因為在 slim 跟 ERB 模板(其他模板比如 HAML 之類的就不清楚了)中,雙等號其實是 Rails 的 raw 這個 helper 方法的縮寫
To insert something verbatim use the raw helper rather than calling html_safe:<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>or, equivalently, use <%==:<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
也就是說上面的代碼等同于:
input class='xxx' value=raw(params[:account])
其中 raw 方法在 Rails 文檔中的解釋是這樣子的:
This method outputs without escaping a string. Since escaping tags is now default, this can be used when you don't want Rails to automatically escape tags. This is not recommended if the data is coming from the user's input.
大概意思就是,這個方法將會跳過對傳入的字符串進行標簽過濾以及其他處理,直接將字符串輸出到 HTML 中。
所以到現在原因就很清晰了,因為不小心在代碼里多加了一個等號,變成了雙等號,導致將會直接把用戶的輸入輸出到待渲染的 HTML 中,在不自知的情況下留下了 XSS 漏洞。于是乎,修復方案僅需去掉一個等號即可:
input class='xxx' value=params[:account]
這樣,Rails 就能繼續自動過濾輸入的 :account 的參數并且自動過濾惡意內容了。
raw、String#html_safe 以及 <%== %>
在查看 raw 方法的文檔時,順便看了其源碼,極其簡單,只有一行:
# File actionview/lib/action_view/helpers/output_safety_helper.rb, line 16def raw(stringish) stringish.to_s.html_safeend
raw 只是先確保將 stringish 參數轉化為字符串,然后調用了 String#html_safe 方法而已。而且在 String#html_safe 的文檔中,同樣反復強調慎重使用這兩個方法:
It will be inserted into HTML with no additional escaping performed. It is your responsibilty to ensure that the string contains no malicious content. This method is equivalent to the raw helper in views.
所以,可以總結一下,以下三種寫法的代碼都是等價的,都是不安全的:
input class='xxx' value==params[:account]input class='xxx' value=raw(params[:account])input class='xxx' value=params[:account].html_safe
那在切實需要輸出包含 HTML 內容比如富文本編輯器編輯的內容時,如何保證安全?
方案很簡單,只需要使用文檔中推薦的 sanitize helper 方法:
It is recommended that you use sanitize instead of this method(html_safe).(#sanitize)Sanitizes HTML input, stripping all tags and attributes that aren't whitelisted.
或者使用一些其他第三方的 gem 用來做過濾處理。
總結
新聞熱點
疑難解答