Fix potential optional aes key read problem

This commit is contained in:
deajan 2025-04-18 22:27:22 +02:00
parent 56ce653a5b
commit f984ee9e40
2 changed files with 28 additions and 17 deletions

View file

@ -39,9 +39,12 @@ sys.path.insert(0, os.path.normpath(os.path.join(os.path.dirname(__file__), ".."
logger = getLogger()
opt_aes_key = get_aes_key()
opt_aes_key, msg = get_aes_key()
if opt_aes_key:
logger.info(msg)
AES_KEY = opt_aes_key
elif opt_aes_key is False:
logger.critical(msg)
# Monkeypatching ruamel.yaml ordreddict so we get to use pseudo dot notations

View file

@ -55,23 +55,31 @@ def get_aes_key():
"""
key = None
key_location = os.environ.get("NPBACKUP_KEY_LOCATION", None)
if key_location and os.path.isfile(key_location):
try:
with open(key_location, "rb") as key_file:
key = key_file.read()
except OSError as exc:
msg = f"Cannot read encryption key file: {exc}"
return False, msg
else:
key_command = os.environ.get("NPBACKUP_KEY_COMMAND", None)
if key_command:
exit_code, output = command_runner(key_command, encoding=False, shell=True)
if exit_code != 0:
msg = f"Cannot run encryption key command: {output}"
try:
key_location = os.environ.get("NPBACKUP_KEY_LOCATION", None)
if key_location and os.path.isfile(key_location):
try:
with open(key_location, "rb") as key_file:
key = key_file.read()
msg = f"Encryption key file read"
except OSError as exc:
msg = f"Cannot read encryption key file: {exc}"
return False, msg
key = bytes(output)
return obfuscation(key)
else:
key_command = os.environ.get("NPBACKUP_KEY_COMMAND", None)
if key_command:
exit_code, output = command_runner(key_command, encoding=False, shell=True)
if exit_code != 0:
msg = f"Cannot run encryption key command: {output}"
return False, msg
key = bytes(output)
msg = f"Encryption key read from command"
except Exception as exc:
msg = f"Error reading encryption key: {exc}"
return False, msg
if key:
return obfuscation(key), msg
return None, ""
def create_key_file(key_location: str):