PayPal BugBounty Program : How I Hacked PayPal Accounts – Authentication System Bypass Vulnerability

Today I am going to make a public disclosure of a critical vulnerability I have found during my research in PayPal Core Application, This vulnerability allowed me to completely bypass the CSRF Prevention System, which lead to account hijacking and issue privileged actions on target user through a series of flaws.


I  – Discovery Phase :

After analyzing the web application I took a look at the Customer Profile (My Selling Tools) Settings module (classic view), after intercepting some requests I’ve identified a reflected XSS issue via customerprofile settings. The finding resides in the request made after clicking on the expand/collapse option on the page.
[+]Selling online
[+]Getting paid and managing my risk
[+]Shipping my items


While testing I intercepted this request which is sent with these parameters :

  • “group” parameter : represent the option ( shippingItems, paymentAndRisk, sellingItems)
  • “state” parameter : represent the state (0 ==> Collapsed , 1 ==> Expanded )


Proof of Concept Demonstration

Blind XML External Entities Out-Of-Band Channel Vulnerability : PayPal Case Study


XML External Entities weakness resides in the application’s XML input parsing capabilities. This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. It leads to the disclosure of confidential data, denial of service, server-side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts. PayPal official web application (PayPal Inc – PayPal Multi-Order Shipping Application [Core]) suffered from this critical security vulnerability.


PayPal Multi-Order Shipping is a tool that allows to print up to 50 domestic U.S. Postal Service shipping labels at a time, right from PayPal account. Including multiple services:

  • Import transactions from eBay and/or PayPal
  • Manually create one or more ad-hoc labels
  • Get orders ready to print labels
  • Edit shipping details for an order
  • Add insurance and signature confirmation to an order
  • Combine multiple orders into one shipment
  • Revert a combined order
  • Add or remove columns in the Orders to Ship tab
  • Application settings and time-saving tools
  • Printing labels and supporting documentation Carrier Pickup™ and post-shipment management

Identification Phase :

The application is XML based, the requests exchanged with the server are structured data in XML format. While testing the application’s features through intercepting requests within the environment the following requests caught my attention :

In the first attempt, we need to confirm that entities are interpreted in the most basic form. We replace VALUE with an inline entity to analyse the server behavior:

The response returned is invalid input error so the server has a reflection point to displays the injected payload and since the XML requests are user-supplied I tested for basic XML Injection to check the application’s XML processing methods by trying to extract files with the injected entity (remote file) back to the client. The idea of this attack is to declare an external general entity and reference an internal file on a network resource or locally:

We noticed that the application only check at position: strings, numeric, CDATA values. The values referenced from the metadata or entities inside the document aren’t used. Therefore, it is not possible to get a direct response after submitting our request.


Overview of XXE Processing:

XML parsers typically support external references by default, external entities can reference files on the parser’s file-system. External entities can often also reference network resources via the HTTP protocol handler. The ability to send requests to other systems can allow the vulnerable server to be used as an attack proxy. By submitting suitable payloads, an attacker can cause the application server to attack other systems that it can interact with. This may include public third-party systems, internal systems within the same organization, or services available on the local loopback adapter of the application server itself. Depending on the network architecture, this may expose highly vulnerable internal services that are not otherwise accessible to external attackers.



    After multiple tests, I confirmed that there is no direct feedback channel from which we can force the server to display the result in the response, So I used a technique in which we inject an XML payload using External Entity in “DOCTYPE” instead of general entities, the DOCTYPE declaration with the SYSTEM keyword causes an XML parser to read data from a URI and permits it to be proceeded into the document :

    The application server response was an Internal Server Error message, right after I sent the request, my server received a connection from a PayPal’s internal server:

    Now we confirm that External Entities are activated, this means that connections are allowed to remote systems from the vulnerable server and it’s possible to use an external DTD to extract local files via web requests. This technique will allow us to load any network resources from a host we control. The resources can be hosted on an HTTP server, FTP server, …etc.


In order to overcome parsing restrictions such as (limited use of external Entities, referencing General/Parameter entities in the main XML document), I thought about:

  • Using Parameter entities within a DTD definition.
  • Making the server interacts with my external domain and make a resolution of XXE payload instead of performing attack directly inside the XML document.

This attack can be executed by referencing the hosted DTD resource only. The request does not even have to contain any XML body, for as long as the server processes XML requests.

A. XXE Data Retrieval through Protocol Handlers :

Parameter entities help us to access external resources transferring to them file content from the server, where the parser is located, via external entities using the technique described above. It allows attacking parsers, on which result direct output is not supported.

Now the objective is to gain access to server’s internal local files / resources (file disclosure) exploiting protocol handlers (wrappers) used in many platforms/parsers which support a variety of URL schemes/protocols :

When performing data extraction from the target application and initiating a connection back to my server in order to fetch a DTD then send the file contents. Assuming a strict firewall restrictions is in place, I tested different protocol handlers and common ports (21, 23, 80, 443, 8080, …) then I realized that the target server block outgoing connections to some TCP ports such as: 21 (FTP), 8080, 8000, 1337, 2222…etc.

However, we still have an option to fetch arbitrary file via HTTP/HTTPS requests back to a controlled domain. Following the extraction of “/etc/passwd” file, after couple of tries, few seconds an incoming connection is opened and the file content is received:

As noticed the length of data sent within the URL is almost certainly limited, depending on some particular implementation, that’s why only a single line of /etc/passwd can be read using this method. The URL must generally consist of properly formed Unicode data and must also conform to the particular XML library’s restrictions on characters permitted in the URL. Sometimes a parser does not check the length of a created URI, and a lot of parsers convert line feeds automatically (Xerces replaces them with spaces, and System.XML processes with URL encode).

B.Bypass URI length & Server Firewall restriction :

Consider the following:

  • Control of data chunks length that will be checked on the side of our controlled server.
  • Connections are established to remote systems from the vulnerable server, it’s possible to use of an external DTD to exfiltrate data.
  • Control of TCP communication protocol with PayPal remote Server.
  • Emulate Custom Server listening on ports including (HTTPS, HTTP).

So, to overcome this limitation instead of setting an HTTP Server, I used a technique to trick the target server to initiate a connection to a custom FTP Server on port 443 (https), each line from multiline URI will be requested as separate command. Once the XML interpreter parses the external DTD file, the contents of the file to read are sent to the custom FTP server and retrieve all data in only one request.

Thus, our final payload:

POC source code :

Custom FTP Server

HTTP Server

After testing and fuzzing more capabilities I could exploit XXE Out-Of-band to disclose some files and much more attacks were possible.

This weakness gives a remote attacker (with no privileges nor user interaction) access to PayPal servers and its internal systems.

Blind XXE OOB Attack scenario



Remote Code Execution Scenario:

The consequences were highly dangerous, gives an attacker the ability to effectively bypass strict firewalls, authorization schemes, sensitive data disclosure and PayPal internal networks access. In our case I successfully exfiltrate any kind of data to my external server after running XXE recon which provided me with visibility into the target system and identifying installed applications, gaining a toehold for RCE endpoints. I figured a way to read configuration files, server log files, users history and internal hosts information, …etc. From the connections, we received after executing our XXE exploit on the target application. Due to the sensitivity of the PayPal information exposed I am not allowed to share the RCE exploitation part, but I am going to demonstrate a working scenario consists of attacking Apache Tomcat installation in PayPal’s internal server following these steps:

  1. Gain Access to Web Administration Portals via History Logs:
  2. Check for contents of history logs (e.g.: ~/.bash_history), look up for deployed services.
  3. Perform a Local System File Scan.
  4. Identify an Apache Tomcat application.
  5. Send Apache Tomcat Configuration files, Authentication Credentials and Server to probe via XXE with a request back to our Server.
  6. Web Browser to Access the Web Administration Console once we found the URL in the configs.
  7. Confirmed RCE, grant access.



Follow me on twitter :





In-depth study of PHP & Zend Engine TSRM Algorithms.

Today we’re going to shed a light on an interesting topic. PHP internals, this term is used to refer to all those things that are not directly accessible to userspace code (php script). This post explains the concept of (ZTS) Zend thread safety in multi-threaded environment, PHP lifecycle and a detailed analysis of TSRM mechanism.

Zend Thread Safety Principles:

Thread Security means to guarantee a safe access to public resources in a multithreaded environment. Generally each thread has a private stack but all threads share a common heap. In C language, when a variable is declared outside of any function, it becomes a global variable, then this variable will be assigned to the process of shared storage space, different threads refer to the same memory address space. At first PHP had no concern for thread security because there was no resource competition or concurrency between threads ( single-threaded environment ).

After the appearance of single-process multithreaded web servers a new approach to handling global data became necessary. Eventually this would appear as a new layer in PHP called TSRM (Thread Safe Resource Management), the concrete implementation of Zend Thread-Safe mechanism. In this paper we’ll discuss examples of specific implementations in Apache HTTP web server (Worker MPM) which uses threads. Threads proceed through TSRM which manage access to its global variables. Each thread assigned an area, and is identified by a unique ID as shown below :

The following figure shows a schematic view of ZTS concept: ZTSConcept

General Overview about PHP Request Life Cycle :

Every PHP instance go through numerous events involving Request Init, Module Init and finally Shutdown events. The initial startup, before page requesting (SCRIPT) begins, PHP interpreter calls every extension’s MINIT (Module Initialization) method to initialize extension modules.

During this phase extensions declares constants, register resource, stream, and filter handlers that all will be used in next requests. Once a request is made, PHP interpreter sets up an environment to operate requests which includes a symbol table (php variables and could be Engine’s vars too).

PHP loops through its extensions again and calls each extension’s RINIT ( Request Initialization ) method which run at the start of every page request. During this phase extensions reset global variables to default values ( either in multithreaded env), pass variables into the script’s symbol table.

Finally when the request has completed execution, due to the end of scripts file or by exiting through a die() or exit() statements, the cleanup process start by calling each extension’s RSHUTDOWN (Request Shutdown) method. RSHUTDOWN corresponds to auto_append_file configuration directive. But the difference between RSHUTDOWN and auto_append_file, is that RSHUTDOWN don’t get interrupted by a call from exit() – die() will always be executed, while auto_append_file is skipped by such calls. After RSHUTDOWN methods have completed, symbol table and non-persistent resources are destroyed.

Now it’s SAPI and web server turn to shutdown, PHP loops through each extension’s MSHUTDOWN (Module Shutdown) method and unregister any kind of remaining resources.

Illustration of php running in a multi-threaded server, handling requests life cycle as shown below: PHPLifeCycle

TSRM API & Related Algorithms:

This section is about analyzing the implementation details of the main TSRM algorithms. Let’s start first with defining data structures :

Data Structures :

TSRM concerned with 2 important data structures :

  1. tsrm_tls_entry .                                                                                   
  2. tsrm_resource_type.
typedef struct _tsrm_tls_entry tsrm_tls_entry;

struct _tsrm_tls_entry {
void **storage; // global variable storage array 
int count; // resources recorded count,
THREAD_T thread_id;
tsrm_tls_entry *next;

Each tsrm_tls_entry node corresponds to a thread. Multiple tsrm_tls_entry linked together to form tsrm_tls_table , a static global variable defined in the memory manager table :

/* The memory manager table */
static tsrm_tls_entry **tsrm_tls_table=NULL;
static int tsrm_tls_table_size; //
static ts_rsrc_id id_count; 

tsrm_resource_type‘s internal structure is relatively simple:

typedef struct {
size_t size; // shared memory size ( resources )
ts_allocate_ctor ctor // resources constructor
ts_allocate_dtor dtor // resources destructor 
int done; // a flag to identify resource usage. 
} tsrm_resource_type; 

tsrm_resource_type resource (or global variables) as a unit, every time a new resource is allocated, it will create a tsrm_resource_type element and expand global resource table. All tsrm_resource_type is an array approach consisting tsrm_types_table, with rsrc_id as the index of resources.  This data structure is mainly used in TSRM to manage each thread creation and release resources. tsrm_types_table is a global static variable defined in the resource sizes table as resource_types_table :

/* The resource sizes table */
static tsrm_resource_type *resource_types_table=NULL;
static int resource_types_table_size;
Implementation Details :

Basically the TSRM mechanism has 3 major functions to pick for representative analysis. The first is tsrm_startup function that is called in the process sapi initial stage, to initialize TSRM environment. The following is the function code :

/* Startup TSRM (call once for the entire process) */
TSRM_API int tsrm_startup(int expected_threads, int expected_resources, int debug_level, char *debug_filename)
#if defined(GNUPTH)
#elif defined(PTHREADS)
 pthread_key_create( &tls_key, 0 );
#elif defined(TSRM_ST)
 st_key_create(&tls_key, 0);
#elif defined(TSRM_WIN32)
 tls_key = TlsAlloc();
#elif defined(BETHREADS)
 tls_key = tls_allocate();

 tsrm_error_file = stderr;
 tsrm_error_set(debug_level, debug_filename);
 tsrm_tls_table_size = expected_threads;

 tsrm_tls_table = (tsrm_tls_entry **) calloc(tsrm_tls_table_size, sizeof(tsrm_tls_entry *));
 if (!tsrm_tls_table) {
 TSRM_ERROR((TSRM_ERROR_LEVEL_ERROR, "Unable to allocate TLS table"));
 return 0;

 resource_types_table_size = expected_resources;
 resource_types_table = (tsrm_resource_type *) calloc(resource_types_table_size, sizeof(tsrm_resource_type));
 if (!resource_types_table) {
 TSRM_ERROR((TSRM_ERROR_LEVEL_ERROR, "Unable to allocate resource types table"));
 tsrm_tls_table = NULL;
 return 0;

 tsmm_mutex = tsrm_mutex_alloc();
 // Initialize the thread start and end handles
 tsrm_new_thread_begin_handler = tsrm_new_thread_end_handler = NULL;

 TSRM_ERROR((TSRM_ERROR_LEVEL_CORE, "Started up TSRM, %d expected threads, %d expected resources", expected_threads, expected_resources));
 return 1;


The main task here is to initialize the two data structures mentioned above.

First two parameters are : expected_threads and expected_resources. These two parameters are passed by the SAPI, it represents the number of threads and the number of resources expected in the environment. Next the function initialize tsrm_tls_table_size (mentioned in the memory manager table) with expected_threads value and following allocate memory space for tsrm_tls_table (via calloc) and initialize id_count with 0 for the first use. The same procedure is applied to resource_types_table, resource_types_table_size is initialized with expected_resources value then allocate memory space for resource_types_table
(mentioned in the the resource sizes table). Finally it allocates a mutex to handle resources allocation and usuage without mutual interference between threads.
Below the implementation code for tsrm_mutex_alloc() :

/* Allocate a mutex */
TSRM_API MUTEX_T tsrm_mutex_alloc(void)
MUTEX_T mutexp;
#ifdef TSRM_WIN32
mutexp = malloc(sizeof(CRITICAL_SECTION));
#elif defined(GNUPTH)
mutexp = (MUTEX_T) malloc(sizeof(*mutexp));

/* code ... */

#ifdef THR_DEBUG
printf("Mutex created thread: %d\n",mythreadid());
return( mutexp );

The second function ts_allocate_id, significantly the most important in the TSRM mechanism, needs to be carefully analyzed. Generally speaking this function is used to allocate global resources in a multithreaded environment and return the resource ID so let’s discover how it works.

You can find the source code here :  TSRM : ts_allocate_id.                                            
                                                                 TSRM : ts_allocate_id (link 2).

We call this function during the extension’s MINIT process, TSRM layer is notified with the size of data which needs to be stored by the extension. Following that TSRM adds the number of bytes to its running total of data space requirements then returns a new, unique identifier for that segment’s portion of the global thread’s data pool. It’s used to apply a global variable in a multithreaded environment (in ex : Apache Worker MPM ) and return the ressource ID.

Analysis :

Once we call ts_allocate_id function, 4 parameters are passed by the extension. Example ( Apache SAPI extension ):

static PHP_MINIT_FUNCTION(apache)
#ifdef ZTS
ts_allocate_id(&php_apache_info_id, sizeof(php_apache_info_struct), (ts_allocate_ctor) php_apache_globals_ctor, NULL);
php_apache_globals_ctor(&php_apache_info TSRMLS_CC);
return SUCCESS;

Next PHP kernel lock the calling thread using tsrm_mutex_lock function to handle concurrency issues. Once locked id_count is incremented, to generate a new resource ID, after generating a resource ID, it gives the current location of the newly allocated storage, each resource will be stored in tsrm_types_table. In fact, we can consider tsrm_types_table a sort of HashTable, its key is the resource ID and value is tsrm_resource_type structure.

Later it will assing resource data to resource_types_table and set done to 0 which means that the resource is currently in use. After the allocation of resource ID,  ts_allocate_id function will traverse all the threads and for each thread’s tsrm_tls_entry allocate the resources required memory space based on id_count. More precisely it will check if the global variables recorded count is less than the id_count and enlarge the existing global variables (resources) storage array. Then allocate the size of ressources starting from the last count and call the resource constructor.

We should note that tsrm_tls_table (in other words tsrm thread local storage table) is a HashTable, an array of pointers to each thread private data (tsrm_tls_entry ). Index is calculated using the following macro :

// Thr stand for thread_id
// ts  stand for tsrm_tls_table_size 
#define THREAD_HASH_OF(thr, ts) (unsigned long)thr%(unsigned long)ts
// Usage Example
hash_value = THREAD_HASH_OF(thread_id, tsrm_tls_table_size);
thread_resources = tsrm_tls_table[hash_value];
Resource Allocation Process Flow chart :

DiagramTSRMFinally it’s time for tsrm_shutdown function to shutdown TSRM and do some memory cleanup job.

/* Shutdown TSRM (call once for the entire process) */
TSRM_API void tsrm_shutdown(void)
    int i;

    if (tsrm_tls_table) {
        for (i=0; i<tsrm_tls_table_size; i++) {
            tsrm_tls_entry *p = tsrm_tls_table[i], *next_p;

            while (p) {
                int j;

                next_p = p->next;
                for (j=0; j<p->count; j++) {
                    if (p->storage[j]) {
                        if (resource_types_table && !resource_types_table[j].done && resource_types_table[j].dtor) {
                            resource_types_table[j].dtor(p->storage[j], &p->storage);
                p = next_p;
        tsrm_tls_table = NULL;
    // Release resources table
    if (resource_types_table) {
    // Release Thread Lock
    tsmm_mutex = NULL;
    if (tsrm_error_file!=stderr) {
// Delete Thread Key
#if defined(GNUPTH)
#elif defined(PTHREADS)
    pthread_setspecific(tls_key, 0);
#elif defined(TSRM_WIN32)

tsrm_shutdown pass through all the existing threads, save the next thread node before freeing the current thread, thus the function invoke the resource destructor and start freeing each element from the global variable storage array. Finally release the tsrm_tls_table, so this way we shutdown the thread-safe memory manager.

Here is a look at Apache sapi TSRM calls during MINIT & MSHUTDOWN phase :

SAPIcallsIn fact the purpose of calling tsrm_startup with 1 as value for expected threads, is that in most cases PHP still used with single-threaded environments so it’s a good reason not to waste memory space.

So by this we come up to the end of this paper.

Stay tuned for more interesting stuff.

References :
  • TSRM source code in PHP interpreter repository :   TSRM 
  • Extending & Embedding PHP Book.


Follow me on twitter :

Oracle WebLogic Server – JNDI Tree Second-Order Code Injection


Hi Everyone, today i want to share with you a post about a vulnerability i’ve discovered times ago, it was already fixed by the vendor. So before i get started i’ll explain first what is a second-order code injection mostly code injection vulnerabilities.

Code Injection is a type of exploitation caused by processing invalid data input. The concept of injection attacks is to introduce (or “inject”) malicious code into a program so as to change the course of execution. Such an attack may be performed by adding strings of malicious characters into data values in the form or argument values in the URL. Injection attacks generally take advantages of inadequate validation over input/output data, for example:

  • – Lack of defining a class of allowed characters (such as standard regular expressions or custom classes)
  • – Lack of restricting the data format.
  • – Lack of checking the amount of expected data (such as maximum length restriction)
  • – Lack of restricting the data type (such as numerical input only)

In this form of injection attack, the attackers introduce improper scripts into the web browsers. The technique is most often used to inject JavaScript, VBScript, ActiveX, HTML, Flash or any other types of codes that web browsers may execute. Once the injection is successfully performed, hackers can carry out a variety of malicious attacks including account hijacking, changing of user settings, cookie theft, poisoning, Cross-Site Request Forgery or false advertising.

-Second-order code injection :
Second-order code injection is the realisation of malicious code injected into an application by an attacker, but not activated in real-time by the application. In a lot of cases, the victim of the attack may not even be using the same application that the attacker injected their code.

I – Weakness Analysis :

The Code injection vulnerability reside in the Weblogic Server Administration Console (JNDI Tree Structure ). After testing on this platform i realized that i’m able to inject any strings into “server” parameter value. So i injected strings of malicious payloads (javascript/php/Ajax…) into the argument value in the following URI :
-[ /consolejndi.portal?_nfpb=true&_pageLabel=JNDIHomePage&server=(MALICIOUS_CODE) ] and it was a successfull injection, i can execute any code passed to the argument value.

Let’s look more deeper to identify the source of this issue, If we check “tree.js” we find actually that we can ovewrite/corrupt 3 TreeNode() function parameters.
When we take a look at the code *(1-1) we realize that TreeNode function it’s created as a “JSTree” class object, once all arguments are set the JNDI Tree is created by the function createTree(startNode) then we add new nodes in the previous tree with the function addNode(parentNode, recursedNodes) if the “nodeName” is valid. Therefore any attacker can take advantages of this inadequate validation over input/output data. The link above mention the main functions/methods that are processing and building the tree, its content and identifying the vulnerable parameters. (*Check the link )

Difference between the application behaviour in the (1-1) and (1-2) cases :

Actually Dynamic Analysis of data flow and tracking the execution of some functionalities such as ( Tree creation, Add new node, Expand/ collapse operation, Methods used to build JNDI tree,..etc.) helped me to identify the source of this weakness. The following link shows how to recognize the application behaviour in 2 statements, normal and in case of injecting a malicious code :

III – Exploitation :

In order to exploit this vulnerability an attacker can use several ways to inject a payload and execute arbitrary codes. Furthermore there is a possibility to interact with the environment, gain control of JSTree Class objects and the possibility to access an object in a WebLogic Server environment.

  1.  Session Control : Suppose now that we use the void()(returns a null value to the web browser) JavaScript function instead of alert(). We could change the DOM values inside this function and no navigation change state would occur. Oracle Weblogic server use “ADMINCONSOLESESSION” as a session main cookie, so if we start a new navigation to the same website in another browser instance, we’ll get a new “ADMINCONSOLESESSION”; we could change the session IDs in both instances by this payload : javascript: void(document.cookie=”ADMINCONSOLESESSION = <<another session ID>>”);
  2. XSS Shell.
  3. Phishing Attacks :Using Javascript, CSS or HTML an attacker can trick the victim to log in. The basic concept is to override the HTML of the current page to look identical to the login page. Little does the victim know, his credentials are sent to the attacker instead of to the website when trying to log in.  An attack vector for this kind of attack :
  1. Framework-based attacks :-Different attacks/exploitation could be provided with the help of a framework like BeEF, XSSF.


  1. Cross-Site Scripting Worms & Viruses : Using an application to host the malware code, triggers the purpose of second-order code injection issues, XSS worms and viruses take control over a Web browser and propagate by forcing it to copy the malware to other locations on the Web to infect others. XSS malware payloads could force the browser to send email, transfer money, delete/modify data, hack other websites, download illegal content, and many other forms of malicious activity. XSS exploits, typically HTML/JavaScript, use three ways to force browsers to send remote HTTP requests: Embedded HTML Tags, JavaScript DOM Objects, XMLHTTPRequest (XHR).XSS worm functions example :

-Access to local files from browser/ Screen-captures and send data to attacker :

So guys by this we come up to the end of this article,

See you soon, stay tuned 🙂

Best regards.


Follow me on twitter :

Facebook Bug Bounty !

Hi guys,

I’ve recently got an email from Facebook Security Team confirming that i was rewarded regarding an issue that i’ve reported 2 months ago, it’s about 3 vulnerabilities so since it may take some time before they fix these bugs, Facebook decided to rewarded me.

vulns including :

– Link Shim Protection Bypass – Open redirect. (confirmed)

– 2nd Open redirect ( i was not the first to disclose it ).

-Send Invitation to Event functionality.

-Privacy Selector Bypass lead to post on users wall via Facebook Wi-Fi Check in Hotspots.


Stay tuned.. 🙂

Nice articles are coming soon.

JSON Based Attack Techniques (XSS) Part#1

Hi Everyone,

I want to talk about some advanced attacks and potential security flaws especially when using JSON Applications that can lead to Data Injection/Session Hijacking issues.

In this 1st part i’ll talk about a particular kind of vulnerabilities in web applications that are vulnerable more and more to XSS vulnerabilities that are reflected in non HTML responses, For example : JSON. Before I go further, i want to define JSON : JavaScript Object Notation (JSON) is a simple, text-based data transfer format that is used to transmit data between a server and web applications, it’s widely used as a transport mechanism in AJAX applications. I’ll not give some JSON code samples you can find it over the net. In general, every expression that is valid in JavaScript is also valid in JSON.

So in order to apply our tests we have to know that JSON data objects can be evaluated. So, this feature helps to overcome the security restrictions applied by the SOP (same origin policy). However, we can use scripts to communicate and transmit data by the nature of AJAX applications.

Hacking JSON consist on the following typical Fuzzing techniques :

– Array overwrite.

-Large/negative numbers.

-Symbols like <@’_”%/–.

-Additional serialized objects.

As i mentioned before i’ll demonstrate an example of exploiting an XSS vulnerability. But exploiting XSS vectors against Internet Explorer is more than an “alert(‘XSS’)” and as we all know it’s a little bit hard in this situation because browsers pop up the file download instead of rendering the response when the returned content-type is application/json or application/javascript or application/json-rpc.


Thus, the only solution is to bypass JSON parsing mechanism to indirectly exploit this issue, before we move to the trick that will allow us to attack the vulnerable application (IE versions below 10), I want to explain how Microsoft Internet Explorer Filters works. Recently i had a chance to explore how this filters prevent such attacks :

Microsoft Internet Explorer’s XSS Filters :                                                                 ===============================

Filters within Internet Explorer (IE) 8/9 have the capability to deal with and to detect reflected XSS attacks by applying regular expressions to response data. If this data were reflected within the response, IE would handle the payload to prevent it from actually triggering.

The following command show some Filters :
C:\>findstr /C:”sc{r}” \WINDOWS\SYSWOW64\mshtml.dll|find “<                                     C:\>findstr /C:”script” \WINDOWS\SYSWOW64\mshtml.dll|find “{”
Here are a some of the extracted regular expressions including Unicode characters, common URI attributes and event handler names…etc :


After converting the resulting regular expressions, then creating SecRules to prevent XSS attacks against a web application, any
user can apply blacklist-filtering secrules against incoming request data.                                    Some of the converted IE XSS filters:

It was just a quick look into IE Cross-site Scripting filters, Now we pass to the method we’ll use to overcome the problem we encounter previously. This problem is linked to IE content sniffing heuristics, any file can be interpreted as executable Javascript under many circumstances. It’s actually a security weakness even if the data is sent with the appropriate JSON content type and well configured, this concept remains true even if JSON is not embedded in HTML. However this way is based on rendering JSON responses in IE by direct browsing. First we should know how IE defines file types and what content-type will be set for each response :

  1.  IE search for the response data content-type in the windows registry for the specific CLSID key  (know more about CLSID i.e: “CLSID”=6650f4a1-E8B5-A1CF-BB82-012500DDCE0B ), to find the correct handler for that response.
  2. If the content-type is found, IE will consider that to be the valid content-type otherwise IE will attempt to identify the content-type from the file extension or another way.

In our situation the default mime-type list of Internet Explorer does not include any JSON data mime-type. Besides when visiting a link with JSON data included, IE directly prompts the file download dialog because the specific content-type to consider for the requested file is not found when IE attempts to search in the windows registry (HKCR\MIME\Database\Content Type\CLSID).

In order to force IE to recognize JSON responses and render them, the file extension must be considered by IE as text/html (.htm or .html) within the URL. In addition regarding the manner that most web servers use to parse the path, most server side languages (PHP, Python, Perl CGI…) accepts “path-info” parameter that uses the slash sign (/) as delimiter to be passed from the URL  (i.e : HTTP://[domain_name]/[path-info]?[GET params]). Then when an web application is vulnerable to a reflected XSS, the attacker simply adds “.html” as path-info, consequently the server returns a page with XSS content and the same JSON file type and finally IE matches .html path-info to be text/html and directly triggers XSS.

This way we are now able to exploit XSS using a combination of path-info parameter and IE’s content-type designation weakness.

That’s all for this 1st part guys stay in touch … 🙂

You can check my previous research about a kind of JSON attacks :


Follow me on twitter :

Facebook Malicious W0rm !

Hi Everyone,

Phishers became more professional , using various ways to get users credentials, Facebook is one of the popular websites that is apt to such attacks.

Today i want to share with you guys this blog post concerning a malicious code that is widespread all over the internet. Recently I was tagged in a post by a friend on Facebook, so i checked this post and i found that it’s about a new method to “Hack Facebook accounts” as i wanted me too to hack some Facebook accounts ( lol :p ) i was curious on how can i do it, then i found these steps :

  1. First go to your victim’s profile.
  2. Select Inspect Element.
  3. Copy the code from this link :
  4. Now paste the script into the box given blow (Console).
  5. Press Enter and after 10 seconds you’ll get a message from your victim includes his email and password.

I didn’t follow these steps of course, I suspected something wrong so on i checked directly the link. I found that it contained some obfuscated JavaScript, I took a fast look trying to understand what this script does to hack Facebook accounts, I noticed that it’s not clear so far ( hex encoding/not structured code) generally not fully understandable. My curiosity growth and i tried to examine it deeply. Consequently i copy the code to a JavaScript beautifier in order to reveal the hidden sections, after decoding it i was looking at the code, it revealed some sections but still not fully comprehensible, there were a few methods that were designed to be confusing, and then several strings and arrays that would eventually be decoded using another way and executed to understand the code.

At the beginning i thought i’m facing a kind of Luckysploit malwares, so in this case i have to find better ways to run javascript in a secure environment to minimize the risks that go with executing it. I didn’t see any tool could be built to generically deobfuscate this code completely. I got Malzilla in my hands so i sent the sample to Malzilla Decoder and i tried to run the script away from my Facebook account or browser and show eval() result in some parts of the code because it seems sending some POST Requests to Facebook server. Anyway this wasn’t able to get me the values I was looking for and if I had missed another eval() it’s possible that I could have executed what was clearly malicious code. I proceeded directly to manual analysis , i examined the code, it was clearly 9 main functions that sends many XHR requests to Facebook server and perform many actions, but initially the script brings some cookies like : c_user & fb_dtsg – to implement them later.

var fb_dtsg = document.getElementsByName(‘fb_dtsg’)[0].value;

var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);

In addition i noticed that the 3 last functions : [ Report(param), arkadaslari_al(id), RandomArkadas(), yorum_yap(id,param) ] appears to be obfuscated to make the code more disorganized using an easy method simply we have 2 arrays : _0xb161 & _0xa22c contains multiple elements hex encoded :

var _0xa22c = [“value”, “fb_dtsg”, “getElementsByName”, “match”, “cookie”, “1395443067381092”, “onreadystatechange”, “readyState”, “arkadaslar = “, “for (;;);”, “”, [……..] “status”, “close”];

I realized after that these elements are used to be implemented in the functions i already mentioned and passed around via a series of misleading assignments. Every time a function wants to use an element it sets a reference to it ( i.e :  _0xa22c[2] ==> “getElementsByName”). After digging around for a few minutes and coding a simple program to put each element in its place. Finally i got an organized and comprehensible code, Now it’s time to take a look to the tasks assigned to each function.

Deobfuscated & explained script here :

We should now do a simulation of this process to ( get the victim email & password ohh i’m so excited ^^ :p) since we know what the code does & discovered the bad reasons behind coding this script. Besides once i executed this script following the steps above using a test accounts in an isolated environment to prevent any risky execution i got a strange behavior. The background of Facebook changes, a media player appears and auto-played, all the functions executed their tasks successfully, actual results was stealing your Facebook cookies and uses your account to like a series of pages,subscribe in a list, add profiles, auto follow,report a profile, Like and get tagged in a post. So the hole process results in gaining access to Facebook paths/sensitive Data.

fb  fb2

Moreover i was searching for many sources on the net to get a similar sample. Then i found many codes with different audio links : so i suspected that maybe it’s used to run a crafted mp3 files ( i.e : used to exploit a 0-Day in browsers) or to run some malicious binaries. worse than that, i found some Add-ons that is used to such ends but some of them are deleted  like “Facebook Essential”, but many others still used for bad purpose.

To sum up i want to mention that these scripts can be extended to steal victim cookies easily or used on potential victim to loads a compromised web page or opens a malicious link. Contains often highly obfuscated Javascript that determines what is on the victim’s computers and loads all exploits to which this computer is vulnerable. So we wanted at the beginning to trap a victim and get his credentials but we are the real victim.

It’s just a quick post, hope you like it.

Stay tuned …

email :