#!/usr/bin/perl -w
###############################################################################
#
# This script decrypts data given a valid combination of several user passwords.
# The data should have been encrypted with the other script of the keysafe
# toolchain.
#
# Essentially, the script does:
# 1. Unpack the encrypted source.
# 2. Read user passwords from the prompt.
# 3. Try to decrypt each group files until success.
#    Retrieves the master key or abort if the passwords matched no group file.
# 4. Decrypt the data and print it to the screen.
# 
# User passwords are sorted and concatenated to form the group password. Due to
# this, neither user names nor group or other information has to be specified.
# Only the user passwords.
#
# The user is guided through the process and checksums are handled as well.
#
# The script has the following dependencies:
# * perl
# * mktemp
# * tar
# * gpg
# * stty
# * less
#
# Run without parameters to see the syntax.
#
# This script is part of the keysafe toolchain.
#
################################################################################
#
# Copyright (c) 2014, Matthias Baumgartner
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the keysafe nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL MATTHIAS BAUMGARTNER BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 
###############################################################################

use warnings;
use IPC::Open2;
use FileHandle;
use File::Path qw(remove_tree);
use Term::ANSIColor;

# Config vars - Have to match the values in encrypt.pl
my $ALGO_CHECKSUM = 'sha256';
my $SRC_DATA = 'data.gpg';
my $DEBUG = 0;

###############################################################################

# Get the command-line params
my $syntax = "syntax: decrypt.pl </pth/to/source>\n";
my $src = shift || die("ERROR: Please specify a source.\n$syntax");

###############################################################################

# Print greeter
print color('bright_red') . "

Dear user,

You are trying to decrypt an archive with multiple users.

Presumably, this is a sensitive operation. Please ensure that you are in
an appropriate setting - no intruders, watching over your shoulder or
hardware you don't fully trust.

The procedure is as follows:
1. You have received a paperslip with the following information:
    - A user name
    - A password
    - A checksum
    - A list of decryption partners
2. Ensure that you are accompanied by a combination of partners, as
   stated on your hardcopy. Ensure, every user has his/her information
   ready.
3. Start the decryption process - since you see this message, you've already
   successfully achieved this step.
4. A checksum will be printed out. Compare it to the one on your hardcopy and
   ensure it's the same one.
5. Each partner enters his/her password individually. The order does not matter.
6. If successfull, the content of the archive is printed to the console. All
   information is temporarily stored. If you need some of the displayed information,
   copy or memorize it immediately. Better yet, use it directly, so have the
   necessary infrastructure close by.
7. When finished, close the console and shut down the machine to remove traces.

Cheers! " . color('reset') . "

********************************************************************************

";

###############################################################################

# Initialization
my $dst_tmp = `mktemp -d`;
$dst_tmp =~ s/\n//;
print "Temporary destination: $dst_tmp\n" if $DEBUG;

###############################################################################

# Get the source's checksum
my $cmd_checksum = "gpg --print-md ${ALGO_CHECKSUM} ${src}";
print "\$ $cmd_checksum\n" if $DEBUG;
my $checksum = `$cmd_checksum`;
$checksum =~ s/[\r\n\s]+/ /g;
$checksum =~ s/^.*:\s*//;
print "Checksum: $checksum\n" if $DEBUG;

# Query the checksum
print "The checksum is:\n $checksum\n\n";
print "Type yes, if the checksum is the same as on your hardcopy. (yes/NO): ";
my $answer = <STDIN>;
if ($answer !~ /^\s*y(es)?\s*$/i)
{
    print color('bright_red') . "
The checksum was not confirmed. This means that
 a) You're trying to open a different file than your hardcopy specifies.
 b) The file has been modified (possibly malicious)." . color('reset') . "

If you absolutely must try to open this file, type uppercase YES.
Note that this will likely fail and you might give away information.
  Continue? (YES/NO): ";

    $answer = <STDIN>;
    if ($answer !~ /^\s*YES\s*$/)
    {
        remove_tree($dst_tmp);
        die("Aborted due to invalid file checksum.\n");
    }
}

###############################################################################

# Unpack source
my $cmd_unpack = "tar -xzf $src -C $dst_tmp";
print "\$ $cmd_unpack\n" if $DEBUG;
system($cmd_unpack);

###############################################################################

my $key_master = 0;
while(1)
{
    # Query user's passwords
    my @passwords;
    print "
********************************************************************************
Please enter the user passwords. Confirm each password with a newline (enter)
character. Stop password input with an empty line (i.e. press enter twice
after the last password). You won't see the characters you type:
";
    system('stty','-echo');
    while(my $user_password = <STDIN>)
    {
        chomp($user_password);
        print "\n";
        last if $user_password =~ /^\s*$/;
        push(@passwords, $user_password);
    }
    system('stty','echo');
    print "You've entered " . scalar @passwords ." passwords\n";
    
    # Sort passwords
    @passwords = sort @passwords;
    my $key_group = join('', @passwords);
    print "Group password: $key_group\n" if $DEBUG;

    # Decrypt master key from group files until successful or groups exhausted
    opendir(TMPDIR, $dst_tmp);
    while(my $file = readdir(TMPDIR))
    {
        if ($file !~ /^group_\d+$/)
        {
            next;
        }

        my $cmd_decrypt_grp = "gpg --batch --passphrase-fd 0 --no-use-agent -d $dst_tmp/$file 2>/dev/null";
        print "\$ $cmd_decrypt_grp\n" if $DEBUG;
        open2(*Reader, *Writer, $cmd_decrypt_grp);
        print Writer $key_group . "\n";
        $key_master = <Reader>;
        last if ($key_master);
    }

    if ($key_master)
    {
        last;
    }
    else
    {
        # Unsuccessfull
        print color('bright_red') . "
Your password didn't work. Please make sure that
 a) You've entered all the password correctly.
 b) You've entered the passwords of all users.
 c) The user combination is valid, as stated on your hardcopy." . color('reset') . "

Do you want to re-enter the passwords? (y/N): ";

        my $answer = <STDIN>;
        if ($answer !~ /^\s*y(es)?\s*$/i)
        {
            # Abort
            remove_tree($dst_tmp);
            die("ERROR: Invalid Password\n");
        }
    }
}

###############################################################################

# Decrypt data with master key
my $cmd_decrypt_data = "gpg --batch --passphrase-fd 0 --no-use-agent -d $dst_tmp/$SRC_DATA 2>/dev/null";
print "\$ $cmd_decrypt_data\n" if $DEBUG;
open2(*Reader, *Writer, $cmd_decrypt_data);
print Writer $key_master . "\n";
open(FD_DATA, "|-", 'less -Sc');
print FD_DATA "********************************************************************************
The archive was successfully decrypted. Its content is printed below.

You can use the cursor (up, down, left, right) to move around.

Once finished, press 'q' to complete the decryption process. You will then
not be able to see this content anymore!

Unfortunately, I cannot offer any means to send the content anywhere.
Meaning you cannot print, copy-paste or mail it. If not memorizable,
you'll have to resort to writing it down by hand. Check for errors twice!
Better yet, you've prepared and have whatever device nearby to digest the
information you see here directly.
Sorry for the inconvenience.

--------------------------------------------------------------------------------
";

#print color('bright_red') . "The archive was successfully decrypted. Its content is printed below.\n" . color('reset');
while (my $line = <Reader>)
{
    print FD_DATA $line;
}

close FD_DATA;

###############################################################################

remove_tree($dst_tmp);

print "--------------------------------------------------------------------------------
The decryption process was completed successfully. Have a nice day.
";
## EOF ##
