/
GnuPG.pm
2108 lines (1806 loc) · 66.6 KB
/
GnuPG.pm
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2024 Best Practical Solutions, LLC
# <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work 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 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
use strict;
use warnings;
use 5.010;
package RT::Crypt::GnuPG;
use Role::Basic 'with';
with 'RT::Crypt::Role';
use IO::Handle;
use File::Which qw();
use RT::Crypt::GnuPG::CRLFHandle;
use GnuPG::Interface;
use RT::EmailParser ();
use RT::Util 'safe_run_child', 'mime_recommended_filename';
use URI::Escape;
=head1 NAME
RT::Crypt::GnuPG - GNU Privacy Guard encryption/decryption/verification/signing
=head1 DESCRIPTION
This module provides support for encryption and signing of outgoing
messages using GnuPG, as well as the decryption and verification of
incoming email.
=head1 CONFIGURATION
There are two relevant configuration options, both of which are hashes:
C<GnuPG> and C<GnuPGOptions>. The first one controls RT specific
options; it enables you to enable/disable the GPG protocol or change the
format of messages. The second one is a hash with options which are
passed to the C<gnupg> utility. You can use it to define a keyserver,
enable auto-retrieval of keys, or set almost any option which C<gnupg>
supports on your system.
=head2 %GnuPG
=head3 Enabling GnuPG
Set to true value to enable this subsystem:
Set( %GnuPG,
Enable => 1,
... other options ...
);
=head3 Setting the GnuPG Command
By default, RT looks for a command named C<gpg> in your C<$PATH> to run GnuPG.
If the command has a different name or is outside the C<$PATH> on your system,
you can specify the full path of the GnuPG command using the C<GnuPG> option:
Set( %GnuPG,
Enable => 1,
GnuPG => '/usr/local/bin/gpg2',
... other options ...
);
=head3 Format of outgoing messages
The format of outgoing messages can be controlled using the
C<OutgoingMessagesFormat> option in the RT config:
Set( %GnuPG,
... other options ...
OutgoingMessagesFormat => 'RFC',
... other options ...
);
or
Set( %GnuPG,
... other options ...
OutgoingMessagesFormat => 'Inline',
... other options ...
);
The two formats for GPG mail are as follows:
=over
=item RFC
This format, the default, is also known as GPG/MIME, and is described in
RFC3156 and RFC1847. The technique described in these RFCs is well
supported by many mail user agents (MUA); however, some older MUAs only
support inline signatures and encryption.
=item Inline
This format doesn't take advantage of MIME, but some mail clients do not
support GPG/MIME. In general, this format is discouraged because modern
mail clients typically do not support it well.
Text parts are signed using clear-text signatures. For each attachment,
the signature is attached separately as a file with a '.sig' extension
added to the filename. Encryption of text parts is implemented using
inline format, while other parts are replaced with attachments with the
filename extension '.pgp'.
=back
=head3 Passphrases
Passphrases for keys may be set by passing C<Passphrase>. It may be set
to a scalar (to use for all keys), an anonymous function, or a hash (to
look up by address). If the hash is used, the '' key is used as a
default.
=head2 %GnuPGOptions
Use this hash to set additional options of the 'gnupg' program. The
only options which are disallowed are options which alter the output
format or attempt to run commands; this includes C<--sign>,
C<--list-options>, etc.
Some GnuPG options take arguments, while others take none. (Such as
C<--use-agent>). For options without specific value use C<undef> as
hash value. To disable these options, you may comment them out or
delete them from the hash:
Set(%GnuPGOptions,
'option-with-value' => 'value',
'enabled-option-without-value' => undef,
# 'commented-option' => 'value or undef',
);
B<NOTE> that options may contain the '-' character and such options
B<MUST> be quoted, otherwise you will see the quite cryptic error C<gpg:
Invalid option "--0">.
Common options include:
=over
=item --homedir
The GnuPG home directory where the keyrings are stored; by default it is
set to F</opt/rt5/var/data/gpg>.
You can manage this data with the 'gpg' commandline utility using the
GNUPGHOME environment variable or C<--homedir> option. Other utilities may
be used as well.
In a standard installation, access to this directory should be granted
to the web server user which is running RT's web interface; however, if
you are running cronjobs or other utilities that access RT directly via
API, and may generate encrypted/signed notifications, then the users you
execute these scripts under must have access too.
Be aware that granting access to the directory to many users makes the
keys less secure -- and some features, such as auto-import of keys, may
not be available if directory permissions are too permissive. To enable
these features and suppress warnings about permissions on the directory,
add the C<--no-permission-warning> option to C<GnuPGOptions>.
=item --digest-algo
This option is required when the C<RFC> format for outgoing messages is
used. RT defaults to 'SHA1' by default, but you may wish to override
it. C<gnupg --version> will list the algorithms supported by your
C<gnupg> installation under 'hash functions'; these generally include
MD5, SHA1, RIPEMD160, and SHA256.
=item --use-agent
This option lets you use GPG Agent to cache the passphrase of secret
keys. See
L<http://www.gnupg.org/documentation/manuals/gnupg/Invoking-GPG_002dAGENT.html>
for information about GPG Agent.
=item --passphrase
This option lets you set the passphrase of RT's key directly. This
option is special in that it is not passed directly to GPG; rather, it
is put into a file that GPG then reads (which is more secure). The
downside is that anyone who has read access to your RT_SiteConfig.pm
file can see the passphrase -- thus we recommend the --use-agent option
whenever possible.
=item other
Read C<man gpg> to get list of all options this program supports.
=back
=head2 Per-queue options
Using the web interface it's possible to enable signing and/or encrypting by
default. As an administrative user of RT, open 'Admin' then 'Queues',
and select a queue. On the page you can see information about the queue's keys
at the bottom and two checkboxes to choose default actions.
As well, encryption is enabled for auto-replies and other notifications when
an encrypted message enters system via mailgate interface even if queue's
option is disabled.
=head2 Encrypting to untrusted keys
Due to limitations of GnuPG, it's impossible to encrypt to an untrusted key,
unless 'always trust' mode is enabled.
=head1 FOR DEVELOPERS
=head2 Documentation and references
=over
=item RFC1847
Security Multiparts for MIME: Multipart/Signed and Multipart/Encrypted.
Describes generic MIME security framework, "mulitpart/signed" and
"multipart/encrypted" MIME types.
=item RFC3156
MIME Security with Pretty Good Privacy (PGP), updates RFC2015.
=back
=cut
# gnupg options supported by GnuPG::Interface
# other otions should be handled via extra_args argument
my %supported_opt = map { $_ => 1 } qw(
always_trust
armor
batch
comment
compress_algo
default_key
encrypt_to
extra_args
force_v3_sigs
homedir
logger_fd
no_greeting
no_options
no_verbose
openpgp
options
passphrase_fd
quiet
recipients
rfc1991
status_fd
textmode
verbose
);
# DEV WARNING: always pass all STD* handles to GnuPG interface even if we don't
# need them, just pass 'IO::Handle->new()' and then close it after safe_run_child.
# we don't want to leak anything into FCGI/Apache/MP handles, this break things.
# So code should look like:
# my $handles = GnuPG::Handles->new(
# stdin => ($handle{'stdin'} = IO::Handle->new()),
# stdout => ($handle{'stdout'} = IO::Handle->new()),
# stderr => ($handle{'stderr'} = IO::Handle->new()),
# ...
# );
sub CallGnuPG {
my $self = shift;
my %args = (
Options => undef,
Signer => undef,
Recipients => [],
Passphrase => undef,
Command => undef,
CommandArgs => [],
Content => undef,
Handles => {},
Direct => undef,
Output => undef,
@_
);
my %handle = %{$args{Handles}};
my ($handles, $handle_list) = _make_gpg_handles( %handle );
$handles->options( $_ )->{'direct'} = 1
for @{$args{Direct} || [keys %handle] };
%handle = %$handle_list;
my $content = $args{Content};
my $command = $args{Command};
my %GnuPGOptions = RT->Config->Get('GnuPGOptions');
my %opt = (
'digest-algo' => 'SHA1',
'cert-digest-algo' => 'SHA256',
%GnuPGOptions,
%{ $args{Options} || {} },
);
my $gnupg = GnuPG::Interface->new( call => $self->GnuPGPath );
$gnupg->options->hash_init(
_PrepareGnuPGOptions( %opt ),
);
$gnupg->options->armor( 1 );
$gnupg->options->meta_interactive( 0 );
$gnupg->options->default_key( $args{Signer} )
if defined $args{Signer};
my %seen;
$gnupg->options->push_recipients( $_ ) for
map { RT::Crypt->UseKeyForEncryption($_) || $_ }
grep { !$seen{ $_ }++ }
@{ $args{Recipients} || [] };
$args{Passphrase} = $GnuPGOptions{passphrase}
unless defined $args{'Passphrase'};
$args{Passphrase} = $self->GetPassphrase( Address => $args{Signer} )
unless defined $args{'Passphrase'};
$gnupg->passphrase( $args{'Passphrase'} )
if defined $args{Passphrase};
eval {
local $SIG{'CHLD'} = 'DEFAULT';
my $pid = safe_run_child {
if ($command =~ /^--/) {
$gnupg->wrap_call(
handles => $handles,
commands => [$command],
command_args => $args{CommandArgs},
);
} else {
$gnupg->$command(
handles => $handles,
command_args => $args{CommandArgs},
);
}
};
{
local $SIG{'PIPE'} = 'IGNORE';
if (Scalar::Util::blessed($content) and $content->can("print")) {
$content->print( $handle{'stdin'} );
} elsif (ref($content) eq "SCALAR") {
$handle{'stdin'}->print( ${ $content } );
} elsif (defined $content) {
$handle{'stdin'}->print( $content );
}
close $handle{'stdin'} or die "Can't close gnupg input handle: $!";
$args{Callback}->(%handle) if $args{Callback};
}
waitpid $pid, 0;
};
my $err = $@;
if ($args{Output}) {
push @{$args{Output}}, readline $handle{stdout};
if (not close $handle{stdout}) {
$err ||= "Can't close gnupg output handle: $!";
}
}
my %res;
$res{'exit_code'} = $?;
foreach ( qw(stderr logger status) ) {
$res{$_} = do { local $/ = undef; readline $handle{$_} };
delete $res{$_} unless $res{$_} && $res{$_} =~ /\S/s;
if (not close $handle{$_}) {
$err ||= "Can't close gnupg $_ handle: $!";
}
}
$RT::Logger->debug( $res{'status'} ) if $res{'status'};
$RT::Logger->warning( $res{'stderr'} ) if $res{'stderr'};
$RT::Logger->error( $res{'logger'} ) if $res{'logger'} && $?;
if ( $err || $res{'exit_code'} ) {
$res{'message'} = $err? $err : "gpg exited with error code ". ($res{'exit_code'} >> 8);
}
return %res;
}
sub SignEncrypt {
my $self = shift;
my $format = lc RT->Config->Get('GnuPG')->{'OutgoingMessagesFormat'} || 'RFC';
if ( $format eq 'inline' ) {
return $self->SignEncryptInline( @_ );
} else {
return $self->SignEncryptRFC3156( @_ );
}
}
sub SignEncryptRFC3156 {
my $self = shift;
my %args = (
Entity => undef,
Sign => 1,
Signer => undef,
Passphrase => undef,
Encrypt => 1,
Recipients => undef,
@_
);
my $entity = $args{'Entity'};
my %res;
if ( $args{'Sign'} && !$args{'Encrypt'} ) {
# required by RFC3156(Ch. 5) and RFC1847(Ch. 2.1)
foreach ( grep !$_->is_multipart, $entity->parts_DFS ) {
my $tenc = $_->head->mime_encoding;
unless ( $tenc =~ m/^(?:7bit|quoted-printable|base64)$/i ) {
$_->head->mime_attr( 'Content-Transfer-Encoding'
=> $_->effective_type =~ m{^text/}? 'quoted-printable': 'base64'
);
}
}
$entity->make_multipart( 'mixed', Force => 1 );
my @signature;
# We use RT::Crypt::GnuPG::CRLFHandle to canonicalize the
# MIME::Entity output to use \r\n instead of \n for its newlines
%res = $self->CallGnuPG(
Signer => $args{'Signer'},
Command => "detach_sign",
Handles => { stdin => RT::Crypt::GnuPG::CRLFHandle->new },
Direct => [],
Passphrase => $args{'Passphrase'},
Content => $entity->parts(0),
Output => \@signature,
);
return %res if $res{message};
# setup RFC1847(Ch.2.1) requirements
my $protocol = 'application/pgp-signature';
my $algo = RT->Config->Get('GnuPGOptions')->{'digest-algo'} || 'SHA1';
$entity->head->mime_attr( 'Content-Type' => 'multipart/signed' );
$entity->head->mime_attr( 'Content-Type.protocol' => $protocol );
$entity->head->mime_attr( 'Content-Type.micalg' => 'pgp-'. lc $algo );
$entity->attach(
Type => $protocol,
Disposition => 'inline',
Data => \@signature,
Encoding => '7bit',
);
}
if ( $args{'Encrypt'} ) {
my @recipients = map $_->address,
map Email::Address->parse( Encode::decode( "UTF-8", $_ ) ),
map $entity->head->get( $_ ),
qw(To Cc Bcc);
my ($tmp_fh, $tmp_fn) = File::Temp::tempfile( UNLINK => 1 );
binmode $tmp_fh, ':raw';
$entity->make_multipart( 'mixed', Force => 1 );
%res = $self->CallGnuPG(
Signer => $args{'Signer'},
Recipients => \@recipients,
Command => ( $args{'Sign'} ? "sign_and_encrypt" : "encrypt" ),
Handles => { stdout => $tmp_fh },
Passphrase => $args{'Passphrase'},
Content => $entity->parts(0),
);
return %res if $res{message};
my $protocol = 'application/pgp-encrypted';
$entity->parts([]);
$entity->head->mime_attr( 'Content-Type' => 'multipart/encrypted' );
$entity->head->mime_attr( 'Content-Type.protocol' => $protocol );
$entity->attach(
Type => $protocol,
Disposition => 'inline',
Data => ['Version: 1',''],
Encoding => '7bit',
);
$entity->attach(
Type => 'application/octet-stream',
Disposition => 'inline',
Path => $tmp_fn,
Filename => '',
Encoding => '7bit',
);
$entity->parts(-1)->bodyhandle->{'_dirty_hack_to_save_a_ref_tmp_fh'} = $tmp_fh;
}
return %res;
}
sub SignEncryptInline {
my $self = shift;
my %args = ( @_ );
my $entity = $args{'Entity'};
my %res;
$entity->make_singlepart;
if ( $entity->is_multipart ) {
foreach ( $entity->parts ) {
%res = $self->SignEncryptInline( @_, Entity => $_ );
return %res if $res{'exit_code'};
}
return %res;
}
return $self->_SignEncryptTextInline( @_ )
if $entity->effective_type =~ /^text\//i;
return $self->_SignEncryptAttachmentInline( @_ );
}
sub _SignEncryptTextInline {
my $self = shift;
my %args = (
Entity => undef,
Sign => 1,
Signer => undef,
Passphrase => undef,
Encrypt => 1,
Recipients => undef,
@_
);
return unless $args{'Sign'} || $args{'Encrypt'};
my ($tmp_fh, $tmp_fn) = File::Temp::tempfile( UNLINK => 1 );
binmode $tmp_fh, ':raw';
my $entity = $args{'Entity'};
my %res = $self->CallGnuPG(
Signer => $args{'Signer'},
Recipients => $args{'Recipients'},
Command => ( $args{'Sign'} && $args{'Encrypt'}
? 'sign_and_encrypt'
: ( $args{'Sign'}
? 'clearsign'
: 'encrypt' ) ),
Handles => { stdout => $tmp_fh },
Passphrase => $args{'Passphrase'},
Content => $entity->bodyhandle,
);
return %res if $res{message};
$entity->bodyhandle( MIME::Body::File->new( $tmp_fn) );
$entity->{'__store_tmp_handle_to_avoid_early_cleanup'} = $tmp_fh;
return %res;
}
sub _SignEncryptAttachmentInline {
my $self = shift;
my %args = (
Entity => undef,
Sign => 1,
Signer => undef,
Passphrase => undef,
Encrypt => 1,
Recipients => undef,
@_
);
return unless $args{'Sign'} || $args{'Encrypt'};
my $entity = $args{'Entity'};
my ($tmp_fh, $tmp_fn) = File::Temp::tempfile( UNLINK => 1 );
binmode $tmp_fh, ':raw';
my %res = $self->CallGnuPG(
Signer => $args{'Signer'},
Recipients => $args{'Recipients'},
Command => ( $args{'Sign'} && $args{'Encrypt'}
? 'sign_and_encrypt'
: ( $args{'Sign'}
? 'detach_sign'
: 'encrypt' ) ),
Handles => { stdout => $tmp_fh },
Passphrase => $args{'Passphrase'},
Content => $entity->bodyhandle,
);
return %res if $res{message};
my $filename = mime_recommended_filename( $entity ) || 'no_name';
if ( $args{'Sign'} && !$args{'Encrypt'} ) {
$entity->make_multipart;
$entity->attach(
Type => 'application/octet-stream',
Path => $tmp_fn,
Filename => "$filename.sig",
Disposition => 'attachment',
);
} else {
$entity->bodyhandle(MIME::Body::File->new( $tmp_fn) );
$entity->effective_type('application/octet-stream');
$entity->head->mime_attr( $_ => "$filename.pgp" )
foreach (qw(Content-Type.name Content-Disposition.filename));
}
$entity->{'__store_tmp_handle_to_avoid_early_cleanup'} = $tmp_fh;
return %res;
}
sub SignEncryptContent {
my $self = shift;
my %args = (
Content => undef,
Sign => 1,
Signer => undef,
Passphrase => undef,
Encrypt => 1,
Recipients => undef,
@_
);
return unless $args{'Sign'} || $args{'Encrypt'};
my ($tmp_fh, $tmp_fn) = File::Temp::tempfile( UNLINK => 1 );
binmode $tmp_fh, ':raw';
my %res = $self->CallGnuPG(
Signer => $args{'Signer'},
Recipients => $args{'Recipients'},
Command => ( $args{'Sign'} && $args{'Encrypt'}
? 'sign_and_encrypt'
: ( $args{'Sign'}
? 'clearsign'
: 'encrypt' ) ),
Handles => { stdout => $tmp_fh },
Passphrase => $args{'Passphrase'},
Content => $args{'Content'},
);
return %res if $res{message};
${ $args{'Content'} } = '';
seek $tmp_fh, 0, 0;
while (1) {
my $status = read $tmp_fh, my $buf, 4*1024;
unless ( defined $status ) {
$RT::Logger->crit( "couldn't read message: $!" );
} elsif ( !$status ) {
last;
}
${ $args{'Content'} } .= $buf;
}
return %res;
}
sub CheckIfProtected {
my $self = shift;
my %args = ( Entity => undef, @_ );
my $entity = $args{'Entity'};
# we check inline PGP block later in another sub
return () unless $entity->is_multipart;
# RFC3156, multipart/{signed,encrypted}
my $type = $entity->effective_type;
return () unless $type =~ /^multipart\/(?:encrypted|signed)$/;
unless ( $entity->parts == 2 ) {
$RT::Logger->error( "Encrypted or signed entity must has two subparts. Skipped" );
return ();
}
my $protocol = $entity->head->mime_attr( 'Content-Type.protocol' );
unless ( $protocol ) {
# if protocol is not set then we can check second part for PGP message
$RT::Logger->error( "Entity is '$type', but has no protocol defined. Checking for PGP part" );
my $protected = $self->_CheckIfProtectedInline( $entity->parts(1), 1 );
return () unless $protected;
if ( $protected eq 'signature' ) {
$RT::Logger->debug("Found part signed according to RFC3156");
return (
Type => 'signed',
Format => 'RFC3156',
Top => $entity,
Data => $entity->parts(0),
Signature => $entity->parts(1),
);
} else {
$RT::Logger->debug("Found part encrypted according to RFC3156");
return (
Type => 'encrypted',
Format => 'RFC3156',
Top => $entity,
Data => $entity->parts(1),
Info => $entity->parts(0),
);
}
}
elsif ( $type eq 'multipart/encrypted' ) {
unless ( $protocol eq 'application/pgp-encrypted' ) {
$RT::Logger->info( "Skipping protocol '$protocol', only 'application/pgp-encrypted' is supported" );
return ();
}
$RT::Logger->debug("Found part encrypted according to RFC3156");
return (
Type => 'encrypted',
Format => 'RFC3156',
Top => $entity,
Data => $entity->parts(1),
Info => $entity->parts(0),
);
} else {
unless ( $protocol eq 'application/pgp-signature' ) {
$RT::Logger->info( "Skipping protocol '$protocol', only 'application/pgp-signature' is supported" );
return ();
}
$RT::Logger->debug("Found part signed according to RFC3156");
return (
Type => 'signed',
Format => 'RFC3156',
Top => $entity,
Data => $entity->parts(0),
Signature => $entity->parts(1),
);
}
return ();
}
sub FindScatteredParts {
my $self = shift;
my %args = ( Parts => [], Skip => {}, @_ );
my @res;
my @parts = @{ $args{'Parts'} };
# attachments signed with signature in another part
{
my @file_indices;
for (my $i = 0; $i < @parts; $i++ ) {
my $part = $parts[ $i ];
# we can not associate a signature within an attachment
# without file names
my $fname = $part->head->recommended_filename;
next unless $fname;
my $type = $part->effective_type;
if ( $type eq 'application/pgp-signature' ) {
push @file_indices, $i;
}
elsif ( $type eq 'application/octet-stream' && $fname =~ /\.sig$/i ) {
push @file_indices, $i;
}
}
foreach my $i ( @file_indices ) {
my $sig_part = $parts[ $i ];
my $sig_name = $sig_part->head->recommended_filename;
my ($file_name) = $sig_name =~ /^(.*?)(?:\.sig)?$/;
my ($data_part_idx) =
grep $file_name eq ($parts[$_]->head->recommended_filename||''),
grep $sig_part ne $parts[$_],
0 .. @parts - 1;
unless ( defined $data_part_idx ) {
$RT::Logger->error("Found $sig_name attachment, but didn't find $file_name");
next;
}
my $data_part_in = $parts[ $data_part_idx ];
$RT::Logger->debug("Found signature (in '$sig_name') of attachment '$file_name'");
$args{'Skip'}{$data_part_in} = 1;
$args{'Skip'}{$sig_part} = 1;
push @res, {
Type => 'signed',
Format => 'Attachment',
Top => $args{'Parents'}{$sig_part},
Data => $data_part_in,
Signature => $sig_part,
};
}
}
my $file_extension_regex = join '|', @{ RT->Config->Get('GnuPG')->{FileExtensions} };
# attachments with inline encryption
foreach my $part ( @parts ) {
next if $args{'Skip'}{$part};
my $fname = $part->head->recommended_filename || '';
next unless $fname =~ /\.(?:$file_extension_regex)$/;
# skip pgp keys, which could have .asc file extension
next if ( $part->head->mime_type // '' ) eq 'application/pgp-keys';
$RT::Logger->debug("Found encrypted attachment '$fname'");
$args{'Skip'}{$part} = 1;
push @res, {
Type => 'encrypted',
Format => 'Attachment',
Data => $part,
};
}
# inline PGP block
foreach my $part ( @parts ) {
next if $args{'Skip'}{$part};
my $type = $self->_CheckIfProtectedInline( $part );
next unless $type;
my $file = ($part->head->recommended_filename||'') =~ /\.(?:$file_extension_regex)$/;
$args{'Skip'}{$part} = 1;
push @res, {
Type => $type,
Format => !$file || $type eq 'signed'? 'Inline' : 'Attachment',
Data => $part,
};
}
return @res;
}
sub _CheckIfProtectedInline {
my $self = shift;
my $entity = shift;
my $check_for_signature = shift || 0;
my $io = $entity->open('r');
unless ( $io ) {
$RT::Logger->warning( "Entity of type ". $entity->effective_type ." has no body" );
return '';
}
# Deal with "partitioned" PGP mail, which (contrary to common
# sense) unnecessarily applies a base64 transfer encoding to PGP
# mail (whose content is already base64-encoded).
if ( $entity->bodyhandle->is_encoded and $entity->head->mime_encoding ) {
my $decoder = MIME::Decoder->new( $entity->head->mime_encoding );
if ($decoder) {
local $@;
eval {
my $buf = '';
open my $fh, '>', \$buf
or die "Couldn't open scalar for writing: $!";
binmode $fh, ":raw";
$decoder->decode($io, $fh);
close $fh or die "Couldn't close scalar: $!";
open $fh, '<', \$buf
or die "Couldn't re-open scalar for reading: $!";
binmode $fh, ":raw";
$io = $fh;
1;
} or do {
$RT::Logger->error("Couldn't decode body: $@");
}
}
}
while ( defined($_ = $io->getline) ) {
if ( /^-----BEGIN PGP (SIGNED )?MESSAGE-----\s*$/ ) {
return $1? 'signed': 'encrypted';
}
elsif ( $check_for_signature && !/^-----BEGIN PGP SIGNATURE-----\s*$/ ) {
return 'signature';
}
}
$io->close;
return '';
}
sub VerifyDecrypt {
my $self = shift;
my %args = (
Info => undef,
@_
);
my %res;
my $item = $args{'Info'};
my $status_on;
if ( $item->{'Type'} eq 'signed' ) {
if ( $item->{'Format'} eq 'RFC3156' ) {
%res = $self->VerifyRFC3156( %$item );
$status_on = $item->{'Top'};
} elsif ( $item->{'Format'} eq 'Inline' ) {
%res = $self->VerifyInline( %$item );
$status_on = $item->{'Data'};
} elsif ( $item->{'Format'} eq 'Attachment' ) {
%res = $self->VerifyAttachment( %$item );
$status_on = $item->{'Data'};
} else {
die "Unknown format '".$item->{'Format'} . "' of GnuPG signed part";
}
} elsif ( $item->{'Type'} eq 'encrypted' ) {
if ( $item->{'Format'} eq 'RFC3156' ) {
%res = $self->DecryptRFC3156( %$item );
$status_on = $item->{'Top'};
} elsif ( $item->{'Format'} eq 'Inline' ) {
%res = $self->DecryptInline( %$item );
$status_on = $item->{'Data'};
} elsif ( $item->{'Format'} eq 'Attachment' ) {
%res = $self->DecryptAttachment( %$item );
$status_on = $item->{'Data'};
} else {
die "Unknown format '".$item->{'Format'} . "' of GnuPG encrypted part";
}
} else {
die "Unknown type '".$item->{'Type'} . "' of protected item";
}
return (%res, status_on => $status_on);
}
sub VerifyInline { return (shift)->DecryptInline( @_ ) }
sub VerifyAttachment {
my $self = shift;
my %args = ( Data => undef, Signature => undef, @_ );
foreach ( $args{'Data'}, $args{'Signature'} ) {
next unless $_->bodyhandle->is_encoded;
require RT::EmailParser;
RT::EmailParser->_DecodeBody($_);
}
my ($tmp_fh, $tmp_fn) = File::Temp::tempfile( UNLINK => 1 );
binmode $tmp_fh, ':raw';
$args{'Data'}->bodyhandle->print( $tmp_fh );
$tmp_fh->flush;
my %res = $self->CallGnuPG(
Command => "verify",
CommandArgs => [ '-', $tmp_fn ],
Passphrase => $args{'Passphrase'},
Content => $args{'Signature'}->bodyhandle,
);
$args{'Top'}->parts( [
grep "$_" ne $args{'Signature'}, $args{'Top'}->parts
] );
$args{'Top'}->make_singlepart;