Search code examples
formssecuritycsrf

How to prevent submitting form from localhost to server


I've googled this for two days and I just can't find anything describing the following issue:

Let's say I have the following form on "www.example.com":

<form action="formProcessor.htm" method="post">
  <input name="field1" value="abc" />
  <input name="field2" value="123" />
  <input name="field3" value="etc" type="hidden" />
  <input value="Submit" type="submit" />
</form>

My concern is: What if somebody creates a local file simulating this form, fills in all the values manually, and then submit it to "www.example.com/formProcessor"?

Question #1: Is there any way to prevent this?

Question #2: Is this considered so-called CSRF?

I know you can try to validate the REFERRER, but I also know that this can be easily forged (just look for the "modify header" FF add-on).

If this is a basic question, please bear patience with me, I'm fairly new to website security.

Mark


Solution

  • Yes, that is Cross-site Request Forgery.

    You can prevent it by creating a one-time key, and storing that in a hidden input element in your form something like this:

    <?php
    
    $_SESSION['formkey'] = md5(rand() . time() . $_SERVER['REMOTE_ADDR']);
    
    ...
    
    <input type="hidden" name="formkey" value="$_SESSION['formkey']" />
    
    ?>
    

    And upon submit, you check whether the submitted key matches the one you have stored in your session. If so, you process the form, otherwise deny the request.

    An attacker (or innocent visitor visiting through an attackers' site) will not know the key, and thus not be able to submit the form.

    Only visitors from your site, where you regenerate and set the correct key on every form, will be able to submit.