Sunday, November 25, 2012

Bash Scripting examples

Example1:
This shows the usage of single quote and double quote.

#!/bin/bash
test="bla bla bla bla";
echo 'I read a sentence like $test inside double quotes';
echo "I read a sentence like $test inside double quotes";
apple='$test'; #Single quotes takes it as a literals
banana=\$test; #Backslash does the same thing
MYIP=`ifconfig eth0 | grep inet | cut -d: -f2 | cut -d" " -f1`;
echo "My IP address is $MYIP";


Example2:
This shows the if condition operation.

#!/bin/bash
fruit1="apple";
fruit2="banana";
if [ $fruit1 != $fruit2 ]
then
   echo "$fruit1 is not equal to $fruit2";
else
   echo "$fruit1 is equal to $fruit2";
fi
# -n is for non empty & -z is for zero length
if [ -n $fruit1 ]
then
   echo "Fruit1 is not the empty string";
else
   echo "Fruit1 is an empty string";
fi

Example3:
#!/bin/bash
# -eq equal, -ne notequal
# -gt (greater than), -ge (greater than or = 2)
# -lt (less that), -le (less than or = 2)
num1=5;
num2=10;
num3=15;
if [ $num1 -ge $num2 ]
then
   echo "$num1 is greater than or equal to $num2";
else
   echo "$num1 is less than $num2";
fi
let num4=$num1+$num2;
if [ $num4 -eq $num3 ]
then
   echo "$num4 is equal to $num3";
else
   echo "$num4 is not equal to $num3";
fi

Example4:
#!/bin/bash
# -r is read permission set, -w for write, -x for execute
# -d (is the file a directory), -f for file, -s non-empty file
dir1=/home/bala;
file1=/tmp/script.sh;
if [ -d $file1 ]
then
   echo "$file1 is a directory";
else
   echo "$file1 is not a directory";
fi
if [ -x $file1 ]
then
   echo "$file1 is executable";
else
   echo "$file1 is not executable";
fi
if [ -r $dir1 -a -x $dir1 ]
then
   echo "$file1 is readable N executable";
else
   echo "$file1 is not both read & executable";
fi

Example5:
#!/bin/bash
#This script is going to loop into useraccount
passFile=/etc/passwd
userCount=0;
specialCount=0;

userIds=`cat $passFile | cut -d: -f3`;
echo $userIds;
for id in $userIds
do
    if [ $id -ge 1000 ]
        then
            echo $id
            #echo $userCount
            let userCount=userCount+1;
            #echo $userCount
        else
            #echo $specialCount
            let specialCount=specialCount+1;
    fi
done
echo "There are $userCount normal users and $specialCount special users on the system"

Sunday, September 9, 2012

Recover Ubuntu from initramfs

Today I powered up my Ubuntu 10.04 on my VM and all of a sudden it complained that it cannot load my OS and gave me (initramfs) prompt and I started searching on the net regarding the same, Many said that the grub may be at fault or the Grub does not know where to look for to mount the Root of the file system from.

I attached a LiveCD to my VM and went into try Ubuntu and once that opened I opened up GParted to see if the partitions are still in there.  I tried to mount the harddisk locally by clicking on Places and the harddisk.   It got mounted normally.  Then I rebooted the system and remove the Live CD in the process.  The VM eventually came back telling that there were some orfan inodes which if needed I can press "F" to fix I did that and the system rebooted once again and my Ubuntu on VM started working :-D  I know every situation may not be as lucky as this.

Wednesday, September 5, 2012

Updating Flash on Ubuntu 10.04

On one of my machine I had Ubuntu 10.04 which got its Firefox upgraded to 15, so from then on when ever I opened Firefox it would connect to Mozilla's website to check if all the plugin are upto date and it kept complaining that Flash is out of date. It also gave me a small button next to it to fix the issue.  So I clicked it and downloaded the tar.gz file, extracted it.

Then move the old libflashplayer.so to old.

# mv /usr/lib/mozilla/plugins/libflashplayer.so /usr/lib/mozilla/plugins/libflashplayer.so_old

Then copy the libflashplayer.so from the extracted tar.gz file to the location.

# cp -rvf /home//Downloads/software/Adobe\ Flash/install_flash_player_11_linux.x86_64/libflashplayer.so /usr/lib/mozilla/plugins/libflashplayer.so


Restart the browser, The plugin check should not complain once again.  Then go ahead and remove the old libflashplayer.so_old file.

# rm /usr/lib/mozilla/plugins/libflashplayer.so_old

Saturday, July 21, 2012

Fixed DVD Driver not opening

Wow I have never removed almost all the components of a DVD drive and put them back togather to this extent.

LG DVD tray opening problem, It stopped opening even when I take a pin and push the pin hole.

Note:  I don't take responsibility if you break you DVD by following my steps.

Step1: Remove the drive from CPU by removing all the screws.
Step2: Remove Four Screws to remove the back plate of DVD drive.
Step3: Detach two sets of Ribbon cable from the main board and remove the board, be careful there are two more cable behind the board as well.
Step4: Now you can just see under side of the board where in two more cable are attached.  The smaller Ribbon cable will pop out as soon as you pull it, However the larger one is clipped down, we have to move the clip up before pulling the largest Ribbon Cable.
Step5: Remove the assemble which holds the Lens by unscrewing two screws towards the end of the box.  The other side is just held with Rubber which can be squeezed to pull them out.
Step6: Now remove the Plastic where the Rubber was attached to the Lens assembly.
Step7: Now remove the Tray by sliding it out,  Here I broke a small notch as I did not know how to remove it.
Step8: Now clean all the place where you see movement and I applied Lip Vaseline.
Step9: Do all the steps shown above in reverse :-)
Step10: You have now breathed new air into your old DVD which was about to be dumped :-D Hurray.


Tuesday, July 10, 2012

Analyzing a Snort Alert

Yesterday I was going about doing my things and suddenly noticed that there were three alerts on my IDS with the signature shown below.


I tried looking at the payload it was really huge like shown below.


I tried looking up the IP http://whois.domaintools.com/91.229.143.59 however I did not get any information useful to me.

I wanted to clean up the payload shown above to see just the URL, so I used the command as shown grep http tmp.txt | cut -d" " -f1 | grep \' | cut -d\' -f1


Well fair enough except the first one all the others does seem to be malicious, so I set out seeking my Web Proxy logs to see how did I land up on the IP.

One look at the proxy logs I almost felt like a amnesia patient getting back his\her memories :-D, because yesterday I was using urlquery.net for some experiment which I was performing. 


Bottom line: Long story short it really pays to have logging enabled to determine if an incident is a false positive or not :-)

Sunday, July 8, 2012

Metasploit SNMP

Here we will try to enumerate all that we could using an unprotected SNMP on an XP machine.

Let us load up msfconsole and use this auxiliary scanner.

msf > use auxiliary/scanner/snmp/snmp_enum


Let us set the RHOST to 192.168.1.17
msf  auxiliary(snmp_enum) > show options

Module options (auxiliary/scanner/snmp/snmp_enum):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   COMMUNITY  public           yes       SNMP Community String
   RETRIES    1                yes       SNMP Retries
   RHOSTS     192.168.1.17     yes       The target address range or CIDR identifier
   RPORT      161              yes       The target port
   THREADS    1                yes       The number of concurrent threads
   TIMEOUT    1                yes       SNMP Timeout
   VERSION    1                yes       SNMP Version <1/2c>
Let the enumeration begin :-)
msf  auxiliary(snmp_enum) > run

[*] 192.168.1.17, Connected.
[*] System information

Host IP                       : 192.168.1.17
Hostname                      : TEST-COMP
Description                   : Hardware: x86 Family 6 Model 23 Stepping 6 AT/AT COMPATIBLE - Software: Windows 2000 Version 5.1 (Build 2600 Uniprocessor Free)
Contact                       : -
Location                      : -
Uptime snmp                   : 4 days, 08:42:26.92
Uptime system                 : 00:04:07.25
System date                   : 2012-7-8 22:23:32.0
User accounts:
     ["Admin"]
     ["Guest"]
     ["Analyst"]
     ["Administrator"]
     ["HelpAssistant"]
     ["SUPPORT_388945a0"]
Network information:
    IP forwarding enabled         : no
    Default TTL                   : 128
    TCP segments received         : 16205
    TCP segments sent             : 7460
    TCP segments retrans          : 7576
    Input datagrams               : 20191
    Delivered datagrams           : 20192
    Output datagrams              : 16540
Network interfaces:
     Interface                    : [ unknown ] AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport
      Id                          : 2
      Mac Address                 : 08:00:27:1a:c8:46
      Type                        : unknown
      Speed                       : 100 Mbps
      MTU                         : 1500
      In octets                   : 8255084
      Out octets                  : 1517158

Network IP:
     Id     IP Address     Netmask     Broadcast
     1     127.0.0.1     255.0.0.0     1
     2     192.168.1.17     255.255.255.0     1
Routing information:
     Destination     Next hop     Mask     Metric
     0.0.0.0     192.168.1.1     0.0.0.0     20
     127.0.0.0     127.0.0.1     255.0.0.0     1
     192.168.1.0     192.168.1.17     255.255.255.0     20
     192.168.1.17     127.0.0.1     255.255.255.255     20
     192.168.1.255     192.168.1.17     255.255.255.255     20
     224.0.0.0     192.168.1.17     240.0.0.0     20
     255.255.255.255     192.168.1.17     255.255.255.255     1
TCP connections and listening ports:
     192.168.1.17     1430     192.168.1.16     80     unknown
     192.168.1.17     1431     192.168.1.16     80     unknown
     192.168.1.17     1433     192.168.1.16     3333     unknown
     192.168.1.17     4444     192.168.1.16     44817     unknown
Listening UDP ports:
     Local address     Local port
     0.0.0.0     161
     0.0.0.0     162
Network services:
     Index     Name
     0     Server
     7     SNMP Service
     21     SNMP Trap Service
Storage information:
     Description                  : ["C:\\ Label:  Serial Number 501d446f"]
      Device id                   : [1]
      Filesystem type             : ["Fixed Disk"]
      Device unit                 : [4096]
      Memory size                 : 9.99 GB
      Memory used                 : 3.47 GB
     Description                  : ["Physical Memory"]
      Device id                   : [4]
      Filesystem type             : ["Ram"]
      Device unit                 : [65536]
      Memory size                 : 511.44 MB
      Memory used                 : 349.00 MB
Software components:
     Id     Status     Name     Path     Parameters
     1     Microsoft Office Enterprise 200
     2     Oracle VM VirtualBox Guest Addi
     3     Python 2.7 PIL-1.1.7
     4     J2SE Runtime Environment 5.0 Up
     5     Python 2.7.1
     6     WebFldrs XP
     7     Adobe Reader 9.4.0


[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf  auxiliary(snmp_enum) >

Saturday, July 7, 2012

Metasploit 10n11 and 12n13




Remote Desktop Problem from Ubuntu 10.04 to Ubuntu 10.04

OMG I spent a lot of time trying to troubleshoot this simple one, which will keep me haunting for a lot of days to come :-(

The task was very simple at hand,  I had to take remote desktop of System A running Ubuntu10.04 natively with a nvidia graphics card on to SystemB running Ubuntu10.04 inside a VirtualBox.

First step I tried vino the inbuilt remote desktop service.  I turned it on and sure enough it was running however when I attempted to connect to it from SystemB I got just a Black screen over VNC viewer, at times I was able to see the remote system and move my mouse and click on certain thing, it does work on the remote system however the VNC screen locally was not refreshing :-(


Second step I tried removing all Desktop effects in SystemA still no change.

Third Step I installed vnc4server, with apt-get install vnc4server and started VNC server on port 5901 with the command vncserver :1 now I was able to see and interact with just a bash terminal no gnome.  To fix the VNCServer running on port 5901 I had to edit the file in the path ~.vnc/xstartup

The only change is I had to add sh on the exec /etc/X11/xinit/xinitrc and kill the current vncserver session and restart it.

http://www.havetheknowhow.com/Configure-the-server/Install-VNC.html

#!/bin/sh

# Uncomment the following two lines for normal desktop:
unset SESSION_MANAGER
exec sh /etc/X11/xinit/xinitrc


[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
x-terminal-emulator -geometry 1280x1024+10+10 -ls -title "$VNCDESKTOP Desktop" &
Now I was able to see and interact with the desktop of SystemA, However I was not able to see display:0 of SystemA.  When I attempted to start vnc4server on display 0 like vncserver :0 I got an error saying that it is already in use so I jumped to 4th solution.

Fourth Step: I installed X11VNC still I was having the same problem as I had at step 1.

Fifth Step: I clicked on System > Administration > Hardware drivers
I saw a green dot with nvidia properitary driver being installed on systemA and I chose to Remove it and restarted systemA. Viola now my problem got fixed at last.

Tuesday, June 26, 2012

Upload to VT from Ubuntu

Hi I have always wondered as to why on Ubuntu there is no Rightclick on a file and upload to VT, so I modified a python script available on the internet to upload a file on VT and display the results.

I have shows the Python code at the end.

Next to add some actions after right clicking on a file inside nautilus you need nautilus-actions

Next configure nautilus-actions as shown.




The %M is what is going to take our file as input for vtcheck.py.  That is it you have all that you need for Rightclicking on a file and Upload to VT in Ubuntu.




I am not sure if the python script would be shown correctly on blogger, so this screenshot of the code.






cat /usr/bin/vtcheck.py
#!/usr/bin/env python
import hashlib, httplib, mimetypes, os, pprint, simplejson, sys, urlparse, webbrowser, time
DEFAULT_TYPE = 'application/octet-stream'
REPORT_URL = 'https://www.virustotal.com/api/get_file_report.json'
SCAN_URL = 'https://www.virustotal.com/api/scan_file.json'
API_KEY = 'REGISTER_ON_VT_TO_GET_API_KEY'

# The following function is modified from the snippet at:
# http://code.activestate.com/recipes/146306/
def encode_multipart_formdata(fields, files=()):
    """
    fields is a dictionary of name to value for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be
    uploaded as files.
    Return (content_type, body) ready for httplib.HTTP instance
    """
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for key, value in fields.items():
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
                 (key, filename))
        content_type = mimetypes.guess_type(filename)[0] or DEFAULT_TYPE
        L.append('Content-Type: %s' % content_type)
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body

def post_multipart(url, fields, files=()):
    """
    url is the full to send the post request to.
    fields is a dictionary of name to value for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be
    uploaded as files.
    Return body of http response.
    """
    content_type, data = encode_multipart_formdata(fields, files)
    url_parts = urlparse.urlparse(url)
    if url_parts.scheme == 'http':
        h = httplib.HTTPConnection(url_parts.netloc)
    elif url_parts.scheme == 'https':
        h = httplib.HTTPSConnection(url_parts.netloc)
    else:
        raise Exception('Unsupported URL scheme')
    path = urlparse.urlunparse(('', '') + url_parts[2:])
    h.request('POST', path, data, {'content-type':content_type})
    return h.getresponse().read()

def scan_file(filename):
    files = [('file', filename, open(filename, 'rb').read())]
    json = post_multipart(SCAN_URL, {'key':API_KEY}, files)
    return simplejson.loads(json)

def get_report(filename):
    md5sum = hashlib.md5(open(filename, 'rb').read()).hexdigest()
    json = post_multipart(REPORT_URL, {'resource':md5sum, 'key':API_KEY})
    data = simplejson.loads(json)
    if data['result'] != 1:
        print 'Result not found, submitting file.'
        data = scan_file(filename)
        if data['result'] == 1:
        time.sleep(25)
        SAMPLE_URL = "http://www.virustotal.com/file-scan/report.html?id=" + md5sum
        webbrowser.open(SAMPLE_URL)
            print 'Submit successful.'
            print 'Please wait a few minutes and try again to receive report.'
        else:
        time.sleep(25)
        SAMPLE_URL = "http://www.virustotal.com/file-scan/report.html?id=" + md5sum
        webbrowser.open(SAMPLE_URL)
            print 'Submit failed.'
            pprint.pprint(data)
    else:
    SAMPLE_URL = "http://www.virustotal.com/file-scan/report.html?id=" + md5sum
    #print SAMPLE_URL
    webbrowser.open(SAMPLE_URL)
        pprint.pprint(data['report'])


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'Usage: %s filename' % sys.argv[0]
        sys.exit(1)

    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print '%s is not a valid file' % filename
        sys.exit(1)

    get_report(filename)
bala@bala-laptop:~$



Here is the python code

Monday, June 25, 2012

6n7Metasploit


5Metasploit


Watermark using Composite, Python and Identify

A few days ago I wanted to watermark few of my images on cmd line and I wrote this blog http://bullet-bala.blogspot.in/2012/06/adding-watermark.html and the trouble which I had was that the Watermark was either very small or very big and got out of the final image. The result of which I created a small python script to extract the Dimension of an image and resize my Watermarker so my water marker always looks okay on the final image.

Initial step create an watermark image and put in inside /usr/local/src/watermark1.jpeg

Next call my python script on command line like so




$cat  watermark.py


#!/usr/bin/python
#Author: Balasubramaniam Natarajan
#Create WaterMark
import subprocess
import sys
import os

#Here I want to get the File to WaterMark
if len(sys.argv) < 2:
print"You need to specify the src image file"
print"For example"
print"watermark.py "
sys.exit()

src = sys.argv[1]
print "Your Input Image File is: ", src

#This command extracts the Dimentions of my Image
CreateImgSize = "identify -format '%wx%h\n' "+src
Size = subprocess.Popen(CreateImgSize, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = Size.communicate()
#This is to trim the additional new line from the above command.
out = out.rstrip('\n')
print "The Dimension of the Image is: ",out, " Pixels"

#This is going to be the name of the output file.
WaterMarkedImage = src+"_output.png"
WaterMarkCmd = "composite -dissolve 10% -gravity south -resize ", out, " /usr/local/src/watermark1.jpeg  ",src, WaterMarkedImage
# The above WaterMarkCmd become tuple which os.system can't accept.
#print type(WaterMarkCmd)
# FinalCmd is a string got from the tuple
FinalCmd = " ".join(WaterMarkCmd)
print "The final command is: ", FinalCmd
os.system(FinalCmd)

#END


Sunday, June 10, 2012

Convert JPEG to PDF

WOW there is a very simple tool which comes along with Ubuntu called convert

$convert input.jpeg output.pdf

Wola that is it we have the image in a PDF form now enjoy :-)

Sunday, June 3, 2012

Adding WaterMark

To add WaterMark to an image we can use the tool which ships with Ubuntu

$composite -dissolve 10% -gravity south input_file.jpeg watermark.jpeg output.jpeg
$composite -dissolve 10% -gravity south watermark1.jpeg IPTables1.jpeg output.jpeg

Here 10% is the brightness of the watermark1.jpge
-gravity south will pull your image to the bottom

Friday, June 1, 2012

nethogs - See which process is eating Bandwidth

Today I discovered that nethogs will show exactly what I wanted (i.e) group the process which are currently active and which are transmitting over the Ethernet\wireless.

#apt-get install nethogs

You need to start nethogs as root

#nethogs


Squid Configuration - Part2


Monday, May 21, 2012

Squid Configuration - Part1


Apache Port Changing on Ubuntu

To change the default port on which Apache listens to on Ubuntu and to access the webpages over the same rename all port 80  to 999 as I have shown.

root@Bodhidarmar:/etc/apache2# grep 999 ports.conf
NameVirtualHost *:999
Listen 192.168.56.101:999
root@Bodhidarmar:/etc/apache2# grep 999 sites-available/default
less-than VirtualHost *:999 grt-than
root@Bodhidarmar:/etc/apache2#

Now access http://IP-address:999

Saturday, May 5, 2012

Making ISO file on Command Line

To make a ISO file on the command line is very simple.

bala@bala-lappi:~$ mkisofs -V PDF -J -R -o pdf.iso PDF/
I: -input-charset not specified, using utf-8 (detected in locale settings)
Total translation table size: 0
Total rockridge attributes bytes: 454
Total directory bytes: 670
Path table size(bytes): 10
Max brk space used 0
814 extents written (1 MB)

bala@bala-lappi:~$ ls -ltrh pdf.iso
-rw-r--r-- 1 bala bala 1.6M 2012-05-05 12:20 pdf.iso
bala@bala-lappi:~$ file pdf.iso
pdf.iso: # ISO 9660 CD-ROM filesystem data 'PDF                       

Now to record that to a disk on cmd link, -v for verbose    '
bala@bala-lappi:~$ cdrecord -v -eject pdf.iso

Friday, March 16, 2012

Wednesday, March 7, 2012

Ubuntu's Registry

WoW today I found out something which is almost equal to windows registry in Ubuntu  we can open it up with the command.

$ gconf-editor

Someone correct me if I am wrong.

Friday, February 24, 2012

Windows Update

Today I was performing Windows update it said that it needs to get two mandatory update I clicked on Okay and I was watching my SNORT IDS.  I saw two " FILE-IDENTIFY Portable Executable binary file magic detection" alerts in them what scared me was that they were from my ISP :-0. I know that we don't have any Micros0ft office in an around my place.

So I went to my windows machine and typed in netstat -aon sure enough I can see two established connection to the IP 122.165.249.90


 ID   < Signature >   < Timestamp >   < Source Address >   < Dest. Address >   < Layer 4 Proto > 
#0-(5-49658) [snort] DNS SPOOF query response with TTL of 1 min. and no authority 2012-02-24 05:38:37 192.168.1.1:53 192.168.56.200:57649 UDP
#1-(5-49659) [snort] FILE-IDENTIFY Portable Executable binary file magic detection 2012-02-24 05:39:33 122.165.249.90:80 192.168.56.200:49160 TCP
#2-(5-49660) [snort] FILE-IDENTIFY Portable Executable binary file magic detection 2012-02-24 05:39:34 122.165.249.90:80 192.168.56.200:49161 TCP

Next I clicked on the first IDS alert and found that it was trying to resolve dns.msftncsi.com and it resolves to the IP Address: 131.107.255.255. This increased my doubt, however drilling further down.  I started running PCAP and restarted my Windows machine.  I found that a second DNS query went out to download.windowsupdate.com which has a CNAME as shown below and my system at last ended up downloading from 122.165.xxx.xxx :-)

bala@bala-laptop:~$ nslookup download.windowsupdate.com
Server:        192.168.1.1
Address:    192.168.1.1#53

Non-authoritative answer:
download.windowsupdate.com    canonical name = download.windowsupdate.nsatc.net.
download.windowsupdate.nsatc.net    canonical name = main.dl.wu.akadns.net.
main.dl.wu.akadns.net    canonical name = intl.dl.wu.akadns.net.
intl.dl.wu.akadns.net    canonical name = dl.wu.ms.geo.akadns.net.
dl.wu.ms.geo.akadns.net    canonical name = a26.ms.akamai.net.
Name:    a26.ms.akamai.net
Address: 122.165.249.90
Name:    a26.ms.akamai.net
Address: 122.165.249.91




Saturday, February 4, 2012

Snort Action

Snort can take the following types of Actions.



The Activate and Dynamic are dropped for the more recent Tagging and Flowbits

The actions of Drop, Reject and SDrop are used when Snort is in Inline mode.

Friday, February 3, 2012

Functions In Assembly


Functions in Assembly
 * Defining a function in Assembly is as follows
.type MyFirstFunction, @fuction

MyFirstFunction:

ret


 * Function is called using "call MyFirstFunction"


Passing Arguments & Returing Values


 * Passing Arguments to Function
- Registers
- Global Memory locations
- Stack
 * Returning Value from a function
- Registers
- Global Memory locations


Program Starts here


.data
FirstString:
.asciz "firstfunctioncall\n"
SecondString:
.asciz "secondfunctioncall\n"
.text
.globl _start
.type MyFirstFunction , @function
MyFirstFunction: #String ptr & length will be added by caller
movl $4, %eax
movl $1, %ebx
int $0x80
ret
_start:
nop
#We will print firstfunctioncall here
movl $FirstString, %ecx
movl $18, %edx
call MyFirstFunction
#We will print secondfunctioncall here
movl $SecondString, %ecx
movl $19, %edx
call MyFirstFunction
#Now we will exit the program
movl $1, %eax
movl $0, %ebx
int $0x80


bala@bala-laptop:~/ASM$ as -ggstabs -o Function.o Function.s 
bala@bala-laptop:~/ASM$ ld -o Function Function.o
bala@bala-laptop:~/ASM$ ./Function 
firstfunctioncall
secondfunctioncall
bala@bala-laptop:~/ASM$ gdb ./Function 
(gdb) break *_start+1
Breakpoint 1 at 0x4000be: file Function.s, line 17.
(gdb) run
Starting program: /home/bala/ASM/Function 
Breakpoint 1, _start () at Function.s:17
17 movl $FirstString, %ecx
(gdb) print /x &FirstString 
$1 = 0x6000e8
(gdb) s
18 movl $18, %edx
(gdb) print /x $rcx
$3 = 0x6000e8
(gdb) s
19 call MyFirstFunction
(gdb) disassemble MyFirstFunction 
Dump of assembler code for function MyFirstFunction:
   0x00000000004000b0 <+0>: mov    $0x4,%eax
   0x00000000004000b5 <+5>: mov    $0x1,%ebx
   0x00000000004000ba <+10>: int    $0x80
   0x00000000004000bc <+12>: retq   
End of assembler dump.
(gdb) print /x $rip
$4 = 0x4000c8
(gdb) s
MyFirstFunction () at Function.s:10
10 movl $4, %eax
(gdb) print /x $rip
$5 = 0x4000b0
(gdb) s
11 movl $1, %ebx
(gdb) s
12 int $0x80
(gdb) s
firstfunctioncall
MyFirstFunction () at Function.s:13
13 ret
(gdb) s
_start () at Function.s:21
21 movl $SecondString, %ecx
(gdb) print /x $rip
$6 = 0x4000cd
(gdb) c
Continuing.
secondfunctioncall
Program exited normally.
(gdb) 


Program Starts here


.data
FirstString:
.asciz "firstfunctioncall\n"
SecondString:
.asciz "secondfunctioncall\n"
.bss
.lcomm StringPtr, 4
.lcomm StringLen, 4
.text
.globl _start
.type MyFirstFunction , @function
MyFirstFunction: #String ptr & length will be added by caller
movl $4, %eax
movl $1, %ebx
movl StringPtr, %ecx
movl StringLen, %edx
int $0x80
ret
_start:
nop
#We will print firstfunctioncall here
movl $FirstString, StringPtr
movl $18, StringLen
call MyFirstFunction
#We will print secondfunctioncall here
movl $SecondString, StringPtr
movl $19, StringLen
call MyFirstFunction
#Now we will exit the program
ExitCall:
movl $1, %eax
movl $0, %ebx
int $0x80


bala@bala-laptop:~/ASM$ as -ggstabs -o Function2.o Function2.s 
bala@bala-laptop:~/ASM$ ld -o Function2 Function2.o
bala@bala-laptop:~/ASM$ ./Function2
firstfunctioncall
secondfunctioncall
bala@bala-laptop:~/ASM$ gdb ./Function2
(gdb) break *_start+1
Breakpoint 1 at 0x4000cc: file Function2.s, line 22.
(gdb) run
Starting program: /home/bala/ASM/Function2 
Breakpoint 1, _start () at Function2.s:22
warning: Source file is more recent than executable.
22 movl $FirstString, StringPtr
(gdb) print /x &FirstString 
$1 = 0x600110
(gdb) x /1xw &StringPtr 
0x600138 : 0x00000000
(gdb) x /1xw &StringLen 
0x60013c : 0x00000000
(gdb) s
23 movl $18, StringLen
(gdb) s
24 call MyFirstFunction
(gdb) x /1xw &StringPtr 
0x600138 : 0x00600110
(gdb) x /1xw &StringLen 
0x60013c : 0x00000012
(gdb) x /1dw &StringLen 
0x60013c : 18
(gdb) s
MyFirstFunction () at Function2.s:13
13 movl $4, %eax
(gdb) s
14 movl $1, %ebx
(gdb) s
15 movl StringPtr, %ecx
(gdb) s
16 movl StringLen, %edx
(gdb) s
17 int $0x80
(gdb) s
firstfunctioncall
MyFirstFunction () at Function2.s:18
18 ret
(gdb) c
Continuing.
secondfunctioncall
Program exited normally.
(gdb) 

Thursday, February 2, 2012

Conditional Branching & Loop

Conditional Branching
 * JXX - JA, JAE, JE, JG, JZ, JNZ etc
 * These Jump depends on the state of eflags
    - Zero Flag (ZF)
    - Parity Flag (PF)
    - OverFlowFlag (OF)
    - Sign Flag (SF)
    - Carry Flag (CF)
 * Only Short & Near jumps are supported, Far Jumps not allowed

Program Start here
.data
    HelloWorld:
        .asciz "Hello Earth!\n"
    ZeroFlagSet:
        .asciz "Zero Flag was Set!\n"
    ZeroFlagNotSet:
        .asciz "Zero Flag Not Set!\n"
.text
    .globl _start
    _start:
        nop
        movl $10, %eax
        xorl %eax, %eax  #To set Zero Flag
        jz FlagSetPrint
    FlagNotSetPrint:
        # Write CallDemo
        movl $4, %eax
        movl $1, %ebx
        leal ZeroFlagNotSet, %ecx
        movl $20, %edx
        int $0x80
        jmp ExitProgram
    FlagSetPrint:
        # Write CallDemo
        movl $4, %eax
        movl $1, %ebx
        leal ZeroFlagSet, %ecx
        movl $20, %edx
        int $0x80
        jmp ExitProgram
    ExitProgram:
        # Exit the program
        movl $1, %eax
        movl $10, %ebx
        int $0x80

Jump on Zero Example
================

bala@bala-laptop:~/ASM$ as -ggstabs -o ConditionalBranch.o ConditionalBranch.s
bala@bala-laptop:~/ASM$ ld -o ConditionalBranch ConditionalBranch.o
bala@bala-laptop:~/ASM$ ./ConditionalBranch
Zero Flag was Set!
bala@bala-laptop:~/ASM$ gdb ./ConditionalBranch
(gdb) list 1
8    .text
9        .globl _start
10        _start:
(gdb) break *_start+1
Breakpoint 1 at 0x4000b1: file ConditionalBranch.s, line 12.
(gdb) run
Starting program: /home/bala/ASM/ConditionalBranch
Breakpoint 1, _start () at ConditionalBranch.s:12
12            movl $10, %eax
(gdb) s
13            xorl %eax, %eax  #To set Zero Flag
(gdb) info registers
rbp            0x0    0x0
rsp            0x7fffffffe3b0    0x7fffffffe3b0
rip            0x4000b6    0x4000b6 <_start+6>
eflags         0x202    [ IF ]
cs             0x33    51
ss             0x2b    43
(gdb) s
14            jz FlagSetPrint
(gdb) info registers
rbp            0x0    0x0
rsp            0x7fffffffe3b0    0x7fffffffe3b0
rip            0x4000b8    0x4000b8 <_start+8>
eflags         0x246    [ PF ZF IF ]
cs             0x33    51
ss             0x2b    43
(gdb) s
FlagSetPrint () at ConditionalBranch.s:25
25            movl $4, %eax
(gdb) s
26            movl $1, %ebx
(gdb) s
27            leal ZeroFlagSet, %ecx
(gdb) s
28            movl $20, %edx
(gdb) s
29            int $0x80
(gdb) s
Zero Flag was Set!
30            jmp ExitProgram

LOOP Instruction

 * This is a normal Loop instruction
 * Number of times to Loop given in ECX, i-- automatically
 *

Program Start here

.data
    HelloWorld:
        .asciz "Hello Earth!\n"
.text
    .globl _start
    _start:
        nop

        movl $5, %ecx
    PrintFiveTimes:
        pushq %rcx
        movl $4, %eax
        movl $1, %ebx
        leal HelloWorld, %ecx
        movl $13, %edx
        int $0x80
        popq %rcx
    loop PrintFiveTimes
    jmp ExitProgram

ExitProgram:
        # Exit the program
        movl $1, %eax
        movl $10, %ebx
        int $0x80


bala@bala-laptop:~/ASM$ gdb ./Loop
(gdb) break *_start+1
Breakpoint 1 at 0x4000b1: file Loop.s, line 9.
(gdb) run
Starting program: /home/bala/ASM/Loop
Breakpoint 1, _start () at Loop.s:9
9            movl $5, %ecx
(gdb) s
PrintFiveTimes () at Loop.s:11
11            pushq %rcx
(gdb) print /x $rsp
$1 = 0x7fffffffe3d0
(gdb) x/1xw 0x7fffffffe3d0
0x7fffffffe3d0:    0x00000001
(gdb) s
PrintFiveTimes () at Loop.s:12
12            movl $4, %eax
(gdb) print /x $rsp
$2 = 0x7fffffffe3c8
(gdb) x/1xw 0x7fffffffe3c8
0x7fffffffe3c8:    0x00000005
(gdb) s
13            movl $1, %ebx
(gdb) s
14            leal HelloWorld, %ecx
(gdb) s
15            movl $13, %edx
(gdb) s
16            int $0x80
(gdb) s
Hello Earth!
17            popq %rcx
(gdb) s
PrintFiveTimes () at Loop.s:18
18        loop PrintFiveTimes
(gdb) print /x $rcx
$4 = 0x5
(gdb) s
11            pushq %rcx
(gdb) s
PrintFiveTimes () at Loop.s:12
12            movl $4, %eax
(gdb) s
13            movl $1, %ebx
(gdb) s
14            leal HelloWorld, %ecx
(gdb) s
15            movl $13, %edx
(gdb) s
16            int $0x80
(gdb) s
Hello Earth!
17            popq %rcx
(gdb) print /x $rsp
$5 = 0x7fffffffe3c8
(gdb) x /1xw 0x7fffffffe3c8
0x7fffffffe3c8:    0x00000004
(gdb)