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

Search results for 'mit'

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.

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

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.