Userinteraction with Perl

Til today I scripted the user interactions in Perl by my own, but now I’ve learned there is an easier way to interact with the user.

The old way was something like this:

my $input = "";
while ($input ne "yes")
{
    print "say yes: ";
    chomp ($input = <>); 
}
print "thanks\\n";

That does what I want it to do, but if you want more complex operations it’s somewhat difficult to hack it. If you want the user to choose something from a menu or to give you an integer, you have to write lots of code and you have to verify the input by your own. There is a Perl module called IO::Prompt to simplify this ( aptitude install libio-prompt-perl ). For example to get an integer from the user you can use this part of code:

use IO::Prompt;
my $integer = prompt ("give me your integer: ", -integer);

The function prompt will print the string and waits for an input. When the user gives an input it will chomp it and verifies the input by your condition (here it tests whether the input is an integer). If the test fails it prints an error and gives the user a new chance to type a correct value until the conditions are complied. So you can be sure that the returned value is definitely an integer! Of course you can tell prompt to check for more difficult conditions, something like a regular expression. For example to get a hexadecimal value you can use this:

use IO::Prompt;
my $hex = prompt ("give me a hex: ",
			 -req => {"Need a *hexadecimal* value!: " => qr/^[0-9A-F]+$/i}
			 );
print "decimal value: " . hex($hex) . "\\n";

With -req this function expects a hash, it’s entries must match to the input or it will print the corresponding key as error message. As values you can pass functions that should return true if the input is correct, or a regular expression that must pattern match or something like this (see IO::Prompt). Here I’m using a regular expression that matches to hexadecimal input and if the user enters a correct input it’s converted to base 10. An example run might look like this:

/tmp % ./prompt-test.pl
give me a hex: NOHEX
Need a *hexadecimal* value!: w00t
Need a *hexadecimal* value!: A6
decimal value: 166

Even menus are simple to realize. For example:

use IO::Prompt;
my $day = prompt ('Whats your favorite day?',
				-menu =>
				[
					'Monday',
					'Tuesday',
					'Wednesday',
					'Thursday',
					'Friday',
					'Saturday',
					'Sunday'
				]);
print "your choice was: " . $day . "\\n";

If you run this program your menu may look like:

/tmp % ./prompt-test.pl
Whats your favorite day?
     a. Monday
     b. Tuesday
     c. Wednesday
     d. Thursday
     e. Friday
     f. Saturday
     g. Sunday

> f
your choice was: Saturday

The freaks among you will try more complex menus. You are allowed to use hashes in hashes in arrays for your menu and prompt will lead the user through your options. You should know where to find further information about this :P

Show all tags in WP when creating new post

I was annoyed that WordPress by default just shows 45 most used tags on the Add New Post page and found a solution to display all Tags.

After I create a new post in this blog I usually tag it. WordPress provides a very helpful widget that displays the most used tags, but I want to see all tags that I’ve created in the past. Some research through the net doesn’t bring solutions, so I had to walk through the code on my own. Wasn’t very difficult, it was clear that the tags come with Ajax to the site, and I found the code in wordpress/wp-admin/admin-ajax.php on line 616 (WordPress 3.0.1) or wordpress/wp-admin/includes/ajax-actions.php on line 666 (WordPress 3.6, see comments):

$tags = get_terms( $taxonomy, array( 'number' => 45, 'orderby' => 'count', 'order' => 'DESC' ) );

That is what you’ll carry by JavaScript. To get more tags just change this line to something like this:

$tags = get_terms( $taxonomy, array( 'number' => 999, 'orderby' => 'count', 'order' => 'DESC' ) );

You can also edit wordpress/wp-admin/includes/meta-boxes.php , original is:

<p class="hide-if-no-js"><a href="#titlediv" class="tagcloud-link" id="link-<?php echo $tax_name; ?>">< ?php echo $taxonomy->labels->choose_from_most_used; ?></a></p>

If you change it to:

<p class="hide-if-no-js"><a href="#titlediv" class="tagcloud-link" id="link-<?php echo $tax_name; ?>">< ?php echo $taxonomy->labels->all_items; ?></a></p>

the link to get the tags will be called All Tags, not Choose from the most used tags.

I hope this could help some of you. With the next WordPress update these changes will be lost, but you should be able to do it again and maybe I’ll blog about it ;)

Update for WordPress 3.6

You need to edit:

  • wordpress/wp-admin/includes/ajax-actions.php line 666
  • wordpress/wp-admin/includes/meta-boxes.php

(thanks to Gustavo Barreto)

Update for WordPress 3.8.1

You need to edit:

  • wordpress/wp-admin/includes/ajax-actions.php line 691
  • wordpress/wp-admin/includes/meta-boxes.php line 381

(thanks to August for reminder)

Update for WordPress 3.9.1

You need to edit:

  • wordpress/wp-admin/includes/ajax-actions.php line 702
  • wordpress/wp-admin/includes/meta-boxes.php line 410

Update for WordPress 4.1

You need to edit:

  • wordpress/wp-admin/includes/ajax-actions.php line 836
  • wordpress/wp-admin/includes/meta-boxes.php line 431

Increasing anonymity with Tor

Terrified I had to notice, that some of you don’t know Tor!? Here is a little intro, so you don’t have to die stupid.

When you for example request a website, the server that provides this site knows your IP address, with this address it’s able to detect your real location. It also get to know your UserAgent and a lot of other things like that. So the other site of your connection knows quite a lot of you, which system you’re working on, which browser you use, where (which website) do you come from and so on.. But is it essential to let the world know so much about you!? Of course not! By the way, think about the security issue ;)

So what to do!? One option is not to use the internet, only connect to servers you trust. But the better solution is to use Tor! Tor is a software to get anonymous network connection. It works like a big proxy. All around the world are Tor-server. When you try to connect to a webserver you won’t do it directly, but you will connect to a Tor access-node, this node is connecting further nodes, until an exit-node is reached. This exit-node will now send your initial request to the webserver, wait for a response and send this response on a way through the Tor-network back to your machine. The connections between the Tor nodes are encrypted and randomly chosen, so nobody is able to find the way your requests took through the Tor nodes. This process is called onion routing and is much more complicated than I described here, but it’s to much to talk about in detail.

Setting up Tor

The setup is very easy. Just add the Tor repositories to your sources.list:

deb     http://deb.torproject.org/torproject.org DISTRIBUTION main
# for more actual updates (always be careful with experimental) use:
deb     http://deb.torproject.org/torproject.org experimental-DISTRIBUTION main

I for example added the following to my /etc/apt/sources.list.d/3rdparty.list :

# tor
deb     http://deb.torproject.org/torproject.org sid main
deb     http://deb.torproject.org/torproject.org experimental-sid main

After that add the GPG-Key of this repository:

gpg --keyserver keys.gnupg.net --recv 886DDD89
gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | sudo apt-key add -

And install the software:

aptitude update
aptitude install tor tor-geoipdb

If you now start Tor with /etc/init.d/tor start it is listening on 127.0.0.1:9050 . You also need a small proxy like privoxy:

aptitude install privoxy

It’s configuration is very easy, just tell privoxy to send the packages to Tor with the following in /etc/privoxy/config :

forward-socks4a / localhost:9050 .

The rest of this file should be configured correctly.

That’s it! Everything that now reaches your proxy is finding its anonymous way through the Tor-network.

Configuring client software

Now you have to force your software to use the proxy. The most important client software is probably your browser. For example in firefox (or iceweasel) you find the settings in Edit->Preferences->Advanced->Network->Settings and check Manual proxy configuration. Your proxy is 127.0.0.1 (or rather localhost) on port 8118 . Now your more anonymous, just ask a website where you come from. (at the moment I’m using an exit node from Russian Federation and the webserver recognizes me as Windows 7 user with Firefox 3.6 while using a sidux and iceweasel 3.5.11). Here you can verify that you Tor configuration is working. There are also some AddOns for firefox, that makes live easier. For example Torbutton or FoxyProxy. With it you can enable or disable the usage of Tor with a single mouse click.

But Tor is not only designed for browsers. You can configure a lot of software to go through Tor, for example gajim in Edit->Accounts->Your Account->Connection, or in opera with Settings->Preferences->Advanced->Network->Proxy Servers…. Nearly every thing that is able to connect the internet may be able to use your proxy. You can also activate the usage of your proxy by default by including the following line in your .bashrc or .zshrc or what ever:

export HTTP_PROXY=127.0.0.1:8118

Problems and imperfections

You have to know that the encryption between the Tor nodes doesn’t mean your request is fully encrypted. The connection between exit-node and webserver isn’t encrypted by default. This part of your connection is just encrypted if your request is encrypted, for example if you use SSL (https) in your browser. Otherwise the exit-node can read your data. So it is possible that bad people or evil governments may provide untold thousands of exit-nodes, so they can read a lot of traffic of people that want to be anonymous! Another thing you may dislike is the speed. Your traffic is passing a lot of additional nodes, so of course your speed decreases. So you have to balance between anonymity and speed. I think the slow down isn’t that hard, it’s acceptable for me. Choose by your own…

Conclusion

Tor is a very nice project, for further reading you may take a look on the projects website. If you hold a server that is contactable for the public you should think about providing an onion node on it! It’s very easy, but you should know about legal stuff.

Cracked next Captcha

Ok, when Micha saw my tiny hack he changed his implementation (as promised) and told me I’m not able to hack it again… Micha, your captcha failed again :P

Lets have another look to his code:

<p>
	Lösen Sie bitte die folgende Aufgabe (ggf. <em>x</em> bestimmen) <br />

		<img src="http://mathtran.open.ac.uk/cgi-bin/mathtran?D=1;tex=2%5E%7B%202%20%7D" alt="2^{ 2 }" title="2^{ 2 }"/>
	</p>
	<p><input name="captvalue" id="captvalue" value="" size="40" tabindex="4" type="text"/></p>
	<input name="captcha" value="kwCci5YUFw27oJWwxYc6JuuDuvhMd+K95V1TYf3vwJrZqZf2fJCdABUx/4pxMb08kkV/" type="hidden"/>

First of all he renamed the fields, so of course my last attack will fail :P The next problem is, that the hash for a 7 isn’t the hash for another 7 of a different calculation. Maybe he’s using the arithmetic problem or the time or other things for his hash calculation. So if we don’t know how his calculation for the hash is, the last attack is senseless… Btw he told me that he’s using encryption. If you’re bored, try to break it, it’s to much for me. But Micha bets three beer that I’m not able. So no chance to quit!

In my last post I had another idea to crack the captcha: Parse the formula. Ok, I wrote about parsing the URI to the external server that produces the picture, of course it’s much easier to parse the title - or alt -tag of the image! These fields are human readable to get the site handicapped accessible. Of course worthy that he provides this fields! So, after some reloads I had a small idea with what kind of problems I have to deal with:

Simple calculations
something like: , just calculate the solution
Convertings
like , first convert the formula before calculating the solution
Sums
for example , first rewrite the sum-symbol, than calculate the solution

That’s the theory, the code is this time a little bit longer:

// ==UserScript==
// @name           micha-captcha-hack-v2
// @namespace      binfalse
// @description    solve michas captchas without human thinking ;)
// @include        http://0rpheus.net/*
// ==/UserScript==

var capt_field = document.getElementsByName ("captvalue");
if (capt_field)
{
	//search for the image
	var imgs = document.getElementsByTagName ("img");
	var img = 0;
	for (var i = 0; i < imgs.length; i++)
	{
		if (imgs[i].src && imgs[i].src.indexOf ("mathtran.open.ac.uk") >= 0)
		{
			img = imgs[i];
			break;
		}
	}
	
	if (img != 0)
	{
		var problem = img.title;
		// parse simple math operations
		problem = problem.replace (/\\cos\s*0/, " 1 ");
		problem = problem.replace ("\\div", " / ");
		problem = problem.replace ("\\cdot", " * ");
		problem = problem.replace (/\\sin\s*\\frac\s*{\s*\\pi\s*}\s*{\s*2\s*}/, " 1 ");
		problem = problem.replace (/\\frac\s*{(.+?)}{(.+?)}/, "($1) / ($2)");
		problem = problem.replace (/\\sqrt\s*{(.+?)}/, " Math.sqrt ($1) ");
		problem = problem.replace (/([^m ]+)\s*\^\s*{(.+?)}/, " Math.pow ($1, $2) ");
		
		if (problem.indexOf ("=") < 0)
		{
			//simpel problem, just calc..
			capt_field[0].value = eval (problem);
		}
		else if (problem.indexOf ("sum") < 0)
		{
			//converting -> very simple scripted ;)
			var tmp = problem.indexOf ("=");
			var left = problem.substr (0, tmp);
			var right = problem.substr (tmp + 1);
			if (right.indexOf ('x') >= 0)
			{
				tmp = right;
				right = left;
				left = tmp;
			}
			// lhs is x -> convert every other shit to rhs ;)
			
			// kill adds
			var leftpieces = left.split ('+');
			for (var i = 0; i < leftpieces.length; i++)
				if (leftpieces[i].indexOf ('x') < 0)
					right = right + " - " + leftpieces[i];
				else
					left = leftpieces[i];
			
			// kill subs
			var leftpieces = left.split ('-');
			for (var i = 0; i < leftpieces.length; i++)
				if (leftpieces[i].indexOf ('x') < 0)
					right = right + " + " + leftpieces[i];
				else
					left = leftpieces[i];
			
			// kill mults
			var leftpieces = left.split ('*');
			for (var i = 0; i < leftpieces.length; i++)
				if (leftpieces[i].indexOf ('x') < 0)
					right = "(" + right + ") / " + leftpieces[i];
				else
					left = leftpieces[i];
			
			// kill divs
			var leftpieces = left.split ('/');
			for (var i = 0; i < leftpieces.length; i++)
				if (leftpieces[i].indexOf ('x') < 0)
					right = "(" + right + ") * " + leftpieces[i];
				else
					left = leftpieces[i];
			
			capt_field[0] = eval (right);
		}
		else
		{
			//sumproblem
			eval (problem.replace (/^.+sum.+?{(.+?)}.+{(.+?)}(.+)$/, "$2;to=$1;s='$3';"));
			var longprob = "";
			for (var i = n; i < to; i++)
				longprob = longprob + " " + s.replace ('n', i) + " +";
			longprob += 0;
			capt_field[0].value = eval (longprob);
		}
		
	}
	else
	{
		capt_field[0].value = "uuups, no img found!?";
		capt_field[0].style.background = "red";
	}
}

As you can see, it’s a little bit tricky and just works for some mathematical formulas that are of interest. If he combines the converting problem with brackets or something like that, this code fails.. But the algorithm is easy to modify for such changes ;)

But respect, to crack my captcha you don’t need that intelligence, it’s feasible in much less code. I hope he doesn’t rewrite his plugin again, don’t want to calculate that stuff by brain…

Cracked a captcha

Micha just implemented an own Captcha-Plugin for wordpress, I just cracked it some minutes later ;)

This version is deprecated, see Cracked next Captcha…

Micha was annoyed of his previous Captcha-Plugin, neither valid nor beautiful, so he decided to write his own tool for killing bots.

When I saw his new captchas I was wondering wheter he will get further comments. His captchas ask for solution of mathematical problems like or or .. Who the hell wants to calculate that stuff!? Me not! ;)

So I developed a little userscript that solves this problem. When you take a look to the source code of his website you’ll find something like this:

Lösen Sie bitte die folgende Aufgabe (ggf. <em>x</em> bestimmen) <br />

		<img src="http://mathtran.open.ac.uk/cgi-bin/mathtran?D=1;tex=228%20%5Cdiv%2019" alt="228 \div 19" title="228 \div 19"/>
	
	<p><input name="captvalue" id="captvalue" value="" size="40" tabindex="4" type="text"/></p>
	<input name="sercret" value="c9679a3b8ab5151bdf143c43091e59a757cb15ce" type="hidden"/>

So you see, there is an image created by an external server, an input field where you can put the solution and an input field of the type hidden with a crypt value (seems like a hash^^). The most of you will see several ways to hack this:

  1. Parse the string of the image like the external server does to create the -image. So you’ll get an arithmetic problem, easy to solve.
  2. Find out what kind of hash is in the value of the secret hidden input-field and try to find a number that matches that hash, maybe via brute force.
  3. Solve one captcha and fake the rest ;)

Of course the last solution is the easiest one. So I solved on captcha, solution was 7 and the secret key was 9ee4251f80923e6239ae66ab50a357daa6039f04 , hack done!

The development of the userscript was more than simple:

// ==UserScript==
// @name           micha-captcha-hack
// @namespace      binfalse
// @description    solve michas captchas without thinking ;)
// @include        http://0rpheus.net/*
// ==/UserScript==

var hidden_field = document.getElementsByName ("sercret");
var capt_field = document.getElementsByName ("captvalue");
if (hidden_field && capt_field)
{
	capt_field[0].value = 7;
	hidden_field[0].value = '9ee4251f80923e6239ae66ab50a357daa6039f04';
}

I think that this script won’t work for a long time, so there is no download available ;) If you want to use it, copy&paste, you know.

Ähm, before anybody starts to blame me, a similar workaround kills also my captcha-solution… :P

New logo for Iceweasel

Actually iceweasel is searching for a new logo.

When I updated a PC of our work group I recognized that iceweasel, iceape and icedove are searching for new logos. Micha just created one for iceweasel with xfig, here is a similar one with tikz:

\begin{tikzpicture}
\draw (-1,0) circle (1cm);
\draw (-1.2,0.3) circle (0.15cm);
\draw (-0.11,-0.4) -- (1,-1);
\draw (1,-1) -- (3,-1);
\draw (2,-1) -- (2.5,-2);
\draw (2,-1) -- (1.5,-2);
\draw (4,-1) -- (6,-1);
\draw (6,-1) -- (6.5,-2);
\draw (6,-1) -- (5.5,-2);
\draw (6,-1) -- (8,0.5);
\draw (-1.9,-0.4) .. controls +(190:1.8cm) and +(180:1.2cm) .. (-2,0);
\draw (-0.7,0.95) .. controls +(90:0.2cm) and +(60:1.8cm) .. (-1.1, 1);
\draw (-1.5,0.85) .. controls +(60:1.6cm) and +(60:0.2cm) .. (-0.85, 1.4);
\draw (3.5,-3) -- (2.5,1);
\draw (3.5,-3) -- (4.5,1);
\draw (3.5,2.5) circle (1cm);
\filldraw [white, draw=black] (2.8,1.7) circle (1cm);
\filldraw [white, draw=black] (4,1.5) circle (1cm);
\end{tikzpicture}

If the maintainer understand something about art they will use one of our creations! ;)

Tweet-button for website

Yeah, completely in twitter-fever! Just developed a tweet-button.

You can see the button at the end of every post. The button itself of course isn’t my work, I just copied it from twitter, but when you click the link around it you can tweet the actual post directly to twitter! Feel free to try it! ;)

It’s more than easy. All the code you need is (replace […]):

<a href="http://twitter.com/share?url=[URL_TO_THIS_SITE]&amp;lang=[en|de|..]&amp;via=[NAME_OF_YOUR_TWITTER_ACCOUNT_FOR_@_LINK]&amp;text=[TEXT_FOR_TWITTERMSG]" >
      Tweet it <img src="[TWITTER_IMAGE]"/>
</a>

So the code that I wrote in my theme is:

if ( is_singular() )
{
	$tweet = '<span id="tweetit"><a href="http://twitter.com/share?url=https%3A%2F%2F'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].'&amp;lang=en&amp;via=binfalse&amp;text='.the_title('', '', false).'" >
	<span id="tweetittext">Tweet it</span>
	<img src="/wp-content/uploads/2010/08/btn_tweet_mini.png"/>
	</a></span>';
	$tweet .= "<br />";
}

After that just using the $tweet variable at any position I like ;)

Here you can find a documentation.

Journey to Usedom

The last two weeks I took a time out. The first week I visited my sister living on Usedom, Rumpel came with me.

Those of you who are following me on Twitter may have noticed the one or other story, it was one of the best trips I made! Very funny and of course much too short ;)

We cycled a lot of km’s, climbed on trees, swum in the Baltic Sea, took sunbathes on the beach, went to Poland and so on. Detailed reports would blow up the framework of this website, but I’ll provide some pictures at Picasa, here is also a YouTube video from Poland.

And I’ve prepared a funny animated gif of an interesting evening ;)

So, if you ever have the chance to go to Usedom: Do it!!

Usedom - Aug 2010
Usedom - Aug 2010

Entering next level: Wordpress 3.0.1

The yellow bar on the top of the administration panel was very annoying, so I just decided to update the Software.

Nothing special happened, please tell me if anything seems to be wrong!

Btw. I installed another plugin that tweets news from this blog. Let’s see if it works.

Expiration dates of hash functions!?

Just read the so called Algorithmencatalog (maybe Algorithms Catalog in English!?), published by our German Bundesnetzagentur. They seem to know exact expiration dates for hash functions ;)

In this PDF file I found the following table (see original screen-shot):

* i.e. for creation of qualified certs, not for creation or verification of other qualified signed data. ** i.e. for creation of qualified certs with at least 20 bit entropy in its serial number, not for creation or verification of other qualified signed data. *** exclusively for verification of qualified certs
Creation of qualified certs*: suitable til end of 2009 Creation of qualified certs**: suitable til end of 2010 suitable til end of 2010 suitable til end of 2015 suitable til end of 2016
SHA-1 SHA-1 RIPEMD-160 SHA-224 (SHA-1, RIPEMD-160)*** SHA-256, SHA-384, SHA-512

So I hope there is anybody out there that has started to crack SHA-1 to get finished this year :P

(maybe it’s the recounter’s turn!?^^)