Esempio n. 1
0
    def init_trust(self):
        # Create a temporary directory and save a test key-pair to it:
        temp_dir = tempfile.TemporaryDirectory()
        temp_path = temp_dir.name
        private_key, public_key = TrustBasics.generateNewKeyPair()
        private_path = os.path.join(temp_path, "test_private_key.pem")
        public_path = os.path.join(temp_path, "test_public_key.pem")
        TrustBasics.saveKeyPair(private_key, private_path, public_path,
                                _passphrase)

        # Create random files:
        all_paths = [
            os.path.abspath(os.path.join(temp_path, x, y, z))
            for x in _folder_names for y in _subfolder_names
            for z in _file_names
        ]
        for path in all_paths:
            folder_path = os.path.dirname(path)
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
            with open(path, "w") as file:
                file.write("".join(
                    random.choice(['a', 'b', 'c', '0', '1', '2', '\n'])
                    for _ in range(1024)))

        # Instantiate a trust object with the public key that was just generated:
        violation_callback = MagicMock()
        trust = Trust(
            public_path)  # No '.getInstance', since key & handler provided.
        trust._violation_handler = violation_callback
        yield temp_path, private_path, trust, violation_callback

        temp_dir.cleanup()
Esempio n. 2
0
    def test_initTrustFail(self):
        with pytest.raises(Exception):
            Trust("key-not-found")

        with pytest.raises(Exception):
            Trust.getInstance()

        assert Trust.getInstanceOrNone() is None
Esempio n. 3
0
    def init_trust(self):
        # Create a temporary directory and save a test key-pair to it:
        temp_dir = tempfile.TemporaryDirectory()
        temp_path = temp_dir.name
        private_key, public_key = TrustBasics.generateNewKeyPair()
        private_path = os.path.join(temp_path, "test_private_key.pem")
        public_path = os.path.join(temp_path, "test_public_key.pem")
        TrustBasics.saveKeyPair(private_key, private_path, public_path,
                                _passphrase)

        # Create random files:
        all_paths = [
            os.path.abspath(os.path.join(temp_path, x, y, z))
            for x in _folder_names for y in _subfolder_names
            for z in _file_names
        ]
        for path in all_paths:
            folder_path = os.path.dirname(path)
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
            with open(path, "w") as file:
                file.write("".join(
                    random.choice(['a', 'b', 'c', '0', '1', '2', '\n'])
                    for _ in range(1024)))

        # Set up mocked Central File Storage & plugin file (don't move the files yet, though):
        CentralFileStorage.setIsEnterprise(True)

        central_storage_dir = tempfile.TemporaryDirectory()
        central_storage_path = central_storage_dir.name
        large_plugin_path = os.path.join(temp_path, _folder_names[2])
        store_folder = os.path.join(large_plugin_path, _subfolder_names[0])
        store_file = os.path.join(large_plugin_path, _file_names[2])

        central_storage_dict = [[
            f"{_subfolder_names[0]}", f"{_subfolder_names[0]}", "1.0.0",
            CentralFileStorage._hashItem(store_folder)
        ],
                                [
                                    f"{_file_names[2]}", f"{_file_names[2]}",
                                    "1.0.0",
                                    CentralFileStorage._hashItem(store_file)
                                ]]
        central_storage_file_path = os.path.join(
            large_plugin_path, TrustBasics.getCentralStorageFilename())
        with open(central_storage_file_path, "w") as file:
            json.dump(central_storage_dict, file, indent=2)

        # Instantiate a trust object with the public key that was just generated:
        violation_callback = MagicMock()
        trust = Trust(
            public_path)  # No '.getInstance', since key & handler provided.
        trust._violation_handler = violation_callback
        yield temp_path, private_path, trust, violation_callback, central_storage_path

        temp_dir.cleanup()
        central_storage_dir.cleanup()
        CentralFileStorage.setIsEnterprise(False)
Esempio n. 4
0
    def setCheckIfTrusted(self, check_if_trusted: bool) -> None:
        self._check_if_trusted = check_if_trusted

        # As part of CURA-7016, for now, we skip checking altogether if the public key is missing. That might not be as
        #   bad as it sounds, as non-admin enterprise users shouldn't have access to that file's location anyway.
        # TODO: DON'T FORGET TO REMOVE THESE (COMMENTS AND) NEXT 2 LINES WHEN WE _CAN_ START SIGNING THE PLUGINS.
        if not os.path.exists(Trust.getPublicRootKeyPath()):
            self._check_if_trusted = False

        if self._check_if_trusted:
            self._trust_checker = Trust.getInstance()
Esempio n. 5
0
 def setCheckIfTrusted(self,
                       check_if_trusted: bool,
                       debug_mode: bool = False) -> None:
     self._check_if_trusted = check_if_trusted
     if self._check_if_trusted:
         self._trust_checker = Trust.getInstance()
         # 'Trust.getInstance()' will raise an exception if anything goes wrong (e.g.: 'unable to read public key').
         # Any such exception is explicitly _not_ caught here, as the application should quit with a crash.
         if self._trust_checker:
             self._trust_checker.setFollowSymlinks(debug_mode)
Esempio n. 6
0
    def _isScriptAllowed(file_path: str) -> bool:
        """Checks whether the given file is allowed to be loaded"""
        if not ApplicationMetadata.IsEnterpriseVersion:
            # No signature needed
            return True

        dir_path = os.path.split(file_path)[0]  # type: str
        plugin_path = PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin")
        assert plugin_path is not None  # appease mypy
        bundled_path = os.path.join(plugin_path, "scripts")
        if dir_path == bundled_path:
            # Bundled scripts are trusted.
            return True

        trust_instance = Trust.getInstanceOrNone()
        if trust_instance is not None and Trust.signatureFileExistsFor(file_path):
            if trust_instance.signedFileCheck(file_path):
                return True

        return False  # Default verdict should be False, being the most secure fallback
Esempio n. 7
0
 def _trustHook(self, file_name: Optional[str]) -> bool:
     # NOTE: In an enterprise environment, if there _is_ a signature file for an unbundled package, verify it.
     #       (Note that this is a different behaviour w.r.t. the plugins, where the check is not just verification!)
     #       (Note that there shouldn't be a check if trust has to be here, since it'll continue on 'no signature'.)
     if file_name is None:
         return True
     trust_instance = Trust.getInstanceOrNone()
     if trust_instance is not None:
         from UM.Application import Application
         install_prefix = os.path.abspath(Application.getInstallPrefix())
         try:
             common_path = os.path.commonpath([install_prefix, file_name])
         except ValueError:
             common_path = ""
         if common_path is "" or not common_path.startswith(install_prefix):
             if trust_instance.signatureFileExistsFor(file_name):
                 _containerRegistry.setExplicitReadOnly(self.getId())  # TODO???: self._read_only = True
                 if not trust_instance.signedFileCheck(file_name):
                     raise Exception("Can't validate file {0}".format(file_name))
     return True
Esempio n. 8
0
    def init_trust(self):
        # create a temporary directory and save a test key-pair to it:
        temp_dir = tempfile.TemporaryDirectory()
        temp_path = temp_dir.name
        private_key, public_key = TrustBasics.generateNewKeyPair()
        private_path = os.path.join(temp_path, "test_private_key.pem")
        public_path = os.path.join(temp_path, "test_public_key.pem")
        TrustBasics.saveKeyPair(private_key, private_path, public_path, _passphrase)

        # create random files:
        all_paths = [os.path.abspath(os.path.join(temp_path, x, y, z))
                     for x in _folder_names for y in _subfolder_names for z in _file_names]
        for path in all_paths:
            folder_path = os.path.dirname(path)
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
            with open(path, "w") as file:
                file.write("".join(random.choice(['a', 'b', 'c', '0', '1', '2', '\n']) for _ in range(1024)))

        # instantiate a trust object with the public key that was just generated:
        trust = Trust(public_path)  # Don't use Trust.getInstance as that uses the 'normal' public key instead of test.
        yield temp_path, private_path, trust

        temp_dir.cleanup()
Esempio n. 9
0
 def setCheckIfTrusted(self, check_if_trusted: bool) -> None:
     self._check_if_trusted = check_if_trusted
     if self._check_if_trusted:
         self._trust_checker = Trust.getInstance()