RailsCasts9 Filtering Sensitive Logs 过滤敏感日志

这是一个用户注册页面,填入用户名和密码按确认提交。

查看后台日志的话,能够发现所有页面提交的参数都是以明文方式保存在日志中的。

terminal

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方法。可以通过名字指定对输出到日志的内容进行保护。

ruby

class ApplicationController < ActionController::Base
  filter_parameter_logging "password" 
end

再往后的Rails版本中,都会缺省加入这句过滤条件,只不过是备注释着的。可以去掉注释以便开启这个特性。重新刷新页面,查看日志内容。

terminal

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语句。再说,本来也不应该向数据库中存放明文密码,而是应该加密混淆后在入库。


转自:http://railscasts.com/episodes/9-filtering-sensitive-logs?language=zh&view=asciicast

你可能感兴趣的:(RailsCasts9 Filtering Sensitive Logs 过滤敏感日志)