188 lines
12 KiB
Python
188 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Independent FUC-XB runtime. Never changes DPL/HN/XrayR or certificate renewals."""
|
|
import argparse,fcntl,hashlib,json,os,pathlib,re,shutil,subprocess,time
|
|
|
|
OWNER='fuc-xb-launch-20261105'
|
|
SHA='55bf71fa9d9f2048d3255ae7c0af929a41897ca7743f6ead34132a6ca4c79043'
|
|
ETC=pathlib.Path('/etc/fuc-xb-node')
|
|
OPT=pathlib.Path('/opt/fuc-xb-node')
|
|
STATE=pathlib.Path('/var/lib/fuc-xb-node')
|
|
UNIT=pathlib.Path('/etc/systemd/system/fuc-xb-node.service')
|
|
REFRESH=pathlib.Path('/etc/systemd/system/fuc-xb-certificate-refresh.service')
|
|
TIMER=pathlib.Path('/etc/systemd/system/fuc-xb-certificate-refresh.timer')
|
|
JOURNAL=None
|
|
|
|
def same_protected(actual,expected):
|
|
# ExecStart serializes transient pid/start/exit metadata which daemon-reload
|
|
# may reset. Unit bytes, executable, config, MainPID/start time/NRestarts
|
|
# remain the authoritative protection checks.
|
|
def stable(value):return {k:stable(v)for k,v in value.items()if k!='execstart_sha256'}if isinstance(value,dict)else value
|
|
return stable(actual)==stable(expected)
|
|
|
|
def run(args):
|
|
p=subprocess.run(args,capture_output=True,text=True,timeout=45)
|
|
assert p.returncode==0,'FUC node operation failed; no credentials logged'
|
|
return p.stdout.strip()
|
|
def digest(path):return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()
|
|
def protected():
|
|
result={}
|
|
for name in ['XrayR','dpl-node']:
|
|
props=dict(x.split('=',1)for x in run(['systemctl','show',name,'-p','MainPID','-p','ActiveState','-p','NRestarts','-p','ExecMainStartTimestampMonotonic','-p','ExecStart']).splitlines()if '='in x)
|
|
cmd=props.pop('ExecStart','');m=re.search(r'path=([^ ;]+)',cmd);binary=m.group(1)if m else None
|
|
paths=['/etc/'+name+'/config.yml']
|
|
if name=='XrayR':paths+=['/usr/local/XrayR/config.yml']
|
|
result[name]={'properties':props,'binary':binary,'binary_sha256':digest(binary)if binary and pathlib.Path(binary).is_file()else None,'execstart_sha256':hashlib.sha256(cmd.encode()).hexdigest(),'config_sha256':{p:digest(p)for p in paths if pathlib.Path(p).is_file()},'unit_sha256':hashlib.sha256(run(['systemctl','cat',name]).encode()).hexdigest()}
|
|
return result
|
|
def persist():
|
|
tmp=STATE/'owner.json.tmp';tmp.write_text(json.dumps(JOURNAL,indent=2));tmp.chmod(0o600);tmp.replace(STATE/'owner.json')
|
|
def write(path,text,mode=0o600):
|
|
assert not os.path.lexists(str(path)),'FUC path already exists; inspect ownership'
|
|
try:
|
|
with path.open('xb')as f:f.write(text.encode()if isinstance(text,str)else text)
|
|
path.chmod(mode)
|
|
finally:
|
|
if path.is_file():JOURNAL['files'][str(path)]=digest(path);persist()
|
|
def validate_cert(row):
|
|
cert=row['certificate'];key=row['private_key'];domain=row['sni']
|
|
run(['openssl','x509','-in',cert,'-noout','-checkhost',domain]);run(['openssl','x509','-in',cert,'-noout','-checkend','604800']);run(['openssl','verify','-untrusted',cert,cert])
|
|
assert run(['openssl','x509','-in',cert,'-pubkey','-noout'])==run(['openssl','pkey','-in',key,'-pubout']),'Certificate key mismatch'
|
|
return run(['openssl','x509','-in',cert,'-noout','-fingerprint','-sha256'])
|
|
def owned_units():
|
|
for p in [UNIT,REFRESH,TIMER]:
|
|
assert not os.path.lexists('/etc/systemd/system/'+p.name+'.d'),'Unexpected FUC systemd override'
|
|
props=dict(x.split('=',1)for x in run(['systemctl','show',p.name,'-p','FragmentPath','-p','DropInPaths']).splitlines()if '='in x)
|
|
assert props.get('FragmentPath')==str(p) and not props.get('DropInPaths'),'Parsed FUC unit changed'
|
|
def verify():
|
|
state=json.loads((STATE/'owner.json').read_text());assert state['owner']==OWNER
|
|
assert same_protected(protected(),state['protected']),'Unrelated original service drift; stop for review'
|
|
assert digest(OPT/'xboard-node')==SHA
|
|
owned_units()
|
|
assert all(pathlib.Path(p).is_file()and digest(p)==sha for p,sha in state['files'].items()),'FUC owned files drift'
|
|
status=run(['systemctl','show','fuc-xb-node','-p','ActiveState','--value'])
|
|
pid=run(['systemctl','show','fuc-xb-node','-p','MainPID','--value']);listener=run(['ss','-H','-ltnp','sport = :24445'])
|
|
return {'owner':OWNER,'active':status=='active','original_services_unchanged':True,'binary_sha256':SHA,'port_listening':('pid='+pid+',')in listener,'owned_files_unchanged':True,'cert_timer_enabled':run(['systemctl','is-enabled','fuc-xb-certificate-refresh.timer'])=='enabled','cert_timer_active':run(['systemctl','is-active','fuc-xb-certificate-refresh.timer'])=='active'}
|
|
def install(context):
|
|
global JOURNAL
|
|
row=context['node'];assert context['owner']==OWNER and row['listen_port']==24445
|
|
assert context['source']=='https://fuc-xb-test.gemcook.net'
|
|
assert isinstance(context['machine_id'],int)and context['machine_id']>0
|
|
token=context['machine_token'];assert len(token)>=32 and token.isalnum(),'Unexpected machine token encoding'
|
|
assert digest('/opt/dpl-node/xboard-node')==SHA
|
|
assert not run(['ss','-H','-ltn','sport = :24445']),'Port in use'
|
|
assert all(not os.path.lexists(str(p))for p in [ETC,OPT,STATE,UNIT,REFRESH,TIMER]),'FUC namespace collision'
|
|
for name in ['fuc-xb-node.service','fuc-xb-certificate-refresh.service','fuc-xb-certificate-refresh.timer']:
|
|
assert not os.path.lexists('/etc/systemd/system/'+name+'.d'),'Existing systemd override'
|
|
props=dict(x.split('=',1)for x in run(['systemctl','show',name,'-p','LoadState','-p','FragmentPath','-p','DropInPaths']).splitlines()if '='in x)
|
|
assert props.get('LoadState')=='not-found' and not props.get('FragmentPath') and not props.get('DropInPaths'),'Existing parsed systemd unit'
|
|
total=int(pathlib.Path('/proc/meminfo').read_text().splitlines()[0].split()[1])*1024
|
|
assert total>=1000000000,'Candidate below physical-memory requirement'
|
|
cert=validate_cert(row);before=protected();assert same_protected(before,context['expected_units']),'Preflight old-service baseline changed'
|
|
STATE.mkdir(mode=0o700)
|
|
JOURNAL={'owner':OWNER,'node':row,'machine_id':context['machine_id'],'protected':before,'certificate_fingerprint':cert,'files':{},'created_directories':[str(STATE)],'phase':'installing'};persist()
|
|
try:return install_files(context,token)
|
|
except BaseException:
|
|
cleanup=[]
|
|
for command in [['systemctl','disable','--now','fuc-xb-certificate-refresh.timer','fuc-xb-node'],['systemctl','stop','fuc-xb-certificate-refresh.service']]:
|
|
try:cleanup.append({'operation':command[1],'returncode':subprocess.run(command,capture_output=True,timeout=45).returncode})
|
|
except subprocess.TimeoutExpired:cleanup.append({'operation':command[1],'timed_out':True})
|
|
JOURNAL['failure_cleanup']=cleanup
|
|
JOURNAL['phase']='failed';persist()
|
|
raise
|
|
def install_files(context,token):
|
|
for p in [ETC,OPT]:p.mkdir(mode=0o700);JOURNAL['created_directories'].append(str(p));persist()
|
|
write(OPT/'xboard-node',pathlib.Path('/opt/dpl-node/xboard-node').read_bytes(),0o700)
|
|
assert digest(OPT/'xboard-node')==SHA,'Copied binary hash differs before execution'
|
|
cfg={'panel':{'url':context['source']},'machine':{'machine_id':context['machine_id'],'token_env':'FUC_XB_MACHINE_TOKEN'},'kernel':{'type':'singbox','config_dir':str(STATE/'kernel')},'log':{'level':'warn'},'runtime':{'gomemlimit':'128MiB','gogc':75},'node':{'push_interval':5,'pull_interval':5}}
|
|
write(ETC/'config.json',json.dumps(cfg));write(ETC/'secret.env','FUC_XB_MACHINE_TOKEN='+token+'\n')
|
|
unit='''[Unit]
|
|
Description=FUC-XB independent native V2 node
|
|
After=network-online.target
|
|
Wants=network-online.target
|
|
[Service]
|
|
Type=simple
|
|
EnvironmentFile=/etc/fuc-xb-node/secret.env
|
|
WorkingDirectory=/var/lib/fuc-xb-node
|
|
ExecStart=/opt/fuc-xb-node/xboard-node -c /etc/fuc-xb-node/config.json
|
|
Restart=on-failure
|
|
RestartSec=5
|
|
MemoryMax=256M
|
|
CPUQuota=50%
|
|
LimitNOFILE=1048576
|
|
UMask=0077
|
|
NoNewPrivileges=true
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
'''
|
|
write(UNIT,unit,0o644)
|
|
helper=pathlib.Path(__file__).with_name('certificate-refresh.py');write(OPT/helper.name,helper.read_bytes(),0o700)
|
|
write(REFRESH,'''[Unit]
|
|
Description=Reload only FUC-XB after its existing certificate changes
|
|
[Service]
|
|
Type=oneshot
|
|
ExecStart=/usr/bin/python3 /opt/fuc-xb-node/certificate-refresh.py
|
|
''',0o644)
|
|
write(TIMER,'''[Unit]
|
|
Description=Check FUC-XB certificate every five minutes
|
|
[Timer]
|
|
OnBootSec=3min
|
|
OnUnitActiveSec=5min
|
|
Persistent=true
|
|
[Install]
|
|
WantedBy=timers.target
|
|
''',0o644)
|
|
run(['systemctl','daemon-reload']);run(['systemctl','enable','--now','fuc-xb-node','fuc-xb-certificate-refresh.timer'])
|
|
for _ in range(45):
|
|
if run(['ss','-H','-ltn','sport = :24445']):break
|
|
time.sleep(1)
|
|
value=verify();assert value['active']and value['port_listening'],'Node not ready'
|
|
JOURNAL['phase']='installed';persist();(STATE/'installed.json').write_text(json.dumps(value,indent=2));return value
|
|
def rollback():
|
|
state=json.loads((STATE/'owner.json').read_text());assert state['owner']==OWNER and same_protected(protected(),state['protected'])
|
|
assert all(pathlib.Path(p).is_file()and digest(p)==sha for p,sha in state['files'].items()),'Owned files changed; no automatic removal'
|
|
if str(TIMER)in state['files']:run(['systemctl','disable','--now','fuc-xb-certificate-refresh.timer'])
|
|
services=[p.stem for p in [REFRESH,UNIT]if str(p)in state['files']]
|
|
if services:run(['systemctl','stop',*services])
|
|
if str(UNIT)in state['files']:run(['systemctl','disable','fuc-xb-node'])
|
|
for service in services:
|
|
assert run(['systemctl','show',service,'-p','MainPID','--value'])=='0','Owned process still running; retain files'
|
|
assert run(['systemctl','show',service,'-p','ActiveState','--value']) in ['inactive','failed'],'Owned service not stopped'
|
|
if str(TIMER)in state['files']:
|
|
assert run(['systemctl','show','fuc-xb-certificate-refresh.timer','-p','ActiveState','--value'])=='inactive','Timer still running'
|
|
enabled=subprocess.run(['systemctl','is-enabled','fuc-xb-certificate-refresh.timer'],capture_output=True,text=True,timeout=30)
|
|
assert enabled.stdout.strip()=='disabled','Timer still enabled'
|
|
for p in [UNIT,REFRESH,TIMER]:
|
|
if str(p)in state['files']:p.unlink()
|
|
# Exact independent namespaces only. Secrets are removed with the FUC configuration.
|
|
for p in reversed(state['created_directories']):shutil.rmtree(p)
|
|
run(['systemctl','daemon-reload']);assert same_protected(protected(),state['protected'])
|
|
return {'rollback':True,'original_services_unchanged':True}
|
|
def resume(context):
|
|
global JOURNAL
|
|
JOURNAL=json.loads((STATE/'owner.json').read_text())
|
|
assert JOURNAL['owner']==OWNER and JOURNAL['machine_id']==context['machine_id'] and JOURNAL['node']==context['node']
|
|
assert JOURNAL['phase']in ['failed','installed'],'Unknown partial phase; inspect'
|
|
assert same_protected(protected(),JOURNAL['protected']) and same_protected(protected(),context['expected_units'])
|
|
assert all(pathlib.Path(p).is_file()and digest(p)==sha for p,sha in JOURNAL['files'].items()),'Partial runtime files changed'
|
|
assert (ETC/'secret.env').read_text()=='FUC_XB_MACHINE_TOKEN='+context['machine_token']+'\n'
|
|
owned_units()
|
|
validate_cert(context['node'])
|
|
try:
|
|
run(['systemctl','enable','--now','fuc-xb-node','fuc-xb-certificate-refresh.timer'])
|
|
for _ in range(45):
|
|
if run(['ss','-H','-ltn','sport = :24445']):break
|
|
time.sleep(1)
|
|
value=verify();assert value['active']and value['port_listening'],'Resumed node not ready'
|
|
JOURNAL['phase']='installed';persist();return value
|
|
except BaseException:
|
|
cleanup=subprocess.run(['systemctl','disable','--now','fuc-xb-node','fuc-xb-certificate-refresh.timer'],capture_output=True,timeout=45)
|
|
JOURNAL['phase']='failed';JOURNAL['resume_cleanup_returncode']=cleanup.returncode;persist();raise
|
|
if __name__=='__main__':
|
|
import sys
|
|
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['install','verify','rollback','resume']);args=p.parse_args()
|
|
lock=open('/run/lock/fuc-xb-node.lock','a');fcntl.flock(lock,fcntl.LOCK_EX)
|
|
if args.action=='install':value=install(json.load(sys.stdin))
|
|
elif args.action=='resume':value=resume(json.load(sys.stdin))
|
|
elif args.action=='verify':value=verify()
|
|
else:value=rollback()
|
|
print(json.dumps(value))
|