Feedback needed for my XSS CSRF in php form

Security issues related to php and mysql usage. How to make your code secure? Security measures and configurations? It's all in here!

Moderators: egami, macek, gesf

Post Reply
netero
New php-forum User
New php-forum User
Posts: 1
Joined: Mon Nov 06, 2017 4:14 pm

Mon Nov 06, 2017 4:27 pm

<r>Hello i am new to php security and i try to learn(some parts) applying it to mail() function<br/>

Can you please comment on my code if i do the XSS and CSRF correctly with ajax and is it secure enough or maybe i need to add something? please ignore the front end its just some copy paste.<br/>

2)Do i really need data validation checks in my mailer.php because i use the html5 form validation checks is that ok?

3)And do i need another die(); after the mail was send(the red comment) and maybe that unset is not needed?(the red comment) i am not sure about it<br/>

4)Also i have CSRF , do i need Google reCAPTCHA? or its CSRF or the reCAPTCHA but not both of them together?<br/>



INDEX.PHP</B>
<CODE><s>

Code: Select all

</s><i>
</i><?php
session_start();
if(empty($_SESSION['token'])){
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$key =$_SESSION['token'];
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Website Contact Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
	_("submit-button").disabled = true;
	_("status").innerHTML = 'please wait ...';
	var formdata = new FormData();
	formdata.append( "name", _("name").value );
	formdata.append( "email", _("email").value );
	formdata.append( "comments", _("comments").value );
        formdata.append( "key", _("key").value );
    
	var ajax = new XMLHttpRequest();
	ajax.open( "POST", "mail.php" );
	ajax.onreadystatechange = function() {
		if(ajax.readyState == 4 && ajax.status == 200) {
			if(ajax.responseText == "success"){
				_("contact-form").innerHTML = '<h2>Ευχαριστώ '+_("name").value+', το μήνυμα σου στάλθηκε</h2>';
			} else {
				_("status").innerHTML = ajax.responseText;
				_("submit-button").disabled = false;
			}
		}
	}
	ajax.send( formdata );
        
}
</script>
</head>
<body>


<form id="contact-form" onsubmit="submitForm(); return false;" method="post">
           
            <label style="color:wheat;" for="name">Ονομα *</label>
            <div class="form-group">
                <input id="name" placeholder="Το όνομα σου" type="text" class="form-control" style="width: 30%" required>
            </div>
            
            <label style="color:wheat;" for="email">Email *</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
                <input id="email" style="width: 26%" class="form-control" type="email" placeholder="Το Email σου" required>
            </div>
 
            <label style="padding-top: 8px; color:wheat;" for="comments">Σχόλια *</label>
            <div class="form-group">
                <textarea id="comments" placeholder="Γράψε μας ένα μήνυμα με τυχόν ερωτήσεις/απορίες που έχεις και θα σου απαντήσουμε άμεσα!" class="form-control" rows="8" style="resize:none;" required></textarea>
            </div>
 
            <div class="form-group">
                <input id="submit-button" name="submit" type="submit" value="Αποστολή" class="btn btn-info btn-block">
                <input type="hidden" id="key" name="key" value="<?php echo $key; ?>">
                <span id="status"></span>
            </div>
  
</form>

<div>
<br>
<p>
This is some random text it stays here so you can see the AJAX magic tricks
</p>
</div>


</body>
</html>
<e>
</e></CODE>

<br/>
MAIL.PHP
<CODE><s>

Code: Select all

</s><i>
</i><?php
session_start();

function escape_tags($str){
    return htmlentities($str, ENT_QUOTES, 'UTF-8');  
}
function header_injection($str){
    return preg_match("/[\r\n]/", $str);
}

//CSRF code
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
    if(!empty($_POST['key'])){
          if(hash_equals($_SESSION['token'], $_POST['key'])){
//CSRF code 

if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['comments']) ){
	$name_value = escape_tags(trim($_POST['name'])); 
	$email_value = escape_tags(trim($_POST['email']));
	$message_value = escape_tags(nl2br($_POST['comments']));
    
    if(header_injection($name_value) || header_injection($email_value)){
      die();
     } 


	$to = "myemail@gmail.com";	
	
	$subject = 'Contact Form Message';
	$message = '<b>Name:</b> '.$name_value.' <br><b>Email:</b> '.$email_value.' <hr><p>'.$message_value.'</p>';
	$headers = "From: $email_value\n";
	$headers .= "MIME-Version: 1.0\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\n";

	if( mail($to, $subject, $message, $headers) ){
		echo "success";
	} else {
		echo "The server failed to send the message. Please try again later.";
	}
}


[color=#FF0000]//do i need another die(); here?[/color]
//CSRF code here
}
        else{
   [color=#FF0000]     unset($_SESSION['token']); [/color]            
die('CSRF is invalid');
            }
    }          
    
    else{
        die('CSRF token not found');
    }
    
}
    
?>

<e>
</e></CODE>

https://markusruhll.000webhostapp.com

Post Reply