Claudiu Creanga
Claudiu Creanga

Reputation: 8386

Is this form safe?

I have this form by which a user sends me an email. I don't know if it is secured, or if issues with security appear only if sql is involved...

html:

<form id="form4" action="send_mic.php"  name="form4" method="post" >

           <textarea name="message4" cols="4" rows="4"  id="message4" ></textarea><br />

           <input type="text"  id="name4" name="name4" value="" /><br />

           <input type="text"  id="email4" name="email4" value=""  /><br />

          <input type="submit" value="" id="submit" />

</form>

jquery:

<script type="text/javascript">
$(document).ready(function () {
    $('#form4').ajaxForm({
        beforeSubmit: validate
    });

    function validate(formData, jqForm, options) {
        var name = $('input[name=name4]').fieldValue();
        var email = $('input[name=email4]').fieldValue();
        var message = $('textarea[name=message4]').fieldValue();

        if (!name[0]) {
            alert('Please enter a value for name');
            return false;
        }
        if (!email[0]) {
            alert('Please enter a value for email');
            return false;
        }
        if (!message[0]) {
            alert('Please enter a value for message');
            return false;
        }

        else {

        $("#content").fadeOut(1000, function () {
            $(this).html("<img src='images/postauto3.png'/>").fadeIn(2000);
        });

        var message = $('textarea[name=message4]').val('');
        var name = $('input[name=name4]').val('');
        var email = $('input[name=email4]').val('');

            } 
    }

});



    </script> 

php:

<?php
        if($_POST){
                $email = $_POST['email4'];
                $name = $_POST ['name4'];
                $message = $_POST ['message4'];
                // response hash
                $ajaxresponse = array('type'=>'', 'message4'=>'');

                try {
                        // do some sort of data validations, very simple example below
                        $all_fields = array('name4', 'email4', 'message4');

                        foreach($all_fields as $field){
                                if(empty($_POST[$field])){
                                        throw new Exception('Required field "'.ucfirst($field).'" missing input.');
                                }
                        }

                        // ok, if field validations are ok
                        // now Send Email, ect.

                        // let's assume everything is ok, setup successful response
                        $subject = "New Contact";
                        //get todays date
                        $todayis = date("l, F j, Y, g:i a") ;

                        $message = " $todayis \n
                        Attention: \n\n
                        Please see the message below: \n\n
                        Email Address: $email \n\n
                        Message: $message \n\n

                        ";

                        $from = "From: $email\r\n";


                        //put your email address here
                        mail("[email protected]", $subject, $message, $from);

                        //prep json response
                        $ajaxresponse['type'] = 'success';
                        $ajaxresponse['message'] = 'Thank You! Will be in touch soon';  
                } catch(Exception $e){
                        $ajaxresponse['type'] = 'error';
                        $ajaxresponse['message'] = $e->getMessage();
                }
                // now we are ready to turn this hash into JSON
                print json_encode($ajaxresponse);
                exit;
        }
?>

So, are there any security problems when using forms to send emails? Is this ok? Thanks!

Upvotes: 2

Views: 833

Answers (7)

dipmala
dipmala

Reputation: 2011

You should add captcha , client side and server side validation in form

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75635

In general, rule of the thumb should always be: NEVER trust user provided data. And no, your code is not bullet proof. Since you do not verify nor sanitize user input and you use mail() at the same time you are vulnerable. User can easily feed you with crafted value for email4 filed. Since you use form data directly, then email4 can be used to inject additional mail headers to your outgoing mail. It these headers would be BCC: or CC: or even TO: then then you would be simply acting as spam relay. For example if I post this

[email protected]
CC: [email protected], [email protected], [email protected],
X-Spam-Owned: Whoa

as your email4 then your header would end looking like this:

To: [email protected]
CC: [email protected], [email protected], [email protected], 
X-Spam-Owned: Whoa

to post multiline data you simply glue texts with CRLFs.

To avoid security holes like this you should consider dropping mail() and use something more clever that would take care of something like this too (not that mail() is bad, but you need to know what you are doing as it is rather low than high level function). I suggest using PHPMailer or similar package. You should always verify user provided data (especially ensure that single-line fields, like subject are really single line - stripping CRLFs suffice). Add captcha as you are open to automated form submission.

Upvotes: 6

haynar
haynar

Reputation: 6040

Even if you are not working with database, there could be security problems in email sending. Of course you can't be hacked by this form, but the problems will occure when the user will input something like this in EMail field:

[email protected]  // there is a new line here
CC:[email protected],[email protected],[email protected]

so the best you can do is sanitizing all the input fields for mail function, to prevent such spam delivery. And as @WebnetMobile.com has already sad, never trust user inputs

Upvotes: 1

techie_28
techie_28

Reputation: 2133

You can additionally wrap your server side code with

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  /* special ajax here */
  die($content);
}

This will ensure the ajax request is coming on the server.

And please mind your ID that you are using in one of your jQuery selector in your question.

Upvotes: 1

user399666
user399666

Reputation: 19909

  1. You could add a captcha to prevent spam.
  2. You could protect against email injections by using:

    filter_var($email, FILTER_VALIDATE_EMAIL)

Upvotes: 3

Bang Dao
Bang Dao

Reputation: 5112

I think this form is safe, mean that no one can really h@ck your website throught this form.
But you need to add somethings for better result: 1. You should also check the post variable in php server side, mean that you should check if email / name / message is valid of not
2. You should add some captcha to prevent spam

Upvotes: 1

Peon
Peon

Reputation: 8030

I don't see a security issue in there, since you are not modifying anything on your server side. Might be an issue with spam though. Add some captcha to it. The rest looks ok.

Upvotes: 0

Related Questions