Skip to content

Commit

Permalink
Encrypt passwords an tokens in config.yaml
Browse files Browse the repository at this point in the history
  • Loading branch information
Dielee committed Jun 1, 2021
1 parent 61daa3b commit ea7b66f
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 10 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,6 @@ modules.xml
# End of https://www.toptal.com/developers/gitignore/api/intellij+all
/docs/_build/
.idea
Backend/src/.key
Backend/src/.vscode/settings.json
Backend/config/.key
5 changes: 3 additions & 2 deletions Backend/config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ backendIP: 192.168.60.2
backendLanguage: de-DE
backendPort: 5558
dbMode: mssql
encrypted: true
parserIP: ''
parserPort: ''
parserToken: ''
parserToken: 86dd5f2745b84e0bf742c7637f840dc6
sqlDatabase: ''
sqlPassword: Test
sqlPassword: c38a1f67558a7a0bf742c7637f840dc6
sqlServerIP: ''
sqlUsername: ''
useSSL: false
3 changes: 2 additions & 1 deletion Backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ pyodbc==4.0.30
requests==2.25.1
uuid==1.30
mysql-connector-python==8.0.25
cryptography==3.4.7
cryptography==3.4.7
pycryptodome==3.10.1
1 change: 0 additions & 1 deletion Backend/src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
load_db_conn,
)


def main():
cfg = load_conf()

Expand Down
100 changes: 96 additions & 4 deletions Backend/src/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import json
import yaml
import os
from mysql.connector import connect, Error
from datetime import datetime, timedelta
import ipaddress
import socket
from mysql.connector import connect, Error
from datetime import datetime, timedelta

from Crypto.Cipher import AES
from cryptography.fernet import Fernet
from binascii import b2a_hex, a2b_hex
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
Expand All @@ -17,6 +20,40 @@

cfg = None
api_token = None
key = None
BLOCK_SIZE = 16
SEGMENT_SIZE = 128

def encrypt(plaintext):
key = check_existing_key()
key = key.encode('utf-8')
iv = key

aes = AES.new(key, AES.MODE_CFB, iv, segment_size=SEGMENT_SIZE)
plaintext = _pad_string(plaintext)
encrypted_text = aes.encrypt(plaintext.encode())
return b2a_hex(encrypted_text).rstrip().decode()

def decrypt(encrypted_text):
key = check_existing_key()
key = key.encode('utf-8')[:16]
iv = key

aes = AES.new(key, AES.MODE_CFB, iv, segment_size=SEGMENT_SIZE)
encrypted_text_bytes = a2b_hex(encrypted_text)
decrypted_text = aes.decrypt(encrypted_text_bytes)
decrypted_text = _unpad_string(decrypted_text.decode())
return decrypted_text

def _pad_string(value):
length = len(value)
pad_size = BLOCK_SIZE - (length % BLOCK_SIZE)
return value.ljust(length + pad_size, '\x00')

def _unpad_string(value):
while value[-1] == '\x00':
value = value[:-1]
return value

def create_ssl_cert(
ip_addresses=None,
Expand Down Expand Up @@ -123,7 +160,7 @@ def create_ssl_cert(
open(cert_file, "wb").write(cert_pem)

def update_server_config(settings):
update_config_yaml(settings)
crypt_config(settings)
load_conf(True)
create_web_config()

Expand All @@ -135,6 +172,7 @@ def update_config_yaml(settings):
def create_web_config():
web_json = "../webroot/settings/settings.json"
web_cfg = {
"encrypted": cfg["encrypted"],
"useSSL": cfg["useSSL"],
"backendHostname": cfg["backendHostname"],
"backendIP": cfg["backendIP"],
Expand All @@ -154,6 +192,27 @@ def create_web_config():
f.write(json.dumps(web_cfg))
f.close()

def check_existing_key():
if not os.path.isfile(r"../config/.key"):
create_key()
else:
read_key()

return key

def read_key():
global key
if not key:
with open(r"../config/.key") as f:
key = f.readline()

def create_key():
global key
new_key = Fernet.generate_key().decode('utf-8')[:16]
f = open("../config/.key", "w")
f.write(new_key)
key = new_key
f.close()

def check_existing_token():
if not os.path.isfile(r".api_token"):
Expand All @@ -163,7 +222,6 @@ def check_existing_token():

return api_token


def read_token():
global api_token
if not api_token:
Expand Down Expand Up @@ -231,8 +289,42 @@ def load_conf(force_reload=False):
with open("../config/config.yaml", "r") as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)

cfg = crypt_config(cfg)

return cfg

def crypt_config(settings):
rewrite_config = False
encrypted_cfg = settings.copy()

if 'encrypted' in settings:
is_encrypted = settings['encrypted']
else:
is_encrypted = False

for c, v in settings.items():
if v and ("Token" in c or "Password" in c):
if not is_encrypted:
rewrite_config = True

encrypted = encrypt(str(v))
encrypted_cfg[c] = encrypted
else:
try:
decrypted = decrypt(str(v))
settings[c] = decrypted
except Exception as e:
if "Non-hexadecimal digit found" in str(e):
print("Decription failed. Please set encryption flag in config yaml to False")
else:
print(e)

if rewrite_config:
settings['encrypted'] = True
encrypted_cfg['encrypted'] = True
update_config_yaml(encrypted_cfg)

return settings

def delete_from_db(table_name, id):
conn, cur = load_db_conn()
Expand Down
2 changes: 1 addition & 1 deletion Frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script src="node_modules/web-animations-js/web-animations-next.min.js"></script>
<script>
var version="0.10.2"
var version="0.11.0"
var mainPage;
var scanPage;
var historyPage;
Expand Down
2 changes: 1 addition & 1 deletion Frontend/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class MainElement extends LitElement {
nparserPort = parseInt(nparserPort)
}

var post_json = {"useSSL": nuseSSL, "backendHostname": nbackendHostname, "backendIP": nbackendIP, "backendPort": nbackendPort, "backendLanguage": nlanguage, "parserIP": nparserIP, "parserPort": nparserPort,
var post_json = {"encrypted": false, "useSSL": nuseSSL, "backendHostname": nbackendHostname, "backendIP": nbackendIP, "backendPort": nbackendPort, "backendLanguage": nlanguage, "parserIP": nparserIP, "parserPort": nparserPort,
"parserToken": nparserToken, "dbMode": ndbMode,"sqlServerIP": nsqlServerIP, "sqlDatabase": nsqlServerDatabase, "sqlUsername": nsqlServerUsername, "sqlPassword": nsqlServerPassword}

xhr.send(JSON.stringify(post_json));
Expand Down

0 comments on commit ea7b66f

Please sign in to comment.