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

Search results for 'files'

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-04-21 Hooking interrupt descriptor table

Hook interrupt descriptor table

Hooking interrupt table is very interesting thing
with it you can dissallow some operations to be made or watch what
happening in system. This article is more like review and more tehnical
description is in link 1

First thing that we should know that it will done trought kernel module
there is 2 commands for loading and unloading modules

insmod

and

rmmod

there is way how we can check system call addresses and position of syscall
table

grep sys_call_table /proc/kallsyms
grep system_call /proc/kallsyms

also we can use it for detecting our module functions and syscall addreses
grep sys_write /proc/kallsyms
or if we whant check out module functions
grep hook_idt /proc/kallsyms
We will now try to hook sys_mkdir. I usualy using some minimalistic windowmanagers but some browsers or other GUIsh programs like such directories "Download" or "Desktop" all my directories in ~/ is lowercase and I realy hate anoying "Download" and "Desktop" directories that are made without my permission and for my lowercase /home directory style is agly. With this hook they will be denied to make such thing. Out kernel module consist of such functions:

static int __init hook_init(void) //stufff on module init,idt hooking
static void __exit hook_exit(void) //stuff on module exit, restore idt table

asmlinkage long hooked_mkdir(const char *filename, mode_t mode) //our hook function

//how works this functions you can find in link number 1 
void *get_writable_sct(void *sct_addr)
void *get_syscall_table(void) 
Basic hooked function is:
asmlinkage long hooked_mkdir(const char *filename, mode_t mode)
{
	return mkdir(filename, mode);
}
but now we need to add check for ("Desktop","Download"). First we need some error that will returned when some one whant to make bad directory we will use EACCES error. here is modified functions for out task:
//hook mkfile command
asmlinkage long hooked_mkdir(const char *filename, mode_t mode)
{
	//it will disallow all files that starts with Desktop&&Download
	if (((strncmp(filename,"Desktop",7) == 0) && (strlen(filename) == 7)) ||
		((strncmp(filename,"Download",8) == 0) && (strlen(filename) == 8)))
	{
		printk(KERN_INFO "Mkdir hook\n");
		return EACCES;
	}
	return real_mkdir(filename, mode);
}
For module compiling: make This is tested with kernel version 2.6.38 Links:
[1] http://codenull.net/articles/kmh_en.html
[2] http://www.gadgetweb.de/linux/40-how-to-hijacking-the-syscall-table-on-latest-26x-kernel-systems.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

2011-02-10 ReprBin - represent binary files in different formats

This is bin2hex style project. It converts binary to other formats. Its purpose is to use with combination with assembler or uC.Code is public and on Evil Google::Code page
Google storage

SVN line: svn checkout http://represent-binary-file.googlecode.com/svn/trunk/ represent-binary-file-read-only

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-10-06 Xlib hello world

First programm with Xlib. Goal was to make something without decorations and as small as possible.Click on it to destroy window.
Source

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-09-07 Robatik

This is programming game where you have to controll your robots with simple assembler like language. Game is inspired by AutoWars.  Source contains source,small turorial and examples.
Robatik Game

2010-08-23 ELF text section

This code based on .text writable

Find out .text section and make it writable.
segmentcheck.h contains two functions

int sec_text_check( FILE* );

check if given file have .text writable section or not. return 0 if  fasle, 1 if true and -1 if there was some kind error.
int sec_text_set( FILE* , int );
set section segment to writable/unwritable depends on second value that canbe 0 or 1.
Code:
Source includes two tests for both functions.I have not tested both functions very whell. That whay there can be some error.I have used used that for proving concept. And have checked result with
test1
and
readelf -l simple
Source

2010-07-26 Snake by wudu

Terminal snake. First project in python by wudu

Author: wudu

Source
Google Code

2010-07-20 Python MIT Binary Trees

After reading chapter form MIT Introduction in algorithms about trees I have implemented same algorithm in pythonI haven't tryed to make best perfomance only easy to understund and one to one like is in pseudo-codeTree python class that are used to represent BinaryTree.

class Tree:
	p = None
	left = None
	right = None
	key = 0
pseudo-code
Inorder_Tree_Walk( x )
if x != NIL
    then Inorder_Tree_Walk( left[x] )
        print key[x]
        Inorder_Tree_Walk( right[x] )
python code

def inorder_tree_walk( t ):
    if t != None:
        inorder_tree_walk( t.left )
        print t.key,
        inorder_tree_walk( t.right )
pseudo code
Tree_Search( x , k )
if x = NIL or k = key[x]
    then return x
if k < key[x]
    then return Tree_Search( left[x] , k )
    else return Tree_Search( right[x] , k )
python code
def tree_search( t , k ):
    if (t == None) or (k == t.key):
        return t
    if k < t.key:
        return tree_search( t.left, k )
    return tree_search( t.right, k )
pseudo code
Tree_Minimum( x )
while left[x] != NIL
    do x <- left[x]
return x
python code
def tree_minimum( t ):
    while t.left != None:
        t = t.left
    return t
pseudo code
Tree_Maximum( x )
while right[x] != NIL
    do x <- right[x]
return x
python code
def tree_maximum( t ):
    while t.right != None:
        t = t.right
    return t
python code
def tree_root( t ):
    while ( t.p != None):
        t = t.p
    return t
pseudo code
Tree_Successor( x )
if right[x] != NIL
    then return Tree_Minimum( right[x] )
y <- p[x]
while y != NIL and x = right[y]
    do  x <- y
        y <- p[y]
return y
python code
def tree_successor( t ):
    if t.right != None:
        return tree_minimum( t.right )
    y = t.p
    while (y != None) and (t == y.right):
        t = y
        y = y.p
    return y
pseudo code
Tree_Insert( T , z )
y <- NIL
x <- root[T]
while x != NIL
    do y <- x
        if key[z] < key[x]
            then x <- left[x]
            else x <- right[x]
p[x] <- y
if y = NIL
    then root[T] <- z
    else if key[z] < key[y]
        then left[y] <- z
        else right[y] <- z
python code
def tree_insert( t , z ):
    y = None
    x = tree_root( t )
    while x != None:
        y = x
        if z.key < x.key:
            x = x.left
        else:
            x = x.right
    z.p = y
    if y == None:
        r = tree_root( t )
        r = z
    else:
        if z.key < y.key:
            y.left = z
        else:
            y.right = z
           
def tree_insert_recrusive( t , z ):
    if t.left == None and t.right == None:
        if z.key < t.key:
            t.left = z
        else:
            t.right = z
        return
    if z.key < t.key:
        tree_insert_recrusive( t.left , z )
    else:
        tree_insert_recrusive( t.right , z )
pseudo code
Tree_Delete( T , z )
if left[z] = NIL or right[z] = NIL
    then y <- z
    else y <- Tree_Successor( z )
if left[y] != NIL
    then x <- left[y]
    else x <- right[y]
if x != NIL
    then p[x] <- p[y]
if p[y] = NIL
    then root[T] <- x
    else if y = left[p[y]]
        then left[p[y]] <- x
        else right[p[y]] <- x
if y != z
    then key[z] <- key[y]
return y
python code
def tree_delete( t , z ):
    if (z.left == None) or (z.right == None):
        y = z
    else:
        y = tree_successor( z )
    if y.left != None:
        x = y.left
    else:
        x = y.right
    if x != None:
        x.p = y.p
    if y.p == None:
        r = tree_root( t )
        r = x
        t = r
    else:
        if y == y.p.left:
            y.p.left = x
        else:
            y.p.right = x
    if y != z:
        z.key = y.key
    return y
Example of usage:Now we can use out tree. There is some more functions like create_tree that creates binary tree from given array. And print_tree that print all ree values.
keys = [10,6,1,0,3,8,7,9,21,15,11,17,25,23,46]
max_deep = log(len(keys),2)

def create_tree( n=0 , p=None):
    if (len(keys) == 0) or (n >= max_deep):
        return None
    t = Tree()
    t.p = p
    t.key = keys.pop(0)
    t.left = create_tree( n+1 , t )
    t.right = create_tree( n+1 , t)
    return t
       
def print_tree( t ):
    if (t != None) and (t.key != None):
        if t.left == t.right == None:
            print "Key:%d "%(t.key)
            return
        if t.left.key == None:
            print "Key:%d Right:%d"%(t.key,t.right.key)
            print_tree( t.right )
            return
        if t.right.key == None:
            print "Key:%d Left:%d"%(t.key,t.left.key)
            print_tree( t.left )
            return
        print "Key:%d Left:%d Right:%d"%(t.key,t.left.key,t.right.key)
        print_tree( t.left )
        print_tree( t.right )


t = create_tree()
r = tree_search( t, 10 )
n = Tree()
n.key = 150
tree_insert_recrusive( t , n )
inorder_tree_walk( t )
print ""
tree_delete( t , r )
inorder_tree_walk( t )
print ""
r = tree_root( t )
print r.key


Source

2010-06-25 PSP sample color filled rectangle

This is sample where is drawn colofilled rectangle. Used functions was taken from
pspsokoban
and
valentine-hbl.
To take screenshot press SELECT
for exit press HOME.
As it very simple to code and easy to see what is inside. It can be firstprogramm that you would try to modify and test on PSP.

Tested:valentine-hbl - R86
firmware - 6.20
model - 3003

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-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

2010-03-16 Python Manage Lynksys Router

Good fellow asked me to write some script that will help him to turn on/off passway to global network. There was used linksys machine for controlling such stuffHere is some code that login, change some rulles and logout. Also pygtk script that doit in visual way

from linksys import *

ls = LinkSys( "http://192.168.1.1/" )
ls.login( "admin" , "admin" )
ls.setip( STATIC_IP , "gateway" , 10 , 66 , 66 , 66 )
ls.setip( STATIC_IP , "subnet" , 255 , 255 , 255 , 0  )
if ls.response():
	print "Succes"
else:
	print "O_O AIam BAd GUy -^-"
ls.logout()
Everything was writen in early 2009. I have tested at that days. Now I don't have linksys machine to test it.
Source

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

2010-01-24 Linux Local Descriptor Table

If 0x80**** adreeses is default nope. You can setup your own. Compiler will not see thembut you can do it. Setup LDT and you will see it.

use32
mov dword [0] ,"Hall"
mov dword [4] ,"Ball"
mov dword [8] ,"Mall"
mov dword [12],0x00000000
yes everything starts from 0x0
#include <stdlib.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <asm/ldt.h>

char new_segment[16];

int main()
{
	int r;
	
	struct user_desc *ldt;
	
	ldt = (struct user_desc*)malloc(sizeof(struct user_desc));
	
	ldt->entry_number = 0;
	ldt->base_addr = ((unsigned long)&new_segment);
	ldt->limit = 16;
	ldt->seg_32bit = 0x1;
	ldt->contents = 0x0;
	ldt->read_exec_only = 0x0;
	ldt->limit_in_pages = 0x0;
	ldt->seg_not_present = 0x0;
	ldt->useable = 0x1;
	
	printf("Start\n");
	r = syscall( __NR_modify_ldt, 1 , ldt , sizeof(struct user_desc) );
	if ( r == -1 )
	{
		printf("Sorry\n");
		exit( 0 );
	}
	asm("pushl %ds");
	asm("movl $0x7, %eax"); /* 0111: 0-Index 1-Using the LDT table 11-RPL of 3 */
	asm("movl %eax, %ds");	
	asm(".byte 0xc7,0x5,0x0,0x0,0x0,0x0,0x48,0x61,0x6c,0x6c,0xc7,0x5,0x4,0x0,0x0,0x0,0x42,0x61,0x6c,0x6c,0xc7,0x5,0x8,0x0,0x0,0x0,0x4d,0x61,0x6c,0x6c,0xc7,0x5,0xc,0x0,0x0,0x0,0x0,0x0,0x0,0x0");
	asm("popl %ds");
	printf("End\n");
	
	printf("Segment [%s]\n",new_segment);
	
	free( ldt );
	
	return 0;
}


asm(".byte ... ") is code.bin

Compile:
fasm code.asm code.bin
gcc main.c -o main

Source

« Previous 123