Skip to content

Instantly share code, notes, and snippets.

@adrianlzt
Last active January 16, 2025 15:12
Show Gist options
  • Save adrianlzt/b2c2c9581757ad359216eef0f05beb1a to your computer and use it in GitHub Desktop.
Save adrianlzt/b2c2c9581757ad359216eef0f05beb1a to your computer and use it in GitHub Desktop.
Connect to the PostgreSQL where AWX stores its data, Get the credentials stored and select which one you want to decode. You need to pass the AWX secret_key.
❯ uv run https://gist.githubusercontent.com/adrianlzt/b2c2c9581757ad359216eef0f05beb1a/raw/5a0f29c2496a98e9aef0eef8ad1469d1cbdd09e8/awx_secrets.py --host 10.1.1.10 --user awx --password SECRETPASSWORD --secret-key SECRETKEY

Reading inline script metadata from `./awx_secrets.py`
Available secrets:
1. Name: Demo Credential, Type: Machine
Select the secret to decrypt: 7
username: admin
#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.8"
# dependencies = [
# "asgiref==3.8.1",
# "cffi==1.16.0",
# "cryptography==2.8",
# "django==5.0.6",
# "pycparser==2.22",
# "pytz==2024.1",
# "six==1.16.0",
# "sqlparse==0.5.0",
# "psycopg2==2.9.9",
# ]
# ///
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Distributed under terms of the MIT license.
"""
Extracting the value of an ssh key of AWX.
In the database, extract the encrypted value of the ssh key and its id.
credential_type_id=2 is the ssh key type.
select id,inputs->'ssh_key_data' as ssh_key from main_credential where name = 'NAME_OF_THE_KEY' and credential_type_id=2;
Use those values to set id and encrypted_value.
Set also the secret_key value from the SECRET key file.
"""
import base64
import hashlib
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from django.utils.encoding import smart_str, smart_bytes
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.
"""
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 decrypt_value(encryption_key, value):
raw_data = value[len("$encrypted$") :]
# If the encrypted string contains a UTF8 marker, discard it
utf8 = raw_data.startswith("UTF8$")
if utf8:
raw_data = raw_data[len("UTF8$") :]
algo, b64data = raw_data.split("$", 1)
if algo != "AESCBC":
raise ValueError("unsupported algorithm: %s" % algo)
encrypted = base64.b64decode(b64data)
f = Fernet256(encryption_key)
value = f.decrypt(encrypted)
return smart_str(value)
def get_encryption_key(field_name, pk=None, secret_key=None):
"""
Generate key for encrypted password based on field name,
``settings.SECRET_KEY``, and instance pk (if available).
:param pk: (optional) the primary key of the model object;
can be omitted in situations where you're encrypting a setting
that is not database-persistent (like a read-only setting)
"""
h = hashlib.sha512()
h.update(smart_bytes(secret_key))
if pk is not None:
h.update(smart_bytes(str(pk)))
h.update(smart_bytes(field_name))
return base64.urlsafe_b64encode(h.digest())
import getpass
import psycopg2
import json
import argparse
def main():
parser = argparse.ArgumentParser(description="Decrypt AWX secrets.")
parser.add_argument("--host", help="Database host", required=True)
parser.add_argument("--user", help="Database user", required=True)
parser.add_argument("--password", help="Database password", required=True)
parser.add_argument("--secret-key", help="Secret key", required=False)
args = parser.parse_args()
if args.secret_key:
secret_key = args.secret_key
else:
secret_key = getpass.getpass(prompt="Enter the secret key: ")
try:
conn = psycopg2.connect(
host=args.host,
user=args.user,
password=args.password,
database="awx",
)
cur = conn.cursor()
cur.execute(
"select c.id, c.name as secret, t.name as credential_type, c.inputs from main_credential c JOIN main_credentialtype t ON c.credential_type_id = t.id;"
)
rows = cur.fetchall()
print("Available secrets:")
for i, row in enumerate(rows):
print(f"{i + 1}. Name: {row[1]}, Type: {row[2]}")
selection = int(input("Select the secret to decrypt: ")) - 1
selected_row = rows[selection]
selected_id = selected_row[0]
inputs = selected_row[3]
for key, value in inputs.items():
if isinstance(value, str) and value.startswith("$encrypted"):
field_name = key
key_ = get_encryption_key(
field_name, selected_id, secret_key=secret_key
)
decrypted_value = decrypt_value(key_, value)
print(f"Decrypted {key}: {decrypted_value}")
else:
print(f"{key}: {value}")
except psycopg2.Error as e:
print(f"Error connecting to database: {e}")
finally:
if conn:
cur.close()
conn.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment