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