Difference between revisions of "Script for theft alarm using HDAPS"

From ThinkWiki
Jump to: navigation, search
(Hmm, Bluetooth...)
 
(40 intermediate revisions by 10 users not shown)
Line 1: Line 1:
 
==General==
 
==General==
  
Recent ThinkPad models include a built-in two-axis accelerometer, as part of the [[HDAPS]] feature. This accelerometer can be put to another use: as a laptop theft deterrent. The following script detects when the laptop is moved and emits a loud audio alarm. Against a casual laptop-snatcher in a populated environment (e.g., typical office space) this can be an effective deterrent.
+
Recent ThinkPad models include a built-in two-axis accelerometer, as part of the [[HDAPS]] feature. This accelerometer can be put to another use: as a laptop theft deterrent. The following scripts detect when the laptop is moved, and emits a loud audio alarm.  
  
Note that the alarm cannot work when the laptop is suspended or powered off. You will buy an external motion detector alarm for those cases.
+
This alarm can be an effective deterrent against a casual laptop-snatcher in a populated environment (e.g., typical office space). It's also useful when you're across the room from the laptop and want to know if someone fiddles with it.
  
==Prerequisites==
+
Note that the alarm is disabled when the laptop is suspended or powered off. You can buy external (hardware) motion detector alarms to handle those cases.
  
*hdaps module loaded (comes with kernel 2.6.14 and later)
+
{{WARN|The audio alarm is played at a very high volume. Never enable the alarm while wearing headphones connected to the laptop's speaker output or when the laptop is connected to a high-power amplifier.}}
*sox (SOund eXchange) sound utility
 
*aumix command line mixer
 
 
 
The latter two should be included with your distribution, but check if they are installed.
 
  
 
==A comprehensive script==
 
==A comprehensive script==
Line 17: Line 13:
 
This Perl script periodically samples the tilt data reported by the accelerometer, computes the variance over recent samples, and triggers the alarm when the variance exceeds a given threshold.
 
This Perl script periodically samples the tilt data reported by the accelerometer, computes the variance over recent samples, and triggers the alarm when the variance exceeds a given threshold.
  
On an [[HDAPS]]-equipped laptop running a modern Linux installation with the <tt>hdaps</tt> kernel module loaded, the script should work as is. Just run <tt>./th-theft --arm</tt> and see (or rather, hear) what happens when you tilt your laptop. The volume and alarm sound can be adjusted at the top of the script. On a ThinkPad {{T43}}, the synthetic siren at a volume of 100 (up from the default 70) is quite ear-splitting.
+
On a ThinkPad with [[Active Protection System]] running a modern Linux installation with the [[HDAPS|hdaps]] kernel module loaded, the script should work as is. Just run {{cmdroot|tp-theft --arm}} and see (or rather, hear) what happens when you tilt your laptop.  
  
The script is designed to run continuously in the background, so by default the alarm will be activated only when the KDE screen saver is locked. If you you open the laptop lid (or press the lid button) shortly before or after the beginning of movement, the alarm will be suspended (except for a brief warning) and you will get a few seconds of grace to unlock the screen saver (preferably, [[How to enable the fingerprint reader|using the integrated fingerprint reader]]!). You can disable this functionality by passing the "--arm" parameter, by setting <tt>$use_kde=0</tt> and <tt>$use_lid=0</tt>, or by using the simpler script below.
+
The volume and alarm sound can be adjusted at the top of the script. On a ThinkPad {{T43}}, the synthetic siren at <tt>$alarm_volume=100</tt> (up from the default 70) is quite ear-splitting, and combined with <tt>$acpi_volume=15</tt> it is dangerously loud.
  
<pre>
+
The script is designed to run continuously in the background, so by default the alarm will be activated only when the KDE screen saver is locked. If you you open the laptop lid (or press the lid button) shortly before or after the beginning of movement, the alarm will be suspended (except for a brief warning) and you will get a few seconds of grace to unlock the screen saver (preferably, [[How to enable the integrated fingerprint reader|using the integrated fingerprint reader]]!). You can disable this functionality by passing the <tt>--arm</tt> parameter, by setting <tt>$use_kde=0</tt> and <tt>$use_lid=0</tt>, or by using the simpler script below.
#!/usr/bin/perl
 
#
 
# tp-theft v0.2.1 (http://thinkwiki.org/wiki/Script_for_theft_alarm_using_HDAPS)
 
# Provided under the GNU General Public License version 2 or later or
 
# the GNU Free Documentation License version 1.2 or later, at your option.
 
# See http://www.gnu.org/copyleft/gpl.html for the Warranty Disclaimer.
 
  
# This script uses the HDAPS accelerometer found on recent ThinkPad models
+
There is also an option to track a BlueTooth device (e.g., a mobile phone). In this case, the alarm is activated (and optionally, the KDE desktop is locked) whenever the device is turned off or too distant for a given period, and deactivated when the BlueTooth device is nearby. You need to provide the device's BD address. If both KDE screen saver and BlueTooth checking are enabled, then the alarm will be activated when *either* the screensaver is enabled or the BlueTooth device is amiss.
# to emit an audio alarm when the laptop is tilted. In sufficiently
 
# populated environments, it can be used as a laptop theft deterrent.
 
# Uses a state machine and some heuristics to reduce false alarms.
 
#
 
# By default the alarm will be activated only when the KDE screen saver is
 
# locked. If you you open the laptop lid (or press the lid button) shortly
 
# before or after the beginning of movement, the alarm will be suspended
 
# (except for a brief warning) and you will get a few seconds of grace to
 
# unlock the screen saver. You can disable this functionality by passing
 
# the "--arm" parameter, or by setting  $use_kde=0  and  $use_lid=0 .
 
  
use strict;
+
===Prerequisites===
use warnings;
 
use FileHandle;
 
use Time::HiRes qw(usleep time);
 
  
##############################
+
* ThinkPad with [[Active Protection System]]
# Siren volume and content
+
* [[HDAPS|hdaps]] kernel module loaded (included in kernel 2.6.14 and later)
 +
* Optional: [[ibm-acpi|ibm_acpi]] module loaded with the <tt>experimental=1</tt> parameter (included in kernel 2.6.14 and later; needed only for full volume control)
 +
The following are included in all modern Linux distributions:
 +
* ALSA sound system, <tt>alsactl</tt>, <tt>aplay</tt>, <tt>amixer</tt> )
 +
* <tt>sox</tt> (SOund eXchange) sound utility
  
# Alarm audio volume (0..100)
+
===The script===
my $alarm_volume = 70;
+
{{CodeRef|tp-theft}}
# Alarm command (default: synthesize a siren for 1.0 seconds):
 
my $alarm_cmd = "sox -t nul /dev/null -t ossdsp /dev/dsp synth 1.0 sine 2000-4000 sine 4000-2000";
 
# my $alarm_cmd = "play keep_your_hands_off_me.wav";
 
  
# Warning audio volume (0..100)
+
==A basic script==
my $warn_volume = 45;
 
# Alarm command (default: synthesize a biref siren):
 
my $warn_cmd = "sox -t nul /dev/null -t ossdsp /dev/dsp synth 0.05 sine 2000-4000 sine 4000-2000";
 
# my $warn_cmd = "play dump.wav";
 
  
 +
This is a simpler version of the above script, which omits the fancier functionality such as KDE screensaver detection, lid detection and state machine.
  
##############################
+
===Prerequisites===
# Activation control
 
  
# Tilt threshold (increase value to decrease sensitivity):
+
* ThinkPad with [[Active Protection System]]
my $thresh = 0.20;
+
* [[HDAPS|hdaps]] kernel module loaded (included in kernel 2.6.14 and later)
# Minimum movement duration between warning and alarm:
+
* <tt>aumix</tt> mixer control utility (included in all modern Linux distributions)
my $min_hold = 1.3;
+
* <tt>sox</tt> (SOund eXchange) sound utility (included in all modern Linux distributions, e.g. packages "sox" and "libsox-fmt-oss" in Ubuntu)
# When armed, any movement triggers alarm. How long should it remain armed?
+
* in newer Versions of sox (e.g. shipped with current Ubuntu), the used parameters are no longer supported. You have to replace "-t nul /dev/null" with "-n" in line 19.
my $arm_persist = 6;
 
  
# Activate according to KDE screen saver? Otherwise, always active:
+
===The script===
my $use_kde = 1;
 
# When screen saver locked, wait this long before activation:
 
my $kde_lock_delay = 8;
 
  
# Provide grace period if laptop lid is opened?
+
{{CodeRef|tp-theft-basic}}
my $use_lid = 1;
 
# Opening a lid will grant this many seconds of grace (once):
 
my $lid_grace = 7;
 
# Lid must to be opened within this time to hold/pause alarm:
 
my $lid_grace_window = 8;
 
# Alarm will hold off this long when grace is available:
 
my $lid_hold = 3;
 
# After this many seconds of no movement, will allow grace again:
 
my $grace_relax = 15;
 
  
 +
== LCARS edition ==
 +
The simple script modified to show a [http://memory-alpha.org/wiki/LCARS LCARS] red alert flash animation from Star Trek Voyager instead of a beep.
  
##############################
+
===Prerequisites===
# Other vars
+
* ThinkPad with [[Active Protection System]]
 +
* [[HDAPS|hdaps]] kernel module loaded (included in kernel 2.6.14 and later)
 +
* <tt>gtk-gnash</tt> [http://www.gnashdev.org/ Gnash] a GNU SWF movie player
 +
* internet connection to get the swf from http://lcars.org.uk (you may download the file and adjust the path)
  
my $interval = 0.1;  # sampling intervalm in seconds
+
===The script===
my $depth = 10;      # number of recent samples to analyze
 
my $verbose = 2;    # 0=nothing, 1=alarms, 2=state transitions, 3=everything
 
my $kde_check_interval = 1.5; # KDE screen saver check is expensive
 
my $pos_file = '/sys/devices/platform/hdaps/position';
 
my $lid_file = '/proc/acpi/button/lid/LID/state';
 
  
##############################
+
{{CodeRef|tp-theft-lcars}}
# Utility functions
 
  
sub say {
+
==Ideas for improvement==
    my ($verb, $what) = @_;
+
Features awaiting contribution:
    print(gmtime().": $what\n") if $verb<=$verbose;
 
}
 
  
sub slurp { # read whole file
+
===Activation===
    my ($filename) = @_;
+
* Gnome and xscreensaver support (similarly to [http://fdd.com/software/radeon/lightwatch.pl lightwatch.pl]?)
    local $/;
+
* Monitor X server presence  and make noise on sudden X server shutdown (i.e. catch {{key|ctrl}}{{key|alt}}{{key|backspace}} events).
    my $fh = new FileHandle("$filename","<") or return;
+
Already done !* Monitor AC power and take it into account for alarm activation -- thieves seldom carry a UPS.
    return <$fh>;
+
* Don't arm the alarm if movement of similar magnitude was happening also before the screensaver was auto-locked (the owner might be in a moving vehicle, etc.).
}
+
* Disarm the alarm (or hold it off for a few seconds, as already implemented for lid open) based on voice/sound recognition using the built-in microphone.
 +
* Use fingerprint reader to disarm the alarm.
  
sub stddev { # standard deviation of list
+
===Precaution===
    my $sum=0;
+
* Disable the alarm when headphones are plugged in -- it may cause hearing damage (if the user ignores the initial warning), and won't be effective anyway. '''Can we detect whether the something is plugged into the headphones/line-out socket?'''
    my $sumsq=0;
+
* Theft attempts may be accompanied by rough handling, especially when the siren kicks in. So when starting an alarm also park the disk heads. Release the parking when a key is pressed (according {{path|/sys/bus/platform/drivers/hdaps/hdaps/keyboard_activity}}) so that the login prompt can start up. This requires kernel support for disk head parking and queue freezing, currently developed for the (original) HDAPS functionality.
    my $n=$#_+1;
 
    for my $v (@_) {
 
        $sum += $v;
 
        $sumsq += $v*$v;
 
    }
 
    return sqrt($n*$sumsq - $sum*$sum)/($n*($n-1));
 
}
 
  
my $alarm_file; # flags ongoing alarm (and also stores saved mixer settings)
+
===Indication===
sub sound_alarm {
+
* Use XOSD to ivisually ndicate state changes.
    my ($name, $volume, $cmd) = @_;
+
* Use TrayIcon to indicate state changes.
    return if (defined($alarm_file) && -f $alarm_file);
+
* Use Notifications to indicate state changes.
    say(1,$name);
 
    $alarm_file = `mktemp /tmp/tp-theft-sem.XXXXXXXX` or die "mktemp: $?";
 
    chomp($alarm_file);
 
    system('/bin/bash', '-c', <<"EOF")==0 or die "Failed: $?";
 
( trap \"aumix -L -f $alarm_file > /dev/null; rm -f $alarm_file" EXIT HUP QUIT TERM
 
  aumix -S -f $alarm_file &&
 
  aumix -v $volume -w 100 &&
 
  $cmd ) &
 
EOF
 
}
 
  
 +
===Lockdown===
 +
* Disable the volume buttons when the script is running so that a thief can't just turn the volume down. (Not an issue when <tt>ibm_acpi</tt> volume control is available - see [[#Prerequisites|Prerequisites]].)
 +
* Disable suspend and powersaving measures when armed.
 +
* Disable poweroff (to the extent possible) when armed - or at least use the two seconds the power button acpi function comes active before poweroff to make as much noise as possible (it may take a while for a casual thief to actully remove the battery).
  
##############################
+
===Alert===
# KDE screen saver lock check
+
* Start out quietly, and increase siren duration and volume if movement persists. Reset after a period of no movement.
 
+
* Report theft via network (if you get a chance to):
if ($use_kde) { # Basic sanity check
+
**Check for presence of wired or open wireless network and connect if not already connected.
    `/sbin/pidof kdesktop`; $?==0 or die "Can't use KDE, it's not running.\n";
+
**Send eMail to email to sms gateway or use an online sms service.
}
+
**If builtin webcam is present, take shots and upload them to a server or send via email. (This could be activated over a reboot, so that even if the thief gets away with the laptop, it would still be somewhat traceable.)
 
+
**If WAN of GPS devices are present, use it to detect position to a web server.
sub kdesktop_lock_status {
+
* When the alarm is triggered, also show a visual warning on the display. Override screensaver/powersaving if necessary. I.e., inform the thief that the notebook has a power on password and is useless without it. (This can be done by selecting a dedicated screensaver for that purpose.)
    # See if kdesktop_lock is running and check its cmdline and automatic lock delay
+
* Eject optical drive to irritate and hence slow down the thief.
    my $bin = '/usr/bin/kdesktop_lock';
 
    my $pids = `/sbin/pidof $bin`;
 
    return 'off' unless $?==0;
 
    for my $pid (split(/\s+/,$pids)) {
 
        next unless $pid =~ m/^\d+$/;
 
        # Attached to display ":0" or "localhost:0"?
 
        my $environ = slurp("/proc/$pid/environ") or next;
 
        my $good=0; my $home;
 
        for (split(/\x00/,$environ)) {
 
            $good=1 if m/^DISPLAY=(localhost)?:0$/;
 
            $home=$1 if m/^HOME=(.+)$/;  # also remember its $HOME
 
        }
 
        next unless $good;
 
        # Check command line
 
        my $cmdline = slurp("/proc/$pid/cmdline") or next;
 
        $cmdline =~ m/^[^\x00]+\x00(?:([^\x00]+)\x00)?/ or die "Cannot parse $bin command line\n";
 
        if (!defined($1)) {
 
            # Read KDE screensaver lock time
 
            defined($home) or die "Cannot find HOME in environment of $bin process";
 
            my $rc_path = "$home/.kde/share/config/kdesktoprc";
 
            my $rc = new FileHandle($rc_path,"<") or die "Error opening $rc_path: $!";
 
            while (<$rc>) { m/^LockGrace=(\d+)$/ and return ('auto', $1/1000.0); };
 
            die "Cannot parse $rc_path";
 
        } elsif ($1 eq '--forcelock') {
 
            return "force";
 
        }
 
    }
 
    return 'off';
 
}
 
 
 
my $last_kls_update = 0; # time of last update
 
my $last_kls = 'init';  # last state seen
 
my $last_kls_start;      # when that state started
 
 
 
sub check_kde_lock {
 
    # De/activate according to KDE screen saver:
 
    my $now=time();
 
    return if $now < $last_kls_update + $kde_check_interval;
 
    my ($kls, $auto_delay) = kdesktop_lock_status();
 
    $last_kls_update = time();
 
    if ($kls ne $last_kls) {
 
        $last_kls = $kls;
 
        $last_kls_start = $now;
 
    }
 
    if ($kls eq 'off') { # no screen saver
 
        return(0, 'KDE screen saver not locked');
 
    } elsif ($kls eq 'auto') { # screen saver with automatic lock
 
        if ($now >= $last_kls_start + $auto_delay + $kde_lock_delay) {
 
            return(1, 'KDE screen saver is auto-locked');
 
        }
 
    } elsif ($kls eq 'force') { # screen saver with forced lock
 
        if ($now >= $last_kls_start + $kde_lock_delay) {
 
            return(1, 'KDE screen saver is forced-locked');
 
        }
 
    }
 
}
 
  
 +
===Other===
 +
* Implement this functionality in the embedded controller, so that the alarm will work even when the laptop is suspended. It may be possible to do so without IBM/Lenovo's involvement, using the [http://forum.thinkpads.com/viewtopic.php?t=20958 embedded controller disassembly].
 +
* On Ubuntu, some of the paths don't work. alsactl is in /sbin, not /usr/sbin, and pidof is in /bin, not /sbin. These probably shouldn't be hardcoded paths. (Fix: create symlinks)
  
##############################
+
==Pitfalls (and solutions?)==
# Lid checking
+
* The audible alarm can always be suppressed by plugging earphones into the audio-jack (could be dealt with if software override for the audio-jack diversion is possible).
 +
* The power button can be held to hard poweroff the notebook (can be avoided by using usb/bluetooth detection, closing the lid and sounding alarm if lid is opened before the usb/bluetooth device is present).
 +
* The thief can unplug the battery to hard poweroff the notebook (can't do anything about it, but to set the alarm settings so that it goes off quickly - i.e., when using bluetooth detection, disable grace-period if activated manually)
  
if ($use_lid) { # sanity check
+
==Another Script (plugin-based)==
    slurp($lid_file) or die "Can't use lid via $lid_file: $!";
+
there's another script with the same intention available at http://www.informatik.hu-berlin.de/~pilop/HOWTO_Gentoo_T43/#TheftAlarm
}
 
  
my $last_lid_status = 'open';
+
it uses a plugin-architecture for different checks (HDAPS, ethernet, power, lid, ...)
my $last_lid_open = 0;
 
  
sub check_lid {
+
==Yet another script (python/gtk based)==
    my $lid = slurp($lid_file) or return;
+
You can find yet another version of this script at
    if ($lid =~ m/state: *open$/) {
 
        $last_lid_open = time() if ($last_lid_status eq 'closed');
 
        $last_lid_status = 'open';
 
    } else {
 
        $last_lid_status = 'closed';
 
    }
 
}
 
  
 +
http://r3blog.nl/index.php/thinkpad-theft
 +
(source at https://bitbucket.org/trbs/thinkpad-theft/overview/)
  
##############################
+
It has almost the same features as the comprehensive script above, with a few improvements. It uses dbus to query the screensaver status and gconf for storing configuration value. To improve the delay before the alarm sounds, it has a built-in wav player, and it opens the file-descriptor of the wav at startup time (thereby removing the need to spawn an application to play the alarm; imagine someone stealing your laptop while you're doing heavy disk io). Furthermore, it has a trayicon allowing you to manipulate most settings stored in gconf aswell as showing you the current status of the alarm. The 0.2 release features activation on missing presence of a bluetooth or usb device.
# Main code
 
  
my $state;
+
There is a [https://bitbucket.org/trbs/thinkpad-theft/overview new repository] at BitBucket that has seen some patches to fix problems with the unstable dbus-screensaver api and more.
my %state_names=(0=>'disabled    ',
 
                1=>'active+grace',
 
                2=>'active      ',
 
                3=>'hold+grace  ',
 
                4=>'armed+grace ',
 
                5=>'hold        ',
 
                6=>'armed      ',
 
                7=>'armed-force '  );
 
my $state_end = 0;
 
my $last_tilt = 0;
 
  
sub set_state {
+
==Conceptional thoughts==
    my ($st,  $why) = @_;
+
The above feature improvement suggestions partly require the theft protection software to be running as root (ACPI and hardware management), partly to be running as user (DBus SessionBus communications). Hence the following approach would be the one opening for the most coverage:
    say(2, "state=[".$state_names{$st}."]  ($why)");
+
*theft-protection-daemon; run as root by init; controlling config, system related activation, lockdown and alarm
    $state = $st;
+
*theft-protection-trayicon; run in user-session; reporting desktop related activation criteria to the daemon and giving visual user feedback on the desktop
}
+
*theft-protection-properties; runnable as user; reporting configuration changes to daemon
  
sub get_pos {
+
Ideally, they would provide a plugin-system, with plugins consisting of a functional and a gui part.
    my $pos = slurp($pos_file) or die "Can't open HDAPS file $pos_file: $!\n";
+
With this scheme, the theft protection can't be circumvented i.e. by pressing {{key|ctrl}}{{key|alt}}{{key|backspace}}.
    $pos =~ m/^\((-?\d+),(-?\d+)\)$/ or die "Can't parse $pos_file content\n";
 
    return ($1,$2);
 
}
 
 
 
 
 
for (@ARGV) {
 
    m/^--arm/ && do { set_state(7, "arm forced"); $use_lid=0; $use_kde=0; last; };
 
    die "Unknown parameter\n";
 
}
 
set_state($use_lid?1:2, "init") if !defined($state);
 
 
 
# Initial sensor read:
 
my (@XHIST, @YHIST);
 
my ($x,$y) = get_pos;
 
for (1..$depth) {
 
    push(@XHIST,$x);
 
    push(@YHIST,$y);
 
}
 
 
 
while (1) {
 
    usleep($interval*1000000);
 
 
 
    # Collect data:
 
    my $now = time();
 
    my ($x,$y) = get_pos;
 
    shift(@XHIST); push(@XHIST,$x);
 
    shift(@YHIST); push(@YHIST,$y);
 
    check_lid() if $use_lid;
 
    if ($use_kde && (my ($op, $why) = check_kde_lock())) {
 
        set_state($use_lid?1:2, $why) if $op==1 && $state==0;
 
        set_state(0, $why) if $op==0 && $state>0;
 
    }
 
    next unless $state>0;
 
 
 
    # Analyze:
 
    my $xdev = stddev(@XHIST);
 
    my $ydev = stddev(@YHIST);
 
    say(3,"X: v=$xdev (".join(',',@XHIST).")  Y: v=$ydev (".join(",",@YHIST).")");
 
    my $tilted = ($xdev>$thresh || $ydev>$thresh);
 
    $last_tilt = $now if $tilted;
 
 
 
    # Decide: state machine transitions
 
    if ($state==1) { # active+grace
 
        if ($tilted) {
 
            set_state(3, "motion detected, holding for $lid_hold seconds, open lid for grace");
 
            $state_end = $now + $lid_hold;
 
            sound_alarm("WARNING", $warn_volume, $warn_cmd);
 
        }
 
    } elsif ($state==2) { # active
 
        if ($tilted) {
 
            set_state(5, "motion detected, holding for $min_hold seconds");
 
            $state_end = $now + $min_hold;
 
            sound_alarm("WARNING", $warn_volume, $warn_cmd);
 
        } else {
 
            if ($use_lid && ($now > $last_tilt + $grace_relax )) {
 
                set_state(1, "$grace_relax seconds since last motion, so allowing grace again");
 
            }
 
        }
 
    } elsif ($state==3) { # hold+grace
 
        if ($now < $last_lid_open + $lid_grace) {
 
            set_state(5, "lid opened, holding for $lid_grace seconds grace period");
 
            $state_end = $now + $lid_grace;
 
        } elsif ($now >= $state_end) {
 
            my $delta = $lid_grace_window - $lid_hold;
 
            $state_end = $now + $delta;
 
            set_state(4, "hold ended, arming but allowing grace for $delta more seconds");
 
        }
 
    } elsif ($state==4) { # armed+grace
 
        if ($now < $last_lid_open + $lid_grace) {
 
            set_state(5, "lid opened, holding for $lid_grace seconds grace period");
 
            $state_end = $now + $lid_grace;
 
        } elsif ($now >= $state_end) {
 
            set_state(6, "grace window ended");
 
        }
 
    } elsif ($state==5) { # hold
 
        if ($now >= $state_end) {
 
            set_state(6, "hold ended, arming");
 
        }
 
    } elsif ($state==6) { # armed
 
        if ($now > $last_tilt + $arm_persist) {
 
            set_state(2, "no motion for $arm_persist seconds, unarming");
 
        }
 
    }
 
 
 
    if (($state==4 || $state==6 || $state==7) && $tilted) {
 
        sound_alarm("ALARM", $alarm_volume, $alarm_cmd);
 
    }
 
}
 
</pre>
 
 
 
The [[User:Thinker|author]] of the script makes it available the terms of both the [http://www.gnu.org/copyleft/gpl.html GPL] version 2 or later, or at your option, the [http://www.gnu.org/copyleft/fdl.html GFDL].
 
 
 
==A basic script==
 
 
 
This is a simpler version of the above script, which omits the fancier functionality such as KDE screensaver detection, lid detection and state machine.
 
 
 
<pre>
 
#!/usr/bin/perl
 
# tp-theft v0.1 (http://thinkwiki.org/wiki/Script_for_theft_alarm_using_HDAPS)
 
# This script uses the HDAPS accelerometer found on recent ThinkPad models
 
# to emit an audio alarm when the laptop is tilted. In sufficiently
 
# populated environments, it can be used as a laptop theft deterrent.
 
#
 
# This file is placed in the public domain and may be freely distributed.
 
 
 
use strict;
 
use warnings;
 
 
 
##############################
 
# Siren volume and content
 
 
 
# Audio volume (0..100)
 
my $volume = 70;
 
 
 
# Synthesize a siren for 1.0 seconds:
 
my $play_cmd = "sox -t nul /dev/null -t ossdsp /dev/dsp synth 1.0 sine 2000-4000 sine 4000-2000";
 
 
 
# Play a file:
 
# my $play_cmd = "play keep_your_hands_off_me.wav";
 
 
 
##############################
 
# Other tweakables
 
 
 
my $thresh = 0.20;  # tilt threshold (increase value to decrease sensitivity)
 
my $interval = 0.1;  # sampling interval in seconds
 
my $depth = 10;      # number of recent samples to analyze
 
my $pos_file='/sys/devices/platform/hdaps/position';
 
my $verbose = 1;
 
 
 
##############################
 
# Code
 
 
 
sub get_pos {
 
    open(POS,"<",$pos_file) or die "Can't open HDAPS file $pos_file: $!\n";
 
    $_=<POS>;
 
    m/^\((-?\d+),(-?\d+)\)$/ or die "Can't parse $pos_file content\n";
 
    return ($1,$2);
 
}
 
 
 
sub stddev {
 
    my $sum=0;
 
    my $sumsq=0;
 
    my $n=$#_+1;
 
    for my $v (@_) {
 
$sum += $v;
 
$sumsq += $v*$v;
 
    }
 
    return sqrt($n*$sumsq - $sum*$sum)/($n*($n-1));
 
}
 
 
 
my (@XHIST, @YHIST);
 
my ($x,$y) = get_pos;
 
for (1..$depth) {
 
    push(@XHIST,$x);
 
    push(@YHIST,$y);
 
}
 
my $alarm_file; # flags ongoing alarm (and stores saved mixer settings)
 
 
 
while (1) {
 
    my ($x,$y) = get_pos;
 
    shift(@XHIST); push(@XHIST,$x);
 
    shift(@YHIST); push(@YHIST,$y);
 
    my $xdev = stddev(@XHIST);
 
    my $ydev = stddev(@YHIST);
 
 
 
    # Print variance and history
 
    print "X: v=$xdev (".join(',',@XHIST).")  Y: v=$ydev (".join(",",@YHIST).")\n" if $verbose>1;
 
 
 
    my $tilted = $xdev>$thresh || $ydev>$thresh;
 
 
 
    if ($tilted && !(defined($alarm_file) && -f $alarm_file)) {
 
print "ALARM\n" if $verbose>0;
 
$alarm_file = `mktemp /tmp/hdaps-tilt.XXXXXXXX` or die "mktemp: $?";
 
chomp($alarm_file);
 
system('/bin/bash', '-c', <<"EOF")==0 or die "Failed: $?";
 
( trap \"aumix -L -f $alarm_file > /dev/null; rm -f $alarm_file" EXIT HUP QUIT TERM
 
  aumix -S -f $alarm_file &&
 
  aumix -v $volume -w 100 &&
 
  $play_cmd) &
 
EOF
 
    }
 
 
 
    select(undef, undef, undef, $interval); # sleep
 
}
 
</pre>
 
 
 
The [[User:Thinker|author]] of the script disclaims all warranty for this script, and releases it to the public domain.
 
 
 
==To do==
 
Features awaiting contribution:
 
* Start out quietly, and increase siren duration and volume if movement persists. Reset after a period of no movement.
 
* Gnome and xscreensaver support (similarly to [http://fdd.com/software/radeon/lightwatch.pl lightwatch.pl]?)
 
* Report theft via network (if you get a chance to).
 
* Monitor AC power and take it into account for alarm activation -- thieves seldom carry a UPS.
 
* Monitor proximity to a bluetooth device carried by the owner, and take it into account for alarm activation. I'll implement this if you get [[User:Thinker|me]] a  [[IBM Integrated Bluetooth IV with 56K Modem (BMDC-3)|BMDC-3]] Bluetooth card.
 
  
 
[[Category:Scripts]]
 
[[Category:Scripts]]

Latest revision as of 17:20, 5 August 2011

General

Recent ThinkPad models include a built-in two-axis accelerometer, as part of the HDAPS feature. This accelerometer can be put to another use: as a laptop theft deterrent. The following scripts detect when the laptop is moved, and emits a loud audio alarm.

This alarm can be an effective deterrent against a casual laptop-snatcher in a populated environment (e.g., typical office space). It's also useful when you're across the room from the laptop and want to know if someone fiddles with it.

Note that the alarm is disabled when the laptop is suspended or powered off. You can buy external (hardware) motion detector alarms to handle those cases.

ATTENTION!
The audio alarm is played at a very high volume. Never enable the alarm while wearing headphones connected to the laptop's speaker output or when the laptop is connected to a high-power amplifier.

A comprehensive script

This Perl script periodically samples the tilt data reported by the accelerometer, computes the variance over recent samples, and triggers the alarm when the variance exceeds a given threshold.

On a ThinkPad with Active Protection System running a modern Linux installation with the hdaps kernel module loaded, the script should work as is. Just run # tp-theft --arm and see (or rather, hear) what happens when you tilt your laptop.

The volume and alarm sound can be adjusted at the top of the script. On a ThinkPad T43, the synthetic siren at $alarm_volume=100 (up from the default 70) is quite ear-splitting, and combined with $acpi_volume=15 it is dangerously loud.

The script is designed to run continuously in the background, so by default the alarm will be activated only when the KDE screen saver is locked. If you you open the laptop lid (or press the lid button) shortly before or after the beginning of movement, the alarm will be suspended (except for a brief warning) and you will get a few seconds of grace to unlock the screen saver (preferably, using the integrated fingerprint reader!). You can disable this functionality by passing the --arm parameter, by setting $use_kde=0 and $use_lid=0, or by using the simpler script below.

There is also an option to track a BlueTooth device (e.g., a mobile phone). In this case, the alarm is activated (and optionally, the KDE desktop is locked) whenever the device is turned off or too distant for a given period, and deactivated when the BlueTooth device is nearby. You need to provide the device's BD address. If both KDE screen saver and BlueTooth checking are enabled, then the alarm will be activated when *either* the screensaver is enabled or the BlueTooth device is amiss.

Prerequisites

  • ThinkPad with Active Protection System
  • hdaps kernel module loaded (included in kernel 2.6.14 and later)
  • Optional: ibm_acpi module loaded with the experimental=1 parameter (included in kernel 2.6.14 and later; needed only for full volume control)

The following are included in all modern Linux distributions:

  • ALSA sound system, alsactl, aplay, amixer )
  • sox (SOund eXchange) sound utility

The script

tp-theft (download)

A basic script

This is a simpler version of the above script, which omits the fancier functionality such as KDE screensaver detection, lid detection and state machine.

Prerequisites

  • ThinkPad with Active Protection System
  • hdaps kernel module loaded (included in kernel 2.6.14 and later)
  • aumix mixer control utility (included in all modern Linux distributions)
  • sox (SOund eXchange) sound utility (included in all modern Linux distributions, e.g. packages "sox" and "libsox-fmt-oss" in Ubuntu)
  • in newer Versions of sox (e.g. shipped with current Ubuntu), the used parameters are no longer supported. You have to replace "-t nul /dev/null" with "-n" in line 19.

The script

tp-theft-basic (download)

LCARS edition

The simple script modified to show a LCARS red alert flash animation from Star Trek Voyager instead of a beep.

Prerequisites

The script

tp-theft-lcars (download)

Ideas for improvement

Features awaiting contribution:

Activation

  • Gnome and xscreensaver support (similarly to lightwatch.pl?)
  • Monitor X server presence and make noise on sudden X server shutdown (i.e. catch ctrlaltbackspace events).

Already done !* Monitor AC power and take it into account for alarm activation -- thieves seldom carry a UPS.

  • Don't arm the alarm if movement of similar magnitude was happening also before the screensaver was auto-locked (the owner might be in a moving vehicle, etc.).
  • Disarm the alarm (or hold it off for a few seconds, as already implemented for lid open) based on voice/sound recognition using the built-in microphone.
  • Use fingerprint reader to disarm the alarm.

Precaution

  • Disable the alarm when headphones are plugged in -- it may cause hearing damage (if the user ignores the initial warning), and won't be effective anyway. Can we detect whether the something is plugged into the headphones/line-out socket?
  • Theft attempts may be accompanied by rough handling, especially when the siren kicks in. So when starting an alarm also park the disk heads. Release the parking when a key is pressed (according /sys/bus/platform/drivers/hdaps/hdaps/keyboard_activity) so that the login prompt can start up. This requires kernel support for disk head parking and queue freezing, currently developed for the (original) HDAPS functionality.

Indication

  • Use XOSD to ivisually ndicate state changes.
  • Use TrayIcon to indicate state changes.
  • Use Notifications to indicate state changes.

Lockdown

  • Disable the volume buttons when the script is running so that a thief can't just turn the volume down. (Not an issue when ibm_acpi volume control is available - see Prerequisites.)
  • Disable suspend and powersaving measures when armed.
  • Disable poweroff (to the extent possible) when armed - or at least use the two seconds the power button acpi function comes active before poweroff to make as much noise as possible (it may take a while for a casual thief to actully remove the battery).

Alert

  • Start out quietly, and increase siren duration and volume if movement persists. Reset after a period of no movement.
  • Report theft via network (if you get a chance to):
    • Check for presence of wired or open wireless network and connect if not already connected.
    • Send eMail to email to sms gateway or use an online sms service.
    • If builtin webcam is present, take shots and upload them to a server or send via email. (This could be activated over a reboot, so that even if the thief gets away with the laptop, it would still be somewhat traceable.)
    • If WAN of GPS devices are present, use it to detect position to a web server.
  • When the alarm is triggered, also show a visual warning on the display. Override screensaver/powersaving if necessary. I.e., inform the thief that the notebook has a power on password and is useless without it. (This can be done by selecting a dedicated screensaver for that purpose.)
  • Eject optical drive to irritate and hence slow down the thief.

Other

  • Implement this functionality in the embedded controller, so that the alarm will work even when the laptop is suspended. It may be possible to do so without IBM/Lenovo's involvement, using the embedded controller disassembly.
  • On Ubuntu, some of the paths don't work. alsactl is in /sbin, not /usr/sbin, and pidof is in /bin, not /sbin. These probably shouldn't be hardcoded paths. (Fix: create symlinks)

Pitfalls (and solutions?)

  • The audible alarm can always be suppressed by plugging earphones into the audio-jack (could be dealt with if software override for the audio-jack diversion is possible).
  • The power button can be held to hard poweroff the notebook (can be avoided by using usb/bluetooth detection, closing the lid and sounding alarm if lid is opened before the usb/bluetooth device is present).
  • The thief can unplug the battery to hard poweroff the notebook (can't do anything about it, but to set the alarm settings so that it goes off quickly - i.e., when using bluetooth detection, disable grace-period if activated manually)

Another Script (plugin-based)

there's another script with the same intention available at http://www.informatik.hu-berlin.de/~pilop/HOWTO_Gentoo_T43/#TheftAlarm

it uses a plugin-architecture for different checks (HDAPS, ethernet, power, lid, ...)

Yet another script (python/gtk based)

You can find yet another version of this script at

http://r3blog.nl/index.php/thinkpad-theft (source at https://bitbucket.org/trbs/thinkpad-theft/overview/)

It has almost the same features as the comprehensive script above, with a few improvements. It uses dbus to query the screensaver status and gconf for storing configuration value. To improve the delay before the alarm sounds, it has a built-in wav player, and it opens the file-descriptor of the wav at startup time (thereby removing the need to spawn an application to play the alarm; imagine someone stealing your laptop while you're doing heavy disk io). Furthermore, it has a trayicon allowing you to manipulate most settings stored in gconf aswell as showing you the current status of the alarm. The 0.2 release features activation on missing presence of a bluetooth or usb device.

There is a new repository at BitBucket that has seen some patches to fix problems with the unstable dbus-screensaver api and more.

Conceptional thoughts

The above feature improvement suggestions partly require the theft protection software to be running as root (ACPI and hardware management), partly to be running as user (DBus SessionBus communications). Hence the following approach would be the one opening for the most coverage:

  • theft-protection-daemon; run as root by init; controlling config, system related activation, lockdown and alarm
  • theft-protection-trayicon; run in user-session; reporting desktop related activation criteria to the daemon and giving visual user feedback on the desktop
  • theft-protection-properties; runnable as user; reporting configuration changes to daemon

Ideally, they would provide a plugin-system, with plugins consisting of a functional and a gui part. With this scheme, the theft protection can't be circumvented i.e. by pressing ctrlaltbackspace.