2022-11-26 12:49:57 +00:00
|
|
|
import os
|
2023-01-19 01:57:21 +00:00
|
|
|
import json
|
2022-11-26 12:49:57 +00:00
|
|
|
import subprocess
|
|
|
|
|
2022-11-26 20:33:31 +00:00
|
|
|
class BitwardenCommandException(Exception):
|
|
|
|
pass
|
|
|
|
|
2022-11-26 17:55:42 +00:00
|
|
|
def get_secret_from_bitwarden(id):
|
2022-11-26 20:33:31 +00:00
|
|
|
return command_wrapper(command=f"get item {id}")
|
2022-11-26 12:49:57 +00:00
|
|
|
|
|
|
|
def unlock_bw(logger):
|
2023-01-19 01:57:21 +00:00
|
|
|
status_output = command_wrapper("status")
|
|
|
|
status = json.loads(status_output)['status']
|
|
|
|
if status == 'unlocked':
|
|
|
|
logger.info("Already unlocked")
|
|
|
|
return
|
2022-11-26 20:33:31 +00:00
|
|
|
token_output = command_wrapper("unlock --passwordenv BW_PASSWORD")
|
2022-11-26 12:49:57 +00:00
|
|
|
tokens = token_output.split('"')[1::2]
|
|
|
|
os.environ["BW_SESSION"] = tokens[1]
|
|
|
|
logger.info("Signin successful. Session exported")
|
|
|
|
|
2022-11-26 20:33:31 +00:00
|
|
|
def command_wrapper(command):
|
2022-11-26 12:49:57 +00:00
|
|
|
system_env = dict(os.environ)
|
|
|
|
sp = subprocess.Popen([f"bw {command}"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, shell=True, env=system_env)
|
|
|
|
out, err = sp.communicate()
|
|
|
|
if err:
|
2022-11-26 20:33:31 +00:00
|
|
|
raise BitwardenCommandException(err)
|
|
|
|
return out.decode(encoding='UTF-8')
|
|
|
|
|
|
|
|
def parse_login_scope(secret_json, key):
|
|
|
|
return secret_json["login"][key]
|
|
|
|
|
|
|
|
def parse_fields_scope(secret_json, key):
|
|
|
|
for entry in secret_json["fields"]:
|
|
|
|
if entry['name'] == key:
|
|
|
|
return entry['value']
|