RailsCasts中文版,#9 Filtering Sensitive Logs 遮盖日志中记录的敏感信息

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

E009I01

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

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

posted on 2012-11-24 22:19  边晓宇  阅读(1302)  评论(0编辑  收藏  举报