开发者

Is the use of hidden fields in forms insecure?

For example

Imagine I have the following form

  <%= form_for(@comment) do |f| %>

    <%= f.hidden_field :user_id%>
    <%= f.hidden_field :article_id%>

    <%= f.label :content %><br />
    <%= f.text_area :content %>

    <%= f.submit %>
  <% end %>

I got the :user_id and :article_id values with:

Comment.new(:user_id => current_user.id, :article_id => @article.id)

When I display the form in the browser it will look like this:

<form action="/comments" method="post">

  <input some_rails_tokens_here />

  <!-- THIS AREA HERE-->
  <input id="comment_user_id" name="comment[user_id]" type="hidden" value="1" />
  <input id="comment_article_id" 开发者_StackOverflow社区name="comment[article_id]" type="hidden" value="1" />
  <!-- THIS AREA HERE-->

  <label for="comment_content">Content</label><br />
  <textarea id="comment_content" name="comment[content]"></textarea>

  <input type="submit" />
</form>

My question is, what if someone changes the post parameters and instead of being the value for :user_id => 1 it is changed to :user_id => 2. The same with the article.

I want to believe that is verified with the rails tokens, but I am not sure.


A hidden field in a form is no more or less secure than any other data that come from user. That is, it should not be trivally trusted: It comes from the user and is open to manipulation and specialty injection.

When the data is sent back to the server, the server should validate that data and not assume that the operation is allowed/invalid just based on a particular user-modifiable context. Depending upon needs, approaches like hash checksums can be used to have a very high degree of confidence that the data was not tampered with (but again, this should be verified by the server each request!). Using "session state" mitigates the problem entirely by keeping the data out of user-manipulation land.

Happy coding.


If comments from un-registered users are allowed then why bother about the user_id at all, and if comments are only allowed from registered users then use sessions to track the user, instead of passing user_id in a form element.

And to answer your question if using hidden fields is insecure, without proper sanity check even the visible fields are insecure.


If the value of those fields is critical, then don't trust the user to return them unchanged. Otherwise, a hidden field is no less or no more secure than a regular visible field - if it's in the HTML, someone can change it.


Data sent from the client to the server cannot be trusted without server-side checks (including HTML forms and browser cookies). The data could be maliciously modified or sent multiple times.

I have read stories about e-commerce sites that submitted the product price from an HTML form. A cheap user could edit the HTML form data they submit to the server to change the product price.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜