-9

Am using proper PDO prepared statements and allow user to enter certain input and store those input to SQL

BUT

My entire SQL table is dropped can someone please help me what wrong i made bellow

CODE

    <?php

$db_username = 'sanoj';
$db_password = '123456';
$newname = md5(rand() * time());
if (isset($_FILES['files'])) {
    $uploadedFiles = array();
    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
        $errors = array();
        $file_name = md5(uniqid("") . time());
        $file_size = $_FILES['files']['size'][$key];
        $file_tmp = $_FILES['files']['tmp_name'][$key];
        $file_type = $_FILES['files']['type'][$key];

        if ($file_type == "image/gif") {
            $sExt = ".gif";
        } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
            $sExt = ".jpg";
        } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
            $sExt = ".png";
        }
        if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
            $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
        }
        if ($file_size > 2097152000) {
            $errors[] = 'File size must be less than 2 MB';
        }
        $desired_dir = "user_data/";
        if (empty($errors)) {
            if (is_dir($desired_dir) == false) {
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
                $uploadedFiles[$key] = array($file_name . $sExt, 1);
            } else {
                echo "Couldn't upload file " . $_FILES['files']['name'][$key];
                $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
            }
        } else {

        }
    }

    foreach ($uploadedFiles as $key => $row) {
        if (!empty($row[1])) {
            $codestr = '$file' . ($key + 1) . ' = $row[0];';
            eval($codestr);
        } else {
            $codestr = '$file' . ($key + 1) . ' = NULL;';
            eval($codestr);
        }
    }
}
$orig_directory = "$desired_dir";    //Full image folder
$thumb_directory = "thumb/";    //Thumbnail folder

/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = @opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1) { //Check to make sure the folder opened
    $allowed_types = array('jpg', 'jpeg', 'gif', 'png');
    $file_type = array();
    $ext = '';
    $title = '';
    $i = 0;

    while ($file_name = @readdir($dir_handle)) {
        /* Skipping the system files: */
        if ($file_name == '.' || $file_name == '..')
            continue;

        $file_type = explode('.', $file_name);    //This gets the file name of the images
        $ext = strtolower(array_pop($file_type));

        /* Using the file name (withouth the extension) as a image title: */
        $title = implode('.', $file_type);
        $title = htmlspecialchars($title);

        /* If the file extension is allowed: */
        if (in_array($ext, $allowed_types)) {

            /* If you would like to inpute images into a database, do your mysql query here */

            /* The code past here is the code at the start of the tutorial */
            /* Outputting each image: */

            $nw = 100;
            $nh = 100;
            $source = "$desired_dir{$file_name}";
            $stype = explode(".", $source);
            $stype = $stype[count($stype) - 1];
            $dest = "thumb/{$file_name}";

            $size = getimagesize($source);
            $w = $size[0];
            $h = $size[1];

            switch ($stype) {
                case 'gif':
                    $simg = imagecreatefromgif($source);
                    break;
                case 'jpg':
                    $simg = imagecreatefromjpeg($source);
                    break;
                case 'png':
                    $simg = imagecreatefrompng($source);
                    break;
            }

            $dimg = resizePreservingAspectRatio($simg, $nw, $nh);
            imagepng($dimg, $dest);
        }
    }

    /* Closing the directory */
    @closedir($dir_handle);
}

try {
#connection 
    $conn = new PDO('mysql:host=localhost;dbname=localtest', $db_username, $db_password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $data = $conn->prepare('INSERT INTO agriculture (cacat, mtype, mtitle, image1, image2, image3, image4, image5, description, mcondition, cmodel, price, youare, mname, email, phone, ylocation, ystreet) VALUES (:cacat, :mtype, :mtitle, :image1, :image2, :image3, :image4, :image5, :description, :mcondition, :cmodel, :price, :youare, :mname, :email, :phone, :ylocation, :ystreet)');
    $cacat = filter_input(INPUT_POST, 'cacat', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $mtype = filter_input(INPUT_POST, 'mtype', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $mtitle = filter_input(INPUT_POST, 'mtitle', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $mcondition = filter_input(INPUT_POST, 'mcondition', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $cmodel = filter_input(INPUT_POST, 'cmodel', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $price = filter_input(INPUT_POST, 'price', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $youare = filter_input(INPUT_POST, 'youare', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $mname = filter_input(INPUT_POST, 'mname', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $ylocation = filter_input(INPUT_POST, 'ylocation', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $ystreet = filter_input(INPUT_POST, 'ystreet', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
    $data->execute(array(':cacat' => $cacat,
        ':mtype' => $mtype,
        ':mtitle' => $mtitle,
        'image1' => $file1,
        'image2' => $file2,
        'image3' => $file3,
        'image4' => $file4,
        'image5' => $file5, ':description' => $description, ':mcondition' => $mcondition, ':cmodel' => $cmodel, ':price' => $price, ':youare' => $youare, ':mname' => $mname, ':email' => $email, ':phone' => $phone, ':ylocation' => $ylocation, ':ystreet' => $ystreet));
#exception handiling
} catch (PDOException $e) {
    echo $e->getMessage();
}

function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
    $srcWidth = imagesx($img);
    $srcHeight = imagesy($img);

    // Determine new width / height preserving aspect ratio
    $srcRatio = $srcWidth / $srcHeight;
    $targetRatio = $targetWidth / $targetHeight;
    if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
        $imgTargetWidth = $srcWidth;
        $imgTargetHeight = $srcHeight;
    } else if ($targetRatio > $srcRatio) {
        $imgTargetWidth = (int) ($targetHeight * $srcRatio);
        $imgTargetHeight = $targetHeight;
    } else {
        $imgTargetWidth = $targetWidth;
        $imgTargetHeight = (int) ($targetWidth / $srcRatio);
    }

    // Creating new image with desired size
    $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);

    // Add transparency if your reduced image does not fit with the new size
    $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
    imagefill($targetImg, 0, 0, $targetTransparent);
    imagecolortransparent($targetImg, $targetTransparent);

    // Copies image, centered to the new one (if it does not fit to it)
    imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

    return $targetImg;
}

?>

Even in my previous QUESTION i asked about how to have multiple filter for input in PDO Since i have certain filter to validate user input but my table is dropped can someone help me please this is serious problem

SQL

create table `agriculture`(
`id` int(9) NOT NULL auto_increment,
`cacat` varchar(255) NOT NULL default '',
`mtype` varchar(255) NOT NULL default '',
`mtitle` varchar(255) NOT NULL default '',
`image1` varchar(255) NOT NULL default '',
`image2` varchar(255) NOT NULL default '',
`image3` varchar(255) NOT NULL default '',
`image4` varchar(255) NOT NULL default '',
`image5` varchar(255) NOT NULL default '',
`description` varchar(255) NOT NULL default '',
`mcondition` varchar(255) NOT NULL default '',
`cmodel` varchar(255) NOT NULL default '',
`price` varchar(255) NOT NULL default '',
`youare` varchar(255) NOT NULL default '',
`mname` varchar(255) NOT NULL default '',
`email` varchar(255) NOT NULL default '',
`phone` varchar(255) NOT NULL default '',
`ylocation` varchar(255) NOT NULL default '',
`ystreet` varchar(255) NOT NULL default '',
`ipnu` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 ;

Make above code PROTECT from SQL injection and XSS (Cross site scripting)

SOLVE

make this code Protect from SQL injection and XSS (Cross site scripting) attack and use basename() method while file uploaing

who solve this will be awared

Community
  • 1
  • 1
stack user
  • 11
  • 7
  • A prepared statement with sanitized input doesn't 100% prevent SQL injection. – Brian Driscoll Dec 24 '14 at 06:20
  • So what is the procedure to prevent i need to prevent SQL injection can you please help me i need to protect from hacking – stack user Dec 24 '14 at 06:23
  • There is no 100% effective solution. With enough time and creativity any query that takes user input can be injected. – Brian Driscoll Dec 24 '14 at 06:26
  • 2
    http://stackoverflow.com/q/134099/ – Funk Forty Niner Dec 24 '14 at 06:28
  • 1
    @stackuser, so, how can you be sure that your application was hacked? How can you be sure that it was hacked through this query? – sectus Dec 24 '14 at 06:32
  • 2
    I can't solve anything for you. You will need to read through that link along with any other links on that page. There is no "magic silver bullet". You should also read into XSS (Cross site scripting) http://en.wikipedia.org/wiki/Cross-site_scripting which you may be a victim of, and Google that term also. I suggest you look through Stack's http://security.stackexchange.com/ and also Code review http://codereview.stackexchange.com/ where you can post your code/question there. You will get a better response in one of those. – Funk Forty Niner Dec 24 '14 at 06:37
  • 1
    See also http://stackoverflow.com/q/5741187/ – Funk Forty Niner Dec 24 '14 at 06:37
  • @sectus application was hacked i think table is been dropped `mysql_real_escape_string` is missing in my stament – stack user Dec 24 '14 at 06:39
  • @stackuser , forget about this function – sectus Dec 24 '14 at 06:41
  • @Fred-ii- i posted my code codereview.stackexchange.com i got response that i should `mysql_real_escape_string` but mysql_real_escape_string is Deprecated – stack user Dec 24 '14 at 06:41
  • Did you mention the fact that you were using PDO? You know you can't mix those 2 APIs. Plus, what is the link to your post there? – Funk Forty Niner Dec 24 '14 at 06:42
  • @sectus how can i add `mysql_real_escape_string` but `mysql_real_escape_string` is Deprecated can you help me to add mysql_real_escape_string in PDO – stack user Dec 24 '14 at 06:43
  • @stackuser, please, add link to your question on codereview – sectus Dec 24 '14 at 07:12
  • @sectus http://codereview.stackexchange.com/questions/74512/unable-to-make-pdo-with-prepared-statements code will be different but same method – stack user Dec 24 '14 at 07:22
  • Ah so it's about uploading files. That's why you're getting attacked, you have a security hole in your form and in your PHP. You need to use `basename` http://php.net/manual/en/function.basename.php you didn't post that in your question here. See also http://stackoverflow.com/q/2347056/ – Funk Forty Niner Dec 24 '14 at 07:26
  • @Fred-ii- my text input are protected from `SQL injection` may be 50% **i need to create security for files** is it right – stack user Dec 24 '14 at 07:32
  • That is exactly right. – Funk Forty Niner Dec 24 '14 at 07:32
  • @Fred-ii- how safe is my text input – stack user Dec 24 '14 at 07:36
  • They should be fine, it's your files. You should also post your HTML form that goes with your code. But I can't view it right now, I have to go to bed. Post it and I'll check it later. – Funk Forty Niner Dec 24 '14 at 07:37
  • @stackuser , there is no answers at all. Where is `mysql_real_escape_string` mentioning? – sectus Dec 24 '14 at 07:53
  • @Fred-ii- here is my form http://jsfiddle.net/a9sf4w2w/ and php processing http://codereview.stackexchange.com/questions/74512/unable-to-make-pdo-with-prepared-statements – stack user Dec 24 '14 at 08:00
  • @sectus `mysql_real_escape_string` is Deprecated can you help me to add mysql_real_escape_string in PDO – stack user Dec 24 '14 at 16:26
  • are you saying someone hacked you and dropped your table – meda Dec 24 '14 at 16:31
  • @Fred-ii- have you find – stack user Dec 25 '14 at 13:54

1 Answers1

2

Some things I recommend you.

Remove all unneeded privileges to the webapplication database user. If your web application doesn't needs the drop, it should not have that privilege (review all of them). I recommend you in the future to consider PostgreSQL instead of MySQL if you are looking for open source Database server as privileges are more finegrained. This will not fix an SQL injection but would mitigate.

The file uploaded as image can actually be a php code and it could be included in another file or even maybe executed directly. Therefore I highly recommend you to put the folder somewhere it cannot be interpreted or included. Check this thread for instance.

GIF/Jpeg File containing PHP code

Be very very careful with the eval calls.

If you still are unsure of your SQL code (to me looks ok buy I could be missing something) I highly recommend you to not follow the SQL statement blacklisting. Blacklisting is totally the wrong approach. If unsure you can try this since you are using MySQL

http://www.greensql.com/

To protect against XSS I recommend you this library:

http://htmlpurifier.org/

These are not the only things you should protect against. Consider CSRF and session fixation attacks for example.

Hope it helps.

Community
  • 1
  • 1
Waldo Alvarez
  • 314
  • 1
  • 11
  • but i want those code secure if i follow your answer i need to have lots of changes in my pages –  Dec 29 '14 at 07:03
  • not everything I recommend you is a change in your code. Database privileges, greensql installation and selecting another folder is just configuration. HtmlPurifier is just a couple of lines. Session fixation is very simple too, check this code: http://en.wikipedia.org/wiki/Session_fixation#Defense_in_depth – Waldo Alvarez Dec 29 '14 at 07:20
  • For CSRF the code is a little bit larger but is already done: http://www.wikihow.com/Prevent-Cross-Site-Request-Forgery-(CSRF)-Attacks-in-PHP All you have to do is copy/paste the class once and call methods for each form printing and form processing to ensure same origin. – Waldo Alvarez Dec 29 '14 at 07:33
  • if you could make `CSRF` with above code i could make bounty how could i award answer with links –  Dec 29 '14 at 16:34
  • Problem that is work, not a question. Seems that is why it is being downvoted. If you want I can offer you a complete code review since likely that is not the only place you have security problems, and fix your web application in a more proper place like freelancer for instance. – Waldo Alvarez Dec 29 '14 at 20:00
  • Sorry not enough rep. Can you please share your sql schema structure to upload to my local server and not have to recreate the table. I see just right away a reflected XSS and seems basename is not required as you are just generating a random filename. – Waldo Alvarez Dec 30 '14 at 00:04
  • @WaldoAlvarez added sql schema structure – stack user Dec 30 '14 at 09:13