onsdag 6. juni 2012

Check for correct password in PostgreSQL

Check if a ROLE has the correct password, and change if it isn't:
1:  #!/bin/bash                                                                                                                    
2:  DB_USER='icinga'  
3:  DB_PASSWORD='Jaht5aChkib2The5iA'  
4:  SALT=$DB_USER  
5:  MD5_PASSWORD=$(echo -n ${DB_PASSWORD}${SALT} | md5sum | cut -d" " -f1)  
6:  PASSWORD_HASH="md5${MD5_PASSWORD}"  
7:  CURRENT_PASS=$(psql -tA -c "SELECT passwd FROM pg_shadow WHERE usename = '${DB_USER}';")  
8:    
9:  if ! [ $CURRENT_PASS == $PASSWORD_HASH ]; then  
10:    psql -tA -c "ALTER ROLE ${DB_USER} WITH PASSWORD '${DB_PASSWORD}';"  
11:  fi  
Note: to be run locally as postgres user.

mandag 3. januar 2011

Restrict ssh access to one command, but allow parameters

Sometimes one needs to allow a script to login to a server using a SSH key to do a job. That can be achieved by adding the scripts SSH public key to the remote user's authorized_keys file. The private keys are often stored without password to allow the script to use the key and not stopping execution by an interactive prompt for the private key password.

This puts the remote server at risk because if the originating server is compromised an attacker would easily gain access to the remote server as well. To reduce the damage of a compromised private key, one often restricts the access of the key to the minimum required to get the script's job done. This can be accomplished by using SSH-key options in the authorized_keys file.

Example:
from="fromserver.example.com",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,command="/home/user/bin/script.sh" ssh-rsa  AAAAB3NzA..Dxq= user@fromserver.example.com

This is quite effective, and restricts the attacker to executing the specified forced command, and only from a specified host, with no terminal or X11 access.

Other times one needs to do a sync job using rsync. Let's see how that works out with the above scheme.

Example command:
/usr/bin/rsync /some/dir/ user@remote.example.com:/some/other/dir/


Example entry in authorized_keys:
from="fromserver.example.com",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,command="/usr/bin/rsync" ssh-rsa  AAAAB3NzA..Dxq= user@fromserver.example.com

Trying that, you'll soon noticed that all your command line arguments are ignored, and you'll get the help text from rsync as output. The forced command option does not allow arbitrary command line arguments to the command.

There is a workaround by using the $SSH_ORIGINAL_COMMAND environment variable that the ssh program creates. The problem with that is that you'll need a wrapper script to deal with the arguments because it will have the executable twice in the argument list:
from="fromserver.example.com",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,command="/usr/bin/rsync $SSH_ORIGINAL_COMMAND" ssh-rsa  AAAAB3NzA..Dxq= user@fromserver.example.com

This will produce this command:
/usr/bin/rsync /usr/bin/rsync /some/dir/ user@remote.example.com:/some/other/dir/


A solution to this is the wrapper script that interprets the environment variable and executes the correct command:
#!/bin/bash
case $SSH_ORIGINAL_COMMAND in
    "/usr/bin/rsync "*)
        $SSH_ORIGINAL_COMMAND
        ;;
    *)
        echo "Permission denied."
        exit 1
        ;;
esac

This adds complexity and requires a script to be installed on the remote server. It is also possible to achieve a similar solution without the wrapper script:

from="fromserver.example.com",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,command="/usr/bin/rsync ${SSH_ORIGINAL_COMMAND#* }"

Notice the '#* ' right after SSH_ORIGINAL_COMMAND. The # modifier in bash is used to remove the smallest prefix pattern, and so '#* ' will remove everything up until and including the first space.

There are some security concerns however. For instance this would be possible from the machine "fromserver.example.com":


rsync authorized_keys user@server:/home/user/.ssh/authorized_keys

That would allow an attacker to swap the file with anything, and thus the security is easily breached. To prevent that,  make the file owned by root and remove write permissions on the file, or make it immutable with chattr.

chown root:root /home/user/.ssh/authorized_keys
chmod a-w       /home/user/.ssh/authorized_keys
chattr +i       /home/user/.ssh/authorized_keys

Allowing the unrestricted use of the rsync program will allow an attacker to replace any files the user has write access to. Beware that there probably are other holes in this that I didn't find.

mandag 13. september 2010

Managing GlassFish domains with Puppet

Following James Turnbull's plugin HOWTO, I've created a new Puppet resource type for managing GlassFish domains. You can get it via the Puppet Forge.

This plugin is meant to replace the previously used (with success) exec type for managing GlassFish domains:
$passfile = "/home/gfish/.aspass"
$portbase = "4900"
$asadmin = "/opt/NSBglassfish/bin/asadmin"
$domaindir = "/opt/NSBglassfish/glassfish/domains"

exec {
"create-domain-$name":
command => "$asadmin --user admin --passwordfile $passfile create-domain --profile cluster --portbase $portbase --savelogin $name",
user => "admin",
creates => "$domaindir/$name";
}

his new resource type allows for more functionality and expressive clarity than the exec type. For example, it allows you to easily delete the domain by using the ensure => absent property. This is how one specifies a new GlassFish domain with this:
glassfish {
"mydomain":
portbase => "4800",
adminuser => "admin",
passwordfile => "/home/gfish/.aspass",
profile => "cluster",
ensure => present;

"myolddomain":
ensure => absent;
}

I plan to add more features to it, such as adding system-properties and jvm-options.

mandag 24. mai 2010

Parsing the /etc/passwd file with Ruby

I decided to write a program to parse the /etc/passwd file in my favourite scripting language. The file has seven fields: user, password, UID, GID, GECOS, home and shell.

Writing this snippet of code, I used some metaprogramming features in Ruby that I learned from Metaprogramming Ruby by Paolo Perrotta, like "OpenStruct", Dynamic Methods and method_missing(). I created a structure to hold the field information for each line in the file like this:

class PasswdFile
class PasswdEntry
def initialize
@attributes = {}
end

def method_missing(name, *args)
attribute = name.to_s
if attribute =~ /=$/
@attributes[attribute.chop] = args[0]
else
@attributes[attribute]
end
end

def import(line)
field_names = [:user, :password, :uid, :gid, :gecos, :home, :shell]
fields = line.split(":")
puts "Error: Not a passwd line, not 7 fields" unless fields.length == 7
field_names.each do |field_name|
self.send("#{field_name}=", fields[field_names.index(field_name)])
end
end
end

attr_reader :filename
def initialize(filename="/etc/passwd")
@entries = []
import(filename)
end

def import(filename)
File.open(filename, "r").each do |line|
entry = PasswdEntry.new
entry.import line
@entries << entry
end
end

def each
@entries.each do |entry|
yield entry
end
end

def print
field_names = [:user, :password, :uid, :gid, :gecos, :home, :shell]

@entries.each do |entry|
puts "ENTRY:"
field_names.each do |field_name|
puts " #{field_name}: " + entry.send("#{field_name}")
end
end
end
end

To show an example of useage, we can print each field, like this:

entries = PasswdFile.new
entries.print

tirsdag 18. august 2009

Rooting the HTC Hero

On friday I got my new HTC Hero in the mail. Yesterday, I rooted it following instructions on phandroid.com. Instead of from Windows, like in the article on phandroid.com, I did it from Linux, and here is how.

1. Download android-sdk-linux_x86-1.5_r3.zip

2. Download orange-htc-hero-uk-boot.img-28-july-2009.zip

3. Download fastboot for Linux.

4. Run these commands:
# unzip android-sdk-linux_x86-1.5_r3.zip
# unzip orange-htc-hero-uk-boot.img-28-july-2009.zip
# mv orange-htc-hero-uk-boot.img-28-july-2009/boot.img.insecure android-sdk-linux_x86-1.5_r3/tools
# unzip fastboot.zip
# mv fastboot android-sdk-linux_x86-1.5_r3/tools
# cd android-sdk-linux_x86-1.5_r3/tools
5. Shutdown the phone and plug in the USB cable.

6. Press and hold the back key and power on the phone.
This will get you into the fastboot USB screen (the white screen with three androids at the bottom).

7. Run this command:
# sudo ./fastboot boot boot.img.insecure
downloading 'boot.img'... OKAY
booting... OKAY
Now your device will start from the given image with root access.

8. In the phone's alerts menu, click HTC Sync.

9. Run this command:
sudo ./adb shell
This will give you a root shell on the device.

10. From this shell, run these commands:
# mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
# cp -a /system/bin/su /system/bin/su.backup
# cat /system/bin/sh > /system/bin/su
# chmod 4755 /system/bin/su
# reboot
Now your device is rooted!

tirsdag 11. august 2009

ZFS root disk mirror

So, I just installed OpenSolaris on a Sun Blade X6240 Server Module. I have two disks on this machine, and wanted to use disk mirroring. I didn't want to use the integrated LSI 1068E hardware RAID controller, I wanted to use the much cooler ZFS mirror feature.

During installation, it was not possible to set up mirroring, it had to wait until after the first boot. The installation wizard created the necessary partitions, ZFS filesystem and installed GRUB on the system, and I don't know what commands it has run to set up the disk the way it is now. So, to attach the mirror disk to the ZFS pool, I copied the partition table to the mirror:

# prtvtoc /dev/rdsk/c8t0d0s2 | fmthard -s - /dev/rdsk/c8t1d0s2

Now that's done, and I proceeded to attach the mirror disk into the ZFS pool:
# zpool status rpool
pool: rpool
state: ONLINE
scrub: none requested
config:

NAME STATE READ WRITE CKSUM
rpool ONLINE 0 0 0
c8t0d0s0 ONLINE 0 0 0

errors: No known data errors
# zpool attach -f rpool c8t0d0s0 c8t1d0s0
Please be sure to invoke installgrub(1M) to make 'c8t1d0s0' bootable.
# zpool status rpool
pool: rpool
state: ONLINE
status: One or more devices is currently being resilvered. The pool will
continue to function, possibly in a degraded state.
action: Wait for the resilver to complete.
scrub: resilver in progress for 0h0m, 15.41% done, 0h1m to go
config:

NAME STATE READ WRITE CKSUM
rpool ONLINE 0 0 0
mirror ONLINE 0 0 0
c8t0d0s0 ONLINE 0 0 0
c8t1d0s0 ONLINE 0 0 0 1.07G resilvered

errors: No known data errors

Installing GRUB and updating the master boot sector was also necessary to be able to boot off the mirror:
# installgrub -m /boot/grub/stage1 /boot/grub/stage2 /dev/rdsk/c8t1d0s0
Updating master boot sector destroys existing boot managers (if any).
continue (y/n)?y
stage1 written to partition 0 sector 0 (abs 16065)
stage2 written to partition 0, 271 sectors starting at 50 (abs 16115)
stage1 written to master boot sector

And that's that!

tirsdag 21. juli 2009

BADSIG 40976EAF437D05B5

When running apt-get update today, I got this error message:

The following signatures were invalid: BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key

Strange. And it was no good retrying, the same error occurred over and over again. apt-get stopped complaining after running update with this option:

apt-get update -o Acquire::http::No-Cache=True

and this:

apt-get update -o Acquire::BrokenProxy=true

I suspect my company's Barracuda Spam & Virus Firewall is to blame, as it has been blamed for arbitrarily corrupting downloads before by my co-workers. How can I know for certain?

tirsdag 17. februar 2009

H.264 at 1080p with NVIDIA's VDPAU on Linux

NVIDIA released support for their Video Decode and Presentation API for Unix with version 180.06 of their video and OpenGL driver for Xorg. They have also released patches to MPlayer so we can actually use it. I have tried getting it to work on my Gentoo GNU/Linux x86_64, but with the earliest drivers I got a green video window followed by a Xorg freeze with my graphics card. I had to SSH into the computer and kill MPlayer and Xorg. One of the versions even froze the kernel up completely. Version 180.27 actually didn't freeze my computer, put instead of the decoded video I got a random mosaic of colors.

With version 180.29 it did function properly with my XFX GeForce 280 GTX XXX graphics card. It's working great, and I can play H.264 1080p video with MPlayer using only 3% of a single CPU core!

To get VDPAU working you need, as I mentioned, a recent driver and at least version 180.06. Also you need a patched MPlayer, witch you can obtain the sources for here. Get the header files under "include" as well, and unpack the tarball and run the script checkout-patch-build.sh to retrieve MPlayer sources, patches and compile it all. As it is now (version 3482714), the VDPAU patches need additional patching to be able to play H.264 video above level 4.1:


--- libvo/vo_vdpau.c.orig 2009-02-17 15:03:25.936006847 +0100
+++ libvo/vo_vdpau.c 2009-02-17 18:43:43.995005259 +0100
@@ -90,7 +90,7 @@
/* Numbers of video and ouput Surfaces */
#define NUM_OUTPUT_SURFACES 3
#define NUM_VIDEO_SURFACES_MPEG2 3 // (1 frame being decoded, 2 reference)
-#define NUM_VIDEO_SURFACES_H264 17 // (1 frame being decoded, up to 16 references)
+#define NUM_VIDEO_SURFACES_H264 18 // (1 frame being decoded, 16 reference frames, plus b_frames and b_pyramid)
#define NUM_VIDEO_SURFACES_VC1 3 // (same as MPEG-2)
#define NUM_VIDEO_SURFACES_NON_ACCEL_YUV 1 // surfaces for YV12 etc.
#define NUM_VIDEO_SURFACES_NON_ACCEL_RGB 0 // surfaces for RGB or YUV4:4:4
@@ -701,10 +701,7 @@
uint32_t round_width = (vid_width + 15) & ~15;
uint32_t round_height = (vid_height + 15) & ~15;
uint32_t surf_size = (round_width * round_height * 3) / 2;
- max_references = (12 * 1024 * 1024) / surf_size;
- if (max_references > 16) {
- max_references = 16;
- }
+ max_references = 16; // Support for H.264 Level 5.1
}
break;
default:

mandag 16. februar 2009

CueCat USB barcode scanner hacked!

Last week I ordered a CueCat USB barcode scanner from LibraryThing. Today I gave it a first try, on my new book Pragmatic Version Control Using Git. Eager to try my new toy that I had envisioned to ease the process of adding my books to a database I plugged it in, observed that it was recognised as a HID, tried to scan the barcode, and out came this gibberish: .C3nZC3nZC3n2C3P3DxP6DxnY.fHmc.E3zXDhv1C3nYDNzY.

Quite disappointed, I realized that this thing might not be easily used with Linux after all. I searched on Google for CueCat, and soon realized that the stupid scanner outputs a serial number unique to this scanner, followed by the type of barcode and finally the barcode number, and all this is encrypted with CueCat's sophisticated "XOR with C"-cipher:
#!/usr/bin/perl -n 
# Copyright: Larry Wall
printf "Serial: %s Type: %s Code: %s\n",
map {
tr/a-zA-Z0-9+-/ -_/;
$_ = unpack 'u', chr(32 + length()*3/4) . $_;
s/\0+$//;
$_ ^= "C" x length;
} /\.([^.]+)/g;


So I foresaw that this dongle was going to be a pain to use. But after some more reading, I came across this page that shows me how to hack the CueCat and disable the encryption alltogether. So disassembled the device and cut pin number 5, like this:


After reassembling the scanner, I tried it on my book again. And lo and behold, there was the real ISBN number I had been looking for: 9781934356159!

lørdag 14. februar 2009

BuyPass switces to Java to interface with SmartCard

BuyPass is switching to using a Java implementation to interface with their BuyPass SmartCards. This is good news for everyone using a 64-bit Linux operating system. Their current access library called jnipcsc is only available for 32-bit architectures, and even then it's a pain to get working. They estimate that the new version of the BuyPass Java applet is ready for release in march 2009.

lørdag 22. november 2008

Emacs-w3m, a simple Emacs interface to w3m

The Emacs-w3m interface to the text based WWW browser is quite handy for reading those nasty HTML-only emails in Gnus.

The latest 1.4.4 release of Emacs-w3m is very old (2005), and doesn't work with Emacs 23. For Gentoo users of the development branch of Emacs 23 and Gnus, the only compatible version is in the CVS. There is currently no ebuild to install it. So, here is an ebuild to install it properly using Portage, if you want it.

emacs-w3m-9999.ebuild

# Copyright 1999-2008 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header$

inherit elisp cvs autotools

DESCRIPTION="Emacs-w3m is an interface program of w3m on Emacs"
HOMEPAGE="http://emacs-w3m.namazu.org"
ECVS_SERVER="cvs.namazu.org:/storage/cvsroot"
ECVS_MODULE="emacs-w3m"
ECVS_BRANCH="HEAD"
S="${WORKDIR}/${ECVS_MODULE}"

LICENSE="GPL-2"
SLOT="0"
KEYWORDS="alpha amd64 ppc sparc x86"
IUSE=""

DEPEND="virtual/w3m"
RDEPEND="${DEPEND}"

SITEFILE=71${PN}-gentoo.el

src_unpack() {
cvs_src_unpack
cd "${S}"
eautoreconf
}

# This is NOT redundant: elisp.eclass redefines src_compile() from default
src_compile() {
econf || die "econf failed"
emake || die "emake failed"
}

src_install() {
emake lispdir="${D}"/${SITELISP}/${PN} \
infodir="${D}"/usr/share/info \
ICONDIR="${D}"/usr/share/pixmaps/${PN} \
install install-icons || die "emake install failed"

elisp-site-file-install "${FILESDIR}/${SITEFILE}"
dodoc ChangeLog* README*
}

pkg_postinst() {
elisp-site-regen
einfo "Please see /usr/share/doc/${PF}/README*"
einfo
elog "If you want to use the shimbun library, please emerge app-emacs/apel"
elog "and app-emacs/flim."
einfo
}

pkg_postrm() {
elisp-site-regen
}

tirsdag 18. november 2008

Finally 64-bit Flash for Linux

Adobe has finally released a alpha of its first 64-bit Flash Player. This is in no way too soon. Users running 64-bit operating systems have been requesting this for several years to apparently deaf ears. Until now. Now, all that's left is for them to open source it, but I guess that's asking a bit much. I for one will surely be enjoying my Flash content from my 64-bit browser instead of having to start the 32-bit browser to be able to watch YouTube-clips.

On the other hand, the Gnash project has had a 64-bit Flash Player for quite some time now, and it's even capable of playing videos at YouTube. I suppose that in a couple of years when it's more stable, I'll be switching to using that one instead.

tirsdag 28. oktober 2008

BackupPC's mysterious paths

I've used BackupPC for a few years now, and I've found that it's a very good backup tool. The first installation I did was for Snota and it is still running just fine on it's Ubuntu machine. Installing it on Ubuntu was a breeze. It's clear that it's package maintainer Ludovic Drolez is doing a good job packaging it.

Yesterday I installed BackupPC on my home network. The lucky machine is running Gentoo. Gentoo's Portage repository is currently only stocking the rather old-ish 2.1.2 version from 2005. A lot has happened since (including support for multi level incrementals), and I decided to update the ebuild script to install the latest version (3.1.0). This was not as straight forward as I had hoped.

The included configure.pl script from BackupPC does not only configure paths, but it goes ahead and installs the files all the same. Not exactly what I'd expect from a script called configure. It should be splitted into a configure and an install script.

BackupPC has a facination with using "BackupPC" with capital letters in it's install paths, and I prefer not using them in install paths, as does the Debian and Ubuntu team. It's more standard that way. It is rather difficult to convince BackupPC that I prefer to use lower case letters, since it did not find the config.pl-file when I put it in /etc/backuppc instead of /etc/BackupPC. I actually had to patch Lib.pm so it would find it. It took me a while to find out why BackupPC didn't want to start, the error messages weren't exactly trying to tell me that it couldn't find config.pl.

Now it's running fine, and happily taking backups of my files. This is a great backup program once it is installed properly!

lørdag 11. oktober 2008

Trying out e-blog.el

This is my first weblog, and I'm happy to say I'm doing it directly from my Emacs using e-blog.el that uses the Gdata API for Blogger.

It is really easy to set up, I only had to load e-blog: (load "e-blog.el") and then do M-x e-blog-new-post, write the post, and hit C-c C-c.