Exemplo n.º 1
0
 def test_get_con_config_exception(self):
     """
     Test get_con_config() if nmcli returns error code != 10.
     It should raise an exception (CommandException).
     """
     con_name = ["bogus-uuid"]
     self.mock_run_command.side_effect = CommandException(
         err=["Error: bogus-uuid - no such connection profile.", ""],
         cmd=["/usr/bin/nmcli", "c", "show", "bogus-uuid"],
         out=[""],
         rc=1,
     )
     with self.assertRaises(CommandException):
         get_con_config(con_name)
Exemplo n.º 2
0
 def test_get_dev_config_exception(self):
     """
     Test get_dev_config() if nmcli returns error code != 10.
     It should raise an exception (CommandException).
     """
     dev_name = ["vethXX"]
     self.mock_run_command.side_effect = CommandException(
         err=["Error: Device 'vethXX' not found.", ""],
         cmd=["/usr/bin/nmcli", "d", "show", "vethXX"],
         out=[""],
         rc=1,
     )
     with self.assertRaises(CommandException):
         get_dev_config(dev_name)
Exemplo n.º 3
0
 def test_domain_workgroup_invalid(self):
     """
     Test domain_workgroup() if AD domain can't be reached.
     It should raise a CommandException.
     """
     domain = "bogusad.bogusdomain.com"
     self.mock_run_command.side_effect = CommandException(
         err=["Didn't find the cldap server!", ""],
         cmd=["/usr/bin/net", "ads", "workgroup", "-S", domain],
         out=[""],
         rc=255,
     )
     with self.assertRaises(CommandException):
         domain_workgroup(domain)
Exemplo n.º 4
0
 def test_get_con_config_con_not_found(self):
     """
     Test get_con_config() if connection is not found / vanished.
     It should return an empty dict.
     """
     con_name = ["bogus-uuid"]
     expected_result = {}
     self.mock_run_command.side_effect = CommandException(
         err=["Error: bogus-uuid - no such connection profile.", ""],
         cmd=["/usr/bin/nmcli", "c", "show", "bogus-uuid"],
         out=[""],
         rc=10,
     )
     returned = get_dev_config(con_name)
     self.assertEqual(
         returned,
         expected_result,
         msg="Un-expected get_con_config() result:\n "
         "returned = ({}).\n "
         "expected = ({}).\n "
         "for con_name: {}".format(returned, expected_result, con_name),
     )
Exemplo n.º 5
0
 def test_get_dev_config_dev_not_found(self):
     """
     Test get_dev_config() if device is not found / vanished.
     It should return an empty dict.
     """
     dev_name = ["vethXX"]
     expected_result = {}
     self.mock_run_command.side_effect = CommandException(
         err=["Error: Device 'vethXX' not found.", ""],
         cmd=["/usr/bin/nmcli", "d", "show", "vethXX"],
         out=[""],
         rc=10,
     )
     returned = get_dev_config(dev_name)
     self.assertEqual(
         returned,
         expected_result,
         msg="Un-expected get_dev_config() result:\n "
         "returned = ({}).\n "
         "expected = ({}).\n "
         "for dev_name: {}".format(returned, expected_result, dev_name),
     )
Exemplo n.º 6
0
def establish_keyfile(dev_byid, keyfile_withpath, passphrase):
    """
    Ensures that the given keyfile_withpath exists and calls create_keyfile()
    if it doesn't. Then attempts to register the established keyfile with the
    dev_byid device via "cryptsetup luksAddKey dev keyfile passphrase". But
    only if the passphrase is found to not equal '', flag for skip luksAddKey.
    N.B. The passphrase is passed to the command via a secure temporary file.
    Care is taken to remove this file irrespective of outcome.
    An existing keyfile will not be altered or deleted but a freshly created
    keyfile will be removed if our 'cryptsetup luksAddKey' returns non zero.
    :param dev_byid: by-id type name without path as found in db Disks.name.
    :param keyfile_withpath: the intended keyfile with full path.
    :param passphrase: LUKS passphrase: any current key slot passphrase. If
    an empty passphrase is passed then 'cryptsetup luksAddKey' is skipped.
    :return: True if keyfile successfully registered. False or an Exception 
    is raised in all other instances.
    """
    fresh_keyfile = False  # Until we find otherwise.
    # First we establish if our keyfile exists, and if not we create it.
    if not os.path.isfile(keyfile_withpath):
        # attempt to create our keyfile:
        if not create_keyfile(keyfile_withpath):
            # msg = ('Failed to establish new or existing keyfile: %s: %s' %
            #        (keyfile_withpath, e.__str__()))
            # raise Exception(msg)
            return False
        fresh_keyfile = True
    # We are by now assured of an existing keyfile_withpath.
    # Only register this keyfile with our LUKS container if needed:
    if passphrase == '':
        # If an empty passphrase was passed then we interpret this as a flag
        # to indicate no requirement to 'cryptsetup luksAddKey' so we are now
        # done. Use case is the return to "auto unlock via keyfile" when that
        # keyfile has already been registered. UI will not ask for passphrase
        # as it is assumed that an existing keyfile is already registered.
        return True
    dev_byid_withpath = get_device_path(dev_byid)
    tfo, npath = mkstemp()
    # Pythons _candidate_tempdir_list() should ensure our npath temp file is
    # in memory (tmpfs). From https://docs.python.org/2/library/tempfile.html
    # we have "Creates a temporary file in the most secure manner possible."
    # Populate this file with our passphrase and use as cryptsetup keyfile.
    # We set rc in case our try fails earlier than our run_command.
    rc = 0
    cmd = [
        CRYPTSETUP, 'luksAddKey', dev_byid_withpath, keyfile_withpath,
        '--key-file', npath
    ]
    try:
        with open(npath, 'w') as passphrase_file_object:
            passphrase_file_object.write(passphrase)
        out, err, rc = run_command(cmd, throw=False)
        if rc != 0:  # our luksAddKey command failed.
            if fresh_keyfile:
                # a freshly created keyfile without successful luksAddKey is
                # meaningless so remove it.
                os.remove(keyfile_withpath)
            raise CommandException(('%s' % cmd), out, err, rc)
    except Exception as e:
        if rc == 1:
            msg = 'Wrong Parameters exception'
        elif rc == 2:
            msg = 'No Permission (Bad Passphrase) exception'
        elif rc == 3:
            msg = 'Out of Memory exception'
        elif rc == 4:
            msg = 'Wrong Device Specified exception'
        elif rc == 5:
            msg = "Device already exists or device is busy exception"
        else:
            msg = 'Exception'
        msg += ' while running command(%s): %s' % (cmd, e.__str__())
        raise Exception(msg)
    finally:
        passphrase_file_object.close()
        if os.path.exists(npath):
            try:
                os.remove(npath)
            except Exception as e:
                msg = ('Exception while removing temp file %s: %s' %
                       (npath, e.__str__()))
                raise Exception(msg)
    return True