Beiträge aus der Kategorie "Nerdcenter"

Debian Lenny: pam_mount, files and loop devices

When I was trying to automatically mount an encrypted image at login using pam_mount, I encountered a strange problem:
I wasn’t able to find any errors in my configuration (at least none connected to this behaviour), but mount.crypt was unable to mount the image.
Enabling debugging in pam_mount.conf.xml (<debug enable="1" />) revealed the command used for mounting:

pam_mount(misc.c:272) command: mount.crypt [-o loop] [/home/foobar/container] [/home/foobar/crypto]

In Debians libpam-mount 0.44-1+lenny3, /sbin/mount.crypt is a bash script that calls cryptsetup with parameters generated during its runtime.
Debugging it (set -x), I stumpled upon the following command:

cryptsetup -c aes -h ripemd160 -s 256 create _home_foobar_container /home/foobar/container

…which returned the following error message:

Command failed: BLKROGET failed on device: Inappropriate ioctl for device

So mount.crypt has been passed the loop option but cryptsetup was told to mount the encrypted image instead of the associated loopback device (normally mount.crypt executes losetup to create this association in its function _losetup, but this apparently has never been called).

Long story short:
There seems to be a bug in Debians libpam-mount 0.44-1+lenny3.
The case statement at line 110 in /sbin/mount.crypt doesn’t work as expected because the variable $KEY used for option comparison has an ordinary space at its values beginning.
To fix this, you can either change the way how passed options are saved in the OPTION variable (starting at line 60) or change line 110 to the following:

case ${KEY/ /} in

This will remove all spaces.

 

How-to: Debian: Automatically mounted loopback images with dm-crypt, LUKS, pam_mount

How to create encrypted loopback images with dm-crypt and LUKS + automatically mounting them after login with pam_mount

I recommend using debian squeeze for this scenario as lenny includes a very old version of libpam-mount and I had lots of problems when I tried using it.
Using only the libpam-mount package and its dependencies from squeeze maybe (I didn’t try it and I wouldn’t recommend it either) does the job too, but at least has a very bitter after taste if you take a closer look at the dependencies.

1. Make sure you have the required kernel modules loaded. If you use the stock debian kernel, this will be the case. if you don’t, make sure you’ve set the following options:

  • CONFIG_BLK_DEV_DM=y or CONFIG_BLK_DEV_DM=M
  • CONFIG_DM_CRYPT=y or CONFIG_DM_CRYPT=M
  • CONFIG_CRYPTO_CBC=y

Additionally, you need to include support for at least one cipher.

In make menuconfig, you can find the required kernel modules at the following locations:

Device Drivers  --->
	Multi-device support (RAID and LVM)  --->
		 Device mapper support
		 Crypt target support

Cryptographic options  --->
	 SHA256 digest algorithm
	 AES cipher algorithms (x86_64)

To avoid a reboot, you can build all of these options as modules. If you chose to do so, you can later load the modules by using modprobe .

2. Install the required packages
apt-get install cryptsetup libpam-mount
…apt-get should take care of all dependencies

3. Generate a random key and assign it to a variable for later use

KEY=`tr -cd [:graph:] < /dev/urandom | head -c 79`

4. Encrypt the key and save it to a file

echo $KEY | openssl aes-256-cbc > container.key

5. Create the loopback file and fill it with random data

dd if=/dev/urandom of=~/container.img bs=1G count=10

This will create a 10GB file and fill it with random data taken from /dev/urandom.
Another option (which will be much faster especially on older hardware) is using /dev/zero to fill the loopback file with zeros:

dd if=/dev/zero of=~/container.img bs=1G count=10

6. Set up a loop device

losetup /dev/loop0 ~/container.img

7. LuksFormat it

echo $KEY | cryptsetup -v -c aes -s 256 luksFormat /dev/loop0

8. Open it

cryptsetup luksOpen /dev/loop0 container

9. Make a filesystem of your choice

mkfs.xfs /dev/mapper/container

10. Close it and delete loop

cryptsetup luksClose container && losetup -d /dev/loop0

11. Configure pam_mount
Open /etc/security/pam_mount.conf.xml in your favorite text editor and change it to the following:

<?xml version="1.0" encoding="utf-8" ?>

<!DOCTYPE pam_mount SYSTEM "pam_mount.conf.xml.dtd">
<pam_mount>
	<debug enable="1" />
	<mkmountpoint enable="1" remove="true" />

	<msg-sessionpw>reenter password for pam_mount:</msg-sessionpw>
	<volume user="foobar" path="/home/foobar/container.img" mountpoint="/home/foobar/containercontents"
		options="cipher=aes-cbc-essiv:sha256,hash=sha512,keysize=256" fstype="crypt" fskeycipher="aes-256-cbc"

		fskeypath="/home/foobar/container.key" fskeyhash="md5" />
</pam_mount>

Using this configuration the image /home/foobar/container.img will get mounted into /home/foobar/containercontents when the user foobar logs in.
Enabling debugging is pretty usefull if something isn’t working as it should. In this case you can take a look at /var/log/auth.log.

12. Include /etc/pam.d/common-pammount in the PAM configuration files of the services that should use it (for example: SSHd)
Open /etc/security/sshd in your favorite text editor. Look for the line “@include common-session” and add a new line after it:

...
@include common-session
@include common-pammount
...

13. If needed, change the configuration of the relevant services (for example: SSHd)
Open /etc/ssh/sshd_config in your favority text editor and make sure you have the following lines in there:

# pam_mount
UsePAM yes
PasswordAuthentication yes
ChallengeResponseAuthentication no
UsePrivilegeSeparation no
PermitUserEnvironment yes

If you disable PasswordAuthentication and use keys instead you have to enter the users password after connecting via SSH.

14. Test if anything works as expected
Open a root session or use sudo and watch the auth log by using tail -f /var/log/auth.log. Then login as the user for which you have configured a volume earlier.
If the encrypted loopback image gets mounted, also test if it gets unmounted again, when the user logs out.
If anything works remove the debug line from /etc/security/pam_mount.conf.xml.

Many thanks go to the users tuxophil and pillgrim from the gentoo forums. Large parts of this howto were taken from their postings at http://forums.gentoo.org/viewtopic-t-274651.html.

 

TYPO3: Frontend Renderer als Singleton

Renderer sind stets einmalig. Das Singleton Design Pattern bilded genau dies ab: Es wird lediglich eine einzige Instanz der Klasse erzeugt und zurückgegeben. Die folgende Klasse kann als Basis für die View-Schicht der eigenen TYPO3 Extension verwendet werden. Sie ist von pi_base abgeleitet und bietet so den gewohnten Funktionsumfang. Der Codeschnipsel stammt aus einer mini TYPO3 Extension, an der ich gerade privat bastel.

<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2009 Thorsten Boock <thorsten (at) nerdcenter.de>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free Software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

require_once(PATH_tslib . 'class.tslib_pibase.php');

/**
 * Frontend Renderer
 * Till PHP 5.3 this class has to be declared as final because
 * we don't know the names of the classes extending this one.
 *
 * @author Thorsten Boock <thorsten (at) nerdcenter.de>
 */
final class tx_tbwhoisonline_renderer_fe extends tslib_pibase {
	/**
	 * Instance of this class (Singleton Design Pattern)
	 *
	 * @var tx_whoisonline_renderer_fe
	 */
	private static		$instance					=	null;
	/**
	 * Path to the template file used for rendering
	 *
	 * @var string
	 */
	private				$templateFile				=	'';
	/**
	 * The contents of the file $this->templateFile
	 *
	 * @var string
	 */
	private				$templateHTML				=	'';

	/**
	 * Empty constructor (Singleton Design Pattern)
	 *
	 */
	private function __construct() {

	}

	/**
	 * Empty clone function (Singleton Design Pattern)
	 *
	 */
	private function __clone() {

	}

	/**
	 * Instantiating this object (Singleton Design Pattern)
	 *
	 * @return tx_tbwhoisonline_renderer_fe
	 */
	public static function getInstance() {
		if(self::$instance == null) {
			self::$instance = new tx_tbwhoisonline_renderer_fe();
		}
		return self::$instance;
	}

	/**
	 * Initializing this object
	 *
	 * @param array $conf
	 */
	public function init($conf) {
		// init tslib_pibase
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();
		// get cObj instance and load template
 		$this->cObj = t3lib_div::makeInstance('tslib_cObj');
 		$this->templateHTML = $this->cObj->fileResource($this->templateFile);
		// override defaults with typoscript configuration
		foreach($this->conf as $key => $value) {
			$key = str_replace('.', '', $key);
			if(isset($this->$key)) {
				$this->$key = $value;
			}
		}
	}
}
?>

 

OS X kernel_task CPU-Usage

Als ich heute in der Firma saß wurden sämtliche Anwendungen, die auf meinem MacBook liefen, plötzlich ziemlich langsam. Doch welcher Prozess sorgte dafür?

Zu meiner Überraschung fand sich der Prozess kernel_task bezüglich seines CPU Appetits auf Platz Eins wieder. Wenn ich das ganze richtig verstanden habe ist kernel_task eine Zusammenfassung sämtlicher Kernelprozesse (inkl. derer von Kernel Extensions (.kext Dateien), welche als Thread dieses Prozesses laufen. Diese Prozesse werden also anders als etwa bei Linux und BSD zusammengefasst dargestellt. Wenn man auf der Suche nach der Ursache für den von mir beobachteten Leistungsabfall ist, stört das ganz ungemein, denn man kann z.B. nicht sofort erkennen ob das Problem etwa vom Kernel Modul für das verwendete Dateisystem herrührt.

Eine Google Suche offenbarte zwar diverse Foren- und Mailinglistenbeiträge, bei denen sehr ähnliche Probleme geschildert wurden, eine Lösung fand sich jedoch nicht. So blieb mir nur noch Raten. Da ich am Vortrag Virtualbox installiert habe, wodurch auch einige Kernelmodule mitinstalliert wurden, lag dort mein erster Verdacht. Also Virtualbox samt der Module mit dem mitgelieferten Shell (Bash?) -Skript deinstalliert. Die Module wurden sofort unloaded (hm, irgendwie fällt mir gerade kein sinnvolles, deutsches Wort dafür ein… entladen oder ausladen klingt doof) doch die Prozessor-Auslastung nahm nicht ab. Aus einem komplett anderen Grund habe ich später die Dateirechte Reparieren Funktion von Disk Util angehauen. Keine sofortige Veränderung. Irgendwann ausgeschaltet.

Als ich das MacBook gerade wieder eingeschaltet habe ist wieder alles super. Da ich zwischenzeitlich diverse Versuche mit anschließenden Neustarts (etwa PRAM reset) versucht habe, glaube ich, dass eine der beiden Aktionen etwas bewirkt hat. Sie waren das letzte, was ich gemacht habe. Irgendwie fände ich es logisch wenn es die erstere gewesen ist aber vielleicht war es ja auch einfach Magie Icon Wink in OS X kernel_task CPU-Usage

Mein System ist übrigens ein 10.5.6.

 

PHP: Bit Flags

In manchen Fällen können Bit Flags in PHP-Skripten sehr nützlich sein. Etwa wenn es darum geht,
anhand eines “action”-Parameters zu entscheiden, welche Objekte instanziiert werden sollen. U.a. auf diese Weise kann
- sonst redundanter – Code gesparrt werden.

Kennern des binären Zahlensystems sollten also mal einen Blick darauf werfen. Alle anderen sollten dringend zu
diesen Kennern werden – das macht nicht nur das Verständniss des folgenden Codesnippets sondern das ganze (IT-) Leben einfacher Icon Wink in PHP: Bit Flags

Das Prinzip ist eigentlich ganz einfach: Es werden einzelne Bits einer Integer Variablen gesetzt. Mit einer
logisch AND Verknüpfung kann dann geprüft werden, ob einzelne Bits gesetzt wurden. Mit AND können Bits gelöscht werden,
mit OR werden sie hinzu addiert. Jedes Bit stellt ein Flag dar. Ist ein Flag gesetzt werden entsprechende Aktionen ausgeführt.

Ein kleines Beispiel zu Bit Flags in PHP5:

class example_controller {
	/**
	 * Flags set by $this->setFlags()
	 *
	 * @var int
	 */
	private		$flags			=	0;
	/**
	 * Instantiate the renderer object if this flag is set
	 *
	 * @var int
	 */
	const		FLAG_RENDERER		=	1;
	/**
	 * Do something cool if this flag is set
	 *
	 * @var int
	 */
	const		FLAG_DO_COOL_STUFF	=	2;
	/**
	 * Do even more cool stuff if this flag is set
	 *
	 * @var int
	 */
	const		FLAG_EVEN_MORE_STUFF	=	4;

	/**
	 * Initializes this object
	 *
	 */
	public function init() {
		$this->setFlags();
		$this->processFlags();
	}

	/**
	 * Setting the flags according to parameters
	 *
	 */
	private function setFlags() {
		if(!empty($_GET['action'])) {
			switch($_GET['action']) {
				case 'createFoo':
					$this->flags |= self::FLAG_RENDERER;
					break;
				case 'saveFoo':
					$this->flags |= self::FLAG_RENDERER;
					$this->flags |= self::FLAG_DO_COOL_STUFF;
					break;
			}
		}
	}

	/**
	 * Instantiates objects by flags
	 *
	 */
	private function processFlags() {
		// instantiate renderer
		if(($this->flags & self::FLAG_RENDERER) > 0) {
			require_once(EXTENSION_LIBPATH . 'class.example_renderer.php');
			$this->renderer = example_renderer::getInstance();
			$this->renderer->init();
		}
		// do cool stuff
		if(($this->flags & self::FLAG_DO_COOL_STUFF) > 0) {
			require_once('./lib/class.cool_stuff_factory.php');
			$myCoolStuff = cool_stuff_factory::makeInstance();
			$myCoolStuff->save();
		}
		// do even more cool stuff
		if(($this->flags & self::FLAG_EVEN_MORE_STUFF) > 0) {
			require_once('./lib/class.even_more_stuff.php');
		}
	}
}

 

Magento Serverumzug

Magento gestaltet einen Serverumzug leider schwieriger, als er sein müsste. Die Entwickler haben zahlreiche Stolpersteine versteckt, die es eigentlich gar nicht geben müsste (etwa das speichern vollständiger URLs in der Datenbank). Dennoch ist ein Serverwechsel einfacher, als man mancherorts liest:

1. Im Magento Backend unbedingt den Cache deaktivieren, zumindest den Konfigurations-Cache, denn auch die MySQL Zugangsdaten werden gecached, was dazu führt, dass nach dem Umzug nichts funktioniert und keine Möglichkeit dazu besteht, mit akzeptablen Aufwand den Cache zu leeren – der Login im Adminbereich geht dann nämlich auch nicht mehr.

2. SQL-Dump erzeugen:

mysqldump -uBENUTZER -pPASSWORT DATENBANK > magento.sql

3. Leider speichert Magento Komplette URLs in der Datenbank, etwa die Base URL und die Secure Base URL.
Daher ist es notwendig, die verwendeten IPs / Domains in dem Dump zu suchen und zu ersetzen, sofern sich diese geändert haben.
Den Dump dazu einfach in mit dem Lieblings-Texteditor (z.B. nano) öffnen oder alternativ mit reichlich Kommandozeilen-Magic (grep, sed). Ersteres geht in diesem Fall ausnahmsweise schneller Icon Wink in Magento Serverumzug

4. GZIP-komprimiertes Tararchiv aus dem Magento-Rootverzeichnis und dem SQLdump erzeugen:

tar cfz magento.tgz ~/public_html/magento magento.sql

5. Das Archiv per SCP oder FTP auf den neuen Server schieben, z.B.:

scp magento.tgz user@host:/absoluter_verzeichnis_pfad/

6. Das Archiv auf dem neuen Server entpacken:

tar xfz magento.tgz

7. Falls notwendig die entpackten Dateien / Verzeichnisse via mv ins neue htdocs verschieben…

8. Den entpackten Dump in die neue Datenbank einspielen:

mysql -uBENUTZER -pPASSWORT DATENBANK < magento.sql

9. Leider speichert Magento absolute Pfade, die für die Installation von Erweiterungen via Pear (bzw. Magento Connect als Frontend) verwendet werden.
Um diese Pfade zu aktualisieren muss man ins neue Magento-Wurzelverzeichnis wechseln und dort folgenden befehl ausführen:

./pear mage-setup

Ansonsten ist es nicht möglich Erweiterungen via Magento Connect einzuspielen!

 

MacBook iSight Kamera funktioniert nicht

Mein MacBook hat sich heute morgen geweigert zu starten. Fünf Anläufe waren nötig, damit das Teil endlich lief. Als es dann endlich geklappt hat, konnte ich mir erst einmal die Schweißperlen von der Stirn wischen, die bei dem Gedanken an meine Abschlussarbeit auf dem Gerät entstanden. Aber etwas war anders als sonst: Die Grüne LED neben der iSight Kamera leuchtete plötzlich permanent auf. Eigentlich zeigt diese an, dass die Kamera aktiv ist, was aber nicht der Fall war. In Photo Booth blieb das Bild schwarz. Neustart & co brachten keine Besserung. Folgendes hingegen schon:

  • MacBook ausschalten
  • Netzteil-Kabel entfernen und Batterie herausnehmen
  • 5 Sekunden auf den Einschalter drücken
  • Batterie wieder einlegen, Netzteil-Kabel wieder ran und tata – alles funktioniert wieder wie gewünscht

 

Webdesign-Kunden im Alltag

Einfach nur herrlich dieser Clip. Es trifft zwar glücklicher Weise nur auf wenige potentielle Auftraggeber zu aber dennoch begegnet einem diese Spezies immer wieder: Menschen mit dem Wunsch die perfekte Website innerhalb kürzester Zeit zu erhalten – selbstverständlich zum Ramschpreis. Das Video zeigt, wie sie außerhalb ihrer geschäftlichen Tätigkeit agieren.

 

XEN Loop Disk Image vergrößern

Das Loop Disk Image einer XEN DomU ist zu klein geworden? Solang die Festplatte des Hypervisors noch genügend Platzreserven hat, ist das glücklicherweise kein unlösbares Problem. Loop Disk Images können mit Bordmitteln vergrößert werden. Zwei kleine Beispiele für die Vorgehensweise bei EXT2, EXT3 und XFS Dateisystem:

EXT2 / EXT3 Dateisystem
VM herunterfahren:

xm shutdown domu.blub.local

Image um 30GB vergrößern:

dd if=/dev/zero bs=1024k count=30720 >> disk.img

Fehler im Dateisystem korrigieren:

e2fsck -f disk.img

Dateisystem auf die Größe des Images vergrößern:

resize2fs disk.img

XFS Dateisystem
VM herunterfahren:

xm shutdown domu.blub.local

Image um 30GB vergrößern:

dd if=/dev/zero bs=1024k count=30720 >> disk.img

Fehler im Dateisystem korrigieren:

xfs_repair -f disk.img

Dateisystem auf die Größe des Images vergrößern:

mount disk.img /mnt/tmp/ -o loop
xfs_growfs -d /mnt/tmp/

 

WordPress Update

Lange Zeit habe ich davor gescheut, meine WordPress-Installation zu aktualisieren. Hauptsächlich, weil ich Angst vor dem Aufwand hatte, schließlich habe ich noch WordPress 2.1 benutzt (aktuell ist 2.8.4) und daher mit zahlreichen Inkompabilitäten gerechnet. Letzte Nacht habe ich es dann trotzdem gewagt und das WordPress Update durchgeführt.

Und es geht doch…
…uralte WordPress-Installationen problemlos zu aktualisieren. Sogar ziemlich einfach. Orientiert habe ich mich dabei an diesem Artikel. Mir persönlich erschien es dabei aber sauberer, die neue Version herunter zu laden und die paar Sachen (Bilder), die ich aus der der alten Installation benötigte in die neue hinein zu kopieren. Dies ermöglicht es einem, eine Subdomain anzulegen, auf der man die neue Installation erst einmal testen kann. Anschließend kann man mit einem Symlink einfach die verwendete Installation wechseln.