這是一個用戶註冊頁面,填入用戶名和密碼按確認提交。
查看後臺日誌的話,能夠發現所有頁面提交的參數都是以明文方式保存在日誌中的。
Processing UsersController#create (for 127.0.0.1 at 2009-01-02 10:13:13) [POST]
Parameters: {"user"=>{"name"=>"eifion", "password_confirmation"=>"secret", "password"=>"secret"}, "commit"=>"Register", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5"}
User Create (0.5ms) INSERT INTO "users" ("name", "updated_at", "password_confirmation", "password", "created_at") VALUES('eifion', '2009-01-02 10:13:13', 'secret', 'secret', '2009-01-02 10:13:13')
在日誌中記錄這種敏感信息的方式肯定是有安全隱患的。從Rails1.2開始,在
ApplicationController
中增加了filter_parameter_logging
方法。可以通過名字指定對輸出到日誌的內容進行保護。
class ApplicationController < ActionController::Base
filter_parameter_logging "password"
end
再往後的Rails版本中,都會缺省加入這句過濾條件,只不過是備註釋着的。可以去掉註釋以便開啓這個特性。重新刷新頁面,查看日誌內容。
Processing UsersController#create (for 127.0.0.1 at 2009-01-02 11:02:33) [POST]
Parameters: {"user"=>{"name"=>"susan", "password_confirmation"=>"[FILTERED]", "password"=>"[FILTERED]"}, "commit"=>"Register", "action"=>"create", "authenticity_token"=>"9efc03bcc37191d8a6dc3676e2e7890ecdfda0b5", "controller"=>"users"}
User Create (0.4ms) INSERT INTO "users" ("name", "updated_at", "password_confirmation", "password", "created_at") VALUES('susan', '2009-01-02 11:02:33', 'verysecret', 'verysecret', '2009-01-02 11:02:33')
可以看到,日誌中password的值被[FILTERED]
遮蓋住了,不再以明文顯示。需要注意的是,這個特性會對所有參數名中包含那些定義在filter_parameter_logging
方法中字符的變量生效。比如說,password_confirmation
參數的值也被遮蓋後才計入日誌的。雖然能在SQL語句中看到明文,但請放心的是,這只是開發模式下纔會有的內容,發佈模式(product)下不會記錄SQL語句。再說,本來也不應該向數據庫中存放明文密碼,而是應該加密混淆後在入庫。
作者授權:Your welcome to post the translated text on your blog
as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.
原文鏈接:http://railscasts.com/episodes/9-filtering-sensitive-logs