#!/usr/bin/perl
#
#  Copyright (c) 2011-2020 FastMail Pty Ltd. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#
#  2. 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.
#
#  3. The name "Fastmail Pty Ltd" must not be used to
#     endorse or promote products derived from this software without
#     prior written permission. For permission or any legal
#     details, please contact
#      FastMail Pty Ltd
#      PO Box 234
#      Collins St West 8007
#      Victoria
#      Australia
#
#  4. Redistributions of any form whatsoever must retain the following
#     acknowledgment:
#     "This product includes software developed by Fastmail Pty. Ltd."
#
#  FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
#  INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY  AND FITNESS, IN NO
#  EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
#  OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
#  USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
#  TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
#  OF THIS SOFTWARE.
#

package Cassandane::Cyrus::URLAuth;
use strict;
use warnings;
use Cwd qw(abs_path);
use File::Path qw(mkpath);
use DateTime;
use Data::Dumper;
use Digest::SHA qw(hmac_sha1_hex);

use lib '.';
use base qw(Cassandane::Cyrus::TestCase);
use Cassandane::Util::Log;
use Cassandane::Util::NetString;


sub new
{
    my $class = shift;

    my $config = Cassandane::Config->default()->clone();
    $config->set(servername => "127.0.0.1"); # urlauth needs matching servername

    return $class->SUPER::new({
        config => $config,
        adminstore => 1,
        services => ['imap']
    }, @_);
}

sub set_up
{
    my ($self) = @_;
    $self->SUPER::set_up();
}

sub tear_down
{
    my ($self) = @_;
    $self->SUPER::tear_down();
}

sub test_urlfetch
{
    my ($self) = @_;

    my %exp_sub;
    my $store = $self->{store};
    my $talk = $store->get_client();

    $store->set_folder("INBOX");
    $store->_select();
    $self->{gen}->set_next_uid(1);

    my $body;

    # Subpart 1
    $body = "--047d7b33dd729737fe04d3bde348\r\n"
    . "Content-Type: text/plain; charset=UTF-8\r\n"
    . "\r\n"
    . "body1"
    . "\r\n";

    # Subpart 2
    $body .= "--047d7b33dd729737fe04d3bde348\r\n"
    . "Content-Type: multipart/mixed;boundary=frontier\r\n"
    . "\r\n";

    # Subpart 2.1
    $body .= "--frontier\r\n"
    . "Content-Type: text/plain\r\n"
    . "\r\n"
    . "body21"
    . "\r\n";

    # End subpart 2
    $body .= "--frontier--\r\n";

    # Subpart 3
    my $msg3 = ""
    . "Return-Path: <Ava.Nguyen\@local>\r\n"
    . "Mime-Version: 1.0\r\n"
    . "Content-Type: text/plain\r\n"
    . "Content-Transfer-Encoding: 7bit\r\n"
    . "Subject: bar\r\n"
    . "From: Ava T. Nguyen <Ava.Nguyen\@local>\r\n"
    . "Message-ID: <fake.1475639947.6507\@local>\r\n"
    . "Date: Wed, 05 Oct 2016 14:59:07 +1100\r\n"
    . "To: Test User <test\@local>\r\n"
    . "\r\n"
    . "body3";

    $body .= "--047d7b33dd729737fe04d3bde348\r\n"
    . "Content-Type: message/rfc822\r\n"
    . "\r\n"
    . $msg3
    . "\r\n";

    # End body
    $body .= "--047d7b33dd729737fe04d3bde348--";

    $self->make_message("foo",
        mime_type => "multipart/mixed",
        mime_boundary => "047d7b33dd729737fe04d3bde348",
        body => $body
    );

    my $data;
    my %handlers =
    (
        urlfetch => sub
        {
            my ($cmd, $params) = @_;
            $data = ${$params}[1];
        },
    );

    my $url = $talk->_imap_cmd('genurlauth', 0, "genurlauth",
                               "imap://cassandane\@127.0.0.1/INBOX/;uid=1/;section=3.TEXT;partial=1.3;urlauth=user+cassandane",
                               'INTERNAL');

    my $res = $talk->_imap_cmd('urlfetch', 0, \%handlers, substr($url, 1, -1));
    
    $self->assert_str_equals($data, "ody");
}

sub test_perms
    :UnixHierarchySep :AltNamespace
{
    my ($self) = @_;

    $self->{instance}->create_user('other');

    my $msg = $self->make_message("Message A");

    my $url;
    my %handlers = (
        genurlauth => sub {
            my ($cmd, $params) = @_;
            $url = $params->[0];
        }
    );

    my $svc = $self->{instance}->get_service('imap');
    my $store = $svc->create_store(username => 'other');
    my $talk = $store->get_client();

    $talk->_imap_cmd(
        'genurlauth', 0, \%handlers,
        "imap://other\@127.0.0.1/Other%20Users%2fcassandane/;uid=1;urlauth=user+other",
        "INTERNAL",
    );

    # 'other' has no rights on cassandane's mailbox, so the server must refuse
    # to mint a URLAUTH token for it. Without this check, cmd_urlfetch would
    # happily hand over the message: it skips ACLs whenever urlauth.access is
    # set, trusting that a valid token implies the authorizer had the rights
    # to delegate.
    $self->assert_null($url);
}

sub test_revoked_access_invalidates_url
    :UnixHierarchySep :AltNamespace
{
    my ($self) = @_;

    my $admintalk = $self->{adminstore}->get_client;

    $self->{instance}->create_user('other');

    $self->make_message("Secret Message");

    # Grant 'other' read+lookup so that genurlauth will mint a token.
    $admintalk->setacl('user/cassandane', 'other', 'lrs')
        or die "setacl: " . $admintalk->get_last_error;

    my $svc = $self->{instance}->get_service('imap');
    my $store = $svc->create_store(username => 'other');
    my $other_talk = $store->get_client();

    # 'other' mints a URLAUTH token while authorized.
    my $url;
    $other_talk->_imap_cmd(
        'genurlauth', 0,
        { genurlauth => sub { $url = $_[1]->[0] } },
        'imap://other@127.0.0.1/Other%20Users%2fcassandane/;uid=1;urlauth=user+other',
        'INTERNAL',
    );
    $self->assert_not_null($url, 'genurlauth should succeed while authorized');

    # Captured value is wrapped in quotes; strip them for urlfetch.
    (my $bare_url = $url) =~ s/\A"(.*)"\z/$1/;

    # Sanity check: the token works while access is in place.
    my $data;
    $other_talk->_imap_cmd(
        'urlfetch', 0,
        { urlfetch => sub { $data = $_[1]->[1] } },
        $bare_url,
    );
    $self->assert_not_null($data, 'URL should fetch while authorizer is authorized');

    # Revoke 'other's access entirely.
    $admintalk->setacl('user/cassandane', 'other', '')
        or die "setacl: " . $admintalk->get_last_error;

    # The token is cryptographically intact, but the authorizer's right to
    # delegate the message is gone. cmd_urlfetch must re-check ACLs at fetch
    # time and refuse, instead of trusting the token alone.
    my $stolen;
    $other_talk->_imap_cmd(
        'urlfetch', 0,
        { urlfetch => sub { $stolen = $_[1]->[1] } },
        $bare_url,
    );
    $self->assert_null($stolen, 'URL must not fetch after authorizer access revoked');
}

sub test_forged_empty_key
    :UnixHierarchySep :AltNamespace
{
    my ($self) = @_;

    # The victim has an INBOX and a second folder.  The secret we don't want
    # leaked lives in the second folder.
    my $talk = $self->{store}->get_client;
    $talk->create("Archive") or die "create Archive: " . $talk->get_last_error;

    $self->{store}->set_folder("INBOX");
    $self->make_message("Public INBOX message");

    $self->{store}->set_folder("Archive");
    $self->make_message("Secret archived message");

    # Cause the victim's mboxkey.db to be created, but with an entry only for
    # the INBOX -- *not* for the Archive folder we're about to attack.  An
    # mboxkey.db appears in the wild whenever a user has ever issued a
    # GENURLAUTH (or a RESETKEY for a specific mailbox).
    my $seed;
    $talk->_imap_cmd(
        'genurlauth', 0,
        { genurlauth => sub { $seed = $_[1]->[0] } },
        'imap://cassandane@127.0.0.1/INBOX/;uid=1;urlauth=user+cassandane',
        'INTERNAL',
    );
    $self->assert_not_null($seed, 'victim should be able to URLAUTH their own INBOX');

    # Now the attacker forges a token for the *Archive* folder.  Because
    # mboxkey_read() returns {key=NULL, keylen=0} for any mailbox it has never
    # stored, cmd_urlfetch computes HMAC-SHA1 with an empty key -- which is
    # entirely attacker-computable.
    $self->{instance}->create_user('attacker');

    my $rump = 'imap://cassandane@127.0.0.1/Archive/;uid=1;urlauth=user+attacker';
    my $token = '00' . hmac_sha1_hex($rump, '');
    my $forged = "$rump:internal:$token";

    my $svc = $self->{instance}->get_service('imap');
    my $store = $svc->create_store(username => 'attacker');
    my $attacker = $store->get_client();

    my $stolen;
    $attacker->_imap_cmd(
        'urlfetch', 0,
        { urlfetch => sub { $stolen = $_[1]->[1] } },
        $forged,
    );

    $self->assert_null($stolen);
}

1;
