Defencely Clarifies Python Object Injection Exploitation

 

Readers,

Welcome to Defencely Blog, This is Rony, part of the Red Teaming Operations Associate at Defencely Cloud Security Pvt. Ltd. & we are extremely delighted to present scenarios of exploitation of a recently conducted security operations for prestigious organizations in India & for Global Enterprises.

Today at Defencely Lab we are going to explain & demonstrate the Python Object Injection attack in minute details. The whole demonstration will be done with our coded intended vulnerable Application & Exploit which you can find at this Link –  Github – Python Object Injection

Contents – 

  • Introduction to Python Classes and Objects.
  • What is an Object Injection?
  • Detecting an Object Injection Attack.
  • Understanding the workflow of a Vulnerable Application.
  • Coding our own exploit against the intended Vulnerable Application.

Prerequisite – 

  • Basic Understanding on OOP Concepts.

Introduction to Python Classes and Objects.

 

What are Classes?

Class is basically a template where you store your variables & methods.

What are Objects?

Objects can be Anything, an instance of a class, a variable or a function in a class.

 

Lets go into the practical examples :-

Here you can see we have created an instance of the class named Test, and assigned the same to a variable named simpleapp passing the value of the variable rony to the Instance.

Output –

“ simpleapp = Test(rony) ”

When this particular code is executed python creates an object and then we are passing our value to the first parameter. Whenever python creates an object the __init__ function gets invoked. __init__ works like a constructor in python.

The random things which got printed with our output it’s because We are directly printing out the instance assigned variable to show how python is treating this as an object.

What is an Object Injection?

Object Injection is an Application Level Security Vulnerability that could allow an attacker to perform critical level attacks depending on the context.

Python specifically have its native module named as “Pickle” which is vulnerable to Object Injection on particular scenarios.

Python already lists pickle as risky module on their official documentation when user controlled data is passed.

We can compare the module “Pickle” with the serialize/unserialize() native functions in PHP which is also vulnerable to Object Injection when user inputs are supplied.

In Python we don’t need a magic methods as a condition to Inject into the Objects Unlike PHP.

Serializing and Deserializing in python is just Pickling and Unpickling of data.

Unpickling of data is NOT necessarily dangerous in Python until and unless user input data are passed to the process of Unpickling.

This is how Pickled and Unpickled data looks like in python –

 

Detecting an Object Injection Attack 

To achieve an Object injection, you have to do a white-box Pentest on a application. Because whenever you are pickling on complex Objects the serialized data in Python comes with the name of the class, variables & their values.

The Pickle module offers us four methods for easy and fast pickling/Unpickling.

  • dump()
  • dumps()
  • load()
  • loads()

You can find their respective functioning in Python’s Official Documentation.

As I already mentioned Unpickling of data is NOT necessarily dangerous, but If you are handling user inputs where in the backend you are pickling and unpickling the user inputted data that’s where the risk comes in. I quote – “Never Trust User Inputs”.

If the data supplied is user controlled it can obviously get tampered.

So, if you see pickled data is passing through any HTTP method, there might be a possibility of Object Injection.

 

Understanding the workflow of a Vulnerable Application

Filename: pickle.py

We will be studying the above code and tweak this accordingly to achieve an object injection.

Ignore everything else written on the code above let’s concentrate on the three things.

  • The user input which is the arg variable in this case.
  • The final_workout() method inside the class simpleApp which interestingly runs a python file.
  • The method which is called app.secureaApp() which is unpickling the inputted data.

Now lets dive deep and lets understand what role does these methods are playing.

The secureApp() method in the simpleApp() class

I am assuming that you probably have read the Python Official Documentation which i have already linked above & know the in’s and out’s of the methods used in this particular post by now.

Methods

  1. dump()
  2. dumps()
  3. load()
  4. loads()

What this secureApp() method is doing is taking a filename as an argument. Unpickling the data from the file using the load() method from the pickle module and assigning the value means the unpickled data to the variable workDone. Which is later on taken as an argument by the final_workout() method.

Let’s see what’s there on the final_workout() method.

The final_workout() method in the simpleApp() class –

This method creates a python file named code.py writes the unpickled data into the file and runs it. Simple right?

Let’s see how it looks like when we run our main vulnerable application pickle.py with the already generated serialized data.

As we can see it prints out the content from the serialized data and runs it successfully which prints out the string.

We will learn, crafting our own serialized data to do a successful object injection on the same application.

 

 

Coding our own Exploit

We now know that the pickle.py is working with the serialized data, so to serialize and making our own crafted payload we will be using the dumps() method to pickle our payloads.

And here is our final exploit to have our own serialized payload data which you can also found on the shared Github Link.

Filename:- exploit_pickle.py

 

We are going to serialize a piece of code which includes system commands with the exploit coded and test it if it works.

And we are now able to Successfully inject our own crafted codes.

I hope this will be a tremendous insight for such vulnerabilities which are well hidden in heap of crafted Enterprise Code & we are hoping to continue providing excellent security services for all kind of business houses & the enterprises in an absolute integrity.

This is Rony Das from Defencely Cloud Security Pvt. Ltd. & join you next week on Defencely Blog with more such highlights whereby our Defencely Lab exploitation goes beyond all measurements bypassing all kinds of security walls.

Thank you & have an excellent day ahead.

 

Defencely Red Team were able to Compromise Half Million Indian E-commerce Data!? How?

Welcome to Defencely Blog, This is Rony, part of the Red Teaming Operations Associate at Defencely Cloud Security Pvt. Ltd. & we are extremely delighted to present scenarios of exploitation of a recently conducted security operations for prestigious organizations in India & Abroad. This will be the same scenario which we faced while doing a security inspection on an extremely high profile target & is likely to repeat for most other organizations.

We are excluding the names of the actual target and will be demonstrating the same on a demo application which is intentionally coded for achieving the exact same scenario in order to reflect most grave mistakes developers have been making. It’s our part & parcel to make the Indian E-Commerce aware of the risks which it comes surrounded with & how compliance’s could not be met due to these potential risk factors which if immediately not resolved – would be liable & answerable to investor deck.

You can find the demo application which will be used for the demonstration on this Github Repository.

Let’s get started,

Contents – 

  • WorkFlow
  • Technical Understanding
  • Exploiting

WorkFlow – 

Basically our target had an Android Application which at this point is very susceptible to most insecure API Security Practices. Most of the Android Applications which deals with huge customer data uses APIs (Application Programming Interfaces) to make their tasks easy. And this makes it much easier to tamper things out when your API calls are done without any authentication services or let’s put as it is even with an authenticated services, there are other risks in the authentication mechanism itself. That’s where our Ops Team started enumerating.

An attacker has to be well versed & very well aware of having dealt with programming languages to build any GUI Desktop app, iOS app or any Android app to considerably know  the in’s & out’s of Event Listeners and Handlers. What this does is, detects your touch and clicks to collect data according to the invoked functions and then sends it via APIs and receive the output in the same way.

In our special scenario, there was a List of menu which were used for different tasks, our ops team started clicking on all the menus at the moment & ended with a menu named “Profile”. While intercepting the requests our testers came across an URL which was requested by the Application & that’s exactly where the target started getting interesting.

In order for our readers to understand this better, lets jump into the Technical Details.

Technical Details

NoteFurther explanation and demonstration will done using the coded example application. These details are for minute level of understanding which is very needed.

The URL looked similar to as below at the time when the application were tested for security violations:

api01.example.com/api/rest/v1/?customerId=89892381

Defencely Red Team ops hit open the URL on our customized browser look at the rendered output which we’re surprised to have a look into:

The URL was throwing the results as JSON parsed format and the same fetched out credentials which one could see in the screenshot as well above.  Please remember, this is a sample coded application & not the real details or any of it. The rendered output were every customers profile details which are extremely sensitive in nature such as their Email, Phone Number, First Name & Last Name. These details could be later used for social engineering attacks & more targeted attacks on a particular customer if it needed to be.

The most basic flaw was the API was taking inputs directly without any validations in place or a mechanism put forward for any such authorization which should had been needed in the first place. Our Red Team Ops concluded that their could be an instance of “Unauthorized API Service Calls” which would really look like an Insecure Direct Object References on OWASP Top 10 Chart.

What if an attacker can enumerate all the customer id’s & then frame a very particular script to obtain all those records given that the parameter was vulnerable to insecure direct object references given that this time an API Service calls were in place!? We replaced the integer values to determine if such changes are rendered as per our hope & voila!

At this point our Red Team Associates & security professionals were clear there were no authorization service in place due to the lack of which validation failed to check if such a service request calls should be allowed in an insecure way to gain an insecure direct object reference attack.

This meant the API were identifying their users using a Uniquely identified key, in this case it’s “customer_Id”. That’s a very real problem with the Enterprises. There were no mapping which had authorization in place for such an API call. We’re sure, many large scale enterprises are equally open to such attacks & their reputation clings on a tolls way after an investigation from compliance team given that the compliance team is enough aggressively capable of checking routinely on rampage a single unclosed vulnerability might cost.

Defencely was able to code a script to know exact numbers of registered users, this script can be found at Simple Python Script to guess the range.

Now let’s simplify the exploitation process.

Exploitation

Defencely created another Python Script for the Proof of Concept showing to the company & to simplify the attack as well in order to demonstrate the grave concern to senior managers & the management team which quickly later reacted to it’s closure of the threat uncovered by the Red Team Operations.

 

Taking out users credentials, remember these same credentials could be harvested & mounted to their social account profiles as most of the time, credentials will always be the same for a victim:

 

That’s all we have for now. Let’s look forward to more amazement at Defencely Red Team Operations Labs next week for absolutely yet another amazing uncover story of how we’re adding value to our customerbase with insider threat program as well as routine sound-ful & an offensive Vulnerability Assessment followed by a Penetration Test for critical applications both at the staging level & production bases. Our manual security assessments methods have proved the best value. Feel free to touchbase at shritam@defencely.com, Shritam Bhowmick, Red Team Lead @Defencely for any Security Operations Related queries or say “Hi” to us at hi@defencely.com for inquiries.

We should see you again next week with another operational tale of the broad security premises where 0days are always a possibility & at proximity of a security compliance issue which always will be a sooner or later decision by the Indian E-Commerce Management & stakeholders.

Let’s act pro-actively.

Estimating Web Application Security Testing

I was recently asked how to estimate time and measure the appropriate timelimit for a certain security program and what considerable items should be inspected before one decides a timeline for particular tests. While the below post might be very sound for small to medium scale businesses, it might fail for enterprise organizations but this will surely prove an elementary insight in generic terms.

We have all heard about the time a pentester invests in order to determine the logistics for enumeration of a web application which is about to go for security testing. In most generic terms, certain pre-assumtions are in place and it’s natural for the security managers to estimate the necessary time-frame to be able to cut across costs on implementation, arranging appropriate resources for the task, etc. This post educates the minimum necessary to-the-point to determine these metrics.

Considerable Items

  • Number of URL’s which could be fetched via Burp’s Spider
  • Number of Parameters which could be fetched via Burp’s Engagement tools
  • Number of vhosts if not pointing to same main application resources
  • Existence of Web Service or API’s which are included in scope
    1. Here you will like to fetch the API’s included via Questionnaires
    2. Map the web services parameter (REST or SOAP)
    3. Add all of this to the pointers of Web Services (sum)

Estimation

The complexity and the size as discussed previously in the answer can be determined via accessing the vhosts, the number of dynamic URL’s (dynamic only means the application is talking to the back-end at the data tier level). Consider using test cases such as I in my one of the research had did previously for the clients below (this is private and one can define there own):

Web Security Test Case

If you are not aware and almost need to estimate a timeline delivery, use Gnatt chart for each submission and test case module i.e. define modules in periodic terms such as ‘Input Validation Security Test cases’, Session Management Security Test Cases’, etc. A look at the below timeline must give an absolute idea how to estimate a proper enterprise delivery schedule:

Web Application Security Project Timeline

But before all of this, what most significant is to roadmap the project planner and describe the client the needed test cases in worksheet so that the client could necessarily go through the requirements document and provide a submission for the same to fix a proper timeline scheduling for you; this can be done in one of these ways:

  1. Map the requirements, if white-box, what are the credentials requirements, etc?
  2. Fill the gaps, check the application before you commit, what are more details required?
  3. Always reach to the conclusions from summation of the aforementioned.
  4. Add more amount of days than the original derived, that way you ensure quality.

A project planner could look something like this which can be a integral need for planning the web application security project phases as well as help you in defining timelines for the project:

Web Security Project Planner

The estimation again is the by-product and it’s not necessarily that you wouldn’t face any scope creep’s, time delay on the project, resources for the project, etc in-between the project (which is why the additional day post which you map the timelines). Now, what rest that remains is to pin-point the critical path and the break points of the project e.g. what could go possibly wrong and to what extend, etc. You need to manage this extremely well and define everything beforehand. Best of luck! I hope you find this information useful.

About the Author

Shritam Bhowmick is an application penetration tester professionally equipped with traditional as well as professional application penetration test experience adding value to Defencely Inc. Red Team and currently holds Technical Expertise at application threat reporting and coordination for Defencely Inc.’s global clients. At his belt of accomplishments, he has experience in identifying critical application vulnerabilities and add value to Defencely Inc. with his research work. The R&D sector towards application security is growing green at Defencely and is taken care by him cheap new balance. Professionally, he have had experiences with several other companies working on critical application security vulnerability assessments and penetration test security engagements, leading the Red Team and also holds experience training curious students at his leisure time. He also does independent application security consultancy.

Out of professional expertise at Application Security, Shritam Bhowmick utilizes his knowledge for constructive Red Teaming Penetration Testing Engagements for Indian Top Notch Clients and has a proven record for his excellence in the field of IT Security. A Google search with his name would suffice the eye. Shritam Bhowmick has been delivering numerous research papers which are mostly application security centric and loves to go beyond in the details. This approach has taken him into innovating stuff rather than re-inventing the wheel for others to harness old security concepts. In his spare time, which is barely a little; he blogs, brain-storms on web security concepts and prefers to stay away from the normal living. Apart from his professional living, he finds bliss in reading books, playing chess, philanthropy, and basket-ball for the sweat. He wildly loves watching horror movies for the thrill and exploring new places for seeking new people alike.

Solution to Cutting Out Cost Expenditure on Information Security

It’s not at all by surprise that information security is most expensive task and is closely knit to risk managers to provide quality assured security to it’s end-product be it: web applications, thick clients or in general software. To reduce overthinking over complicated executive level decision by project managers, it’s essential in general to know how an information security program works.

How to access necessary components for Enterprise security solutions?

The first approach to solving a problem is to understand it’s question. In information security, the question for an organization is to solve security gaps by placing a security program a provide a security plan further to eliminate this rising security gap but how shall the security program look like and how it shall commence is entirely upto security managers. The necessary components are to be placed before the administration and gain an approval to commence these components in order to manage enterprise risks – which includes ‘security’.

In applications, this entire Application life-cycle management (ALM) will have a particular process and it’s components will be essentially:

  1. people
  2. process
  3. product

SDLC_1

Security management for all of them have to be taken into consideration, whether it’s to educate it’s people about security and provide required awareness about information security policies around the organization, secure processes for the organization and the secure product itself. This can be a top-down approach to provide a framework for security (security program) and then plan security in specific ways to protect business assets and it’s interests of the organization. During this entire time in the process, cost can be a factor due to the approved budget for the program and maintenance of the security program to keep solving security gaps in a way they should be.

How to solve ”cost” factor in a security program?

The security managers takes decisions related to security and hence should be able to decide the overall cost in recurring terms. But it’s not just about determining the cost – it’s also about cost cutting to9 get the project budget fixed without affecting the quality provided by the security program. First it’s necessary to access what accomplishments are to be made during the entire life-span of an application or the application that is being developed in-house and will be in production servers after it’s deployed. Some of these have to be considered while setting by layout and determine the costs:

  1. Objectives
  2. Required people
  3. Required outsourcing
  4. Required maintenance

The objectives should be very clear to the project managers in order to set the right people in-house to handle security problems and these people will be responsible to handle and mitigate risks and plan further with internal development teams. It’s also necessary to outsource tasks which needs subject matter expertise since security isn’t about just one thing. When discussing information security – for an instance there might be one than more components that are to be taken care of such as:

  1. secure coding practices in-house
  2. architectural risk analysis
  3. threat analysis
  4. security audits
  5. penetration testing

For most applications, the first three is done in-house and these includes costs too. Involvement of penetration testing comes from outsourcing after the product or software (web applications) are deployed but during SDLC a ‘secure’ mechanism has to be placed which gives birth to SSDLC (secure SDLC). Most threat analysis come after risk analysis has been done at an architectural level because managers have to decide on resource that is to be allocated to each of these components. To cut costs, it’s required that skilled-labor are employed to each of the steps in security framework rather than trying to randomly handle security which most often fails and which isn’t cost effective at-all. Threat analysis will involve:

  • threat modeling
  • threat treatment
  • threat management

Thereat management people and it’s resources will also be responsible for the later results which are out during penetration tests and in-case expected outputs are not acquired, a team of expertise should be able to look at the functional dependency and improve their formal test cases which are two:

  1. positive testing (functional testing)
  2. negative testing (exceptional testing)

Functional testing means what web applications are supposed to do i.e. input v/s output and negative testing means how the applications handle exception or are there any ways in which exceptions occur, and could these lead to business risks? Most of the negative test cases are something which needs focus since they are the elements to which later penetration testing proves unit security testing wasn’t effective and that can be something which might be of concern. Why? because at later stages costs comes to an exponentially to manages security risks and accordingly rearrange and re-implement to make a correction and make the product work without it’s security being affected (and also since organizations have to maintain compliance).

These pointers are small things where the cost cutting can be most accurate because if a pin-point analysis is done how such extra costs can be reduced in security programs, so that at later stages all of it contributes to an overall security budget of the organization. Sometimes it’s also the reason why organization now outsource finance to managed bug bounties. To deliberately handle security the right way, it’s also necessary to keep quality while in the SDLC period, since after the product is released – it might be out of hand and a little too late for managers to manage security.

How does Defencely solve your problems?

Defencely provides a 360 security solution to organizational security problems whether the products are in SDLC or it has been already deployed. If applications are in SDLC phases, it’s more beneficial to cost-cut your resources and get dedicated security expertise to help you realize and reduce risks before any commitments or deployments to your applications – it’s like winning the war before it starts. This could also be beneficial to compliance that the organization has chosen and the required reports it needs to prove their applications are secure for it’s customers and end-users.

The solutions provided is overall and hence it’s extremely helpful to know if certain application passed improvement to maintain a continual security check . This can be in terms of application security assessments, penetration tests, and simulated security testing where a red team accesses your applications in offensive ways to determine measure of security and give your organization the overall security posture. Let’s get you started with the right security program for your platform, contact us to get to help you solve your enterprise security problems.

About the Author

Shritam Bhowmick is an application penetration tester professionally equipped with traditional as well as professional application penetration test experience adding value to Defencely Inc. Red Team and currently holds Technical Expertise at application threat reporting and coordination for Defencely Inc.’s global clients. At his belt of accomplishments, he has experience in identifying critical application vulnerabilities and add value to Defencely Inc. with his research work. The R&D sector towards application security is growing green at Defencely and is taken care by him air max sale. Professionally, he have had experiences with several other companies working on critical application security vulnerability assessments and penetration test security engagements, leading the Red Team and also holds experience training curious students at his leisure time. He also does independent application security consultancy.

Out of professional expertise at Application Security, Shritam Bhowmick utilizes his knowledge for constructive Red Teaming Penetration Testing Engagements for Indian Top Notch Clients and has a proven record for his excellence in the field of IT Security. A Google search with his name would suffice the eye. Shritam Bhowmick has been delivering numerous research papers which are mostly application security centric and loves to go beyond in the details. This approach has taken him into innovating stuff rather than re-inventing the wheel for others to harness old security concepts. In his spare time, which is barely a little; he blogs, brain-storms on web security concepts and prefers to stay away from the normal living. Apart from his professional living, he finds bliss in reading books, playing chess, philanthropy, and basket-ball for the sweat. He wildly loves watching horror movies for the thrill and exploring new places for seeking new people alike.