Thursday, November 8, 2012

Password strength case studies

PASSWORDS! They're everywhere! Turn on your computer, you need a password for your user account, log in to your facebook, you need a password, go to an ATM machine, you need a password, make online transactions, you need a password. They're de facto standard of our modern lifestyle. In terms of access control, passwords are one of the 3 types of information ('something you know', 'something you have', 'something you are') that can be used for authentication -or simply- logging in.

The main purpose of having a password is simple. The private or confidential information of an individual or an organisation must not be revealed to another person or party. Access to an information system must be limited to a person or group of people. That's why passwords come into picture but just having a password based access is not a solution at all!

Most of the times, passwords are created by users and as goes the principles of psychology, people tend to choose passwords which are easier to remember. Examples of such passwords include, "password", "password123", "iloveyouangelina", "123456", or the person's own name, their gf/bf's name, their birthdate, their birthplace or usually it is something they admire the most like their son/daughter's name, name of a celebrity or some word related to their religion. I'm pretty sure more than half of the people use these kind of passwords. The problem lies here, these passwords are easier for you to remember, but also these are easy to guess for antagonists out there who hate you! The point here is, the passwords which you use for your online accounts or any other, should be "strong password". This might prevent your facebook account from being accessed by your stalking ex who just 'guessed it'! :P

A strong password maybe something which satisfies the following:
1. It should be min. 10 characters in length. (passwords upto 25-30 in length are okay, but that gives you more pain in remembering them. Also there are chances for you to forget them.)
2. It should have both uppercase letters, lowercase letters, numbers and special characters. Having these four types of characters in the password is exceptionally useful, it exponentially increases the strength of your password. Some websites now make it mandatory to have atleast one from these four sets of characters in your password while registering.
3. It goes without saying, but weak passwords as mentioned above are a big NO NO!
4. Although it is not mandatory, some organisations and websites enforce a policy of changing your password every 3 or 4 months and they have a limit of 10-12 on password repetition cycle.

Before going ahead, I'd like to brief you about brute forcing. Brute forcing is a way of gaining access to somebody's account by simply trying out all the possible combinations of characters. It's like throwing mud (well, alot of mud!) against a wall and seeing what sticks! There are automated programs that try out all the possible passwords (like a, b, c, d, ...aa, ab, ac, .. zazaa ... aaa1.. awdg343 and so on) until one of them matches for the given username. Obviously anyone's password will be one of all the permutations of characters. However, one point is in our favour. This process of generating all possible combinations of characters and trying them against a password field takes a lot of time and computing power. But then there is Moore's law of increase in computing power. Your best bet would be to adhere to strong passwords.

Now let's consider few password combinations and the time required to crack them by brute force:

1. "facebook"
Take for example, 'facebook' as your password. This password is 8 characters long and has only lowercase letters. Let us assume that an attacker knows that you have only lowercase letters in your password. Therefore, each character must be any one from the set of 26 smallcase letters {a, b, c, d, e ... y, z}. Since there are 8 positions in the password, each position may have one of the 26 smallcase letters independent of others. Hence, total there are 26x26x26x26x26x26x26x26 = 2.088E11 i.e. 208 billion possible combinations!
But that's really not a big deal, with today's computing power of trying ~ 4 billion passwords per second, this password can be cracked in less than a minute!
P. S. This is excluding the fact that if your password is as simple as "facebook", attacker would simply guess it! :D

2. "FeedBackForm"
Now this password has little more length - 12 characters. This one contains both uppercase and lowercase letters. Therefore, each position out of 12 can have one out of 26 (uppercase) + 26 (lowercase) = 52 characters. In computers, we treat uppercase A and lowercase a separately. Again, irrespective of other characters. Chances of each position being occupied by one of 52 letters is mutually exclusive i.e. probability for each character is 1/52. (I miss my discrete mathematics class :P ). So, if we calculate,
52x52x .... 12 times. This amounts to, 3.909E20 ! That's 390 billion billion combinations. Now that will take 3 thousand years to crack the password. It is nearly impossible for anything to stick that long. If supercomputers are employed and grids of high-performing computers are engaged, this task can be distributed to all of them which can reduce the maximum time required to few months if not years.

3. "LinkHere73"
Notice that we reduce the password length to 10. One more character set is now added to   the password, that is, digits. Digits can be any character from 0-9. Now, the character set for our password becomes 52 (uppercase n lowercase letters) + 10 (digits) = 62. Again, each of the 10 characters from the password can be any one of these 62. So, 62 objects, for 10 positions, that gives us 8.39E17 or 83 million billion. This will take ~ 6 years for a conventional PC to crack it.

4. "h@cK52Mon!l"
Here we have used additional special characters-@,! in our password. Length of this password is 11 characters. This is a typical example of a strong password. Total character set is both case letters + digits + special characters. That comes out to be around 95 (I have considered only printable characters from the ASCII set here). So, again, 95 characters individually for 11 positions, 95^11 = 5.688E21. 5688 billion billion. Considering the same computing power, this will take 4 thousand years to crack this password which is near to impossible to be done by a single computer.

5. "S00p3r!!$7r0nGPa$$wrD"
This monster over here, is an example of super strong password. This is a type of password that we hackers and security professionals use. It has got all the four character sets and it is 21 characters long. Calculating with permutations, we get 95^21 = 3.4E41. This is a really really huge number. Even if we double up the power of a high-performance desktop PC, (10 billion combinations per second, provided that the target system doesn't crash :D),  it would take some thousand billion billion years i.e. 13 sextillion years to crack one single 21 character password! That is waaaayyy greater than the age of universe which started 14 billion years ago!
It is a waste of time to deploy computers to crack this type of super strong passwords, one has higher probability of success in mere phishing or social engineering.

One last note, in the examples mentioned above, we assume that the target system gives us unlimited number of attempts to try a username-password combination. This is not the case in real world. After a few unsuccessful attempts, websites or servers may block you for a predefined period of time. If this action persists, the admin may block the IP address or the account altogether. Also, having a strong password is not the foolproof solutions since there are many other methods like trojans, keyloggers, MITM attacks that can be used to extract your password without even interacting with the authentication system.

related: http://vipulchaskar.blogspot.in/2010/07/you-are-on-target-common-user.html

Saturday, October 27, 2012

Whatsapp security torn apart

Whatsapp is something you probably use right now, or atleast heard of its name. It is a cross platform IM application for smartphones. Along with messages, people can also send audio, video and images. It is available for all leading smartphone platforms like android, iOS, blackberry, Symbian, Windows etc. Whatsapp handles a few billion messages everyday. That is, approx. more than 50,000 messages are being sent every second! This signifies the popularity of this smartphone app. That is incredible success for a company which was started just a few years ago.

Indeed whatsapp is a great alternative to conventional texting, no doubt. But along with all the merits and successes, this app has got some drawbacks too. It has been heavily criticized for its security issues, mainly cryptographic standards and the way it handles user's personal data. Following paragraphs will elaborate on the security mechanisms this app uses.

As most of the popular instant messaging clients like yahoo and gtalk do, whatsapp uses XMPP i.e. eXtensible Messaging and Presence Protocol. Whatsapp implements a modified version of this standard. On installing this app, it creates an account on whatsapp's server.
Its username, or technically known as 'Jabber ID' is concatenation of the user's country code and their mobile number.
For example, 911234567890 where 91 is the country code followed by 10 digit mobile number.
username : <mobile no>@s.whatsapp.net

There's something interesting about the password. It is generated from the phone's IMEI number or MAC address.
For android devices, the password is md5 hash of the phone IMEI no reversed.
password : md5(strrev($imei))
For iOS devices, the password is md5 hash of the device's Wireless Interface card MAC address, written twice. Mac address is concatenated with itself and its md5 is found out.
password : md5(mac+mac)

Messages are sent as TCP packets. As whatsapp puts it, no messages are stored on their servers once they're delivered to the recipient. For sending of multimedia like audio, video or pictures, the data is first uploaded to the HTTP server. A link to the uploaded file is sent to the recepient's phone alongwith thumbnail file, if required.

Previously, till August 12, 2012, messages were being sent in cleartext. Anyone on the same wifi network was able to sniff the packets and read messages. This gave attackers ability to launch a session hijacking attack. However, currently messages are being sent encrypted for iOS and android. Whatsapp does not specify what encryption standard it implements for some undisclosed location. The encryption algorithm it uses currently has been reverse engineered, especially for iOS devices. Here's a link to the article:
http://pastebin.com/g9UPuviz
Overall verdict is that the current encryption mechanisms are not according to a standard.

This app uses phone's IMEI number or mac address as password. Something that is easily accessible to someone in physical contact with the phone. IMEI number can be found out with apps available in the market, also it is printed on the back side of the battery. Someone using the same wifi network as you, can easily find out the mac address of the iOS device, without being in physical contact, by sniffing. Therefore, anyone using a public wifi for whatsapp is at risk of getting their data sniffed and their account can be used to send and receive messages. All an attacker has to know is victim's mobile number (which is obviously known to him) and the phone's mac address or IMEI to enter into a script. Then they are able to send and receive messages from the compromised account.

Initial login at whatsapp's server uses digest access authentication. You can try this out yourself:
https://r.whatsapp.net/v1/exist.php?cc=<country code>&in=<mobile no>&udid=<password>

Here,
country code and mobile no are to be replaced by your country code and mobile no, and password is something you can get from md5 of IMEI or Mac, as explained earlier.
On successful request, it should give you a status response 'ok' meaning that you're valid over there on whatsapp.. :P
Although whatspp doesn't officially provide its API, there is an open source project called 'WhatsAPI'. Those guys have done a great job of creating whatsapp's API by reverse engineering. It has been very popular though some legal issues have been surrounding it recently.
https://github.com/venomous0x/WhatsAPI
This API is coded in both PHP and Python and can be used in integration with web apps. It can be used to send whatsapp messages to any number. Other such third party web-based API is available:
http://www.whatsapp-api.com/

The API itself is hosted on their site and can be accessed with HTTP requests. Although this service costs money to start using it. 
One more thing we all know, whatsapp shares your contacts with their server to see which contacts are present. The way it is done is very insecure. The mobile numbers of your contacts are sent as an array through HTTP request parameter as follows:

https://sro.whatsapp.net/client/iphone/iq.php?cd=1&cc=$countrycode&me=$yournumber&u[]=$friend1&u[]=$friend2&u[]=$friend3&u[]=$friend4

The verdict... as you can see, whatsapp has got so much to work on security. At the same time, its presence cannot be denied in our daily life. iOS users, do not use it on public wifi, 3G or your own wifi with no other users will do. If you are concerned about security, avoid giving your phone to people who you don't trust because that will be an easy way for them to know your IMEI. We hope that they come up with better alternative to current passwords and standard cryptography implementations to increase reputability with the security community too :)



Tuesday, October 23, 2012

Exploiting eval() function in Python

          I came across a pretty interesting function in python yesterday while coding. It is the eval() function. Basically it takes a string which has a valid python expression, and evaluates it as a regular python code. The risk with this function, if the user manages to enter custom crafted string into this function, it has capability to execute shell commands. Once a remote attacker manages to enter shell commands into your python file hosted on web server, it won't be long before you have to run to the office at midnight because you got a call that web server is compromised.

Here's a link to the usage of eval() function in official python documentation.
          http://docs.python.org/library/functions.html#eval

Using eval function:
The following example demonstrates how eval() works:
         
So it simply takes a string as expression and evaluates it. How can we exploit it to get shell codes executed? There are few ways of doing so.

1. Consider running the following code:

          >>> eval("os.getcwd()")


     This will give your present working directory. You can execute other functions of OS module too, like this one.

         >>>eval("os.system('clear')")
     
     This call will clear the console window and will just display a '0' which i guess is the return value of that function. It works on linux only, windows users, try replacing 'clear' with 'CLS'.
Okay that's there, but how can a potential attacker exploit it? well, what if you replace os.system('clear') with something like os.system('rm -rf /') ?  You get the point right... :D
p.s. please don't execute this one unless you want a clean slate!

2. There's another interesting module in python called as 'subprocess'. 
     http://docs.python.org/library/subprocess.html
The subprocess module allows spanning of new processes and connecting their i/o through pipes. As the official documentation puts it, it intends to replace older modules and functions including os.system.
with the getoutput() function you can execute commands and get their output as follows:

          >>> import subprocess
          >>> subprocess.getoutput('ls')
          >>>eval("subprocess.getoutput('pwd')")

Again, ls or pwd can be replaced by more harmful commands, something like, "rm /etc/passwd" or "rm /any/file/present" depending on your current user privileges.

          >>>eval("subprocess.getoutput('rm /any/file/present')")

Wait a minute!
This only works if you have the OS module or subprocess module imported right? The program you're trying to exploit must have these modules imported in advance. Try running the command

          >>> eval("os.getcwd()")

without importing the OS module. It will give a NameError saying that name 'os' is not defined.
Well, there is a way around this...

There's a global __import__() function in python. It accepts a module name and imports it.
Hence,
__import__('os')
will import the os module and will return a reference to this module. Through this, we can execute functions in the OS module with malicious parameters. The crafted eval() function will look like this:

         >>> eval('__import__("subprocess").getoutput("ls")')


That's all from the attacker point of view, here's how we can 'try' to minimize the risk associated with eval() function.
If you've seen the official documentation of eval(), there are second and third parameters that this function accepts. They are the global and local namespaces that this function accepts for evaluating the expression. The global namespace must be a dictionary while local namespace can be any mapping object.


This example demonstrates how global namespace works. In the first attempt, our global and local namespaces are blank, indicated by {},{} parameters. (by the way, these namespaces are dictionaries that map its index element to its value) Hence, there is no reference of the 'num' object that python can find. Hence it raises an exception saying that 'num' is not defined.
In the second attempt, we set the reference of "num" to the num variable that we have set to 10. Hence now the python can evaluate num*num and return 100.

So, does setting global and local namespaces to blank ({},{}) solve our problem of arbitrary command execution?

               >>> eval('__import__("os").getcwd()',{},{})

It doesn't... because __import__ is a part of "__builtins__" pseudo module. This module and its functions are available to the python program unless you manually restrict it. Now, in the global namespace, you will map "__builtins__" to something blank, empty, a None object maybe. This will prevent the __import__ function (or any other function from __builtins__ ) getting called. Global namespace will look like, {"__builtins__":None} or {"__builtins__":{}}

Hence, now the function,

     >>> eval('__import__("os").getcwd()',{"__builtins__":{}},{})

Will fail because it can't find any reference to __import__ and os either.

This will mitigate most of the security risks, but is still not a foolproof solution. There are ways to bypass the __builtins__:None too, but that is out of the scope of this article.

There are other ways of securing your eval() function too, like removing all the double underscores ("__") from a string before it is passed over to the eval function. This should prevent most of the attacks as of now unless someone comes up with a new method to bypass this. :D

astring = "This string has __double__ underscores"
astring = astring.replace("__","")

The above string can now be passed to the eval function.

One more way, use the literal_eval from the module "ast". ast.literal_eval is a much more secure way to evaluate python strings than the generic eval() function. More documentation about ast module can be found here.

http://docs.python.org/library/ast.html

There are other such dangerous functions in python too, like exec() or file exec and again, there are ways to exploit these and also ways to thwart possible attacks. Input validation plays important role here if you are deploying these on web server or any other public server.


Thanks for reading! :)

Saturday, October 13, 2012

Local DNS Cache Poisoning


You’ve heard about the DNS while configuring your internet connection. You enter two DNS values, one primary DNS and another secondary DNS. DNS is fundamental for the functioning of internet. Through this article, I will explain what DNS is, why it is necessary, how it works and a simple DNS cache poisoning attack. Let’s get started…

What is DNS?

DNS stands for ‘Domain Name System’. The official Wikipedia definition goes something like this:
     The Domain Name System (DNS) is a hierarchical distributed naming system for computers, services, or any resource connected to the Internet or a private network.

Basically, DNS is a service that translates human recognizable domain names (such as www.google.com, twitter.com etc) to their respective IP addresses.

On the internet or any IP network, computers and servers recognize each other by their IP address and not their domain names like google.com. Therefore, it is necessary to convert the domain name which you type in the address bar of your browser to its respective IP address i.e. the IP address where the server residing. Then your browser can establish connection with that server and start exchange of data.

Why DNS is necessary?

It’s difficult for ordinary people to remember hundreds of IP addresses which belong to different web servers. Naturally it’s easier to remember the domain names. This practice of using simpler names, rather than IP addresses, dates back to the ARPANET era. Computers used to have something called as a ‘hosts’ file which mapped computer names to their respective ip address.
In 1983 the DNS was invented which was followed by BIND server, the first DNS server based on unix platform. This eliminated the need for end users to maintain a hosts file.
Another advantage of DNS is that, even if the web server changes its IP address or migrates from one location to the other on internet; its domain name remains the same. Hence end user does not need to worry about the mapped ip address by the DNS service. The DNS servers can add or update DNS entries/records internally.

How does DNS work?

From a client’s point of view, working of DNS is very simple. It sends the request to the configured DNS server. The server sends back the answer and the client establishes a connection with that host. The sequence of steps that take place are as follows:
1.      User types www.example.com in his web browser.
2.      The computer sends request to the DNS server that it is configured to use. The request goes like this – “Where is www.example.com?”
3.      The DNS server receives this request and begins looking up its database to find entry for www.example.com. Luckily, this time, it finds the entry and corresponding IP address (say 192.0.43.10).
4.      It replies back to the client – “www.example.com is at 192.0.43.10”
5.      Client receives this response and starts communicating with the ip address.

Actually, DNS is a distributed system. All the DNS servers are interdependent to resolve an IP address completely. Suppose you made a DNS query for www.microsoft.com and the DNS server you are assigned to, finds that it doesn’t have that record present in its database. How can it find out where www.microsoft.com resides?

Structure of the distributed system

To find out where a particular host belongs, the client has to make recursive DNS queries to reach to the authoritative name server for that particular domain. As the name implies, authoritative name servers have authority over their respective domain name. Authoritative name servers can assign authoritative name servers for their sub domains. Anyway, look at the following hierarchy of the distributed domain name space. Yup, it’s a tree as we studied in the discrete mathematics class… :-P




Whenever a client has to find an IP address corresponding to a host, say, www.microsoft.com, it performs recursive DNS queries on the respective authoritative name servers. A root name server has authentic records of all the ‘Top level domains’ (.com, .org, .net etc.). The name servers for TLDs have records for all the domain names under them e.g. example.com, google.com etc. The process goes like this…

Client        : I wanna go to www.microsoft.com, but I don’t have any records corresponding to that. I know, I’ll ask the root name server.

*client sends request to root name server*

Root name server           : Hmm, I see you’re going to a “.com” domain, Here’s the address of “.com” TLD. Go and ask him.

*client receives the address sends request to .com TLD server*

.com TLD                          : Well, Microsoft.com comes under me. And here’s the address of “Microsoft.com” authoritative name server. You’ll get your answer from there!

*client receives the address and sends request to Microsoft.com nameserver*

Microsoft.com NS           :Hello, You’ve come to right place. I’m the authoritative nameserver for www.microsoft.com and here’s its IP address.

*client receives the address of www.microsoft.com and starts communication with the web server*

Poof, as you can see, resolving domain names is a complicated process and generate a lot of load on the root nameservers as well as TLD nameservers.
To overcome this, your local DNS servers (maybe servers assigned by your ISP) cache the DNS records in their own database such that each time a client makes a request, they don’t have to make recursive DNS queries. They can respond with the matching DNS record entry in their own cache. This also takes away a lot of load from root and TLD nameservers.

DNS Cache Poisoning:

Alright, now let’s look at DNS from a hacker’s point of view. If one can manipulate the records in the DNS cache server, the records are said to be poisoned. An attacker can change the IP address corresponding to a legitimate domain name. Whenever a client requests for this legitimate domain name resolution, they’ll be provided with this spoofed IP address which the attacker inserted. The attacker may have hosted some malicious website on this ip address or maybe created a replica of the original legitimate website for phishing purposes. The number of things an attacker can do with a spoofed DNS record are many. In a nutshell, a poisoned or a compromised DNS server provides invalid or illegitimate DNS resolutions which may point to malicious websites.

Local DNS cache poisoning:

As we’ve seen before, each computer has a ‘hosts’ file which maps domain names to their corresponding IP addresses. Remember when I said client goes to its local DNS server when the user types in a website name? I lied. :-P First of all, the client checks its own ‘hosts’ file if it can find the corresponding entry there. If it doesn’t, then it goes to the local DNS server. Here we’re going to manipulate the hosts file on our PC to redirect some legitimate website names to wherever we want.
Windows users can find the hosts file at the following location:

C:\Windows\System32\drivers\etc\hosts

Remember that hosts file does not have any extension.
Linux users, the hosts file is located at:

/etc/hosts

Edit the hosts file with your favorite editor. Remember that you need administrator privileges on windows and root privileges on linux to be able to do that.
Anyway, the hosts file may look like this:





Now add the following text to the end of the file:
127.0.0.1     www.facebook.com
On windows, it will look like this:

Here, www.facebook.com is the website name which will get redirected, you can replace this with any other website name you want. 127.0.0.1 is the IP address where www.facebook.com will point to. In our case, this is the local loopback IP address, you can replace this by any other ip.

Save the file and try opening www.facebook.com or whatever website name you typed through your browser. It will open your localhost and if there’s no web server currently running, it will say page cannot be displayed.

There are some applications of manipulating hosts file. In home or office environment, a hosts file can be used to block social networking and adult pornography websites just by setting them to point to your localhost or any other webpage on your network containing a warning. Also hosts file can be used for DNS cache poisoning as we saw just now. Legitimate website names may redirect you to a malicious website which may try to introduce Trojans, viruses on your PC or try to phish your online banking or social networking account.

One may also write a simple bash script or a batch file that may manipulate or replace hosts file automatically. This technique is been used in some viruses and worms to poison DNS cache of thousands of innocent users to land them on malicious or spoofed websites. It is advisable to follow the best security practices.

Thank you for following me throughout this article and I hope you’ve found this informative. Waiting for your comments… :)
This article is for information purposes only.

Thursday, September 6, 2012

Changing apache banner to trick nmap scans

'Security Through Obscurity'. This principle is used in securing computer systems by implementation of secrecy in design to provide security. The basic idea is not revealing details about the system or giving out wrong information in attempt to thwart possible attacks. Although this principle provides security upto some extent, it does not actually fix the vulnerability. The only possible benefit is the delay in information gathering phase (wikipedia). However i've been willing to try it out and here I'd like to share it...

I'll show you how to change apache server name to anything you wish (like windows IIS and so on) which will appear in HTTP response headers. The folloing screenshot shows default output of the apache server to nmap scan.

Here I am using apache2 on ubuntu box in VM.
First of all, we need to install mod_security apache module. We do that by typing the following commands on a shell.
       root@ubuntu:~#apt-get update
     root@ubuntu:~#apt-get install libapache-mod-security

Now that mod-security is installed, we need to enable it by typing:
            root@ubuntu:~#a2enmod mod-security

You may want to restart your server at this point of time by typing:
           root@ubuntu:~#/etc/init.d/apache2 restart

Navigate to the following directory:
            /etc/apache2/conf.d/
and open the file "security" with your favorite editor. It should look something like this:

See the line "ServerTokens OS" ?
Replace that with "ServerTokens Full". (alternatively, you can comment out 'ServerTokens OS' and remove the comment on 'ServerTokens Full').

Scroll down a bit and you'll see this line: ServerSignature On
Replace this line with : SecServerSignature Microsoft-IIS/5.0
Note the difference. Here, you can replace "Microsoft-IIS/5.0" with any other name you want. This is the string which is going to appear in the HTTP responses of the server.

Save the file and exit. Restart the server typing in:
          root@ubuntu:~#etc/init.d/apache2 restart

Now you're ready to fire up nmap and scan your host!

There it is! It showed our apache server as microsoft iis.

This technique can be used to temporarily mask the web server name while a critical unpatched vulnerability is existing.
However, there are many other ways a skilled hacker can determine the actual service and version running on the machine. One should not totally depend upon 'security through obscurity' principle and it should never be used as the primary defense against attacks.
Nothing beats secure application coding!
Please let me know your comments and suggestions.. :)
Thank you!





DNS Changer Malware

Hello readers,
Its difficult to juggle between academics, extracurricular, social life, learning stuff and still finding time to write article for my blog. I've got some nice advice today from one of the senior member on a hacker's forum. Nowonwards I'll be doing my best to keep this blog updated. So do check out!
This is an article I wrote for our college magazine which will be published tomorrow. There was a word limit and it's intended for general audience. Here we go...



These warnings splashed across the internet, facebook, google and newspapers, ‘you may lose your access to internet on 9th of July.’ The reason behind it, the FBI was to take down around 100 rough DNS servers that infected over 4 million computers in over 100 countries. ‘Operation Ghost Click’ –as it was codenamed- is considered one of the biggest cybercrime takedowns in the history.
          Year 2007, a group of Estonian and Russian hackers released this DNS hijacking malware. This ‘DNS changer’ malware made its way into user’s computers by tricking them into downloading a video-codec (a piece of software required to play the video format)  when they visit certain websites.  This malware would then change the DNS server entries in the infected computer to point them to a rogue DNS set up by attackers. These servers redirected links of certain websites to advertising pages, thus pulling a revenue of whooping $14 million to its creators through fraudulent advertising. The malware also prevented any installed antivirus from receiving security updates. Within four years of presence of this malware all over the world, its botnet (zombie network) grew up to few million, a large part of which was in the USA.
          On 9 Nov 2011, FBI and the US authorities began the ‘operation ghost click’ to take down this multi million cybercrime racket. Six Estonian and one Russian national connected to the DNSchanger being charged and arrested, FBI seized the DNS servers connected to the malware. Plan was to immediately take down these rough DNS changer, although this would mean leaving millions of infected users without a way to connect to the internet. Hence the court ordered Internet Systems Consortium (ISC) to operate the replacement DNS servers and prompt the infected users about the presence of malware. The deadline of this court order was delayed up to 9th July 2012 because of the concern that there were still many infected computers across the world. During this period, FBI began extensive media campaign to warn users about the DNS changer malware and they might lose access to internet on 9th July.
          Impact of this shutdown is considered minimal, credits to the informational campaign surrounding the malware, ISPs providing temporary DNS to the affected customers, Antivirus companies doing their best along with facebook and google providing notifications to the visitors who were affected by the malware. It has been estimated that number of infections still present is dropped down to some ten thousands. A website http://www.dcwg.org is set up to provide information and help people scan and remove malware from their machines.
          While the damage done by DNSchanger is much under control now, many botnets consisting thousands of zombies, still exist in the world. At worst, sophisticated attacks against government and military systems can be launched from these infected computers, which may create trouble for the end user. It won’t hurt to follow simple security practices to combat the evergrowing hackers’ underground.

Friday, March 2, 2012

Web application attack: XSS


1.     Introduction:
The web has grown exponentially in last few years catering as the foremost platform for e-commerce, Social networking, Banking, Online shopping, Entertainment and much more. Web servers and web applications are being deployed to provide services and carry out operations where the medium World Wide Web is involved. Naturally web application security issues have surfaced, which have become a major cause of concern for organizations which depend on www for their functioning. The field of web application security has increased at great pace with new vulnerabilities and security flaws coming into picture. There will be hardly anyone reading this article, who has not heard of news related to website compromise, user account hacking or ethical hacking. The OWASP lists top 10 web application security risks. OWASP stands for open web application security project. It is a worldwide charitable organization focused on improving security of application software. XSS is a common vulnerability found in web applications which ranks 2nd out of OWASP’s top 10. Nearly 39% of web application security flaws are related to XSS. In this article, I will try to explain how XSS works, its dangers and how these attacks can be prevented.

2.     What is XSS:
XSS stands for Cross site scripting. (Do not confuse XSS with CSS which stand for ‘Cascading Style Sheets’ and are nowhere related). XSS is basically, injecting malicious scripts into webpages or webapplications through an HTTP request which tampers with the expected output from web application. In this, the malicious scripts (precisely, Javascript) exploits the interpretation of scripts in web browser. The browser is fooled into executing scripts that appear to come from trusted website. These XSS attacks occur when web applications send user-supplied input to the browser without proper sanitization. The idea of XSS will get clearer when we discuss the first example in section ‘Finding XSS vulnerabilities’.

3.     Risks of XSS flaws:
Okay, so, what’s the deal when my web browser executes some strange scripts? What all damage it can possibly have? Well, if the website you’re accessing has XSS vulnerability, an attacker with good knowledge can hijack your session with server, steal cookies from your PC, deface webpages, redirect you to unintended webpages and introduce malware scripts into your browser. XSS also aids phishing-a common way of hacking social networking and bank accounts. XSS vulnerabilities are classified as very widespread and most prevalent web application security vulnerability by OWASP. Impacts of XSS are classified as ‘moderate’. Risks arising from XSS range from constantly popping annoying pop-ups to total user account compromise, installing malware, virus on victim’s PC.

4.     Types of XSS:
Reading theory about security stuff like this is always boring. I promise I’ll quickly introduce you to the 3 types of XSS and then we’ll move on to next topics which I hope, you’ll find interesting. Anyways, the 3 types of XSS attacks are called - stored, reflected and DOM based.
1)     Stored:
Stored XSS attacks are those when the malicious script permanently gets stored on the webpages, databases of victim website. Think of it like this- there is this news website which allows you to enter comments on their news articles. The comments stay on the page forever. Now instead of putting comment, you entered a javascript and sent it. Now this javascript will stay there forever and execute every time page is accessed. Here you just performed stored XSS attack. It is found in chatrooms, shoutboxes, bulletin boards, blogs etc.
2)     Reflected:
According to me, reflected XSS vulnerabilities are the most common of all vulnerabilities. For example, consider a situation where a website asks you to enter your name and then greets you by name. Like, “Good Morning !”. Now instead of putting your name, if you put a javascript, it will be echoed back from server and your browser will execute the script. Here we performed reflected XSS attack. It is called ‘reflected’ because the name entered by you doesn’t get stored on website. Error messages, search results, or any other response from server that includes atleast some of the user-supplied data maybe vulnerable to reflected XSS.
3)     DOM based:
Very rare. DOM based XSS are quite similar to the reflected XSS except that script doesn’t need to be echoed from server. Script is injected into the browser’s own DOM environment. The malicious code is passed as a parameter to the script residing on a webpage which unknowingly executes it.

5.     Finding XSS vulnerabilities:
In this section, we’re actually going to find a XSS vulnerability. XSS is basically injection of scripts into webpages. Consider the following simple PHP code which is vulnerable to XSS.



$query = $_POST['query'];
if (isset($_POST['query']))
{
echo "You searched for " . $query . "!";
}

echo "
Please type your search query below:

";
?>
If you have a web server installed, try running this PHP file. It asks you to enter a search query and simply prints “You searched for ”. Suppose if you type ‘PICT’, it will print, “You searched for PICT!”. The URL in this case will be:
http://www.example.com/search.php?query=PICT
Now, what if we replace “PICT” with following snippet of code?
URL will become:
http://www.example.com/search.php?query=
Here, the page will print upto “You searched for “ and then it will actually parse as any other HTML tag and execute the javascript code in between. The alert function is just used for demonstration and it can be replaced with any other javascript code-as we explore in next section. This is a reflected type of XSS attack.  Detection of XSS vulnerability is very easy by testing the input fields or manual analysis of web application code. If a webpage stores user supplied input as an attribute of an HTML tag, putting “> before the script tag will terminate the previous tag and hence browser will interpret script smoothly. Not only javascript, it is even possible to inject HTML code into XSS vulnerable webpage as follows:
http://www.example.com/search.php?query=

Great website!


As you can guess, this will print “You searched for “ and then ‘Great website’ in bigger font size. Similarly, all other HTML tags can be used here. Some mechanisms to thwart XSS attempts like magic quotes can be bypassed with String.fromCharCode() javascript function,  URL obfuscation, hex encoding etc but that is out of scope of this article.

6.     Exploiting XSS flaws:
1)     Injecting phishing page:
Phishing is basically, making the victim log in to a fake login page where the credentials entered by him are recorded by attacker. Their username and password is recorded in some database and they’re redirected back to original website. This is very very common hack these days and lots of people are attempting to ‘phish’ each other’s facebook accounts! If a webpage has XSS vulnerability, the contents of entire webpage can be modified to make it look like a login page where user can enter his credentials. The following example URL will demonstrate this:
http://www.example.com/search.php?query=
Username:
Password:

The above code is self-explanatory where write.php is a PHP file which records username and password sent to it through HTTP GET request.
2)     Iframe phishing:
This is similar to previous one. Instead of putting long html tags like
, etc, the attacker injects iframe in the target webpage as follows:
http://www.example.com/search.php?query=
notice that the 100% height and 100% width occupies the whole size of window and the victim won’t notice the difference if they’re foolish enough!
3)     Redirect phishing:
The injected javascript could be coded to redirect the user to another webpage where the attacker’s phishing page is hosted.
http://www.example.com/search.php?query=
where fakepage.htm is the page attacker wants victim to visit.
4)     Cookie stealing:
A user’s session with server can be hijacked once the attacker gets his cookie. The website should have XSS vulnerability for successful execution of this attack. The attacker can craft his link as follows:
http://www.example.com/search.php?query=
When the user opens such kind of link, the cookie stored by current session (i.e. by example.com) is passed as ‘cookie’ parameter to ‘write.php’ which is a PHP file hosted by attacker on his own domain. This php file records the cookie into database.
5)     Website defacement:
A website is prone to defacement if it has stored XSS vulnerability on it. The attacker can inject a script which can entirely modify the way a webpage looks. The injected script can make any changes to the page relying upon the power of Javascript. I’m sure you must have seen websites which say that they’re ‘hacked’ alongwith some message from hackers!
6)     Javascript events:
Javascript event triggers can be wisely used to perform XSS on websites which allow HTML tags but ban the usage of
When the error page is loaded, browser will parse