Sunday, April 27, 2014

eLearnSecurity Advanced Reverse Engineering Of Software - Review

There is a saying "To understand how something works, you must take it apart and unravel its secrets" that's exactly what reverse engineering is all about i.e. breaking down things apart to figure out how they work from inside. If you have a keen interest in software reverse engineering and are curious on how the bad guys really go about cracking the softwares and developing keygens/patches for it, if you are interested in how security professionals go about analyzing complex malwares, then the "ARES Course" is for you.

Straight from the horse's mouth,  "This advanced reverse engineering training course is highly practical, meaning you will learn things by yourself and not just listen to some instructors and watch. If you like the "learning-by-doing" approach, then this is for you. This is NOT a "learn - repeat - forget" type of training. The course guidance ensures that you will get all the necessary knowledge along the way."

Pre-requisites

Before you enroll into this course, the following are the pre-requisites mentioned by the author.

1) You don't need to already be a reverse engineer to attempt this course, this course takes you from a very beginner level up to an advanced level.

2) Knowledge of assembly language would certainly be helpful, however the author covers important instructions along while demonstrations. In the written part, the author also provides several references assembly guiders and reference books. So, in case if you are unaware what particular assembly instruction does you can quickly look through the references.

3) Basic knowledge of programming concepts (Variables, Strings, functions, pointers etc) is required, however you don't need to be a hardcore programmer to be enrolled into this course.

The course is divided into three parts

1) Foundations
2) Technical Part 1
3) Technical Part 2

Foundations

The "Foundation" part talks about the necessary theory you need to understand how understand before you dive into the technical parts. The course focuses specifically upon the intel 32 bit architecture, memory segments such as stack heap, flags, registers and popularly used windows API's and tools in the trade for reversing.

The author points out that it's not necessary to be a master at assembly language in order to become a successful reverse engineer and which started making sense to me as soon as i finished the technical parts of the course, however as mentioned before the knowledge about certain programming concepts will surely be a great help for you.  Here is what the author states:

Probably, you've heard that if you want to become a reverse engineer you have to master assembly language first, which is far from truth. Of course, being a programmer, especially in not a very high level language like C/C++ can be very helpful in some concepts like points, etc.. but in regards to reversing and assembly language, what you really need is to be able to understand what you see. There's no need to write complex programs using assembly.

Technical Part I - Learning how to reverse

The "technical part 1" goes from very basic software patching up-to in depth analysis of algorithms and windows API's. The very first module of this section is  "String References & Basic Patching", in this module the authors explains several methods of patching an executable such as manipulating, noping out the jumps etc to change the program flow. The next module focuses on using the "Stack" for tracing back algorithm, this comes handy when we are up against a binary, where the strings are encrypted and decrypted on the runtime and therefore we are unable to locate the algorithm with static analysis.

In the next module "Algorithm Reversing" the author digs deeper into the world of reverse engineering by analyzing the algorithms in detail to find a solution that would really validate the given algorithm and this is where the real fun starts. The next module, "Windows Registry Manipulation" is more related to reversing malware rather than cracking softwares, the author analyses an application that is trying to read specific piece of information from the registry, in this module the author also explains the use of "Hardware breakpoints" for monitoring access into specific memory areas. In the next module "File Manipulation", the author dives into more practical reverse engineering methods, where he examines an application that is trying to read contents of a specific file inside the system.


Technical Part II - Anti-reversing tricks

In real world, the binary analysis is not as easy as you might think, you might encounter different obstacles and protections when doing professional reverse engineering. Developers have came up with several tricks for making the binary analysis process much harder by using anti-debugging api's, code obfuscation, packers etc.

The modules gives insights into bypassing most commonly used anti-reversing tricks such as bypassing anti-debugging mechanisms, de-obfuscating code obfuscation and the process of manually unpacking a binary. Last but not least, the author explains about reversing multi-threaded applications, the author points out that analyzing these applications can be bit tricky for beginners, however after understanding the concepts of creations of multi-threads on run-time, this process becomes much more easy.


Challenges

Each module comes with a unique challenge which contains a binary which would allow you to practically perform the techniques you have learnt in the video section of the course. In case if you are unable to solve it, just don't panic, in the video parts the author walks you through solving the challenge.

Exam And Certification


Once you have mastered all the techniques taught in the course, you can appear in the eCRE examination, the exam is divided in to two different parts i.e. theory and practical. You must score at-least 88% in theory part which is a multiple choice question and answers.

 Once you have passed the eCRE Stage 1 (Theory part) you would be allowed to attempt the eCRE Stage 2 in which you dive in to the practical part of the examination, you would be given binaries and would have 7 days to analyse them and write a formal report about it. A examiner will formally analyse your report and if you pass you are titled as "eLearnSecurity Certified Reverse Engineer"

Launch Webinar

If you would like to see this course in action, I would recommend you to take a look at the launch webinar, in which the author shows live demonstration of analysing obfuscated binary.


Conclusion


If you are passionate about reverse engineering or have a dream persuading your career as a reverse engineer, then this course is definitely for you. Overall, I would rate the course to be 9/10 as this one of the most technical and informative courses I have ever taken.

For further information about the course, Please refer the following link - https://www.elearnsecurity.com/course/advanced_reverse_engineering_of_software/

Tuesday, April 15, 2014

What is the .htaccess file and what do I use it for?


.htaccess - The Point of DiscussionHT(Hyper Text) access file is actually a directory level configuration file which supports handsome number of servers and those webservers allow administrators for decentralized management of Web Server Configuration. The original purpose of .htaccess ” is reflected inside its name was to allow per-directory access control, for example: requiring a password to access the a directory or file. Nowadays it is used for various other purposes, as .htaccess files can override many other configuration settings including content type and character set, CGI handlers, etc it could very useful for penetration testers as well as webmasters.

Why .htaccess??

The WebServer reads these files every time when the website is loaded. So the changes to the .htaccess file can immediately effect the Server with respect to main Configuration file of server. .htaccess can also be used to authorization/authentication i.e. permitting or denying a user to access a certain content.


1.Authorization & Authentication


A .htaccess file is often used  for both authentication and authorization i.e. to specify security restrictions for a certain resource. The .htaccess file is often accompanied by a .htpassword file which stores valid usernames and their passwords for authentication purposes. We will see examples of both of them (Authorization and Authentication) in later part of this article.

2.Rewriting Urls

Rewriting is sometimes used as conditional operator to add filter to block a specific word or string in a statement.

3.SSI

SSI can be actually helpful to maintain a website dynamically using input parameters specified by the administrators. SSI directories can be defined within the .htaccess itself.

4.Customizing the Error Responses


A .htaccess file can also be used to customize error messages. For example -  What to do if a 404 error occur?, Shall it be redirected to the homepage?, we can also control other things such as Mime types, cache control etc.

Where .htaccess Should Be Placed?

So, we have already discussed about various uses of  .htaccess, now its time to know where .htaccess file should be placed for optimal performance. .htaccess should be placed inside root web directory of the webserver,  so that it could have same effect on all the content within the website but sometimes, it could be placed in a specific directory to perform a task.

For example - A hosting company has described the maximum upload limit of 100mb per image, however in case if one of the customers wanted to upload a picture that is of 110mb what should he do?, He would contact the hosting company ofcourse, now instead of allowing the upload of 110mb from the server for all users, the company would ask the user to place a .htaccess file inside the directory and set the upload limit to 110mb.

Note:This files needs to handled with utmost care because of its sensitiveness. Even a single mistake can lead you to some serious security concerns, So if you don't know what you are doing, we would recommend not to play with it.

Advantages

One of the main advantages of a .htaccess file is that the changes made to this file would take immediate effect on the webserver as opposed to making changes in the main configuration file which often requires the server to be restarted and hence a downtime might occur.  Also, as we explained from the above example that .htaccess allows unprivileged user to perform a privileged action without need to change the main configuration file.

Disadvantages

There are two main disadvantages of .htaccess, one it creates performance loss, second it raises security concerns as you are allowing an unprivileged users to modify the configuration changes. For example - System administrator has disabled the use of the "Symbolic links", however the overrides are allowed, in case if an attacker compromises a single website on the server, he could create a custom .htaccess which would allow symlinks if they are not enabled by default and hence it would allow an attacker to read files outside the user's home directory. The folllowing .htaccess file would allow an attacker to enable and follow symlinks:

OPTIONS  Indexes Includes ExecCGI FollowSymLinksAddHandler txt .phpAddHandler cgi-script .cgiAddHandler cgi-script .plOPTIONS  Indexes Includes ExecCGI FollowSymLinksOptions Indexes FollowSymLinksAddType txt .phpAddType text/html .shtmlOptions AllOptions All

As regards with the performance impact, guys at drupal groups have provided a great explanation. "Here are some excerpts from Wrox's 'Professional Apache' in the chapter on improving Apache's performance:"

"If AllowOverride is set to anything other than 'None', Apache will check for directives in .htaccess files for each directory from the root all the way down to the directory in which the requested resource resides, after aliasing has been taken into account. This can be extremely time consuming since Apache does this check every time a URL is requested, so unless absolutely needed, always (set AllowOverride to 'None')"

Source - https://groups.drupal.org/node/22864

How .htaccess can help in improving security? 

Preventing Common Attacks (But not fully). .htacess can be used to define a blacklist of keywords that you would like to block when it arrives the server. Take a look at the following example

"RewriteEngine on" is responsible for starting the filtering process followed by the specific keyword word you would like to block, which in this case is "order". In this way .htaccess can be used to create a blacklist to filter out malicious inputs for attacks such as SQLi, XSS, LFI, RFI etc. However, this approach is not recommended as blacklist has never been the solution for any security related problem, instead the best option is to fix the vulnerabilities from within the code, the vulnerabilities can be detected via static or dynamic code analysis.


The following screenshots give examples on creating a blacklist with the help of .htaccess:

























Authorization

As discussed before .htaccess could be very helpful for "Authorization" i.e. we can define who is authorized to access the content, in simpler words we can permit or deny a specific Person(s) based upon his IP address .

All we have to do is to simply use allow and deny keywords with in the .htaccess. This feature could be used as a security for admins to only allow their IP to access the administrator page .

Authentication

.htaccess can also be used to password protect a directory, for that we would also need an .htpasswd file. A .htpasswd contains the username and password for basic authentication of users. The following is a great website that could be used to generate .htpasswd files:

  • http://www.htaccesstools.com/htpasswd-generator/
The Protected content could be accessed as follows: http://username:password@www.website.com/directory/


The following screenshot demonstrates the usage of .htaccess by etsy.com to protect wp-admin page for wordpress.


Hiding Errors

This approach is also not recommended and it's called as security through obsecurity, which means that if an attacker cannot find something he is less likely to exploit it.  The idea behind this technique is to turn of php errors, which would not return errors for common vulnerabilities such as SQLi, FPD, LFI etc. However, this approach would only prevent script kiddies not real penetration testers.

Switches Used while working with Php Flag are : php_flag display_errors no/yes [on/off]









Last but not least, we would recommend following video, in case you are really interested in learning more about this topic.

Conclusion

 In this article, we precisely tried to cover various aspects of the .htaccess file, however this topic is far from over, based upon your comments and feedback we might come up with it's part 2.

About Author

This article was original written by Muhammad Adeel (independent Security researcher), however it was later modified by "Rafay Baloch" to make it more clear and understandable.

Saturday, April 12, 2014

DOM XSS Explained - Part 1

         

Cross Site scripting (XSS) has been a problem for well over a decade now, XSS just like other well known security issues such as SQL, XPATH, LDAP Injection etc fells inside the category of input validation attacks. An xss vulnerability occurs when an input taken from the user is not filtered/santized before it's returned back to the user. The XSS can be divided into the following three categories:



1) Reflected XSS
2) Stored XSS 
3) DOM Based XSS 

As time has passed by the security community has came up with lots of solutions to mitigate XSS attacks such as encoding libraries, Web Application filters based upon blacklists, Browser based XSS filters, Content security policy etc, however all of them have had some limitation either not being able to mitigate xss attacks in a certain context. For example - We have a well known PHP based protection library called HTML purifier, it offers great protection against XSS attacks in lots of different context, however currently it has no support for HTML 5, talking about content security policy which dubbed as the best solution for mitigating xss attacks has no support for inline JS as well as no support for mobile browsers.

However, traditional XSS has been mitigated to some extent where the input is sent to the server and when is returned without any sanitation. However what happens in case where the user input is never sent to the server side and get's executed on the client side?. In that case all the server side defenses would fail as the payload never arrives the server. This is what is referred as DOM based XSS when the payload is never sent to the server and is executed on the client side, in order to understand DOM based XSS better, we would need to understand, what's DOM.

What is DOM?    

DOM stands for document object model and all it is a javascript's way of accessing page. Each and every HTML element has a correspoding entity inside of DOM.

What is DOM Based XSS? 

A DOM based XSS vulnerability occurs when a source get's executed as a sink without any sanitization. A source is commonly refered as any thing that takes input, which apparentely in javascript is "Everything taken from a URL". Common sources inside javascript are document.url, location.hash, location.href, document.referer. A more detailed list is available at the DOM based XSS Wiki.

A sink is refered to anything that creates HTML in an insecure way. There are wide variety of different sinks depending upon the javascript libraray you use. For example: In javascript document.write, innerHTML, eval are the most commonly found sinks, where as in jquery we have .html(), .appendto() etc. We can find a list of commonly used sinks at DOM based XSS wiki.

How to find DOM Based XSS?

There are couple of different approaches to detecting DOM based XSS such as black box fuzzing, static analysis and Dynamic analysis. We will discuss all three of them.

Black Box Fuzzing

In black box fuzzing approach, we try injecting different XSS vectors inside different javascript sources and hoping for  javascript to be executed. A tool called Ra-2 is an example of blackbox fuzzing approach towards DOM based XSS. The Fundamental problem with this approach is that it's not context aware and contains several false negatives.

Static Analysis

Another approach is to detecting DOM based XSS is by performing a static source code analysis, where by we try finding out the sources/sinks and we trace if a source is being executed as a sink.DOM based XSS wiki contains a list of regular expressions which would help you find out the sources/sinks:

The following regular expressions would help you determine all the sources and sinks in a javascript file:

Finding Sources: 


/(location\s*[\[.])|([.\[]\s*["']?\s*(arguments|dialogArguments|innerHTML|write(ln)?|open(Dialog)?|showModalDialog|
cookie|URL|documentURI|baseURI|referrer|name|opener|parent|top|content|self|frames)\W)|(localStorage|sessionStorage|
Database)/

Finding Javascript Sinks:


/((src|href|data|location|code|value|action)\s*["'\]]*\s*\+?\s*=)|((replace|assign|navigate|getResponseHeader|open

(Dialog)?|showModalDialog|eval|evaluate|execCommand|execScript|setTimeout|setInterval)\s*["'\]]*\s*\()/

Finding Jquery based sinks

/after\(|\.append\(|\.before\(|\.html\(|\.prepend\(|\.replaceWith\(|\.wrap\(|\.wrapAll\(|\$\(|\.globalEval\(|\.add\(|

jQUery\(|\$\(|\.parseHTML\(/


JSprime and IBM appscan apply this particular approach to detecting DOM based XSS. The fundamental problem with this approach is that javascript code may be compressed, packed or Obfuscated, in that scenario Static analysis won't help us. Also in case where the code is encoded and is decsoded and executed at runtime a static code analyzer won't be able to detect it. An example of this would be the following statement:

eval('var a'+'=loc'+'ation'+'.hash');

The strings would are spilitted and would be joined together in memory at runtime and would be executed by using the eval function.

Dynamic Analysis 

As mentioned above, a static code analyzer won't be able to detect obfuscated and code which would execute at the run-time. In that case, we have another approach called as Dynamic taint tracking. The taint flag is added to the source and it's tracked until it is executed via a source at run-time. Dominator is currently the only tool in the market that utilizes this methodology, however there are several places where dominator is not effective

1) Human interaction is necessary for the analysis to be performed.
2) If a human misses to test a feature dominator would also miss.
3) A better dynamic taint tracking is required.

Let's now talk about few examples:

Example:

<HTML>
<TITLE>Welcome!</TITLE>
Hi
<SCRIPT>
var pos=document.URL.indexOf("name=")+5;
document.write(document.URL.substring(pos,document.URL.length));
</SCRIPT>
<BR>
Welcome to our system

</HTML>

The following code is taken from Amiet klien's paper on "DOM based XSS", In the above script we see a javascript source document.url that takes input from a url, The indexof property searches for the name parameter inside the url and is saved into the "pos" variable, later the user input stored inside the pos variable is being directly written to the DOM without any sanitization.

By inserting the following payload, javascript would be executed and hence would finalize the DOM based XSS attack:

http://www.target.com/page?name=<script>alert(1);</script>

In the above case one might argue that the payload would be sent to the server in initial requests, but in the following scenario where we specify a hash before the name variable, the payload would not be sent to the server.

http://www.target.com/page?#name=<script>alert(1);</script>

Let's take a look at another example:

<html>
<body>
<h2>POC for settimeout DOMXSS</h2>
<body>
<script>
var i=location.hash.split('#')[1];
(function () {
setTimeout(i,3000);
})();
</script>
</body>
</html>

In this case, the source is location.hash, the split function is used which would split up everything after hash, the user input is being stored under variable "i" which is later executed via setTimeout() function which is a known javascript sink.

The following would trigger an alert after three seconds:

http://www.target.com/page.html#alert(1)

Example 3 

<script>
var redir = location.hash.split("#")[1];
x = document.getElementById('anchor');
x.setAttribute('href',redir);
</script>

The following is another very simple example of DOM based XSS, the input is taken from location.hash and is stored inside redir variable. Next, we use getElementByID method to  search for anchor element with id "anchor". next the value of redir is assigned to the href attribute via the setAttribute API. The sink in this case is the href. You may try replacing href with src and it would still result in the javascript being executed.

Cross Browser Detection

Some browsers encode special characters when taken from a particular before displaying it back to the DOM and due to this reason a DOM based XSS vulnerability might trigger in one browser, but does not trigger in another browser. For example: Firefox encodes every thing sent after ?, where as internet explorer doesn't. A list of these characters is already compiled up on DOM based XSS wiki.  Consider, Spending some time reviewing it.

Defending Against DOM Based XSS

The following steps shall be taken to mitigate DOM based XSS attacks

1) Unsafe sinks shall not be used. They shall be replaced with safe methods. For example: innerHTML is classified as a dangerous sink, however innertext could be used in place of innerHTML, which is a safe DOM method. Similarly in jquery, .html() (equivalent to innerHTMLof javascript) is classified as a dangerous method, alternatively we have .text() method to safely write things to the DOM.

2) As there are several different javascript libraries, community should make effort in classifying all the dangerous sinks in that particular libraray and introduce safe methods


This concludes the introductory post on DOM based XSS, Stay tuned for the part 2. 

Monday, April 7, 2014

Hacker's Dome - First Blood CTF



When it comes to Information Security, there's a great way to learn, train and keep sharp your skills. This can be done using gamification mechanics to speed up the learning curve and improve retention rate. Capture The Flag competitions use gamification mechanics and represent one of the best ways to learn security hands on.

We've created Hacker's Dome as a place for CTF365  users to play weekend CTFs with great prizes. In order to get access to Hacker's Dome, the first thing you need is a registered and confirmed CTF365 account.

Although we're at the start of our journey, the goal of Hacker's Dome is to become your weekend security training - where fun, entertainment and awesome prizes will be at its best.

Hacker's Dome is a CTF Platform where you can deploy your own CTF and invite web developers, system administrators and security professionals to take your challenges. Think RackSpace, of CTF Competitions.

We design the challenges with public vulnerabilities or known misconfigurations. Most of them can be found on exploit-db.com or other public sources. We don’t target 0-day vulnerabilities, so you won’t have to disclose your knowledge about arcane methods for getting access to a machine. We use Kali and the basic tools for the purpose of demonstrating the concept of a CTF challenge when we discuss the technical aspects of a competition.

Hacker's Dome - First Blood

First Blood is our first CTF and will start on May 17 2014 15:00 UTC.

Difficulty Grade: Beginners/Intermediate

The Prizes:

We have awesome prizes packages worth > $ 6000 US

First Place Package:

  • WiFi Pineapple Mark V Ultra Bundle (because you love to hack)
  • One year CTF365 Premium Access (because you love to train your skills)
  • Personalized T-shirt and Hat with your CodeName on it. (because you deserve to show off)
  • "Hacker's Dome" + "Hacker's Dome - First Blood" stickers

Second Place Package:
  • WiFi Pineapple Mark V Tactical Bundle (because you love to hack)
  • 6 Months CTF365 Premium Access (because you love to train your skills)
  • Personalized T-shirt and Hat with your CodeName on it. (because you deserve to show off)
  • "Hacker's Dome" + "Hacker's Dome - First Blood" stickers

Third Place Package:

  • WiFi Pineapple Mark V Travel Bundle (because you love to hack)
  • 3 Months CTF365 Premium Access (because you love to train your skills)
  • Personalized T-shirt and Hat with your CodeName on it. (because you deserve to show off)
  • "Hacker's Dome" + "Hacker's Dome - First Blood" stickers

The Raffle

Yes! We have a raffle with a King Prize thanks to Rapid7 - Metasploit guys.

Raffle King Prize - Full Year Metasploit Pro Licence

The fact that Metasploit gave us the opportunity to run a raffle off such great King Prize, makes us proud of what we've done and it encourages us to keep up our good work.

Interested candidates - Click here to register.

About Author - Marius Corici

Serial entrepreneur, in love with Artificial Intelligence. Never a quitter, always a perfectionist, looking for challenges that will change the world we live in. I believe in people and great teams and I do hate that I don’t manage to grab some time to start blogging.