Archive for the ‘Linux’ Category

RabbitEdit

Saturday, October 4th, 2008

RabbitEdit is a nifty tool that allows easier Rabbit development and saves you quite some time and effort.
Its purpose is to automatically do particular common things for you, like writing pieces of code, creating parent directories for your new source files, and add the newly created files (and directories) in the SVN repository.
It can be found in rabbit/etc/rabbitedit/ and its installation is as simple as:

# make install 

You can uninstall it similarly, running:

# make uninstall 

Its configuration file can be found at /etc/rabbitedit/rabbitedit.conf and follows the common configuration rules used by the most programs.
You can see how it works, by issuing:

$ rabbitedit --help

A simple example of its usage, could be the following:

$ rabbitedit --parents --svn libs/customer/settings.php

Let’s assume you are in the root directory of your rabbit project. By running the above, RabbitEdit creates libs/customer/ if it does not exist (this is indicated by the “–parents” option), adds that directory to the SVN repository (indicated by “–svn”) as well as libs/customer/settings.php, and if settings.php did not exist before, it creates it and writes a standard piece of code in it (having the information that the file is a lib, and is about the settings of customers). If the file existed before, it leaves it as it was. Then, it opens the file with the source code editor of your choice.

RabbitEdit is written in Python, and is designed with the hope it fastens up the development of Rabbit projects and gives developers the chance to avoid drudgery, and focus on really important things, like actually coding.

“echo” and “md5sum”

Saturday, October 4th, 2008

A problem I faced when I attempted to manually set a password for my user in Water, was that I could not login. I created the md5 sum of my password, running:

$ echo mypassword|md5sum

and pasted it into the MySQL field of phpMyAdmin. After many login failures and enough searching about what is to blame, Kostis90gr found out that “echo”, is outputting a newline at the end of the string, so the md5 sum produced from the command above, was different than the one produced from PHP’s md5() function, simply because they were given different input. So, the right thing to do, is to pass “echo” the “-n” option, like:

$ echo -n mypassword|md5sum

which prevents “echo” from outputting a newline at the end of the string.
I hope this post is helpful, because my unawareness of this “echo”’s little “particularity”, caused me quite enough frustration.

Overloading in PHP must use public methods

Friday, July 25th, 2008

The magically overloading methods in PHP, such as __get, and __set must be public according to The PHP Manual.

Aleksis recently pointed that out to me by making his new methods public, which gave me the initiative to look it up at the manual.

I thought this script to convert them might end up being useful to others, too:

for i in `find -iname "*.php"
               |xargs egrep -i "(private|protected) function __(get|set)"
               |awk -F: '{print $1}'`
do 
sed 's/\(private\|protected\) function __\(get\|set\)/public function __\2/' $i >$i.processed;
mv $i.processed $i
done

Change collation on all columns of a database

Sunday, May 25th, 2008

It was recently required for me to change the collation of each and every column of every table in a database from ‘latin1′ to ‘utf8′. Although the table collations were correct, the column collations were incorrect. It’s a cumbersome process to perform manually, and there’s apparently no real automated way to do it without a script. Although collation information is only meta-data, not actual data, I found this problem interesting.

Changing one column collation information is easy enough to do with one MySQL query:

ALTER TABLE `moods` 
CHANGE `mood_label` `mood_label` text CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Changing all the columns is more difficult. Here’s a small script that I came up with to do it recently:

dionyziz@orion:~$ mysqldump -u root --password=1234 \ 
--no-data --no-create-db --compact ccbeta \
|egrep 'CREATE TABLE|latin1' \
|sed 's/CREATE TABLE `\(.*\)` (/;ALTER TABLE `\1`/' \
|sed 's/character set latin1/CHARACTER SET utf8 COLLATE utf8_unicode_ci/' \
|sed 's/  `\(.*\)`/ CHANGE `\1` `\1`/'>columns
dionyziz@orion:~$ php -r 'file_put_contents( "columns", 
    preg_replace( "#^;|ALTER TABLE `.*`(\\s*;|$)#", "", 
    preg_replace( "#,(\\s*);#", ";\\1", 
    file_get_contents( "columns" ) ) ) );'
dionyziz@orion:~$ mysql -u root --password=1234 ccbeta <columns

Let’s go through it step-by-step.

mysqldump -u root --password=1234 --no-data --no-create-db --compact ccbeta

This creates a list of CREATE TABLE statements for all our tables. That’s good because it’ll allow us to determine whether the collation of a column is incorrect. Here’s an example CREATE TABLE statement:

CREATE TABLE `albums` (
  `album_id` int(11) NOT NULL auto_increment,
  `album_userid` int(11) NOT NULL default '0',
  `album_created` datetime NOT NULL default '0000-00-00 00:00:00',
  `album_name` text character set latin1 NOT NULL,
  `album_description` text character set latin1 NOT NULL,
  PRIMARY KEY  (`album_id`),
  KEY `album_userid` (`album_userid` )
) ENGINE=MyISAM AUTO_INCREMENT=55 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

In this example, the `album_name` and `album_description` columns are wrong and need their collations changed.

egrep 'CREATE TABLE|latin1'

This simple line limits our results to only lines that contain “CREATE TABLE” or “latin1″. That’s useful since it’ll only show the table names followed by a list of all incorrectly collated columns, if any. The result would be something like this:

CREATE TABLE `relations` (
CREATE TABLE `searches` (
 `search_query` text character set latin1 NOT NULL,
CREATE TABLE `shoutbox` (
 `shout_text` text character set latin1 NOT NULL,
 `shout_delreason` text character set latin1 NOT NULL,

(with more entries potentially)

Good. Now all we need to do is modify these lines to make them ALTER TABLE lines:

sed 's/CREATE TABLE `\(.*\)` (/;ALTER TABLE `\1`/'

Ah, the magic of regular expressions. This removes the final “(” of every CREATE TABLE line, as we don’t need it and also changes the word “CREATE” into “ALTER”. It also adds a semicolon in front of the ALTER TABLE statement (to terminate the previous statement).

sed 's/character set latin1/CHARACTER SET utf8 COLLATE utf8_unicode_ci/'

Straightforward enough, this replaces the existing character set instruction from latin1 to utf8, and adds the correct collation as well.

sed 's/  `\(.*\)`/ CHANGE `\1` `\1`/'

Finally, this adds the word “CHANGE” in front of every column line and repeats the column name (as we want to tell MySQL which column to change (first repetition) and to which to change it (second repetition)). The result is:

;ALTER TABLE `relations`
;ALTER TABLE `searches`
 CHANGE `search_query` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
;ALTER TABLE `shoutbox`
 CHANGE `shout_text` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 CHANGE `shout_delreason` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

Pretty close to what we actually want. You’ll notice three problems:

  • There are empty ALTER statements
  • There’s an extra comma at the end of every column (providing all your tables have a primary key, as they should)
  • There’s a redundant semicolon at the beginning

These problems cannot easily be fixed by sed because sed performs a line-to-line processing. A sed expert might have been able to provide us with a better solution, but I’ll prefer to use the PREG feature of PHP. To use PHP, first let’s save our current result into a file:

>columns

Time to run our PHP code on the target file:

php -r 'file_put_contents( "columns", 
    preg_replace( "#^;|ALTER TABLE `.*`(\\s*;|$)#", "", 
    preg_replace( "#,(\\s*);#", ";\\1", 
    file_get_contents( "columns" ) ) ) );'

Let’s analyze it in short.

file_get_contents( "columns" );

This, simply enough, reads the “columns” file into memory. Now we’ll perform two regular expression replacements:

First, we’ll match the following regular expression:

#,(\s*);# 

(notice that the # are separators that wrap the regular expression for clarity — they aren’t part of the actual regular expression)

Anything matching this will be replaced by ;\1. This means that a comma followed by any whitespace (including a new line) followed by a semicolon will be replaced by only a semicolon (and the same whitespace). This simply removes the redundant comma at the end of every ALTER statement.

Second, we’ll match the following:

#^;|ALTER TABLE `.*`(\\s*;|$)# 

Anything matching will be removed. You’ll notice that this regular expression matches basically two things (separated by the first alternation (pipe) character).

The first part is:

#^;# 

It’ll remove the first line if it only contains a single semicolon (which it does in our example).

The second part is:

#ALTER TABLE `.*`(\\s*;|$)# 

This will look for empty ALTER TABLE statements (an ALTER TABLE statement followed only by whitespace and a semicolon or an end-of-file) and remove them.

Finally, we’ll write the result back to the file we read from:

file_put_contents( "columns", ... );

Now if we cat that file we’ll see that it contains all ALTER statements in the form we want them:

ALTER TABLE `searches`
 CHANGE `search_query` `search_query` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `shoutbox`
 CHANGE `shout_text` `shout_text` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 CHANGE `shout_delreason` `shout_delreason` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;

Excellent. Finally, let’s execute it:

mysql -u root --password=1234 ccbeta <columns

You can also add ‘time’ in front of it to measure how long it’ll take. We can now validate that the collations were changed successfully by, again, performing our initial dump and grepping for ‘latin1′ to confirm that there are none.

Accessing MySQL using a SSH-Tunnel

Wednesday, May 21st, 2008

Due to security aspects MySQL server often only listen on localhost and accessing them remotely is not possible. With a simple trick you can access them with your favourite tool aswell.

ssh -l login_name -N -L [bind_address:]port:host:hostport remoteServer

login_name is your username on the remote machine
bind_address is the local interface’s address where the tunnel should bind to
port is the local port the tunnel should bind to
host is the remote host to which you want to connect
hostport is the remote port to which you want to connect
remoteServer is the server using which you want to etablish the tunnel
-N should disable starting the login shell

So for creating a tunnel for MySQL the command looks like this:

ssh -l user-remote -N -L 123456:localhost:3306 remoteServer

This create a tunnel to MySQL running on remoteServer. You are able to access MySQL on port 123456 on localhost. For example you can use the following command:

mysql --port=123456 -h 127.0.0.1 --user=mysqlUser --password=mysqlPassword database

How to change your standard editor

Sunday, April 13th, 2008

Everyone who is using linux knows that if you type editor in a bash shell an editor opens. But where can you change that editor?

Change the editor temporarily

Just execute the following on your shell:

export EDITOR=joe

Change the editor forever

Edit ~/.bash_profile and add the following:

export EDITOR=joe

Fighting against DDoS

Wednesday, March 12th, 2008

The last week we had some downtimes due to a distributed denial-of-service attack. I’m not sure if it was directly related to our Kamibu projects because there is a bug in the current lighttpd version. An attack can cause a bufferoverflow of Lighttpd with a DDoS. So at all someone tried to get our sites down.

Our solution is very easy. We created a little script fetching all connections by using netstat, counting the number of connections per IP and if there are more than x connections from a certain IP it will add the IP to our firewall. Very simple but helpfull. We execute the script periodically to stop a possible DDoS.

KDE 4 Installation Guide for Gentoo

Tuesday, January 15th, 2008

KDE 4 was released a few days ago. However, Gentoo developers have no yet included KDE 4 ebuilds to the portage tree, and thus Gentoo users have to install it by hand.

The instructions here can be followed by users of other Linux distributions too, but for example Debian users may use apt-get, which is much less error-prone.

Actually, I am going to describe the way I installed KDE 4 to my own PC, and I cannot guarantee that this is going to work for you too. You have to be sure about what you are doing, as I don’t want to be blamed if someone’s computer is harmed in any way!

What you ‘ll need
* latest version of Qt (emerge -av qt)
* latest version of cmake (emerge -av cmake)
* I had KDE 3.5 installed, but I’m not sure if you actually need it
* Strigi strigi.sourceforge.net
* Soprano framework soprano.sourceforge.net
* QImageBlitz library http://sourceforge.net/projects/qimageblitz

Start the fun!

First of all, create a folder where you will build kde4. e.g.:

mkdir ~/kde4
cd ~/kde4

Now, download all the needed files from kde.org. You can use a bash script invoking the wget command:

#!/bin/bash
 
SERVER='http://files.kde.org/stable/4.0.0/src/'
#add any other package you like
FILES=( kdelibs kdepimlibs kdebase kdebase-runtime kdebase-workspace kdebindings kdesdk kdeutils ) 
NAME_END='-4.0.0.tar.bz2'
 
for file in ${FILES[@]} 
do
    wget $SERVER$file$NAME_END &> /dev/null
    echo "Done downloading $file";
done
 
echo "Done."

write this to a file and execute it:

vi download.sh # (paste the code here)
chmod u+x download.sh
./download.sh

…or you could download them from http://www.kde.org/info/4.0.php

I’ve included only the packages that I believe to be necessary. For a complete list enter the kde download site.

Building the packages!

Now, for every package you ‘ve downloaded, you ‘ll have to do the following: (e.g. for kdelibs)

1. Decompress the .tar.bz2 file

tar -xvjf kdelibs-4.0.0.tar.bz2

2. Make a new directory where you ”ll build the package

mkdir kdelibs-build

3. Enter the directory and create the MakeFile for the package (via the cmake command):

cd kdelibs-build
cmake ../kdelibs-4.0.0

4. Build and install the package

sudo make
sudo make install
cd ../

You could actually create a nice little script to do this for the package of your choice: pkginstall.sh

#!/bin/bash
 
PACKAGE=$1;
 
tar -xvjf $PACKAGE-4.0.0.tar.bz2
mkdir $PACKAGE-build
cd $PACKAGE-build
cmake ../$PACKAGE-4.0.0
sudo make
sudo make install
cd ../

And now for e.g. kdeutils:

./pkginstall.sh kdeutils

but I think it would be better to write every command on its own, as you may encounter various errors.

The packages are recommended to be installed in this order:
* kdelibs
* kdepimlibs
* kdebase
* kdebase-runtime
* kdebase-workspace
* kdebindings
* kdesdk
* kdeutils

and any other package after these.

Try it out!

By now, you should have build KDE 4.
To try it, execute this script: kde4.sh:

#!/bin/bash
X -ac :1 & export DISPLAY=:1
exec startkde

The first line creates a new X display - e.g. I have X on tty7, and a new X display starts on tty8
and the second starts the KDE.

If everything is ok, you are ready to use KDE 4!

Troubleshooting

First of all, the previous script for testing KDE 4, didn’t work on my PC. KDE 4 loaded OK, but just after it loaded, KDE 3 started on top of it! I had to write my own “startkde”, and thankfully it was easier than I thought: kde4.sh:

#!/bin/bash
X -ac :1 & export DISPLAY=:1
plasma
exec kwin
dolphin

Instead of calling startkde, which doesn’t work as it should, we manually start plasma (the KDE desktop), kwin (the window manager for KDE) and the dolphin file manager.

And now, KDE 4 started, but it was very KDE 3-ish. I had to go to Computer -> System Settings on the main menu, and set all options on “Appearance” from “Plastique” to “Oxygen”, the default for KDE 4 (e.g. theme).

During building KDE 4 I got errors like: Package “X” missing, so I had to install that package. Don’t hesitate, and just do it.
You’ll probably don’t face such a problem if you follow my instructions at “What you ‘ll need”.

Also, I got some errors during compiling (kdebase-4.0.0 I think), and I had to change some files. Specifically:
I got an error in two files, that QWidget::SetAccessibleName was not defined, so I had to comment out one line from them. That didn’t produce any problems, but I don’t think that it is the best solution.

I hope you won’t have any other problems. If you have any, just post a comment!

In The End

Here we come to the end of this guide, I hope you had fun!

Happy KDE 4 for everyone! :D

UPDATE: Added description of what each line of the bash scripts does.
UPDATE 2: KDE 4 ebuilds have been added to the portage tree, but they are masked on profile.mask and under ~x86 because they are unstable (and they are absolutely right).

BASH coolness by dionyziz + kostis90gr

Sunday, December 16th, 2007

As dionyziz said below,Zino is our new name. To do that conversion, though, some hacks were needed.Mostly stuff like that:

for i in $( find -iname "*.js" ! -path "*svn*" ); do
    sed -e 's/static.chit-chat.gr/static.zino.gr/g' $i > $i-temp;
    mv -f $i-temp $i;
done

DoS by mistake?

Monday, October 22nd, 2007

It’s well known that people try to brute force SSH servers using dictionary attacks to try to guess username and password combinations. The ssh daemon does not disclose the fact that password logins are disabled and root logins are disabled most of the time, and that only simple users can login, and those only using a public/private rsa key pair. We do that, it works fine, it’s good, and secure. But we still get brute force attacks.

One of them happened yesterday. The first thing we noticed was that one of our servers was down! I tried logging in to look into what’s going on, and I couldn’t see anything weird. Everything was in perfect shape. And although Apache was running, HTTP connections timed out. I restarted Apache. No luck.

Then I noticed the netstat log:

netstat.png

That’s the count of active TCP/IP connections every second, during the last few hours. Interesting that at some point it grows to a few hundred. This server doesn’t get that big of a load, so we weren’t expected to handle that. And it worked as a DoS.

But what was going on? Nothing in Apache access logs, or error logs…

Apparently, it was yet another SSH dictionary attack. Christian noticed it…

Oct 21 22:23:37 Gutenberg sshd[25711]: Invalid user Rauno from 84.103.144.152
Oct 21 22:23:37 Gutenberg sshd[25721]: Invalid user Reeta from 84.103.144.152
Oct 21 22:23:38 Gutenberg sshd[25735]: Invalid user Reetta from 84.103.144.152
Oct 21 22:23:43 Gutenberg sshd[25752]: Invalid user Reija from 84.103.144.152
Oct 21 22:23:44 Gutenberg sshd[25826]: Invalid user Reijo from 84.103.144.152
Oct 21 22:23:44 Gutenberg sshd[25882]: Invalid user Reima from 84.103.144.152
Oct 21 22:23:45 Gutenberg sshd[25913]: Invalid user Reino from 84.103.144.152
Oct 21 22:23:48 Gutenberg sshd[25963]: Invalid user Reko from 84.103.144.152
Oct 21 22:23:49 Gutenberg sshd[26009]: Invalid user Reversals from 84.103.144.152
Oct 21 22:23:53 Gutenberg sshd[26053]: Invalid user Riikka from 84.103.144.152

(Actual IP addresses and server names vary)

And… the log keeps going and going for thousands of attempts, and they keep becoming more often. He probably used a fast server for that.

In either case, although we were completely secure from an SSH login perspective (even if he guessed an actual password using this method -which he wouldn’t because we use secure passwords-, he wouldn’t be able to login without an rsa key), we were vulnerable to a DoS attack. Lately we’ve been trying to become less parsimonious about security, establishing almost formal procedures to avoid XSS attacks and SQL injections, as well as other attacks. It’s about time to come up with more drastic methods for blocking DoS attackers.