#!/usr/bin/perl -w
#
# Copyright (C) 2004  Thomer M. Gil (lockout@thomer.com)
# 
# This program is free software. You may distribute it under the terms of
# the GNU General Public License as published by the Free Software
# Foundation, version 2.
# 
# This program 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.
#

=head1 NAME

lockout - avoid slacking and impose productivity and discipline on yourself

=head1 WARNING

This program is VERY DANGEROUS.  If it fails, you may end up not knowing the
root password to your own computer (in which case you need to boot into
single-user mode).  There are no known reports of this actually happening, but
we don't know how stupid you are.  Also, you should probably not run this on a
multi-user system.

=cut

=head1 SYNOPSIS

 lockout lock HhMm | Hh | Mm
 lockout lock HH:MM
 lockout lock HH:MMam | HH:MMpm
 lockout lock HHam | HHpm
 lockout lock
 
 lockout unlock [force]
 
 lockout status

=cut

=head1 DESCRIPTION

Lockout is a tool that imposes discipline on you so that you get some work
done.  For example, lockout can be used to install a firewall that does not
let you browse the Web.  Lockout changes the root password for a specified
duration; this prevents you from secretly ripping down the firewall and then
browsing the Web anyway.  In case of an emergency, you can reboot your
computer to undo the effects of lockout and to restore the original root
password.

Obviously, B<lockout lock> and B<lockout unlock> can only be run by root.
B<lockout status> can be run by any user.

B<lockout> without any parameters shows a brief help message.

B<lockout lock> takes one optional parameter.  If no parameter is given, you
are dropped in interactive mode and asked for the duration of the lock or the
time at which the lock should be lifted.  You can also supply this as a
parameter on the command line.  Lockout understands various time formats.  You
can specify a delay, e.g., I<3h> (3 hours), I<1h30m> (1 hour and 30 minutes),
or I<90m> (1 hour and 30 minutes), or you can specify absolute time, e.g.,
I<2pm>, I<2:30am>, I<15:30>, etc.  You will be asked to confirm the time at
which lockout will unlock your system.  If you type "yes", lockout executes
F</etc/lockout/lock.sh> and changes the root password to something completely
random.  F</etc/lockout/lock.sh> is a shell script that you write.  It takes
measures to make sure you stop slacking.  For example, it could install a
firewall that prevents outgoing connections to port 80.  See the L</EXAMPLES>
section below.

B<lockout unlock> takes an optional I<force> parameter.  Without any
parameters, B<lockout lock> will check whether it is time to unlock the system
and, if so, executes F</etc/lockout/unlock.sh>, which is a shell script that
you write.  It should undo the effects of F</etc/lockout/lock.sh>, executed
when the system was locked.  If you pass the I<force> parameter to B<lockout
unlock>, lockout will forcibly unlock your system, whether it was really time
for that or not.  B<lockout unlock> should be called every minute by cron.
See L</CONFIGURATION>.

B<lockout status> will print out the time at which the system is going to
be unlocked.

=cut

=head1 CONFIGURATION

/etc/cron.d/lockout B<must> contain the following two entries:

    */1 * * * *	        root	/usr/bin/lockout unlock >/dev/null 2>&1
    @reboot	        root	/usr/bin/lockout unlock force >/dev/null 2>&1

The examples that follow assume you are using L<sudo(8)> and you have a file,
F</etc/lockout/sudoers.normal> which is the normal F</etc/sudoers> file, and
F</etc/lockout/sudoers.lock>, which is the F</etc/sudoers> file when lockout
locks your computer.  This example also assumes you are using L<iptables(8)>.
F</var/lib/iptables/active> should contain your default firewall rules, and
F</var/lib/iptables/work> should contain the firewall rules that enforce
discipline.  See below for an example.

F</etc/lock/lock.sh> imposes discipline.  For example:

    #!/bin/sh
    /etc/init.d/iptables load work
    cp /etc/lockout/sudoers.lock /etc/sudoers
    /etc/init.d/sudo stop
    /etc/init.d/sudo start

F</etc/lock/unlock.sh> undoes these effects.  For example:

    #!/bin/sh
    /etc/init.d/iptables restart
    cp /etc/lockout/sudoers.normal /etc/sudoers
    /etc/init.d/sudo stop
    /etc/init.d/sudo start

Your F</var/lib/iptables/work> may look something like this:

    *filter
    :INPUT ACCEPT [1047:99548]
    :FORWARD ACCEPT [0:0]
    :OUTPUT ACCEPT [1104:120792]
    
    # allow incoming packets from localhost, ntp,
    # and existing connections
    -A INPUT -i lo -j ACCEPT
    -A INPUT -p udp -m udp --source-port ntp -m state --state ESTABLISHED -j ACCEPT
    -A INPUT -m state --state ESTABLISHED -j ACCEPT
    -A INPUT -p tcp -j DROP
    -A INPUT -p udp -j DROP
    
    # allow outgoing connections for email and DNS
    -A OUTPUT -d 127.0.0.1/8 -j ACCEPT
    -A OUTPUT -p tcp -m tcp --dport smtp -j ACCEPT
    -A OUTPUT -p tcp -m tcp --dport domain -j ACCEPT
    -A OUTPUT -p udp -m udp --dport domain -j ACCEPT
    -A OUTPUT -j DROP
    COMMIT

=cut

=head1 EXAMPLES

    lockout lock 2h30m   [locks out for 2h and 30m]
    lockout lock 90m     [locks out for 1h and 30m]
    lockout lock 3pm     [locks out until 3pm]
    lockout lock 3:20am  [locks out until 3:20am]
    lockout lock 15:20   [locks out until 3:20pm]

    lockout status       [shows when the system is going to be unlocked]

=cut

=head1 FILES

F</etc/lockout/lock.sh>: executed when running B<lockout lock>

F</etc/lockout/unlock.sh>: executed when running B<lockout unlock>

=cut

=head1 SEE ALSO

L<usermod(8)>, L<iptables(8)>, L<passwd(1)>, L<cron(8)>, L<crontab(1)>

=cut

=head1 BUGS

Arguably, a program that changes the root password to something random with
the possibility of never recovering the original password might be considered
a bug by itself.  Other than that, no known bugs.

=cut

=head1 AUTHOR

Thomer M. Gil, http://thomer.com/lockout/

=cut

#
# MANUAL INSTALLATION INSTRUCTIONS
#
#    0.  Become root
#    1.  Place this file in /usr/bin/
#    2.  chmod 755 /usr/bin/lockout
#    3.  mkdir -p /etc/lockout/
#    4.  chmod 700 /etc/lockout/
#    5.  touch /etc/lockout/lock.sh
#        [see manual page for example contents]
#    6.  touch /etc/lockout/unlock.sh
#        [see manual page for example contents]
#    7.  chmod 700 /etc/lockout/*.sh
#    8.  make bloody sure cron daemon is running.  Always.
#    9.  create a file /etc/cron.d/lockout (permission -rw-r--r--) and add the
#        following two entries to it:
#
#    ---------------------------------------------------------------------
#    #
#    # NB: do not remove!  removing these entries will cause lockout to fail,
#    # which means that you may end up not knowing your root password.
#    #
#    */1 * * * *   root    /usr/bin/lockout unlock >/dev/null 2>&1
#    @reboot       root    /usr/bin/lockout unlock force >/dev/null 2>&1
#    ---------------------------------------------------------------------
#    (Or whatever the correct path to lockout is.)
#

use Fcntl;

#
# the user-supplied script that does everything to impose labor
#
my $LOCK_SCRIPT = "/etc/lockout/lock.sh";

#
# the user-supplied script that undoes everything that LOCK_SCRIPT does
#
my $UNLOCK_SCRIPT = "/etc/lockout/unlock.sh";

#
# where the original crypted root password is stored
#
my $PW_FILE = "/root/.lockfile";

#
# where the unlock time is stored.  used for "lockout status"
#
my $UNLOCK_TIME_FILE = "/tmp/lockout.XXX";

#
# root's crontab
#
my $CRONTAB = "/etc/cron.d/lockout";

#
# program used to change password
#
my $USERMOD = "/usr/sbin/usermod";


#
#
# DO NOT EDIT ANYTHING BELOW THIS LINE
#
#

my $TIME = 0;
my $MODE = "lock"; # or unlock, or status
my $FORCE = "";
my $VERSION = "0.2.3";
my $MAGIC_STRING = "09lsk082slaslkfhjl828u24kjx098";

sub lock {
  print "Only root can run 'lockout lock'.\n" and exit -1 if $>;

  # are there calls to unlock?
  open CRONTAB, "<$CRONTAB" or die "Couldn't check $CRONTAB.";
  my ($unlock, $unlock_force) = (0, 0);
  while(<CRONTAB>) {
    my $valid = 0;
    /^\s*\*\/1\s+\*\s+\*\s+\*\s+\*\s+root\s+(\S+)\s+unlock\s*.*$/ and $valid = $unlock = 1;
    /^\s*\@reboot\s+root\s+(\S+)\s+unlock\s+force\s*.*$/ and $valid = $unlock_force = 1;

    if($valid) {
      -x $1 or print "$1 does not exist or is not executable.  run 'crontab -u root -e'\n" and exit -1;
      &is_us($1) or print "Hm.  $1 in $CRONTAB looks right, but the MAGIC STRING is wrong.\n";
    }
  }
  close CRONTAB;
  unless($unlock && $unlock_force) {
    print <<EOF;
Your $CRONTAB should contain:

/1 * * * *	root	/usr/bin/lockout unlock
\@reboot	root	/usr/bin/lockout unlock force
EOF
    exit -1;
  }

  # can we do this?
  -f $PW_FILE and print "Already locked.  Unlock first with 'lockout unlock force'.\n" and exit -1;
  -x $LOCK_SCRIPT or print "Warning: no executable $LOCK_SCRIPT found.\n";
  -x $UNLOCK_SCRIPT or print "Warning: no executable $UNLOCK_SCRIPT found.\n";
  -x $USERMOD or print "Error: $USERMOD not found or not executable.\n" and exit -1;

  $| = 1;
  my $release_time = $TIME + (60 - ($TIME % 60));
  print "You are going to be locked out until: " . localtime($release_time) . ".\n";
  print "Are your sure? (yes/no) ";
  chomp(my $answer = <>);
  $answer =~ m/yes/ or return 0;

  srand(time() ^ ($$ + ($$ << 15)));

  # old password
  my ($name, $oldpass) = getpwent;
  $name eq "root" or die "Dazed and confuzed because name isn't root.";

  # write rescue file
  sysopen(UNLOCK, $PW_FILE, O_WRONLY | O_TRUNC | O_CREAT, 0600)
    or die "Couldn't open unlock file: $!";
  print UNLOCK "$TIME\n$oldpass\n";
  close UNLOCK;

  # write UNLOCK TIME
  sysopen(UNLOCK, $UNLOCK_TIME_FILE, O_WRONLY | O_TRUNC | O_CREAT)
    or die "Couldn't open unlock-time file: $!";
  print UNLOCK "$release_time\n";
  close UNLOCK;
  chmod 0644, $UNLOCK_TIME_FILE;

  # change the password
  &change_password(&random_key());

  # execute the user-supplied lock script
  system $LOCK_SCRIPT;

  return 1;
}


sub unlock {
  print "Only root can run 'lockout unlock'.\n" and exit -1 if $>;

  # read time and pass
  open UNLOCK, $PW_FILE or print "Couldn't open the unlock file.  The system probably wasn't locked.\n" and exit -1;
  chomp(my $time = <UNLOCK>);
  chomp(my $pass = <UNLOCK>);
  close UNLOCK;

  # don't unlock if it's too early.  force argument overrides this.
  time < $time and return 0 unless $FORCE;

  &change_password($pass);

  -x $UNLOCK_SCRIPT and system $UNLOCK_SCRIPT;
  unlink $PW_FILE;
  unlink $UNLOCK_TIME_FILE;

  return 1;
}


sub status {
  open FILE, "<$UNLOCK_TIME_FILE"
    or print "It seems your system is not locked.\n" and return;
  chomp(my $time = <FILE>);
  close FILE;

  if($time > time) {
    my ($h) = split /\./, (($time - time)/3600);
    my ($m) = split /\./, ((($time - time) % 3600)/60);
    my $s = ($time - time)%60;
    print "Locked until: " . localtime($time) . ". ";
    $h and print $h . "h ";
    ($m || ($h && $s)) and print $m . "m ";
    $s and print $s . "s ";
    print "to go.\n";
  } elsif(time - $time <= 10) {
    print "System is being unlocked now.\n";
  } else {
    print <<EOF;

Your system should have been unlocked by now.  Is cron running?  If not, you
might have a problem.  Try rebooting your machine first.  If that doesn't
restore the root password, try booting in single user mode to change the
password.  Good luck.
EOF
  }
}



sub change_password {
  my ($pass) = @_;
  system "$USERMOD -p '$pass' root";
}


sub random_key {
  my $key = "";
  for(my $i=0; $i<32; $i++) {
    my $c = "";
    my $r = rand();
                                                                                
    if($r < 0.33) {
      # lower case char
      $c .= sprintf("%c", int(rand 26) + 65);
    } elsif($r < 0.66) {
      # number
      $c .= sprintf("%u", int(rand 9) + 1);
    } else {
      # upper case char
      $c .= sprintf("%c", int(rand 26) + 97);
    }
    $key .= $c;
  }
                                                                                
  return $key;
}


sub is_us {
  my ($path) = @_;
  my $help = `$path`;
  $help =~ m/MAGIC STRING:\s+(\S+)/m;
  $1 eq $MAGIC_STRING and return 1;
  return 0;
}


# computes the number of seconds between now and the given time
sub delay {
  my ($h, $m, $ap) = @_;
  my ($nows, $nowm, $nowh) = (localtime(time))[0..2];

  defined $ap && $ap =~ m/pm/i && $h < 12 and $h += 12;
  defined $ap && $ap =~ m/am/i && $h == 12 and $h = 24;

  my $now = $nowh * 3600 + $nowm * 60 + $nows;
  my $then = $h * 3600 + $m * 60;

  if($then > $now) {
    return $then - $now;
  } elsif($then < $now) {
    return 24 * 3600 - ($now - $then);
  }
  return 0;
}


sub process_args {
  my @args = @_;

  $MODE = shift @args;
  $MODE and $MODE =~ m/lock|unlock|status/ or &usage() and exit -1;

  if($MODE eq "lock") {
    my $time_str = shift @args;

    while(1) {
      if(!defined $time_str) {
        print "Time ('?' for help, 'q' to quit): ";
        chomp($time_str = <>);
      }

      if($time_str =~ m/^\s*q\s*$/) {
        exit 0;
      } elsif ($time_str =~ m/^\s*\?\s*$/) {
        &usage();
        $time_str = undef;
        next;
      } elsif ($time_str =~ m/^(\d+)h(\d+)m$/) {
        $TIME = time + ($1 || 0) * 3600 + ($2 || 0) * 60; last;
      } elsif ($time_str =~ m/^(\d+)h$/) {
        $TIME = time + $1 * 3600; last;
      } elsif ($time_str =~ m/^(\d+)m$/) {
        $TIME = time + $1 * 60; last;
      } elsif($time_str =~ m/^(\d+):(\d+)$/ && $1 >= 0 && $1 <= 23 && $2 >= 0 && $2 <= 59) {
        $TIME = time + &delay($1, $2) - 5; last;
      } elsif($time_str =~ m/^(\d+):(\d+)(am|pm)$/i && $1 >= 1 && $1 <= 12 && $2 >= 0 && $2 <= 59) {
        $TIME = time + &delay($1, $2, $3) - 5; last;
      } elsif($time_str =~ m/^(\d+)(am|pm)$/i && $1 >= 1 && $1 <= 12) {
        $TIME = time + &delay($1, 0, $2) - 5; last;
      } else {
        warn "Invalid time format.\n";
        $time_str = undef;
        next;
      }

      $TIME or print "Time can't be zero.\n" and next;
    }
  }

  if($MODE eq "unlock") {
    $FORCE = shift @args;
    if(defined $FORCE) {
      $FORCE eq "force" or &usage and exit -1;
    }
  }
}




sub main {
  my @args = @ARGV;
  @ARGV = ();
  &process_args(@args);

  if($MODE eq "lock") {
    &lock() or print "Aborted.\n" and exit -1;
    print "Locked out.\n";
    exit 0;

  } elsif($MODE eq "unlock") {
    &unlock() or print "Work more, slacker.  (Use 'force' to force.)\n" and exit -1;
    exit 0;

  } elsif($MODE eq "status") {
    &status();
    exit 0;
  }

  &usage and exit -1;
}


sub usage {
  print <<EOF;
!! WARNING !!
  This program is VERY DANGEROUS.  It will cause your root password to be
  changed to something random.  If things fail horribly, it won't be changed
  back and you will be screwed.  Use at your own risk!

LOCKING YOUR COMPUTER (root only)
  lockout lock [HhMm|Hh|Mm]      (H and M are positive integers)
  lockout lock HH:MM             (HH is 0-23, MM is 0-60)
  lockout lock HH:MM[am|pm]      (HH is 0-12, MM is 0-60)
  lockout lock HH[am|pm]         (HH is 0-12)
  lockout lock                   (will ask you for one of the above)

  (The first version specifies a delay; all others specify absolute time.)

  Changes the root password to something random, executes
  $LOCK_SCRIPT and relies on the cron daemon and root's
  crontab to invoke 'lockout unlock' every minute so that your system is
  unlocked at the specified time.

  Example: lockout lock 2h30m   [locks out for 2h and 30m]
  Example: lockout lock 90m     [locks out for 1h and 30m]
  Example: lockout lock 3pm     [locks out until 3pm]
  Example: lockout lock 3:20am  [locks out until 3:20am]
  Example: lockout lock 15:20   [locks out until 3:20pm]

UNLOCKING YOUR COMPUTER (root only)
  lockout unlock [force]

  Changes the root password back and executes $UNLOCK_SCRIPT.

  This should be automatically invoked by cron every minute.  (You'll be
  screwed if this doesn't happen.)  However, you can manually force your
  computer to be unlocked by using the 'force' argument.


STATUS (any user)
  lockout status

  Tells you when the system is going to be unlocked.

FILES
  $LOCK_SCRIPT             -- script executed on lock
  $UNLOCK_SCRIPT           -- script executed on unlock
  $CRONTAB              -- this file must contain:
  ----------------------------------------------------------------
  */1 * * * *	root    /usr/bin/lockout unlock >/dev/null 2>&1
  \@reboot       root    /usr/bin/lockout unlock force >/dev/null 2>&1
  ----------------------------------------------------------------
  (or another, correct path to lockout)

VERSION
  lockout version $VERSION

MAGIC STRING: $MAGIC_STRING
EOF
}
                                                                                


&main();
