Wednesday 30 October 2013

The Dark Mod

Having seen the announcement The Dark Mod version 2.0 is completely standalone and was inspired by the Thief series of games which I enjoyed playing (and I am looking forward to the new one that is coming out soon), I decided to give it a try.

There were a few issues to getting it up and running.

Following the instructions I downloaded the updater and set it running, which downloaded all the needed files. However, when I tried to run it, it kept crashing out.
I had hoped this was just due to it being a 32bit binary and I was running it on 64bit. I installed additional 32bit libraries (and their dependencies) that were missing libboost-filesystem, DevIL, mesa-dri-drivers.

This got me a little further, I got a blank screen and could hear music and sound effects. When looking at a copy of the startup messages (passed to tee and dumped to a file), I saw messages relating to not being able to load various font and image files (including ones related to the menu), hence the black screen. I double checked that there were no addition files by re-running the updater, everything was downloaded.
Checking the startup messages and checking the forum, quickly lead me to this page which appeared to have exactly the same symptoms and was suggesting that this was related to S3TC (S3 Texture Compression) support.
There was a suggestion that disabling this in the config might work, however this did not work for me.
Was I missing the 32bit library that contained this support? I was, however as I was testing this on Fedora, Fedora does not ship this particular library as it is patented by S3. I could have gone and downloaded this from a 3rd party repo, but I am not happy at installing lots of extra packages from random locations.
Luckily I came across another solution when using mesa drivers >  version 9 and this is to set the following variable before launching thedarkmod
force_s3tc_enable=true
This worked fine and allowed me to launch the game and start playing through the training mission.


Tuesday 29 October 2013

zenity

I have been messing round with zenity to pop up dialog boxes.

One particular script was to remind me to take a break every so often, when it popped up a dialog box it has a random fortune in it. This was fairly easy to get going but there were a couple of strange behaviours in zenity that I had to figure out.

First one was random sizes of dialog box. When using the --info selection of dialog box often the windows it created were off the screen, even with small amounts of text.
This seems to be due to zenity wrapping the text with a fixed width as mentioned in a number of bug postings, so to solve this I used the  --no-wrap option.

Second one is a little more random. I had occasionally noticed my dialog boxes containing the text "All updates are complete", originally I thought that maybe this was a random fortune, however none of the fortune files contains this string.
Doing some further digging, I found out that this is the default message (mentioned here) and that zenity is trying to handle Pango markup and that I should make sure that any of the following characters "&\<>" are escaped prior to passing in.
In later versions of zenity (including the version I am using) there is an undocumented option --no-markup. This now works however I cannot pass "\n" to be interpreted as a new line. Therefore I can either, use this option and explicitly put a line break in the output I want, or pass the output of fortune through sed first and not worry about the no markup option.
The invocation of sed is
sed -e 's/\\/\\\\/g' -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g

There was another issue I came across.
When zenity generates a dialog box it will try to place it above the window where it was launched from, it does this by getting the environment variable $WINDOWID, to prevent this unset this variable in the script before calling zenity.




Tuesday 15 October 2013

Sending key presses to specific windows in X

For a project I wanted to send key presses to a specific X Window, so I dug out my code from "Moving mouse and pressing keys in X using python" and made some modifications.
I also included the code I wrote in "screenshots using Python under Linux" for finding a particular window id from its name.


As an example the following code takes a window name as an argument to the program when run, finds the window id and then sends the key press of F11 (the window I wanted to interact with was a browser window and therefore it will go fullscreen).

#!/usr/bin/python
"""
Issue a keypress event in X to a specific window
"""
from Xlib import XK, display, ext, X, protocol
import sys
import time

def get_window(display, name):
    root_win = display.screen().root
    window_list = [root_win]

    while len(window_list) != 0:
        win = window_list.pop(0)
        if win.get_wm_name() == name:
           return win.id
        children = win.query_tree().children
        if children != None:
            window_list += children

    print 'Unable to find window matching - %s\n' % name
    sys.exit(1)


d=display.Display()

win=get_window(d,sys.argv[1])

keysym=XK.string_to_keysym("F11")
keycode=d.keysym_to_keycode(keysym)

event = protocol.event.KeyPress(
   time = int(time.time()),
   root = d.screen().root,
   window = win,
   same_screen = 0, child = X.NONE,
   root_x = 0, root_y = 0, event_x = 0, event_y = 0,
   state = 0,
   detail = keycode
)
d.send_event(win, event, propagate=True)
d.sync()
event = protocol.event.KeyRelease(
   time = int(time.time()),
   root = d.screen().root,
   window = win,
   same_screen = 0, child = X.NONE,
   root_x = 0, root_y = 0, event_x = 0, event_y = 0,
   state = 0,
   detail = keycode
)
d.send_event(win, event, propagate=True)
d.sync()

While this seemed to work (my Firefox browser window went into fullscreen mode), I did start to see some strange behaviour, such as none of the menus would display either from the toolbar or right clicking in the window. I did notice that clicking on a menu did very briefly flash up what looked like an outline, so I wondered if this could have anything to do with focus and modified my code like so.

#!/usr/bin/python
"""
Issue a keypress event in X to a specific window
"""
from Xlib import XK, display, ext, X, protocol
import sys
import time

def get_window(display, name):
root_win = display.screen().root
window_list = [root_win]

while len(window_list) != 0:
win = window_list.pop(0)
#print win.get_wm_name()
if win.get_wm_name() == name:
return win.id
children = win.query_tree().children
if children != None:
window_list += children

print 'Unable to find window matching - %s\n' % name
sys.exit(1)

d=display.Display()

win=get_window(d,sys.argv[1])

keysym=XK.string_to_keysym("F11")
keycode=d.keysym_to_keycode(keysym)

#store current input focus
currentfocus=d.get_input_focus()

#set input focus to selected window
d.set_input_focus(win, X.RevertToParent,X.CurrentTime)

#send keypress and keyrelease
ext.xtest.fake_input(d, X.KeyPress, keycode)
ext.xtest.fake_input(d, X.KeyRelease, keycode)

#revert focus to original window
d.set_input_focus(currentfocus.focus,X.RevertToParent,X.CurrentTime)

d.sync()
d.close()

This seems to work much better and Firefox still works correctly.

Wednesday 9 October 2013

vim substitution tricks

I wanted to figure out a way to add an incrementing number before a certain character on each line for a program I was writing.
In vim this is fairly simple to achieve.

Here is a sample of some lines in my file
number=1234
number=4543
number=7978
number=3321

Now I want to add an incrementing number before the "=" so I have some unique variables. I can either select the lines I want in vim using the visual selection (shift-v) or I can put an address specification.
For this example I used the visual selection so I get and address specified as '<,'>

Now I supply the ex command
:let i=1 | '<,'>s/=/\=i."="/ | let i+=1

This will now give me
number1=1234
number2=4543
number3=7978
number4=3321

This seemed to work the same as the following command but less typing
:let i=1 | '<,>'g/=/s//\=i."="/ | let i+=1

However if I wish to change the increment I have to use the long command, e.g. to go up in steps of two, change the ex command to
:let i=1 | '<,>'g/=/s//\=i."="/ | let i+=2

Which now gives me
number1=1234
number3=4543
number5=7978
number7=3321

The string to replace in the search and replace pattern above starts with "\=" indicating that this is the start of an expression, subsequent strings are concatenated with ".".

Tuesday 8 October 2013

python and numbers 08 and 09

I had noticed that the syntax highlighting in vim did not seem to pick up the numbers 08 and 09 in some code I was writing. However, it was only when running some code containing these numbers that I appreciated what was happening.

If numbers have been represented with a leading 0 then these are interpreted as octal numbers and therefore each digit after can only go up to 7, therefore 08 and 09 are invalid.

This can be seen if you try to run the following code
number = 08
print number

You get an error similar to
  File "number", line 4
    number=08
            ^
SyntaxError: invalid token

Random Programming challenges

I have found some interesting websites that set interesting problems to challenge your programming skills and as I have been messing round more with python I have decided to have a go at some of them using python.

A particularly interesting one is Project Euler where I have just achieved the award Decathlete for solving the first ten problems. I suspect the rest will be much harder.

Another challenging set of problems is at http://escape.alf.nu/ this guides you through some common pitfalls in javascript programming. The aim is to get the sample code to call alert(1).

Thursday 3 October 2013

Rookie mistake python loops and variable scope

While writing some simple python code I stumbled upon a rookie mistake which I appear to still be making so writing it down here to remind me.

Scope of variables is important in loops especially when using them to increment.

I was writing some code to work out if the product of two 3 digit numbers is a palindrome (not very elegant algorithm just brute forces it). Here is my original algorithm

a=100
b=100

numbers=[]

while a < 1000:
  while b < 1000:
    product=a*b
    print a, b, product
    if (product == int(str(product)[::-1])):
        print "palindrome"
        numbers.append(product)
    b+=1
  a+=1

From the output I noticed something strange the outer loop only went round once even though I thought I had incremented a after the inner loop.

Then it struck me I had defined b outside my while loop so it would not get reset upon next iteration of the outer loop and therefore the inner loop would not run again (and print something out). Therefore it looked like I was only looping once on the outer loop.
This could be proven by adding "print a" before incrementing a on the last line.

Moving "b=100" inside the outer loop solves the problem.

Working code looks like so
a=100
numbers=[]
while a < 1000:
  b=100
  while b < 1000:
    product=a*b
    print a, b, product
    if (product == int(str(product)[::-1])):
        print "palindrome"
        numbers.append(product)
    b+=1
  a+=1

Another alternative is to change the while loops to for loops.



Wednesday 2 October 2013

Easter egg in gnome-shell

I have just found and easter egg in gnome-shell.

In gnome, move the cursor up to the top left corner as if you were going to open an application, then in the search box type "free the fish"

Wanda








Clicking on the icon or hitting return will bring up a dialog box containing a random fortune.

Drag and Drop in a webpage

I saw a cool feature on a website allowing you to drag and drop a file onto the page and it will be uploaded.

I wondered how this was done and after some experimentation I believe I understand how to do this. I should note that I was working with firefox on Linux and I have not tested this code in other browsers on other platforms.

I created a simple blank html page with a line explaining to drag and drop a file onto the page.

Then a little javascript to handle the dragging and dropping a file.

In my script I need to get the whole document (or the body element) which can be done with
document.documentElement

Then I need to add some event listeners to this to listen for the drag and drop events (in particular the "drop" event). I created some functions to be called when these events are triggered.
To prove a file has been dropped all I did was popup an alert with the name of the file dragged and dropped.
My test code only handled the first file dropped, but it should not be too difficult to add a loop to process the rest.

So my basic javascript would look like this
function noop(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
}

var drop = document.documentElement;

drop.addEventListener("dragover", noop, false);
drop.addEventListener("dragexit", noop, false);
drop.addEventListener("drop", function(e) {
     e.stopPropagation();
     e.preventDefault();
     //only get the first file, add loop for multiple file handling
     var files = e.dataTransfer.files;
     var file = files[0];
     alert("file '"+file.name+"' dragged and dropped");
     return false;
},false);

This was not successful and kept giving me an error in firefox, this was probably due to trying to do things before the document was ready. Therefore I used jQuery to ensure the document was ready, now my code was wrapped like so

$(document).ready(function() {
...
});

However, this still did not seem to be working. I found some old bugs which suggested that firefox had problems with drag and drop from anything other than nautilus, but I was using nautilus so it should work.
Then it struck me I was dragging items from the recent files window in nautilus, could these be references to the files? I opened the actual directory where the test files were and drag and drop worked perfectly.

I did not do anything with the file dropped, but is should not be difficult to add upload code to pass to a server side script for processing.

Tuesday 1 October 2013

Reversing Shellcode

I was looking at some shellcode and there are lots of articles on how to compose shellcode but not that many on how to get it back to assembly for analysis.

The easiest way appears to be to dump the shellcode to a file,  this can be done with a perl one liner e.g.

 perl -e 'print "\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e"' > shellcode

 Then using ndisasm from nasm to convert this shellcode back to assembly mnemonics. The shellcode I was looking at was for 32bit architecture therefore I can use the following

ndisasm -b 32 shellcode

Which gives me
00000000  682F2F7368        push dword 0x68732f2f
00000005  682F62696E        push dword 0x6e69622f


It should be noted that this is a nonsense example as the shellcode only pushes "/bin//sh" onto the stack and does not do anything with it, however it shows how to use the tools.