summaryrefslogtreecommitdiff
path: root/script/cookiecheck.pl
blob: a078b8caf68af854561b01b21392b8253e273b83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env perl

use v5.34;
use warnings;
use utf8;
use autodie;

use Digest::SHA 'hmac_sha256_hex';
use JSON::PP 'decode_json';
use MIME::Base64 'decode_base64';
use Pod::Usage 'pod2usage';


sub main {
    pod2usage if !@ARGV || $ARGV[0] eq '-h' || $ARGV[0] eq '--help';

    die 'invalid number of args' unless @ARGV == 1 || @ARGV == 3;
    my @check_args = $ARGV[0];
    if (@ARGV == 3) {
        push @check_args, $ARGV[1], $ARGV[2];
    }

    my ($match, $res) = check_cookie(@check_args);

    if (defined $match && !$match) {
        say STDERR 'mismatched mac';
        exit 1;
    }

    my $json = decode_json $res;
    print JSON::PP->new()->pretty(1)->canonical(1)->encode($json);
}

sub check_cookie {
    my $cookie = shift;

    # split
    my $splitAt = rindex $cookie, '--';
    die 'invalid format' if $splitAt == -1;
    my $val = substr $cookie, 0, $splitAt;
    my $sig = substr $cookie, $splitAt+2;

    my $match;
    if (@_) {
        my ($cookie_name, $secret) = @_;
        # hmac
        my $check = hmac_sha256_hex "$cookie_name=$val", $secret;
        $match = $sig eq $check;
    }

    # change base64 padding
    $val =~ s/-*$/'=' x length $&/e;

    # base64
    my $res = decode_base64 $val;

    # cookie content padding
    $res =~ s/Z*$//;

    return $match, $res;
}

main unless caller;

1

__END__

=encoding utf-8

=head1 NAME

mojocookiecheck - Prints out a Signed Cookie of Mojolicious

=head1 SYNOPSIS

mojocookiecheck.pl [OPTIONS] COOKIE_BODY [COOKIE_NAME SECRET]

  Options:
    -h  --help    print this help

=head1 DESCRIPTION

This is a cookie checker for Mojolicious that converts them from an opaque
character string to something nicely readable. It also can check the HMAC.