10/10/2018, 00:11

lỗ hổng bảo mật

file index này có 1 số lỗ hổng bảo mật, em tìm được 1 số lỗi như user name và password nhưng kô biết sửa thế nào, có bác nào giúp em với được kô? các bác hướng dẫn em thêm 1 chút để có thể vá các lỗi bảo mật được kô? cám ơn mọi người trước ^_^
<html>
<head>
<meta http-equiv="Content-Language" content="en" />
<meta name="GENERATOR" content="Zend Studio" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simple message board</title>
</head>
<body bgcolor="#CCAAFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">
<h1>Simple message board</h1>
<?php

$dbServer = "localhost"; // needs to be "web334.cs.auckland.ac.nz" when you submit
$database = "messageboard"; // replace this by the database name on web334 (=your UPI)
$dbUser = "user334"; // replace this by your own UPI
$dbPassword = "myfunnypasswd"; // replace this by your database password

// Simple connection setup - note: lack of proper error handling here is NOT a security
// hole (it merely looks ugly)
if ($connection = @mysql_connect($dbServer, $dbUser, $dbPassword)) {
if (!@mysql_select_db($database,$connection)) {
// If you get an error here, you probably haven't set up the
// database correctly
echo "Error: Could log into DB server but database is not accessible. Reason: ";
echo mysql_error();
exit();
}
}
else
{
// If you get an error here, you either haven't set up your
// database password correctly, or you have been hacked :-(
echo "Error: Cannot connect to database server: ";
echo mysql_error();
exit();
}

// we've learned that much: always initialise variables
$loggedIn = false;
$loggedInAsAdmin = false;

// check login data
// Note: The fact that the database stores the password in plain
// text does not on its own represent a security hole in the context
// of this assignment.
$user = $_POST["USER"];
$password = $_POST["PASSWORD"];
$query = "select * from users where userId='$user' and userPassword='$password'";
$queryResultHandle = mysql_query($query);
if (mysql_num_rows($queryResultHandle) > 0) {
$queryResult = mysql_fetch_assoc($queryResultHandle);
// user exists and is authenticated
$loggedIn = true;
// get the user's full name from the database record
$name = $queryResult["userName"];
echo "<h3>User: $name</h3>";
// check whether it is an admin user
if ($queryResult["userIsAdmin"] == "1") {
$loggedInAsAdmin = true;
}
}

if (!$loggedIn) {
// Case 1: User is not logged in
// - Escape from PHP mode to show login form.
// - Pre-complete form with username, if any was specified
?>
<form action="./index.php" method="POST">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="USER"
value="<?php echo $user; ?>">
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="PASSWORD">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Login">
</td>
</tr>
</table>
</form>
<?php
}
else
{
// Case 2 or 3
$showList = true;
// Check whether we need to show a special form
// and include it if need be. Also, do any save,
// update or delete of messages, users or passwords
switch ($_POST["MODE"]) {
case "NEWUSER":
if (!$loggedInAsAdmin) {
exit();
}
case "NEWPASS":
case "NEWMESS":
// All these cases require a form to be shown.
// Include the respective form from its external
// file:
include($_POST["MODE"].".php");
include("./COMMONFORM.php");
// Also, we don't show the list of messages in this case
$showList = false;
break;
case "SAVEPASS":
// If a change of user ID has been requested, make
// sure that the new user doesn't already exist
if ($user != $_POST["NEWUSERID"]) {
$query = "select * from users where userId='{$_POST["NEWUSERID"]}'";
$queryResultHandle = mysql_query($query);
if (mysql_num_rows($queryResultHandle) > 0) {
echo "<p><b>User ID for user <i>$user</i> could not be changed
because the new id is already in use!</b></p>";
include("NEWPASS.php");
include("./COMMONFORM.php");
$showList = false;
break;
}
// If we get here, the new user ID is unique
}
// check whether the passwords match
if ($_POST["NEWPASSWORD1"] == $_POST["NEWPASSWORD2"]) {
// Passwords match, so update database
$query = "update users
set userId = '{$_POST["NEWUSERID"]}',
userPassword = '{$_POST["NEWPASSWORD1"]}'
where userId = '$user'";
if (@mysql_query($query)) {
echo "<p><b>Password for user <i>$user</i> updated!</b></p>";
// use new user ID and password from now on
rename("messages/$user","messages/".$_POST["NEWUSERID"]);
$user = $_POST["NEWUSERID"];
$password = $_POST["NEWPASSWORD1"];
}
else
{
echo "<p><b>Password for user <i>$user</i> could not be updated because of a database problem!</b></p>";
}
}
else
{
echo "<p><b>New passwords do not match! Please try again.</b></p>";
// show form again and suppress message list
include("NEWPASS.php");
include("./COMMONFORM.php");
$showList = false;
}
break;
case "SAVEUSER":
// First, make sure that we are logged in as admin.
// If not, exit here.
if (!$loggedInAsAdmin) {
exit();
}
// Ensure that we have entered a user ID:
if ($_POST["NEWUSERID"] == "") {
echo "<p><b>Could not save user - no ID specified!</b></p>";
break;
}
if ($_POST["NEWPASSWORD1"] == "") {
echo "<p><b>Could not save user - no password specified!</b></p>";
break;
}
// Now make sure that the user doesn't already exist
$query = "select * from users where userId='{$_POST["NEWUSERID"]}'";
$queryResultHandle = mysql_query($query);
if (mysql_num_rows($queryResultHandle) == 0) {
// This user name is new indeed!
// Check whether the passwords match
if ($_POST["NEWPASSWORD1"] != $_POST["NEWPASSWORD2"]) {
include("NEWUSER.php");
include("./COMMONFORM.php");
$showList = false;
break;
}
$query = "insert into users (userId, userName, userPassword, userIsAdmin)
values ('{$_POST["NEWUSERID"]}',
'{$_POST["NEWUSERNAME"]}',
'{$_POST["NEWPASSWORD1"]}',
0)";
if (!@mysql_query($query)) {
echo "<p><b>Could not save user - something is wrong!</b></p>";
break;
}
}
else
{
echo "<p><b>User could not be saved. Reason: User already exists!</b></p>";
break;
}
// One last thing needs to be done: We need to create
// a default message file for the user.
file_put_contents("messages/".$_POST["NEWUSERID"],
"<"."?php $messages=array(); ?".">");
// Done!
echo "<h3>User <b>".$_POST["NEWUSERID"]."</b> created</h3>";
break;
case "SAVEMESS":

@include("messages/".$user);
// If the file exists, we should now have a $messages array.
// Generate a unique ID for the new message:
$messageId = uniqid("");
// Now generate the contents for the new message file.
// Start with the opening PHP tag, split here across two
// strings to avoid syntax problems in some editors:
$contents = "<?"."php $messages = array(";
// Add existing messages through a loop
foreach ($messages as $existingMessageId => $message) {
$contents .= "'$existingMessageId' => array(
'userId' => '$user',
'title' => '".$message["title"]."',
'text' => '".$message["text"]."'
), ";
}
// Add the latest message by appending:
$contents .= "'$messageId' => array(
'userId' => '$user',
'title' => '".$_POST["NEWMESSTITLE"]."',
'text' => '".$_POST["NEWMESSTEXT"]."'
)";
// Close $messages array and PHP tag
$contents .= "); ?".">";
// Save file
file_put_contents("messages/".$user,$contents);
echo "<h3>Message <i>".$_POST["NEWMESSTITLE"]."</i> saved</h3>";
break;
case "DELETEUSER":
// We must be admin to delete a user
// First, make sure that we are logged in as admin.
// If not, exit here.
if (!$loggedInAsAdmin) {
exit();
}
// Delete user from database:
$query = "delete from users where userId = '{$_POST["USERTODELETE"]}'";
if (!@mysql_query($query)) {
echo "<p><b>Could not delete user - something is wrong!</b></p>";
break;
}
// Delete user's messages
unlink("messages/".$_POST["USERTODELETE"]);
echo "<h3>User <b>".$_POST["USERTODELETE"]."</b> removed</h3>";
break;
case "DELETEMESS":
// We must be admin to delete a message
// First, make sure that we are logged in as admin.
// If not, exit here.
if (!$loggedInAsAdmin) {
exit();
}
// Load all messages for the sender
@include("messages/".$_POST["SENDER"]);
// If the file exists, we should now have a $messages array.
// Save message title:
$title = $messages[$_POST["MESSAGETODELETE"]]["title"];
// Generate the contents for the new message file,
// skipping the message to be deleted.
// Start with the opening PHP tag, split here across two
// strings to avoid syntax problems in some editors:
$contents = "<?"."php $messages = array(";
// Add existing messages through a loop
$commaFlag = false; // remember whether we've added commas to $contents
foreach ($messages as $messageId => $message) {
if ($messageId == $_POST["MESSAGETODELETE"]) continue;
$contents .= "'$messageId' => array(
'userId' => '".$message["userId"]."',
'title' => '".$message["title"]."',
'text' => '".$message["text"]."'
), ";
$commaFlag = true;
}
// Remove trailing comma
if ($commaFlag) {
$contents = substr($contents, 0, strlen($contents) - 2);
}
// Close $messages array and PHP tag
$contents .= "); ?".">";
// Save file
file_put_contents("messages/".$_POST["SENDER"],$contents);
echo "<h3>Message <b>$title</b> deleted</h3>";
break;
default: break;
}

//
// At this point, all forms have been shown and all
// housekeeping has been done. Show the list of messages
// where applicable.
//
$allMessages = array();
//
// Grab a list of all users from the database
//
$query = "select * from users";
$queryResultHandle = mysql_query($query);
// Aggregate all messages by looping through users
// and loading their messages
while ($userRecord = mysql_fetch_assoc($queryResultHandle)) {
// Keep hold of the user information
$users[$userRecord["userId"]] = $userRecord;
// Add the messages for this user
include("messages/".$userRecord["userId"]);
$allMessages = array_merge($allMessages, $messages);
}
// Sort the messages by age (same as sorting by ID)
ksort($allMessages,SORT_STRING);
// Output messages as a table
echo "<p><table border="1">";
// Loop through messages array, output each message as a table row
foreach ($allMessages as $messageId => $message) {
echo "<tr>";
// Set variables for cell template
$sender = $message['userId'];
$userName = $users[$sender]["userName"];
// Include template
include("MESSAGE.php");
// If the user is an admin, we also need a form for
// deletion of the message and/or user
if ($loggedInAsAdmin) {
include("DELETEFORM.php");
}
echo "</tr>";
}
// Close table tag
echo "</table></p>";
// Add buttons for new messages and password change
include("BUTTONS.php");
if ($loggedInAsAdmin) {
include("ADMINBUTTON.php");
}
} // end of authenticated user processing
?>
</body>
</html>
jiSh@n viết 02:19 ngày 10/10/2018
Lỗ hổng to dùng: ko filter dữ liệu trước khi đưa vào câu query.
vnz viết 02:18 ngày 10/10/2018
$query = "select * from users where userId=\""
.$_POST["$user"]
."\" and userPassword = \""
.$_POST["$password"]."\"";
em làm thế này đúng kô bác ???
zoejoe viết 02:18 ngày 10/10/2018
Như thế vẫn đúng, nhưng tốt nhất nên lọc dữ liệu vào. Một số lỗi bảo mật như xss có thể xuyên thủng trang của bạn, hoặc có thể là SQL injection. Xem lại cách filter nhé
vnz viết 02:16 ngày 10/10/2018
còn gì nữa kô hả các bác? em dốt cái này lắm, bác nào chỉ lỗi thêm cho em rồi em mò em sửa vây, thanks
Bài liên quan
0