Skip to contentSkip to conversation

sstate: use oe.gpg_sign for signing/verifying

PATCH New Markus Lehtonen 1 participant 6 messages Feb 10, 2016

lore
Share & tools
lore
#0 lore raw

cover sstate: use oe.gpg_sign for signing/verifying

This patchset modifies sstate.bbclass to utilize the recently added oe.gpg_sign library module. This unifies the code as now all gpg signing operations during the build are done with the help of this module. The first four patches add new features and refactor oe.gpg_sign in order to make it usable for sstate signing/verification. The fifth patch finally changes sstate.bbclass to use it.

[YOCTO #9006]

The following changes since commit cbdf4abde6d80b6123c7546d2b4c9c2a7f359ec7:

sign_package_feed.bbclass: fix task dependencies (2016-02-08 17:16:12 +0200)

are available in the git repository at:

git://git.openembedded.org/openembedded-core-contrib marquiz/sstate

for you to fetch changes up to 10ac62ab77a862a4efdcf68d20dd7331bfbc6f7a:

sstate.bbclass: use oe.gpg_sign for gpg signing (2016-02-10 16:02:18 +0200)

Markus Lehtonen (5):
oe/gpg_sign: add verify() method
oe/gpg_sign: add 'armor' argument to detach_sign() sign_rpm.bbclass: do not store key details in signer instance oe/gpg_sign: add 'passphrase' argument to detach_sign method sstate.bbclass: use oe.gpg_sign for gpg signing

 meta/classes/sign_rpm.bbclass          |  9 +++--
 meta/classes/sstate.bbclass            | 38 ++++++++++-----------
 meta/lib/oe/gpg_sign.py                | 60 ++++++++++++++++++++++------------
 meta/lib/oe/package_manager.py         |  9 +++--
 meta/recipes-core/meta/signing-keys.bb | 16 ++++-----
 5 files changed, 71 insertions(+), 61 deletions(-)
Signature · 1 line
2.6.2
#1 lore raw

PATCH 1/5 oe/gpg_sign: add verify() method

A new method for verifying detached signatures.

[YOCTO #9006]

---
 meta/lib/oe/gpg_sign.py | 10 ++++++++++
 1 file changed, 10 insertions(+)
meta/lib/oe/gpg_sign.py +10 -0
index 821787e..a4f310e 100644
@@ -65,6 +65,16 @@ class LocalSigner(object):
             raise bb.build.FuncFailed("Failed to create signature for '%s': %s" %
                                       (input_file, output))
 
+    def verify(self, sig_file):
+        """Verify signature"""
+        cmd = self.gpg_bin + " --verify "
+        if self.gpg_path:
+            cmd += "--homedir %s " % self.gpg_path
+        cmd += sig_file
+        status, _ = oe.utils.getstatusoutput(cmd)
+        ret = False if status else True
+        return ret
+
 
 def get_signer(d, backend, keyid, passphrase_file):
     """Get signer object for the specified backend"""
Signature · 1 line
2.6.2
#2 lore raw

PATCH 2/5 oe/gpg_sign: add 'armor' argument to detach_sign()

In reply to Markus Lehtonen

[YOCTO #9006]

---
 meta/lib/oe/gpg_sign.py | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
meta/lib/oe/gpg_sign.py +4 -2
index a4f310e..16a2364 100644
@@ -52,13 +52,15 @@ class LocalSigner(object):
             bb.error('rpmsign failed: %s' % proc.before.strip())
             raise bb.build.FuncFailed("Failed to sign RPM packages")
 
-    def detach_sign(self, input_file):
+    def detach_sign(self, input_file, armor=True):
         """Create a detached signature of a file"""
-        cmd = "%s --detach-sign --armor --batch --no-tty --yes " \
+        cmd = "%s --detach-sign --batch --no-tty --yes " \
                   "--passphrase-file '%s' -u '%s' " % \
                   (self.gpg_bin, self.passphrase_file, self.keyid)
         if self.gpg_path:
             cmd += "--homedir %s " % self.gpg_path
+        if armor:
+            cmd += "--armor "
         cmd += input_file
         status, output = oe.utils.getstatusoutput(cmd)
         if status:
Signature · 1 line
2.6.2
#3 lore raw

PATCH 3/5 sign_rpm.bbclass: do not store key details in signer instance

In reply to Markus Lehtonen

Refactor the LocalSigner class. Do not store keyid or passphrase file in the signer object as they are only needed for some of the methods. For example, the newly added verify() method does not need any key parameters and export_pubkey only uses keyid.

---
 meta/classes/sign_rpm.bbclass          |  9 ++++-----
 meta/lib/oe/gpg_sign.py                | 24 +++++++++++-------------
 meta/lib/oe/package_manager.py         |  9 ++++-----
 meta/recipes-core/meta/signing-keys.bb | 16 ++++++----------
 4 files changed, 25 insertions(+), 33 deletions(-)
meta/classes/sign_rpm.bbclass +4 -5
index 8bcabee..8b59bac 100644
@@ -36,13 +36,12 @@ python sign_rpm () {
     import glob
     from oe.gpg_sign import get_signer
 
-    signer = get_signer(d,
-                        d.getVar('RPM_GPG_BACKEND', True),
-                        d.getVar('RPM_GPG_NAME', True),
-                        d.getVar('RPM_GPG_PASSPHRASE_FILE', True))
+    signer = get_signer(d, d.getVar('RPM_GPG_BACKEND', True))
     rpms = glob.glob(d.getVar('RPM_PKGWRITEDIR', True) + '/*')
 
-    signer.sign_rpms(rpms)
+    signer.sign_rpms(rpms,
+                     d.getVar('RPM_GPG_NAME', True),
+                     d.getVar('RPM_GPG_PASSPHRASE_FILE', True))
 }
 
 do_package_index[depends] += "signing-keys:do_export_public_keys"
meta/lib/oe/gpg_sign.py +11 -13
index 16a2364..c4cadd6 100644
@@ -6,31 +6,29 @@ import oe.utils
 
 class LocalSigner(object):
     """Class for handling local (on the build host) signing"""
-    def __init__(self, d, keyid, passphrase_file):
-        self.keyid = keyid
-        self.passphrase_file = passphrase_file
+    def __init__(self, d):
         self.gpg_bin = d.getVar('GPG_BIN', True) or \
                   bb.utils.which(os.getenv('PATH'), 'gpg')
         self.gpg_path = d.getVar('GPG_PATH', True)
         self.rpm_bin = bb.utils.which(os.getenv('PATH'), "rpm")
 
-    def export_pubkey(self, output_file):
+    def export_pubkey(self, output_file, keyid):
         """Export GPG public key to a file"""
         cmd = '%s --batch --yes --export --armor -o %s ' % \
                 (self.gpg_bin, output_file)
         if self.gpg_path:
             cmd += "--homedir %s " % self.gpg_path
-        cmd += self.keyid
+        cmd += keyid
         status, output = oe.utils.getstatusoutput(cmd)
         if status:
             raise bb.build.FuncFailed('Failed to export gpg public key (%s): %s' %
-                                      (self.keyid, output))
+                                      (keyid, output))
 
-    def sign_rpms(self, files):
+    def sign_rpms(self, files, keyid, passphrase_file):
         """Sign RPM files"""
         import pexpect
 
-        cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % self.keyid
+        cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid
         if self.gpg_bin:
             cmd += "--define '%%__gpg %s' " % self.gpg_bin
         if self.gpg_path:
@@ -41,7 +39,7 @@ class LocalSigner(object):
         proc = pexpect.spawn(cmd)
         try:
             proc.expect_exact('Enter pass phrase:', timeout=15)
-            with open(self.passphrase_file) as fobj:
+            with open(passphrase_file) as fobj:
                 proc.sendline(fobj.readline().rstrip('\n'))
             proc.expect(pexpect.EOF, timeout=900)
             proc.close()
@@ -52,11 +50,11 @@ class LocalSigner(object):
             bb.error('rpmsign failed: %s' % proc.before.strip())
             raise bb.build.FuncFailed("Failed to sign RPM packages")
 
-    def detach_sign(self, input_file, armor=True):
+    def detach_sign(self, input_file, keyid, passphrase_file, armor=True):
         """Create a detached signature of a file"""
         cmd = "%s --detach-sign --batch --no-tty --yes " \
                   "--passphrase-file '%s' -u '%s' " % \
-                  (self.gpg_bin, self.passphrase_file, self.keyid)
+                  (self.gpg_bin, passphrase_file, keyid)
         if self.gpg_path:
             cmd += "--homedir %s " % self.gpg_path
         if armor:
@@ -78,11 +76,11 @@ class LocalSigner(object):
         return ret
 
 
-def get_signer(d, backend, keyid, passphrase_file):
+def get_signer(d, backend):
     """Get signer object for the specified backend"""
     # Use local signing by default
     if backend == 'local':
-        return LocalSigner(d, keyid, passphrase_file)
+        return LocalSigner(d)
     else:
         bb.fatal("Unsupported signing backend '%s'" % backend)
 
meta/lib/oe/package_manager.py +4 -5
index 26f6466..b30a4da 100644
@@ -110,10 +110,7 @@ class RpmIndexer(Indexer):
 
         rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo")
         if self.d.getVar('PACKAGE_FEED_SIGN', True) == '1':
-            signer = get_signer(self.d,
-                                self.d.getVar('PACKAGE_FEED_GPG_BACKEND', True),
-                                self.d.getVar('PACKAGE_FEED_GPG_NAME', True),
-                                self.d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE', True))
+            signer = get_signer(self.d, self.d.getVar('PACKAGE_FEED_GPG_BACKEND', True))
         else:
             signer = None
         index_cmds = []
@@ -144,7 +141,9 @@ class RpmIndexer(Indexer):
         # Sign repomd
         if signer:
             for repomd in repomd_files:
-                signer.detach_sign(repomd)
+                signer.detach_sign(repomd,
+                                   self.d.getVar('PACKAGE_FEED_GPG_NAME', True),
+                                   self.d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE', True))
         # Copy pubkey(s) to repo
         distro_version = self.d.getVar('DISTRO_VERSION', True) or "oe.0"
         if self.d.getVar('RPM_SIGN_PACKAGES', True) == '1':
meta/recipes-core/meta/signing-keys.bb +6 -10
index d7aa79d..d7763c6 100644
@@ -26,18 +26,14 @@ python do_export_public_keys () {
 
     if d.getVar("RPM_SIGN_PACKAGES", True):
         # Export public key of the rpm signing key
-        signer = get_signer(d,
-                            d.getVar('RPM_GPG_BACKEND', True),
-                            d.getVar('RPM_GPG_NAME', True),
-                            d.getVar('RPM_GPG_PASSPHRASE_FILE', True))
-        signer.export_pubkey(d.getVar('RPM_GPG_PUBKEY', True))
+        signer = get_signer(d, d.getVar('RPM_GPG_BACKEND', True))
+        signer.export_pubkey(d.getVar('RPM_GPG_PUBKEY', True),
+                             d.getVar('RPM_GPG_NAME', True))
 
     if d.getVar('PACKAGE_FEED_SIGN', True) == '1':
         # Export public key of the feed signing key
-        signer = get_signer(d,
-                            d.getVar('PACKAGE_FEED_GPG_BACKEND', True),
-                            d.getVar('PACKAGE_FEED_GPG_NAME', True),
-                            d.getVar('PACKAGE_FEED_GPG_PASSPHRASE_FILE', True))
-        signer.export_pubkey(d.getVar('PACKAGE_FEED_GPG_PUBKEY', True))
+        signer = get_signer(d, d.getVar('PACKAGE_FEED_GPG_BACKEND', True))
+        signer.export_pubkey(d.getVar('PACKAGE_FEED_GPG_PUBKEY', True),
+                             d.getVar('PACKAGE_FEED_GPG_NAME', True))
 }
 addtask do_export_public_keys before do_build
Signature · 1 line
2.6.2
#4 lore raw

PATCH 4/5 oe/gpg_sign: add 'passphrase' argument to detach_sign method

In reply to Markus Lehtonen

This allows directly giving the passphrase, instead of reading from a file.

[YOCTO #9006]

---
 meta/lib/oe/gpg_sign.py | 30 ++++++++++++++++++++----------
 1 file changed, 20 insertions(+), 10 deletions(-)
meta/lib/oe/gpg_sign.py +20 -10
index c4cadd6..ada1b2f 100644
@@ -50,20 +50,30 @@ class LocalSigner(object):
             bb.error('rpmsign failed: %s' % proc.before.strip())
             raise bb.build.FuncFailed("Failed to sign RPM packages")
 
-    def detach_sign(self, input_file, keyid, passphrase_file, armor=True):
+    def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True):
         """Create a detached signature of a file"""
-        cmd = "%s --detach-sign --batch --no-tty --yes " \
-                  "--passphrase-file '%s' -u '%s' " % \
-                  (self.gpg_bin, passphrase_file, keyid)
+        import subprocess
+
+        if passphrase_file and passphrase:
+            raise Exception("You should use either passphrase_file of passphrase, not both")
+
+        cmd = [self.gpg_bin, '--detach-sign', '--batch', '--no-tty', '--yes',
+               '-u', keyid]
+        if passphrase_file:
+            cmd += ['--passphrase-file', passphrase_file]
+        else:
+            cmd += ['--passphrase-fd', '0']
         if self.gpg_path:
-            cmd += "--homedir %s " % self.gpg_path
+            cmd += ['--homedir', self.gpg_path]
         if armor:
-            cmd += "--armor "
-        cmd += input_file
-        status, output = oe.utils.getstatusoutput(cmd)
-        if status:
+            cmd += ['--armor']
+        cmd.append(input_file)
+        job = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                               stderr=subprocess.PIPE)
+        _, stderr = job.communicate(passphrase)
+        if job.returncode:
             raise bb.build.FuncFailed("Failed to create signature for '%s': %s" %
-                                      (input_file, output))
+                                      (input_file, stderr))
 
     def verify(self, sig_file):
         """Verify signature"""
Signature · 1 line
2.6.2
#5 lore raw

PATCH 5/5 sstate.bbclass: use oe.gpg_sign for gpg signing

In reply to Markus Lehtonen

[YOCTO #9006]

---
 meta/classes/sstate.bbclass | 38 +++++++++++++++++---------------------
 1 file changed, 17 insertions(+), 21 deletions(-)
meta/classes/sstate.bbclass +17 -21
index 024b801..19fac32 100644
@@ -268,23 +268,10 @@ def sstate_install(ss, d):
 sstate_install[vardepsexclude] += "SSTATE_DUPWHITELIST STATE_MANMACH SSTATE_MANFILEPREFIX"
 sstate_install[vardeps] += "${SSTATEPOSTINSTFUNCS}"
 
-def sstate_build_gpg_command(d, *args, **kwargs):
-    # Returns a list for subprocess.call() unless passed flatten=True when this
-    # returns a flattened string.
-    l = [d.getVar("GPG_BIN", True) or "gpg"]
-    if d.getVar("GPG_PATH", True):
-        l += ["--homedir", d.getVar("GPG_PATH", True)]
-    l += args
-
-    if kwargs.get("flatten", False):
-        import pipes
-        return " ".join(map(pipes.quote, l))
-    else:
-        return l
-
 def sstate_installpkg(ss, d):
     import oe.path
     import subprocess
+    from oe.gpg_sign import get_signer
 
     def prepdir(dir):
         # remove dir if it exists, ensure any parent directories do exist
@@ -310,7 +297,8 @@ def sstate_installpkg(ss, d):
     d.setVar('SSTATE_PKG', sstatepkg)
 
     if bb.utils.to_boolean(d.getVar("SSTATE_VERIFY_SIG", True), False):
-        if subprocess.call(sstate_build_gpg_command(d, "--verify", sstatepkg + ".sig", sstatepkg)) != 0:
+        signer = get_signer(d, 'local')
+        if not signer.verify(sstatepkg + '.sig'):
             bb.warn("Cannot verify signature on sstate package %s" % sstatepkg)
 
     for f in (d.getVar('SSTATEPREINSTFUNCS', True) or '').split() + ['sstate_unpack_package'] + (d.getVar('SSTATEPOSTUNPACKFUNCS', True) or '').split():
@@ -585,7 +573,8 @@ def sstate_package(ss, d):
     d.setVar('SSTATE_BUILDDIR', sstatebuild)
     d.setVar('SSTATE_PKG', sstatepkg)
 
-    for f in (d.getVar('SSTATECREATEFUNCS', True) or '').split() + ['sstate_create_package'] + \
+    for f in (d.getVar('SSTATECREATEFUNCS', True) or '').split() + \
+             ['sstate_create_package', 'sstate_sign_package'] + \
              (d.getVar('SSTATEPOSTCREATEFUNCS', True) or '').split():
         # All hooks should run in SSTATE_BUILDDIR.
         bb.build.exec_func(f, d, (sstatebuild,))
@@ -689,15 +678,22 @@ sstate_create_package () {
 	chmod 0664 $TFILE
 	mv -f $TFILE ${SSTATE_PKG}
 
-	if [ -n "${SSTATE_SIG_KEY}" ]; then
-		rm -f ${SSTATE_PKG}.sig
-		echo ${SSTATE_SIG_PASSPHRASE} | ${@sstate_build_gpg_command(d, "--batch", "--passphrase-fd", "0", "--detach-sign", "--local-user", "${SSTATE_SIG_KEY}", "--output", "${SSTATE_PKG}.sig", "${SSTATE_PKG}", flatten=True)}
-	fi
-
 	cd ${WORKDIR}
 	rm -rf ${SSTATE_BUILDDIR}
 }
 
+python sstate_sign_package () {
+    from oe.gpg_sign import get_signer
+
+    if d.getVar('SSTATE_SIG_KEY', True):
+        signer = get_signer(d, 'local')
+        sstate_pkg = d.getVar('SSTATE_PKG', True)
+        if os.path.exists(sstate_pkg + '.sig'):
+            os.unlink(sstate_pkg + '.sig')
+        signer.detach_sign(sstate_pkg, d.getVar('SSTATE_SIG_KEY'), None,
+                           d.getVar('SSTATE_SIG_PASSPHRASE'), armor=False)
+}
+
 #
 # Shell function to decompress and prepare a package for installation
 # Will be run from within SSTATE_INSTDIR.
Signature · 1 line
2.6.2