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

Search results for 'bug'

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-09-28 Linux antidebug 5

When debuging programm line by line or when running it
in some debugger then ther can be some time delays when you
pressing buttons. We can measure them with asm command

rdtsc 


this instruction read time-stamp counter into edx:eax in our programm will be enought values from
eax

function for c that uses rdtsc is

extern int get_timer()


in fasm it looks like

get_timer:
	rdtsc
	ret


ther is writen code

s = get_timer();
for (i=0;i<10000;i++)
{
}
e = get_timer();
d = e - s;


average time to execute 10000 is 70069 ticks for value
on with we detecting how fast working code i have choose
twice of average 120000 if execution time is larger then
probably it is debuged.

Compile
make


2011-09-15 Linux antidebug 4

Here is one more method how to check if your application is debugged.
Need to set signal handler with handles interrupt number 3 with is used
for step by step debugging

Compile:
gcc main.c -o main

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE  1

void sig_handler( int );

int debuging;

int main()
{
	debuging = FALSE;
	signal(SIGTRAP, sig_handler);
	__asm__("int3");
	if (debuging == FALSE)
	{
		printf("Nothing special\n");
	} else
	{
		printf("Playing seek and hide\n");
	}
	exit(1);
}

void sig_handler( int sig)
{
	debuging = TRUE;
}


Run:
./main

Example with asm

Compile:
fasm ad4.asm ad4.o
gcc ad4.o -o ad4
format ELF

include 'ccall.inc'

SYS_EXIT	equ		1
SIGTRAP		equ		5
TRUE		equ		1
FALSE		equ		0
section '.text' executable

public main

extrn printf
extrn exit
extrn signal

main:
	ccall	signal, SIGTRAP, sig_handler
	int		3h
	
	cmp		[debug],FALSE
	jne		no_dbg
	ccall	printf,str1
	jmp exit
	
no_dbg:
	ccall	printf,str2

to_exit:
	mov		eax, SYS_EXIT
	mov		ebx, 0
	int		80h

sig_handler:
	param1 equ dword [ebp+8]	
	mov		[debug], TRUE
	ret

section '.data' writable

debug	db	FALSE
str1	db "Under debug",0xA,0
str2	db "No debug",0xA,0
Tested and works for gdb and ald. Links:
[1] http://blog.binarycell.org/2011/04/simple-antidebugging-methods-part-2.html

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

2010-12-03 Skype Rich Mood Text Animations

Mood text in skype is simple and not very interactive. Trought skype api there can be done some animations.First step was to test set mood text  trought api.Here is script that directly sends to skype Skype commnd for setting rich mood text. Linux dont support latest skype Protocol 7 (API version 3.0) but on Win there everything words ok. Here you type in commandline
./setrichmood.py "New mood"
and rich mood text changed

import sys
import os
import Skype4Py

skype = Skype4Py.Skype()
skype.Attach()

if len(sys.argv) == 2:
	if os.path.exists( sys.argv[1] ):
		f = open( sys.argv[1] , "r" )
		s = unicode(f.read())
		f.close()
		c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+s )
		skype.SendCommand( c )
	else:
		s = unicode(sys.argv[1])
		c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+s )
		skype.SendCommand( c )

Why I it call rich mood text? because it support some xml like commands.from skype api there is such commands
Example:

//------------------------------------------------------------------
// For purpose of bit conservation we omit feedback notifications
SET PROFILE RICH_MOOD_TEXT Smiley: <ss type="smile">:-)</ss>
SET PROFILE RICH_MOOD_TEXT <font color="#ff0010">Red text</font>
SET PROFILE RICH_MOOD_TEXT <blink>Blinking text</blink>
SET PROFILE RICH_MOOD_TEXT <b>Bold text</b>
SET PROFILE RICH_MOOD_TEXT <i>Italics</i>
SET PROFILE RICH_MOOD_TEXT <u>Underlined</u>
SET PROFILE RICH_MOOD_TEXT First lineSecond lineThird line

<ss type="smile"></ss> also accepts following smileys:

    * smile, sad, laugh, cool, surprised, wink, cry, sweat, speechless, kiss, tongueout, blush, wonder, sleepy, snooze, dull, inlove, talk, yawn, puke, doh, angry, wasntme, party, worry, mmm, nerdy, lipssealed, hi, call, devil, angel, envy, wait, hug, makeup, giggle, clap, think, bow, rofl, whew, happy, smirk, nod, shake, punch, emo, no, yes, handshake, skype, heart, brokenheart, mail, flower, rain, sun, time, music, movie, phone, coffee, pizza, cash, muscle, beer, drink, dance, ninja, star, mooning, finger, bandit, smoke, toivo, rock, headbang, poolparty, swear, bug, fubar, tmi. 
I have tryed use them one inside other but it doesnt worked.How there can be made animations? Here is very simple example that reads from file linesand after time delay shows lines.

./moodanime.py anime.xml
Here is new peace of script:
import sys
import os
import Skype4Py
import time

skype = Skype4Py.Skype()
skype.Attach()

s = []
if os.path.exists( sys.argv[1] ):
	f = open( sys.argv[1] , "r" )
	for line in f:
		s.append(line)
	f.close()
	
while True:
	for frame in s:
		c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+frame )
		skype.SendCommand( c )
		time.sleep( 1 )

as example file can be:
____Bonanza____
___#Bonanza#___
__##Bonanza##__
_###Bonanza###_
####Bonanza####
_###Bonanza###_
__##Bonanza##__
___#Bonanza#___

And now everything works fine. I have tested this scipts with python2.7 and on ArchLinux. If there is some problems try static or dynamic skype from skype download page

2010-10-06 LISP city simulator

Here is first LISP programm that I wrote for LISP courses that I am taking in university.Press food ration per day and houses that you whant to build. There is no end in game.You play until food is zero or until write quit. It was challenging to write something in lisp and also very interesting.Forget to mention that it has some bugs.
Source

2010-04-24 CVE 2010-1160 Exploiting nano

CVE-2010-1160 Nano Changed File Symlink Privilege EscalationUsualy if I have to edit some file I am using nano editor. It is almost on every distribution and easy and fast to use. Some time ago i hated vim beacouse of Ctrl-D =] and that way used nano or pico. Now I know how to exit from vim :q!. After this bugreported in CVE i was exited to check it out in real life. It is first bug that i have fully tested.This bug is fixed in newest versions. Testing all nano version this bug works on < 2.1.7 versions now on my system is latest nano version and I have compiled many < 2.1.7 versions to test this bug. To get your nano version run:$ nano -VWhen user is editing file nano don't check if it is edited by some one else. When saving file it simply save it and dont check if it was modified. If file was changed by some one else then nano will overwrite it with his text. But it can be changed to symlink that points to other file. How to use it in real life:

1) Open file with nano
2) Change file or set symlink
3) Make changes in file and save file in nano
4) See result in symlinked file

Everytning looks like$nano text.txtNow some one do:$ls -s empty.txt text.txtNano savewhach you save in text.txtIn  python it looks like:

os.remove( "text.txt" )
open( "empty.txt" , "w" ).close()
os.symlink( "empty.txt" , "text.txt"


Python step by step

If you are root and opening file with owner isnt you. Than owner while you editing his file can setsymlink to some "/etc/important.conf" and you will overwrite it with some other unrelated info. This can make some harm to your system.How can it be exploited in real life by "small unpreviliged user". Make some interesting file that root will interested in. Make some process that whachs nanos running in system.
If nano opened file is our , symlink it.

1)Detect running nano in system
2)Check with file is opened
3)If file is yours make symlink
Nano catch

Script is only for user and dont work if you try to symlink root opened nano. It makesall steps as described above. Change script variables for your tests:
debug = True
nano = "nano-2.0.9"
user = "user"
sym_path="/home/user/empty.txt"

Tested only with python 2.6.5

Simply be uptodated or if you using old nano dont open with privileged user unpriveleged user files. It will save you from this bug.
Linkage:
[1] http://osvdb.org/show/osvdb/63872
[2] http://cve.mitre.org/cgi-bin/cvename.cgi?name=2010-1160
[3] http://drosenbe.blogspot.com/2010/03/nano-as-root.html
[4] http://svn.savannah.gnu.org/viewvc/trunk/nano/ChangeLog?revision=4503&amp;root=nano&amp;view=markup

2010-03-05 Linux antidebug 3

Now we will try to make disasm output whery unclear. We make jump with eax register
Programm 1

main:
	push lbl+1
	pop eax
	jmp eax	
lbl:
	db 0xe8
	mov eax, 4
	mov ebx, 1
	mov ecx, msg1
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	int 80h
Output is same as source. Nothing changes
Dissassembler output 1
? ....... ! main:                           ;xref o80482d7     
? ....... !   push        offset_804837d                  
? 8048379 !   pop         eax                        
? 804837a !   jmp         eax                         
? 804837c     db          0e8h                            
? 804837d !                                                   
? ....... ! offset_804837d:                 ;xref o8048374 
? ....... !   mov         eax, 4                       
? 8048382 !   mov         ebx, 1                   
? 8048387 !   mov         ecx, strz_I_am_running__8049568  
? 804838c !   mov         edx, 0eh           
? 8048391 !   int         80h              
? 8048393 !   mov         eax, 1             
? 8048398 !   mov         ebx, 0 
? 804839d !   int         80h 


Here we add only one instruction. We get jump adress and add 1. Disasm cannot calculate adress of jmp.
Programm 2
Like in first programm disasm think that we push correct adress and disasm it. And our byte 0xe9 is used for disasm output. That nice.
main:
	push lbl
	pop eax
	inc eax
	jmp eax
lbl:
	db 0xe9
	mov eax, 4
	mov ebx, 1
	mov ecx, msg1
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	int 80h

Dissassembler output 2
? ....... ! main:                           ;xref o80482d7  
? ....... !   push        offset_804837d 
? 8048379 !   pop         eax            
? 804837a !   inc         eax     
? 804837b !   jmp         eax   
? 804837d !                      
? ....... ! offset_804837d:                 ;xref o8048374 
? ....... !   jmp         804883ah        
? 8048382     add         [ebx+1], bh     
? 8048388     mov         ecx, 8049568h   
? 804838d     mov         edx, 0eh  
? 8048392     int         80h     
? 8048394     mov         eax, 1  
? 8048399     mov         ebx, 0 
? 804839e     int         80h 
Now we add nop instruction after every line of our code. It doesnt have any imapct on programm work.
Programm 3
main:
	push lbl
	pop eax
	inc eax
	jmp eax
lbl:
	db 0xe9
	mov eax, 4
	nop 
	mov ebx, 1
	nop
	mov ecx, msg1
	nop
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	jmp lbl2+1
lbl2:
	db 0xe9
	int 80h

Disasm output now is very nice. Output isnt very good. For first time when you view this output it is very unclearabout what exactly is done by this code.
Dissassembler output 3
? ....... ! main:                           ;xref o80482d7
? ....... !   push        offset_804837d  
? 8048379 !   pop         eax   
? 804837a !   inc         eax     
? 804837b !   jmp         eax  
? 804837d !               
? ....... ! offset_804837d:                 ;xref o8048374 
? ....... !   jmp         804883ah   
? 8048382     add         [eax+1bbh], dl
? 8048388     add         [eax+49578b9h], dl  
? 804838e     or          [eax+0ebah], dl     
? 8048394     add         ch, cl               
? 8048396     cmp         byte ptr [eax+1], 0bbh  
? 804839d     add         [eax], al   
? 804839f     add         [eax], al  
? 80483a1     jmp         80483a4h
? 80483a3     jmp         98950475h  

Here is one more way how to make unclear jumo to other place. We using functionand inside function we change return adress by 1.

Programm 4
Thats also works fine. Disasm dont know real return adress ans and use 0xe8 as he think is better.
main:
	call fun
	db 0xe8
	mov eax, 4
	mov ebx, 1
	mov ecx, msg1
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	int 80h
	
fun:
	pop ebp
	inc ebp
	push ebp
	ret

Dissassembler output 4
? ....... ! main:                           ;xref o80482d7 
? ....... !   call        sub_804839c   
? 8048379 !   call        8048836h  
? 804837e !   add         [ebx+1], bh      
? 8048384 !   mov         ecx, strz_I_am_running__8049568
? 8048389 !   mov         edx, 0eh
? 804838e !   int         80h 
? 8048390 !   mov         eax, 1 
? 8048395 !   mov         ebx, 0
? 804839a !   int         80h 
? 804839c !                       
? ....... ! ;-----------------------     
? ....... ! ;  S U B R O U T I N E   
? ....... ! ;----------------------- 
? ....... ! sub_804839c:                    ;xref c8048374  
? ....... !   pop         ebp     
? 804839d !   inc         ebp     
? 804839e !   push        ebp 
? 804839f !   ret  


Source

2010-02-26 Linux antidebug 2

This is dirty solution it checks programms argv[0] name with your defined namewhen running debuger such as gdb or ald name is chaned to fullpath nameuser defined name from terminal is './main'.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>

int main( int argc , char **argv )
{
	pid_t pid,ppid;
	FILE *f;
	char str[128];
	char spid[10];
	
	//openfile and write ppid
	f = fopen( "pid.txt" , "w" );
	pid = getpid();
	fprintf(f,"%d ",pid);
	fclose( f );
	f = fopen( "pid.txt" , "r" );
	fscanf( f , "%s" , spid );
	fclose( f );
	
	strcpy( str , "cat /proc/" );
	strcat( str , &spid[0] );
	strcat( str , "/cmdline");
	printf( "[%s]\n", spid );
	system( str );
	
	printf("\n");
}
Dirty function that makes dirty solution at one place
int badppid( const char *real_name )
{
	pid_t pid,ppid;
	FILE *f;
	char str[128];
	char spid[10];
		f = fopen( "pid.txt" , "w" );
	pid = getpid();
	fprintf(f,"%d ",pid);
	fclose( f );
	
	
	f = fopen( "pid.txt" , "r" );
	fscanf( f , "%s" , spid );
	fclose( f );
	
	
	strcpy( str , "cat /proc/" );
	strcat( str , &spid[0] );
	strcat( str , "/cmdline > name.txt");
	system( str );
	
	f = fopen( "name.txt" , "r" );
	fscanf( f , "%s" , str );
	fclose( f );
	if ( strncmp(str,real_name,strlen(real_name)) != 0 )
	{
		return -1;
	}
	
	return 0;
}
Source

2010-02-23 Linux antidebug 1

When ptrace is used for programm debugin then only one ptrace can be attached to programmwhen we trying run ptrace with PTRACE_TRACEME then we get  -1. I tested with gdb,ald. Also this method shouldwork with IDApro

#include <stdlib.h>
#include <stdio.h>
#include <sys/ptrace.h>

long int ptraced()
{
	return (ptrace(PTRACE_TRACEME, 0, 0, 0) == -1);
}

int main()
{
	if ( ptraced() )
	{
		printf("Ptraced!\n");
	}
	return 0;
}


Source

2009-10-08 UNIX-programming

Programming sample from various themes.
Basic HTTP server
BIn2Hex converter
Arp Packet Analyzer
Keyboard LED flush
PC speaker
Xlib, hello world

Interesting themes:
Linux Format String Attack
ELF rewrite function
ELF text section
Linux ShellCode 1
Local Descriptor Table
Nano bug (CVS 2010-1160)

Antidebug
Antidebug 1
Antidebug 2
Antidebug 3