<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># Copyright Â© 2007, 2022 Guillem Jover &lt;guillem@debian.org&gt;
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see &lt;https://www.gnu.org/licenses/&gt;.

=encoding utf8

=head1 NAME

Dpkg::OpenPGP::Backend::GnuPG - OpenPGP backend for GnuPG

=head1 DESCRIPTION

This module provides a class that implements the OpenPGP backend
for GnuPG.

B&lt;Note&gt;: This is a private module, its API can change at any time.

=cut

package Dpkg::OpenPGP::Backend::GnuPG 0.01;

use strict;
use warnings;

use POSIX qw(:sys_wait_h);
use File::Temp;
use MIME::Base64;

use Dpkg::ErrorHandling;
use Dpkg::IPC;
use Dpkg::File;
use Dpkg::Path qw(find_command);
use Dpkg::OpenPGP::ErrorCodes;

use parent qw(Dpkg::OpenPGP::Backend);

sub DEFAULT_CMDV {
    return [ qw(gpgv-sq gpgv) ];
}

sub DEFAULT_CMDSTORE {
    return [ qw(gpg-agent) ];
}

sub DEFAULT_CMD {
    return [ qw(gpg-sq gpg) ];
}

sub has_backend_cmd {
    my $self = shift;

    return defined $self-&gt;{cmd} &amp;&amp; defined $self-&gt;{cmdstore};
}

sub has_keystore {
    my $self = shift;

    return 0 if not defined $self-&gt;{cmdstore};
    return 1 if ($ENV{GNUPGHOME} &amp;&amp; -e $ENV{GNUPGHOME}) ||
                ($ENV{HOME} &amp;&amp; -e "$ENV{HOME}/.gnupg");
    return 0;
}

sub can_use_key {
    my ($self, $key) = @_;

    # With gpg, a secret key always requires gpg-agent (the key store).
    return $self-&gt;has_keystore();
}

sub has_verify_cmd {
    my $self = shift;

    return defined $self-&gt;{cmdv} || defined $self-&gt;{cmd};
}

sub get_trusted_keyrings {
    my $self = shift;

    my $keystore;
    if ($ENV{GNUPGHOME} &amp;&amp; -e $ENV{GNUPGHOME}) {
        $keystore = $ENV{GNUPGHOME};
    } elsif ($ENV{HOME} &amp;&amp; -e "$ENV{HOME}/.gnupg") {
        $keystore = "$ENV{HOME}/.gnupg";
    } else {
        return;
    }

    my @keyrings;
    foreach my $keyring (qw(trustedkeys.kbx trustedkeys.gpg)) {
        push @keyrings, "$keystore/$keyring" if -r "$keystore/$keyring";
    }
    return @keyrings;
}

# _pgp_* functions are strictly for applying or removing ASCII armor.
# See &lt;https://datatracker.ietf.org/doc/html/rfc4880#section-6&gt; for more
# details.
#
# Note that these _pgp_* functions are only necessary while relying on
# gpgv, and gpgv itself does not verify multiple signatures correctly
# (see https://bugs.debian.org/1010955).

sub _pgp_dearmor_data {
    my ($type, $data) = @_;

    # Note that we ignore an incorrect or absent checksum, following the
    # guidance of
    # &lt;https://datatracker.ietf.org/doc/draft-ietf-openpgp-crypto-refresh/&gt;.
    my $armor_regex = qr{
        -----BEGIN\ PGP\ \Q$type\E-----[\r\t ]*\n
        (?:[^:]+:\ [^\n]*[\r\t ]*\n)*
        [\r\t ]*\n
        ([a-zA-Z0-9/+\n]+={0,2})[\r\t ]*\n
        (?:=[a-zA-Z0-9/+]{4}[\r\t ]*\n)?
        -----END\ PGP\ \Q$type\E-----
    }xm;

    if ($data =~ m/$armor_regex/) {
        return decode_base64($1);
    }
    return;
}

sub _pgp_armor_checksum {
    my ($data) = @_;

    # From the upcoming revision to RFC 4880
    # &lt;https://datatracker.ietf.org/doc/draft-ietf-openpgp-crypto-refresh/&gt;.
    #
    # The resulting three-octet-wide value then gets base64-encoded into
    # four base64 ASCII characters.

    my $CRC24_INIT = 0xB704CE;
    my $CRC24_GENERATOR = 0x864CFB;

    my @bytes = unpack 'C*', $data;
    my $crc = $CRC24_INIT;
    for my $b (@bytes) {
        $crc ^= ($b &lt;&lt; 16);
        for (1 .. 8) {
            $crc &lt;&lt;= 1;
            if ($crc &amp; 0x1000000) {
                # Clear bit 25 to avoid overflow.
                $crc &amp;= 0xffffff;
                $crc ^= $CRC24_GENERATOR;
            }
        }
    }
    my $sum = pack 'CCC', ($crc &gt;&gt; 16) &amp; 0xff, ($crc &gt;&gt; 8) &amp; 0xff, $crc &amp; 0xff;
    return encode_base64($sum, q{});
}

sub _pgp_armor_data {
    my ($type, $data) = @_;

    my $out = encode_base64($data, q{}) =~ s/(.{1,64})/$1\n/gr;
    chomp $out;
    my $crc = _pgp_armor_checksum($data);
    my $armor = &lt;&lt;~"ARMOR";
        -----BEGIN PGP $type-----

        $out
        =$crc
        -----END PGP $type-----
        ARMOR
    return $armor;
}

sub armor {
    my ($self, $type, $in, $out) = @_;

    my $raw_data = file_slurp($in);
    my $data = _pgp_dearmor_data($type, $raw_data) // $raw_data;
    my $armor = _pgp_armor_data($type, $data);
    return OPENPGP_BAD_DATA unless defined $armor;
    file_dump($out, $armor);

    return OPENPGP_OK;
}

sub dearmor {
    my ($self, $type, $in, $out) = @_;

    my $armor = file_slurp($in);
    my $data = _pgp_dearmor_data($type, $armor);
    return OPENPGP_BAD_DATA unless defined $data;
    file_dump($out, $data);

    return OPENPGP_OK;
}

sub _gpg_exec
{
    my ($self, @exec) = @_;

    my ($stdout, $stderr);
    spawn(exec =&gt; \@exec, wait_child =&gt; 1, nocheck =&gt; 1, timeout =&gt; 10,
          to_string =&gt; \$stdout, error_to_string =&gt; \$stderr);
    if (WIFEXITED($?)) {
        my $status = WEXITSTATUS($?);
        print { *STDERR } "$stdout$stderr" if $status;
        return $status;
    } else {
        subprocerr("@exec");
    }
}

sub _gpg_options_weak_digests {
    my @gpg_weak_digests = map {
        (qw(--weak-digest), $_)
    } qw(SHA1 RIPEMD160);

    return @gpg_weak_digests;
}

sub _gpg_verify {
    my ($self, $signeddata, $sig, $data, @certs) = @_;

    return OPENPGP_MISSING_CMD if ! $self-&gt;has_verify_cmd();

    my $gpg_home = File::Temp-&gt;newdir('dpkg-gpg-verify.XXXXXXXX', TMPDIR =&gt; 1);
    my @cmd_opts = qw(--no-options --no-default-keyring --batch --quiet);
    my @gpg_opts;
    push @gpg_opts, _gpg_options_weak_digests();
    push @gpg_opts, '--homedir', $gpg_home;
    push @cmd_opts, @gpg_opts;

    my @exec;
    if ($self-&gt;{cmdv}) {
        push @exec, $self-&gt;{cmdv};
        push @exec, @gpg_opts;
        # We need to touch the trustedkeys.gpg keyring, otherwise gpgv will
        # emit an error about the trustedkeys.kbx file being of unknown type.
        file_touch("$gpg_home/trustedkeys.gpg");
    } else {
        push @exec, $self-&gt;{cmd};
        push @exec, @cmd_opts;
    }
    foreach my $cert (@certs) {
        my $certring = File::Temp-&gt;new(UNLINK =&gt; 1, SUFFIX =&gt; '.pgp');
        my $rc;
        # XXX: The internal dearmor() does not handle concatenated ASCII Armor,
        # but the old implementation handled such certificate keyrings, so to
        # avoid regressing for now, we fallback to use the GnuPG dearmor.
        if ($cert =~ m{\.kbx$}) {
            # Accept GnuPG apparent keybox-format keyrings as-is.
            $rc = 1;
        } elsif (defined $self-&gt;{cmd}) {
            $rc = $self-&gt;_gpg_exec($self-&gt;{cmd}, @cmd_opts, '--yes',
                                          '--output', $certring,
                                          '--dearmor', $cert);
        } else {
            $rc = $self-&gt;dearmor('PUBLIC KEY BLOCK', $cert, $certring);
        }
        $certring = $cert if $rc;
        push @exec, '--keyring', $certring;
    }
    push @exec, '--output', $data if defined $data;
    if (! $self-&gt;{cmdv}) {
        push @exec, '--verify';
    }
    push @exec, $sig if defined $sig;
    push @exec, $signeddata;

    my $rc = $self-&gt;_gpg_exec(@exec);
    return OPENPGP_NO_SIG if $rc;
    return OPENPGP_OK;
}

sub inline_verify {
    my ($self, $inlinesigned, $data, @certs) = @_;

    return $self-&gt;_gpg_verify($inlinesigned, undef, $data, @certs);
}

sub verify {
    my ($self, $data, $sig, @certs) = @_;

    return $self-&gt;_gpg_verify($data, $sig, undef, @certs);
}

sub inline_sign {
    my ($self, $data, $inlinesigned, $key) = @_;

    return OPENPGP_MISSING_CMD if ! $self-&gt;has_backend_cmd();

    my @exec = ($self-&gt;{cmd});
    push @exec, _gpg_options_weak_digests();
    push @exec, qw(--utf8-strings --textmode --armor);
    # Set conformance level.
    push @exec, '--openpgp';
    # Set secure algorithm preferences.
    push @exec, '--personal-digest-preferences', 'SHA512 SHA384 SHA256 SHA224';
    if ($key-&gt;type eq 'keyfile') {
        # Promote the keyfile keyhandle to a keystore, this way we share the
        # same gpg-agent and can get any password cached.
        my $gpg_home = File::Temp-&gt;newdir('dpkg-sign.XXXXXXXX', TMPDIR =&gt; 1);

        push @exec, '--homedir', $gpg_home;
        $self-&gt;_gpg_exec(@exec, qw(--quiet --no-tty --batch --import), $key-&gt;handle);
        $key-&gt;set('keystore', $gpg_home);
    } elsif ($key-&gt;type eq 'keystore') {
        push @exec, '--homedir', $key-&gt;handle;
    } else {
        push @exec, '--local-user', $key-&gt;handle;
    }
    push @exec, '--output', $inlinesigned;

    my $rc = $self-&gt;_gpg_exec(@exec, '--clearsign', $data);
    return OPENPGP_CMD_CANNOT_SIGN if $rc;
    return OPENPGP_OK;
}

=head1 CHANGES

=head2 Version 0.xx

This is a private module.

=cut

1;
</pre></body></html>