Plack-Middleware-CSRFBlock-0.10/0000755000175000017500000000000012360533470014414 5ustar mmpmmpPlack-Middleware-CSRFBlock-0.10/README.pod0000644000175000017500000001203712360533470016060 0ustar mmpmmp=pod =encoding UTF-8 =head1 NAME Plack::Middleware::CSRFBlock - Block CSRF Attacks with minimal changes to your app =head1 VERSION version 0.10 =head1 SYNOPSIS use Plack::Builder; my $app = sub { ... } builder { enable 'Session'; enable 'CSRFBlock'; $app; } =head1 DESCRIPTION This middleware blocks CSRF. You can use this middleware without any modifications to your application, in most cases. Here is the strategy: =over 4 =item output filter When the application response content-type is "text/html" or "application/xhtml+xml", this inserts a hidden input tag that contains a token string into C
s in the response body. For example, when the application response body is: input form
This becomes: input form
This affects C
tags with C, case insensitive. It is possible to add an optional meta tag by setting C to a defined value. The 'name' attribute of the HTML tag will be set to the value of C. For the previous example, when C is set to 'csrf_token', the output will be: input form =item input check For every POST requests, this module checks the C header first, then C input parameters. If the correct token is not found in either, then a 403 Forbidden is returned by default. Supports C and C for input parameters, but any C will be validated with the C header. Thus, every C will have to have either the header, or the appropriate form parameters in the body. =item javascript This module can be used easily with javascript by having your javascript provide the C with any ajax C requests it makes. You can get the C in javascript by getting the value of the C C tag in the page . Here is sample code that will work for C: $(document).ajaxSend(function(e, xhr, options) { var token = $("meta[name='csrftoken']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", token); }); This will include the X-CSRF-Token header with any C requests made from your javascript. =back =head1 OPTIONS use Plack::Builder; my $app = sub { ... } builder { enable 'Session'; enable 'CSRFBlock', parameter_name => 'csrf_secret', token_length => 20, session_key => 'csrf_token', blocked => sub { [302, [Location => 'http://www.google.com'], ['']]; }, onetime => 0, ; $app; } =over 4 =item parameter_name (default:"SEC") Name of the input tag for the token. =item meta_tag (default:undef) Name of the C tag added to the C tag of output pages. The content of this C tag will be the token value. The purpose of this tag is to give javascript access to the token if needed for AJAX requests. If this attribute is not explicitly set the meta tag will not be included. =item header_name (default:"X-CSRF-Token") Name of the HTTP Header that the token can be sent in. This is useful for sending the header for Javascript AJAX requests, and this header is required for any post request that is not of type C or C. =item token_length (default:16); Length of the token string. Max value is 40. =item session_key (default:"csrfblock.token") This middleware uses L for token storage. this is the session key for that. =item blocked (default:403 response) The application called when CSRF is detected. Note: This application can read posted data, but DO NOT use them! =item onetime (default:FALSE) If this is true, this middleware uses B token, that is, whenever client sent collect token and this middleware detect that, token string is regenerated. This makes your applications more secure, but in many cases, is too strict. =back =head1 SEE ALSO L =head1 AUTHORS =over 4 =item * Rintaro Ishizaki =item * William Wolf =item * Matthew Phillips =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014 by the Authors of Plack-Middleware-CSRFBlock. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Plack-Middleware-CSRFBlock-0.10/META.yml0000644000175000017500000000143312360533470015666 0ustar mmpmmp--- abstract: 'Block CSRF Attacks with minimal changes to your app' author: - 'Rintaro Ishizaki ' - 'William Wolf ' - 'Matthew Phillips ' build_requires: File::Spec: 0 HTTP::Request::Common: 0 IO::Handle: 0 IPC::Open3: 0 Plack::Middleware::Session: 0 Test::More: 0 configure_requires: ExtUtils::MakeMaker: 6.30 dynamic_config: 0 generated_by: 'Dist::Zilla version 5.019, CPAN::Meta::Converter version 2.141520' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: Plack-Middleware-CSRFBlock requires: Digest::SHA1: 0 HTML::Parser: 0 Plack: 0 Time::HiRes: 0 resources: repository: git://github.com/mattp-/Plack-Middleware-CSRFBlock.git version: 0.10 Plack-Middleware-CSRFBlock-0.10/Makefile.PL0000644000175000017500000000303212360533470016364 0ustar mmpmmp # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.019. use strict; use warnings; use ExtUtils::MakeMaker 6.30; my %WriteMakefileArgs = ( "ABSTRACT" => "Block CSRF Attacks with minimal changes to your app", "AUTHOR" => "Rintaro Ishizaki , William Wolf , Matthew Phillips ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.30" }, "DISTNAME" => "Plack-Middleware-CSRFBlock", "EXE_FILES" => [], "LICENSE" => "perl", "NAME" => "Plack::Middleware::CSRFBlock", "PREREQ_PM" => { "Digest::SHA1" => 0, "HTML::Parser" => 0, "Plack" => 0, "Time::HiRes" => 0 }, "TEST_REQUIRES" => { "File::Spec" => 0, "HTTP::Request::Common" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Plack::Middleware::Session" => 0, "Test::More" => 0 }, "VERSION" => "0.10", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Digest::SHA1" => 0, "File::Spec" => 0, "HTML::Parser" => 0, "HTTP::Request::Common" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Plack" => 0, "Plack::Middleware::Session" => 0, "Test::More" => 0, "Time::HiRes" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Plack-Middleware-CSRFBlock-0.10/xt/0000755000175000017500000000000012360533470015047 5ustar mmpmmpPlack-Middleware-CSRFBlock-0.10/xt/03_pod.t0000644000175000017500000000020112360533470016311 0ustar mmpmmpuse Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); Plack-Middleware-CSRFBlock-0.10/xt/02_perlcritic.t0000644000175000017500000000033312360533470017674 0ustar mmpmmpuse strict; use Test::More; eval { require Test::Perl::Critic; Test::Perl::Critic->import( -profile => 'xt/perlcriticrc'); }; plan skip_all => "Test::Perl::Critic is not installed." if $@; all_critic_ok('lib'); Plack-Middleware-CSRFBlock-0.10/xt/perlcriticrc0000644000175000017500000000013412360533470017455 0ustar mmpmmp[-TestingAndDebugging::RequireUseStrict] [TestingAndDebugging::ProhibitNoStrict] allow=refs Plack-Middleware-CSRFBlock-0.10/xt/01_podspell.t0000644000175000017500000000051212360533470017354 0ustar mmpmmpuse Test::More; eval q{ use Test::Spelling }; plan skip_all => "Test::Spelling is not installed." if $@; add_stopwords(map { split /[\s\:\-]/ } ); $ENV{LANG} = 'C'; all_pod_files_spelling_ok('lib'); __DATA__ Rintaro Ishizaki rintaro@cpan.org Plack::Middleware::CSRFBlock CSRF Javascript ajax csrftoken javascript middleware Plack-Middleware-CSRFBlock-0.10/t/0000755000175000017500000000000012360533470014657 5ustar mmpmmpPlack-Middleware-CSRFBlock-0.10/t/00-compile.t0000644000175000017500000000173712360533470016721 0ustar mmpmmpuse 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.043 use Test::More tests => 1 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'Plack/Middleware/CSRFBlock.pm' ); # no fake home requested my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') if $ENV{AUTHOR_TESTING}; Plack-Middleware-CSRFBlock-0.10/t/00_compile.t0000644000175000017500000000013012360533470016765 0ustar mmpmmpuse strict; use Test::More tests => 1; BEGIN { use_ok 'Plack::Middleware::CSRFBlock' } Plack-Middleware-CSRFBlock-0.10/t/01_basic.t0000644000175000017500000002722012360533470016430 0ustar mmpmmpuse Test::More; use strict; use warnings; use Plack::Test; use HTTP::Request::Common; use Plack::Builder; use Plack::Session::State::Cookie; my $form = < the form
FORM my $form_outside = < the form
FORM my $form_localhost = < the form
FORM my $form_localhost_port = < the form
FORM my $base_app = sub { my $req = Plack::Request->new(shift); my $name = $req->param('name') or die 'name not found'; return [ 200, [ 'Content-Type' => 'text/plain' ], [ "Hello " . $name ] ] }; my $mapped = builder { mount "/post" => $base_app; mount "/form/html" => sub { [ 200, [ 'Content-Type' => 'text/html' ], [ $form ] ] }; mount "/form/xhtml" => sub { [ 200, [ 'Content-Type' => 'application/xhtml+xml' ], [ $form ] ] }; mount "/form/text" => sub { [ 200, [ 'Content-Type' => 'text/plain' ], [ $form ] ] }; mount "/form/html-charset" => sub { [ 200, [ 'Content-Type' => 'text/html; charset=UTF-8' ], [ $form ] ] }; mount "/form/xhtml-charset" => sub { [ 200, [ 'Content-Type' => 'application/xhtml+xml; charset=UTF-8' ], [ $form ] ] }; mount "/form/text-charset" => sub { [ 200, [ 'Content-Type' => 'text/plain; charset=UTF-8' ], [ $form ] ] }; mount "/form/html-outside" => sub { [ 200, [ 'Content-Type' => 'text/html' ], [ $form_outside ] ] }; mount "/form/html-localhost" => sub { [ 200, [ 'Content-Type' => 'text/html' ], [ $form_localhost ] ] }; mount "/form/html-localhost-port" => sub { [ 200, [ 'Content-Type' => 'text/html' ], [ $form_localhost_port ] ] }; }; # normal input my $app1 = builder { enable 'Session', state => Plack::Session::State::Cookie->new(session_key => 'sid'); enable 'CSRFBlock'; $mapped; }; # psgix.input.buffered my $app2 = builder { enable 'Session', state => Plack::Session::State::Cookie->new(session_key => 'sid'); enable sub { my $app = shift; sub { my $env = shift; my $req = Plack::Request->new($env); my $content = $req->content; # <<< force psgix.input.buffered true. $app->($env); }; }; enable 'CSRFBlock'; $mapped; }; for my $app ($app1, $app2) { test_psgi app => $app, client => sub { my $cb = shift; my $res = $cb->(POST "http://localhost/post", [name => 'Plack']); is $res->code, 403; my $h_cookie = $res->header('Set-Cookie'); $h_cookie =~ /sid=([^; ]+)/; my $sid = $1; ok($sid); $res = $cb->(POST "http://localhost/post", [name => 'Plack'], Cookie => "sid=$sid"); is $res->code, 403, 'Forbidden for CSRF'; $res = $cb->(POST "http://localhost/post", [SEC => '1234567890123456', name => 'Plack'], Cookie => "sid=$sid"); is $res->code, 403, 'Forbidden for faked token'; $res = $cb->(GET "http://localhost/form/html", Cookie => "sid=$sid"); is $res->code, 200, 'form /form/html'; ok $res->content =~ //, 'form_has_token /form/html'; my $token = $1; # Make sure we *dont* have the meta header here ok $res->content !~ //; $res = $cb->(GET "http://localhost/form/html-charset", Cookie => "sid=$sid"); is $res->code, 200, 'form /form/html-charset'; ok $res->content =~ //, 'form_has_token /form/html-charset'; is $1, $token, 'same token for same sid'; $res = $cb->(GET "http://localhost/form/html-outside", Cookie => "sid=$sid"); is $res->code, 200, 'form /form/html-outside'; ok $res->content !~ //, 'form_has_not_token /form/html-outside'; $res = $cb->(GET "http://localhost/form/html-localhost", Cookie => "sid=$sid"); is $res->code, 200, 'form /form/html-localhost'; ok $res->content =~ //, 'form_has_token /form/html-localhost'; is $1, $token, 'same token for same sid again'; $res = $cb->(GET "http://localhost/form/html-localhost-port", Cookie => "sid=$sid"); is $res->code, 200, 'form /form/html-localhost-port'; ok $res->content =~ //, 'form_has_token /form/html-localhost-port'; is $1, $token, 'same token for same sid again2'; # application/x-www-form-urlencoded $res = $cb->(POST "http://localhost/post", [SEC => $token, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'application/x-www-form-urlencoded' ); is $res->code, 200, 'correct token returns 200'; is $res->content, 'Hello Plack', 'name param'; $res = $cb->(POST "http://localhost/post", [SEC => $token, x => 'x' x 20000, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'application/x-www-form-urlencoded' ); is $res->code, 200, 'correnct token returns 200 / long body'; is $res->content, 'Hello Plack', 'name param / long body'; # multipart/form-data $res = $cb->(POST "http://localhost/post", [SEC => $token, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'multipart/form-data' ); is $res->code, 200, 'correct token returns 200 / multipart/form-data'; is $res->content, 'Hello Plack', 'name param / multipart/form-data'; $res = $cb->(POST "http://localhost/post", [SEC => $token, x => 'x' x 20000, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'multipart/form-data' ); is $res->code, 200, 'correct token returns 200 / long body / multipart/form-data'; is $res->content, 'Hello Plack', 'name param / long body / multipart/form-data'; # application/x-www-form-urlencoded; charset=UTF-8 $res = $cb->(POST "http://localhost/post", [SEC => $token, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'application/x-www-form-urlencoded; chartset=UTF-8' ); is $res->code, 200, 'correct token returns 200 / charset'; is $res->content, 'Hello Plack', 'name param / charset'; $res = $cb->(POST "http://localhost/post", [SEC => $token, x => 'x' x 20000, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'application/x-www-form-urlencoded; chartset=UTF-8' ); is $res->code, 200, 'correct token returns 200 / long body / charset'; is $res->content, 'Hello Plack', 'name param / long body /charset'; # multipart/form-data; charset=UTF-8 $res = $cb->(POST "http://localhost/post", [SEC => $token, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'multipart/form-data; chartset=UTF-8' ); is $res->code, 200, 'correct token returns 200 / long body / multipart/form-data / charset'; is $res->content, 'Hello Plack', 'name param / long body / multipart/form-data / charset'; $res = $cb->(POST "http://localhost/post", [SEC => $token, x => 'x' x 20000, name => 'Plack'], Cookie => "sid=$sid", 'Content-Type' => 'multipart/form-data; chartset=UTF-8' ); is $res->code, 200; is $res->content, 'Hello Plack'; # supported content-type $res = $cb->(GET "http://localhost/form/xhtml", Cookie => "sid=$sid"); like $res->content, qr//, 'xhtml form has token'; $res = $cb->(GET "http://localhost/form/text", Cookie => "sid=$sid"); unlike $res->content, qr//, 'text form has not token'; $res = $cb->(GET "http://localhost/form/xhtml-charset", Cookie => "sid=$sid"); like $res->content, qr//, 'xhtml-charset form has token'; $res = $cb->(GET "http://localhost/form/text-charset", Cookie => "sid=$sid"); unlike $res->content, qr//, 'text-charset form has token'; }; }; # for my $app ($app1,$app2) # customized parameter my $app3 = builder { enable 'Session', , state => Plack::Session::State::Cookie->new(session_key => 'sid'); enable 'CSRFBlock', token_length => 8, parameter_name => 'TKN', onetime => 1, blocked => sub { [ 404, ['Content-Type' => 'text/plain'], [ 'csrf' ] ] } ; $mapped; }; test_psgi app => $app3, client => sub { my $cb = shift; my $res = $cb->(GET "http://localhost/form/xhtml"); is $res->code, 200, 'w/param form'; my $h_cookie = $res->header('Set-Cookie'); $h_cookie =~ /sid=([^; ]+)/; my $sid = $1; ok $res->content =~ //; my $token = $1; $res = $cb->(POST "http://localhost/post", [TKN => $token, name => 'Plack'], Cookie => "sid=$sid"); is $res->code, 200, 'w/param:onetime token use firsttime'; $res = $cb->(POST "http://localhost/post", [TKN => $token, name => 'Plack'], Cookie => "sid=$sid"); is $res->code, 404, 'w/param:onetime second token use'; is $res->content, 'csrf', 'w/param:blocked custom blocked app'; for(1..2) { $res = $cb->(GET "http://localhost/form/xhtml", Cookie => "sid=$sid"); is $res->code, 200, 'w/param form again'; ok $res->content =~ //; isnt $1, $token, 'w/param:onetime token changed'; $token = $1; $res = $cb->(POST "http://localhost/post", [TKN => $token, name => 'Plack'], Cookie => "sid=$sid"); is $res->code, 200, 'w/param:onetime new token used'; } $res = $cb->(POST "http://localhost/post", [TKN => $token, name => 'Plack'], Cookie => "sid=$sid"); is $res->code, 404, 'w/param:onetime second token use again'; is $res->content, 'csrf', 'w/param:blocked custom blocked app again'; }; # Test Meta Tag + Header my $app4 = builder { enable 'Session', state => Plack::Session::State::Cookie->new(session_key => 'sid'); enable 'CSRFBlock', token_length => 8, meta_tag => 'csrftoken'; $mapped; }; test_psgi app => $app4, client => sub { my $cb = shift; my $res = $cb->(GET "http://localhost/form/html"); is $res->code, 200; my $h_cookie = $res->header('Set-Cookie'); $h_cookie =~ /sid=([^; ]+)/; my $sid = $1; ok $res->content =~ //; my $token = $1; ok $res->content =~ //; my $meta_token = $1; is $token => $meta_token, 'Got correct token in meta tag'; $res = $cb->( POST "http://localhost/post", [name => 'Plack'], Cookie => "sid=$sid", 'X-CSRF-Token' => $meta_token ); is $res->code, 200, 'w/Token in Header Only'; }; done_testing; Plack-Middleware-CSRFBlock-0.10/lib/0000755000175000017500000000000012360533470015162 5ustar mmpmmpPlack-Middleware-CSRFBlock-0.10/lib/Plack/0000755000175000017500000000000012360533470016214 5ustar mmpmmpPlack-Middleware-CSRFBlock-0.10/lib/Plack/Middleware/0000755000175000017500000000000012360533470020271 5ustar mmpmmpPlack-Middleware-CSRFBlock-0.10/lib/Plack/Middleware/CSRFBlock.pm0000644000175000017500000002423012360533470022340 0ustar mmpmmppackage Plack::Middleware::CSRFBlock; $Plack::Middleware::CSRFBlock::VERSION = '0.10'; use parent qw(Plack::Middleware); use strict; use warnings; # ABSTRACT: Block CSRF Attacks with minimal changes to your app use Digest::SHA1; use Time::HiRes qw(time); use HTML::Parser; use Plack::Request; use Plack::TempBuffer; use Plack::Util; use Plack::Util::Accessor qw( parameter_name header_name add_meta meta_tag token_length session_key blocked onetime _token_generator logger ); sub prepare_app { my ($self) = @_; $self->parameter_name('SEC') unless defined $self->parameter_name; $self->token_length(16) unless defined $self->token_length; $self->session_key('csrfblock.token') unless defined $self->session_key; # Upper-case header name and replace - with _ my $header_name = uc($self->header_name || 'X-CSRF-Token'); $header_name =~ s/-/_/g; $self->header_name($header_name); $self->_token_generator(sub { my $token = Digest::SHA1::sha1_hex(rand() . $$ . {} . time); substr($token, 0 , $self->token_length); }); } sub log { my ($self, $level, $msg) = @_; $self->logger->({ level => $level, message => "CSRFBlock: $msg" }); } sub call { my($self, $env) = @_; # cache the logger $self->logger($env->{'psgix.logger'} || sub { }) unless defined $self->logger; # Generate a Plack Request for this request my $request = Plack::Request->new($env); # We need a session my $session = $request->session; unless ($session) { $self->log( error => 'No session found!' ); die "CSRFBlock needs Session." unless $session; } my $token = $session->{$self->session_key}; if($request->method =~ m{^post$}i) { # Log the request with env info $self->log(debug => 'Got POST Request'); # If we don't have a token, can't do anything return $self->token_not_found($env) unless $token; my $found; # First, check if the header is set correctly. $found = ( $request->header( $self->header_name ) || '') eq $token; $self->log(debug => 'Found in Header? : ' . ($found ? 1 : 0)); # If the token wasn't set, let's check the params unless ($found) { my $val = $request->parameters->{ $self->parameter_name } || ''; $found = $val eq $token; $self->log(debug => 'Found in parameters : ' . ($found ? 1 : 0)); } return $self->token_not_found($env) unless $found; # If we are using onetime token, remove it from the session delete $session->{$self->session_key} if $self->onetime; } return $self->response_cb($self->app->($env), sub { my $res = shift; my $ct = Plack::Util::header_get($res->[1], 'Content-Type') || ''; if($ct !~ m{^text/html}i and $ct !~ m{^application/xhtml[+]xml}i){ return $res; } my @out; my $http_host = $request->uri->host; my $token = $session->{$self->session_key} ||= $self->_token_generator->(); my $parameter_name = $self->parameter_name; my $p = HTML::Parser->new( api_version => 3, start_h => [sub { my($tag, $attr, $text) = @_; push @out, $text; no warnings 'uninitialized'; $tag = lc($tag); # If we found the head tag and we want to add a tag if( $tag eq 'head' && $self->meta_tag) { # Put the csrftoken in a element in # So that you can get the token in javascript in your # App to set in X-CSRF-Token header for all your AJAX # Requests push @out, q{}; } # If tag isn't 'form' and method isn't 'post' we dont care return unless $tag eq 'form' && $attr->{'method'} =~ /post/i; if( !($attr->{'action'} =~ m{^https?://([^/:]+)[/:]} and $1 ne $http_host) ) { push @out, '"; } # TODO: determine xhtml or html? return; }, "tagname, attr, text"], default_h => [\@out , '@{text}'], ); my $done; return sub { return if $done; if(defined(my $chunk = shift)) { $p->parse($chunk); } else { $p->eof; $done++; } join '', splice @out; } }); } sub token_not_found { my ($self, $env) = (shift, shift); $self->log(error => 'Token not found, returning 403!'); if(my $app_for_blocked = $self->blocked) { return $app_for_blocked->($env, @_); } else { my $body = 'CSRF detected'; return [ 403, [ 'Content-Type' => 'text/plain', 'Content-Length' => length($body) ], [ $body ] ]; } } 1; __END__ =pod =encoding UTF-8 =head1 NAME Plack::Middleware::CSRFBlock - Block CSRF Attacks with minimal changes to your app =head1 VERSION version 0.10 =head1 SYNOPSIS use Plack::Builder; my $app = sub { ... } builder { enable 'Session'; enable 'CSRFBlock'; $app; } =head1 DESCRIPTION This middleware blocks CSRF. You can use this middleware without any modifications to your application, in most cases. Here is the strategy: =over 4 =item output filter When the application response content-type is "text/html" or "application/xhtml+xml", this inserts a hidden input tag that contains a token string into C
s in the response body. For example, when the application response body is: input form
This becomes: input form
This affects C
tags with C, case insensitive. It is possible to add an optional meta tag by setting C to a defined value. The 'name' attribute of the HTML tag will be set to the value of C. For the previous example, when C is set to 'csrf_token', the output will be: input form =item input check For every POST requests, this module checks the C header first, then C input parameters. If the correct token is not found in either, then a 403 Forbidden is returned by default. Supports C and C for input parameters, but any C will be validated with the C header. Thus, every C will have to have either the header, or the appropriate form parameters in the body. =item javascript This module can be used easily with javascript by having your javascript provide the C with any ajax C requests it makes. You can get the C in javascript by getting the value of the C C tag in the page . Here is sample code that will work for C: $(document).ajaxSend(function(e, xhr, options) { var token = $("meta[name='csrftoken']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", token); }); This will include the X-CSRF-Token header with any C requests made from your javascript. =back =head1 OPTIONS use Plack::Builder; my $app = sub { ... } builder { enable 'Session'; enable 'CSRFBlock', parameter_name => 'csrf_secret', token_length => 20, session_key => 'csrf_token', blocked => sub { [302, [Location => 'http://www.google.com'], ['']]; }, onetime => 0, ; $app; } =over 4 =item parameter_name (default:"SEC") Name of the input tag for the token. =item meta_tag (default:undef) Name of the C tag added to the C tag of output pages. The content of this C tag will be the token value. The purpose of this tag is to give javascript access to the token if needed for AJAX requests. If this attribute is not explicitly set the meta tag will not be included. =item header_name (default:"X-CSRF-Token") Name of the HTTP Header that the token can be sent in. This is useful for sending the header for Javascript AJAX requests, and this header is required for any post request that is not of type C or C. =item token_length (default:16); Length of the token string. Max value is 40. =item session_key (default:"csrfblock.token") This middleware uses L for token storage. this is the session key for that. =item blocked (default:403 response) The application called when CSRF is detected. Note: This application can read posted data, but DO NOT use them! =item onetime (default:FALSE) If this is true, this middleware uses B token, that is, whenever client sent collect token and this middleware detect that, token string is regenerated. This makes your applications more secure, but in many cases, is too strict. =back =head1 SEE ALSO L =head1 AUTHORS =over 4 =item * Rintaro Ishizaki =item * William Wolf =item * Matthew Phillips =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2014 by the Authors of Plack-Middleware-CSRFBlock. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Plack-Middleware-CSRFBlock-0.10/MANIFEST0000644000175000017500000000045212360533470015546 0ustar mmpmmp# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.019. Changes LICENSE MANIFEST META.yml Makefile.PL README.md README.pod dist.ini lib/Plack/Middleware/CSRFBlock.pm t/00-compile.t t/00_compile.t t/01_basic.t xt/01_podspell.t xt/02_perlcritic.t xt/03_pod.t xt/perlcriticrc Plack-Middleware-CSRFBlock-0.10/Changes0000644000175000017500000000075412360533470015715 0ustar mmpmmpRevision history for Plack::Middleware::CSRFBlock 0.10 Sun Jul 13 12:38:35 EDT 2014 * fix incorrect changes entries. 0.9 Fri Jul 11 14:14:39 EDT 2014 * use Time::Hires for higher granularity timing (thanks @jwittkoski) * log messages to debug instead of info stream (thanks @jwittkoski) 0.8 Wed May 29 13:17:06 EDT 2013 * sets repository in META.yml to differentiate from other forks (thanks @oalders) 0.07 Tue Apr 16 09:36:04 EDT 2013 * doc updates (thanks @myrall) Plack-Middleware-CSRFBlock-0.10/dist.ini0000644000175000017500000000157112360533470016064 0ustar mmpmmpname = Plack-Middleware-CSRFBlock author = Rintaro Ishizaki author = William Wolf author = Matthew Phillips copyright_holder = the Authors of Plack-Middleware-CSRFBlock license = Perl_5 version = 0.10 [@Filter] -bundle = @Basic -remove = Readme -remove = GatherDir [GatherDir] exclude_filename = Makefile.PL exclude_filename = README.md [Prereqs / RuntimeRequires] Digest::SHA1 = 0 Time::HiRes = 0 HTML::Parser = 0 Plack = 0 [Prereqs / TestRequires] HTTP::Request::Common = 0 Plack::Middleware::Session = 0 [PkgVersion] [Test::Compile] [PodWeaver] finder = :InstallModules [ReadmeAnyFromPod / ReadmeMarkdownInBuild] type = markdown filename = README.md location = build [ReadmeAnyFromPod / ReadmePodInBuild] type = pod filename = README.pod location = build [CopyFilesFromBuild] copy = README.md [Repository] Plack-Middleware-CSRFBlock-0.10/LICENSE0000644000175000017500000004400212360533470015421 0ustar mmpmmpThis software is copyright (c) 2014 by the Authors of Plack-Middleware-CSRFBlock. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2014 by the Authors of Plack-Middleware-CSRFBlock. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2014 by the Authors of Plack-Middleware-CSRFBlock. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Plack-Middleware-CSRFBlock-0.10/README.md0000644000175000017500000001252712360533470015702 0ustar mmpmmp# NAME Plack::Middleware::CSRFBlock - Block CSRF Attacks with minimal changes to your app # VERSION version 0.10 # SYNOPSIS use Plack::Builder; my $app = sub { ... } builder { enable 'Session'; enable 'CSRFBlock'; $app; } # DESCRIPTION This middleware blocks CSRF. You can use this middleware without any modifications to your application, in most cases. Here is the strategy: - output filter When the application response content-type is "text/html" or "application/xhtml+xml", this inserts a hidden input tag that contains a token string into `form`s in the response body. For example, when the application response body is: input form
This becomes: input form
This affects `form` tags with `method="post"`, case insensitive. It is possible to add an optional meta tag by setting `meta_tag` to a defined value. The 'name' attribute of the HTML tag will be set to the value of `meta_tag`. For the previous example, when `meta_tag` is set to 'csrf\_token', the output will be: input form
- input check For every POST requests, this module checks the `X-CSRF-Token` header first, then `POST` input parameters. If the correct token is not found in either, then a 403 Forbidden is returned by default. Supports `application/x-www-form-urlencoded` and `multipart/form-data` for input parameters, but any `POST` will be validated with the `X-CSRF-Token` header. Thus, every `POST` will have to have either the header, or the appropriate form parameters in the body. - javascript This module can be used easily with javascript by having your javascript provide the `X-CSRF-Token` with any ajax `POST` requests it makes. You can get the `token` in javascript by getting the value of the `csrftoken` `meta` tag in the page . Here is sample code that will work for `jQuery`: $(document).ajaxSend(function(e, xhr, options) { var token = $("meta[name='csrftoken']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", token); }); This will include the X-CSRF-Token header with any `AJAX` requests made from your javascript. # OPTIONS use Plack::Builder; my $app = sub { ... } builder { enable 'Session'; enable 'CSRFBlock', parameter_name => 'csrf_secret', token_length => 20, session_key => 'csrf_token', blocked => sub { [302, [Location => 'http://www.google.com'], ['']]; }, onetime => 0, ; $app; } - parameter\_name (default:"SEC") Name of the input tag for the token. - meta\_tag (default:undef) Name of the `meta` tag added to the `head` tag of output pages. The content of this `meta` tag will be the token value. The purpose of this tag is to give javascript access to the token if needed for AJAX requests. If this attribute is not explicitly set the meta tag will not be included. - header\_name (default:"X-CSRF-Token") Name of the HTTP Header that the token can be sent in. This is useful for sending the header for Javascript AJAX requests, and this header is required for any post request that is not of type `application/x-www-form-urlencoded` or `multipart/form-data`. - token\_length (default:16); Length of the token string. Max value is 40. - session\_key (default:"csrfblock.token") This middleware uses [Plack::Middleware::Session](http://search.cpan.org/perldoc?Plack::Middleware::Session) for token storage. this is the session key for that. - blocked (default:403 response) The application called when CSRF is detected. Note: This application can read posted data, but DO NOT use them! - onetime (default:FALSE) If this is true, this middleware uses __onetime__ token, that is, whenever client sent collect token and this middleware detect that, token string is regenerated. This makes your applications more secure, but in many cases, is too strict. # SEE ALSO [Plack::Middleware::Session](http://search.cpan.org/perldoc?Plack::Middleware::Session) # AUTHORS - Rintaro Ishizaki - William Wolf - Matthew Phillips # COPYRIGHT AND LICENSE This software is copyright (c) 2014 by the Authors of Plack-Middleware-CSRFBlock. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.