chantra / rpms / dnf

Forked from rpms/dnf 2 years ago
Clone

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

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