diff --git a/Dockerfile b/Dockerfile index 707a5eb..8de0107 100644 --- a/Dockerfile +++ b/Dockerfile @@ -38,6 +38,7 @@ ENV PYTHONPATH="/usr/local/lib" \ TFW_TERMINADO_DIR="/tmp/terminado_server" \ TFW_FRONTEND_DIR="/srv/frontend" \ TFW_SERVER_DIR="/srv/.tfw" \ + TFW_AUTH_KEY="/tmp/tfw-auth.key" \ TFW_HISTFILE="/home/${AVATAO_USER}/.bash_history" \ PROMPT_COMMAND="history -a" diff --git a/lib/tfw/crypto.py b/lib/tfw/crypto.py index a40cf5c..af632d8 100644 --- a/lib/tfw/crypto.py +++ b/lib/tfw/crypto.py @@ -5,6 +5,9 @@ from functools import wraps from base64 import b64encode, b64decode from copy import deepcopy from hashlib import md5 +from os import urandom, chmod +from os.path import exists +from stat import S_IRUSR, S_IWUSR, S_IXUSR from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.hashes import SHA256 @@ -12,6 +15,8 @@ from cryptography.hazmat.primitives.hmac import HMAC as _HMAC from cryptography.exceptions import InvalidSignature from tfw.networking import message_bytes +from tfw.decorators import lazy_property +from tfw.config import TFWENV def message_checksum(message): @@ -38,6 +43,32 @@ def verify_message(key, message): return False +class KeyManager: + def __init__(self): + self.keyfile = TFWENV.AUTH_KEY + if not exists(self.keyfile): + self._init_auth_key() + + @lazy_property + def auth_key(self): + with open(self.keyfile, 'rb') as ifile: + return ifile.read() + + def _init_auth_key(self): + key = self.generate_key() + with open(self.keyfile, 'wb') as ofile: + ofile.write(key) + self._chmod_700_keyfile() + return key + + @staticmethod + def generate_key(): + return urandom(32) + + def _chmod_700_keyfile(self): + chmod(self.keyfile, S_IRUSR | S_IWUSR | S_IXUSR) + + class HMAC: def __init__(self, key, message): self.key = key