Wednesday, August 7, 2013

Detecting Graphics Hardware using Objective-C

Recently, I encountered an issue with a specific graphics card and as a fix, I wanted my application to detect the Graphics Hardware and proceed accordingly. While I was searching on the web, I couldn't find much about solving the problem but I somehow managed to a collect bits and pieces and come up with the solution. So, in this post I am going to discuss the approaches which came to my mind to solve the problem, and the approach used by me.

Approaches:

1. Forking a new process and using exec() family of methods to execute the system command system_profiler SPDisplays and fetching the graphics information.

2. Second approach is almost similar to the first one, the only difference is that instead of using fork to
create a new process, we use NSTask to execute system_profiler .

3. The third approach is to use IOKit. Below is the code which can be used to get the model of the graphics card:

- (void)displayGraphicsInfo
{
    // Get dictionary of all the PCI Devicces
    CFMutableDictionaryRef matchDict = IOServiceMatching("IOPCIDevice");
    
    // Create an iterator
    io_iterator_t iterator;
    
    if (IOServiceGetMatchingServices(kIOMasterPortDefault,matchDict,
                                     &iterator) == kIOReturnSuccess)
    {
        // Iterator for devices found
        io_registry_entry_t regEntry;
        
        while ((regEntry = IOIteratorNext(iterator))) {
            // Put this services object into a dictionary object.
            CFMutableDictionaryRef serviceDictionary;
            if (IORegistryEntryCreateCFProperties(regEntry,
                                                  &serviceDictionary,
                                                  kCFAllocatorDefault,
                                                  kNilOptions) != kIOReturnSuccess)
            {
                // Service dictionary creation failed.
                IOObjectRelease(regEntry);
                continue;
            }
            const void *GPUModel = CFDictionaryGetValue(serviceDictionary, @"model");
            
            if (GPUModel != nil) {
                if (CFGetTypeID(GPUModel) == CFDataGetTypeID()) {
                    // Create a string from the CFDataRef.
                    NSString *modelName = [[NSString alloc] initWithData:
                                           (NSData *)GPUModel encoding:NSASCIIStringEncoding];
                    
                    NSLog(@"GPU Model: %@", modelName);
                    [modelName release];
                }
            }
            // Release the dictionary
            CFRelease(serviceDictionary);
            // Release the serviceObject
            IOObjectRelease(regEntry);
        }
        // Release the iterator
        IOObjectRelease(iterator);
    }
}

The approach which I have used is the 3rd approach. The drawbacks of 1st and 2nd approaches are that they are considerably slow as compared to the 3rd approach.

Source: The credit of the above solution goes to the author of *Coder Blog, Mike Piatek-Jimenez and the original post can be found here.

    Saturday, September 1, 2012

    Debugging: unrecognized selector sent to instance

    If you are a cocoa developer, you must be familiar with  "unrecognized selector sent to instance". And many number of times, it may have increased your caffeine intake :) . But in this post, we are going to see an elegant solution to pin point to the root cause of this message.

    Suppose your console shows you the message:
    -[MoneyWellAppDelegate doThatThingYouDo]: unrecognized selector sent to instance 0xa275230

    Looking at the Xcode backtrace doesn't seem to help either, since it most likely looks like so:





    At this point you start to hunt through your code, looking to see, who sent the -doThatThingYouDo message. You may find the answer right away or you may spend the next hour trying to figure out where that call is coming from.

    The Elegant Way

    The better way of finding out where the things have gone wrong is to pop over to the breakpoint navigator, click the + button at the bottom and choose Add Symbolic Breakpoint .

    In the symbol field enter this symbol:

    -[NSObject (NSObject) doesNotRecognizeSelector:]

    Now when any instance of any object within your program is sent a message to which it does not respond, you will be presented with a backtrace that takes you right to the point where that message was sent.



    So you see, easy peasy japanesey :)

    CREDITS:

    The original source of this blog post is here. The contents of this blog post have been published by the permission of the original author Michael Fey. Many thanks to Michael Fey for this wonderful post.

    Sunday, August 5, 2012

    Cocoa: Creating your own frameworks

    This tutorial is about reusing your code by means of a framework. In this tutorial, we are going to learn, how to create frameworks in cocoa using Xcode and how can we use these frameworks in our applications.

    All you need to know before going through this post is just the basic knowledge of objective - C and Xcode.

    So, lets begin.

    Creating a Framework

    1. Create a new project in Xcode using the Cocoa Framework template.


    2. Create a class which will contain your implementation

    3. Implement your methods in the yourClass.m file and declare them as well in the yourClass.h file as shown below:

      TestClass.h
      #import <Cocoa/Cocoa.h>

      @interface TestClass : NSObject
      +(void)showMessage;
      @end

      TestClass.m
      #import "TestClass.h"

      @implementation TestClass
      +(void)showMessage
      {
          NSLog(@"This is the MESSAGE");
      }
      @end

    4. To make the headers of yourClass available to the application developer, you need to mark the yourClass.h  file as public (which is specified as project by default) as shown in image below:

    5. Now, you need to set the Installation Directory  for your framework ( you can set it to any location you please but I prefer @executable_path/../Frameworks )

    6. Build your framework and you are good to go.

    Using your framework in an Application

    Now, lets see how we can use our framework in an application. For this purpose we will create a sample test application.

    1. Create an application using the cocoa application  template.

    2. Add the framework you just created in your application.

    3. Add a new Copy Files build phase.



    4. Use your framework's classes like any other class as shown below:

      AppDelegate.h
      #import <Cocoa/Cocoa.h>

      @interface AppDelegate : NSObject <NSApplicationDelegate>

      @property (assign) IBOutlet NSWindow *window;

      @end

      AppDelegate.m
      #import "AppDelegate.h"
      #import "TestFramework/TestClass.h"

      @implementation AppDelegate
      @synthesize window = _window;
      - (void)dealloc
      {
          [super dealloc];
      }

      - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
      {
          // Insert code here to initialize your application
          [TestClass showMessage];
      }

      @end


      And VOILA......


    Please do leave your comments behind.

    Wednesday, July 18, 2012

    Cocoa memory management: Tips and Tricks

    This post covers some tips for novice programmers that can be helpful if you are not using ARC and are managing the memory yourself. For this post, I assume, that you are familiar with memory management and related methods ( retain, alloc, release ... etc ). So lets begin:

    Using Anonymous Objects

    It is pretty common for the developers to use anonymous objects and a newbie programmer can unknowingly leak memory while using them as shown in the example below:

    [[NSMenuItem alloc]initWithTitle:[[NSString alloc] initWithString:@"xyz"] action:@selector(selector:) keyEquivalent:@""];

    In the code above, we are trying to create a new menu item, which requires a NSString as one of its arguments and we are creating the string there and then. As we can see that we are using alloc to create the
    string, the retain count of this string is being incremented from 0 to 1. But we wont be able to release it because we have no reference to it. Hence, this statement is leaking memory.

    So, lets rectify this statement:

    [[NSMenuItem alloc]initWithTitle:[[[NSString alloc] initWithString:@"xyz"]autorelease] action:@selector(selector:) keyEquivalent:@""];

    By using autorelease while creating a string, the autorelease pool will make sure that this string won't be released for a minimum of 1 event loop cycle (so we can use it without worrying) and after that, autorelease pool will also make sure that this string is released in the near future.

    Using Notifications

    Although using notifications is not directly related to memory management, but I feel it is worth mentioning.
    When you register to receive a  notification, the notification center creates a weak reference to your object. Now suppose, you have registered an object as observer with the notification center to receive a notification and at some point of time, the observer has been released and ceases to exist, the notification center will be unaware of this release as it holds only a weak reference of the object. So, the notification center will keep on sending notifications to that object even if does not exist. So, we should notify the notification center that the object no longer exists.

    So, ideally when you register for a notification, you must un-register for that notification in -(void)dealloc; or at some other appropriate place.

    Thursday, April 5, 2012

    Building a COCOA application: The Basics

    In this tutorial we are going to learn building a basic application in cocoa. Before building the application I assume that the reader is familiar with the following:

    Prerequisites

    • Familiarity with XCode.
    • Basic knowledge of Objective-C (Data Types, messages, properties etc..)
    • Introductory knowledge of cocoa ( XIB/NIB Files, Outlets, Actions etc.. )
    • Knowledge of MVC (Mode-View-Controller) architecture ( You can get familiar with MVC here )
    Setting Up The Development Environment

    Here is what we are going to use for this tutorial:
    • Operating System:  Mac OS X ( Lion - Version 10.7.3 )
    • XCode: XCode 4.2
    • GCC: GCC 4.2

    Lets Begin
    Before starting with the development lets see what are we going to build today and the major steps that we are going to perform during the whole development process. Below is the goal we want to achieve today.


    We would be creating and application "USD Converter". The user will provide the exchange rate for USD and the number or dollars to convert. As the user press "Convert" button, the application would multiply the exchange rate with number of dollars to provide the amount in other currency in the third text box.

    The major steps we are going to follow are:

    1. Create the View for the application.
    2. Implement the Model (business logic) for our application.
    3. Create a Controller class.
    4. Connect Controller and View.


    Create View for the Application

    So lets begin by creating a new XCode project as shown below:


    We will be selecting to create a Cocoa Application. Once we have created the project we will have to open the Xib file.




    Now Xib file will be containing the view of our application. Below is the step by step procedure to create the View for our application:

    Steps:



    1. Open the xib file using Xcode 4.2
    2. Click on the "Window" object so as to display the window as it would look in our application.
          
    3. Drag a new "Label" object from the object library and place it at appropriate position in the window.
              
    4. Drag a "Text Field" object from the object library and position it in front of the label applied in step 3.
          
    5. As shown in steps 3 and 4,  add another pair of label and text field object as shown in image below
         
    6. Add a "Horizontal Line" object so as to separate out the upper and lower region of the window (just for the sake of beautification)
       
    7. Add another set of label and text field object below the horizontal line similar to step 5.
        
    8. Add a "Push Button" object from object library to be used as the "Convert" button.
       
    9. Set the initialFirstResponder outlet of the window. The initialFirstResponder outlet defines on which  control the cursor will be when the application loads initially.
    10. Set "nextKeyView" outlet for each of the Text Field. The "nextKeyView" outlet defines on which control the cursor move next, when the user presses the <TAB> key.
    11. Similarly set the nextKeyView of the 2nd text field to the 3rd text field.

    AND.....

    Now we have the view for our application.

    Implementing the Model

    Now we have the view but we still need to write the business logic behind our application. We will write this business logic in the model class. So now lets begin with the implementing the model class:

    • Add new Objective-C class to your project and name it as modelClass. This will add two files, modelClass.h and  modelClass.m file.
    • Now lets analyze what do we need in our modelClass: When the "Convert" button is pressed we would want our model class to get two float values corresponding to "Exchange Rate per USD" and "Dollars to convert"and return a float value containing the value corresponding to "Amount in other currency".
    • So below is the code for modelClass.h file:

      #import <Foundation/Foundation.h>

      @interface modelClass : NSObject{
          float convertedAmount;  //variable to hold the converted amount
      }
      @property (readonly) float convertedAmount;
      //method to convert USD to other currency
      -(float)convertCurrency:(float)USD:(float)exchangeRate; 
      @end


    • We have declared a method "convertCurrency" which would take the number of dollars to convert and the exchange rate as arguments and return the float value of the converted amount.
    • Now lets see the implementation file modelClass.m : 

      #import "modelClass.h"

      @implementation modelClass
      @synthesize convertedAmount;
      -(float)convertCurrency:(float)USD:(float)exchangeRate{
          convertedAmount = USD * exchangeRate;
          return convertedAmount;
      }
      @end

    • Above is the implementation of the convertCurrency method. As we can see, this method calculates the converted value by multiplying its arguments and sets the result in variable convertedAmount and returns the same.
    So, now we have the view as well as the model for our application. Now all we need to complete our application is the controller, which we will come to know below.

    Creating the Controller Class

    Once we have the view and the model, they must be connected, and this connection is taken care by the controller class. We will add a new class to our project namely "controllerClass"whose code is shown below:

    controllerClass.h


    #import <Foundation/Foundation.h>

    #import "modelClass.h"



    @interface controllerClass : NSObject{

        modelClass *modelObject;

        IBOutlet NSTextField *exchangeRateField;

        IBOutlet NSTextField *dollarsToConvertField;

        IBOutlet NSTextField *finalAmountField;

    }

    -(id)init;

    -(IBAction)convertAction:(id)sender;

    @end


    controllerClass.m

    #import "controllerClass.h"



    @implementation controllerClass

    -(id)init{

        self = [super init];

        modelObject = [[modelClass alloc]init];

        return self;

    }

    -(IBAction)convertAction:(id)sender{

        float exchangeRate,dollars,finalAmount;

        exchangeRate = [exchangeRateField floatValue]; //Get value from text field

        dollars = [dollarsToConvertField floatValue];  //Get value from text field



        //call method from modelClass to calculate final amount
        finalAmount = [modelObject convertCurrency:dollars :exchangeRate]; 
        [finalAmountField setFloatValue:finalAmount];  //Set the final amount in text field
    }
    @end




    • As we can see above in the controllerClass.h file, we will need to have 3 outlets -  each corresponding to a text field in view and we would need 1 action corresponding to the convert button.
    • When the user presses the Convert button, it would call the -(IBAction)convertAction:(id)sender action, which will read values from text fields and call the method of "modelClass" so as to convert the value into the other currency. So, the controllerClass would need an object of modelClass (as can be seen in the code above).
    Connect the View with the Controller

    Now lets see how will we connect the view with the controller. To accomplish this follow the below mentioned steps:
    1. Open the Xib file with Xcode 4.2.
    2. Drag-Drop the "Object" from the object library to the left pane of the interface builder as shown in the image below.

    3. Select the newly added object from the left pane and click on the  "Identity Inspector" on the right top and change the "Class" of the object to "controllerClass" as shown in image below. Now, the object you added in step 2 belongs to the class controllerClass.

    4. Right Click on the object of controllerClass, it will show the outlets and actions you defined in controllerClass.

    5. Connect the outlets to corresponding text fields and the action to the Convert button.









      And now your application is all set to go. 
      Build and Run it and have fun with your first cocoa creation.


      Friday, January 6, 2012

      Automate tasks in Selenium using Python: Setting Up the Environment

      This post demonstrates setting up the environment to use Selenium as automation tool via python. I will be demonstrating the whole process on Windows 7.

      Steps:

      1. Install JDK: We would need to install jdk as a prerequisite to the eclipse IDE which we would be using to write the python code. You can find jdk here
      2. Install Eclipse: I would prefer to use the Eclipse Helios. You can find the installer here.
      3. Install Python: We would be using python-2.7 for this tutorial. However you are free to use any version. You can find the python installer here.
      4. Install SetupTools: This will provide you with EasyInstall which would be useful later on. You can find SetupTools corresponding to your python version at this location
      5. Create a new Environment Variable in your system with Name "EASY_INSTALL" and value "<install_path_for_python>\Scripts".  You can find out how to create an environment variable here CREATING ENVIRONMENT VARIABLES.
      6. Add this newly created environment variable to your PATH environment variable by appending "%EASY_INSTALL%" (without inverted commas :) ) to it.
      7. Open Command Prompt and type the command

                           C:\> easy_install pip
      8. Then run the command below at command prompt:

                          C:\> pip install selenium
      9. Setup Eclipse for Python: Now we need to setup our eclipse so that we can use it to code in python. You can set up your eclipse as shown in this blog post Setting Up Eclipse.

        WARNING: In the blog post  Setting Up Eclipse  mentioned above. You would need to slightly modify the instructions in STEP-2(c) . The modification will be:

        In the field "Work with:" you should use the URL:  http://update-production-pydev.s3.amazonaws.com/pydev/updates/site.xml instead of the URL shown ( http://pydev.org/updates/)
      10. Download Selenium Server:  You can download the selenium server form the official website here.
      11. Run the Selenium Server: You can run the selenium server jar at command prompt using the command:

                         C:\> java -jar <path_to_jar_file>
      AND YOU ARE GOOD TO GO..................!!!!!! Now you have the environment to automate your tasks in selenium using python. Enjoy!! :)

      Sunday, December 11, 2011

      Hands on with SHELLCODING

      While writing my "strcpy overflow tutorial", I was about to use my custom made shellcode. But then I realized, If it would have been me reading that tutorial, I surely would have wanted to know from where the h3ll that cryptic code came from. So, I decided to write this small tutorial showing how to write a very basic shellcode. This tutorial is not intended to be exhaustive. It just shows you the hood, its you who will have to pick up the hood and explore whats under it.

      Lab Setup

      Operating System: Windows XP SP3
      C/C++ compiler :      lcc-win32
      Assembler :              nasm
      arwin : A little script to find functions in a dll. You can find it here.

      Debugger :               Immunity Debugger
      Perl:                         ActivePerl-5.12.4
      - A piece of code to test our shellcode
                           char code[]=
                           "PASTE YOUR SHELLCODE HERE";
                           int main(int argc, char**argv)
                           {
                                 int (*func)();
                                 func = (int(*)()) code;
                                 (int)(*func)();
                            }

        Lets Begin

        First of all we should know what a shellcode is. Whenever a vulnerability is found in a piece of code/application, it needs to be exploited to alter the actual behavior of the application. After the attacker has taken control of the application, (s)he needs to make that application do something useful. This something useful can be simply spawning a calculator or opening a port so that attacker can remotely connect to victim's machine. This code which does "something useful" for the attacker is known as shellcode. In other words we can say that the actual code which attacker wants to run after exploiting the vulnerability is known as shellcode.

        What we want to do today
        By the end of this tutorial we will try to make a working shellcode (which you can use when you go through "Strcpy BOF" tutorial ;) ). In addition to that we will also take a look at few techniques which can be used to make your shellcode a bit more reliable. So lets see what our goal state is:


        By the end we would be able to write a shellcode which would invoke a popup as shown above. We would be calling the "MessageBox" method to invoke this  popup.

        Lets analyse the working of above program by loading its exe in a debugger (Immunity Debugger)For example







        If we look at the details of "MessageBox" method here at msdn we find out that this method takes 4 arguments.As we can see in the image above, these 4 arguments are pushed onto the stack and then a call to "MessageBox" is made. Also, it should be noted that the 2nd and 3rd arguments are pointer to strings "Hello World" and "Shellcode" respectively.

        So this is what  we want our shellcode to do:

        1. push the strings "Hello World" and "Shellcode" to the stack.
        2. push the arguments "0" , "pointer to HELLO WORLD", "pointer to SHELLCODE" , 0         onto the stack.
        3. call MessageBox.
          Now lets see how this can be accomplished.

          PUSHING STRINGS ON THE STACK: We will be using a perl script written by Peter Van Eeckhoutte of the "corelan team" to convert strings to hex.  
          #!/usr/bin/perl
          # Perl script written by Peter Van Eeckhoutte
          # http://www.corelan.be:8800
          # This script takes a string as argument
          # and will produce the opcodes
          # to push this string onto the stack
          #
          if ($#ARGV ne 0) {
          print "  usage: $0 ".chr(34)."String to put on stack".chr(34)."\n";
          exit(0);
          }
          #convert string to bytes
          my $strToPush=$ARGV[0];
          my $strThisChar="";
          my $strThisHex="";
          my $cnt=0;
          my $bytecnt=0;
          my $strHex="";
          my $strOpcodes="";
          my $strPush="";
          print "String length : " . length($strToPush)."\n";
          print "Opcodes to push this string onto the stack :\n\n";
          while ($cnt < length($strToPush))
          {
            $strThisChar=substr($strToPush,$cnt,1);
            $strThisHex="\\x".ascii_to_hex($strThisChar);
            if ($bytecnt < 3)
            {
               $strHex=$strHex.$strThisHex;
              $bytecnt=$bytecnt+1;
            }
            else
            {
              $strPush = $strHex.$strThisHex;
              $strPush =~ tr/\\x//d;
              $strHex=chr(34)."\\x68".$strHex.$strThisHex.chr(34).
             "    //PUSH 0x".substr($strPush,6,2).substr($strPush,4,2).
             substr($strPush,2,2).substr($strPush,0,2);

              $strOpcodes=$strHex."\n".$strOpcodes;
              $strHex="";
             $bytecnt=0;
            }
            $cnt=$cnt+1;
          }
          #last line
          if (length($strHex) > 0)
          {
            while(length($strHex) < 12)
            {
              $strHex=$strHex."\\x20";
            }
            $strPush = $strHex;
            $strPush =~ tr/\\x//d;  
            $strHex=chr(34)."\\x68".$strHex."\\x00".chr(34)."    //PUSH 0x00".
            substr($strPush,4,2).substr($strPush,2,2).substr($strPush,0,2);
            $strOpcodes=$strHex."\n".$strOpcodes;
          }
          else
          {
            #add line with spaces + null byte (string terminator)
            $strOpcodes=chr(34)."\\x68\\x20\\x20\\x20\\x00".chr(34).
                        "    //PUSH 0x00202020"."\n".$strOpcodes;
          }
          print $strOpcodes;

          sub ascii_to_hex ($)
          {
             (my $str = shift) =~ s/(.|\n)/sprintf("%02lx", ord $1)/eg;
             return $str;
          }

          For example:

          You can run this Perl script and redirect the output to a text file using redirection ( > ) and use it for yourself.

          We have just generated hex for pushing the strings onto the stack, but the MessageBox method expects pointer to these strings. So, after pushing each of these strings onto the stack we will store ESP in any of the registers and when we need to push the arguments before the method call, we will use these stored pointers.


          WRITING ACTUAL SHELLCODE:

          Below mentioned will be the flow of our shellcode:

          1.   push text "Shellcode" to the stack
          2.   save pointer to this string i.e. ESP to register EBX
          3.   push caption "Hello World!!" to the stack
          4.   again save ESP to ECX
          5.   XOR EAX - to make EAX=0 so that we can use it for arguments having value=0
          6.   push EAX -  1st argument
          7.   push EBX - 2nd argument (pointer to the text "Shellcode")
          8.   push ECX - 3rd argument (pointer to caption "Hello World!!" )
          9.   push EAX - 4th argument
          10. call <address of MessageBox> - for this we need to know the address of MessageBox first.
            GETTING ADDRESS OF "MESSAGEBOX" METHOD
            We can use a C program written by "steve hanna" to find the address of MessageBox method. But before we search for the address, we need to know where to search. To accomplish this we would again load the exe in the debugger and take a look at the log. In this log we can see all the dll's that were loaded before executing the program.






















            We will try to find the MessageBox method in " user32.dll " using arwin as shown below:









            *** Remember the method name is case sensitive ***

            Now, lets write the shellcode ( the assembly version ;) )



            [BITS 32]

            PUSH 0X00202021      ;PUSH "HELLO WORLD"
            PUSH 0X21646C72
            PUSH 0X6F57206F
            PUSH 0X6C6C6548
            MOV EBX,ESP          ;SAVE THE POINTER TO STRING
            PUSH 0X00202065      ;PUSH "SHELLCODE"
            PUSH 0X646F636C
            PUSH 0X6C656853
            MOV ECX,ESP          ;SAVE POINTER TO STRING
            XOR EAX,EAX            ;MAKE EAX=0
            PUSH EAX                 ;PUSH ALL FOUR ARGUMENTS
            PUSH EBX
            PUSH ECX
            PUSH EAX
            MOV ESI,0X7622EA11   ;STORE ADDRESS OF MESSAGEBOX
            CALL ESI                      ;CALLTO MESSAGEBOX



            Now we need to convert this assembly version of shellcode into the hex version which we can use in our C application to test this shellcode. We can do so using nasm as shown below:






            After using nasm we get a binary file. Now we need to convert this binary file into a hex file. We do so again by using a script (pveReadBin.pl) written by Peter Van Eeckhoutte of the "corelan team" .


            #!/usr/bin/perl
            # Perl script written by Peter Van Eeckhoutte
            # http://www.corelan.be:8800
            # This script takes a filename as argument
            # will read the file
            # and output the bytes in \x format
            #
            if ($#ARGV ne 0) {
            print "  usage: $0 ".chr(34)."filename".chr(34)."\n";
            exit(0);
            }
            #open file in binary mode
            print "Reading ".$ARGV[0]."\n";
            open(FILE,$ARGV[0]);
            binmode FILE;
            my ($data, $n, $offset, $strContent);
            $strContent="";
            my $cnt=0;
            while (($n = read FILE, $data, 1, $offset) != 0) {
              $offset += $n;
            }
            close(FILE);

            print "Read ".$offset." bytes\n\n";
            my $cnt=0;
            my $nullbyte=0;
            print chr(34);
            for ($i=0; $i < (length($data)); $i++)
            {
              my $c = substr($data, $i, 1);
              $str1 = sprintf("%01x", ((ord($c) & 0xf0) >> 4) & 0x0f);
              $str2 = sprintf("%01x", ord($c) & 0x0f);
              if ($cnt < 8)
              {
                print "\\x".$str1.$str2;
                $cnt=$cnt+1;
              }
              else
              {
                $cnt=1;
                print chr(34)."\n".chr(34)."\\x".$str1.$str2;
              }
              if (($str1 eq "0") && ($str2 eq "0"))
                {
                  $nullbyte=$nullbyte+1;
                }
            }
            print chr(34).";\n";
            print "\nNumber of null bytes : " . $nullbyte."\n";

            Use the shellcode generated by this script in your C application and Compile & Execute.















            AND VOILA!!!

            Now we have our first working shellcode. After pressing the OK button it is most likely to crash as we have not yet managed to exit cleanly via our shellcode.

            But still we want our shellcode to exit cleanly. So what can we do about it?
            Well like we called the "MessageBox" method, we can also call the "ExitProcess" method. Again we will use the arwin program to search the address of "ExitProcess" method in "Kernel32.dll".







            As we can see here that ExitProcess method takes one argument i.e. the exit code, so before calling this method we need to push this argument onto the stack. We need to modify our code accordingly as shown below:


            [BITS 32]

            PUSH 0X00202021      ;PUSH "HELLO WORLD"
            PUSH 0X21646C72
            PUSH 0X6F57206F
            PUSH 0X6C6C6548
            MOV EBX,ESP          ;SAVE THE POINTER TO STRING
            PUSH 0X00202065      ;PUSH "SHELLCODE"
            PUSH 0X646F636C
            PUSH 0X6C656853
            MOV ECX,ESP          ;SAVE POINTER TO STRING
            XOR EAX,EAX            ;MAKE EAX=0
            PUSH EAX                 ;PUSH ALL FOUR ARGUMENTS
            PUSH EBX
            PUSH ECX
            PUSH EAX
            MOV ESI,0X7622EA11   ;STORE ADDRESS OF MESSAGEBOX
            CALL ESI                     ;CALLTO MESSAGEBOX
            XOR EAX,EAX               ;MAKE EAX=0
            PUSH EAX                    ;PUSH THE ARGUMENT
            MOV EAX,0X7656BBE2 ;STORE ADDRESS OF ExitProcess
            JMP EAX                      ;JUMP TO ExitProcess


            Again, you need to convert this assembly code into hex form using arwin and pveReadBin.pl. Compile & Execute. Here you go, now you have a working shellcode which can exit cleanly and you are going to use it in strcpy BOF tutorial (most probably ;) ).

            But wait, before being too happy you need to take another look at the generated shellcode:

            "\x68\x21\x20\x20\x00\x68\x72\x6c"
            "\x64\x21\x68\x6f\x20\x57\x6f\x68"
            "\x48\x65\x6c\x6c\x89\xe3\x68\x65"
            "\x20\x20\x00\x68\x6c\x63\x6f\x64"
            "\x68\x53\x68\x65\x6c\x89\xe1\x31"
            "\xc0\x50\x53\x51\x50\xbe\x11\xea"
            "\x22\x76\xff\xd6\x31\xc0\x50\xb8"
            "\xe2\xbb\x56\x76\xff\xe0";

            Did you notice anything about the highlighted bytes in the generated shellcode? These wont let your shellcode work with the string functions as these are null bytes and as you might already know that null bytes are used as string terminators. So we need to remove these null bytes so as to make our shellcode work with string functions.

            Well, we have a very simple technique to do so :)

            We will not push these null bytes directly onto the stack, we will modify our shellcode so that these null bytes gets generated themselves by our shellcode. And how do we do it?
            Lets see:

            Now if we look at our assembly code, we find that these two null bytes corresponds to below mentioned instructions:
            PUSH 0X00202021      ;PUSH "HELLO WORLD"
            PUSH 0X00202065      ;PUSH "SHELLCODE"

            What if we subtract 0x11111111 from 0x00202021( =0XEF0F0F10), move it to EBX, add 0x11111111 to EBX. This way we bypass the problem of null bytes and the result we get is the same as in the previous case.
            And similarly, we can handle the 2nd null byte as well.

            Finally, we get this:
            [BITS 32]

            MOV EBX,0XEF0F0F10
            ADD EBX,0X11111111
            PUSH EBX
            PUSH 0X21646C72
            PUSH 0X6F57206F
            PUSH 0X6C6C6548
            MOV EBX,ESP
            MOV ECX,0XEF0F0F54
            ADD ECX,0X11111111
            PUSH ECX
            PUSH 0X646F636C
            PUSH 0X6C656853
            MOV ECX,ESP
            XOR EAX,EAX
            PUSH EAX
            PUSH EBX
            PUSH ECX
            PUSH EAX
            MOV ESI,0X7622EA11 
            CALL ESI   
            XOR EAX,EAX
            PUSH EAX    
            MOV EAX,0X7656BBE2        ;Address of ExitProcess
            JMP EAX   

            Convert to hex using arwin and pveReadBin.pl again.


            Reading shellcode - nullfree.bin
            Read 76 bytes

            "\xbb\x10\x0f\x0f\xef\x81\xc3\x11"
            "\x11\x11\x11\x53\x68\x72\x6c\x64"
            "\x21\x68\x6f\x20\x57\x6f\x68\x48"
            "\x65\x6c\x6c\x89\xe3\xb9\x54\x0f"
            "\x0f\xef\x81\xc1\x11\x11\x11\x11"
            "\x51\x68\x6c\x63\x6f\x64\x68\x53"
            "\x68\x65\x6c\x89\xe1\x31\xc0\x50"
            "\x53\x51\x50\xbe\x11\xea\x22\x76"
            "\xff\xd6\x31\xc0\x50\xb8\xe2\xbb"
            "\x56\x76\xff\xe0";

            Number of null bytes : 0

            As we can see above, this time our shellcode is null-free i.e. it does not contain any null bytes.
            Put it into your C application, Compile & Execute & Yippeee....


















            Now, we have made our shellcode a bit more reliable, as I said in the beginning ;) . 
            Now you are good to go to use this shellcode in string related functions as well ( as well as my strcpy BOF tutorial :) ).

            Thanks for your patience while reading this tutorial (Hope you didn't bang your head against the keyboard :P )