www.main.lv
Don't think just code it

Search results for 'post'

2011-10-30 C inline assembler

There is long time since wanted to learn "creepy" gcc inline assembly.
Looking at manuals its not so hard and "creepy". Using it is more
interesting and dissambly of compiled code is very nice looking.

volatile puts our asm code where it is and don't optimize it without
volatile it can optimize.

What to write in __asm__ directive looks like this

__asm__ __volatile__("our_code":output:input:used)


as code to convert to inline asm we will use last post [2].

There is only one instruction that we using and it usage was

get_timer:
	rdtsc
	ret


its not very optimal and for 1 instruction writing whole function
its not beautiful. We remember that returning result of this function is
saved in eax register.

__asm__ __volatile__("rdtsc":"=a"(x)::)


code looks like this. But we can make it as define function

#define get_timer(X) __asm__ __volatile__("rdtsc":"=a"(X)::)


This code works fine and give 70058 ticks on cycle
When adding option -O2 then result becomes wherry strange.

As we remember that rdtsc return result in edx:eax then we add to
used registers(clobber) %edx.

#define get_timer(X) __asm__ __volatile__("rdtsc":"=a"(X)::"%edx")


And also we can rewrite everything as
inline function.

static inline unsigned int get_timeri()
{
	unsigned int i;
	__asm__ __volatile__("rdtsc":"=a"(i)::);
	return i;
}


Now this two functions works fine with -O options.
When empty cycle is optimized then it becomes empty and resulting
tick number is 32 for both inline function and define macro.
It not working for his main purpose. When no optimization switched
then get_timer works for some ticks faster then get_timeri.

We can add attribute always inline and we will win some ticks
and function will always inline regards optimization level

__attribute__((always_inline)) unsigned int get_timeri() 


Too fix test cycle for our measurement we make it as object file
and it will compiled without options.

void fixed_cycle()
{
	int i;
	for (i=0;i<10000;i++)
	{
	}
}


Now everything looks quite good and also inline assembly works as expected.

For reference about inline asm you can go to [1]

Source

Links
[1]http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
[2]http://main.lv/post/linux-antidebug-5

2011-07-01 AVR disassembler

Disassembler for Atmel AVR microcontrollers made for be fast and simple. No extra features only
basics.  Converts binary file to AVR asm output.

If you have ihex then you can convert it to binary with
ReprBin

Here is example output

2411      CLR   0x11  
be1f      OUT   0x3f   , 0x1    
e5cf      LDI   0xc    , 0x5f   
e0d4      LDI   0xd    , 0x4    
bfde      OUT   0x3e   , 0x1d   
bfcd      OUT   0x3d   , 0x1c   
e010      LDI   0x1    , 0x0    
e6a0      LDI   0xa    , 0x60   
e0b0      LDI   0xb    , 0x0    
ebee      LDI   0xe    , 0xbe   
e0f0      LDI   0xf    , 0x0    
c002      RJMP  +4    
9005      LPM   0x0   
920d      ST    0x0    , 0x0    
36a0      CPI   0xa    , 0x60   
07b1      CPC   0x1b   , 0x11   
f7d9      BRBC  0x1    , -10 
e010      LDI   0x1    , 0x0    
e6a0      LDI   0xa    , 0x60   
e0b0      LDI   0xb    , 0x0    
c001      RJMP  +2    

2011-03-12 Python web login tips

Some times there is need to automitize all tasks.
Like login on page download some info and go out.
There is html parsers they can do such tasks

For example it can be login script for some browser game or mail account that doesnt allow
SMTP or SMTP is not for free.

For example there is web-browser game travian an it after some time playing
it becomes very boring to play because only thing that you do it waiting
while some game events take too many time. Like when you click upgdade
something than you need to wait some hours until finish.

Now here we will make login example.
We need external libraries:
httplib2 http://code.google.com/p/httplib2/
lxml http://lxml.de/

First thing that we need its to get page source.

conn = httplib2.Http("cache")
resp,cont = conn.request("http://travian.com")


After we have source we look on login form
<form method="post" name="snd" action="dorf1.php">
	<input class="text" type="text" name="name" value="">
	<input class="text" type="password" name="password" value="" maxlength="20">
	<input type="image" value="login" name="s1" onclick="xy();" id="btn_login" class="dynamic_img">
	<input type="hidden" name="w" value="">
	<input type="hidden" name="login" value="1299937743">
</form>

 As we see here is many inputs

As ther is only 1 form we dont check and simply take first form from array

from lxml.html import parse,tostring,fromstring,submit_form

page = fromstring( cont )
form = page.forms[0] 
for inp in form.inputs:
	if inp.type == "text":
		inp.value = name
	if inp.type == "password":
		inp.value = password



Dont forget about method="post"

headers = {'Content-type': 'application/x-www-form-urlencoded'}


Now we are ready to send data and get cookie that will allow us
get inside the page

resp , cont = self.conn.request( self.server+"/"+form.action , "POST" , body=urllib.urlencode(body) , headers=headers )


Response has cookie that we need to save if would like to work with page in future

cookie = resp['set-cookie']


Also cookie is needed if whant to logout:

headers = { 'Content-type': 'application/x-www-form-urlencoded' }
headers = { 'Cookie': self.cookie }
body = {}
resp,cont = self.conn.request(self.server+"/logout.php", body=urllib.urlencode(body) , headers=headers)


As you see now cookie is inside headers. You should allways place cookie
inside headers if whant to be loged in. Because only cookie that you get at login
says for server that you are loged in and can see what is behind the wall.

Thers is also easy way how to access DOM components
With your favorite browser you can easly get DOM path to prefered tag in HTML source.

tmp = page.xpath("/html//div//div//div//div//p//span")


You can find some tag by class name using find_class()
Or get text content from tag with text_content()

tmp = page.xpath("/html//div//div//div//div//p//span")[2].find_class("none")[0].text_content()


To make your own script that can parse and get info you need only

reguest()
find_class()
text_content()
xpath()
fromstring()


It is very easy. Now you know everything to make your first script that can login on
you favorite page.

2011-02-18 Intel/Linux/BSD system

FreeBSD assembler sample:
Tools
Simple programm
Hello world
Hello world + libc
C + asm
Links where is somthing useful
Files
Open File

Linux assembler samples:
Hello World
gcc + asm
g++ + asm
Open file 
Make directory

SDL assembler example
SDL programming

FPU Topics
Calculating polinom

SSE
SSE add

Programming sample from various themes.
Basic HTTP server
FPU catch division by zero
BIn2Hex converter
ReprBin
Arp Packet Analyzer
Keyboard LED flush
PC speaker
Xlib, hello world

Interesting themes:
Linux Format String Attack
ELF rewrite function
Assembler scripting language
ELF text section
Linux ShellCode 1
Local Descriptor Table
Nano bug (CVS 2010-1160)
Hooking interrupt descriptor table

Antidebug
Antidebug 1
Antidebug 2
Antidebug 3

2011-01-22 Linux assembler scripting language

This is small interpretr in asm.
It works with small language thats can make simple things
All that you need to know about language
is this symbols "ABCDI$@"

ABCD is used with parametr.
I without param
$@ is params


ABCD - is like assembler command mov where symbol is register name
A0 is mov eax, 0
B9 is mov ebx, 9
only one number is supported. Number range after ABCD suposed to be 0...9. But you can add any other symbol only not @ or $. Look inside ascii table char '0' is 0 and other goes relativly from it. number '~' is '~'-'0'=127-48=79

I - is interupt number 80h

$@ - is variables from stack
@ - uses current varaible from stack and stack pointer goes to next stack value
$ - uses current stack value and dont change stack pointer position

Thats all.

Now we can make our first script and run it.

There is 2 thing that you should know. Script is converted to assembler commands and copyed in memory position.

Every file has hiw own purpose and all they seperated for easy to use

'script.inc' you scipt inside it
'stack_table.inc' configure stack for use
'variables.inc' define variables
'exec.inc' memory region wher script interpreted commands will copyed

Example 1:
Now first example script:

script db 'A1B0I'
mov eax, 1 ;you can look this variable inside
#include < asm/unistd.h> 
or in http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html
mov ebx, 0
int 80h

it is command exit. stack can be empty.
Example2:
Now we can make hello_world.
script db 'A4B1C@D@IA1B0I'
It is
mov eax, 4
mov ebx, 1
mov ecx, buffer_msg; stack value 0
mov edx, buffer_len; stack value 1
int 80h

mov eax, 1
mov ebx, 0
int 80
in C it would be
write(1,buffer_msg,buffer_len)
exit(0);
Here is example how corresponds asm to C code http://www.main.lv/posts/view/linux-assembler-open-file. Ther is used stack in 'stack_table.inc':
stack_table:
	dd buffer_msg ;variable 0
	dd buffer_len ;variable 1
and in 'variables.inc' we define this variables:
buffer_msg db "Hello world",10	;with newline
buffer_len = $-buffer_msg	;using fasm mega feature to detect size
we can count equvialent asm commands and there is 8 of them it means add 8 lines in 'exec.inc'
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90

type make and everything works =]. WooHoo small interpretd language is made and it fits in 417 bytes.

2010-09-16 ELF rewrite function

Main idea was to replace compiled in function with some other code and run it.In default it is not possible. If you try to write some bytes withmemcpy() in function location then segfault happens. Why? Programm has different segments and they used for different program purpose.Our code belongs to readonly-executable segment. And '.text' section We can se it with
readelf -S main -l
in previos post there was program that can be used to make segment writable.After running
./textwriteble main
now segment with '.text' section becomes writable. When we try use memcpy() there is no segfault now.Second thing is how to make our function that will replace compiled in functionposition independent for some data inside function? First of all we should know our current position.It is in eip register. push eip? mov eax, eip? it doesnt work. When we use call in stack is saved return address. Now with this small functionit can be saved in some location

get_ip:
    mov ecx, [esp]
    ret
At this moment we have converted segment to writable.Have writen position detection function. If there would be data that will used in replaced function than need detectposition of that data. For example we will use
mov eax, sys_call ;we will use SYS_WRITE = 5
mov ebx, output_id ; output on terminal is STDOUT 1
mov ecx, pointer_to_msg
mov edx, size_of_msg
int 80h
if this was ordinary situation then define:
msg db "Hello",10
msg_size = $-msg
and our code becomes
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg
mov edx, msg_size
int 80h
but how to know position of msg if you dont know position where function will placed?Use function get_it and you will know current instruction position. And it will next instructionafter
call get_ip
Our code becomes
call get_ip    ;calling and detecting eip
saved_ip:      ;position that will be saved
jmp get_ip_end ;jump over function
get_ip:
    mov ecx, [esp] ;save return eip
    ret
get_ip_end:
mov eax, SYS_WRITE   
mov ebx, STDOUT
add ecx, msg-saved_ip  ;offset of msg
mov edx, msg_size
int 80h
ECX has position independent pointer to our text.For testing purposes function fun() is filled with
asm(".byte 0x90, ... ,0x90");
hex 0x90 translates in nop instruction.nop is No OPeration instruction.And function does nothing.Function fun()  contains
push ebp
mov ebp, esp
start_overwrite_here:
nop
...
...
...
nop
pop ebp
ret
Nop instructions can be replaced with any binary code.There should be enought nop instructions for our binary code.There is no check on function size that way when overwriting can be problemsif binary code size is larger then function size.Start function overwriting at position (&fun+3) witn memcpy()
push ebp
mov ebp, esp
start_overwrite_here:
nop
...
...
...
nop
pop ebp
ret
Wuala function after enabling segment can be overwriten. Here is used previous expirienceand we have mega trick with function replacment.
Compile:
make

Source

Linkage:
[1] http://www.unixwiz.net/techtips/win32-callconv-asm.html
[2] http://www.programmersheaven.com/mb/x86_asm/357735/357735/get-the-value-of-eip/
[3] http://toku.es/2010/06/text-writable/
[4] http://main.lv/posts/view/elf-text-section
[5] http://main.lv/posts/view/linux-assembler-hello-world

2010-04-04 PSP snake game

When I saw ost about patapon exploit that worked on PSP FW 6.20 I was happy. I was bought PSP-3004 for programming but i dont know that not always you can programmyour PSP, but now my dream come true
Link
Since exploit relised I started to trying it. Then I compiled everything
that is needed to programm PSP and now I have my own dirty and unfinished
version of PSP snake game. It can be started at this moment only through exploit.
Source

2009-11-30 Linux ShellCode 1

First shell code writened from example. Shell code is very interesting way how to execute some code.asm source:

use32				
xor eax, eax
inc eax
xor ebx, ebx
int 80h


fasm code.asm code.bin
bin2hex output:
\x31\xc0\x40\x31\xdb\xcd\x80
C source:

#include <stdio.h>
char code[] = "\x31\xc0\x40\x31\xdb\xcd\x80";
int main()
{
  void (*ret)();
  ret = (void (*)())code;
  ret();
  printf("Nope it not working\n");
}


gcc main.c -o main
run
./main
nothing happens. That exactly that code do exits from programm Source

My variant of Bin2Hex

2009-10-24 Making C executables smaller

There are some simple things that can be done to make C executables as small as possible.
Here is some example code we will work with:

#include <SDL/SDL.h>

char quit = 0;

int main()
{
    SDL_Surface *screen,surface;
    SDL_Event e;
    SDL_Init( SDL_INIT_VIDEO );
    screen = SDL_SetVideoMode( 400, 400, 32, SDL_SWSURFACE );
    while(!quit)
        while(SDL_PollEvent(&e)>0)
        {
            if(e.type==SDL_MOUSEBUTTONDOWN) quit=1;
            if(e.type==SDL_KEYDOWN) quit=1;
        }
    SDL_Quit();
}


Compile:
gcc main.c -o main -lSDL

Size before: 5326 bytes
Execute command:
strip main

strip is included in most unix systems. It deletes some info symbols from executables Size after: 3532 bytes
You can also try sstrip which is advanced version of strip. You can download it from ELF kickers webpage. Execute command:
sstrip main
Size after: 1960 bytes
There are some others way to decrease size of programm. GC Masher Allows to bruteforce gcc options for smaller executable size. I where using this options for gcsmaher
-O  -O0  -O1  -O2  -O3  -Os
-ffast-math
-fomit-frame-pointer
-fauto-inc-dec
-mpush-args
-mno-red-zone
-mstackrealign 

After runnig with this options executble size is 5175 bytes and best compiling options are all posible combination.  Combining with sstrip gives 1960 bytes. And there size where not reduced but some time there can be saved some bytes.Now we will change main function with
void _start()
and return change to
asm ( \
      "movl $1,%eax\n" \
      "xor %ebx,%ebx\n" \
      "int $128\n" \
    );
One other thing is to archive your executable and cat it with unpack shell script.
a=/tmp/I;tail -n+2 $0|zcat>$a;chmod +x $a;$a;rm $a;exit
Best options and smallest size now is 563 byte. Nope this is not smallest size try to rename executable name to one symbol and you will get 4 extra bytes.
gcc -Os -ffast-math -fomit-frame-pointer 
-fauto-inc-dec -mpush-args -mno-red-zone -c small.c;
ld -dynamic-linker /lib/ld-linux.so.2 small.o /usr/lib/libSDL.so -o small;
strip -s -R .comment -R .gnu.version small;sstrip small;
7z a -tGZip -mx=9 small.gz small > /dev/null;
cat unpack.header small.gz > small;
chmod a+x small;rm small.gz small.o
Download Source
Rewriting all in asm gives 526 bytes Link.
Link to other resources Link1.
Author in link has 634 bytes. With his options I have 622 bytes and using gcmasher i have 606 bytes. I have used his source in this compare.

2009-03-18 PyGame Post

Wanted to know how will looks when mousepointer moving and all arrows shows it direction
Download

2008-10-26 Modifed Blender Towers

This is modifed verdion of this script. There was added only few new lines of code. Final result is better than simply generated boxes of random height. Also I have added 3 images of 2 random generated towns.
Script