forked from mtusi2026/mtusi2026lab7
Implement lab7 security and compromised worker recovery evidence
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def request(path, body=None, token=None):
|
||||
context = ssl.create_default_context(cafile="/pki/ca.crt")
|
||||
context.load_cert_chain("/identity/service.crt", "/identity/service.key")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request("https://openbao:8200/v1/" + path, data, headers)
|
||||
with urllib.request.urlopen(req, context=context, timeout=3) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def replace(path, data):
|
||||
temporary = path.with_suffix(".next")
|
||||
temporary.write_text(data)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def refresh(role):
|
||||
auth = request("auth/cert/login", {"name": role})["auth"]
|
||||
try:
|
||||
data = request("secret/data/" + role, token=auth["client_token"])["data"]["data"]
|
||||
finally:
|
||||
request("auth/token/revoke-self", {}, auth["client_token"])
|
||||
folder = Path("/runtime")
|
||||
replace(folder / "secrets.json", json.dumps(data))
|
||||
mapping = {
|
||||
"spring.datasource.username": "postgres_user",
|
||||
"spring.datasource.password": "postgres_password",
|
||||
"s3.access-key": "s3_access_key_id",
|
||||
"s3.secret-key": "s3_secret_access_key",
|
||||
"app.redis.password": "cache_password",
|
||||
}
|
||||
for name, key in mapping.items():
|
||||
replace(folder / name, data[key])
|
||||
replace(folder / "lease", str(time.time() + min(auth["lease_duration"], 40)))
|
||||
|
||||
|
||||
def main():
|
||||
role = os.environ["SERVICE_IDENTITY"]
|
||||
while True:
|
||||
try:
|
||||
refresh(role)
|
||||
except Exception as error:
|
||||
print(
|
||||
json.dumps({"event": "secret_refresh_failed", "error_type": type(error).__name__}),
|
||||
flush=True,
|
||||
)
|
||||
time.sleep(10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user