commit 3ff9dbc26a9a04d19c2e2bf18d5ee22d836f17b2
parent 22d4e961b55e934d6f1b04e898cdb3c21d37e41a
Author: Samir Parikh <noreply@samirparikh.com>
Date: Fri, 25 Feb 2022 22:01:50 +0000
get authentication error subroutine to work
Diffstat:
1 file changed, 30 insertions(+), 1 deletion(-)
diff --git a/guess_number3.cgi b/guess_number3.cgi
@@ -4,15 +4,18 @@ use warnings;
use strict;
use CGI;
use CGI::Cookie ();
+use MD5 ();
use constant TRIES => 6;
-use constant COOKIE_NAME => 'guess_number_2';
+use constant COOKIE_NAME => 'guess_number_3';
+use constant SECRET => 'mySuperSecretSecret';
my $game = CGI->new;
# state maintenance subroutines
sub get_state {
my %state = $game->cookie( COOKIE_NAME );
return undef unless %state;
+ authentication_error() unless cookie_check( \%state, 'check');
return \%state;
}
@@ -29,6 +32,7 @@ sub initialize {
sub save_state {
my $state = shift;
+ cookie_check( $state, 'generate' );
return CGI::Cookie->new (
-name => COOKIE_NAME,
-value => $state,
@@ -171,6 +175,31 @@ sub print_footer {
print $game->end_html();
}
+# message authentication checks
+sub cookie_check {
+ my ($state, $action) = @_;
+ return unless ref( $state );
+ my @fields = @{$state}{qw(NUMBER GUESSES_LEFT GUESSED GAMENO WON)};
+ my $newmac = MD5->hexhash(
+ SECRET . MD5->hexhash( join '', SECRET, @fields )
+ );
+ return $state->{MAC} = $newmac if $action eq 'generate';
+ return $newmac eq $state->{MAC} if $action eq 'check';
+ return undef;
+}
+
+sub authentication_error {
+ my $cookie = CGI::Cookie->new(-name => COOKIE_NAME, -value=>'',-expires => '-1d');
+ print $game->header(-cookie => $cookie),
+ $game->start_html(-title => 'Authentication Error'),
+ $game->h1($game->font({-color => 'red'}, 'Authentication Error')),
+ $game->p('This application was unable to confirm the integrity of the',
+ 'cookie that holds your current score.',
+ 'Please reload the page to start a fresh session.'),
+ $game->p('If the problem persists, contact the webmaster.');
+ exit 0;
+}
+
# begin main program
# retrieve current state
my $state = get_state() unless $game->param( 'clear' );