'Getting and passing an encrypted password between Flask, Ansible, then back to Python using Fernet
I am currently creating a web application with Flask.
My Flask Python gets a password from user input through a webform, then that password is pushed to Ansible using the ansible_runner module.
form.py
from cryptography.fernet import Fernet
from tools import load_key
from ansiblerunner import ansible, inventory_hosts
ansible_role = "role"
tags = "install"
username = request.form.get("username")
dcryptpwd = request.form.get("password")
# Encrypt encpwd to pass to Ansible
refKey = load_key()
key = Fernet(refKey)
pwdbyt = bytes(dcryptpwd, 'utf-8')
encpwdbyt = (key.encrypt(pwdbyt))
encpwd = encpwdbyt.decode('utf-8')
inventory = inventory_hosts(username)
runner = ansible(hostname, ansible_role, encpwd, tags)
return render_template("form/form.html")
tools.py
def load_key():
with open('refKey.txt') as f:
refKey = ''.join(f.readlines())
refKeybyt = bytes(refKey, 'utf-8')
f.close()
return refKeybyt
Ansible is then using it on my role in main.yml
- block:
- name: Run setup.py
command: "{{ setup_py_run }} --username {{ username }} --encpwd {{ encpwd }}
no_log: false
delegate_to: localhost
tags:
- rebuild
Then setup.py decrypts the password and uses it here:
# Arguments imported from ansible
username = args.username
encpwd = bytes(args.encpwd,'utf-8')
# Decrypt password
refKey = load_key()
key = Fernet(refKey)
encpwdbyt = key.decrypt(encpwd)
password = encpwdbyt.decode('utf-8')
Currently this solution works, in the Ansible logs the plaintext password no longer shows up and the password gets decrypted successfully.
A few questions here:
- As this stands the private key is hidden in my server in a random directory, and the server is protected with SSH keys. Is this a secure way of 'hiding' a private key?
- Instead of having one key stored that encrypts and decrypts, would it be more secure to generate a new key each time, overwriting the previous key used?
- Is encryption even necessary or am I overthinking this? Should obfuscation be used instead?
I am new to programming and even newer to program security, any insight would be greatly appreciated, thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
