Я испытываю неустанную атаку XSS, которую я не могу предотвратить. У меня есть три общей формы ввода на моем сайте - одна для загрузки изображений, одна для добавления комментариев к странице, а третья - по электронной почте через php. Я защищаю их все так или иначе, но почему-то уязвимость все еще существует.Определение уязвимостей атаки XSS
Мои комментарии Код:
for($j = 0; $j < 3 ; $j++)
{
$s = $styles[array_rand($styles)];
if($song_arr[$k] != '' && $artist_arr[$k] != '' && $name_arr[$k] != '')
{
echo '<td>';
echo '<div class="'.$s.'" style="clear:left" >';
echo '<p class="rendom">';
echo 'Song: '.htmlspecialchars($song_arr[$k]).'<br>Artist: '.htmlspecialchars($artist_arr[$k]).'<br>Submitted By: '.htmlspecialchars($name_arr[$k]);
echo '</p>';
echo '</div>';
echo '</td>';
}
$k++;
}
Загрузить Форма:
if ((($_FILES["userfile"]["type"] == "image/jpg")
|| ($_FILES["userfile"]["type"] == "image/jpeg")
|| ($_FILES["userfile"]["type"] == "image/pjpeg"))
&& ($_FILES["userfile"]["size"] < 20000)) {
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
if (move_uploaded_file ($_FILES['userfile']['tmp_name'],'userfile.jpg')) {
$image = new SimpleImage();
$image->load('userfile.jpg');
$image->resize(29,136);
$image->save('userfile.jpg');
?>
<img src="img/text/uploadSuccess.jpg" alt="Image uploaded successfully." /><br />
<br />
<img src="userfile.jpg?rand=<? echo rand(1,10000); ?>" />
<?
} else {
echo 'Moving uploaded file failed';
}
} else {
echo 'File upload failed';
}
} else {
echo 'Invalid Filetype';
}
Email Форма:
<?php
// Process input variables (trim, stripslash, reformat, generally prepare for email)
$recipients = trim($_POST['recipients']);
$sender_email = trim($_POST['sender_email']);
$sender_name = stripslashes(trim($_POST['sender_name']));
$subject = stripslashes(str_replace(array("\r\n", "\n", "\r"), " ", trim($_POST['subject'])));
$message = stripslashes(str_replace(array("\r\n", "\n", "\r"), "<br />", trim($_POST['message'])));
// Check email addresses for validity
// Explode the comma-separated list of recipients + the sender email address into an array. Even if there is only one recipient, this will check for validity.
$addresses = explode("," , $recipients.",".$sender_email);
// For each email address specified...
foreach ($addresses as $address) {
// If the email address doesn't match the RFC8622 spec regex, assume invalid
if (!(preg_match("~^[A-Z0-9._%+-][email protected](?:[A-Z0-9-]+\.)+(?:[A-Z]{2}|com|org|net|uk|edu|jp|de|br|ca|gov|au|info|nl|fr|us|ru|it|cn|ch|tw|es|se|be|dk|pl|at|il|tv|nz|biz)$~i", trim($address)))) {
// Output error message for invalid email address and end script.
echo '"' . $address . '" is not a valid email address. Please try again.';
return;
}
}
// Check other vars are not empty
if ((empty($sender_name)) OR (empty($subject)) OR (empty($message))) {
// Output error message and end script.
echo 'Please complete all form fields and try again.';
return;
}
// Send HTML email
$headers = "MIME-Version: 1.0\r\nContent-type:text/html;charset=iso-8859-1\r\nFrom: ". $sender_name ." <". $sender_email ."> \n\n";
if (mail($recipients,$subject,$message,$headers)) {
// Mail successfully sent, output success message and end script
echo 'Message sent. We will be in touch with you shortly.';
return;
} else {
// Something unknown went wrong. =(
echo 'Something went wrong which the little worker monkeys could not fix. Please try again.';
return;
}
?>
XSS-держит показ в абсолютном нижней части моей страницы индекса, в который включает() все три вышеупомянутых файла, содержимое которых находится в разных файлах.
Любые идеи?
Хороший улов, вы думаете, что XSS, вставленный здесь, мог каким-то образом встать в нижней части страницы, даже для последующих загрузок страниц на разных машинах? –
Нет, не может. Такая вставка представляет собой непостоянный XSS (http://en.wikipedia.org/wiki/Cross-site_scripting#Non-persistent) и влияет только на пользователя, который отправил запрос. Твое злое;)! – Wookai
Я собираюсь пойти с Вукаем и утверждать, что злоумышленник получил один из своих сценариев на вашем сервере. Кроме того, в том числе файл, путь которого вы получаете путем конкатенации «inc /», переменная GET «страница» и «.inc.php» запрашивает проблемы. Если ваш PHP-код находится в/home/dave и мой находится в/home/eric, я мог бы открыть одну из ваших страниц с помощью «page = ../../eric/evil_script» в строке запроса и сделать вашу страницу включенной мой файл evil_script.inc.php. – ArIck