Blame SOURCES/0004-Use-rpmkeys-alone-to-verify-signature.patch

239748
From a21880fbac479968546304beeeae3ed3bb899373 Mon Sep 17 00:00:00 2001
239748
From: Demi Marie Obenour <demi@invisiblethingslab.com>
239748
Date: Fri, 9 Apr 2021 13:03:03 -0400
239748
Subject: [PATCH] Use rpmkeys alone to verify signature
239748
239748
This avoids having to actually parse the package to check its signature,
239748
which reduces attack surface.  If the output of rpmkeys cannot be
239748
parsed, we assume the package is corrupt (the most likely cause).
239748
---
239748
 dnf/rpm/miscutils.py | 126 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------
239748
 1 file changed, 66 insertions(+), 60 deletions(-)
239748
239748
diff --git a/dnf/rpm/miscutils.py b/dnf/rpm/miscutils.py
239748
index 5f2621c..9d5b286 100644
239748
--- a/dnf/rpm/miscutils.py
239748
+++ b/dnf/rpm/miscutils.py
239748
@@ -13,90 +13,96 @@
239748
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
239748
 # Copyright 2003 Duke University
239748
 
239748
-from __future__ import print_function, absolute_import
239748
-from __future__ import unicode_literals
239748
+from __future__ import print_function, absolute_import, unicode_literals
239748
 
239748
-import rpm
239748
 import os
239748
 import subprocess
239748
 import logging
239748
-
239748
-from dnf.i18n import ucd
239748
-from dnf.i18n import _
239748
 from shutil import which
239748
 
239748
+from dnf.i18n import _
239748
 
239748
-logger = logging.getLogger('dnf')
239748
+_logger = logging.getLogger('dnf')
239748
+_rpmkeys_binary = None
239748
 
239748
+def _find_rpmkeys_binary():
239748
+    global _rpmkeys_binary
239748
+    if _rpmkeys_binary is None:
239748
+        _rpmkeys_binary = which("rpmkeys")
239748
+        _logger.debug(_('Using rpmkeys executable at %s to verify signatures'),
239748
+                      _rpmkeys_binary)
239748
+    return _rpmkeys_binary
239748
 
239748
-def _verifyPkgUsingRpmkeys(package, installroot, fdno):
239748
-    os.lseek(fdno, 0, os.SEEK_SET)
239748
-    rpmkeys_binary = '/usr/bin/rpmkeys'
239748
-    if not os.path.isfile(rpmkeys_binary):
239748
-        rpmkeys_binary = which("rpmkeys")
239748
-        logger.info(_('Using rpmkeys executable from {path} to verify signature for package: {package}.').format(
239748
-            path=rpmkeys_binary, package=package))
239748
+def _process_rpm_output(data):
239748
+    # No signatures or digests = corrupt package.
239748
+    # There is at least one line for -: and another (empty) entry after the
239748
+    # last newline.
239748
+    if len(data) < 3 or data[0] != b'-:' or data[-1]:
239748
+        return 2
239748
+    seen_sig, missing_key, not_trusted, not_signed = False, False, False, False
239748
+    for i in data[1:-1]:
239748
+        if b': BAD' in i:
239748
+            return 2
239748
+        elif i.endswith(b': NOKEY'):
239748
+            missing_key = True
239748
+        elif i.endswith(b': NOTTRUSTED'):
239748
+            not_trusted = True
239748
+        elif i.endswith(b': NOTFOUND'):
239748
+            not_signed = True
239748
+        elif not i.endswith(b': OK'):
239748
+            return 2
239748
+    if not_trusted:
239748
+        return 3
239748
+    elif missing_key:
239748
+        return 1
239748
+    elif not_signed:
239748
+        return 4
239748
+    # we still check return code, so this is safe
239748
+    return 0
239748
 
239748
-    if not os.path.isfile(rpmkeys_binary):
239748
-        logger.critical(_('Cannot find rpmkeys executable to verify signatures.'))
239748
-        return 0
239748
+def _verifyPackageUsingRpmkeys(package, installroot):
239748
+    rpmkeys_binary = _find_rpmkeys_binary()
239748
+    if rpmkeys_binary is None or not os.path.isfile(rpmkeys_binary):
239748
+        _logger.critical(_('Cannot find rpmkeys executable to verify signatures.'))
239748
+        return 2
239748
 
239748
-    args = ('rpmkeys', '--checksig', '--root', installroot, '--define', '_pkgverify_level all', '-')
239748
+    # "--define=_pkgverify_level all" enforces signature checking;
239748
+    # "--define=_pkgverify_flags 0x0" ensures that all signatures and digests
239748
+    # are checked.
239748
+    args = ('rpmkeys', '--checksig', '--root', installroot, '--verbose',
239748
+            '--define=_pkgverify_level all', '--define=_pkgverify_flags 0x0',
239748
+            '-')
239748
     with subprocess.Popen(
239748
             args=args,
239748
             executable=rpmkeys_binary,
239748
             env={'LC_ALL': 'C'},
239748
-            stdin=fdno,
239748
             stdout=subprocess.PIPE,
239748
-            cwd='/') as p:
239748
-        data, err = p.communicate()
239748
-    if p.returncode != 0 or data != b'-: digests signatures OK\n':
239748
-        return 0
239748
-    else:
239748
-        return 1
239748
+            cwd='/',
239748
+            stdin=package) as p:
239748
+        data = p.communicate()[0]
239748
+    returncode = p.returncode
239748
+    if type(returncode) is not int:
239748
+        raise AssertionError('Popen set return code to non-int')
239748
+    # rpmkeys can return something other than 0 or 1 in the case of a
239748
+    # fatal error (OOM, abort() called, SIGSEGV, etc)
239748
+    if returncode >= 2 or returncode < 0:
239748
+        return 2
239748
+    ret = _process_rpm_output(data.split(b'\n'))
239748
+    if ret:
239748
+        return ret
239748
+    return 2 if returncode else 0
239748
 
239748
 def checkSig(ts, package):
239748
     """Takes a transaction set and a package, check it's sigs,
239748
     return 0 if they are all fine
239748
     return 1 if the gpg key can't be found
239748
     return 2 if the header is in someway damaged
239748
     return 3 if the key is not trusted
239748
     return 4 if the pkg is not gpg or pgp signed"""
239748
 
239748
-    value = 4
239748
-    currentflags = ts.setVSFlags(0)
239748
-    fdno = os.open(package, os.O_RDONLY)
239748
+    fdno = os.open(package, os.O_RDONLY|os.O_NOCTTY|os.O_CLOEXEC)
239748
     try:
239748
-        hdr = ts.hdrFromFdno(fdno)
239748
-    except rpm.error as e:
239748
-        if str(e) == "public key not available":
239748
-            value = 1
239748
-        elif str(e) == "public key not trusted":
239748
-            value = 3
239748
-        elif str(e) == "error reading package header":
239748
-            value = 2
239748
-        else:
239748
-            raise ValueError('Unexpected error value %r from ts.hdrFromFdno when checking signature.' % str(e))
239748
-    else:
239748
-        # checks signature from an hdr
239748
-        string = '%|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:' \
239748
-                 '{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|'
239748
-        try:
239748
-            siginfo = hdr.sprintf(string)
239748
-            siginfo = ucd(siginfo)
239748
-
239748
-            if siginfo == '(none)':
239748
-                value = 4
239748
-            elif "Key ID" in siginfo and _verifyPkgUsingRpmkeys(package, ts.ts.rootDir, fdno):
239748
-                value = 0
239748
-            else:
239748
-                raise ValueError('Unexpected return value %r from hdr.sprintf when checking signature.' % siginfo)
239748
-        except UnicodeDecodeError:
239748
-            pass
239748
-
239748
-        del hdr
239748
-
239748
-    os.close(fdno)
239748
-
239748
-    ts.setVSFlags(currentflags)  # put things back like they were before
239748
+        value = _verifyPackageUsingRpmkeys(fdno, ts.ts.rootDir)
239748
+    finally:
239748
+        os.close(fdno)
239748
     return value
239748
--
239748
libgit2 1.0.1
239748