File Coverage

blib/lib/GnuPG.pm
Criterion Covered Total %
statement 373 417 89.4
branch 157 272 57.7
condition 36 70 51.4
subroutine 41 42 97.6
pod 10 25 40.0
total 617 826 74.7


line stmt bran cond sub pod time code
1             #
2             # GnuPG.pm - Interface to the GNU Privacy Guard.
3             #
4             # This file is part of GnuPG.pm.
5             #
6             # Author: Francis J. Lacoste <francis.lacoste@Contre.COM>
7             #
8             # Copyright (C) 2000 iNsu Innovations Inc.
9             # Copyright (C) 2001 Francis J. Lacoste
10             #
11             # This program is free software; you can redistribute it and/or modify
12             # it under the terms of the GNU General Public License as published by
13             # the Free Software Foundation; either version 2 of the License, or
14             # (at your option) any later version.
15             #
16             # This program is distributed in the hope that it will be useful,
17             # but WITHOUT ANY WARRANTY; without even the implied warranty of
18             # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19             # GNU General Public License for more details.
20             #
21             # You should have received a copy of the GNU General Public License
22             # along with this program; if not, write to the Free Software
23             # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24             #
25             package GnuPG;
26              
27              
28 28     28   1453088 use strict;
  28         84  
  28         1092  
29              
30 28     28   224 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS );
  28         84  
  28         3304  
31              
32             BEGIN {
33 28     28   168 require Exporter;
34              
35 28         280 @ISA = qw(Exporter);
36              
37 28         84 @EXPORT = qw();
38              
39 28         112 %EXPORT_TAGS = (
40             algo => [ qw( RSA_RSA DSA_ELGAMAL DSA RSA ) ],
41             trust => [ qw( TRUST_UNDEFINED TRUST_NEVER
42             TRUST_MARGINAL TRUST_FULLY
43             TRUST_ULTIMATE ) ],
44             );
45              
46 28         1036 Exporter::export_ok_tags( qw( algo trust ) );
47              
48 28         616 $VERSION = '0.19';
49             }
50              
51 28     28   140 use constant RSA_RSA => 1;
  28         28  
  28         1232  
52 28     28   140 use constant DSA_ELGAMAL => 2;
  28         56  
  28         1092  
53 28     28   112 use constant DSA => 3;
  28         28  
  28         924  
54 28     28   112 use constant RSA => 4;
  28         56  
  28         1680  
55              
56 28     28   168 use constant TRUST_UNDEFINED => -1;
  28         28  
  28         1064  
57 28     28   112 use constant TRUST_NEVER => 0;
  28         84  
  28         952  
58 28     28   112 use constant TRUST_MARGINAL => 1;
  28         28  
  28         952  
59 28     28   112 use constant TRUST_FULLY => 2;
  28         56  
  28         924  
60 28     28   140 use constant TRUST_ULTIMATE => 3;
  28         28  
  28         896  
61              
62 28     28   224 use Carp;
  28         56  
  28         1484  
63 28     28   11396 use POSIX qw();
  28         131768  
  28         588  
64 28     28   168 use Symbol;
  28         56  
  28         1232  
65 28     28   112 use Fcntl;
  28         56  
  28         104804  
66              
67             sub parse_trust {
68 34     34 0 170 for (shift) {
69 34 50       251 /ULTIMATE/ && do { return TRUST_ULTIMATE; };
  34         136  
70 0 0       0 /FULLY/ && do { return TRUST_FULLY; };
  0         0  
71 0 0       0 /MARGINAL/ && do { return TRUST_MARGINAL; };
  0         0  
72 0 0       0 /NEVER/ && do { return TRUST_NEVER; };
  0         0  
73             # Default
74 0         0 return TRUST_UNDEFINED;
75             }
76             }
77              
78             sub options($;$) {
79 432     432 1 1094 my $self = shift;
80 432 100       1805 $self->{cmd_options} = shift if ( $_[0] );
81 432         1769 $self->{cmd_options};
82             }
83              
84             sub command($;$) {
85 432     432 0 1182 my $self = shift;
86 432 100       2289 $self->{command} = shift if ( $_[0] );
87 432         1518 $self->{command};
88             }
89              
90             sub args($;$) {
91 432     432 0 1038 my $self = shift;
92 432 100       2212 $self->{args} = shift if ( $_[0] );
93 432         1013 $self->{args};
94             }
95              
96             sub cmdline($) {
97 27     27 0 233 my $self = shift;
98 27         907 my $args = [ $self->{gnupg_path} ];
99              
100             # Default options
101 27 50       771 push @$args, "--no-tty" unless $self->{trace};
102             push @$args, "--no-greeting", "--yes", "--status-fd", fileno $self->{status_fd},
103 27         669 "--command-fd", fileno $self->{command_fd};
104            
105             # Check for homedir and options file
106 27 50       560 push @$args, "--homedir", $self->{homedir} if $self->{homedir};
107 27 50       454 push @$args, "--options", $self->{options} if $self->{options};
108              
109             # Command options
110 27         234 push @$args, @{ $self->options };
  27         512  
111              
112              
113             # Command and arguments
114 27         482 push @$args, "--" . $self->command;
115 27         72 push @$args, @{ $self->args };
  27         421  
116              
117 27         161 return $args;
118             }
119              
120             sub end_gnupg($) {
121 378     378 0 1312 my $self = shift;
122              
123             print STDERR "GnuPG: closing status fd " . fileno ($self->{status_fd})
124             . "\n"
125 378 50       2837 if $self->{trace};
126              
127             close $self->{status_fd}
128 378 50       5342 or croak "error while closing pipe: $!\n";
129              
130             print STDERR "GnuPG: closing command fd " . fileno ($self->{command_fd})
131             . "\n"
132 378 50       1428 if $self->{trace};
133              
134             close $self->{command_fd}
135 378 50       2671 or croak "error while closing pipe: $!\n";
136              
137 378 50       102404634029 waitpid $self->{gnupg_pid}, 0
138             or croak "error while waiting for gpg: $!\n";
139              
140              
141 378         3563 for ( qw(protocol gnupg_pid command options args status_fd command_fd
142             input output next_status ) )
143             {
144 3780         20436 delete $self->{$_};
145             }
146              
147             }
148              
149             sub abort_gnupg($$) {
150 0     0 0 0 my ($self,$msg) = @_;
151              
152             # Signal our child that it is the end
153 0 0 0     0 if ($self->{gnupg_pid} && kill 0 => $self->{gnupg_pid} ) {
154 0         0 kill INT => $self->{gnupg_pid};
155             }
156              
157 0         0 $self->end_gnupg;
158              
159 0         0 confess ( $msg );
160             }
161              
162             # Used to push back status information
163             sub next_status($$$) {
164 80     80 0 401 my ($self,$cmd,$arg) = @_;
165              
166 80         793 $self->{next_status} = [$cmd,$arg];
167             }
168              
169             sub read_from_status($) {
170 1745     1745 0 3863 my $self = shift;
171             # Check if a status was pushed back
172 1745 50       5798 if ( $self->{next_status} ) {
173 0         0 my $status = $self->{next_status};
174 0         0 $self->{next_status} = undef;
175 0         0 return @$status;
176             }
177              
178 1745 50       5040 print STDERR "GnuPG: reading from status fd " . fileno ($self->{status_fd}) . "\n" if $self->{trace};
179              
180 1745         3304 my $fd = $self->{status_fd};
181 1745         14458 local $/ = "\n"; # Just to be sure
182 1745         992237646 my $line = <$fd>;
183 1745 50       8990 unless ($line) {
184 0 0       0 print STDERR "GnuPG: got from status fd: EOF" if $self->{trace};
185 0         0 return ();
186             }
187              
188 1745 50       6707 print STDERR "GnuPG: got from status fd: $line" if $self->{trace};
189              
190 1745         20486 my ( $cmd,$arg ) = $line =~ /\[GNUPG:\] (\w+) ?(.+)?$/;
191 1745 50       6264 $self->abort_gnupg( "error communicating with gnupg: bad status line: $line\n" ) unless $cmd;
192 1745 50       5158 print STDERR "GnuPG: Parsed as " . $cmd . " - " . $arg . "\n" if $self->{trace};
193 1745 100       12588 return wantarray ? ( $cmd, $arg ) : $cmd;
194             }
195              
196             sub run_gnupg($) {
197 405     405 0 997 my $self = shift;
198              
199 405         2757 my $fd = gensym;
200 405         10428 my $wfd = gensym;
201              
202 405         5660 my $crfd = gensym; # command read and write file descriptors
203 405         5315 my $cwfd = gensym;
204              
205 405 50       13538 pipe $fd, $wfd
206             or croak ( "error creating status pipe: $!\n" );
207 405         2650 my $old = select $wfd; $| = 1; # Unbuffer
  405         2165  
208 405         1770 select $old;
209              
210 405 50       4510 pipe $crfd, $cwfd
211             or croak ( "error creating command pipe: $!\n" );
212 405         1531 $old = select $cwfd; $| = 1; # Unbuffer
  405         1161  
213 405         1912 select $old;
214              
215             # Keep pipe open after close
216 405 50       2360 fcntl( $fd, F_SETFD, 0 )
217             or croak "error removing close on exec flag: $!\n" ;
218 405 50       1569 fcntl( $wfd, F_SETFD, 0 )
219             or croak "error removing close on exec flag: $!\n" ;
220 405 50       1625 fcntl( $crfd, F_SETFD, 0 )
221             or croak "error removing close on exec flag: $!\n" ;
222 405 50       1592 fcntl( $cwfd, F_SETFD, 0 )
223             or croak "error removing close on exec flag: $!\n" ;
224              
225 405         277322 my $pid = fork;
226 405 50       9858 croak( "error forking: $!" ) unless defined $pid;
227 405 100       6507 if ( $pid ) {
228             # Parent
229 378         10918 close $wfd;
230              
231 378         7987 $self->{status_fd} = $fd;
232 378         3856 $self->{gnupg_pid} = $pid;
233 378         22119 $self->{command_fd} = $cwfd;
234              
235             } else {
236             # Child
237 27         1137 $self->{status_fd} = $wfd;
238 27         349 $self->{command_fd} = $crfd;
239              
240 27         969 my $cmdline = $self->cmdline;
241 27 50       186 unless ( $self->{trace} ) {
242 27 50       2293 open (STDERR, "> /dev/null" )
243             or die "can't redirect stderr to /dev/null: $!\n";
244             }
245              
246             # This is where we grab the data
247 27 100 66     893 if ( ref $self->{input} && defined fileno $self->{input} ) {
    50 66        
    100          
248             open ( STDIN, "<&" . fileno $self->{input} )
249 5 50       109 or die "error setting up data input: $!\n";
250             } elsif ( $self->{input} && -t STDIN) {
251             open ( STDIN, $self->{input} )
252 0 0       0 or die "error setting up data input: $!\n";
253             } elsif ( $self->{input} ) {
254 16         40 push(@{$cmdline}, $self->{input});
  16         122  
255             }# Defaults to stdin
256              
257             # This is where the output goes
258 27 100 66     768 if ( ref $self->{output} && defined fileno $self->{output} ) {
    50 66        
    100          
259             open ( STDOUT, ">&" . fileno $self->{output} )
260 5 50       71 or die "can't redirect stdout to proper output fd: $!\n";
261             } elsif ( $self->{output} && -t STDOUT ) {
262             open ( STDOUT, ">".$self->{output} )
263 0 0       0 or die "can't open $self->{output} for output: $!\n";
264             } elsif ( $self->{output} ) {
265 15         42 my $gpg = shift(@{$cmdline});
  15         40  
266 15         27 unshift(@{$cmdline}, '--output', $self->{output});
  15         126  
267 15         51 unshift(@{$cmdline}, $gpg);
  15         46  
268             } # Defaults to stdout
269              
270             # Close all open file descriptors except STDIN, STDOUT, STDERR
271             # and the status filedescriptor.
272             #
273             # This is needed for the tie interface which opens pipes which
274             # some ends must be closed in the child.
275             #
276             # Besides this is just plain good hygiene
277 27   50     588 my $max_fd = POSIX::sysconf( &POSIX::_SC_OPEN_MAX ) || 256;
278 27         539 foreach my $f ( 3 .. $max_fd ) {
279 14155722 100       25695317 next if $f == fileno $self->{status_fd};
280 14155695 100       25323778 next if $f == fileno $self->{command_fd};
281 14155668         23340442 POSIX::close( $f );
282             }
283              
284             print STDERR 'GnuPG: executing `'
285 27 50       464 . join( ' ', @{$cmdline} ) . '`' if $self->{trace};
  0         0  
286              
287 27 0       0 exec ( @$cmdline )
288             or CORE::die "can't exec gnupg: $!\n";
289             }
290             }
291              
292             sub cpr_maybe_send($$$) {
293 96     96 0 707 ($_[0])->cpr_send( @_[1, $#_], 1);
294             }
295              
296              
297             sub cpr_send($$$;$) {
298 426     426 0 2877 my ($self,$key,$value, $optional) = @_;
299 426         1079 my $fd = $self->{command_fd};
300              
301 426         2068 my ( $cmd, $arg ) = $self->read_from_status;
302 426 100 66     4536 unless ( defined $cmd && $cmd =~ /^GET_/) {
303 80 50       514 $self->abort_gnupg( "protocol error: expected GET_XXX got $cmd\n" )
304             unless $optional;
305 80         1117 $self->next_status( $cmd, $arg );
306 80         432 return;
307             }
308              
309 346 50       1239 unless ( $arg eq $key ) {
310 0 0       0 $self->abort_gnupg ( "protocol error: expected key $key got $arg\n" )
311             unless $optional;
312 0         0 return;
313             }
314              
315 346 50       1221 print STDERR "GnuPG: writing to command fd " . fileno ($fd) . ": $value\n" if $self->{trace};
316              
317 346         7758 print $fd $value . "\n";
318              
319 346         1300 ( $cmd, $arg ) = $self->read_from_status;
320 346 50 33     3181 unless ( defined $cmd && $cmd =~ /^GOT_IT/) {
321 0         0 $self->next_status( $cmd, $arg );
322             }
323             }
324              
325              
326             sub send_passphrase($$) {
327 168     168 0 1137 my ($self,$passwd) = @_;
328              
329             # GnuPG should now tell us that it needs a passphrase
330 168         921 my $cmd = $self->read_from_status;
331             # Skip UserID hint
332 168 100       1917 $cmd = $self->read_from_status if ( $cmd =~ /USERID_HINT/ );
333 168 50       815 if ($cmd =~ /GOOD_PASSPHRASE/) { # This means we didnt need a passphrase
334 0         0 $self->next_status($cmd); # We push this back on for read_from_status
335 0         0 return;
336             }
337 168 50       1133 $self->abort_gnupg( "Protocol error: expected NEED_PASSPHRASE.* got $cmd\n")
338             unless $cmd =~ /NEED_PASSPHRASE/;
339 168         979 $self->cpr_send( "passphrase.enter", $passwd );
340 168 50       787 unless ( $passwd ) {
341 0         0 my $cmd = $self->read_from_status;
342 0 0       0 $self->abort_gnupg( "Protocol error: expected MISSING_PASSPHRASE got $cmd\n" )
343             unless $cmd eq "MISSING_PASSPHRASE";
344             }
345             }
346              
347             sub new($%) {
348 46     46 1 35561 my $proto = shift;
349 46   33     433 my $class = ref $proto || $proto;
350              
351 46         340 my %args = @_;
352              
353 46         126 my $self = {};
354 46 50       234 if ($args{homedir}) {
355             croak ( "Invalid home directory: $args{homedir}\n")
356 46 50 33     1024 unless -d $args{homedir} && -x _;
357 46         235 $self->{homedir} = $args{homedir};
358             }
359 46 50       230 if ($args{options}) {
360             croak ( "Invalid options file: $args{options}\n")
361 0 0       0 unless -r $args{options};
362 0         0 $self->{options} = $args{options};
363             }
364 46 50       197 if ( $args{gnupg_path} ) {
365             croak ( "Invalid gpg path: $args{gnupg_path}\n")
366 0 0       0 unless -x $args{gnupg_path};
367 0         0 $self->{gnupg_path} = $args{gnupg_path};
368             } else {
369 46         383 my ($path) = grep { -x "$_/gpg" } split /:/, $ENV{PATH};
  414         7514  
370 46 50       306 croak ( "Couldn't find gpg in PATH ($ENV{PATH})\n" )
371             unless $path;
372 46         271 $self->{gnupg_path} = "$path/gpg";
373             }
374 46 50       297 $self->{trace} = $args{trace} ? 1 : 0;
375              
376 46         424 bless $self, $class;
377             }
378              
379             sub DESTROY {
380 14     14   400 my $self = shift;
381             # Signal our child that it is the end
382 14 50 33     196 if ($self->{gnupg_pid} && kill 0 => $self->{gnupg_pid} ) {
383 0         0 kill INT => $self->{gnupg_pid};
384             }
385             }
386              
387             sub gen_key($%) {
388 28     28 1 15820 my ($self,%args) = @_;
389 28         140 my $cmd;
390             my $arg;
391              
392 28         112 my $algo = $args{algo};
393 28   50     252 $algo ||= RSA_RSA;
394              
395 28         84 my $size = $args{size};
396 28   50     280 $size ||= 1024;
397 28 50       140 croak ( "Keysize is too small: $size" ) if $size < 768;
398 28 50       140 croak ( "Keysize is too big: $size" ) if $size > 2048;
399              
400 28         112 my $expire = $args{valid};
401 28   50     224 $expire ||= 0;
402              
403 28   50     168 my $passphrase = $args{passphrase} || "";
404 28         84 my $name = $args{name};
405              
406 28 50       168 croak "Missing key name\n" unless $name;
407 28 50       280 croak "Invalid name: $name\n"
408             unless $name =~ /^\s*[^0-9\<\(\[\]\)\>][^\<\(\[\]\)\>]+$/;
409              
410 28         112 my $email = $args{email};
411 28 50       140 if ( $email ) {
412 0 0 0     0 croak "Invalid email address: $email"
413             unless $email =~ /^\s* # Whitespace are okay
414             [a-zA-Z0-9_-] # Doesn't start with a dot
415             [a-zA-Z0-9_.-]*
416             \@ # Contains at most one at
417             [a-zA-Z0-9_.-]+
418             [a-zA-Z0-9_-] # Doesn't end in a dot
419             /x
420             && $email !~ /\.\./;
421             } else {
422 28         84 $email = "";
423             }
424              
425 28         84 my $comment = $args{comment};
426 28 50       112 if ( $comment ) {
427 0 0       0 croak "Invalid characters in comment" if $comment =~ /[()]/;
428             } else {
429 28         420 $comment = "";
430             }
431              
432 28         252 $self->command( "gen-key" );
433 28         196 $self->options( [] );
434 28         140 $self->args( [] );
435              
436 28         224 $self->run_gnupg;
437              
438 27         945 $self->cpr_send("keygen.algo", $algo );
439             # if ( $algo == ELGAMAL ) {
440             # # Shitty interactive program, yes I'm sure.
441             # # I'm a program, I can't change my mind now.
442             # $self->cpr_send( "keygen.algo.elg_se", 1 )
443             # }
444              
445 27         243 $self->cpr_send( "keygen.size", $size );
446 27         135 $self->cpr_send( "keygen.valid", $expire );
447 27         108 $self->cpr_send( "keygen.name", $name );
448 27         135 $self->cpr_send( "keygen.email", $email );
449 27         108 $self->cpr_send( "keygen.comment", $comment );
450              
451 27         189 $self->send_passphrase( $passphrase );
452              
453 27         270 $self->end_gnupg;
454              
455             # Woof. We should now have a generated key !
456             }
457              
458             sub import_keys($%) {
459 78     78 1 66165 my ($self,%args) = @_;
460              
461              
462 78         882 $self->command( "import" );
463 78         621 $self->options( [] );
464              
465 78         260 my $count;
466 78 100       494 if ( ref $args{keys} ) {
467 25         825 $self->args( $args{keys} );
468             } else {
469             # Only one file to import
470 53         238 $self->{input} = $args{keys};
471 53         291 $self->args( [] );
472             }
473              
474 78         520 $self->run_gnupg;
475             FILE:
476 75 100       2171 my $num_files = ref $args{keys} ? @{$args{keys}} : 1;
  24         504  
477 75         733 my ($cmd,$arg);
478              
479             # We will see one IMPORTED for each key that is imported
480             KEY:
481 75         251 while ( 1 ) {
482 101         1602 ($cmd,$arg) = $self->read_from_status;
483 101 100       1111 last KEY unless $cmd =~ /IMPORTED/;
484 26         156 $count++
485             }
486              
487             # We will see one IMPORT_RES for all files processed
488 75 50       553 $self->abort_gnupg ( "protocol error expected IMPORT_OK got $cmd\n" )
489             unless $cmd =~ /IMPORT_OK/;
490 75         756 $self->end_gnupg;
491              
492             # We return the number of imported keys
493 75         1783 return $count;
494             }
495              
496             sub export_keys($%) {
497 69     69 1 45009 my ($self,%args) = @_;
498              
499 69         231 my $options = [];
500 69 50       556 push @$options, "--armor" if $args{armor};
501              
502 69         185 $self->{output} = $args{output};
503              
504 69         208 my $keys = [];
505 69 100       300 if ( $args{keys}) {
506             push @$keys,
507 24 50       168 ref $args{keys} ? @{$args{keys}} : $args{keys};
  0         0  
508             }
509              
510 69 100       350 if ( $args{secret} ) {
    50          
511 22         264 $self->command( "export-secret-keys" );
512             } elsif ( $args{all} ){
513 0         0 $self->command( "export-all" );
514             } else {
515 47         377 $self->command( "export" );
516             }
517 69         486 $self->options( $options );
518 69         345 $self->args( $keys );
519              
520 69         393 $self->run_gnupg;
521 66         1298 $self->end_gnupg;
522             }
523              
524             sub encrypt($%) {
525 104     104 1 98737 my ($self,%args) = @_;
526              
527 104         429 my $options = [];
528             croak ( "no recipient specified\n" )
529 104 50 66     722 unless $args{recipient} or $args{symmetric};
530              
531 104 100       809 for my $recipient (
532             ref $args{recipient} eq 'ARRAY'
533 2         8 ? @{ $args{recipient} }
534             : $args{recipient} ) {
535 106         833 $recipient =~ s/ /\ /g; # Escape spaces in the recipient. This fills some strange edge case
536 106         624 push @$options, "--recipient" => $recipient;
537             }
538              
539 104 100       457 push @$options, "--sign" if $args{sign};
540             croak ( "can't sign an symmetric encrypted message\n" )
541 104 50 66     603 if $args{sign} and $args{symmetric};
542              
543 104   100     677 my $passphrase = $args{passphrase} || "";
544              
545 104 50       554 push @$options, "--armor" if $args{armor};
546             push @$options, "--local-user", $args{"local-user"}
547 104 50       433 if defined $args{"local-user"};
548              
549 104   66     830 $self->{input} = $args{plaintext} || $args{input};
550 104         290 $self->{output} = $args{output};
551 104 100       385 if ( $args{symmetric} ) {
552 17         136 $self->command( "symmetric" );
553             } else {
554 87         785 $self->command( "encrypt" );
555             }
556 104         582 $self->options( $options );
557 104         522 $self->args( [] );
558              
559 104         493 $self->run_gnupg;
560              
561             # Unless we decided to sign or are using symmetric cipher, we are done
562 96 100 66     2129 if ( $args{sign} or $args{symmetric} ) {
563 48         979 $self->send_passphrase( $passphrase );
564 48 100       358 if ( $args{sign} ) {
565 32         147 my ($cmd,$line) = $self->read_from_status;
566 32 50       443 $self->abort_gnupg( "invalid passphrase - $cmd\n" )
567             unless $cmd =~ /GOOD_PASSPHRASE/;
568             }
569             }
570              
571             # It is possible that this key has no assigned trust value.
572             # Assume the caller knows what he is doing.
573 96         944 $self->cpr_maybe_send( "untrusted_key.override", 'y' );
574              
575 96 100       1242 $self->end_gnupg unless $args{tie_mode};
576             }
577              
578             sub sign($%) {
579 33     33 1 14979 my ($self,%args) = @_;
580              
581 33         114 my $options = [];
582 33   50     191 my $passphrase = $args{passphrase} || "";
583              
584 33 50       190 push @$options, "--armor" if $args{armor};
585             push @$options, "--local-user", $args{"local-user"}
586 33 50       159 if defined $args{"local-user"};
587              
588 33   33     182 $self->{input} = $args{plaintext} || $args{input};
589 33         55 $self->{output} = $args{output};
590 33 100       217 if ( $args{clearsign} ) {
    100          
591 10         90 $self->command( "clearsign" );
592             } elsif ( $args{"detach-sign"}) {
593 11         99 $self->command( "detach-sign" );
594             } else {
595 12         120 $self->command( "sign" );
596             }
597 33         168 $self->options( $options );
598 33         154 $self->args( [] );
599              
600 33         134 $self->run_gnupg;
601              
602             # We need to unlock the private key
603 30         577 $self->send_passphrase( $passphrase );
604 30         132 my ($cmd,$line) = $self->read_from_status;
605 30 50       285 $self->abort_gnupg( "invalid passphrase - $cmd\n" )
606             unless $cmd =~ /GOOD_PASSPHRASE/;
607              
608 30 50       285 $self->end_gnupg unless $args{tie_mode};
609             }
610              
611             sub clearsign($%) {
612 10     10 1 5910 my $self = shift;
613 10         70 $self->sign( @_, clearsign => 1 );
614             }
615              
616              
617             sub check_sig($;$$) {
618 34     34 0 227 my ( $self, $cmd, $arg) = @_;
619              
620             # Our caller may already have grabbed the first line of
621             # signature reporting.
622 34 100       370 ($cmd,$arg) = $self->read_from_status unless ( $cmd );
623              
624             # Ignore patent warnings.
625 34 50       229 ( $cmd, $arg ) = $self->read_from_status()
626             if ( $cmd =~ /RSA_OR_IDEA/ );
627              
628             # Ignore automatic key imports
629 34 50       188 ( $cmd, $arg ) = $self->read_from_status()
630             if ( $cmd =~ /IMPORTED/ );
631              
632 34 50       135 ( $cmd, $arg ) = $self->read_from_status()
633             if ( $cmd =~ /IMPORT_OK/ );
634              
635 34 50       127 ( $cmd, $arg ) = $self->read_from_status()
636             if ( $cmd =~ /IMPORT_RES/ );
637              
638 34 50       324 $self->abort_gnupg( "invalid signature from ", $arg =~ /[^ ](.+)/, "\n" )
639             if ( $cmd =~ /BADSIG/);
640              
641 34 50       215 if ( $cmd =~ /ERRSIG/)
642             {
643 0         0 my ($keyid, $key_algo, $digest_algo, $sig_class, $timestamp, $rc)
644             = split ' ', $arg;
645 0 0       0 if ($rc == 9)
646             {
647 0         0 ($cmd, $arg) = $self->read_from_status();
648 0         0 $self->abort_gnupg( "no public key $keyid" );
649             }
650 0         0 $self->abort_gnupg( "error verifying signature from $keyid" )
651             }
652              
653 34 50       210 $self->abort_gnupg ( "protocol error: expected SIG_ID" )
654             unless $cmd =~ /SIG_ID/;
655 34         421 my ( $sigid, $date, $time ) = split /\s+/, $arg;
656              
657 34         246 ( $cmd, $arg ) = $self->read_from_status;
658 34 50       277 $self->abort_gnupg ( "protocol error: expected GOODSIG" )
659             unless $cmd =~ /GOODSIG/;
660 34         202 my ( $keyid, $name ) = split /\s+/, $arg, 2;
661              
662 34         149 ( $cmd, $arg ) = $self->read_from_status;
663 34         101 my $policy_url = undef;
664 34 50       141 if ( $cmd =~ /POLICY_URL/ ) {
665 0         0 $policy_url = $arg;
666 0         0 ( $cmd, $arg ) = $self->read_from_status;
667             }
668              
669 34 50       183 $self->abort_gnupg ( "protocol error: expected VALIDSIG" )
670             unless $cmd =~ /VALIDSIG/;
671 34         154 my ( $fingerprint ) = split /\s+/, $arg, 2;
672              
673 34         123 ( $cmd, $arg ) = $self->read_from_status;
674 34 50       209 $self->abort_gnupg ( "protocol error: expected TRUST*" )
675             unless $cmd =~ /TRUST/;
676 34         238 my ($trust) = parse_trust( $cmd );
677              
678 34         618 return { sigid => $sigid,
679             date => $date,
680             timestamp => $time,
681             keyid => $keyid,
682             user => $name,
683             fingerprint => $fingerprint,
684             trust => $trust,
685             policy_url => $policy_url,
686             };
687             }
688              
689             sub verify($%) {
690 24     24 1 15056 my ($self,%args) = @_;
691              
692 24 50       163 croak ( "missing signature argument\n" ) unless $args{signature};
693 24         64 my $files = [];
694 24 100       116 if ( $args{file} ) {
695             croak ( "detached signature must be in a file\n" )
696 8 50       168 unless -f $args{signature};
697             push @$files, $args{signature},
698 8 50       64 ref $args{file} ? @{$args{file}} : $args{file};
  0         0  
699             } else {
700 16         46 $self->{input} = $args{signature};
701             }
702 24         174 $self->command( "verify" );
703 24         113 $self->options( [] );
704 24         112 $self->args( $files );
705              
706 24         112 $self->run_gnupg;
707 21         447 my $sig = $self->check_sig;
708              
709 21         142 $self->end_gnupg;
710              
711 21         442 return $sig;
712             }
713              
714             sub decrypt($%) {
715 69     69 1 97761 my $self = shift;
716 69         835 my %args = @_;
717              
718 69   66     583 $self->{input} = $args{ciphertext} || $args{input};
719 69         309 $self->{output} = $args{output};
720 69         717 $self->command( "decrypt" );
721 69         518 $self->options( [] );
722 69         465 $self->args( [] );
723              
724 69         474 $self->run_gnupg;
725              
726 63 100       2835 return $self->decrypt_postwrite( @_ ) unless $args{tie_mode};
727             }
728              
729             sub decrypt_postwrite($%) {
730 63     63 0 2160 my ($self,%args) = @_;
731              
732 63   50     464 my $passphrase = $args{passphrase} || "";
733              
734 63         273 my ( $cmd, $arg );
735 63 100       377 unless ( $args{symmetric} ) {
736 51         485 ( $cmd, $arg ) = $self->read_from_status;
737 51 50       704 $self->abort_gnupg ( "protocol error: expected ENC_TO got $cmd: \n" )
738             unless $cmd =~ /ENC_TO/;
739             }
740              
741 63         683 $self->send_passphrase( $passphrase );
742 63         366 ($cmd,$arg) = $self->read_from_status;
743              
744 63 50       480 $self->abort_gnupg ( "invalid passphrase - $cmd\n" )
745             if $cmd =~ /BAD_PASSPHRASE/;
746              
747 63         287 my $sig = undef;
748              
749 63 100       365 if ( ! $args{symmetric} ) {
750 51 50       666 $self->abort_gnupg ( "protocol error: expected GOOD_PASSPHRASE got $cmd: \n" )
751             unless $cmd =~ /GOOD_PASSPHRASE/;
752              
753 51 100       852 $sig = $self->decrypt_postread() unless $args{tie_mode};
754             } else {
755             # gnupg 1.0.2 adds this status message
756 12 50       288 ( $cmd, $arg ) = $self->read_from_status() if $cmd =~ /BEGIN_DECRYPTION/;
757             # gnupg 1.4.12 adds this status message
758 12 50       252 ( $cmd, $arg ) = $self->read_from_status() if $cmd =~ /DECRYPTION_INFO/;
759              
760 12 50       156 $self->abort_gnupg( "invalid passphrase - $cmd" ) unless $cmd =~ /PLAINTEXT/;
761             }
762              
763 63 100       628 $self->end_gnupg() unless $args{tie_mode};
764              
765 63 100       1320 return $sig ? $sig : 1;
766             }
767              
768             sub decrypt_postread($) {
769 51     51 0 240 my $self = shift;
770              
771 51         174 my @cmds;
772             # gnupg 1.0.2 adds this status message
773 51         265 my ( $cmd, $arg ) = $self->read_from_status;
774 51         250 push @cmds, $cmd;
775              
776 51 50       362 if ($cmd =~ /BEGIN_DECRYPTION/) {
777 51         291 ( $cmd, $arg ) = $self->read_from_status();
778 51         188 push @cmds, $cmd;
779             };
780              
781 51         136 my $sig = undef;
782 51   66     688 while (defined $cmd && !($cmd =~ /DECRYPTION_OKAY/)) {
783 166 100       646 if ( $cmd =~ /SIG_ID/ ) {
784 13         325 $sig = $self->check_sig( $cmd, $arg );
785             }
786 166         561 ( $cmd, $arg ) = $self->read_from_status();
787 166 50       1821 push @cmds, $cmd if defined $cmd;
788             };
789              
790 51         442 my $cmds = join ', ', @cmds;
791 51 50       460 $self->abort_gnupg( "protocol error: expected DECRYPTION_OKAY but never got it (all I saw was: $cmds): \n" )
792             unless $cmd =~ /DECRYPTION_OKAY/;
793              
794 51 100       505 return $sig ? $sig : 1;
795             }
796              
797             1;
798             __END__
799              
800             =pod
801              
802             =head1 NAME
803              
804             GnuPG - Perl module interface to the GNU Privacy Guard (v1.x.x series)
805              
806             =head1 SYNOPSIS
807              
808             use GnuPG qw( :algo );
809              
810             my $gpg = new GnuPG();
811              
812             $gpg->encrypt( plaintext => "file.txt", output => "file.gpg",
813             armor => 1, sign => 1,
814             passphrase => $secret );
815              
816             $gpg->decrypt( ciphertext => "file.gpg", output => "file.txt" );
817              
818             $gpg->clearsign( plaintext => "file.txt", output => "file.txt.asc",
819             passphrase => $secret, armor => 1,
820             );
821              
822             $gpg->verify( signature => "file.txt.asc", file => "file.txt" );
823              
824             $gpg->gen_key( name => "Joe Blow", comment => "My GnuPG key",
825             passphrase => $secret,
826             );
827              
828             =head1 DESCRIPTION
829              
830             GnuPG is a perl interface to the GNU Privacy Guard. It uses the
831             shared memory coprocess interface that gpg provides for its
832             wrappers. It tries its best to map the interactive interface of
833             the gpg to a more programmatic model.
834              
835             =head1 API OVERVIEW
836              
837             The API is accessed through methods on a GnuPG object which is
838             a wrapper around the B<gpg> program. All methods takes their
839             argument using named parameters, and errors are returned by
840             throwing an exception (using croak). If you wan't to catch
841             errors you will have to use eval.
842              
843             When handed in a file handle for input or output parameters
844             on many of the functions, the API attempts to tie that
845             handle to STDIN and STDOUT. In certain persistent environments
846             (particularly a web environment), this will not work. This
847             problem can be avoided by passing in file names to all
848             relevant parameters rather than a Perl file handle.
849              
850             There is also a tied file handle interface which you may find more
851             convenient for encryption and decryption. See GnuPG::Tie(3) for details.
852              
853             =head1 CONSTRUCTOR
854              
855             =head2 new ( [params] )
856              
857             You create a new GnuPG wrapper object by invoking its new method.
858             (How original !). The module will try to finds the B<gpg> program
859             in your path and will croak if it can't find it. Here are the
860             parameters that it accepts :
861              
862             =over
863              
864             =item gnupg_path
865              
866             Path to the B<gpg> program.
867              
868             =item options
869              
870             Path to the options file for B<gpg>. If not specified, it will use
871             the default one (usually F<~/.gnupg/options>).
872              
873             =item homedir
874              
875             Path to the B<gpg> home directory. This is the directory that contains
876             the default F<options> file, the public and private key rings as well
877             as the trust database.
878              
879             =item trace
880              
881             If this variable is set to true, B<gpg> debugging output will be sent
882             to stderr.
883              
884             =back
885              
886             Example: my $gpg = new GnuPG();
887              
888             =head1 METHODS
889              
890             =head2 gen_key( [params] )
891              
892             This methods is used to create a new gpg key pair. The methods croaks
893             if there is an error. It is a good idea to press random keys on the
894             keyboard while running this methods because it consumes a lot of
895             entropy from the computer. Here are the parameters it accepts :
896              
897             =over
898              
899             =item algo
900              
901             This is the algorithm use to create the key. Can be I<DSA_ELGAMAL>,
902             I<DSA>, I<RSA_RSA> or I<RSA>.
903             It defaults to I<DSA_ELGAMAL>. To import
904             those constant in your name space, use the I<:algo> tag.
905              
906             =item size
907              
908             The size of the public key. Defaults to 1024. Cannot be less than
909             768 bits, and keys longer than 2048 are also discouraged. (You *DO*
910             know that your monitor may be leaking sensitive information ;-).
911              
912             =item valid
913              
914             How long the key is valid. Defaults to 0 or never expire.
915              
916             =item name
917              
918             This is the only mandatory argument. This is the name that will used
919             to construct the user id.
920              
921             =item email
922              
923             Optional email portion of the user id.
924              
925             =item comment
926              
927             Optional comment portion of the user id.
928              
929             =item passphrase
930              
931             The passphrase that will be used to encrypt the private key. Optional
932             but strongly recommended.
933              
934             =back
935              
936             Example: $gpg->gen_key( algo => DSA_ELGAMAL, size => 1024,
937             name => "My name" );
938              
939             =head2 import_keys( [params] )
940              
941             Import keys into the GnuPG private or public keyring. The method
942             croaks if it encounters an error. It returns the number of
943             keys imported. Parameters :
944              
945             =over
946              
947             =item keys
948              
949             Only parameter and mandatory. It can either be a filename or a
950             reference to an array containing a list of files that will be
951             imported.
952              
953             =back
954              
955             Example: $gpg->import_keys( keys => [ qw( key.pub key.sec ) ] );
956              
957             =head2 export_keys( [params] )
958              
959             Exports keys from the GnuPG keyrings. The method croaks if it
960             encounters an error. Parameters :
961              
962             =over
963              
964             =item keys
965              
966             Optional argument that restricts the keys that will be exported.
967             Can either be a user id or a reference to an array of userid that
968             specifies the keys to be exported. If left unspecified, all keys
969             will be exported.
970              
971             =item secret
972              
973             If this argument is to true, the secret keys rather than the public
974             ones will be exported.
975              
976             =item all
977              
978             If this argument is set to true, all keys (even those that aren't
979             OpenPGP compliant) will be exported.
980              
981             =item output
982              
983             This argument specifies where the keys will be exported. Can be either
984             a file name or a reference to a file handle. If not specified, the
985             keys will be exported to stdout.
986              
987             =item armor
988              
989             Set this parameter to true, if you want the exported keys to be ASCII
990             armored.
991              
992             =back
993              
994             Example: $gpg->export_keys( armor => 1, output => "keyring.pub" );
995              
996              
997             =head2 encrypt( [params] )
998              
999             This method is used to encrypt a message, either using assymetric
1000             or symmetric cryptography. The methods croaks if an error is
1001             encountered. Parameters:
1002              
1003             =over
1004              
1005             =item plaintext
1006              
1007             This argument specifies what to encrypt. It can be either a filename
1008             or a reference to a file handle. If left unspecified, STDIN will be
1009             encrypted.
1010              
1011             =item output
1012              
1013             This optional argument specifies where the ciphertext will be output.
1014             It can be either a file name or a reference to a file handle. If left
1015             unspecified, the ciphertext will be sent to STDOUT.
1016              
1017             =item armor
1018              
1019             If this parameter is set to true, the ciphertext will be ASCII
1020             armored.
1021              
1022             =item symmetric
1023              
1024             If this parameter is set to true, symmetric cryptography will be
1025             used to encrypt the message. You will need to provide a I<passphrase>
1026             parameter.
1027              
1028             =item recipient
1029              
1030             If not using symmetric cryptography, you will have to provide this
1031             parameter. It should contains the userid of the intended recipient of
1032             the message. It will be used to look up the key to use to encrypt the
1033             message. The parameter can also take an array ref, if you want to encrypt
1034             the message for a group of recipients.
1035              
1036             =item sign
1037              
1038             If this parameter is set to true, the message will also be signed. You
1039             will probably have to use the I<passphrase> parameter to unlock the
1040             private key used to sign message. This option is incompatible with
1041             the I<symmetric> one.
1042              
1043             =item local-user
1044              
1045             This parameter is used to specified the private key that will be used
1046             to sign the message. If left unspecified, the default user will be
1047             used. This option only makes sense when using the I<sign> option.
1048              
1049             =item passphrase
1050              
1051             This parameter contains either the secret passphrase for the symmetric
1052             algorithm or the passphrase that should be used to decrypt the private
1053             key.
1054              
1055             =back
1056              
1057             Example: $gpg->encrypt( plaintext => file.txt, output => "file.gpg",
1058             sign => 1, passphrase => $secret
1059             );
1060              
1061             =head2 sign( [params] )
1062              
1063             This method is used create a signature for a file or stream of data.
1064             This method croaks on errors. Parameters :
1065              
1066             =over
1067              
1068             =item plaintext
1069              
1070             This argument specifies what to sign. It can be either a filename
1071             or a reference to a file handle. If left unspecified, the data read on
1072             STDIN will be signed.
1073              
1074             =item output
1075              
1076             This optional argument specifies where the signature will be output.
1077             It can be either a file name or a reference to a file handle. If left
1078             unspecified, the signature will be sent to STDOUT.
1079              
1080             =item armor
1081              
1082             If this parameter is set to true, the signature will be ASCII armored.
1083              
1084             =item passphrase
1085              
1086             This parameter contains the secret that should be used to decrypt the
1087             private key.
1088              
1089             =item local-user
1090              
1091             This parameter is used to specified the private key that will be used
1092             to make the signature . If left unspecified, the default user will be
1093             used.
1094              
1095             =item detach-sign
1096              
1097             If set to true, a digest of the data will be signed rather than
1098             the whole file.
1099              
1100             =back
1101              
1102             Example: $gpg->sign( plaintext => "file.txt", output => "file.txt.asc",
1103             armor => 1,
1104             );
1105              
1106             =head2 clearsign( [params] )
1107              
1108             This methods clearsign a message. The output will contains the original
1109             message with a signature appended. It takes the same parameters as
1110             the B<sign> method.
1111              
1112             =head2 verify( [params] )
1113              
1114             This method verifies a signature against the signed message. The
1115             methods croaks if the signature is invalid or an error is
1116             encountered. If the signature is valid, it returns an hash with
1117             the signature parameters. Here are the method's parameters :
1118              
1119             =over
1120              
1121             =item signature
1122              
1123             If the message and the signature are in the same file (i.e. a
1124             clearsigned message), this parameter can be either a file name or a
1125             reference to a file handle. If the signature doesn't follows the
1126             message, than it must be the name of the file that contains the
1127             signature.
1128              
1129             =item file
1130              
1131             This is a file name or a reference to an array of file names that
1132             contains the signed data.
1133              
1134             =back
1135              
1136             When the signature is valid, here are the elements of the hash
1137             that is returned by the method :
1138              
1139             =over
1140              
1141             =item sigid
1142              
1143             The signature id. This can be used to protect against replay
1144             attack.
1145              
1146             =item date
1147              
1148             The data at which the signature has been made.
1149              
1150             =item timestamp
1151              
1152             The epoch timestamp of the signature.
1153              
1154             =item keyid
1155              
1156             The key id used to make the signature.
1157              
1158             =item user
1159              
1160             The userid of the signer.
1161              
1162             =item fingerprint
1163              
1164             The fingerprint of the signature.
1165              
1166             =item trust
1167              
1168             The trust value of the public key of the signer. Those are values that
1169             can be imported in your namespace with the :trust tag. They are
1170             (TRUST_UNDEFINED, TRUST_NEVER, TRUST_MARGINAL, TRUST_FULLY, TRUST_ULTIMATE).
1171              
1172             =back
1173              
1174             Example : my $sig = $gpg->verify( signature => "file.txt.asc",
1175             file => "file.txt" );
1176              
1177             =head2 decrypt( [params] )
1178              
1179             This method decrypts an encrypted message. It croaks, if there is an
1180             error while decrypting the message. If the message was signed, this
1181             method also verifies the signature. If decryption is sucessful, the
1182             method either returns the valid signature parameters if present, or
1183             true. Method parameters :
1184              
1185             =over
1186              
1187             =item ciphertext
1188              
1189             This optional parameter contains either the name of the file
1190             containing the ciphertext or a reference to a file handle containing
1191             the ciphertext. If not present, STDIN will be decrypted.
1192              
1193             =item output
1194              
1195             This optional parameter determines where the plaintext will be stored.
1196             It can be either a file name or a reference to a file handle. If left
1197             unspecified, the plaintext will be sent to STDOUT.
1198              
1199             =item symmetric
1200              
1201             This should be set to true, if the message is encrypted using
1202             symmetric cryptography.
1203              
1204             =item passphrase
1205              
1206             The passphrase that should be used to decrypt the message (in the case
1207             of a message encrypted using a symmetric cipher) or the secret that
1208             will unlock the private key that should be used to decrypt the
1209             message.
1210              
1211             =back
1212              
1213             Example: $gpg->decrypt( ciphertext => "file.gpg", output => "file.txt"
1214             passphrase => $secret );
1215              
1216             =head1 BUGS AND LIMITATIONS
1217              
1218             This module doesn't work (yet) with the v2 branch of GnuPG.
1219              
1220             =head1 AUTHOR
1221              
1222             Francis J. Lacoste <francis.lacoste@Contre.COM>
1223              
1224             =head1 COPYRIGHT
1225              
1226             Copyright (c) 1999,2000 iNsu Innovations. Inc.
1227             Copyright (c) 2001 Francis J. Lacoste
1228              
1229             This program is free software; you can redistribute it and/or modify
1230             it under the terms of the GNU General Public License as published by
1231             the Free Software Foundation; either version 2 of the License, or
1232             (at your option) any later version.
1233              
1234             =head1 SEE ALSO
1235              
1236             L<GnuPG::Tie>
1237              
1238             Alternative module: L<GnuPG::Interface>
1239              
1240             gpg(1)
1241              
1242             =cut