tony
tony

Reputation: 85

remote javascript-ajax-php attack

Javascript is a client-side language, so scripts can be read and copied.

Now consider this example.

<html>
<head>
<title>title</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<body>
    <script type="text/javascript">
    $(document).ready(function () {
        $('#user').blur(function () {
            var dataString = 'user=' + user;
            $.ajax({
                type: "POST",
                url: "insertUser.php",
                data: dataString
            }
        }
    }
    </script>
    <label for='user' >User:</label>
    <input id="user"  type="text" />
</body>

insertUser.php :

<?php
$user = filter_input(INPUT_POST, 'user');
if (isset($user)) {
    require_once("class.Database.php");
    $db = Database::getInstance();
    $mysqli = $db->getConnection();
    $stmt = $mysqli->prepare("INSERT INTO Users (User) VALUES (?)");
    $stmt->bind_param("s", $user);
    $stmt->execute();
}

Could someone write a script in his localhost for inserting his own data using the path to insertUser.php? Anyway to solve this?

Upvotes: 0

Views: 61

Answers (3)

Kheshav Sewnundun
Kheshav Sewnundun

Reputation: 1244

Could someone write a script in his localhost for inserting his own data using the path to insertUser.php?

Yes, anyone can post its own data using the path to insertUser.php

Anyway to solve this?

1. Check if request is of type Ajax and comming from your domain

if(($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') && ($_SERVER['HTTP_REFERER']=="http://yourdomain/url")) {
 //Is ajax call
}


2. Cross-origin policy; that is denying post from other domains.

3. Generating tokens and validating the token on server side.

Upvotes: 0

Nouman Arshad
Nouman Arshad

Reputation: 593

There are many ways to stop user supplied malicious data inserting into database.

Regarding your situation, you can do the following steps:

  1. Check the incoming ajax calls generated from your server.
  2. Add CSRF through out in your application
  3. Always clean inserted data into your database which is called SQL Injection, you can read about SQL injection in OWSAP
  4. Always use htmlentities() Search for htmlentities php function to display output on the screen

Thanks, I hope this will surely help you to understand the security.

Upvotes: 0

J&#225;n Stibila
J&#225;n Stibila

Reputation: 637

Yes, anyone can send any data to your insertUser.php

About protection, that depend on use-case. Chceck who is sending data, authorize any request that should be authorized etc.

Best practice is to treat any data from outside (no matter where they came from) as if they were the most dangerous and malicious.

Upvotes: 1

Related Questions