home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / perl5 / GnuPG / Interface.pm < prev    next >
Encoding:
Perl POD Document  |  2011-03-08  |  38.7 KB  |  1,332 lines

  1. #  Jnterface.pm
  2. #    - providing an object-oriented approach to interacting with GnuPG
  3. #
  4. #  Copyright (C) 2000 Frank J. Tobin <ftobin@cpan.org>
  5. #
  6. #  This module is free software; you can redistribute it and/or modify it
  7. #  under the same terms as Perl itself.
  8. #
  9. #  This program is distributed in the hope that it will be useful,
  10. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. #
  13.  
  14. package GnuPG::Interface;
  15. use Any::Moose;
  16. with qw(GnuPG::HashInit);
  17.  
  18. use English qw( -no_match_vars );
  19. use Carp;
  20. use Fcntl;
  21. use vars qw( $VERSION );
  22. use Fatal qw( open close pipe fcntl );
  23. use Class::Struct;
  24. use IO::Handle;
  25.  
  26. use Math::BigInt try => 'GMP';
  27. use GnuPG::Options;
  28. use GnuPG::Handles;
  29.  
  30. $VERSION = '0.43';
  31.  
  32. has $_ => (
  33.     isa     => 'Any',
  34.     is      => 'rw',
  35.     clearer => 'clear_' . $_,
  36. ) for qw(call passphrase);
  37.  
  38. has options => (
  39.     isa        => 'GnuPG::Options',
  40.     is         => 'rw',
  41.     lazy_build => 1,
  42. );
  43.  
  44. sub _build_options { GnuPG::Options->new() }
  45.  
  46. # deprecated!
  47. sub gnupg_call { shift->call(@_); }
  48.  
  49. sub BUILD {
  50.     my ( $self, $args ) = @_;
  51.  
  52.     $self->hash_init( call => 'gpg' );
  53.     $self->hash_init(%$args);
  54. }
  55.  
  56. struct(
  57.     fh_setup => {
  58.         parent_end       => '$', child_end      => '$',
  59.         direct           => '$', is_std         => '$',
  60.         parent_is_source => '$', name_shows_dup => '$',
  61.     }
  62. );
  63.  
  64. #################################################################
  65. # real worker functions
  66.  
  67. # This function does any 'extra' stuff that the user might
  68. # not want to handle himself, such as passing in the passphrase
  69. sub wrap_call( $% ) {
  70.     my ( $self, %args ) = @_;
  71.  
  72.     my $handles = $args{handles}
  73.         or croak 'error: no handles defined';
  74.  
  75.     $handles->stdin('<&STDIN')   unless $handles->stdin();
  76.     $handles->stdout('>&STDOUT') unless $handles->stdout();
  77.     $handles->stderr('>&STDERR') unless $handles->stderr();
  78.  
  79.     # so call me sexist; English just doen't cope well
  80.     my $needs_passphrase_handled_for_him
  81.         = ( $self->passphrase() and not $handles->passphrase() ) ? 1 : 0;
  82.  
  83.     if ($needs_passphrase_handled_for_him) {
  84.         $handles->passphrase( IO::Handle->new() );
  85.     }
  86.  
  87.     my $pid = $self->fork_attach_exec(%args);
  88.  
  89.     if ($needs_passphrase_handled_for_him) {
  90.         my $passphrase_handle = $handles->passphrase();
  91.         print $passphrase_handle $self->passphrase();
  92.         close $passphrase_handle;
  93.  
  94.         # We put this in in case the user wants to re-use this object
  95.         $handles->clear_passphrase();
  96.     }
  97.  
  98.     return $pid;
  99. }
  100.  
  101. # does does command-line creation, forking, and execcing
  102. # the reasing cli creation is done here is because we should
  103. # fork before finding the fd's for stuff like --status-fd
  104. sub fork_attach_exec( $% ) {
  105.     my ( $self, %args ) = @_;
  106.  
  107.     my $handles = $args{handles} or croak 'no GnuPG::Handles passed';
  108.  
  109.     # deprecation support
  110.     $args{commands} ||= $args{gnupg_commands};
  111.  
  112.     my @commands
  113.         = ref $args{commands} ? @{ $args{commands} } : ( $args{commands} )
  114.         or croak "no gnupg commands passed";
  115.  
  116.     # deprecation support
  117.     $args{command_args} ||= $args{gnupg_command_args};
  118.  
  119.     my @command_args
  120.         = ref $args{command_args}
  121.         ? @{ $args{command_args} }
  122.         : ( $args{command_args} || () );
  123.  
  124.     my %fhs;
  125.     foreach my $fh_name (
  126.         qw( stdin stdout stderr status
  127.         logger passphrase command
  128.         )
  129.         ) {
  130.         my $fh = $handles->$fh_name() or next;
  131.         $fhs{$fh_name} = fh_setup->new();
  132.         $fhs{$fh_name}->parent_end($fh);
  133.     }
  134.  
  135.     foreach my $fh_name (qw( stdin stdout stderr )) {
  136.         $fhs{$fh_name}->is_std(1);
  137.     }
  138.  
  139.     foreach my $fh_name (qw( stdin passphrase command )) {
  140.         my $entry = $fhs{$fh_name} or next;
  141.         $entry->parent_is_source(1);
  142.     }
  143.  
  144.     # Below is code derived heavily from
  145.     # Marc Horowitz's IPC::Open3, a base Perl module
  146.     foreach my $fh_name ( keys %fhs ) {
  147.         my $entry = $fhs{$fh_name};
  148.  
  149.         my $parent_end = $entry->parent_end();
  150.         my $name_shows_dup = ( $parent_end =~ s/^[<>]&// );
  151.         $entry->parent_end($parent_end);
  152.  
  153.         $entry->name_shows_dup($name_shows_dup);
  154.  
  155.         $entry->direct( $name_shows_dup
  156.                 || $handles->options($fh_name)->{direct}
  157.                 || 0 );
  158.     }
  159.  
  160.     foreach my $fh_name ( keys %fhs ) {
  161.         $fhs{$fh_name}->child_end( IO::Handle->new() );
  162.     }
  163.  
  164.     foreach my $fh_name ( keys %fhs ) {
  165.         my $entry = $fhs{$fh_name};
  166.         next if $entry->direct();
  167.  
  168.         my $reader_end;
  169.         my $writer_end;
  170.         if ( $entry->parent_is_source() ) {
  171.             $reader_end = $entry->child_end();
  172.             $writer_end = $entry->parent_end();
  173.         }
  174.         else {
  175.             $reader_end = $entry->parent_end();
  176.             $writer_end = $entry->child_end();
  177.         }
  178.  
  179.         pipe $reader_end, $writer_end;
  180.     }
  181.  
  182.     my $pid = fork;
  183.  
  184.     die "fork failed: $ERRNO" unless defined $pid;
  185.  
  186.     if ( $pid == 0 )    # child
  187.     {
  188.  
  189.         # these are for safety later to help lessen autovifying,
  190.         # speed things up, and make the code smaller
  191.         my $stdin  = $fhs{stdin};
  192.         my $stdout = $fhs{stdout};
  193.         my $stderr = $fhs{stderr};
  194.  
  195.         # Paul Walmsley says:
  196.         # Perl 5.6's POSIX.pm has a typo in it that prevents us from
  197.         # importing STDERR_FILENO. So we resort to requiring it.
  198.         require POSIX;
  199.  
  200.         my $standard_out
  201.             = IO::Handle->new_from_fd( &POSIX::STDOUT_FILENO, 'w' );
  202.         my $standard_in
  203.             = IO::Handle->new_from_fd( &POSIX::STDIN_FILENO, 'r' );
  204.  
  205.         # Paul Walmsley says:
  206.         # this mess is due to a typo in POSIX.pm on Perl 5.6
  207.         my $stderr_fd = eval {&POSIX::STDERR_FILENO};
  208.         $stderr_fd = 2 unless defined $stderr_fd;
  209.         my $standard_err = IO::Handle->new_from_fd( $stderr_fd, 'w' );
  210.  
  211.         # If she wants to dup the kid's stderr onto her stdout I need to
  212.         # save a copy of her stdout before I put something else there.
  213.         if (    $stdout->parent_end() ne $stderr->parent_end()
  214.             and $stderr->direct()
  215.             and my_fileno( $stderr->parent_end() )
  216.             == my_fileno($standard_out) ) {
  217.             my $tmp = IO::Handle->new();
  218.             open $tmp, '>&' . my_fileno( $stderr->parent_end() );
  219.             $stderr->parent_end($tmp);
  220.         }
  221.  
  222.         if ( $stdin->direct() ) {
  223.             open $standard_in, '<&' . my_fileno( $stdin->parent_end() )
  224.                 unless my_fileno($standard_in)
  225.                     == my_fileno( $stdin->parent_end() );
  226.         }
  227.         else {
  228.             close $stdin->parent_end();
  229.             open $standard_in, '<&=' . my_fileno( $stdin->child_end() );
  230.         }
  231.  
  232.         if ( $stdout->direct() ) {
  233.             open $standard_out, '>&' . my_fileno( $stdout->parent_end() )
  234.                 unless my_fileno($standard_out)
  235.                     == my_fileno( $stdout->parent_end() );
  236.         }
  237.         else {
  238.             close $stdout->parent_end();
  239.             open $standard_out, '>&=' . my_fileno( $stdout->child_end() );
  240.         }
  241.  
  242.         if ( $stdout->parent_end() ne $stderr->parent_end() ) {
  243.  
  244.             # I have to use a fileno here because in this one case
  245.             # I'm doing a dup but the filehandle might be a reference
  246.             # (from the special case above).
  247.             if ( $stderr->direct() ) {
  248.                 open $standard_err, '>&' . my_fileno( $stderr->parent_end() )
  249.                     unless my_fileno($standard_err)
  250.                         == my_fileno( $stderr->parent_end() );
  251.             }
  252.             else {
  253.                 close $stderr->parent_end();
  254.                 open $standard_err, '>&=' . my_fileno( $stderr->child_end() );
  255.             }
  256.         }
  257.         else {
  258.             open $standard_err, '>&STDOUT'
  259.                 unless my_fileno($standard_err) == my_fileno($standard_out);
  260.         }
  261.  
  262.         foreach my $fh_name ( keys %fhs ) {
  263.             my $entry = $fhs{$fh_name};
  264.             next if $entry->is_std();
  265.  
  266.             my $parent_end = $entry->parent_end();
  267.             my $child_end  = $entry->child_end();
  268.  
  269.             if ( $entry->direct() ) {
  270.                 if ( $entry->name_shows_dup() ) {
  271.                     my $open_prefix
  272.                         = $entry->parent_is_source() ? '<&' : '>&';
  273.                     open $child_end, $open_prefix . $parent_end;
  274.                 }
  275.                 else {
  276.                     $child_end = $parent_end;
  277.                     $entry->child_end($child_end);
  278.                 }
  279.             }
  280.             else {
  281.                 close $parent_end;
  282.             }
  283.  
  284.             # we want these fh's to stay open after the exec
  285.             fcntl $child_end, F_SETFD, 0;
  286.  
  287.             # now set the options for the call to GnuPG
  288.             my $fileno = my_fileno($child_end);
  289.             my $option = $fh_name . '_fd';
  290.             $self->options->$option($fileno);
  291.         }
  292.  
  293.         my @command = (
  294.             $self->call(), $self->options->get_args(),
  295.             @commands,     @command_args
  296.         );
  297.  
  298.         exec @command or die "exec() error: $ERRNO";
  299.     }
  300.  
  301.     # parent
  302.  
  303.     # close the child end of any pipes (non-direct stuff)
  304.     foreach my $fh_name ( keys %fhs ) {
  305.         my $entry = $fhs{$fh_name};
  306.         close $entry->child_end() unless $entry->direct();
  307.     }
  308.  
  309.     foreach my $fh_name ( keys %fhs ) {
  310.         my $entry = $fhs{$fh_name};
  311.         next unless $entry->parent_is_source();
  312.  
  313.         my $parent_end = $entry->parent_end();
  314.  
  315.         # close any writing handles if they were a dup
  316.         #any real reason for this?  It bombs if we're doing
  317.         #the automagic >& stuff.
  318.         #close $parent_end if $entry->direct();
  319.  
  320.         # unbuffer pipes
  321.         select( ( select($parent_end), $OUTPUT_AUTOFLUSH = 1 )[0] )
  322.             if $parent_end;
  323.     }
  324.  
  325.     return $pid;
  326. }
  327.  
  328. sub my_fileno {
  329.     no strict 'refs';
  330.     my ($fh) = @_;
  331.     croak "fh is undefined" unless defined $fh;
  332.     return $1 if $fh =~ /^=?(\d+)$/;    # is it a fd in itself?
  333.     my $fileno = fileno $fh;
  334.     croak "error determining fileno for $fh: $ERRNO" unless defined $fileno;
  335.     return $fileno;
  336. }
  337.  
  338.  
  339. sub unescape_string {
  340.   my($str) = splice(@_);
  341.   $str =~ s/\\x(..)/chr(hex($1))/eg;
  342.   return $str;
  343. }
  344.  
  345. ###################################################################
  346.  
  347. sub get_public_keys ( $@ ) {
  348.     my ( $self, @key_ids ) = @_;
  349.  
  350.     return $self->get_keys(
  351.         commands     => ['--list-public-keys'],
  352.         command_args => [@key_ids],
  353.     );
  354. }
  355.  
  356. sub get_secret_keys ( $@ ) {
  357.     my ( $self, @key_ids ) = @_;
  358.  
  359.     return $self->get_keys(
  360.         commands     => ['--list-secret-keys'],
  361.         command_args => [@key_ids],
  362.     );
  363. }
  364.  
  365. sub get_public_keys_with_sigs ( $@ ) {
  366.     my ( $self, @key_ids ) = @_;
  367.  
  368.     return $self->get_keys(
  369.         commands     => ['--check-sigs'],
  370.         command_args => [@key_ids],
  371.     );
  372. }
  373.  
  374. sub get_keys {
  375.     my ( $self, %args ) = @_;
  376.  
  377.     my $saved_options = $self->options();
  378.     my $new_options   = $self->options->copy();
  379.     $self->options($new_options);
  380.     $self->options->push_extra_args(
  381.         '--with-colons',
  382.         '--fixed-list-mode',
  383.         '--with-fingerprint',
  384.         '--with-fingerprint',
  385.         '--with-key-data',
  386.     );
  387.  
  388.     my $stdin  = IO::Handle->new();
  389.     my $stdout = IO::Handle->new();
  390.  
  391.     my $handles = GnuPG::Handles->new(
  392.         stdin  => $stdin,
  393.         stdout => $stdout,
  394.     );
  395.  
  396.     my $pid = $self->wrap_call(
  397.         handles => $handles,
  398.         %args,
  399.     );
  400.  
  401.     my @returned_keys;
  402.     my $current_primary_key;
  403.     my $current_signed_item;
  404.     my $current_key;
  405.  
  406.     require GnuPG::PublicKey;
  407.     require GnuPG::SecretKey;
  408.     require GnuPG::SubKey;
  409.     require GnuPG::Fingerprint;
  410.     require GnuPG::UserId;
  411.     require GnuPG::UserAttribute;
  412.     require GnuPG::Signature;
  413.     require GnuPG::Revoker;
  414.  
  415.     while (<$stdout>) {
  416.         my $line = $_;
  417.         chomp $line;
  418.         my @fields = split ':', $line;
  419.         next unless @fields > 3;
  420.  
  421.         my $record_type = $fields[0];
  422.  
  423.         if ( $record_type eq 'pub' or $record_type eq 'sec' ) {
  424.             push @returned_keys, $current_primary_key
  425.                 if $current_primary_key;
  426.  
  427.             my (
  428.                 $user_id_validity, $key_length, $algo_num, $hex_key_id,
  429.                 $creation_date, $expiration_date,
  430.                 $local_id, $owner_trust, $user_id_string,
  431.                 $sigclass, #unused
  432.                 $usage_flags,
  433.             ) = @fields[ 1 .. $#fields ];
  434.  
  435.             # --fixed-list-mode uses epoch time for creation and expiration date strings.
  436.             # For backward compatibility, we convert them back using GMT;
  437.             my $expiration_date_string;
  438.             if ($expiration_date eq '') {
  439.               $expiration_date = undef;
  440.             } else {
  441.               $expiration_date_string = $self->_downrez_date($expiration_date);
  442.             }
  443.             my $creation_date_string = $self->_downrez_date($creation_date);
  444.  
  445.             $current_primary_key = $current_key
  446.                 = $record_type eq 'pub'
  447.                 ? GnuPG::PublicKey->new()
  448.                 : GnuPG::SecretKey->new();
  449.  
  450.             $current_primary_key->hash_init(
  451.                 length                 => $key_length,
  452.                 algo_num               => $algo_num,
  453.                 hex_id                 => $hex_key_id,
  454.                 local_id               => $local_id,
  455.                 owner_trust            => $owner_trust,
  456.                 creation_date          => $creation_date,
  457.                 expiration_date        => $expiration_date,
  458.                 creation_date_string   => $creation_date_string,
  459.                 expiration_date_string => $expiration_date_string,
  460.                 usage_flags            => $usage_flags,
  461.             );
  462.  
  463.             $current_signed_item = $current_primary_key;
  464.         }
  465.         elsif ( $record_type eq 'fpr' ) {
  466.             my $hex = $fields[9];
  467.             my $f = GnuPG::Fingerprint->new( as_hex_string => $hex );
  468.             $current_key->fingerprint($f);
  469.         }
  470.         elsif ( $record_type eq 'sig' or
  471.                 $record_type eq 'rev'
  472.               ) {
  473.             my (
  474.                 $validity,
  475.                 $algo_num,              $hex_key_id,
  476.                 $signature_date,
  477.                 $expiration_date,
  478.                 $user_id_string,
  479.                 $sig_type,
  480.             ) = @fields[ 1, 3 .. 6, 9, 10 ];
  481.  
  482.             my $expiration_date_string;
  483.             if ($expiration_date eq '') {
  484.               $expiration_date = undef;
  485.             } else {
  486.               $expiration_date_string = $self->_downrez_date($expiration_date);
  487.             }
  488.             my $signature_date_string = $self->_downrez_date($signature_date);
  489.  
  490.             my ($sig_class, $is_exportable);
  491.             if ($sig_type =~ /^([[:xdigit:]]{2})([xl])$/ ) {
  492.               $sig_class = hex($1);
  493.               $is_exportable = ('x' eq $2);
  494.             }
  495.  
  496.             my $signature = GnuPG::Signature->new(
  497.                 validity       => $validity,
  498.                 algo_num       => $algo_num,
  499.                 hex_id         => $hex_key_id,
  500.                 date           => $signature_date,
  501.                 date_string    => $signature_date_string,
  502.                 expiration_date => $expiration_date,
  503.                 expiration_date_string => $expiration_date_string,
  504.                 user_id_string => unescape_string($user_id_string),
  505.                 sig_class      => $sig_class,
  506.                 is_exportable  => $is_exportable,
  507.             );
  508.  
  509.             if ( $current_signed_item->isa('GnuPG::Key') ||
  510.                  $current_signed_item->isa('GnuPG::UserId') ||
  511.                  $current_signed_item->isa('GnuPG::Revoker') ||
  512.                  $current_signed_item->isa('GnuPG::UserAttribute')) {
  513.               if ($record_type eq 'sig') {
  514.                 $current_signed_item->push_signatures($signature);
  515.               } elsif ($record_type eq 'rev') {
  516.                 $current_signed_item->push_revocations($signature);
  517.               }
  518.             } else {
  519.               warn "do not know how to handle signature line: $line\n";
  520.             }
  521.         }
  522.         elsif ( $record_type eq 'uid' ) {
  523.             my ( $validity, $user_id_string ) = @fields[ 1, 9 ];
  524.  
  525.             $current_signed_item = GnuPG::UserId->new(
  526.                 validity  => $validity,
  527.                 as_string => unescape_string($user_id_string),
  528.             );
  529.  
  530.             $current_primary_key->push_user_ids($current_signed_item);
  531.         }
  532.         elsif ( $record_type eq 'uat' ) {
  533.             my ( $validity, $subpacket ) = @fields[ 1, 9 ];
  534.  
  535.             my ( $subpacket_count, $subpacket_total_size ) = split(/ /,$subpacket);
  536.  
  537.             $current_signed_item = GnuPG::UserAttribute->new(
  538.                 validity  => $validity,
  539.                 subpacket_count => $subpacket_count,
  540.                 subpacket_total_size => $subpacket_total_size,
  541.             );
  542.  
  543.             $current_primary_key->push_user_attributes($current_signed_item);
  544.         }
  545.         elsif ( $record_type eq 'sub' or $record_type eq 'ssb' ) {
  546.             my (
  547.                 $validity, $key_length, $algo_num, $hex_id,
  548.                 $creation_date, $expiration_date,
  549.                 $local_id,
  550.                 $dummy0, $dummy1, $dummy2, #unused
  551.                 $usage_flags,
  552.             ) = @fields[ 1 .. 11 ];
  553.  
  554.             my $expiration_date_string;
  555.             if ($expiration_date eq '') {
  556.               $expiration_date = undef;
  557.             } else {
  558.               $expiration_date_string = $self->_downrez_date($expiration_date);
  559.             }
  560.             my $creation_date_string = $self->_downrez_date($creation_date);
  561.  
  562.             $current_signed_item = $current_key
  563.                 = GnuPG::SubKey->new(
  564.                 validity               => $validity,
  565.                 length                 => $key_length,
  566.                 algo_num               => $algo_num,
  567.                 hex_id                 => $hex_id,
  568.                 creation_date          => $creation_date,
  569.                 expiration_date        => $expiration_date,
  570.                 creation_date_string   => $creation_date_string,
  571.                 expiration_date_string => $expiration_date_string,
  572.                 local_id               => $local_id,
  573.                 usage_flags            => $usage_flags,
  574.                 );
  575.  
  576.             $current_primary_key->push_subkeys($current_signed_item);
  577.         }
  578.         elsif ($record_type eq 'rvk') {
  579.           my ($algo_num, $fpr, $class) = @fields[ 3,9,10 ];
  580.           my $rvk = GnuPG::Revoker->new(
  581.            fingerprint => GnuPG::Fingerprint->new( as_hex_string => $fpr ),
  582.            algo_num    => ($algo_num + 0),
  583.            class       => hex($class),
  584.           );
  585.           # pushing to either primary key or subkey, to handle
  586.           # designated revokers to the subkeys too:
  587.           $current_key->push_revokers($rvk);
  588.           # revokers should be bound to the key with signatures:
  589.           $current_signed_item = $rvk;
  590.         }
  591.         elsif ($record_type eq 'pkd') {
  592.           my ($pos, $size, $data) = @fields[ 1,2,3 ];
  593.           $current_key->pubkey_data->[$pos+0] = Math::BigInt->from_hex('0x'.$data);
  594.         }
  595.         elsif ( $record_type ne 'tru' ) {
  596.             warn "unknown record type $record_type";
  597.         }
  598.     }
  599.  
  600.     waitpid $pid, 0;
  601.  
  602.     push @returned_keys, $current_primary_key
  603.         if $current_primary_key;
  604.  
  605.     $self->options($saved_options);
  606.  
  607.     return @returned_keys;
  608. }
  609.  
  610. sub _downrez_date {
  611.     my $self = shift;
  612.     my $date = shift;
  613.     if ($date =~  /^\d+$/) {
  614.         my ($year,$month,$day) = (gmtime($date))[5,4,3];
  615.         $year += 1900;
  616.         $month += 1;
  617.         return    sprintf('%04d-%02d-%02d',   $year, $month, $day);
  618.     }
  619.     return $date;
  620. }
  621.  
  622.  
  623. ################################################################
  624.  
  625. sub list_public_keys {
  626.     my ( $self, %args ) = @_;
  627.     return $self->wrap_call(
  628.         %args,
  629.         commands => ['--list-public-keys'],
  630.     );
  631. }
  632.  
  633. sub list_sigs {
  634.     my ( $self, %args ) = @_;
  635.     return $self->wrap_call(
  636.         %args,
  637.         commands => ['--list-sigs'],
  638.     );
  639. }
  640.  
  641. sub list_secret_keys {
  642.     my ( $self, %args ) = @_;
  643.     return $self->wrap_call(
  644.         %args,
  645.         commands => ['--list-secret-keys'],
  646.     );
  647. }
  648.  
  649. sub encrypt( $% ) {
  650.     my ( $self, %args ) = @_;
  651.     return $self->wrap_call(
  652.         %args,
  653.         commands => ['--encrypt']
  654.     );
  655. }
  656.  
  657. sub encrypt_symmetrically( $% ) {
  658.     my ( $self, %args ) = @_;
  659.     return $self->wrap_call(
  660.         %args,
  661.         commands => ['--symmetric']
  662.     );
  663. }
  664.  
  665. sub sign( $% ) {
  666.     my ( $self, %args ) = @_;
  667.     return $self->wrap_call(
  668.         %args,
  669.         commands => ['--sign']
  670.     );
  671. }
  672.  
  673. sub clearsign( $% ) {
  674.     my ( $self, %args ) = @_;
  675.     return $self->wrap_call(
  676.         %args,,
  677.         commands => ['--clearsign']
  678.     );
  679. }
  680.  
  681. sub detach_sign( $% ) {
  682.     my ( $self, %args ) = @_;
  683.     return $self->wrap_call(
  684.         %args,
  685.         commands => ['--detach-sign']
  686.     );
  687. }
  688.  
  689. sub sign_and_encrypt( $% ) {
  690.     my ( $self, %args ) = @_;
  691.     return $self->wrap_call(
  692.         %args,
  693.         commands => [
  694.             '--sign',
  695.             '--encrypt'
  696.         ]
  697.     );
  698. }
  699.  
  700. sub decrypt( $% ) {
  701.     my ( $self, %args ) = @_;
  702.     return $self->wrap_call(
  703.         %args,
  704.         commands => ['--decrypt']
  705.     );
  706. }
  707.  
  708. sub verify( $% ) {
  709.     my ( $self, %args ) = @_;
  710.     return $self->wrap_call(
  711.         %args,
  712.         commands => ['--verify']
  713.     );
  714. }
  715.  
  716. sub import_keys( $% ) {
  717.     my ( $self, %args ) = @_;
  718.     return $self->wrap_call(
  719.         %args,
  720.         commands => ['--import']
  721.     );
  722. }
  723.  
  724. sub export_keys( $% ) {
  725.     my ( $self, %args ) = @_;
  726.     return $self->wrap_call(
  727.         %args,
  728.         commands => ['--export']
  729.     );
  730. }
  731.  
  732. sub recv_keys( $% ) {
  733.     my ( $self, %args ) = @_;
  734.     return $self->wrap_call(
  735.         %args,
  736.         commands => ['--recv-keys']
  737.     );
  738. }
  739.  
  740. sub send_keys( $% ) {
  741.     my ( $self, %args ) = @_;
  742.     return $self->wrap_call(
  743.         %args,
  744.         commands => ['--send-keys']
  745.     );
  746. }
  747.  
  748. sub test_default_key_passphrase() {
  749.     my ($self) = @_;
  750.  
  751.     # We can't do something like let the user pass
  752.     # in a passphrase handle because we don't exist
  753.     # anymore after the user runs off with the
  754.     # attachments
  755.     croak 'No passphrase defined to test!'
  756.         unless defined $self->passphrase();
  757.  
  758.     my $stdin  = IO::Handle->new();
  759.     my $stdout = IO::Handle->new();
  760.     my $stderr = IO::Handle->new();
  761.     my $status = IO::Handle->new();
  762.  
  763.     my $handles = GnuPG::Handles->new(
  764.         stdin  => $stdin,
  765.         stdout => $stdout,
  766.         stderr => $stderr,
  767.         status => $status
  768.     );
  769.  
  770.     # save this setting since we need to be in non-interactive mode
  771.     my $saved_meta_interactive_option = $self->options->meta_interactive();
  772.     $self->options->clear_meta_interactive();
  773.  
  774.     my $pid = $self->sign( handles => $handles );
  775.  
  776.     close $stdin;
  777.  
  778.     # restore this setting to its original setting
  779.     $self->options->meta_interactive($saved_meta_interactive_option);
  780.  
  781.     # all we realy want to check is the status fh
  782.     while (<$status>) {
  783.         if (/^\[GNUPG:\]\s*GOOD_PASSPHRASE/) {
  784.             waitpid $pid, 0;
  785.             return 1;
  786.         }
  787.     }
  788.  
  789.     # If we didn't catch the regexp above, we'll assume
  790.     # that the passphrase was incorrect
  791.     waitpid $pid, 0;
  792.     return 0;
  793. }
  794.  
  795. 1;
  796.  
  797. ##############################################################
  798.  
  799. =head1 NAME
  800.  
  801. GnuPG::Interface - Perl interface to GnuPG
  802.  
  803. =head1 SYNOPSIS
  804.  
  805.   # A simple example
  806.   use IO::Handle;
  807.   use GnuPG::Interface;
  808.   
  809.   # settting up the situation
  810.   my $gnupg = GnuPG::Interface->new();
  811.   $gnupg->options->hash_init( armor   => 1,
  812.                   homedir => '/home/foobar' );
  813.  
  814.   # Note you can set the recipients even if you aren't encrypting!
  815.   $gnupg->options->push_recipients( 'ftobin@cpan.org' );
  816.   $gnupg->options->meta_interactive( 0 );
  817.  
  818.   # how we create some handles to interact with GnuPG
  819.   my $input   = IO::Handle->new();
  820.   my $output  = IO::Handle->new();
  821.   my $handles = GnuPG::Handles->new( stdin  => $input,
  822.                                      stdout => $output );
  823.  
  824.   # Now we'll go about encrypting with the options already set
  825.   my @plaintext = ( 'foobar' );
  826.   my $pid = $gnupg->encrypt( handles => $handles );
  827.   
  828.   # Now we write to the input of GnuPG
  829.   print $input @plaintext;
  830.   close $input;
  831.  
  832.   # now we read the output
  833.   my @ciphertext = <$output>;
  834.   close $output;
  835.  
  836.   waitpid $pid, 0;
  837.  
  838. =head1 DESCRIPTION
  839.  
  840. GnuPG::Interface and its associated modules are designed to
  841. provide an object-oriented method for interacting with GnuPG,
  842. being able to perform functions such as but not limited
  843. to encrypting, signing,
  844. decryption, verification, and key-listing parsing.
  845.  
  846. =head2 How Data Member Accessor Methods are Created
  847.  
  848. Each module in the GnuPG::Interface bundle relies
  849. on Any::Moose to generate the get/set methods
  850. used to set the object's data members.
  851. I<This is very important to realize.>  This means that
  852. any data member which is a list has special
  853. methods assigned to it for pushing, popping, and
  854. clearing the list.
  855.  
  856. =head2 Understanding Bidirectional Communication
  857.  
  858. It is also imperative to realize that this package
  859. uses interprocess communication methods similar to
  860. those used in L<IPC::Open3>
  861. and L<perlipc/"Bidirectional Communication with Another Process">,
  862. and that users of this package
  863. need to understand how to use this method because this package
  864. does not abstract these methods for the user greatly.
  865. This package is not designed
  866. to abstract this away entirely (partly for security purposes), but rather
  867. to simply help create 'proper', clean calls to GnuPG, and to implement
  868. key-listing parsing.
  869. Please see L<perlipc/"Bidirectional Communication with Another Process">
  870. to learn how to deal with these methods.
  871.  
  872. Using this package to do message processing generally
  873. invovlves creating a GnuPG::Interface object, creating
  874. a GnuPG::Handles object,
  875. setting some options in its B<options> data member,
  876. and then calling a method which invokes GnuPG, such as
  877. B<clearsign>.  One then interacts with with the handles
  878. appropriately, as described in
  879. L<perlipc/"Bidirectional Communication with Another Process">.
  880.  
  881. =head1 OBJECT METHODS
  882.  
  883. =head2 Initialization Methods
  884.  
  885. =over 4
  886.  
  887. =item new( I<%initialization_args> )
  888.  
  889. This methods creates a new object.  The optional arguments are
  890. initialization of data members.
  891.  
  892. =item hash_init( I<%args> ).
  893.  
  894.  
  895. =back
  896.  
  897. =head2 Object Methods which use a GnuPG::Handles Object
  898.  
  899. =over 4
  900.  
  901. =item list_public_keys( % )
  902.  
  903. =item list_sigs( % )
  904.  
  905. =item list_secret_keys( % )
  906.  
  907. =item encrypt( % )
  908.  
  909. =item encrypt_symmetrically( % )
  910.  
  911. =item sign( % )
  912.  
  913. =item clearsign( % )
  914.  
  915. =item detach_sign( % )
  916.  
  917. =item sign_and_encrypt( % )
  918.  
  919. =item decrypt( % )
  920.  
  921. =item verify( % )
  922.  
  923. =item import_keys( % )
  924.  
  925. =item export_keys( % )
  926.  
  927. =item recv_keys( % )
  928.  
  929. =item send_keys( % )
  930.  
  931. These methods each correspond directly to or are very similar
  932. to a GnuPG command described in L<gpg>.  Each of these methods
  933. takes a hash, which currently must contain a key of B<handles>
  934. which has the value of a GnuPG::Handles object.
  935. Another optional key is B<command_args> which should have the value of an
  936. array reference; these arguments will be passed to GnuPG as command arguments.
  937. These command arguments are used for such things as determining the keys to
  938. list in the B<export_keys> method.  I<Please note that GnuPG command arguments
  939. are not the same as GnuPG options>.  To understand what are options and
  940. what are command arguments please read L<gpg/"COMMANDS"> and L<gpg/"OPTIONS">.
  941.  
  942. Each of these calls returns the PID for the resulting GnuPG process.
  943. One can use this PID in a C<waitpid> call instead of a C<wait> call
  944. if more precise process reaping is needed.
  945.  
  946. These methods will attach the handles specified in the B<handles> object
  947. to the running GnuPG object, so that bidirectional communication
  948. can be established.  That is, the optionally-defined B<stdin>,
  949. B<stdout>, B<stderr>, B<status>, B<logger>, and
  950. B<passphrase> handles will be attached to
  951. GnuPG's input, output, standard error,
  952. the handle created by setting B<status-fd>, the handle created by setting B<logger-fd>, and the handle created by setting
  953. B<passphrase-fd> respectively.
  954. This tying of handles of similar to the process
  955. done in I<IPC::Open3>.
  956.  
  957. If you want the GnuPG process to read or write directly to an already-opened
  958. filehandle, you cannot do this via the normal I<IPC::Open3> mechanisms.
  959. In order to accomplish this, set the appropriate B<handles> data member
  960. to the already-opened filehandle, and then set the option B<direct> to be true
  961. for that handle, as described in L<GnuPG::Handles/options>.  For example,
  962. to have GnuPG read from the file F<input.txt> and write to F<output.txt>,
  963. the following snippet may do:
  964.  
  965.   my $infile  = IO::File->new( 'input.txt' );
  966.   my $outfile = IO::File->new( '>output.txt' );
  967.   my $handles = GnuPG::Handles->new( stdin  => $infile,
  968.                                      stdout => $outfile,
  969.                                    );
  970.   $handles->options( 'stdin'  )->{direct} = 1;
  971.   $handles->options( 'stdout' )->{direct} = 1;
  972.  
  973. If any handle in the B<handles> object is not defined, GnuPG's input, output,
  974. and standard error will be tied to the running program's standard error,
  975. standard output, or standard error.  If the B<status> or B<logger> handle
  976. is not defined, this channel of communication is never established with GnuPG,
  977. and so this information is not generated and does not come into play.
  978. If the B<passphrase> data member handle of the B<handles> object
  979. is not defined, but the the B<passphrase> data member handle of GnuPG::Interface
  980. object is, GnuPG::Interface will handle passing this information into GnuPG
  981. for the user as a convience.  Note that this will result in
  982. GnuPG::Interface storing the passphrase in memory, instead of having
  983. it simply 'pass-through' to GnuPG via a handle.
  984.  
  985. =back
  986.  
  987. =head2 Other Methods
  988.  
  989. =over 4
  990.  
  991. =item get_public_keys( @search_strings )
  992.  
  993. =item get_secret_keys( @search_strings )
  994.  
  995. =item get_public_keys_with_sigs( @search_strings )
  996.  
  997. These methods create and return objects of the type GnuPG::PublicKey
  998. or GnuPG::SecretKey respectively.  This is done by parsing the output
  999. of GnuPG with the option B<with-colons> enabled.  The objects created
  1000. do or do not have signature information stored in them, depending
  1001. if the method ends in I<_sigs>; this separation of functionality is there
  1002. because of performance hits when listing information with signatures.
  1003.  
  1004. =item test_default_key_passphrase()
  1005.  
  1006. This method will return a true or false value, depending
  1007. on whether GnuPG reports a good passphrase was entered
  1008. while signing a short message using the values of
  1009. the B<passphrase> data member, and the default
  1010. key specified in the B<options> data member.
  1011.  
  1012. =back
  1013.  
  1014.  
  1015. =head1 Invoking GnuPG with a custom call
  1016.  
  1017. GnuPG::Interface attempts to cover a lot of the commands
  1018. of GnuPG that one would want to perform; however, there may be a lot
  1019. more calls that GnuPG is and will be capable of, so a generic command
  1020. interface is provided, C<wrap_call>.
  1021.  
  1022. =over 4
  1023.  
  1024. =item wrap_call( %args )
  1025.  
  1026. Call GnuPG with a custom command.  The %args hash must contain
  1027. at least the following keys:
  1028.  
  1029. =over 4
  1030.  
  1031. =item commands
  1032.  
  1033. The value of this key in the hash must be a reference to a a list of
  1034. commands for GnuPG, such as C<[ qw( --encrypt --sign ) ]>.
  1035.  
  1036. =item handles
  1037.  
  1038. As with most other GnuPG::Interface methods, B<handles>
  1039. must be a GnuPG::Handles object.
  1040.  
  1041. =back
  1042.  
  1043. The following keys are optional.
  1044.  
  1045. =over 4
  1046.  
  1047. =item command_args
  1048.  
  1049. As with other GnuPG::Interface methods, the value in hash
  1050. for this key must be a reference to a list of arguments
  1051. to be passed to the GnuPG command, such as which
  1052. keys to list in a key-listing.
  1053.  
  1054. =back
  1055.  
  1056. =back
  1057.  
  1058.  
  1059. =head1 OBJECT DATA MEMBERS
  1060.  
  1061. =over 4
  1062.  
  1063. =item call
  1064.  
  1065. This defines the call made to invoke GnuPG.  Defaults to 'gpg'; this
  1066. should be changed if 'gpg' is not in your path, or there is a different
  1067. name for the binary on your system.
  1068.  
  1069. =item passphrase
  1070.  
  1071. In order to lessen the burden of using handles by the user of this package,
  1072. setting this option to one's passphrase for a secret key will allow
  1073. the package to enter the passphrase via a handle to GnuPG by itself
  1074. instead of leaving this to the user.  See also L<GnuPG::Handles/passphrase>.
  1075.  
  1076. =item options
  1077.  
  1078. This data member, of the type GnuPG::Options; the setting stored in this
  1079. data member are used to determine the options used when calling GnuPG
  1080. via I<any> of the object methods described in this package.
  1081. See L<GnuPG::Options> for more information.
  1082.  
  1083. =back
  1084.  
  1085. =head1 EXAMPLES
  1086.  
  1087. The following setup can be done before any of the following examples:
  1088.  
  1089.   use IO::Handle;
  1090.   use GnuPG::Interface;
  1091.  
  1092.   my @original_plaintext = ( "How do you doo?" );
  1093.   my $passphrase = "Three Little Pigs";
  1094.  
  1095.   my $gnupg = GnuPG::Interface->new();
  1096.  
  1097.   $gnupg->options->hash_init( armor    => 1,
  1098.                               recipients => [ 'ftobin@uiuc.edu',
  1099.                                               '0xABCD1234' ],
  1100.                               meta_interactive( 0 ),
  1101.                             );
  1102.  
  1103. =head2 Encrypting
  1104.  
  1105.   # We'll let the standard error of GnuPG pass through
  1106.   # to our own standard error, by not creating
  1107.   # a stderr-part of the $handles object.
  1108.   my ( $input, $output ) = ( IO::Handle->new(),
  1109.                              IO::Handle->new() );
  1110.  
  1111.   my $handles = GnuPG::Handles->new( stdin    => $input,
  1112.                                      stdout   => $output );
  1113.    
  1114.   # this sets up the communication
  1115.   # Note that the recipients were specified earlier
  1116.   # in the 'options' data member of the $gnupg object.
  1117.   my $pid = $gnupg->encrypt( handles => $handles );
  1118.  
  1119.   # this passes in the plaintext
  1120.   print $input @original_plaintext;
  1121.  
  1122.   # this closes the communication channel,
  1123.   # indicating we are done
  1124.   close $input;
  1125.  
  1126.   my @ciphertext = <$output>;  # reading the output
  1127.  
  1128.   waitpid $pid, 0;  # clean up the finished GnuPG process
  1129.  
  1130. =head2 Signing
  1131.  
  1132.   # This time we'll catch the standard error for our perusing
  1133.   my ( $input, $output, $error ) = ( IO::Handle->new(),
  1134.                                      IO::Handle->new(),
  1135.                                      IO::Handle->new(),
  1136.                    );
  1137.  
  1138.   my $handles = GnuPG::Handles->new( stdin    => $input,
  1139.                                      stdout   => $output,
  1140.                                      stderr   => $error,
  1141.                    );
  1142.  
  1143.   # indicate our pasphrase through the
  1144.   # convience method
  1145.   $gnupg->passphrase( $passphrase );
  1146.  
  1147.   # this sets up the communication
  1148.   my $pid = $gnupg->sign( handles => $handles );
  1149.  
  1150.   # this passes in the plaintext
  1151.   print $input @original_plaintext;
  1152.  
  1153.   # this closes the communication channel,
  1154.   # indicating we are done
  1155.   close $input;
  1156.  
  1157.   my @ciphertext   = <$output>;  # reading the output
  1158.   my @error_output = <$error>;   # reading the error
  1159.  
  1160.   close $output;
  1161.   close $error;
  1162.  
  1163.   waitpid $pid, 0;  # clean up the finished GnuPG process
  1164.  
  1165. =head2 Decryption
  1166.  
  1167.   # This time we'll catch the standard error for our perusing
  1168.   # as well as passing in the passphrase manually
  1169.   # as well as the status information given by GnuPG
  1170.   my ( $input, $output, $error, $passphrase_fh, $status_fh )
  1171.     = ( IO::Handle->new(),
  1172.         IO::Handle->new(),
  1173.         IO::Handle->new(),
  1174.         IO::Handle->new(),
  1175.         IO::Handle->new(),
  1176.       );
  1177.  
  1178.   my $handles = GnuPG::Handles->new( stdin      => $input,
  1179.                      stdout     => $output,
  1180.                      stderr     => $error,
  1181.                      passphrase => $passphrase_fh,
  1182.                      status     => $status_fh,
  1183.                    );
  1184.  
  1185.   # this time we'll also demonstrate decrypting
  1186.   # a file written to disk
  1187.   # Make sure you "use IO::File" if you use this module!
  1188.   my $cipher_file = IO::File->new( 'encrypted.gpg' );
  1189.    
  1190.   # this sets up the communication
  1191.   my $pid = $gnupg->decrypt( handles => $handles );
  1192.  
  1193.   # This passes in the passphrase
  1194.   print $passphrase_fh $passphrase;
  1195.   close $passphrase_fh;
  1196.  
  1197.   # this passes in the plaintext
  1198.   print $input $_ while <$cipher_file>;
  1199.  
  1200.   # this closes the communication channel,
  1201.   # indicating we are done
  1202.   close $input;
  1203.   close $cipher_file;
  1204.  
  1205.   my @plaintext    = <$output>;   # reading the output
  1206.   my @error_output = <$error>;    # reading the error
  1207.   my @status_info  = <$status_fh> # read the status info
  1208.  
  1209.   # clean up...
  1210.   close $output;
  1211.   close $error;
  1212.   close $status_fh;
  1213.  
  1214.   waitpid $pid, 0;  # clean up the finished GnuPG process
  1215.  
  1216. =head2 Printing Keys
  1217.  
  1218.   # This time we'll just let GnuPG print to our own output
  1219.   # and read from our input, because no input is needed!
  1220.   my $handles = GnuPG::Handles->new();
  1221.   
  1222.   my @ids = ( 'ftobin', '0xABCD1234' );
  1223.  
  1224.   # this time we need to specify something for
  1225.   # command_args because --list-public-keys takes
  1226.   # search ids as arguments
  1227.   my $pid = $gnupg->list_public_keys( handles      => $handles,
  1228.                                       command_args => [ @ids ] );
  1229.   
  1230.    waitpid $pid, 0;
  1231.  
  1232. =head2 Creating GnuPG::PublicKey Objects
  1233.  
  1234.   my @ids = [ 'ftobin', '0xABCD1234' ];
  1235.  
  1236.   my @keys = $gnupg->get_public_keys( @ids );
  1237.  
  1238.   # no wait is required this time; it's handled internally
  1239.   # since the entire call is encapsulated
  1240.  
  1241. =head2 Custom GnuPG call
  1242.  
  1243.   # assuming $handles is a GnuPG::Handles object
  1244.   my $pid = $gnupg->wrap_call
  1245.     ( commands     => [ qw( --list-packets ) ],
  1246.       command_args => [ qw( test/key.1.asc ) ],
  1247.       handles      => $handles,
  1248.     );
  1249.     
  1250.     my @out = <$handles->stdout()>;
  1251.     waitpid $pid, 0;
  1252.  
  1253.  
  1254. =head1 FAQ
  1255.  
  1256. =over 4
  1257.  
  1258. =item How do I get GnuPG::Interface to read/write directly from
  1259. a filehandle?
  1260.  
  1261. You need to set GnuPG::Handles B<direct> option to be true for the
  1262. filehandles in concern.  See L<GnuPG::Handles/options> and
  1263. L<"Object Methods which use a GnuPG::Handles Object"> for more
  1264. information.
  1265.  
  1266. =item Why do you make it so difficult to get GnuPG to write/read
  1267. from a filehandle?  In the shell, I can just call GnuPG
  1268. with the --outfile option!
  1269.  
  1270. There are lots of issues when trying to tell GnuPG to read/write
  1271. directly from a file, such as if the file isn't there, or
  1272. there is a file, and you want to write over it!  What do you
  1273. want to happen then?  Having the user of this module handle
  1274. these questions beforehand by opening up filehandles to GnuPG
  1275. lets the user know fully what is going to happen in these circumstances,
  1276. and makes the module less error-prone.
  1277.  
  1278. =item When having GnuPG process a large message, sometimes it just
  1279. hanges there.
  1280.  
  1281. Your problem may be due to buffering issues; when GnuPG reads/writes
  1282. to B<non-direct> filehandles (those that are sent to filehandles
  1283. which you read to from into memory, not that those access the disk),
  1284. buffering issues can mess things up.  I recommend looking into
  1285. L<GnuPG::Handles/options>.
  1286.  
  1287. =back
  1288.  
  1289. =head1 NOTES
  1290.  
  1291. This package is the successor to PGP::GPG::MessageProcessor,
  1292. which I found to be too inextensible to carry on further.
  1293. A total redesign was needed, and this is the resulting
  1294. work.
  1295.  
  1296. After any call to a GnuPG-command method of GnuPG::Interface
  1297. in which one passes in the handles,
  1298. one should all B<wait> to clean up GnuPG from the process table.
  1299.  
  1300.  
  1301. =head1 BUGS
  1302.  
  1303. Currently there are problems when transmitting large quantities
  1304. of information over handles; I'm guessing this is due
  1305. to buffering issues.  This bug does not seem specific to this package;
  1306. IPC::Open3 also appears affected.
  1307.  
  1308. I don't know yet how well this modules handles parsing OpenPGP v3 keys.
  1309.  
  1310. =head1 SEE ALSO
  1311.  
  1312. L<GnuPG::Options>,
  1313. L<GnuPG::Handles>,
  1314. L<GnuPG::PublicKey>,
  1315. L<GnuPG::SecretKey>,
  1316. L<gpg>,
  1317. L<perlipc/"Bidirectional Communication with Another Process">
  1318.  
  1319. =head1 AUTHOR
  1320.  
  1321. GnuPg::Interface is currently maintained by Jesse Vincent <jesse@cpan.org>.  
  1322.  
  1323. Frank J. Tobin, ftobin@cpan.org was the original author of the package.
  1324.  
  1325. =cut
  1326.  
  1327.  
  1328. __PACKAGE__->meta->make_immutable;
  1329.  
  1330. 1;
  1331.  
  1332.