1# Create a PGP signature for data, securely. 2# 3# THIS IS NOT A GENERAL PGP MODULE. 4# 5# For a general PGP module that handles encryption and decryption, key ring 6# management, and all of the other wonderful things you want to do with PGP, 7# see the PGP module directory on CPAN. This module is designed to do one and 8# only one thing and do it fast, well, and securely -- create and check 9# detached signatures for some block of data. 10# 11# This above all: to thine own self be true, 12# And it must follow, as the night the day, 13# Thou canst not then be false to any man. 14# -- William Shakespeare, _Hamlet_ 15# 16# SPDX-License-Identifier: GPL-1.0-or-later OR Artistic-1.0-Perl 17 18############################################################################## 19# Modules and declarations 20############################################################################## 21 22package PGP::Sign 1.04; 23 24use 5.020; 25use autodie; 26use warnings; 27 28use Carp qw(croak); 29use Exporter qw(import); 30use File::Temp (); 31use IO::Handle; 32use IPC::Run qw(finish run start timeout); 33use POSIX qw(EAGAIN); 34use Scalar::Util qw(blessed); 35 36# Export pgp_sign and pgp_verify by default for backwards compatibility. 37## no critic (Modules::ProhibitAutomaticExportation) 38our @EXPORT = qw(pgp_sign pgp_verify); 39our @EXPORT_OK = qw(pgp_error); 40## use critic 41 42# The flags to use with the various PGP styles. 43my %SIGN_FLAGS = ( 44 GPG => [ 45 qw( 46 --detach-sign --armor 47 --quiet --textmode --batch --no-tty --pinentry-mode=loopback 48 --no-greeting --no-permission-warning 49 ), 50 ], 51 GPG1 => [ 52 qw( 53 --detach-sign --armor 54 --quiet --textmode --batch --no-tty --no-use-agent 55 --no-greeting --no-permission-warning 56 --force-v3-sigs --allow-weak-digest-algos 57 ), 58 ], 59); 60my %VERIFY_FLAGS = ( 61 GPG => [ 62 qw( 63 --verify 64 --quiet --batch --no-tty 65 --no-greeting --no-permission-warning 66 --no-auto-key-retrieve --no-auto-check-trustdb 67 --allow-weak-digest-algos 68 --disable-dirmngr 69 ), 70 ], 71 GPG1 => [ 72 qw( 73 --verify 74 --quiet --batch --no-tty 75 --no-greeting --no-permission-warning 76 --no-auto-key-retrieve --no-auto-check-trustdb 77 --allow-weak-digest-algos 78 ), 79 ], 80); 81 82############################################################################## 83# Old global variables 84############################################################################## 85 86# These variables are part of the legacy PGP::Sign interface and are 87# maintained for backward compatibility. They are only used by the legacy 88# pgp_sign and pgp_verify functions, not by the new object-oriented API. 89 90# Whether or not to perform some standard whitespace munging to make other 91# signing and checking routines happy. 92our $MUNGE = 0; 93 94# The default path to PGP. PGPS is for signing, PGPV is for verifying. 95# (There's no reason to use separate commands any more, but with PGPv5 these 96# were two different commands, so this became part of the legacy API.) 97our $PGPS; 98our $PGPV; 99 100# The path to the directory containing the key ring. If not set, defaults to 101# $ENV{GNUPGHOME} or $HOME/.gnupg. 102our $PGPPATH; 103 104# What style of PGP invocation to use by default. If not set, defaults to the 105# default style for the object-oriented API. 106our $PGPSTYLE; 107 108# The directory in which temporary files should be created. If not set, 109# defaults to whatever File::Temp decides to use. 110our $TMPDIR; 111 112# Used by pgp_sign and pgp_verify to store errors returned by the 113# object-oriented API so that they can be returned via pgp_error. 114my @ERROR = (); 115 116############################################################################## 117# Utility functions 118############################################################################## 119 120# print with error checking and an explicit file handle. autodie 121# unfortunately can't help us with these because they can't be prototyped and 122# hence can't be overridden. 123# 124# $fh - Output file handle 125# @args - Remaining arguments to print 126# 127# Returns: undef 128# Throws: Text exception on output failure 129sub _print_fh { 130 my ($fh, @args) = @_; 131 print {$fh} @args or croak("print failed: $!"); 132 return; 133} 134 135# Write to a non-blocking file descriptor. Handles the select loop waiting 136# for the file descriptor to be ready to accept data. 137# 138# $fh - Output file handle 139# $data - Data to write 140# 141# Returns: undef 142# Throws: Text exception on output failure 143sub _write_nonblocking { 144 my ($fh, $data) = @_; 145 my $win = q{}; 146 vec($win, fileno($fh), 1) = 1; 147 my $length = length($data); 148 my $total = 0; 149 while ($total < $length) { 150 no autodie qw(syswrite); 151 select(undef, my $wout = $win, undef, undef) 152 or croak("cannot select on pipe: $!"); 153 my $written = syswrite($fh, $data, $length - $total, $total); 154 if (!defined($written) && $! != EAGAIN) { 155 croak("write to pipe failed: $!"); 156 } 157 if (defined($written)) { 158 $total += $written; 159 } 160 } 161 return; 162} 163 164############################################################################## 165# Object-oriented interface 166############################################################################## 167 168# Create a new PGP::Sign object encapsulating the configuration. 169# 170# $args_ref - Anonymous hash of arguments with the following keys: 171# home - Path to the GnuPG homedir containing keyrings 172# munge - Boolean indicating whether to munge whitespace 173# path - Path to the GnuPG binary to use 174# style - Style of OpenPGP backend to use 175# tmpdir - Directory to use for temporary files 176# 177# Returns: Newly created object 178# Throws: Text exception for an invalid OpenPGP backend style 179sub new { 180 my ($class, $args_ref) = @_; 181 182 # Check the style argument. 183 my $style = $args_ref->{style} || 'GPG'; 184 if ($style ne 'GPG' && $style ne 'GPG1') { 185 croak("Unknown OpenPGP backend style $style"); 186 } 187 188 # If path is not given, set a default based on the style. 189 my $path = $args_ref->{path} // lc($style); 190 191 # Create and return the object. 192 my $self = { 193 home => $args_ref->{home}, 194 munge => $args_ref->{munge}, 195 path => $path, 196 style => $style, 197 tmpdir => $args_ref->{tmpdir}, 198 }; 199 bless($self, $class); 200 return $self; 201} 202 203# This function actually sends the data to a file handle. It's necessary to 204# implement munging (stripping trailing spaces on a line). 205# 206# $fh - The file handle to which to write the data 207# $string - The data to write 208sub _write_string { 209 my ($self, $fh, $string) = @_; 210 211 # If there were any left-over spaces from the last invocation, prepend 212 # them to the string and clear them. 213 if ($self->{spaces}) { 214 $string = $self->{spaces} . $string; 215 $self->{spaces} = q{}; 216 } 217 218 # If whitespace munging is enabled, strip any trailing whitespace from 219 # each line of the string for which we've seen the newline. Then, remove 220 # and store any spaces at the end of the string, since the newline may be 221 # in the next chunk. 222 # 223 # If there turn out to be no further chunks, this removes any trailing 224 # whitespace on the last line without a newline, which is still correct. 225 if ($self->{munge}) { 226 $string =~ s{ [ ]+ \n }{\n}xmsg; 227 if ($string =~ s{ ([ ]+) \Z }{}xms) { 228 $self->{spaces} = $1; 229 } 230 } 231 232 _write_nonblocking($fh, $string); 233 return; 234} 235 236# This is our generic "take this data and shove it" routine, used both for 237# signature generation and signature checking. Scalars, references to arrays, 238# references to IO::Handle objects, file globs, references to code, and 239# references to file globs are all supported as ways to get the data, and at 240# most one line at a time is read (cutting down on memory usage). 241# 242# References to code are an interesting subcase. A code reference is executed 243# repeatedly, passing whatever it returns to GnuPG, until it returns undef. 244# 245# $fh - The file handle to which to write the data 246# @sources - The data to write, in any of those formats 247sub _write_data { 248 my ($self, $fh, @sources) = @_; 249 $self->{spaces} = q{}; 250 251 # Deal with all of our possible sources of input, one at a time. 252 # 253 # We can't do anything interesting or particularly "cool" with references 254 # to references, so those we just print. (Perl allows circular 255 # references, so we can't just dereference references to references until 256 # we get something interesting.) 257 for my $source (@sources) { 258 if (ref($source) eq 'ARRAY') { 259 for my $chunk (@$source) { 260 $self->_write_string($fh, $chunk); 261 } 262 } elsif (ref($source) eq 'GLOB' || ref(\$source) eq 'GLOB') { 263 while (defined(my $chunk = <$source>)) { 264 $self->_write_string($fh, $chunk); 265 } 266 } elsif (ref($source) eq 'SCALAR') { 267 $self->_write_string($fh, $$source); 268 } elsif (ref($source) eq 'CODE') { 269 while (defined(my $chunk = &$source())) { 270 $self->_write_string($fh, $chunk); 271 } 272 } elsif (blessed($source)) { 273 if ($source->isa('IO::Handle')) { 274 while (defined(my $chunk = <$source>)) { 275 $self->_write_string($fh, $chunk); 276 } 277 } else { 278 $self->_write_string($fh, $source); 279 } 280 } else { 281 $self->_write_string($fh, $source); 282 } 283 } 284 return; 285} 286 287# Construct the command for signing. This will expect the passphrase on file 288# descriptor 3. 289# 290# $keyid - The OpenPGP key ID with which to sign 291# 292# Returns: List of the command and arguments. 293sub _build_sign_command { 294 my ($self, $keyid) = @_; 295 my @command = ($self->{path}, '-u', $keyid, qw(--passphrase-fd 3)); 296 push(@command, @{ $SIGN_FLAGS{ $self->{style} } }); 297 if ($self->{home}) { 298 push(@command, '--homedir', $self->{home}); 299 } 300 return @command; 301} 302 303# Construct the command for verification. This will send all logging to 304# standard output and the status messages to file descriptor 3. 305# 306# $signature_file - Path to the file containing the signature 307# $data_file - Path to the file containing the signed data 308# 309# Returns: List of the command and arguments. 310sub _build_verify_command { 311 my ($self, $signature_file, $data_file) = @_; 312 my @command = ($self->{path}, qw(--status-fd 3 --logger-fd 1)); 313 push(@command, @{ $VERIFY_FLAGS{ $self->{style} } }); 314 if ($self->{home}) { 315 push(@command, '--homedir', $self->{home}); 316 } 317 push(@command, $signature_file, $data_file); 318 return @command; 319} 320 321# Create a detached signature for the given data. 322# 323# $keyid - GnuPG key ID to use to sign the data 324# $passphrase - Passphrase for the GnuPG key 325# @sources - The data to sign (see _write_data for more information) 326# 327# Returns: The signature as an ASCII-armored block with embedded newlines 328# Throws: Text exception on failure that includes the GnuPG output 329sub sign { 330 my ($self, $keyid, $passphrase, @sources) = @_; 331 332 # Ignore SIGPIPE, since we're going to be talking to GnuPG. 333 local $SIG{PIPE} = 'IGNORE'; 334 335 # Build the command to run. 336 my @command = $self->_build_sign_command($keyid); 337 338 # Fork off a pgp process that we're going to be feeding data to, and tell 339 # it to just generate a signature using the given key id and pass phrase. 340 my $writefh = IO::Handle->new(); 341 my $passfh = IO::Handle->new(); 342 my ($signature, $errors); 343 #<<< 344 my $h = start( 345 \@command, 346 '3<pipe', $passfh, 347 '<pipe', $writefh, 348 '>', \$signature, 349 '2>', \$errors, 350 ); 351 #>>> 352 353 # Push the passphrase to the subprocess so that it doesn't block waiting 354 # for it and not read its input. 355 _write_nonblocking($passfh, $passphrase); 356 close($passfh); 357 358 # Send in the data to be signed. 359 $self->_write_data($writefh, @sources); 360 close($writefh); 361 362 # Get the return status and raise an exception on failure. 363 if (!finish($h)) { 364 my $status = $h->result(); 365 $errors .= "Execution of $command[0] failed with status $status"; 366 croak($errors); 367 } 368 369 # The resulting signature will look something like this: 370 # 371 # -----BEGIN PGP SIGNATURE----- 372 # Version: GnuPG v0.9.2 (SunOS) 373 # Comment: For info see http://www.gnupg.org 374 # 375 # iEYEARECAAYFAjbA/fsACgkQ+YXjQAr8dHYsMQCgpzOkRRopdW0nuiSNMB6Qx2Iw 376 # bw0AoMl82UxQEkh4uIcLSZMdY31Z8gtL 377 # =Dj7i 378 # -----END PGP SIGNATURE----- 379 # 380 # Find and strip the marker line for the start of the signature. 381 my @signature = split(m{\n}xms, $signature); 382 while ((shift @signature) !~ m{-----BEGIN [ ] PGP [ ] SIGNATURE-----}xms) { 383 if (!@signature) { 384 croak('No signature returned by GnuPG'); 385 } 386 } 387 388 # Strip any headers off the signature. Thankfully all of the important 389 # data is encoded into the signature itself, so the headers aren't needed. 390 while (@signature && $signature[0] ne q{}) { 391 shift(@signature); 392 } 393 shift(@signature); 394 395 # Remove the trailing marker line. 396 pop(@signature); 397 398 # Everything else is the signature that we want. 399 return join("\n", @signature); 400} 401 402# Check a detached signature for given data. 403# 404# $signature - The signature as an ASCII-armored string with embedded newlines 405# @sources - The data over which to check the signature 406# 407# Returns: The human-readable key ID of the signature, or an empty string if 408# the signature did not verify 409# Throws: Text exception on an error other than a bad signature 410sub verify { 411 my ($self, $signature, @sources) = @_; 412 chomp($signature); 413 414 # Ignore SIGPIPE, since we're going to be talking to PGP. 415 local $SIG{PIPE} = 'IGNORE'; 416 417 # To verify a detached signature, we need to save both the signature and 418 # the data to files and then run GnuPG on the pair of files. There 419 # doesn't appear to be a way to feed both the data and the signature in on 420 # file descriptors. 421 my @tmpdir = defined($self->{tmpdir}) ? (DIR => $self->{tmpdir}) : (); 422 my $sigfh = File::Temp->new(@tmpdir, SUFFIX => '.asc'); 423 _print_fh($sigfh, "-----BEGIN PGP SIGNATURE-----\n"); 424 _print_fh($sigfh, "\n", $signature); 425 _print_fh($sigfh, "\n-----END PGP SIGNATURE-----\n"); 426 close($sigfh); 427 my $datafh = File::Temp->new(@tmpdir); 428 $self->_write_data($datafh, @sources); 429 close($datafh); 430 431 # Build the command to run. 432 my @command 433 = $self->_build_verify_command($sigfh->filename, $datafh->filename); 434 435 # Call GnuPG to check the signature. 436 my ($output, $results); 437 run(\@command, '>&', \$output, '3>', \$results); 438 my $status = $?; 439 440 # Check for the message that gives us the key status and return the 441 # appropriate thing to our caller. 442 # 443 # GPG 1.4.23 444 # [GNUPG:] GOODSIG 7D80315C5736DE75 Russ Allbery <eagle@eyrie.org> 445 # [GNUPG:] BADSIG 7D80315C5736DE75 Russ Allbery <eagle@eyrie.org> 446 # 447 # Note that this returns the human-readable key ID instead of the actual 448 # key ID. This is a historical wart in the API; a future version will 449 # hopefully add an option to return more accurate signer information. 450 for my $line (split(m{\n}xms, $results)) { 451 if ($line =~ m{ ^ \[GNUPG:\] \s+ GOODSIG \s+ \S+ \s+ (.*) }xms) { 452 return $1; 453 } elsif ($line =~ m{ ^ \[GNUPG:\] \s+ BADSIG \s+ }xms) { 454 return q{}; 455 } 456 } 457 458 # Neither a good nor a bad signature seen. 459 $output .= $results; 460 if ($status != 0) { 461 $output .= "Execution of $command[0] failed with status $status"; 462 } 463 croak($output); 464} 465 466############################################################################## 467# Legacy function API 468############################################################################## 469 470# This is the original API from 0.x versions of PGP::Sign. It is maintained 471# for backwards compatibility, but is now a wrapper around the object-oriented 472# API that uses the legacy global variables. The object-oriented API should 473# be preferred for all new code. 474 475# Create a detached signature for the given data. 476# 477# The original API returned the PGP implementation version from the signature 478# headers as the second element of the list returned in array context. This 479# information is pointless and unnecessary and GnuPG doesn't include that 480# header by default, so the fixed string "GnuPG" is now returned for backwards 481# compatibility. 482# 483# Errors are stored for return by pgp_error(), overwriting any previously 484# stored error. 485# 486# $keyid - GnuPG key ID to use to sign the data 487# $passphrase - Passphrase for the GnuPG key 488# @sources - The data to sign (see _write_data for more information) 489# 490# Returns: The signature as an ASCII-armored block in scalar context 491# The signature and the string "GnuPG" in list context 492# undef or the empty list on error 493sub pgp_sign { 494 my ($keyid, $passphrase, @sources) = @_; 495 @ERROR = (); 496 497 # Create the signer object. 498 my $signer = PGP::Sign->new( 499 { 500 home => $PGPPATH, 501 munge => $MUNGE, 502 path => $PGPS, 503 style => $PGPSTYLE, 504 tmpdir => $TMPDIR, 505 }, 506 ); 507 508 # Do the work, capturing any errors. 509 my $signature = eval { $signer->sign($keyid, $passphrase, @sources) }; 510 if ($@) { 511 @ERROR = split(m{\n}xms, $@); 512 return; 513 } 514 515 # Return the results, including a dummy version if desired. 516 ## no critic (Freenode::Wantarray) 517 return wantarray ? ($signature, 'GnuPG') : $signature; 518 ## use critic 519} 520 521# Check a detached signature for given data. 522# 523# $signature - The signature as an ASCII-armored string with embedded newlines 524# @sources - The data over which to check the signature 525# 526# Returns: The human-readable key ID of the signature 527# An empty string if the signature did not verify 528# undef on error 529sub pgp_verify { 530 my ($signature, $version, @sources) = @_; 531 @ERROR = (); 532 533 # Create the verifier object. 534 my $verifier = PGP::Sign->new( 535 { 536 home => $PGPPATH, 537 munge => $MUNGE, 538 path => $PGPV, 539 style => $PGPSTYLE, 540 tmpdir => $TMPDIR, 541 }, 542 ); 543 544 # Do the work, capturing any errors. 545 my $signer = eval { $verifier->verify($signature, @sources) }; 546 if ($@) { 547 @ERROR = split(m{\n}xms, $@); 548 return; 549 } 550 551 # Return the results. 552 return $signer; 553} 554 555# Retrieve errors from the previous pgp_sign() or pgp_verify() call. 556# 557# Historically the pgp_error() return value in list context had newlines at 558# the end of each line, so add them back in. 559# 560# Returns: A list of GnuPG output and error messages in list context 561# The block of GnuPG output and error message in scalar context 562## no critic (Freenode::Wantarray) 563sub pgp_error { 564 my @error_lines = map { "$_\n" } @ERROR; 565 return wantarray ? @error_lines : join(q{}, @error_lines); 566} 567## use critic 568 569############################################################################## 570# Module return value and documentation 571############################################################################## 572 573# Make sure the module returns true. 5741; 575 576__DATA__ 577 578=for stopwords 579Allbery DSS GNUPGHOME GPG GPG1 Gierth Mitzelfelt OpenPGP PGPMoose PGPPATH 580TMPDIR canonicalized d'Itri egd keyrings pgpverify ps signcontrol 581KEYID --force-v3-sigs --allow-weak-digest-algos --homedir --textmode cleartext 582cryptographic gpg gpg1 gpgv homedir interoperable tmpdir 583 584=head1 NAME 585 586PGP::Sign - Create detached PGP signatures for data, securely 587 588=head1 SYNOPSIS 589 590 use PGP::Sign; 591 my $keyid = '<some-key-id>'; 592 my $passphrase = '<passphrase-for-key>'; 593 my @data = ('lines to', 'be signed'); 594 595 # Object-oriented API. 596 my $pgp = PGP::Sign->new(); 597 my $signature = $pgp->sign($keyid, $passphrase, @data); 598 my $signer = $pgp->verify($signature, @data); 599 600 # Legacy API. 601 $signature = pgp_sign($keyid, $passphrase, @data); 602 $signer = pgp_verify($signature, undef, @data); 603 my @errors = PGP::Sign::pgp_error(); 604 605=head1 REQUIREMENTS 606 607Perl 5.20 or later, the IPC::Run module, and either GnuPG v1 or GnuPG v2. It 608is only tested on UNIX-derivative systems and is moderately unlikely to work 609on Windows. 610 611=head1 DESCRIPTION 612 613This module supports only two OpenPGP operations: Generate and check detached 614PGP signatures for arbitrary text data. It doesn't do encryption, it doesn't 615manage keyrings, it doesn't verify signatures, it just signs things and checks 616signatures. It was written to support Usenet applications like control 617message generation and PGPMoose. 618 619There are two APIs, an object-oriented one and a legacy function API. The 620function API is configured with global variables and has other legacy warts. 621It will continue to be supported for backwards compatibility, but the 622object-oriented API is recommended for all new code. The object-oriented API 623was added in PGP::Sign 1.00. 624 625=head1 CLASS METHODS 626 627=over 4 628 629=item new(ARGS) 630 631Create a new PGP::Sign object. This should be used for all subsequent API 632calls. ARGS should be a hash reference with one or more of the following 633keys. 634 635=over 4 636 637=item home 638 639The GnuPG home directory containing keyrings and other configuration (as 640controlled with the B<--homedir> flag or the GNUPGHOME environment variable). 641If not set, uses the GnuPG default. This directory must contain keyrings with 642the secret keys used for signing and the public keys used for verification, 643and must be in the format expected by the GnuPG version used (see the C<style> 644parameter). 645 646=item munge 647 648If set to a true value, PGP::Sign will strip trailing spaces (only spaces, not 649arbitrary whitespace) when signing or verifying signatures. This will make 650the resulting signatures and verification compatible with programs that 651generate or verify cleartext signatures, since OpenPGP implementations ignore 652trailing spaces when generating or checking cleartext signatures. 653 654=item path 655 656The path to the GnuPG binary to use. If not set, PGP::Sign defaults to 657running B<gpg> (as found on the user's PATH) for a C<style> setting of "GPG" 658and B<gpg1> (as found on the user's PATH) for a C<style> setting of "GPG1". 659 660PGP::Sign does not support B<gpgv> (it passes options that it does not 661understand). This parameter should point to a full GnuPG implementation. 662 663=item style 664 665The style of OpenPGP backend to use, chosen from "GPG" for GnuPG v2 (the 666default) and "GPG1" for GnuPG v1. 667 668If set to "GPG1", PGP::Sign will pass the command-line flags for maximum 669backwards compatibility, including forcing v3 signatures instead of the 670current version. This is interoperable with PGP 2.6.2, at the cost of using 671deprecated protocols and cryptographic algorithms with known weaknesses. 672 673=item tmpdir 674 675The path to a temporary directory to use when verifying signatures. PGP::Sign 676has to write files to disk for signature verification and will do so in this 677directory. If not given, PGP::Sign will use File::Temp's default. 678 679=back 680 681=back 682 683=head1 INSTANCE METHODS 684 685=over 4 686 687=item sign(KEYID, PASSPHRASE, SOURCE[, SOURCE ...]) 688 689Create an OpenPGP signature over all the data contained in the SOURCE 690parameters, using KEYID to make the signature. PASSPHRASE is the passphrase 691for this private key. KEYID can be in any format accepted by GnuPG. 692 693The data given in the SOURCE parameters can be given in a wide variety of 694formats: scalar variables, arrays, references to scalars or arrays, globs or 695references to globs (assumed to be an open file), IO::File objects, or code 696references. 697 698If given a code reference, that function will be repeatedly called to obtain 699more data until it returns undef. This allows passing in an anonymous sub 700that transforms the data on the fly (escaping initial dashes, for instance) 701without having to make an in-memory copy. 702 703The returned signature is the ASCII-armored block with embedded newlines but 704with the marker lines and all headers stripped. 705 706PGP::Sign will always pass the B<--textmode> flag to GnuPG to force treatment 707of all input data as text and canonicalize line endings before generating the 708signature. If configured with the "GPG1" style, PGP::Sign will also pass the 709B<--force-v3-sigs> and B<--allow-weak-digest-algos> flags to allow use of old 710PGP keys and generate signatures that are compatible with old versions of PGP. 711 712On error, sign() will call croak(). 713 714=item verify(SIGNATURE, SOURCE[, SOURCE ...]) 715 716Verify a signature. PGP::Sign will attempt to verify the signature in 717detached mode. The signature must be in the same format as returned by 718sign(): an ASCII-armored block with embedded newlines but with the marker 719lines and all headers stripped. verify() accepts data sources in the SOURCE 720parameters in the same formats accepted by sign(). 721 722verify() returns the user ID of the signer, not the fingerprint or hex key ID. 723If the signature does not verify, verify() will return the empty string. For 724other errors, it will call croak(). 725 726As with sign(), PGP::Sign will always pass the B<--textmode> flag to GnuPG. 727It will also always pass B<--allow-weak-digest-algos> to allow verification 728of old signatures. 729 730=back 731 732=head1 FUNCTIONS 733 734The legacy function interface is supported for backwards compatibility with 735earlier versions of PGP::Sign. It is not recommended for any new code. 736Prefer the object-oriented API. 737 738pgp_sign() and pgp_verify() are exported by default. 739 740=over 4 741 742=item pgp_sign(KEYID, PASSPHRASE, SOURCE[, SOURCE ...]) 743 744Equivalent to creating a new PGP::Sign object and then calling its sign() 745method with the given parameters. The parameters to the object will be set 746based on the global variables described in L</VARIABLES>. The C<path> 747parameter will be set to $PGP::Sign::PGPS. 748 749When called in a scalar context, pgp_sign() returns the signature, the same as 750the sign() method. When called in an array context, pgp_sign() returns a 751two-item list. The second item is the fixed string "GnuPG". Historically, 752this was the version of the OpenPGP implementation, taken from the Version 753header of the signature, but this header is no longer set by GnuPG and had no 754practical use, so pgp_sign() now always returns that fixed value. 755 756On error, pgp_sign() returns undef or an empty list, depending on context. To 757get the corresponding errors, call pgp_error(). 758 759=item pgp_verify(SIGNATURE, VERSION, SOURCE[, SOURCE ...]) 760 761Equivalent to creating a new PGP::Sign object and then calling its verify() 762method with the SIGNATURE and SOURCE parameters. The parameters to the object 763will be set based on the global variables described in L</VARIABLES>. The 764C<path> parameter will be set to $PGP::Sign::PGPV. 765 766The VERSION parameter may be anything and is ignored. 767 768pgp_verify() returns the user ID of the signer (not the hex key ID or 769fingerprint) on success, an empty string if the signature is invalid, and 770undef on any other error. On error, pgp_sign() returns undef or an empty 771list, depending on context. To get the corresponding errors, call 772pgp_error(). 773 774=item pgp_error() 775 776Return the errors encountered by the last pgp_sign() or pgp_verify() call, or 777undef or the empty list depending on context if there were no error. A bad 778signature passed to pgp_verify() is not considered an error for this purpose. 779 780In an array context, a list of lines (including the ending newlines) is 781returned. In a scalar context, a string with embedded newlines is returned. 782 783This function is not exported by default and must be explicitly requested. 784 785=back 786 787=head1 VARIABLES 788 789The following variables control the behavior of the legacy function interface. 790They are not used for the object-oriented API, which replaces them with 791parameters to the new() class method. 792 793=over 4 794 795=item $PGP::Sign::MUNGE 796 797If set to a true value, PGP::Sign will strip trailing spaces (only spaces, not 798arbitrary whitespace) when signing or verifying signatures. This will make 799the resulting signatures and verification compatible with programs that 800generate or verify cleartext signatures, since OpenPGP implementations ignore 801trailing spaces when generating or checking cleartext signatures. 802 803=item $PGP::Sign::PGPPATH 804 805The GnuPG home directory containing keyrings and other configuration (as 806controlled with the B<--homedir> flag or the GNUPGHOME environment variable). 807If not set, uses the GnuPG default. This directory must contain keyrings with 808the secret keys used for signing and the public keys used for verification, 809and must be in the format expected by the GnuPG version used (see 810$PGP::Sign::PGPSTYLE). 811 812=item $PGP::Sign::PGPSTYLE 813 814What style of command line arguments and responses to expect from PGP. Must 815be either "GPG" for GnuPG v2 or "GPG1" for GnuPG v1. The default is "GPG". 816 817If set to "GPG1", PGP::Sign will pass the command-line flags for maximum 818backwards compatibility, including forcing v3 signatures instead of the 819current version. This is interoperable with PGP 2.6.2, at the cost of using 820deprecated protocols and cryptographic algorithms with known weaknesses. 821 822=item $PGP::Sign::PGPS 823 824The path to the program used by pgp_sign(). If not set, PGP::Sign defaults to 825running B<gpg> (as found on the user's PATH) if $PGP::Sign::PGPSTYLE is set to 826"GPG" and B<gpg1> (as found on the user's PATH) if $PGP::Sign::PGPSTYLE is set 827to "GPG1". 828 829=item $PGP::Sign::PGPV 830 831The path to the program used by pgp_verify(). If not set, PGP::Sign defaults 832to running B<gpg> (as found on the user's PATH) if $PGP::Sign::PGPSTYLE is set 833to "GPG" and B<gpg1> (as found on the user's PATH) if $PGP::Sign::PGPSTYLE is 834set to "GPG1". 835 836PGP::Sign does not support B<gpgv> (it passes options that it does not 837understand). This variable should point to a full GnuPG implementation. 838 839=item $PGP::Sign::TMPDIR 840 841The directory in which temporary files are created. Defaults to whatever 842directory File::Temp chooses to use by default. 843 844=back 845 846=head1 ENVIRONMENT 847 848All environment variables that GnuPG normally honors will be passed along to 849GnuPG and will likely have their expected effects. This includes GNUPGHOME, 850unless it is overridden by setting the C<path> parameter to the new() 851constructor or $PGP::Sign::PGPPATH for the legacy interface. 852 853=head1 DIAGNOSTICS 854 855Error messages thrown by croak() or (for the legacy interface) are mostly the 856output from GnuPG or from IPC::Run if it failed to run GnuPG. The exceptions 857are: 858 859=over 4 860 861=item Execution of %s failed with status %s 862 863GnuPG failed and returned the given status code. 864 865=item No signature returned by GnuPG 866 867We tried to generate a signature but, although GnuPG succeeded, the output 868didn't contain anything that looked like a signature. 869 870=item print failed: %s 871 872When writing out the data for signing or verification, print failed with the 873given error. 874 875=item Unknown OpenPGP backend style %s 876 877The parameter to the C<style> option of the new() constructor, or the setting 878of $PGP::Sign::PGPSTYLE, is not one of the recognized values. 879 880=back 881 882=head1 BUGS 883 884The verify() method returns a user ID, which is a poor choice and may be 885insecure unless used very carefully. PGP::Sign should support an option to 886return richer information about the signature verification, including the long 887hex key ID. 888 889PGP::Sign does not currently work with binary data, as it unconditionally 890forces text mode using the B<--textmode> option. 891 892There is no way to tell PGP::Sign to not allow unsafe digest algorithms when 893generating or verifying signatures. 894 895The whitespace munging support addresses the most common difference between 896cleartext and detached signatures, but does not deal with all of the escaping 897issues that are different between those two modes. It's likely that 898extracting a cleartext signature and verifying it with this module or using a 899signature from this module as a cleartext signature will not work in all 900cases. 901 902=head1 CAVEATS 903 904This module is fairly good at what it does, but it doesn't do very much. At 905one point, I had plans to provide more options and more configurability in the 906future, particularly the ability to handle binary data, that would probably 907mean API changes. I'm not sure at this point whether that will ever happen. 908 909=head1 AUTHOR 910 911Russ Allbery <rra@cpan.org> 912 913=head1 COPYRIGHT AND LICENSE 914 915Copyright 1997-2000, 2002, 2004, 2018, 2020 Russ Allbery <rra@cpan.org> 916 917This program is free software; you may redistribute it and/or modify it 918under the same terms as Perl itself. 919 920=head1 SEE ALSO 921 922gpg(1), gpg1(1), L<File::Temp> 923 924L<RFC 4880|https://tools.ietf.org/html/rfc4880>, which is the current 925specification for the OpenPGP message format. 926 927The current version of PGP::Sign is available from CPAN, or directly from its 928web site at L<https://www.eyrie.org/~eagle/software/pgp-sign/>. 929 930=cut 931 932# Local Variables: 933# copyright-at-end-flag: t 934# End: 935