Skip to content

Instantly share code, notes, and snippets.

@asquelt
Created May 6, 2020 14:25
Show Gist options
  • Save asquelt/e85435b88bda59273cf4214984791165 to your computer and use it in GitHub Desktop.
Save asquelt/e85435b88bda59273cf4214984791165 to your computer and use it in GitHub Desktop.
import os
import base64
import hashlib
import logging
import json
import six
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
class Fernet256(Fernet):
'''Not techincally Fernet, but uses the base of the Fernet spec and uses AES-256-CBC
instead of AES-128-CBC. All other functionality remain identical.
ripped from: https://github.com/ansible/awx/blob/bfea00f6dc6af0fb01057ce38e9d0337e6c589aa/awx/main/utils/encryption.py
'''
def __init__(self, key, backend=None):
if backend is None:
backend = default_backend()
key = base64.urlsafe_b64decode(key)
if len(key) != 64:
raise ValueError(
"Fernet key must be 64 url-safe base64-encoded bytes."
)
self._signing_key = key[:32]
self._encryption_key = key[32:]
self._backend = backend
def get_encryption_key(k, pk=None, fn=None):
h = hashlib.sha512()
h.update(k)
if pk is not None:
h.update(pk)
if fn is not None:
h.update(fn)
return base64.urlsafe_b64encode(h.digest())
with open ("/etc/tower/SECRET_KEY", "r") as myfile:
secret=myfile.readlines()
key = secret[0].rstrip()
get_db = 'cd /tmp && su postgres -c "psql awx -c \'select id,name,inputs from main_credential\' -tA"'
res = os.popen(get_db)
for line in res.read().split("\n"):
try:
i, fn, jsons = line.split('|',3)
except:
continue
data = json.loads(jsons)
for k,v in data.items():
if v.startswith('$encrypted$'):
vv = v.split('$')
encrypted = base64.b64decode(vv[-1])
f = Fernet256(get_encryption_key(key,i,k))
cleartext = f.decrypt(encrypted)
print "=== %s ===\n[fn=%s pk=%s]\n\n%s\n" % (fn, k, i, cleartext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment