367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
103 lines
5.1 KiB
Python
103 lines
5.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Explicit operator tool for this machine's disposable Docker Tortoise stack.
|
|
Never talks to a remote realm. Secrets travel through stdin/private files.
|
|
"""
|
|
import argparse
|
|
import datetime
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import zlib
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DB = 'tortoise-docker-db-1'
|
|
CONFIG = Path('/home/praxis/Servers/tortoise-docker/config')
|
|
|
|
def db(sql):
|
|
result = subprocess.run(['docker','exec','-i',DB,'sh','-c',
|
|
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb -uroot --batch --skip-column-names'],
|
|
input=sql, capture_output=True, text=True)
|
|
if result.returncode:
|
|
raise RuntimeError('local database operation failed; SQL and credentials omitted')
|
|
return result.stdout.strip()
|
|
|
|
def private(path, data):
|
|
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
with os.fdopen(fd,'wb') as f:
|
|
f.write(data)
|
|
|
|
def backup():
|
|
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
|
|
recovery=ROOT/'recovery'/stamp
|
|
recovery.mkdir(parents=True,mode=0o700)
|
|
for name in ('realmd.conf','mangosd.conf'):
|
|
shutil.copy2(CONFIG/name,recovery/name)
|
|
(recovery/name).chmod(0o600)
|
|
output=recovery/'test-databases.sql'
|
|
fd=os.open(output,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
with os.fdopen(fd,'wb') as f:
|
|
result=subprocess.run(['docker','exec',DB,'sh','-c',
|
|
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb-dump -uroot --single-transaction --skip-lock-tables --databases tw_logon tw_char'],stdout=f,stderr=subprocess.PIPE)
|
|
if result.returncode:
|
|
raise RuntimeError('local database backup failed; no modifications made')
|
|
private(recovery/'manifest.json',json.dumps({'utc':stamp,'container':DB,'databases':['tw_logon','tw_char'],
|
|
'sha256':hashlib.sha256(output.read_bytes()).hexdigest()},indent=2).encode())
|
|
print('Recovery point:',recovery)
|
|
return recovery
|
|
|
|
def provision(classic_ui=False, ordinary=False):
|
|
# Insert a fresh account; never alter an existing GM's credentials.
|
|
name='GW'+secrets.token_hex(5).upper()
|
|
# Original Turtle GlueXML password field is limited to16characters.
|
|
# Keep existing32character defaults and all existing accounts unchanged.
|
|
password=secrets.token_hex(8 if classic_ui else 16).upper()
|
|
assert not db(f"SELECT id FROM tw_logon.account WHERE username='{name}';")
|
|
recovery=backup()
|
|
directory=ROOT/'secrets'/name
|
|
directory.mkdir(parents=True,mode=0o700)
|
|
private(directory/'password.txt',password.encode())
|
|
private(directory/'version-hash.bin',bytes(20))
|
|
# Honest local diagnostic addon record, no forged fingerprint or signed addon.
|
|
addon=b'GatewayLocal\0'+struct.pack('<BII',1,0,0)
|
|
private(directory/'addon-tail.bin',struct.pack('<I',len(addon))+zlib.compress(addon))
|
|
digest=hashlib.sha1((name+':'+password).encode()).hexdigest().upper()
|
|
rank=0 if ordinary else 4
|
|
account=db(f"INSERT INTO tw_logon.account (username,sha_pass_hash,rank,email,last_ip,active) VALUES ('{name}','{digest}',{rank},'gateway@localhost','127.0.0.1',1); SELECT LAST_INSERT_ID();")
|
|
private(directory/'account.json',json.dumps({'username':name,'account_id':int(account),'auth_port':3724,'world_port':8090,
|
|
'recovery':str(recovery)},indent=2).encode())
|
|
print('Created disposable local test account id',account,'; private inputs:',directory)
|
|
print('No existing account credentials or server integrity settings changed.')
|
|
return directory
|
|
|
|
def probe(directory, executable, create_name=None):
|
|
info=json.loads((directory/'account.json').read_text())
|
|
cmd=[str(executable),'127.0.0.1',str(info['auth_port']),str(info['world_port']),info['username'],
|
|
str(directory/'password.txt'),str(directory/'version-hash.bin'),str(directory/'addon-tail.bin'), '--world-build','5875']
|
|
if create_name: cmd.extend(['--create',create_name])
|
|
return subprocess.run(cmd).returncode
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser()
|
|
parser.add_argument('action',choices=['backup','provision','probe'])
|
|
parser.add_argument('--account-dir',type=Path)
|
|
parser.add_argument('--create')
|
|
parser.add_argument('--classic-ui',action='store_true',help='New disposable account only:16character password for original Turtle login field')
|
|
parser.add_argument('--ordinary',action='store_true',help='Provision a new rank0 account; never change an existing account or grant GM privileges')
|
|
parser.add_argument('--executable',type=Path,default=ROOT/'build/gateway-probe')
|
|
args=parser.parse_args()
|
|
os.umask(0o077)
|
|
if args.classic_ui and args.action!='provision':parser.error('--classic-ui applies only to a new disposable account')
|
|
if args.ordinary and args.action!='provision':parser.error('--ordinary applies only to a new disposable account')
|
|
if args.action=='backup': backup()
|
|
elif args.action=='provision': provision(args.classic_ui,args.ordinary)
|
|
else:
|
|
if not args.account_dir: parser.error('--account-dir required')
|
|
raise SystemExit(probe(args.account_dir,args.executable,args.create))
|
|
|
|
if __name__=='__main__': main()
|