summaryrefslogtreecommitdiff
path: root/cspreport.pm
blob: 99cee371424c2e5618e8eb73d8a4a447978e8919 (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
86
87
88
89
90
91
92
93
94
95
96
package cspreport;
use strict;
use warnings;
use base 'CGI::Application';
use utf8;
use Data::Dumper;
use JSON;
use Net::SMTP;
use Email::MIME;
use MIME::Base64;
use Authen::SASL;

sub setup {
    my $self = shift;
    $self->start_mode('mode1');
    $self->run_modes( 'mode1' => 'cspreport' );
}

sub cspreport {
    my $self = shift;
    my $q    = $self->query();
    $self->header_add( -type => 'text/plain; charset=UTF-8' );

    my $report = $q->param('POSTDATA');
    send_report($report);

    return "OK\n";
}

sub send_report {
    my $report = shift;
    my ( $smtp, @parts, $mime );

    $smtp = Net::SMTP->new( 'localhost', SSL => 1 );
    $smtp->auth(
        Authen::SASL->new(
            mechanism => 'PLAIN',
            callback  => {
                user => '',
                pass => '')
            }
        )
    );
    $smtp->mail('CSP Report <cspreport@domain>');
    $smtp->recipient('Webmaster <webmaster@domain>');
    @parts = (
        Email::MIME->create(
            body_str   => parse_report($report),
            attributes => {
                content_type => 'text/plain',
                charset      => 'UTF-8',
                encoding     => '8bit',
            }
        ),
        Email::MIME->create(
            body_str   => $report,
            attributes => {
                content_type => 'application/json',
                charset      => 'UTF-8',
                encoding     => '8bit',
                name         => 'csp.json',
                disposition  => 'attachment',
            }
        )
    );
    $mime = Email::MIME->create(
        header_str => [
            From    => 'CSP Report <cspreport@domain>',
            To      => 'Webmaster <webmaster@domain>',
            Subject => 'New CSP Report'
        ],
        parts      => \@parts,
        attributes => {
            charset  => 'UTF-8',
            encoding => '8bit',
        }
    );
    $smtp->data( $mime->as_string );
    $smtp->quit();
}

sub parse_report {
    my $report = shift;
    my $output = '';
    my $json   = decode_json($report);
    $output .= '   Quelle: ' . $json->{'csp-report'}->{'document-uri'} . "\n";
    $output .= ' Resource: ' . $json->{'csp-report'}->{'blocked-uri'} . "\n";
    $output .= ' Referrer: ' . $json->{'csp-report'}->{'referrer'} . "\n";
    $output .=
      'Direktive: ' . $json->{'csp-report'}->{'violated-directive'} . "\n";
    $output .=
      '   Policy: ' . $json->{'csp-report'}->{'original-policy'} . "\n";
    return $output;
}

1;