Thursday, July 14, 2011

Evince would not start over SSH X-forwarding

Evince, which is the primary PDF and PostScript viewer on Ubuntu, recently stopped working on my Ubuntu/Natty (11.04) over SSH X-forwarding. It works flawlessly inside 'gnome-session'. But, would not run as a regular application (e.g. xpdf or gv) over X-forwarded SSH.

After digging up a little bit, I found a lots of these message in my
dmesg output:

[1305902.871825] type=1400 audit(1310620543.587:75): apparmor="STATUS" operation="profile_remove" name="/usr/bin/evince" pid=20166 comm="apparmor

It was obvious that apparmor [1] was blocking Evince to run outside Gnome session over SSH. A solution to disable the AppArmor block on Evince over SSH connection was suggested here [2]:

#inside the gnome-terminal
sudo ln -s /etc/apparmor.d/usr.bin.evince /etc/apparmor.d/disable
sudo /etc/init.d/apparmor restart


And voila! Now Evince can again be launched over SSH.

[1] http://en.wikipedia.org/wiki/AppArmour
[2] http://ubuntuforums.org/showthread.php?t=1472642

Thursday, January 27, 2011

No need to multi-thread if one dones't have to ...

I like spend time writing, re-writing, reversing and hacking into codes. I consider myself a learner. Regarding multi-threaded codes, I keep a simple belief that almost all of them could be written using a single thread doing effectively the same thing. I realize the world isn't going to change because of what I believe. I wrote the following little piece to demonstrate a friend of mine that a multi-threaded version of one of his little projects which has a functions that blocks and responsible for a few other things (eg. write_db(), on_demand() ) could also have been written using a single-thread. For whatever it is worth, here is my little demo code:


#include < stdio.h >
#include < sys/time.h >
#include < signal.h >
#include < setjmp.h >

typedef void (*sighandler_t) (int);
sigjmp_buf saved_state;

struct data
{
unsigned int count;
unsigned int epoch;
double watt;
} d;

/*
* This value (in seconds) defines how often an
* attempt is made to read the serial port.
*/
unsigned int sleep_time = 10;
unsigned int sleep_start = 0; // in epoch seconds

/*
* Function to write into SQLite/RRD database.
*/
int write_db()
{
printf("[*] write_db()\n");
return 0;
}

/*
* Function to serve on-demand query.
*/
void on_demand()
{
printf("[*] on_demand() :: ");
printf("count %u now %u watt %.2f\n", d.count, d.epoch, d.watt);
fflush(stdout);
siglongjmp(saved_state, 1);
}

/*
* Function to read from serial port.
*/
int blocking_read()
{
struct timeval timeout;

printf("[*] blocking_read() :: ");

/* simulate the read() blocking-time */
timeout.tv_sec = 0;
timeout.tv_usec = 500;

select(0, NULL, NULL, NULL, &timeout);
d.count = d.count + 1;
d.epoch = time(NULL);
d.watt = random();

printf("count %u now %u watt %.2f\n", d.count, d.epoch, d.watt);
fflush(stdout);
return 0;
}

int main()
{
printf("[*] main() -- pid: %u\n\n", getpid());
fflush(stdout);

signal(SIGUSR1, (sighandler_t) on_demand);

while (1)
{
/*
* If we have just came out from a
* signal, perform the pending delay.
*/
sigsetjmp(saved_state, 1);
if ((int)(sleep_start + sleep_time - time(NULL)) > 0) {
printf("[-] pending delay %u secs\n",
(int)(sleep_start + sleep_time - time(NULL)));
fflush(stdout);
sleep((sleep_start + sleep_time) - time(NULL));
}

blocking_read();
write_db();
printf("\n");
fflush(stdout);

/*
* collect serial port data at
* each 'sleep_time' seconds.
*/
sleep_start = time(NULL);
sleep(sleep_time);
}
return 0;
}

Friday, January 14, 2011

Keyboard num-keys not working in VirtualBox Ubuntu guest

The solution that works for me is by disabling 'Mouse Keys'.
  • Go to System > Preferences > Keyboard.
  • In Mouse Keys tab, un-tick 'Pointer can be controlled using keypad'

Thursday, November 25, 2010

Captcha Prompter

  • This tool is written using PyGTK2. It takes an image file name as input, shows the image to the user and asks him to type the text shown in the image. The goal is to use it inside the Unix scripts. For example, one could do 'CAPTCHA_TEXT=$(python prompt_captcha.py captcha.jpg)' in Bash and perform further actions with $CAPTCHA_TEXT. This little tool will accept png, jpg, gif and most other commonimage formats.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
prompts user to solve captcha image.

This tool is written using PyGTK2. It takes an image file name as input, shows the image to the user and asks him to type the text shown in the image. The goal is to use it inside the Unix scripts. For example, one could do 'CAPTCHA_TEXT=$(python prompt_captcha.py captcha.jpg)' in Bash and perform further actions with $CAPTCHA_TEXT. This little tool will accept png, jpg, gif and most other common image formats.

[*] usage: python prompt_captcha.py captcha_image
"""

__author__ =  'Babil (Golam Sarwar)'
__version__=  '0.1'

import sys
import time
import Image
import gtk
import pygtk


pygtk.require('2.0')

class getCaptcha(object):
    """performs all the GTK2 gui actions"""

    def enter_callback(self, widget, textbox):
        """callback funcion for when user presses the enter key"""
 textbox_text = textbox.get_text()
        print textbox_text
 gtk.main_quit()

    def __init__(self, captcha=None):
        #
 if captcha == None:
  print >> sys.stderr, "[*] usage: python prompt_captcha.py captcha_image"
  sys.exit(-1)

 width, height = Image.open(captcha).size
 
 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
 window.set_geometry_hints(window,width+15,height+15,width+30,height+30)
        window.set_size_request(width, height)
 window.resize(width+15, height+15)
        window.set_title("GTK textbox")
        window.connect("delete_event", lambda w,e: gtk.main_quit())
 window.set_title("Enter Captcha")
 window.set_keep_above(True)
 window.set_urgency_hint(True)
 window.move(gtk.gdk.screen_width()/2 - (width+15)/2, gtk.gdk.screen_height()/2 - (height+15)/2)


        vbox = gtk.VBox(False, 0)
        window.add(vbox)

 image = gtk.Image()
 image.set_from_file(captcha)

 button = gtk.Button()
 button.set_image(image)
 button.set_relief(gtk.RELIEF_HALF)
 #button.set_tooltip_text("Type captcha then press enter \n or click the image.")
        vbox.pack_start(button, True, True, 0)

 textbox = gtk.Entry()
        textbox.set_max_length(50)
        textbox.connect("activate", self.enter_callback, textbox)
 textbox.set_text("Enter captcha & then click on the image :-) ")
        textbox.select_region(0, len(textbox.get_text()))
 vbox.pack_start(textbox, True, True, 10)


 button.connect("clicked", self.enter_callback, textbox)
 window.show()
        vbox.show()
 button.show()
 image.show()
 textbox.show()
 textbox.grab_focus()



def main():
    gtk.main()
    return 0

if __name__ == "__main__":
 if len(sys.argv) >=2: 
  getCaptcha(sys.argv[1])
 else: 
  getCaptcha()
 main()

Monday, November 22, 2010

Download Fileserve links from shell

The script assumes, you have
  • ImageMagick
  • Curl
  • Common Unix utilities (eg. sed, awk, cut etc.)
... are installed in the path. The captcha is shown using 'display' component from ImageMagick. You need X forwarding if you are running the script over ssh.


#!/bin/bash
#source /home/babil/Desktop/recaptcha/plowshare-0.9.4/src/lib.sh

PUB_URL='http://www.fileserve.com/file/zXvrJS2'
FILESERVE_RECAPTCHA_PUBKEY='6LdSvrkSAAAAAOIwNj-IY-Q-p90hQrLinRIpZBPi'
IMAGE_VIEWER="display"

CAPTCHA_IMAGE=$(mktemp) #'captcha.jpg'
COOKIE=$(mktemp) #'tmp_cookie.txt'
HTML=$(mktemp) #'tmp_fileserve.htm'

AGENT='Mozilla/5.0 (X11; U; Linux x86_64; en-AU; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.10 (maverick) Firefox/3.6.12'
CUSTOM_HEADERS='-H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" -H "Accept-Language: en-us,en;q=0.5" -H "Accept-Encoding: gzip,deflate" -H "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" -H "Keep-Alive: 115" -H "Connection: keep-alive"'
XML_HTTP_REQUEST='-H "X-Requested-With: XMLHTTPRequested"'

RED='\e[0;31m'
CYAN='\e[0;36m'
NC='\e[0m' # No Color


function regex_replace() {
RE='s/\(\/\|\\\|&\)/\\&/g'
FROM=$(sed -e "$RE" <<< "$1")
TO=$(sed -e "$RE" <<< "$2")
sed -e "s/$FROM/$TO/g"
}

# Delete leading and trailing spaces, tabs, \r, ...
function strip_whiteSpace() {
echo "$1" | sed "s/^[[:space:]]*//; s/[[:space:]]*$//"
}

# Return uppercase string
function uppercase() {
tr '[a-z]' '[A-Z]'
}

function clean_up()
{
rm -f $COOKIE
rm -f $CAPTCHA_IMAGE
rm -f $HTML
}

function find_fileName()
{

if [ -z $FILE_NAME ]
then
FILE_NAME=$(cat $HTML | grep 'Forum (BBCode)' | sed -n 's/.*File name: \(.*\) File size.*/\1/p')
fi

if [ -z $FILE_NAME ]
then
FILE_NAME=$(cat $HTML | grep 'Forum (BBCode)' | sed -n 's/.*url=\(.*\)\]\[b\].*/\1/p')
fi

if [ -z $FILE_NAME ]
then
FILE_NAME=$(cat $HTML | grep 'Website (HTML)' | sed -n 's/.*href=.\(.*\).>.b.File name.*/\1/p')
fi

if [ -z $FILE_NAME ]
then
FILE_NAME=$(cat $HTML | grep 'Text link' | sed -n 's/.*value="\(.*\)".*/\1/p')
fi

FILE_NAME=$(strip_whiteSpace $FILE_NAME)

}

function delay()
{
for((i=$1;i>=1;i--))
do
echo -n "$i "
sleep 1s
done
echo
}

function check_waitTime()
{
WAIT_TIME=$(cat $HTML | sed -n 's/.*You need to wait \(.*\) seconds to start another download.*/\1/p')
if [ -z $WAIT_TIME ]
then
WAIT_TIME=3
fi
WAIT_TIME=$(strip_whiteSpace $WAIT_TIME)
echo $WAIT_TIME
}

function solve_recaptcha()
{
CAPTCHA_URL='http://www.google.com/recaptcha/api/challenge?k='$FILESERVE_RECAPTCHA_PUBKEY
echo -e "$RED [*] captcha url: $NC $CAPTCHA_URL "

CHALLENGE=$(wget -q --referer $PUB_URL "$CAPTCHA_URL" -O - | grep challenge | sed -n "s/.*'\(.*\)',/\1/p")
echo -e "$RED [*] captcha challenge: $NC $CHALLENGE"
wget -q --referer $PUB_URL http://www.google.com/recaptcha/api/image?c=$CHALLENGE -O $CAPTCHA_IMAGE

#convert -trim $CAPTCHA_IMAGE $CAPTCHA_IMAGE
#$IMAGE_VIEWER "$CAPTCHA_IMAGE" &
#pid=$!
#read -p "[*] enter captcha response: " RESPONSE
#RESPONSE=$(echo $RESPONSE | sed 's/ /+/g')
#disown $(kill -9 $pid) 2>&1 1>/dev/null

echo -e -n "$RED [*] captcha input : $NC"
RESPONSE=$(prompt_captcha.py $CAPTCHA_IMAGE | sed 's/ /+/g')
echo "$RESPONSE"

RESULT=$(curl -s --user-agent "$AGENT" --cookie-jar $COOKIE --referer $PUB_URL http://www.fileserve.com/checkReCaptcha.php --data "recaptcha_challenge_field=$CHALLENGE&recaptcha_response_field=$RESPONSE&recaptcha_shortencode_field=$SHORTENCODE")
}


### - 0
if [ -z "$1" ]
then
echo
echo "[*] usage: $(basename $0) $PUB_URL"
echo
exit -1
else
PUB_URL="$(strip_whiteSpace $1 | sed 's#//fileserve.com#//www.fileserve.com#g')"
fi
echo -e "$RED [*] attempting to download: $CYAN $PUB_URL $NC"


### - 1
clean_up

### - 2
SHORTENCODE=$(echo $PUB_URL | sed -n 's/.*file\/\(.*\)/\1/p' | cut -d '/' -f 1)
SHORTENCODE=$(strip_whiteSpace $SHORTENCODE)

### - 3 save cookie
curl -s --user-agent "$AGENT" --cookie-jar $COOKIE --referer $PUB_URL $PUB_URL --data 'checkTimeLimit=check' --output $HTML

### - 4 immitating "slow download".click()
curl -s --user-agent "$AGENT" --cookie $COOKIE --referer $PUB_URL $PUB_URL --data "recaptcha_shortencode_field=$SHORTENCODE" --output $HTML

### - 5
if [ -z "$2" ]
then
FILE_NAME="$(strip_whiteSpace $2)"
else
FILE_NAME=""
fi
find_fileName
if [ -z $FILE_NAME ]
then
echo "[*] can not find file-name, exiting ..."
exit -1
else
echo -e "$RED [*] file-name found: $NC $FILE_NAME"
fi

### - 6 solve captcha
RESULT="(null)"
while [ $RESULT != "success" ]
do
solve_recaptcha
RESULT=$(echo $RESULT | sed -n 's/{.*"\(.*\)".*/\1/p')
done
echo -e "$RED [*] captcha solved :)$NC"

### - 7 free-user delay
WAIT_TIME=$(curl -s --user-agent "$AGENT" --cookie $COOKIE --referer $PUB_URL $PUB_URL --data "downloadLink=wait" --output -)
echo -e "$RED [*] free-user delay: $NC $WAIT_TIME"
WAIT_TIME=$(echo $WAIT_TIME | sed 's/[^0-9]//g' | bc)
delay $WAIT_TIME
$(curl -s --user-agent "$AGENT" --cookie $COOKIE --referer $PUB_URL $PUB_URL --data "downloadLink=show" --output /dev/null)


### - 8 final download ... should give a 302 redirection
echo -e "$RED [*] Starting download ...$NC"
REDIR=$(curl --user-agent "$AGENT" --cookie $COOKIE --referer $PUB_URL $PUB_URL --data "download=normal" --location --location-trusted --output $FILE_NAME --write-out 'REDIRECT-URL:[%{url_effective}]' | sed -n 's/.*:\[\(.*\)\]/\1/p')

if [[ ! "$REDIR" =~ "/dl/" ]]
then
echo -e "$RED [*] incorrect redirection; delay then restart ...$NC"
mv -f $FILE_NAME $HTML
WAIT_TIME=$(check_waitTime)
delay $WAIT_TIME
$0 $PUB_URL
else
echo -e "$RED [*] done :D. $NC"
clean_up
exit
fi