From d232623ae14a9e0748a76024456c687afd8c06ec Mon Sep 17 00:00:00 2001 From: Juan Jose Nicola Date: Fri, 29 May 2020 11:35:17 +0200 Subject: [PATCH] Create the file with permission only for the owner. Add test. --- ospd/datapickler.py | 23 ++++++++++++++++++++++- tests/test_datapickler.py | 15 +++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/ospd/datapickler.py b/ospd/datapickler.py index fd698d06..f5cfeb2a 100644 --- a/ospd/datapickler.py +++ b/ospd/datapickler.py @@ -20,6 +20,7 @@ import logging import pickle +import os from hashlib import sha256 from pathlib import Path @@ -29,10 +30,26 @@ logger = logging.getLogger(__name__) +OWNER_ONLY_RW_PERMISSION = 0o600 + class DataPickler: def __init__(self, storage_path): self._storage_path = storage_path + self._storage_fd = None + + def _fd_opener(self, path, flags): + os.umask(0) + flags = os.O_CREAT | os.O_WRONLY + self._storage_fd = os.open(path, flags, mode=OWNER_ONLY_RW_PERMISSION) + return self._storage_fd + + def _fd_close(self): + try: + self._storage_fd.close() + self._storage_fd = None + except Exception: # pylint: disable=broad-except + pass def remove_file(self, filename): """ Remove the file containing a scan_info pickled object """ @@ -65,13 +82,17 @@ def store_data(self, filename: str, data_object: Dict) -> str: ) try: - with storage_file_path.open('wb') as scan_info_f: + with open( + storage_file_path, 'wb', opener=self._fd_opener + ) as scan_info_f: scan_info_f.write(pickled_data) except Exception as e: # pylint: disable=broad-except + self._fd_close() raise OspdCommandError( 'Not possible to store scan info for %s. %s' % (filename, e), 'start_scan', ) + self._fd_close() return self._pickled_data_hash_generator(pickled_data) diff --git a/tests/test_datapickler.py b/tests/test_datapickler.py index c94603ed..c4818730 100644 --- a/tests/test_datapickler.py +++ b/tests/test_datapickler.py @@ -57,6 +57,21 @@ def test_store_data_failed(self): OspdCommandError, data_pickler.store_data, filename, data ) + def test_store_data_check_permission(self): + OWNER_ONLY_RW_PERMISSION = '0o100600' + data = {'foo', 'bar'} + filename = 'scan_info_1' + + data_pickler = DataPickler('/tmp') + data_pickler.store_data(filename, data) + + file_path = Path(data_pickler._storage_path) / filename + self.assertEqual( + oct(file_path.stat().st_mode), OWNER_ONLY_RW_PERMISSION + ) + + data_pickler.remove_file(filename) + def test_load_data(self): data_pickler = DataPickler('/tmp')