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


TECHNICAL DETAILS & DESCRIPTION :

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.

BACKGROUND:

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.

XXE OUT-OF-BAND CHANNELS EXPLOITATION:

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.

ATTACK VECTORS :

  1. BYPASS XXE DIRECT-FEEDBACK CHANNEL PARSING RESTRICTION :

    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.

  2. XXE OOB DATA RETRIEVAL VIA PARAMETER ENTITIES:

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.

VIDEO POC :

About

Follow me on twitter : https://twitter.com/r007hunt

 

 

 

 

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)
 pth_init();
#elif defined(PTHREADS)
 pthread_key_create( &tls_key, 0 );
#elif defined(TSRM_ST)
 st_init();
 st_key_create(&tls_key, 0);
#elif defined(TSRM_WIN32)
 tls_key = TlsAlloc();
#elif defined(BETHREADS)
 tls_key = tls_allocate();
#endif

 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;
 }
 id_count=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"));
 free(tsrm_tls_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));
InitializeCriticalSection(mutexp);
#elif defined(GNUPTH)
mutexp = (MUTEX_T) malloc(sizeof(*mutexp));
pth_mutex_init(mutexp);

/* code ... */

#endif
#ifdef THR_DEBUG
printf("Mutex created thread: %d\n",mythreadid());
#endif
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);
#else
php_apache_globals_ctor(&php_apache_info TSRMLS_CC);
#endif
REGISTER_INI_ENTRIES();
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);
                        }
                        free(p->storage[j]);
                    }
                }
                free(p->storage);
                free(p);
                p = next_p;
            }
        }
        free(tsrm_tls_table);
        tsrm_tls_table = NULL;
    }
    // Release resources table
    if (resource_types_table) {
        free(resource_types_table);
        resource_types_table=NULL;
    }
    // Release Thread Lock
    tsrm_mutex_free(tsmm_mutex);
    tsmm_mutex = NULL;
    TSRM_ERROR((TSRM_ERROR_LEVEL_CORE, "Shutdown TSRM"));
    if (tsrm_error_file!=stderr) {
        fclose(tsrm_error_file);
    }
// Delete Thread Key
#if defined(GNUPTH)
    pth_kill();
#elif defined(PTHREADS)
    pthread_setspecific(tls_key, 0);
    pthread_key_delete(tls_key);
#elif defined(TSRM_WIN32)
    TlsFree(tls_key);
#endif
}

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.

About

Follow me on twitter : https://twitter.com/r007hunt

No cON Name CTF 2014 : imMISCible 200 Write-up

Hi guys,  this writeup will be about the challenge imMISCible.

Description: No hints 😦 Just go and get the flag.

Url: https://ctf.noconname.org/chdownloads/immiscible

Points: 200

After checking the file it’s obvious that it’s a ZIP file. Once we extract it we got a file called CTF.py.

#!/usr/bin/env python
# -*- coding: rot13 -*-
vzcbeg bf
vzcbeg znefuny
vzcbeg arj

tybony synt

qrs s():
    tybony synt
    synt = "Abcr!".qrpbqr("rot13")

olgrpbqr = """
LjNNNNNNNNNNNjNNNRNNNNOmyjNNNTDNNTDONTjNNT0ONSbONNSxNNOxNtOfNtOgNjOnNjNOMDZN
MNZNMNDNtjVNMNHNnjVNpcZNMNLNLDDNqNDNMNpNA2RRNUDRNTDVNQquONO0ONOxPDN3LDDNqNDN
ntHNMNbNMNDNtjVNLDDNqNDNntLNMNfNtjRNLDDNMNjNMDRNqNDNtjRNntpNtjNNS2RRNT4NNTDA
NSZbQtNNNTa/////XNRNNNOmONNNNUAbLGRbNDNNNUZTNNNNM2I0MJ52pjfNNNOBG19QG05sGxSA
EKZNNNNNpjRNNNOMpmRNNNNtAGptAwttAwRtAmDtZwNtAwxtAmZtZwNtAmDtAwttAwHtZwNtAwRt
AwxtAmVtZzDtpmRNNNNtAmZtAmNtAwHtAwHtAwDtZwNtAmLtAwHtAzZtAzLtAwZtAwxtAmDtAmxt
ZwNtAzLtpmRNNNNtAwLtZwNtAwRtAzHtZwNtAmHtAzHtAzZtAwRtAwDtAwHtAzHtZwNtAmZtAmpt
AwRtpkNNNNNtAzZtAzZtAzLtAmptZ2LtpjRNNNNtpjZNNNObMKumNjNNNR5QGx4bPNNNNUZUNNNN
nTSmnTkcLaZRNNNNp2uuZKZPNNNNo3AmOtNNNTqyqTIhqaZRNNNNMzkuM3ZUNNNNpzIjoTSwMKZT
NNNNMTIwo2EypjxNNNObMKuxnJqyp3DbNNNNNPtNNNNNXNNNNNOmPNNNNQkmqUWcozp+pjtNNNN8
oJ9xqJkyCtVNNNOmRtNNNONORNRINtLOPtRXNDbORtRCND==
"""

vs __anzr__ != "__znva__".qrpbqr("rot13"):
    pbqrbow = znefuny.ybnqf(olgrpbqr.qrpbqr("rot13"))
    s = arj.shapgvba(pbqrbow, tybonyf(), "s".qrpbqr("rot13"), Abar, Abar)

s()

cevag synt

In order to make this code readable, we apply ROT-13 to every piece of it, we uncomment the bytecode and we get :

import os
import marshal
import new

global flag

def s():
 global flag
 flag = "Abcr!".decode("rot13")

bytecode = "LjNNNNNNNNNNNjNNNRNNNNOmyjNNNTDNNTDONTjNNT0ONSbONNSxNNOxNtOfNtOgNjOnNjNOMDZNMNZNMNDNtjVNMNHNnjVNpcZNMNLNLDDNqNDNMNpNA2RRNUDRNTDVNQquONO0ONOxPDN3LDDNqNDNntHNMNbNMNDNtjVNLDDNqNDNntLNMNfNtjRNLDDNMNjNMDRNqNDNtjRNntpNtjNNS2RRNT4NNTDANSZbQtNNNTa/////XNRNNNOmONNNNUAbLGRbNDNNNUZTNNNNM2I0MJ52pjfNNNOBG19QG05sGxSAEKZNNNNNpjRNNNOMpmRNNNNtAGptAwttAwRtAmDtZwNtAwxtAmZtZwNtAmDtAwttAwHtZwNtAwRtAwxtAmVtZzDtpmRNNNNtAmZtAmNtAwHtAwHtAwDtZwNtAmLtAwHtAzZtAzLtAwZtAwxtAmDtAmxtZwNtAzLtpmRNNNNtAwLtZwNtAwRtAzHtZwNtAmHtAzHtAzZtAwRtAwDtAwHtAzHtZwNtAmZtAmptAwRtpkNNNNNtAzZtAzZtAzLtAmptZ2LtpjRNNNNtpjZNNNObMKumNjNNNR5QGx4bPNNNNUZUNNNNnTSmnTkcLaZRNNNNp2uuZKZPNNNNo3AmOtNNNTqyqTIhqaZRNNNNMzkuM3ZUNNNNpzIjoTSwMKZTNNNNMTIwo2EypjxNNNObMKuxnJqyp3DbNNNNNPtNNNNNXNNNNNOmPNNNNQkmqUWcozp+pjtNNNN8oJ9xqJkyCtVNNNOmRtNNNONORNRINtLOPtRXNDbORtRCND=="

if __name__ != "__main__".decode("rot13"):
 codeobj = marshal.loads(bytecode.decode("rot13"))
 s = new.function(codeobj, globals().decode("rot13"), "s", None, None)

  s()

print flag

Next step is to execute the python script, but when we execute it we get :

Traceback (most recent call last):
  File "main.py", line 14, in 
    codeobj = marshal.loads(bytecode.decode("rot13"))
ValueError: bad marshal data (unknown type code)
Because we are not giving a valid bytecode to marshal.loads which is used to deserialize an encoded string from a byte array, so we should use bytecode.decode(“rot13”) then convert the Base64 we have to Hex.
Final script edited to print the bytecode:
bytecode = "\x63\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x40\x00\x00\x00\x73\x97\x00\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x00\x00\x6d\x01\x00\x5a\x01\x00\x01\x64\x00\x00\x64\x02\x00\x6c\x02\x00\x6d\x03\x00\x5a\x03\x00\x01\x65\x03\x00\x64\x03\x00\x64\x04\x00\x83\x02\x00\x64\x05\x00\x6b\x02\x00\x72\x93\x00\x64\x06\x00\x61\x04\x00\x74\x04\x00\x64\x07\x00\x37\x61\x04\x00\x74\x04\x00\x64\x08\x00\x37\x61\x04\x00\x74\x04\x00\x64\x09\x00\x37\x61\x04\x00\x74\x04\x00\x6a\x05\x00\x64\x0a\x00\x64\x04\x00\x83\x02\x00\x61\x04\x00\x74\x04\x00\x6a\x06\x00\x64\x0b\x00\x83\x01\x00\x61\x04\x00\x64\x0c\x00\x65\x01\x00\x74\x04\x00\x83\x01\x00\x6a\x07\x00\x83\x00\x00\x17\x61\x04\x00\x6e\x00\x00\x64\x0d\x00\x53\x28\x0e\x00\x00\x00\x69\xff\xff\xff\xff\x28\x01\x00\x00\x00\x73\x04\x00\x00\x00\x73\x68\x61\x31\x28\x01\x00\x00\x00\x73\x06\x00\x00\x00\x67\x65\x74\x65\x6e\x76\x73\x0b\x00\x00\x00\x4e\x4f\x5f\x43\x4f\x4e\x5f\x4e\x41\x4d\x45\x73\x00\x00\x00\x00\x73\x01\x00\x00\x00\x59\x73\x31\x00\x00\x00\x20\x35\x37\x20\x36\x38\x20\x36\x31\x20\x37\x34\x20\x32\x30\x20\x36\x39\x20\x37\x33\x20\x32\x30\x20\x37\x34\x20\x36\x38\x20\x36\x35\x20\x32\x30\x20\x36\x31\x20\x36\x39\x20\x37\x32\x20\x32\x64\x20\x73\x31\x00\x00\x00\x20\x37\x33\x20\x37\x30\x20\x36\x35\x20\x36\x35\x20\x36\x34\x20\x32\x30\x20\x37\x36\x20\x36\x35\x20\x36\x63\x20\x36\x66\x20\x36\x33\x20\x36\x39\x20\x37\x34\x20\x37\x39\x20\x32\x30\x20\x36\x66\x20\x73\x31\x00\x00\x00\x20\x36\x36\x20\x32\x30\x20\x36\x31\x20\x36\x65\x20\x32\x30\x20\x37\x35\x20\x36\x65\x20\x36\x63\x20\x36\x31\x20\x36\x34\x20\x36\x35\x20\x36\x65\x20\x32\x30\x20\x37\x33\x20\x37\x37\x20\x36\x31\x20\x73\x10\x00\x00\x00\x20\x36\x63\x20\x36\x63\x20\x36\x66\x20\x37\x37\x20\x33\x66\x20\x73\x01\x00\x00\x00\x20\x73\x03\x00\x00\x00\x68\x65\x78\x73\x03\x00\x00\x00\x4e\x43\x4e\x4e\x28\x08\x00\x00\x00\x73\x07\x00\x00\x00\x68\x61\x73\x68\x6c\x69\x62\x73\x04\x00\x00\x00\x73\x68\x61\x31\x73\x02\x00\x00\x00\x6f\x73\x73\x06\x00\x00\x00\x67\x65\x74\x65\x6e\x76\x73\x04\x00\x00\x00\x66\x6c\x61\x67\x73\x07\x00\x00\x00\x72\x65\x70\x6c\x61\x63\x65\x73\x06\x00\x00\x00\x64\x65\x63\x6f\x64\x65\x73\x09\x00\x00\x00\x68\x65\x78\x64\x69\x67\x65\x73\x74\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x73\x08\x00\x00\x00\x3c\x73\x74\x72\x69\x6e\x67\x3e\x73\x08\x00\x00\x00\x3c\x6d\x6f\x64\x75\x6c\x65\x3e\x02\x00\x00\x00\x73\x12\x00\x00\x00\x10\x01\x10\x01\x15\x02\x06\x01\x0a\x01\x0a\x01\x0a\x01\x12\x01\x0f\x01"

if __name__ != "__main__":
 codeobj = marshal.loads(bytecode)
 s = new.function(codeobj, globals(), "s", None, None)

 s()

print bytecode

We got some strings here :

c@s�ddlmZddlmZedd�dkr�datd7atd7atd	7atjd
d�atjd�adet�j�and
S(i����(ssha1(sgetenvsNO_CON_NAMEssYs1 57 68 61 74 20 69 73 20 74 68 65 20 61 69 72 2d s1 73 70 65 65 64 20 76 65 6c 6f 63 69 74 79 20 6f s1 66 20 61 6e 20 75 6e 6c 61 64 65 6e 20 73 77 61 s 6c 6c 6f 77 3f s shexsNCNN(shashlibssha1sossgetenvsflagsreplacesdecodes	hexdigest(((sss
After checking deeply we found that it might be a python code used to hash with sha1 the following string :
NO_CON_NAME = Hex2ASCII(57 68 61 74 20 69 73 20 74 68 65 20 61 69 72 2d 73 70 65 65 64 20 76 65 6c 6f 63 69 74 79 20 6f 66 20 61 6e 20 75 6e 6c 61 64 65 6e 20 73 77 61 6c 6c 6f 77 3f)
NO_CON_NAME = “What is the air-speed velocity of an unladen swallow?”
Then the final string is replaced or concatenated somehow in the following way :
NCN+sha1(“What is the air-speed velocity of an unladen swallow?”)
After trying this method , I was able to validate the challenge.
 Flag : NCN6ceeeff26e72a40b71e6029a7149ad0626fcf310

 

 

 

Oracle WebLogic Server – JNDI Tree Second-Order Code Injection

 JNDI_Tree

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.

About

Follow me on twitter : https://twitter.com/r007hunt

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.

bounty

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.

json

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 :

xss

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:

http://pastebin.com/yw0rWmgY

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 : http://www.marw0rm.com/handling-session-actions-web-application-authorization-bypass-youtube-as-example/

About

Follow me on twitter : https://twitter.com/r007hunt

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 : http://pastebin.com/raw.php?i=PwMMAP19(o_O).
  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 : http://pastebin.com/1hY0kwCk

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 : http://picosong.com/media/songs/XXXXXX 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 : jigsaw0658@gmail.com