Jump to content

Prevent Spoofed Contact Form Submission_Security of Web form


dingi

Recommended Posts

I am very much concerned about preventing 'spoofed contact web form submissions'. I have a code that may prevent multiple form submissions. This is the code in form.php( actually it is form.html changed extension as php):

/*** begin the session ***/

session_start();

/*** create the form token ***/

$form_token = uniqid();

/*** add the form token to the session ***/

$_SESSION['form_token'] = $form_token;

Now we have to process it with mail processor.php as below:session_start();

/*** check all expected variables are set ***/

if(!isset($_POST['first_name'], $_POST['form_token'], $_SESSION

['form_token']))

{

$message = 'Invalid Submission';

}

/*** check the form tokens match ***/

elseif($_POST['form_token'] != $_SESSION['form_token'])

{

$message = 'Access denied';

}

My doubt is this kind of generating unique token or unique Session ID will also prevent fake or spoofed form submission?   After reading about spoofed contact forms in google links that, hackers could save a copy of " html form page source" and manipulate it, even spoofing 'HTTP_Referer Header' also, I am very much worried. Since my knowledge in PHP is very limited, please help me. I don't know if the above code will protect my Contact Form. I searched this topic in the forum and could not find any solution. Please tell me how to exactly protect contact forms against such attacks. Thank you.

 

Link to comment
Share on other sites

The form sends Email just to me with user input data. The form has "Your Email field" the user has to input. There is no CC option in any of the forms. But I tried to strip out extra charaters in the email field to avoid remote injection of Bcc cc headers and relay email spam. I am not sure about this form about spoofing attack. The html form action tag goes to process.php. Since the user can notice this PHP file from the address bar he now knows the location of the action script, he can directly call this PHP from anywhere after manipulating the html form. Please help. Thank You.

Link to comment
Share on other sites

Captch is nice to keep spambots at bay, but it does nothing to prevent a live spammer from using the form to send spam. You need to take steps to make sure the user is unable to use certain words, and since it takes a line feed to be able to use it for spam, strip all user line feeds from the fields, and use wordwrap() instead. I see no need to reinvent the wheel, so I use a function I got from a book for that purpose, and I use another function that was passed on to me by a friend to verify that any email fields filled in by users contain a valid email address, and that there is an associated MX record in DNS lookup.

 

To prevent form-spam:

// this will run the entire $_POST array through the function. You can define a different array with only certain indices taken from the $_POST array if desired.
function SPAM_SCRUBBER($value) {
$very_bad = array('to:', 'cc:', 'bcc:', 'content_type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:');
foreach( $very_bad as $v ) {
	if( stripos($value, $v) !== false ) return '';
}
$value = str_replace(array("\r", "\n", "%0a", "%0d"), ' ', $value);
return trim($value);
}
$scrubbed = array_map('SPAM_SCRUBBER', $_POST); // change the $_POST array to your array if not running all of $_POST through function

 

To validate email addresses:

function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
	$isValid = false;
} else {
	$domain = substr($email, $atIndex+1);
	$local = substr($email, 0, $atIndex);
	$localLen = strlen($local);
	$domainLen = strlen($domain);
	if ($localLen < 1 || $localLen > 64) { // local part length exceeded
		$isValid = false;
	} else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded
		$isValid = false;
	} else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.'
		$isValid = false;
	} else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots
		$isValid = false;
	} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part
		$isValid = false;
	} else if (preg_match('/\\.\\./', $domain)) {	// domain part has two consecutive dots
		$isValid = false;
	} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless
		// local part is quoted
		if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))	{
			$isValid = false;
		}
	}
	if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { // domain not found in DNS
		$isValid = false;
	}
}
return $isValid;
} // end of function

// FIELD VALIDATION . . . 
if( validEmail($e_mail) == true ) { 
     // address ok
} else {
     // address bad
}

Link to comment
Share on other sites

You could install a capctha box. They're one of those crazy things that force a user to write some scrambled words before allowing them to post. You can get some free ones and they're easy enough to install.

 

Thank you for your suggestion and link to captcha. But I have added captcha to the form already. But still worried about spoofing a form by a spammer. Will captcha prevent Spoofing? I feel it can be defeated by a  spammer who manages to manipulate the saved form after viewing the source code. Am i missing anything here? please tell me.

Link to comment
Share on other sites

Captch is nice to keep spambots at bay, but it does nothing to prevent a live spammer from using the form to send spam. You need to take steps to make sure the user is unable to use certain words, and since it takes a line feed to be able to use it for spam, strip all user line feeds from the fields, and use wordwrap() instead. I see no need to reinvent the wheel, so I use a function I got from a book for that purpose, and I use another function that was passed on to me by a friend to verify that any email fields filled in by users contain a valid email address, and that there is an associated MX record in DNS lookup.

Thank you for an excellent code you mentioned to prevent Spam and validate Email address with MX records and DNS look up. Really worth and nice for sharing such a great code. It is really useful. Please tell me if those codes you mentioned must be inserted after the "session Start" function but before "Mail to" function tag in mail processor.php As we say Captcha box will also little bit help. But how to prevent someone from accessing the mail processor php with remote injection and manipulating techniques and defeat captcha itself and use the form from a remote location?  After inserting your code will it be simply impossible for a spammer to use the form from remote location? Thanks again. Please help.

Link to comment
Share on other sites

There is no code that can make it 100% impossible to use a mail form for spam. What this code will do, however, is make it so the form can't be used to send bulk spam by preventing the use of header injection in the form fields. Using a captcha will make it harder for spambots to utilize your form to send spam. In any event, you can't stop a human from using the form for its intended purpose of sending an email to the address specified in the code. No matter what you do, short of using an incredibly large list of prohibited words, you cannot stop people from using the form to enter a spam message in the text field and sending it to the email address the form processor script uses.

 

Now having said that, I have had these 2 scripts on my contact page for the last 4 years, and in that time I have received a total of 2 spam emails.

 

Regarding where to include the scripts, you'd use them in with the rest of the field validation for your form. You can either copy/paste them in, or save them to files and require_once() them.

Link to comment
Share on other sites

There is no code that can make it 100% impossible to use a mail form for spam. What this code will do, however, is make it so the form can't be used to send bulk spam by preventing the use of header injection in the form fields. Using a captcha will make it harder for spambots to utilize your form to send spam.

Now having said that, I have had these 2 scripts on my contact page for the last 4 years, and in that time I have received a total of 2 spam emails.

That's really good news that there is no spam in 4 years of using a form with your code. Now I feel confident and relieved. Thanks a lot. May I ask you one additional step about Captcha? Captcha is a burden to a genuine user and also for people with visual and hearing problems. That is, Captcha must not be on the form when the user sends mail only once. In case of succesive attempts to send mail by the same user, Captcha should appear on the form from the second attempt onwards. I think this can be done by storing a unique ID in a hidden field or something similar and check if the form was already submitted. We cannot rely on IP address as everyone knows, the user may have Dynamic IP address or switches through a web proxy. I don't how to implement it. Can I use the code I mentioned above (generating Unique Token ID, I dont know if the code is correct), but how to modify it. Any idea please? Since you have very good exposure to PHP you can help me. Thanks again.

Link to comment
Share on other sites

The code I provided has nothing to do with captcha, it does validation only. I don't use a captcha on my contact form at all, and it hasn't been a problem for me. A spammer isn't likely to waste his time on a form that is properly validated and can't be used to send bulk spam to multiple recipients.

Link to comment
Share on other sites

The code I provided has nothing to do with captcha, it does validation only. I don't use a captcha on my contact form at all, and it hasn't been a problem for me. A spammer isn't likely to waste his time on a form that is properly validated and can't be used to send bulk spam to multiple recipients.

I understood that your code has nothing to do with Captcha. It would validate the form well and help processing securely. Your help is really great for me. I will be implementing your code soon. Shall I clarify my doubts with you if there is any difficulty in implementing the same? And there won't be any need to use Captacha also as you said. But I asked you about it because, when there is an acute necessity to implement Captcha we can do it only for those who send repeated mails. I also need to use another separate form that sends data to MYSQL database instead of Email. So I thought of taking addtional precautions. Could you please help me out to protect MYSQL Databse from hackers. I inserted mysql_real_escape_string in PHP. But not sure about it. Is there any other thing or code that I have to do protect remote injection or hijack attacks in MYSQL. Because earlier I had a form with Captcha(now removed due to attacks) that would send data to MYSQL . One day someone deleted all the data from the database. There is no log that gives any details. How to protect against such attacks? How to automatically create log in a text file about all the activites, information such as browser details, IP Address, Date, Time stamps etc...of clients who use the form?  Please help. Thank you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.