]> git.uio.no Git - usit-rt.git/blob - lib/RT/Interface/Email/Auth/Crypt.pm
Putting 4.2.0 on top of 4.0.17
[usit-rt.git] / lib / RT / Interface / Email / Auth / Crypt.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2013 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 package RT::Interface::Email::Auth::Crypt;
50
51 use strict;
52 use warnings;
53
54 =head1 NAME
55
56 RT::Interface::Email::Auth::Crypt - decrypting and verifying protected emails
57
58 =head2 DESCRIPTION
59
60 This mail plugin decrypts and verifies incoming emails. Supported
61 encryption protocols are GnuPG and SMIME.
62
63 This code is independant from code that encrypts/sign outgoing emails, so
64 it's possible to decrypt data without bringing in encryption. To enable
65 it put the module in the mail plugins list:
66
67     Set(@MailPlugins, 'Auth::MailFrom', 'Auth::Crypt', ...other filters...);
68
69 =head3 GnuPG
70
71 To use the gnupg-secured mail gateway, you need to do the following:
72
73 Set up a GnuPG key directory with a pubring containing only the keys
74 you care about and specify the following in your SiteConfig.pm
75
76     Set(%GnuPGOptions, homedir => '/opt/rt4/var/data/GnuPG');
77
78 Read also: L<RT::Crypt> and L<RT::Crypt::GnuPG>.
79
80 =head3 SMIME
81
82 To use the SMIME-secured mail gateway, you need to do the following:
83
84 Set up a SMIME key directory with files containing keys for queues'
85 addresses and specify the following in your SiteConfig.pm
86
87     Set(%SMIME,
88         Enable => 1,
89         OpenSSL => '/usr/bin/openssl',
90         Keyring => '/opt/rt4/var/data/smime',
91         CAPath  => '/opt/rt4/var/data/smime/signing-ca.pem',
92         Passphrase => {
93             'queue.address@example.com' => 'passphrase',
94             '' => 'fallback',
95         },
96     );
97
98 Read also: L<RT::Crypt> and L<RT::Crypt::SMIME>.
99
100 =cut
101
102 sub ApplyBeforeDecode { return 1 }
103
104 use RT::Crypt;
105 use RT::EmailParser ();
106
107 sub GetCurrentUser {
108     my %args = (
109         Message       => undef,
110         RawMessageRef => undef,
111         Queue         => undef,
112         Actions       => undef,
113         @_
114     );
115
116     # we clean all possible headers
117     my @headers =
118         qw(
119             X-RT-Incoming-Encryption
120             X-RT-Incoming-Signature X-RT-Privacy
121             X-RT-Sign X-RT-Encrypt
122         ),
123         map "X-RT-$_-Status", RT::Crypt->Protocols;
124     foreach my $p ( $args{'Message'}->parts_DFS ) {
125         $p->head->delete($_) for @headers;
126     }
127
128     my (@res) = RT::Crypt->VerifyDecrypt(
129         %args,
130         Entity => $args{'Message'},
131     );
132     if ( !@res ) {
133         if (RT->Config->Get('Crypt')->{'RejectOnUnencrypted'}) {
134             EmailErrorToSender(
135                 %args,
136                 Template  => 'Error: unencrypted message',
137                 Arguments => { Message  => $args{'Message'} },
138             );
139             return (-1, 'rejected because the message is unencrypted with RejectOnUnencrypted enabled');
140         }
141         else {
142             $args{'Message'}->head->replace(
143                 'X-RT-Incoming-Encryption' => 'Not encrypted'
144             );
145         }
146         return 1;
147     }
148
149     if ( grep {$_->{'exit_code'}} @res ) {
150         my @fail = grep {$_->{status}{Status} ne "DONE"}
151                    map { my %ret = %{$_}; map {+{%ret, status => $_}} RT::Crypt->ParseStatus( Protocol => $_->{Protocol}, Status => $_->{status})}
152                    @res;
153         for my $fail ( @fail ) {
154             $RT::Logger->warning("Failure during ".$fail->{Protocol}." ". lc($fail->{status}{Operation}) . ": ". $fail->{status}{Message});
155         }
156         my $reject = HandleErrors( Message => $args{'Message'}, Result => \@res );
157         return (0, 'rejected because of problems during decrypting and verifying')
158             if $reject;
159     }
160
161     # attach the original encrypted message
162     $args{'Message'}->attach(
163         Type        => 'application/x-rt-original-message',
164         Disposition => 'inline',
165         Data        => ${ $args{'RawMessageRef'} },
166     );
167
168     my @found;
169     my @check_protocols = RT::Crypt->EnabledOnIncoming;
170     foreach my $part ( $args{'Message'}->parts_DFS ) {
171         my $decrypted;
172
173         foreach my $protocol ( @check_protocols ) {
174             my @status = grep defined && length,
175                 $part->head->get( "X-RT-$protocol-Status" );
176             next unless @status;
177
178             push @found, $protocol;
179
180             for ( map RT::Crypt->ParseStatus( Protocol => $protocol, Status => "$_" ), @status ) {
181                 if ( $_->{Operation} eq 'Decrypt' && $_->{Status} eq 'DONE' ) {
182                     $decrypted = 1;
183                 }
184                 if ( $_->{Operation} eq 'Verify' && $_->{Status} eq 'DONE' ) {
185                     $part->head->replace(
186                         'X-RT-Incoming-Signature' => $_->{UserString}
187                     );
188                 }
189             }
190         }
191
192         $part->head->replace(
193             'X-RT-Incoming-Encryption' => 
194                 $decrypted ? 'Success' : 'Not encrypted'
195         );
196     }
197
198     my %seen;
199     $args{'Message'}->head->replace( 'X-RT-Privacy' => $_ )
200         foreach grep !$seen{$_}++, @found;
201
202     return 1;
203 }
204
205 sub HandleErrors {
206     my %args = (
207         Message => undef,
208         Result => [],
209         @_
210     );
211
212     my $reject = 0;
213
214     my %sent_once = ();
215     foreach my $run ( @{ $args{'Result'} } ) {
216         my @status = RT::Crypt->ParseStatus( Protocol => $run->{'Protocol'}, Status => $run->{'status'} );
217         unless ( $sent_once{'NoPrivateKey'} ) {
218             unless ( CheckNoPrivateKey( Message => $args{'Message'}, Status => \@status ) ) {
219                 $sent_once{'NoPrivateKey'}++;
220                 $reject = 1 if RT->Config->Get('Crypt')->{'RejectOnMissingPrivateKey'};
221             }
222         }
223         unless ( $sent_once{'BadData'} ) {
224             unless ( CheckBadData( Message => $args{'Message'}, Status => \@status ) ) {
225                 $sent_once{'BadData'}++;
226                 $reject = 1 if RT->Config->Get('Crypt')->{'RejectOnBadData'};
227             }
228         }
229     }
230     return $reject;
231 }
232
233 sub CheckNoPrivateKey {
234     my %args = (Message => undef, Status => [], @_ );
235     my @status = @{ $args{'Status'} };
236
237     my @decrypts = grep $_->{'Operation'} eq 'Decrypt', @status;
238     return 1 unless @decrypts;
239     foreach my $action ( @decrypts ) {
240         # if at least one secrete key exist then it's another error
241         return 1 if
242             grep !$_->{'User'}{'SecretKeyMissing'},
243                 @{ $action->{'EncryptedTo'} };
244     }
245
246     $RT::Logger->error("Couldn't decrypt a message: have no private key");
247
248     return EmailErrorToSender(
249         %args,
250         Template  => 'Error: no private key',
251         Arguments => { Message   => $args{'Message'} },
252     );
253 }
254
255 sub CheckBadData {
256     my %args = (Message => undef, Status => [], @_ );
257     my @bad_data_messages = 
258         map $_->{'Message'},
259         grep $_->{'Status'} ne 'DONE' && $_->{'Operation'} eq 'Data',
260         @{ $args{'Status'} };
261     return 1 unless @bad_data_messages;
262
263     return EmailErrorToSender(
264         %args,
265         Template  => 'Error: bad encrypted data',
266         Arguments => { Messages  => [ @bad_data_messages ] },
267     );
268 }
269
270 sub EmailErrorToSender {
271     my %args = (@_);
272
273     $args{'Arguments'} ||= {};
274     $args{'Arguments'}{'TicketObj'} ||= $args{'Ticket'};
275
276     my $address = (RT::Interface::Email::ParseSenderAddressFromHead( $args{'Message'}->head ))[0];
277     my ($status) = RT::Interface::Email::SendEmailUsingTemplate(
278         To        => $address,
279         Template  => $args{'Template'},
280         Arguments => $args{'Arguments'},
281         InReplyTo => $args{'Message'},
282     );
283     unless ( $status ) {
284         $RT::Logger->error("Couldn't send '$args{'Template'}''");
285     }
286     return 0;
287 }
288
289 RT::Base->_ImportOverlays();
290
291 1;