Category Archives: Tips and Tricks

Bit by Bit struggle

Create disk image

  1. Boot from a live media.
  2. Make sure no partitions are mounted from the source hard drive.
  3. Mount the external HDD
  4. Backup the drive.

# dd if=/dev/sdX conv=sync,noerror bs=64K | gzip -c > /path/to/backup.img.gz

If necessary (e.g. when the format of the external HD is FAT32) split the disk image in volumes (see also the split man pages).

# dd if=/dev/sdX conv=sync,noerror bs=64K | gzip -c | split -a3 -b2G - /path/to/backup.img.gz

If there is not enough disk space locally, you may send the image through ssh:

# dd if=/dev/sdX conv=sync,noerror bs=64K | gzip -c | ssh user@local dd of=backup.img.gz

5. Save extra information about the drive geometry necessary in order to interpret the partition table stored within the image. The most important of which is the cylinder size.

# fdisk -l /dev/sdX > /path/to/list_fdisk.info

Note: You may wish to use a block size (bs=) that is equal to the amount of cache on the HD you are backing up. For example, bs=8192K works for an 8 MiB cache. The 64 KiB mentioned in this article is better than the default bs=512 bytes, but it will run faster with a larger bs=.
Restore system

To restore your system:

# gunzip -c /path/to/backup.img.gz | dd of=/dev/sdX

When the image has been split, use the following instead:

# cat /path/to/backup.img.gz* | gunzip -c | dd of=/dev/sdX

Install webacula

You might think that webacula is simple thinkg but it’s not and you think that, you terrible wrong my friend. This is probably most powerfull tool for managing bacula-director. It’s a bit tricky to make it work but once it’s running nothing can stop it. I had find myself cople of times struggling to figured out why it does not wont to start, you’ll see what I’m talking about if you do it off the beaten track. If you want great backup system with great web management tool, just follow my steps because frankly you’ll hate it otherwise.

Everything begins with:

wget http://downloads.sourceforge.net/project/webacula/webacula/7.0.0/webacula-7.0.0.tar.gz

If you have already LAMP-ish stack, you can skip this step
yum install httpd php php-mysql php-gd

tar -xzvf /root/webacula-7.0.0.tar.gz

mv webacula-7.0.0/ /var/www/html/webacula
cd !$
usermod -aG bacula apache
chgrp bacula /usr/sbin/bconsole /etc/bacula/bconsole.conf
cd ../application

vim config.ini
update:
bacula.bconsole = “/usr/sbin/bconsole”
bacula.bconsolecmd = “-n -c /etc/bacula/bconsole.conf”

vim /etc/sudoers
comment Defaults requiretty because otherwise you’ll get error like “sudo: sorry, you must have a tty to run sudo” later on

Defaults requiretty

Next step is my favorite one 🙂

vim /etc/selinux/config
>>> SELINUX=disabled

add following line in sudoers file or create config in:

vim /etc/sudoers.d/apache

apache ALL=NOPASSWD: /usr/sbin/bconsole

reboot (because the selinux) If you have selinux disabled from before it’s note necessary.

Check is apache has permissions to use bconsole:

su -l apache -s /bin/sh -c "/usr/bin/sudo /usr/sbin/bconsole -n -c /etc/bacula/bconsole.conf"
If you go straight to the bconsole, then sudo do the trick.

cd /var/www/html/webacula/install/apache/
cp webacula.conf /etc/httpd/conf.d/webacula.conf
vim /etc/httpd/conf.d/webacula.conf

Change:

Alias /webacula /usr/share/webacula/html


Deny from all

to:

Alias /webacula /var/www/html/webacula/html


Allow from

update your db pass etc.

vim /var/www/html/webacula/application/config.ini

vim /etc/bacula/bacula-dir.conf
update :
catalog = all, !skipped, !saved

cd /var/www/html/webacula/install
./password-to-hash.php

Copy respose to db.conf:

db_pwd=”your root mysql pass”
….
webacula_root_pwd=”your res from ./password-to-hash.php”

cd MySql/
./10_make_tables.sh
./20_acl_make_tables.sh

systemctl restart httpd.service

add Zend Framework to webacula:

cd /var/www/html/webacula/library
wget https://packages.zendframework.com/releases/ZendFramework-1.12.3/ZendFramework-1.12.3-minimal.tar.gz (download only ver 1.12.3!!!!!!)
tar -xzf ZendFramework-1.12.3-minimal.tar.gz
mkdir Zend
cp -Rf ZendFramework-1.12.3-minimal/library/Zend/* Zend/.

go to website 🙂

Now for some reason root passwd does not work out of the box, so we need to recover it by email.

mysql -u root -p
use bacula;
update webacula_users set email=’your email here’;

I preffer to use google mail because they don’t block messages from unexist sender such as root@localhost 🙂 The message will be in your spam folder but at least you’ll recieve it.

That’s all folsk, enjoy your Backup System.

Raspberry Pi kiosk-ish system

I needed to build kiosk-ish system for our reception to display pending tasks etc. I was stumbleing around of bunch of useless tutorials, which are either right and wrong at the same time. I found this one and it is tested on raspbian, work like a charm.

As much as you don’t want to use graphic display manager on your raspbery, you will have to 🙁

We’ll need the following packages:

matchbox
chromium
x11-xserver-utils
ttf-mscorefonts-installer
xwit
sqlite3
libnss3

sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install matchbox chromium x11-xserver-utils ttf-mscorefonts-installer xwit sqlite3 libnss3

If you raspberry does not dettect automaticaly it’s resolution on boot, you can edit /boot/config.txt and add following parametters:

# 1900×1200 at 32bit depth, DMT mode
disable_overscan=1
framebuffer_width=1900
framebuffer_height=1200
framebuffer_depth=32
framebuffer_ignore_alpha=1
hdmi_pixel_encoding=1
hdmi_group=2

Starting Chromium:

Add at the end of youre /etc/rc.local

if [ -f /boot/xinitrc ]; then
ln -fs /boot/xinitrc /home/pi/.xinitrc;
su – pi -c ‘startx’ &
fi

… and create /boot/xinitrc file with:

#!/bin/sh

# Clean up previously running apps, gracefully at first then harshly
killall -TERM chromium 2>/dev/null;
killall -TERM matchbox-window-manager 2>/dev/null;
sleep 2;
killall -9 chromium 2>/dev/null;
killall -9 matchbox-window-manager 2>/dev/null;

# Clean out existing profile information
rm -rf /home/pi/.cache;
rm -rf /home/pi/.config;
rm -rf /home/pi/.pki;

# Generate the bare minimum to keep Chromium happy!
mkdir -p /home/pi/.config/chromium/Default
sqlite3 /home/pi/.config/chromium/Default/Web\ Data “CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR); INSERT INTO meta VALUES(‘version’,’46’); CREATE TABLE keywords (foo INTEGER);”;

# Disable DPMS / Screen blanking
xset -dpms
xset s off

# Reset the framebuffer’s colour-depth
fbset -depth $( cat /sys/module/*fb*/parameters/fbdepth );

# Hide the cursor (move it to the bottom-right, comment out if you want mouse interaction)
xwit -root -warp $( cat /sys/module/*fb*/parameters/fbwidth ) $( cat /sys/module/*fb*/parameters/fbheight )

# Start the window manager (remove “-use_cursor no” if you actually want mouse interaction)
matchbox-window-manager -use_titlebar no -use_cursor no &

# Start the browser (See http://peter.sh/experiments/chromium-command-line-switches/)
chromium –app=http://URL.of.your/choice.html

Save it, reboot and that’s it.

Nagios check_esxi_snapshots

This script is using pySphere api for esxi and do loop through all vms and checks for snapshots.

#!/usr/bin/python
from pysphere import VIServer
import sys

ok = 0
warn = 1
crit = 2
status = { 'OK' : 0 , 'WARNING' : 1, 'CRITICAL' : 2 , 'UNKNOWN' : 3}

server = sys.argv[1]
user = sys.argv[2]
pwd = sys.argv[3]

s = VIServer()
s.connect(server, user, pwd)
names = ""
result = s._retrieve_properties_traversal(
property_names=['name', 'rootSnapshot'],
obj_type="VirtualMachine")
for props in result:
has_snapshots = False
name = ""
for ps in props.PropSet:
if ps.Name=='rootSnapshot' and ps.Val.ManagedObjectReference:
has_snapshots = True
if ps.Name=='name':
name = ps.Val
if has_snapshots:
names = names + name + ', '
if warn == True:

if crit == True:
print names, 'has a snapshot'
print status['CRITICAL']
sys.exit(status['CRITICAL'])
else:
print names, "are running with snapshot"
print status['WARNING']
sys.exit(status['WARNING'])

else:
print 'status OK, no snapshots'
sys.exit(status['OK'])

Cisco 79** xml conf

I lost 3 hours figuring out how to set up these new Cisco phones, because its use new config file, xml instead of cnf …. shit …
[code lang=”xml”]
<device>
<deviceProtocol>SIP</deviceProtocol>
<sshUserId>cisco</sshUserId>
<sshPassword>cisco</sshPassword>
<devicePool>
<dateTimeSetting>
<dateTemplate>D-M-Y</dateTemplate>
<timeZone>Central European Time</timeZone>
<ntps>
<ntp>
<name>uk.pool.ntp.org</name>
</ntp>
</ntps>
</dateTimeSetting>
<callManagerGroup>
<members>
<member priority="0">
<callManager>
<ports>
<ethernetPhonePort>2000</ethernetPhonePort>
<sipPort>5060</sipPort>
<securedSipPort>5061</securedSipPort>
</ports>
<processNodeName>192.168.8.1</processNodeName>
</callManager>
</member>
</members>
</callManagerGroup>
</devicePool>
<sipProfile>
<sipProxies>
<registerWithProxy>true</registerWithProxy>
</sipProxies>
<enableVad>false</enableVad>
<preferredCodec>g729ulaw</preferredCodec>
<natEnabled></natEnabled>
<phoneLabel>Kerri’s Phone</phoneLabel>
<sipLines>
<line button="1">
<featureID>9</featureID>
<featureLabel>207</featureLabel>
<proxy>192.168.8.1</proxy>
<name>207</name>
<displayName>Kerri</displayName>
<authName>207</authName>
<authPassword>73eb0c55b8</authPassword>
<messagesNumber>999</messagesNumber>
</line>
<line button="2">
<featureID>21</featureID>
<featureLabel>201</featureLabel>
<speedDialNumber>201</speedDialNumber>
</line>
</sipLines>
<dialTemplate>dialplan.xml</dialTemplate>
</sipProfile>
<commonProfile>
<phonePassword></phonePassword>
</commonProfile>
<loadInformation>SIP41.8-2-1S</loadInformation>
<versionStamp>1143565489-a3cbf294-7526-4c29-8791-c4fce4ce4c37</versionStamp>
<directoryURL></directoryURL>
<servicesURL></servicesURL>
</device>[/code]

Asterisk watch active calls && Fix database

watch -n 1 "asterisk -vvvvvrx 'core show channels' | grep call"

WARNING[25801] res_config_mysql.c: Realtime table general@queue_log: column ‘time’ cannot be type ‘int(10) unsigned’ (need char)

Sample queue_log table for MySQL:

Drop table in qstat & asterisk database – table queue_log, and add it again. Then edit extconfig.conf

CREATE TABLE `queue_log` (
`id` varchar(40) NOT NULL default auto_increment,
`time` char(10) unsigned default NULL,
`callid` varchar(32) NOT NULL default '',
`queuename` varchar(32) NOT NULL default '',
`agent` varchar(32) NOT NULL default '',
`event` varchar(32) NOT NULL default '',
`data` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
);

Malicous and Suspicious Files – Finding and removing eval(base64_decode)

I found this very very useful tutorial … I found it on the hard way, when everything is messed up! 🙂

Original Article Written by Rahul Bansai – http://devilsworkshop.org/tutorial/remove-evalbase64decode-malicious-code-grep-sed-commands-files-linux-server/55587/

Command to list all infected files:

grep -lr --include=*.php "eval(base64_decode" /path/to/webroot

This is not necessary but its better to check some files manually to confirm if they have malicious code we are looking for. Also we can use this command after running cleanup command to crosscheck if cleanup is really successful.
Command to remove malicious code:

If above command gives you correct output, execute following command to perform actual cleaning:

grep -lr --include=*.php "eval(base64_decode" /path/to/webroot | xargs sed -i.bak 's/

Executing above will remove eval(*) codes. Above command will also generate a backup version of files it will modify. For example, if it removes code from index.php, you will find a new file index.php.bak in same directory with original content of index.php

Now after running above command, you still find some more infected files, then you need to adjust search and replace parameters in for “sed” part. You may also use following command for a “liberal” cleaning at the risk of breaking something. (in case you really break something, like I did, you can jump to “Troubleshooting” section below!)

grep -lr --include=*.php "eval(base64_decode" /path/to/webroot | xargs sed -i.bak '/eval(base64_decode*/d'
Trying to avoid re-appearance of this code injection

Its really though to cover every possible way to protect yourself from such attach in this post.

If you remember, WordPress community faced this kind of issue because of WP-PhpMyAdmin plugin sometime back. In our case, we found some old WordPress demo sites were having that plugin installed.

To remove WP-PhpMyAdmin plugin form all WordPress sites on your server, execute following command:

find /path/to/webroot -name "wp-phpmyadmin" -type d | xargs rm -rf

Above is all we did to get rid of eval(base64_decode(*)) codes from all files on our test server. If this happens again on our server, I will update this post with added info.
Troubleshooting:

Just in case you end up in a mess, below are some useful commands.

Missing find /var/www/ -name "index.php" | grep "/htdocs/index.php" | xargs grep -L "

Don’t worry. If you already have a “find . -name '*.php' -exec sed -i -e :a -e '/^n*$/{$d;N;ba' -e '}' '{}' ;

ThinUbuntu

I was searching for best thin client for one client. I have tried this Thinstation, but everything is so confusing. So I asked myself, why should I use whole thinclient os. I start browsing about some solutions and I found the best one! It use Ubuntu any version, you can tweak it for your needs and have everything that you
need. Lets start with Ubuntu 14.04.1 LTS.

1st you need to install it, update if you want and then all that you need to do is:

sudo apt-get install rdesktop
sudo apt-get install lxde

We gonna use lxde, because is lightweigt and simple. Once these packages are installed you can satart configuring them.

Create executable mythinclient wherever you want, and there you need to pass some parameters to rdesktop. I use following configuration
rdesktop -N -k en-gb -a 32 -z -f -5 -r disk:usb=/media/usb1 host.name/ipaddr

If you want, you can serch for rdesktop parameters. This uses usb redirection host/remote, numlock export 32 bit collors and automatically fullscreen.

Now we need to write autostart conf file to execute this script when user login.

mkdir -p ~/.conf/autostart && vim ~/.conf/autostart/$USER.desktop

[Desktop Entry]
Type=Application
Exec=/home/username/mythinclient
Hidden=false
NoDisplay=false
X-GNOME-Austoart-enabled=true

Now we are going to pass some parameters to lightdm. I have some problems with DHCP, it takes 5 sec to obtain address and by this time, when session start there is no internet and the session does not start … fail …
I solve this with 6 sec bypass 🙂

vim /etc/lightdm/lightdm.conf

[SeatDefaults]
autologin-guest=false
autologin-user=thin
autologin-session=lightdm-autologin
greeter-hide-users=true
greeter-session=unity-greeter
user-session=LXDE.desktop
autologin-user-timeout=6

Now reboot and everything must be OK. :)If you want you can check for additional options of lightdm.conf file

ubuntu boot/6sec login screen and then you are in the game!

rEset mysql password

Create a text file containing the following statements. Replace the password with the password that you want to use.

UPDATE mysql.user SET Password=PASSWORD(‘MyNewPass’) WHERE User=’root’;
FLUSH PRIVILEGES;

Start the MySQL server with the special –init-file option:

shell> mysqld_safe –init-file=/home/me/mysql-init &

The server executes the contents of the file named by the –init-file option at startup, changing each root account password.