[PATCH 7/20] Use BlockDev's crypto plugin instead of devicelibs/crypto.py

vpodzime installerbot-noreply at redhat.com
Fri Feb 27 15:31:52 UTC 2015


From: Vratislav Podzimek <vpodzime at redhat.com>

---
 blivet/devicelibs/crypto.py | 144 --------------------------------------------
 blivet/devicetree.py        |   6 +-
 blivet/errors.py            |   3 -
 blivet/formats/luks.py      |  49 ++++++++-------
 blivet/osinstall.py         |   4 +-
 5 files changed, 31 insertions(+), 175 deletions(-)

diff --git a/blivet/devicelibs/crypto.py b/blivet/devicelibs/crypto.py
index 13a6282..5fc867d 100644
--- a/blivet/devicelibs/crypto.py
+++ b/blivet/devicelibs/crypto.py
@@ -20,151 +20,7 @@
 #            Martin Sivak <msivak at redhat.com>
 #
 
-import random
-import time
-from pycryptsetup import CryptSetup
-
-from ..errors import CryptoError
 from ..size import Size
-from ..util import get_current_entropy
 
 LUKS_METADATA_SIZE = Size("2 MiB")
 MIN_CREATE_ENTROPY = 256 # bits
-
-# Keep the character set size a power of two to make sure all characters are
-# equally likely
-GENERATED_PASSPHRASE_CHARSET = ("0123456789"
-                                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-                                "abcdefghijklmnopqrstuvwxyz"
-                                "./")
-# 20 chars * 6 bits per char = 120 "bits of security"
-GENERATED_PASSPHRASE_LENGTH = 20
-
-def generateBackupPassphrase():
-    raw = [random.choice(GENERATED_PASSPHRASE_CHARSET) for _ in range(GENERATED_PASSPHRASE_LENGTH)]
-
-    # Insert a '-' after every five char chunk for easier reading
-    parts = []
-    for i in range(0, GENERATED_PASSPHRASE_LENGTH, 5):
-        parts.append(''.join(raw[i : i + 5]))
-    return "-".join(parts)
-
-yesDialog = lambda q: True
-logFunc = lambda p, t: None
-passwordDialog = lambda t: None
-
-def is_luks(device):
-    cs = CryptSetup(device=device, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-    return cs.isLuks()
-
-def luks_uuid(device):
-    cs = CryptSetup(device=device, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-    return cs.luksUUID()
-
-def luks_status(name):
-    """True means active, False means inactive (or non-existent)"""
-    cs = CryptSetup(name=name, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-    return cs.status()
-
-def luks_format(device,
-                passphrase=None,
-                cipher=None, key_size=None, key_file=None,
-                min_entropy=0):
-    """
-    Format device as LUKS with the specified parameters.
-
-    :param str device: device to format
-    :param str passphrase: passphrase to add to the new LUKS device
-    :param str cipher: cipher mode to use
-    :param int keysize: keysize to use
-    :param str key_file: key file to use
-    :param int min_entropy: minimum random data entropy level required for LUKS
-                            format creation (0 means entropy level is not checked)
-
-    note::
-              If some minimum entropy is required (min_entropy > 0), the
-              function waits for enough entropy to be gathered by the kernel
-              which may potentially take very long time or even forever.
-    """
-
-    # pylint: disable=unused-argument
-    if not passphrase:
-        raise ValueError("luks_format requires passphrase")
-
-    cs = CryptSetup(device=device, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-
-    #None is not considered as default value and pycryptsetup doesn't accept it
-    #so we need to filter out all Nones
-    kwargs = {}
-
-    # Split cipher designator to cipher name and cipher mode
-    cipherType = None
-    cipherMode = None
-    if cipher:
-        cparts = cipher.split("-")
-        cipherType = "".join(cparts[0:1])
-        cipherMode = "-".join(cparts[1:])
-
-    if cipherType: kwargs["cipher"]  = cipherType
-    if cipherMode: kwargs["cipherMode"]  = cipherMode
-    if   key_size: kwargs["keysize"]  = key_size
-
-    if min_entropy > 0:
-        # min_entropy == 0 means "don't care"
-        while get_current_entropy() < min_entropy:
-            # wait for entropy to become high enough
-            time.sleep(1)
-
-    rc = cs.luksFormat(**kwargs)
-    if rc:
-        raise CryptoError("luks_format failed for '%s'" % device)
-
-    # activate first keyslot
-    cs.addKeyByVolumeKey(newPassphrase=passphrase)
-    if rc:
-        raise CryptoError("luks_add_key_by_volume_key failed for '%s'" % device)
-
-
-def luks_open(device, name, passphrase=None, key_file=None):
-    # pylint: disable=unused-argument
-    if not passphrase:
-        raise ValueError("luks_format requires passphrase")
-
-    cs = CryptSetup(device=device, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-
-    rc = cs.activate(passphrase=passphrase, name=name)
-    if rc<0:
-        raise CryptoError("luks_open failed for %s (%s) with errno %d" % (device, name, rc))
-
-def luks_close(name):
-    cs = CryptSetup(name=name, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-    rc = cs.deactivate()
-
-    if rc:
-        raise CryptoError("luks_close failed for %s" % name)
-
-def luks_add_key(device,
-                 new_passphrase=None,
-                 passphrase=None, key_file=None):
-    # pylint: disable=unused-argument
-    if not passphrase:
-        raise ValueError("luks_add_key requires passphrase")
-
-    cs = CryptSetup(device=device, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-    rc = cs.addKeyByPassphrase(passphrase=passphrase, newPassphrase=new_passphrase)
-
-    if rc<0:
-        raise CryptoError("luks add key failed with errcode %d" % (rc,))
-
-def luks_remove_key(device,
-                    del_passphrase=None,
-                    passphrase=None, key_file=None):
-    # pylint: disable=unused-argument
-    if not passphrase:
-        raise ValueError("luks_remove_key requires passphrase")
-
-    cs = CryptSetup(device=device, yesDialog=yesDialog, logFunc=logFunc, passwordDialog=passwordDialog)
-    rc = cs.removePassphrase(passphrase = passphrase)
-
-    if rc:
-        raise CryptoError("luks remove key failed with errcode %d" % (rc,))
diff --git a/blivet/devicetree.py b/blivet/devicetree.py
index 2960985..76cc7d4 100644
--- a/blivet/devicetree.py
+++ b/blivet/devicetree.py
@@ -30,7 +30,7 @@
 from gi.repository import BlockDev as blockdev
 from gi.repository import GLib
 
-from .errors import CryptoError, DeviceError, DeviceTreeError, DiskLabelCommitError, DMError, FSError, InvalidDiskLabelError, LUKSError, StorageError, UnusableConfigurationError
+from .errors import DeviceError, DeviceTreeError, DiskLabelCommitError, DMError, FSError, InvalidDiskLabelError, LUKSError, StorageError, UnusableConfigurationError
 from .devices import BTRFSDevice, BTRFSSubVolumeDevice, BTRFSVolumeDevice, BTRFSSnapShotDevice
 from .devices import DASDDevice, DMDevice, DMLinearDevice, DMRaidArrayDevice, DiskDevice
 from .devices import FcoeDiskDevice, FileDevice, LoopDevice, LUKSDevice
@@ -1340,7 +1340,7 @@ def handleUdevLUKSFormat(self, info, device):
                     device.format.passphrase = passphrase
                     try:
                         device.format.setup()
-                    except CryptoError:
+                    except GLib.GError:
                         device.format.passphrase = None
                     else:
                         break
@@ -1350,7 +1350,7 @@ def handleUdevLUKSFormat(self, info, device):
                                      exists=True)
             try:
                 luks_device.setup()
-            except (LUKSError, CryptoError, DeviceError) as e:
+            except (LUKSError, GLib.GError, DeviceError) as e:
                 log.info("setup of %s failed: %s", device.format.mapName, e)
                 device.removeChild()
             else:
diff --git a/blivet/errors.py b/blivet/errors.py
index 36b1a78..c6d64a7 100644
--- a/blivet/errors.py
+++ b/blivet/errors.py
@@ -114,9 +114,6 @@ class DMError(StorageError):
 class LVMError(StorageError):
     pass
 
-class CryptoError(StorageError):
-    pass
-
 class MPathError(StorageError):
     pass
 
diff --git a/blivet/formats/luks.py b/blivet/formats/luks.py
index 03af88f..dcb6da5 100644
--- a/blivet/formats/luks.py
+++ b/blivet/formats/luks.py
@@ -20,9 +20,8 @@
 # Red Hat Author(s): Dave Lehman <dlehman at redhat.com>
 #
 
-
-
 import os
+from gi.repository import BlockDev as blockdev
 
 try:
     import volume_key
@@ -188,9 +187,9 @@ def setup(self, **kwargs):
             return
 
         DeviceFormat.setup(self, **kwargs)
-        crypto.luks_open(self.device, self.mapName,
-                       passphrase=self.__passphrase,
-                       key_file=self._key_file)
+        blockdev.crypto_luks_open(self.device, self.mapName,
+                                  passphrase=self.__passphrase,
+                                  key_file=self._key_file)
 
     def teardown(self):
         """ Close, or tear down, the format. """
@@ -201,7 +200,7 @@ def teardown(self):
 
         if self.status:
             log.debug("unmapping %s", self.mapName)
-            crypto.luks_close(self.mapName)
+            blockdev.crypto_luks_close(self.mapName)
 
     def create(self, **kwargs):
         """ Write the formatting to the specified block device.
@@ -223,17 +222,17 @@ def create(self, **kwargs):
 
         try:
             DeviceFormat.create(self, **kwargs)
-            crypto.luks_format(self.device,
-                             passphrase=self.__passphrase,
-                             key_file=self._key_file,
-                             cipher=self.cipher,
-                             key_size=self.key_size,
-                             min_entropy=self.min_luks_entropy)
+            blockdev.crypto_luks_format(self.device,
+                                        passphrase=self.__passphrase,
+                                        key_file=self._key_file,
+                                        cipher=self.cipher,
+                                        key_size=self.key_size,
+                                        min_entropy=self.min_luks_entropy)
 
         except Exception:
             raise
         else:
-            self.uuid = crypto.luks_uuid(self.device)
+            self.uuid = blockdev.crypto_luks_uuid(self.device)
             self.exists = True
             if flags.installer_mode:
                 self.mapName = "luks-%s" % self.uuid
@@ -267,22 +266,26 @@ def addPassphrase(self, passphrase):
         if not self.exists:
             raise LUKSError("format has not been created")
 
-        crypto.luks_add_key(self.device,
-                          passphrase=self.__passphrase,
-                          key_file=self._key_file,
-                          new_passphrase=passphrase)
+        blockdev.crypto_luks_add_key(self.device,
+                                     pass_=self.__passphrase,
+                                     key_file=self._key_file,
+                                     new_passphrase=passphrase)
+
+    def removePassphrase(self):
+        """
+        Remove the saved passphrase (and possibly key file) from the LUKS
+        header.
+
+        """
 
-    def removePassphrase(self, passphrase):
-        """ Remove the specified passphrase from the LUKS header. """
         log_method_call(self, device=self.device,
                         type=self.type, status=self.status)
         if not self.exists:
             raise LUKSError("format has not been created")
 
-        crypto.luks_remove_key(self.device,
-                             passphrase=self.__passphrase,
-                             key_file=self._key_file,
-                             del_passphrase=passphrase)
+        blockdev.crypto_luks_remove_key(self.device,
+                                        passphrase=self.__passphrase,
+                                        key_file=self._key_file)
 
     def _escrowVolumeIdent(self, vol):
         """ Return an escrow packet filename prefix for a volume_key.Volume. """
diff --git a/blivet/osinstall.py b/blivet/osinstall.py
index 8d4fc63..02dca1e 100644
--- a/blivet/osinstall.py
+++ b/blivet/osinstall.py
@@ -24,6 +24,7 @@
 import os
 import stat
 import time
+from gi.repository import BlockDev as blockdev
 
 from . import util
 from . import getSysroot, getTargetPhysicalRoot, errorHandler, ERROR_RAISE
@@ -33,7 +34,6 @@
 from .errors import FSTabTypeMismatchError, UnrecognizedFSTabEntryError, StorageError, FSResizeError, UnknownSourceDeviceError
 from .formats import get_device_format_class
 from .devicelibs.dm import name_from_dm_node
-from .devicelibs.crypto import generateBackupPassphrase
 from .formats import getFormat
 from .flags import flags
 from .platform import platform as _platform
@@ -1089,7 +1089,7 @@ def writeEscrowPackets(storage):
 
     nss.nss.nss_init_nodb() # Does nothing if NSS is already initialized
 
-    backupPassphrase = generateBackupPassphrase()
+    backupPassphrase = blockdev.crypto_generate_backup_passphrase()
 
     try:
         escrowDir = getSysroot() + "/root"


-- 
To view this commit on github, visit https://github.com/rhinstaller/blivet/commit/c42b5640cc731f8f2593469fb2086ade981d6154


More information about the anaconda-patches mailing list