blib/lib/Mail/GnuPG.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 86.6% 13 / 15 CC 1 SCAR 0.7
CC
1
Cov
82%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Build ↑ Summary
1 package Mail::GnuPG;
2  
3 =head1 NAME
4  
5 Mail::GnuPG - Process email with GPG.
6  
7 =head1 SYNOPSIS
8  
9 use Mail::GnuPG;
10 my $mg = new Mail::GnuPG( key => 'ABCDEFGH' );
11 $ret = $mg->mime_sign( $MIMEObj, 'you@my.dom' );
12  
13 =head1 DESCRIPTION
14  
15 Use GnuPG::Interface to process or create PGP signed or encrypted
16 email.
17  
18 =cut
19  
20 7 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 our $VERSION = '0.15_3';
25 my $DEBUG = 0;
26  
27 7 ▶use GnuPG::Interface;
Subroutine BEGIN: called CC=1 SCAR=2.6
28 use File::Spec;
29 use File::Temp;
30 use IO::Handle;
31 use MIME::Entity;
32 use MIME::Parser;
33 use Mail::Address;
34 use IO::Select;
35 use Errno qw(EPIPE);
36  
37 =head2 new
38  
39 Create a new Mail::GnuPG instance.
40  
41 Arguments:
42 Paramhash...
43  
44 key => gpg key id
45 keydir => gpg configuration/key directory
46 passphrase => primary key password
47 use_agent => use gpg-agent if non-zero
48 # FIXME: we need more things here, maybe primary key id.
49  
50  
51 =cut
52  
53 sub new {
54 my $proto = shift;
55 my $class = ref($proto) || $proto;
56 my $self = {
57 key => undef,
58 keydir => undef,
59 passphrase => "",
60 gpg_path => "gpg",
61 use_agent => 0,
62 @_
63 };
64 $self->{last_message} = [];
65 $self->{plaintext} = [];
66 bless ($self, $class);
67 return $self;
68 }
69  
70 sub _set_options {
71 my ($self,$gnupg) = @_;
72 $gnupg->options->meta_interactive( 0 );
73 $gnupg->options->hash_init( armor => 1,
74 ( defined $self->{keydir} ?
75 (homedir => $self->{keydir}) : () ),
76 ( defined $self->{key} ?
77 ( default_key => $self->{key} ) : () ),
78 # ( defined $self->{passphrase} ?
79 # ( passphrase => $self->{passphrase} ) : () ),
80 );
81 $gnupg->call( $self->{gpg_path} ) if defined $self->{gpg_path};
82 }
83  
84  
85 =head2 decrypt
86  
87 Decrypt an encrypted message
88  
89 Input:
90 MIME::Entity containing email message to decrypt.
91  
92 The message can either be in RFC compliant-ish multipart/encrypted
93 format, or just a single part ascii armored message.
94  
95 Output:
96 On Failure:
97 Exit code of gpg. (0 on success)
98  
99 On Success: (just encrypted)
100 (0, undef, undef)
101  
102 On success: (signed and encrypted)
103 ( 0,
104 keyid, # ABCDDCBA
105 emailaddress # Foo Bar <foo@bar.com>
106 )
107  
108 where the keyid is the key that signed it, and emailaddress is full
109 name and email address of the primary uid
110  
111  
112 $self->{last_message} => any errors from gpg
113 $self->{plaintext} => plaintext output from gpg
114 $self->{decrypted} => parsed output as MIME::Entity
115  
116 =cut
117  
118 sub _agent_args{
119 my $self=shift;
120 return $self->{use_agent} ? ('command_args' => ['--use-agent']) : ();
121 }
122  
123 sub decrypt {
124 my ($self, $message) = @_;
125 my $ciphertext = "";
126  
127 $self->{last_message} = [];
128  
129 unless (ref $message && $message->isa("MIME::Entity")) {
130 die "decrypt only knows about MIME::Entitys right now";
131 return 255;
132 }
133  
134 my $armor_message = 0;
135 if ($message->effective_type =~ m!multipart/encrypted!) {
136 die "multipart/encrypted with more than two parts"
137 if ($message->parts != 2);
138 die "Content-Type not pgp-encrypted"
139 unless $message->parts(0)->effective_type =~
140 m!application/pgp-encrypted!;
141 $ciphertext = $message->parts(1)->stringify_body;
142 }
143 elsif ($message->bodyhandle->as_string
144 =~ m!^-----BEGIN PGP MESSAGE-----!m ) {
145 $ciphertext = $message->bodyhandle->as_string;
146 $armor_message = 1;
147 }
148 else {
149 die "Unknown Content-Type or no PGP message in body"
150 }
151  
152 my $gnupg = GnuPG::Interface->new();
153 $self->_set_options($gnupg);
154 # how we create some handles to interact with GnuPG
155 # This time we'll catch the standard error for our perusing
156 # as well as passing in the passphrase manually
157 # as well as the status information given by GnuPG
158 my ( $input, $output, $error, $passphrase_fh, $status_fh )
159 = ( new IO::Handle, new IO::Handle,new IO::Handle,
160 new IO::Handle,new IO::Handle,);
161  
162 my $handles = GnuPG::Handles->new( stdin => $input,
163 stdout => $output,
164 stderr => $error,
165 passphrase => $passphrase_fh,
166 status => $status_fh,
167 );
168  
169 # this sets up the communication
170 my $pid = $gnupg->decrypt( handles => $handles , $self->_agent_args );
171  
172 die "NO PASSPHRASE" unless defined $passphrase_fh;
173 my $read = _communicate([$output, $error, $status_fh],
174 [$input, $passphrase_fh],
175 { $input => $ciphertext,
176 $passphrase_fh => $self->{passphrase}}
177 );
178  
179 my @plaintext = split(/^/m, $read->{$output});
180 my @error_output = split(/^/m, $read->{$error});
181 my @status_info = split(/^/m, $read->{$status_fh});
182  
183 waitpid $pid, 0;
184 my $return = $?;
185 $return = 0 if $return == -1;
186  
187 my $exit_value = $return >> 8;
188
189  
190  
191 $self->{last_message} = \@error_output;
192 $self->{plaintext} = \@plaintext;
193  
194 my $parser = new MIME::Parser;
195 $parser->output_to_core(1);
196  
197 # for armor message (which usually contain no MIME entity)
198 # and if the first line seems to be no header, add an empty
199 # line at the top, otherwise the first line of a text message
200 # will be removed by the parser.
201 if ( $armor_message and $plaintext[0] and $plaintext[0] !~ /^[\w-]+:/ ) {
202 unshift @plaintext, "\n";
203 }
204  
205 my $entity = $parser->parse_data(\@plaintext);
206 $self->{decrypted} = $entity;
207  
208 return $exit_value if $exit_value; # failure
209  
210 # if the message was signed and encrypted, extract the signature
211 # information and return it. In some theory or another, you can't
212 # trust an unsigned encrypted message is from who it says signed it.
213 # (Although I think it would have to go hand in hand at some point.)
214  
215 # FIXME: these regex are likely to break under non english locales.
216 my $result = join "", @error_output;
217 my ($keyid) = $result =~ /using \S+ key ID (.+)$/m;
218 my ($pemail) = $result =~ /Good signature from "(.+)"$/m;
219  
220 return ($exit_value,$keyid,$pemail);
221  
222 }
223  
224 =head2 get_decrypt_key
225  
226 determines the decryption key (and corresponding mail) of a message
227  
228 Input:
229 MIME::Entity containing email message to analyze.
230  
231 The message can either be in RFC compliant-ish multipart/signed
232 format, or just a single part ascii armored message.
233  
234 Output:
235 $key -- decryption key
236 $mail -- corresponding mail address
237  
238 =cut
239  
240 sub get_decrypt_key {
241 my ($self, $message) = @_;
242  
243 unless (ref $message && $message->isa("MIME::Entity")) {
244 die "decrypt only knows about MIME::Entitys right now";
245 }
246  
247 my $ciphertext;
248  
249 if ($message->effective_type =~ m!multipart/encrypted!) {
250 die "multipart/encrypted with more than two parts"
251 if ($message->parts != 2);
252 die "Content-Type not pgp-encrypted"
253 unless $message->parts(0)->effective_type =~
254 m!application/pgp-encrypted!;
255 $ciphertext = $message->parts(1)->stringify_body;
256 }
257 elsif ($message->bodyhandle->as_string
258 =~ m!^-----BEGIN PGP MESSAGE-----!m ) {
259 $ciphertext = $message->bodyhandle->as_string;
260 }
261 else {
262 die "Unknown Content-Type or no PGP message in body"
263 }
264  
265 my $gnupg = GnuPG::Interface->new();
266  
267 # how we create some handles to interact with GnuPG
268 # This time we'll catch the standard error for our perusing
269 # as well as passing in the passphrase manually
270 # as well as the status information given by GnuPG
271 my ( $input, $output, $stderr )
272 = ( new IO::Handle, new IO::Handle, new IO::Handle );
273  
274 my $handles = GnuPG::Handles->new( stdin => $input,
275 stdout => $output,
276 stderr => $stderr,
277 );
278  
279 # this sets up the communication
280 my $pid = $gnupg->wrap_call(
281 handles => $handles,
282 commands => [ "--decrypt" ],
283 command_args => [ "--batch", "--list-only", "--status-fd", "1" ],
284 );
285  
286 my $read = _communicate([$output], [$input], { $input => $ciphertext });
287  
288 # reading the output
289 my @result = split(/^/m, $read->{$output});
290  
291 # clean up the finished GnuPG process
292 waitpid $pid, 0;
293 my $return = $?;
294 $return = 0 if $return == -1;
295  
296 my $exit_value = $return >> 8;
297
298  
299  
300 # set last_message
301 $self->{last_message} = \@result;
302  
303 # grep ENC_TO and NO_SECKEY items
304 my (@enc_to_keys, %no_sec_keys);
305 for ( @result ) {
306 push @enc_to_keys, $1 if /ENC_TO\s+([^\s]+)/;
307 $no_sec_keys{$1} = 1 if /NO_SECKEY\s+([^\s]+)/;
308 }
309  
310 # find first key we have the secret portion of
311 my $key;
312 foreach my $k ( @enc_to_keys ) {
313 if ( not exists $no_sec_keys{$k} ) {
314 $key = $k;
315 last;
316 }
317 }
318  
319 return if not $key;
320  
321 # get mail address of this key
322 die "Invalid Key Format: $key" unless $key =~ /^[0-9A-F]+$/i;
323 my $cmd = $self->{gpg_path} . " --with-colons --list-keys $key 2>&1";
324 my $gpg_out = qx[ $cmd ];
325 ## FIXME: this should probably use open| instead.
326 die "Couldn't find key $key in keyring" if $gpg_out !~ /\S/ or $?;
327 my $mail = (split(":", $gpg_out))[9];
328  
329 return ($mail, $key);
330 }
331  
332 =head2 verify
333  
334 verify a signed message
335  
336 Input:
337 MIME::Entity containing email message to verify.
338  
339 The message can either be in RFC compliant-ish multipart/signed
340 format, or just a single part ascii armored message.
341  
342 Output:
343 On error:
344 Exit code of gpg. (0 on success)
345 On success
346 ( 0,
347 keyid, # ABCDDCBA
348 emailaddress # Foo Bar <foo@bar.com>
349 )
350  
351 where the keyid is the key that signed it, and emailaddress is full
352 name and email address of the primary uid
353  
354 $self->{last_message} => any errors from gpg
355  
356 =cut
357  
358 # Verify RFC2015/RFC3156 email
359 sub verify {
360 my ($self, $message) = @_;
361  
362 my $ciphertext = "";
363 my $sigtext = "";
364  
365 $self->{last_message} = [];
366  
367 unless (ref $message && $message->isa("MIME::Entity")) {
368 die "VerifyMessage only knows about MIME::Entitys right now";
369 return 255;
370 }
371  
372 if ($message->effective_type =~ m!multipart/signed!) {
373 die "multipart/signed with more than two parts"
374 if ($message->parts != 2);
375 die "Content-Type not pgp-signed"
376 unless $message->parts(1)->effective_type =~
377 m!application/pgp-signature!;
378 $ciphertext = $message->parts(0)->as_string;
379 $sigtext = $message->parts(1)->stringify_body;
380 }
381 elsif ( $message->bodyhandle and $message->bodyhandle->as_string
382 =~ m!^-----BEGIN PGP SIGNED MESSAGE-----!m ) {
383 # don't use not $message->body_as_string here, because
384 # the body isn't decoded in this case!!!
385 # (which is evil for quoted-printable transfer encoding)
386 # also the headers and stuff are not needed here
387 $ciphertext = undef;
388 $sigtext = $message->bodyhandle->as_string; # well, actually both
389 }
390 else {
391 die "Unknown Content-Type or no PGP message in body"
392 }
393  
394 my $gnupg = GnuPG::Interface->new();
395 $self->_set_options($gnupg);
396 # how we create some handles to interact with GnuPG
397 my $input = IO::Handle->new();
398 my $error = IO::Handle->new();
399 my $handles = GnuPG::Handles->new( stderr => $error, stdin => $input );
400  
401 my ($sigfh, $sigfile)
402 = File::Temp::tempfile('mgsXXXXXXXX',
403 DIR => File::Spec->tmpdir,
404 UNLINK => 1,
405 );
406 print $sigfh $sigtext;
407 close($sigfh);
408  
409 my ($datafh, $datafile) =
410 File::Temp::tempfile('mgdXXXXXX',
411 DIR => File::Spec->tmpdir,
412 UNLINK => 1,
413 );
414  
415 # according to RFC3156 all line endings MUST be CR/LF
416 if ( defined $ciphertext ) {
417 $ciphertext =~ s/\x0A/\x0D\x0A/g;
418 $ciphertext =~ s/\x0D+/\x0D/g;
419 }
420  
421 # Read the (unencoded) body data:
422 # as_string includes the header portion
423 print $datafh $ciphertext if $ciphertext;
424 close($datafh);
425  
426 my $pid = $gnupg->verify( handles => $handles,
427 command_args => ( $ciphertext ?
428 ["$sigfile", "$datafile"] :
429 "$sigfile" ),
430 );
431  
432 my $read = _communicate([$error], [$input], {$input => ''});
433  
434 my @result = split(/^/m, $read->{$error});
435  
436 unlink $sigfile, $datafile;
437  
438 waitpid $pid, 0;
439 my $return = $?;
440 $return = 0 if $return == -1;
441  
442 my $exit_value = $return >> 8;
443  
444 $self->{last_message} = [@result];
445  
446 return $exit_value if $exit_value; # failure
447  
448 # FIXME: these regex are likely to break under non english locales.
449 my $result = join "", @result;
450 my ($keyid) = $result =~ /using \S+ key ID (.+)$/m;
451 my ($pemail) = $result =~ /Good signature from "(.+)"$/m;
452  
453  
454 return ($exit_value,$keyid,$pemail);
455  
456 }
457  
458 # Should this go elsewhere? The Key handling stuff doesn't seem to
459 # make sense in a Mail:: module.
460 my %key_cache;
461 my $key_cache_age = 0;
462 my $key_cache_expire = 60*60*30; # 30 minutes
463  
464 sub _rebuild_key_cache {
465 my $self = shift;
466 local $_;
467 %key_cache = ();
468 # sometimes the best tool for the job... is not perl
469 open(my $fh, "$self->{gpg_path} --list-public-keys --with-colons | cut -d: -f10|")
470 or die $!;
471 while(<$fh>) {
472 next unless $_;
473 # M::A may not parse the gpg stuff properly. Cross fingers
474 my ($a) = Mail::Address->parse($_); # list context, please
475 $key_cache{$a->address}=1 if ref $a;
476 }
477 }
478  
479 =head2 has_public_key
480  
481 Does the keyring have a public key for the specified email address?
482  
483 FIXME: document better. talk about caching. maybe put a better
484 interface in.
485  
486 =cut
487  
488  
489 sub has_public_key {
490 my ($self,$address) = @_;
491  
492 # cache aging is disabled until someone has enough time to test this
493 if (0) {
494 $self->_rebuild_key_cache() unless ($key_cache_age);
495  
496 if ( $key_cache_age && ( time() - $key_cache_expire > $key_cache_age )) {
497 $self->_rebuild_key_cache();
498 }
499 }
500  
501 $self->_rebuild_key_cache();
502  
503 return 1 if exists $key_cache{$address};
504 return 0;
505  
506 }
507  
508 =head2 mime_sign
509  
510 sign an email message
511  
512 Input:
513 MIME::Entity containing email message to sign
514  
515 Output:
516 Exit code of gpg. (0 on success)
517  
518 $self->{last_message} => any errors from gpg
519  
520 The provided $entity will be signed. (i.e. it _will_ be modified.)
521  
522 =cut
523  
524  
525 sub mime_sign {
526 my ($self,$entity) = @_;
527  
528 die "Not a mime entity"
529 unless $entity->isa("MIME::Entity");
530  
531 $entity->make_multipart;
532 my $workingentity = $entity;
533 if ($entity->parts > 1) {
534 $workingentity = MIME::Entity->build(Type => $entity->head->mime_attr("Content-Type"));
535 $workingentity->add_part($_) for ($entity->parts);
536 $entity->parts([]);
537 $entity->add_part($workingentity);
538 }
539  
540 my $gnupg = GnuPG::Interface->new();
541 $self->_set_options( $gnupg );
542 my ( $input, $output, $error, $passphrase_fh, $status_fh )
543 = ( new IO::Handle, new IO::Handle,new IO::Handle,
544 new IO::Handle,new IO::Handle,);
545 my $handles = GnuPG::Handles->new( stdin => $input,
546 stdout => $output,
547 stderr => $error,
548 passphrase => $passphrase_fh,
549 status => $status_fh,
550 );
551 my $pid = $gnupg->detach_sign( handles => $handles, $self->_agent_args );
552 die "NO PASSPHRASE" unless defined $passphrase_fh;
553  
554 # this passes in the plaintext
555 my $plaintext;
556 if ($workingentity eq $entity) {
557 $plaintext = $entity->parts(0)->as_string;
558 } else {
559 $plaintext = $workingentity->as_string;
560 }
561  
562 # according to RFC3156 all line endings MUST be CR/LF
563 $plaintext =~ s/\x0A/\x0D\x0A/g;
564 $plaintext =~ s/\x0D+/\x0D/g;
565  
566 # DEBUG:
567 # print "SIGNING THIS STRING ----->\n";
568 # $plaintext =~ s/\n/-\n/gs;
569 # warn("SIGNING:\n$plaintext<<<");
570 # warn($entity->as_string);
571 # print STDERR $plaintext;
572 # print "<----\n";
573 my $read = _communicate([$output, $error, $status_fh],
574 [$input, $passphrase_fh],
575 { $input => $plaintext,
576 $passphrase_fh => $self->{passphrase}}
577 );
578  
579 my @signature = split(/^/m, $read->{$output});
580 my @error_output = split(/^/m, $read->{$error});
581 my @status_info = split(/^/m, $read->{$status_fh});
582  
583 waitpid $pid, 0;
584 my $return = $?;
585 $return = 0 if $return == -1;
586  
587 my $exit_value = $return >> 8;
588  
589  
590 $self->{last_message} = \@error_output;
591  
592 $entity->attach( Type => "application/pgp-signature",
593 Disposition => "inline",
594 Data => [@signature],
595 Encoding => "7bit");
596  
597 $entity->head->mime_attr("Content-Type","multipart/signed");
598 $entity->head->mime_attr("Content-Type.protocol","application/pgp-signature");
599 # $entity->head->mime_attr("Content-Type.micalg","pgp-md5");
600 # Richard Hirner notes that Thunderbird/Enigmail really wants a micalg
601 # of pgp-sha1 (which will be GPG version dependent.. older versions
602 # used md5. For now, until we can detect which type was used, the end
603 # user should read the source code, notice this comment, and insert
604 # the appropriate value themselves.
605  
606 return $exit_value;
607 }
608  
609 =head2 clear_sign
610  
611 clearsign the body of an email message
612  
613 Input:
614 MIME::Entity containing email message to sign.
615 This entity MUST have a body.
616  
617 Output:
618 Exit code of gpg. (0 on success)
619  
620 $self->{last_message} => any errors from gpg
621  
622 The provided $entity will be signed. (i.e. it _will_ be modified.)
623  
624 =cut
625  
626 sub clear_sign {
627 my ($self, $entity) = @_;
628
629 die "Not a mime entity"
630 unless $entity->isa("MIME::Entity");
631  
632 my $body = $entity->bodyhandle;
633
634 die "Message has no body"
635 unless defined $body;
636  
637 my $gnupg = GnuPG::Interface->new();
638 $self->_set_options( $gnupg );
639 $gnupg->passphrase ( $self->{passphrase} );
640  
641 my ( $input, $output, $error )
642 = ( new IO::Handle, new IO::Handle, new IO::Handle);
643  
644 my $handles = GnuPG::Handles->new(
645 stdin => $input,
646 stdout => $output,
647 stderr => $error,
648 );
649  
650 my $pid = $gnupg->clearsign ( handles => $handles, $self->_agent_args );
651  
652 my $plaintext = $body->as_string;
653  
654 $plaintext =~ s/\x0A/\x0D\x0A/g;
655 $plaintext =~ s/\x0D+/\x0D/g;
656  
657 my $read = _communicate([$output, $error], [$input], { $input => $plaintext });
658
659 my @ciphertext = split(/^/m, $read->{$output});
660 my @error_output = split(/^/m, $read->{$error});
661
662 waitpid $pid, 0;
663 my $return = $?;
664 $return = 0 if $return == -1;
665  
666 my $exit_value = $return >> 8;
667
668 $self->{last_message} = [@error_output];
669  
670 my $io = $body->open ("w") or die "can't open entity body";
671 $io->print (join('',@ciphertext));
672 $io->close;
673  
674 return $exit_value;
675 }
676  
677  
678 =head2 ascii_encrypt
679  
680 encrypt an email message body using ascii armor
681  
682 Input:
683 MIME::Entity containing email message to encrypt.
684 This entity MUST have a body.
685  
686 list of recipients
687  
688 Output:
689 Exit code of gpg. (0 on success)
690  
691 $self->{last_message} => any errors from gpg
692  
693 The provided $entity will be encrypted. (i.e. it _will_ be modified.)
694  
695 =head2 ascii_signencrypt
696  
697 encrypt and sign an email message body using ascii armor
698  
699 Input:
700 MIME::Entity containing email message to encrypt.
701 This entity MUST have a body.
702  
703 list of recipients
704  
705 Output:
706 Exit code of gpg. (0 on success)
707  
708 $self->{last_message} => any errors from gpg
709  
710 The provided $entity will be encrypted. (i.e. it _will_ be modified.)
711  
712 =cut
713  
714 sub ascii_encrypt {
715 my ($self, $entity, @recipients) = @_;
716 $self->_ascii_encrypt($entity, 0, @recipients);
717 }
718  
719 sub ascii_signencrypt {
720 my ($self, $entity, @recipients) = @_;
721 $self->_ascii_encrypt($entity, 1, @recipients);
722 }
723  
724 sub _ascii_encrypt {
725 my ($self, $entity, $sign, @recipients) = @_;
726
727 die "Not a mime entity"
728 unless $entity->isa("MIME::Entity");
729  
730 my $body = $entity->bodyhandle;
731
732 die "Message has no body"
733 unless defined $body;
734  
735 my $plaintext = $body->as_string;
736  
737 my $gnupg = GnuPG::Interface->new();
738 $self->_set_options( $gnupg );
739 $gnupg->passphrase ( $self->{passphrase} );
740 $gnupg->options->push_recipients( $_ ) for @recipients;
741  
742 my ( $input, $output, $error )
743 = ( new IO::Handle, new IO::Handle, new IO::Handle);
744  
745 my $handles = GnuPG::Handles->new(
746 stdin => $input,
747 stdout => $output,
748 stderr => $error,
749 );
750  
751 my $pid = do {
752 if ( $sign ) {
753 $gnupg->sign_and_encrypt ( handles => $handles, $self->_agent_args );
754 } else {
755 $gnupg->encrypt ( handles => $handles );
756 }
757 };
758  
759 my $read = _communicate([$output, $error], [$input], { $input => $plaintext });
760
761 my @ciphertext = split(/^/m, $read->{$output});
762 my @error_output = split(/^/m, $read->{$error});
763
764 waitpid $pid, 0;
765 my $return = $?;
766 $return = 0 if $return == -1;
767  
768 my $exit_value = $return >> 8;
769
770  
771 $self->{last_message} = [@error_output];
772  
773 my $io = $body->open ("w") or die "can't open entity body";
774 $io->print (join('',@ciphertext));
775 $io->close;
776  
777 return $exit_value;
778 }
779  
780 =head2 mime_encrypt
781  
782 encrypt an email message
783  
784 Input:
785 MIME::Entity containing email message to encrypt
786 list of email addresses to sign to
787  
788 Output:
789 Exit code of gpg. (0 on success)
790  
791 $self->{last_message} => any errors from gpg
792  
793 The provided $entity will be encrypted. (i.e. it _will_ be modified.)
794  
795 =head2 mime_signencrypt
796  
797 sign and encrypt an email message
798  
799 Input:
800 MIME::Entity containing email message to sign encrypt
801 list of email addresses to sign to
802  
803 Output:
804 Exit code of gpg. (0 on success)
805  
806 $self->{last_message} => any errors from gpg
807  
808 The provided $entity will be encrypted. (i.e. it _will_ be modified.)
809  
810 =cut
811  
812 sub mime_encrypt {
813 my $self = shift;
814 $self->_mime_encrypt(0,@_);
815 }
816  
817 sub mime_signencrypt {
818 my $self = shift;
819 $self->_mime_encrypt(1,@_);
820 }
821  
822 sub _mime_encrypt {
823 my ($self,$sign,$entity,@recipients) = @_;
824  
825 die "Not a mime entity"
826 unless $entity->isa("MIME::Entity");
827  
828 my $workingentity = $entity;
829 $entity->make_multipart;
830 if ($entity->parts > 1) {
831 $workingentity = MIME::Entity->build(Type => $entity->head->mime_attr("Content-Type"));
832 $workingentity->add_part($_) for ($entity->parts);
833 $entity->parts([]);
834 $entity->add_part($workingentity);
835 }
836  
837 my $gnupg = GnuPG::Interface->new();
838  
839 $gnupg->options->push_recipients( $_ ) for @recipients;
840 $self->_set_options($gnupg);
841 my ( $input, $output, $error, $passphrase_fh, $status_fh )
842 = ( new IO::Handle, new IO::Handle,new IO::Handle,
843 new IO::Handle,new IO::Handle,);
844 my $handles = GnuPG::Handles->new( stdin => $input,
845 stdout => $output,
846 stderr => $error,
847 passphrase => $passphrase_fh,
848 status => $status_fh,
849 );
850  
851 my $pid = do {
852 if ($sign) {
853 $gnupg->sign_and_encrypt( handles => $handles, $self->_agent_args );
854 } else {
855 $gnupg->encrypt( handles => $handles );
856 }
857 };
858  
859 # this passes in the plaintext
860 my $plaintext;
861 if ($workingentity eq $entity) {
862 $plaintext= $entity->parts(0)->as_string;
863 } else {
864 $plaintext=$workingentity->as_string;
865 }
866  
867 # no need to mangle line endings for encryption (RFC3156)
868 # $plaintext =~ s/\n/\x0D\x0A/sg;
869 # should we store this back into the body?
870  
871 # DEBUG:
872 #print "ENCRYPTING THIS STRING ----->\n";
873 # print $plaintext;
874 # print "<----\n";
875  
876 die "NO PASSPHRASE" unless defined $passphrase_fh;
877 my $read = _communicate([$output, $error, $status_fh],
878 [$input, $passphrase_fh],
879 { $input => $plaintext,
880 $passphrase_fh => $self->{passphrase}}
881 );
882  
883 my @plaintext = split(/^/m, $read->{$output});
884 my @ciphertext = split(/^/m, $read->{$output});
885 my @error_output = split(/^/m, $read->{$error});
886 my @status_info = split(/^/m, $read->{$status_fh});
887  
888 waitpid $pid, 0;
889 my $return = $?;
890 $return = 0 if $return == -1;
891  
892 my $exit_value = $return >> 8;
893
894  
895
896
897 $self->{last_message} = [@error_output];
898  
899  
900 $entity->parts([]); # eliminate all parts
901  
902 $entity->attach(Type => "application/pgp-encrypted",
903 Disposition => "inline",
904 Filename => "msg.asc",
905 Data => ["Version: 1",""],
906 Encoding => "7bit");
907 $entity->attach(Type => "application/octet-stream",
908 Disposition => "inline",
909 Data => [@ciphertext],
910 Encoding => "7bit");
911  
912 $entity->head->mime_attr("Content-Type","multipart/encrypted");
913 $entity->head->mime_attr("Content-Type.protocol","application/pgp-encrypted");
914  
915 $exit_value;
916 }
917  
918 =head2 is_signed
919  
920 best guess as to whether a message is signed or not (by looking at
921 the mime type and message content)
922  
923 Input:
924 MIME::Entity containing email message to test
925  
926 Output:
927 True or False value
928  
929 =head2 is_encrypted
930  
931 best guess as to whether a message is signed or not (by looking at
932 the mime type and message content)
933  
934 Input:
935 MIME::Entity containing email message to test
936  
937 Output:
938 True or False value
939  
940 =cut
941  
942 sub is_signed {
943 my ($self,$entity) = @_;
944 return 1
945 if (($entity->effective_type =~ m!multipart/signed!)
946 ||
947 ($entity->as_string =~ m!^-----BEGIN PGP SIGNED MESSAGE-----!m));
948 return 0;
949 }
950  
951 sub is_encrypted {
952 my ($self,$entity) = @_;
953 return 1
954 if (($entity->effective_type =~ m!multipart/encrypted!)
955 ||
956 ($entity->as_string =~ m!^-----BEGIN PGP MESSAGE-----!m));
957 return 0;
958 }
959  
960 # interleave reads and writes
961 # input parameters:
962 # $rhandles - array ref with a list of file handles for reading
963 # $whandles - array ref with a list of file handles for writing
964 # $wbuf_of - hash ref indexed by the stringified handles
965 # containing the data to write
966 # return value:
967 # $rbuf_of - hash ref indexed by the stringified handles
968 # containing the data that has been read
969 #
970 # read and write errors due to EPIPE (gpg exit) are skipped silently on the
971 # assumption that gpg will explain the problem on the error handle
972 #
973 # other errors cause a non-fatal warning, processing continues on the rest
974 # of the file handles
975 #
976 # NOTE: all the handles get closed inside this function
977  
978 sub _communicate {
979 my $blocksize = 2048;
980 my ($rhandles, $whandles, $wbuf_of) = @_;
981 my $rbuf_of = {};
982  
983 # the current write offsets, again indexed by the stringified handle
984 my $woffset_of;
985  
986 my $reader = IO::Select->new;
987 for (@$rhandles) {
988 $reader->add($_);
989 $rbuf_of->{$_} = '';
990 }
991  
992 my $writer = IO::Select->new;
993 for (@$whandles) {
994 die("no data supplied for handle " . fileno($_)) if !exists $wbuf_of->{$_};
995 if ($wbuf_of->{$_}) {
996 $writer->add($_);
997 } else { # nothing to write
998 close $_;
999 }
1000 }
1001  
1002 # we'll handle EPIPE explicitly below
1003 local $SIG{PIPE} = 'IGNORE';
1004  
1005 while ($reader->handles || $writer->handles) {
1006 my @ready = IO::Select->select($reader, $writer, undef, undef);
1007 if (!@ready) {
1008 die("error doing select: $!");
1009 }
1010 my ($rready, $wready, $eready) = @ready;
1011 if (@$eready) {
1012 die("select returned an unexpected exception handle, this shouldn't happen");
1013 }
1014 for my $rhandle (@$rready) {
1015 my $n = fileno($rhandle);
1016 my $count = sysread($rhandle, $rbuf_of->{$rhandle},
1017 $blocksize, length($rbuf_of->{$rhandle}));
1018 warn("read $count bytes from handle $n") if $DEBUG;
1019 if (!defined $count) { # read error
1020 if ($!{EPIPE}) {
1021 warn("read failure (gpg exited?) from handle $n: $!")
1022 if $DEBUG;
1023 } else {
1024 warn("read failure from handle $n: $!");
1025 }
1026 $reader->remove($rhandle);
1027 close $rhandle;
1028 next;
1029 }
1030 if ($count == 0) { # EOF
1031 warn("read done from handle $n") if $DEBUG;
1032 $reader->remove($rhandle);
1033 close $rhandle;
1034 next;
1035 }
1036 }
1037 for my $whandle (@$wready) {
1038 my $n = fileno($whandle);
1039 $woffset_of->{$whandle} = 0 if !exists $woffset_of->{$whandle};
1040 my $count = syswrite($whandle, $wbuf_of->{$whandle},
1041 $blocksize, $woffset_of->{$whandle});
1042 if (!defined $count) {
1043 if ($!{EPIPE}) { # write error
1044 warn("write failure (gpg exited?) from handle $n: $!")
1045 if $DEBUG;
1046 } else {
1047 warn("write failure from handle $n: $!");
1048 }
1049 $writer->remove($whandle);
1050 close $whandle;
1051 next;
1052 }
1053 warn("wrote $count bytes to handle $n") if $DEBUG;
1054 $woffset_of->{$whandle} += $count;
1055 if ($woffset_of->{$whandle} >= length($wbuf_of->{$whandle})) {
1056 warn("write done to handle $n") if $DEBUG;
1057 $writer->remove($whandle);
1058 close $whandle;
1059 next;
1060 }
1061 }
1062 }
1063 return $rbuf_of;
1064 }
1065  
1066 # FIXME: there's no reason why is_signed and is_encrypted couldn't be
1067 # static (class) methods, so maybe we should support that.
1068  
1069 # FIXME: will we properly deal with signed+encrypted stuff? probably not.
1070  
1071 # Autoload methods go after =cut, and are processed by the autosplit program.
1072  
1073 1;
1074 __END__
« Build ↑ Summary