diff --git a/monkey_island/cc/encryptor.py b/monkey_island/cc/encryptor.py new file mode 100644 index 000000000..7af0840d0 --- /dev/null +++ b/monkey_island/cc/encryptor.py @@ -0,0 +1,48 @@ +import base64 +import os + +from Crypto import Random +from Crypto.Cipher import AES + +__author__ = "itay.mizeretz" + + +class Encryptor: + _BLOCK_SIZE = 32 + _DB_PASSWORD_FILENAME = "mongo_key.bin" + + def __init__(self): + self._load_key() + + def _init_key(self): + self._cipher_key = Random.new().read(self._BLOCK_SIZE) + with open(self._DB_PASSWORD_FILENAME, 'wb') as f: + f.write(self._cipher_key) + + def _load_existing_key(self): + with open(self._DB_PASSWORD_FILENAME, 'rb') as f: + self._cipher_key = f.read() + + def _load_key(self): + if os.path.exists(self._DB_PASSWORD_FILENAME): + self._load_existing_key() + else: + self._init_key() + + def _pad(self, message): + return message + (self._BLOCK_SIZE - (len(message) % self._BLOCK_SIZE)) * chr( + self._BLOCK_SIZE - (len(message) % self._BLOCK_SIZE)) + + def _unpad(self, message): + return message[0:-ord(message[len(message) - 1])] + + def enc(self, message): + cipher_iv = Random.new().read(AES.block_size) + cipher = AES.new(self._cipher_key, AES.MODE_CBC, cipher_iv) + return base64.b64encode(cipher_iv + cipher.encrypt(self._pad(message))) + + def dec(self, enc_message): + enc_message = base64.b64decode(enc_message) + cipher_iv = enc_message[0:AES.block_size] + cipher = AES.new(self._cipher_key, AES.MODE_CBC, cipher_iv) + return self._unpad(cipher.decrypt(enc_message[AES.block_size:])) diff --git a/monkey_island/deb-package/monkey_island_pip_requirements.txt b/monkey_island/deb-package/monkey_island_pip_requirements.txt index 404aad8b0..582efc5f2 100644 --- a/monkey_island/deb-package/monkey_island_pip_requirements.txt +++ b/monkey_island/deb-package/monkey_island_pip_requirements.txt @@ -12,4 +12,5 @@ jsonschema netifaces ipaddress enum34 +PyCrypto virtualenv \ No newline at end of file diff --git a/monkey_island/requirements.txt b/monkey_island/requirements.txt index 9d8bfbfb8..18098eec0 100644 --- a/monkey_island/requirements.txt +++ b/monkey_island/requirements.txt @@ -11,4 +11,5 @@ Flask-Restful jsonschema netifaces ipaddress -enum34 \ No newline at end of file +enum34 +PyCrypto \ No newline at end of file