172 lines
14 KiB
Python
172 lines
14 KiB
Python
"""Run on white jump only. JSON auth/request on stdin; default is read-only probe."""
|
|
import fcntl,hashlib,ipaddress,json,os,re,sys,tempfile,time,urllib.request
|
|
from pathlib import Path
|
|
os.umask(0o077)
|
|
FIELDS=['id','name','tunnelId','inPort','inIp','remoteAddr','strategy','speedId','ipMaxConn','ipSpeedId','maxConn','proxyProtocol','proxyProtocolReceive','proxyProtocolSend','status','userId']
|
|
class Blocked(RuntimeError):pass
|
|
def digest(value):return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
|
def require(value,reason):
|
|
if not value:raise Blocked(reason)
|
|
def atomic(path,value):
|
|
fd,tmp=tempfile.mkstemp(prefix='.relay-',dir=path.parent)
|
|
try:
|
|
with os.fdopen(fd,'w') as f:os.fchmod(f.fileno(),0o600);json.dump(value,f,sort_keys=True);f.flush();os.fsync(f.fileno())
|
|
os.replace(tmp,path)
|
|
finally:
|
|
if os.path.exists(tmp):os.unlink(tmp)
|
|
def normalized(data):
|
|
if isinstance(data,dict):
|
|
rows=data.get('forwards',data.get('list',data.get('records')))
|
|
total=data.get('total',data.get('count'))
|
|
require(isinstance(total,int) and isinstance(rows,list) and total==len(rows),'incomplete_forward_inventory')
|
|
require(not data.get('hasMore') and not data.get('nextPage'),'paginated_inventory_requires_review')
|
|
else:rows=data
|
|
require(isinstance(rows,list),'forward_inventory_unknown')
|
|
result=[{k:item.get(k) for k in FIELDS} for item in rows]
|
|
require(all(type(x['id']) is int and x['id']>0 for x in result),'invalid_forward_identity')
|
|
require(len({x['id'] for x in result})==len(result),'duplicate_forward_identity')
|
|
return sorted(result,key=lambda x:x['id'])
|
|
def captcha_contract(source):
|
|
match=re.search(r'const checkCaptcha\s*=.*?network_default\.(post|get)\("([^"\n]+)"',source)
|
|
require(match is not None,'captcha_contract_unknown')
|
|
return match[1].upper(),'/'+match[2].lstrip('/')
|
|
def validate_request(request):
|
|
require(set(request)=={'batch_id','backup_root','relay_host','tunnel_id','expected_user_id','expected_before_count','expected_before_sha256','rules'},'request_fields_unknown')
|
|
require(re.fullmatch(r'[a-z0-9-]+',request['batch_id'] or ''),'batch_identity_unknown')
|
|
require(re.fullmatch(r'/root/codex-backups/fuc-xb/[a-z0-9-]+/relay',request['backup_root'] or ''),'unsafe_backup_path')
|
|
require(re.fullmatch(r'[a-z0-9.-]+',request['relay_host'] or ''),'unsafe_relay_host')
|
|
for key in ['tunnel_id','expected_user_id','expected_before_count']:require(type(request[key]) is int and request[key]>0,'invalid_request_identity')
|
|
require(re.fullmatch(r'[0-9a-f]{64}',request['expected_before_sha256'] or ''),'frozen_inventory_digest_required')
|
|
rules=request['rules'];require(isinstance(rules,list) and rules,'empty_rule_request')
|
|
for rule in rules:
|
|
require(set(rule)=={'name','port','address','listen_port','old_port'},'rule_fields_unknown')
|
|
require(re.fullmatch(r'fuc-xb-[a-z0-9-]+-anytls',rule['name'] or ''),'unsafe_rule_name')
|
|
require(ipaddress.ip_address(rule['address']).version==4,'ipv4_target_required')
|
|
for key in ['port','listen_port']:require(type(rule[key]) is int and 1024<=rule[key]<=65535,'unsafe_rule_port')
|
|
if rule['old_port'] is not None:require(type(rule['old_port']) is int and 1024<=rule['old_port']<=65535,'unsafe_rule_port')
|
|
require(rule['port']!=rule['old_port'] and rule['listen_port']!=443,'old_port_collision')
|
|
for key in ['name','port','address']:require(len({x[key] for x in rules})==len(rules),'duplicate_candidate_rule')
|
|
def target(rule):return rule['address']+':'+str(rule['listen_port'])
|
|
def matches(row,rule,request):
|
|
expected=dict(name=rule['name'],tunnelId=request['tunnel_id'],inPort=rule['port'],inIp=request['relay_host']+':'+str(rule['port']),remoteAddr=target(rule),strategy='fifo',speedId=None,ipMaxConn=0,ipSpeedId=None,maxConn=0,proxyProtocol=0,proxyProtocolReceive=0,proxyProtocolSend=0,status=1,userId=request['expected_user_id'])
|
|
return all(row.get(k)==value for k,value in expected.items())
|
|
class RelayBatch:
|
|
def __init__(self,request,api,root):validate_request(request);self.request=request;self.api=api;self.root=Path(root)
|
|
def rows(self):
|
|
result=self.api('/forward/list',None);require(result.get('code')==0,'forward_list_failed');return normalized(result.get('data'))
|
|
def inspect(self,rows,journal):
|
|
request=self.request;rules=request['rules'];by_name={}
|
|
if journal:
|
|
require(journal['request_sha256']==digest(request) and journal['request']==request,'different_task_ownership')
|
|
baseline=journal['before']
|
|
require(len(baseline)==request['expected_before_count']and digest(baseline)==request['expected_before_sha256'],'frozen_journal_baseline_changed')
|
|
else:
|
|
require(len(rows)==request['expected_before_count'],'unexpected_initial_rule_count');require(digest(rows)==request['expected_before_sha256'],'frozen_original_inventory_changed');baseline=rows
|
|
for rule in rules:
|
|
collisions=[x for x in rows if x['name']==rule['name'] or str(x['inPort'])==str(rule['port']) or x['remoteAddr']==target(rule)]
|
|
if collisions:
|
|
require(len(collisions)==1 and matches(collisions[0],rule,request),'candidate_rule_conflict')
|
|
require(journal and rule['name'] in journal['intents'],'matching_rule_without_task_intent')
|
|
observed=journal['added'].get(rule['name'])
|
|
require(observed is None or observed==collisions[0],'owned_rule_changed')
|
|
by_name[rule['name']]=collisions[0]
|
|
elif journal:
|
|
require(rule['name'] not in journal['added'],'owned_rule_disappeared')
|
|
require(rule['name'] not in journal['intents'],'unknown_create_outcome_requires_explicit_review')
|
|
if rule['old_port'] is None:
|
|
# Explicit absence is an ownership assertion, not an optional check.
|
|
# Check every rule, including other users/tunnels, in both snapshots.
|
|
for inventory in (baseline,rows):
|
|
require(not any(x['remoteAddr']==rule['address']+':443' for x in inventory),'unexpected_original_443_rule')
|
|
else:
|
|
original=[x for x in baseline if str(x['inPort'])==str(rule['old_port']) and x['remoteAddr']==rule['address']+':443' and x['tunnelId']==request['tunnel_id'] and x['userId']==request['expected_user_id']]
|
|
require(len(original)==1,'original_443_rule_missing')
|
|
added_ids={x['id'] for x in by_name.values()}
|
|
require(normalized([x for x in rows if x['id'] not in added_ids])==baseline,'original_rule_inventory_changed')
|
|
return by_name
|
|
def run(self,apply=False):
|
|
path=self.root/'journal.json';require(not path.is_symlink(),'private_journal_required')
|
|
if self.root.exists():require(not self.root.is_symlink() and not self.root.stat().st_mode&0o077,'private_backup_required')
|
|
if path.exists():require(path.is_file() and not path.stat().st_mode&0o077,'private_journal_required')
|
|
journal=json.loads(path.read_text()) if path.exists() else None
|
|
current=self.rows();found=self.inspect(current,journal)
|
|
if not apply:return {'state':'ready' if len(found)==len(self.request['rules']) else 'absent','captured_at':int(time.time()),'new':list(found.values()),'before_count':len(journal['before']) if journal else len(current),'after_count':len(current),'writes':False,'request_sha256':digest(self.request)}
|
|
if journal is None:
|
|
require(digest(current)==self.request['expected_before_sha256'],'frozen_original_inventory_changed')
|
|
journal={'version':1,'request':self.request,'request_sha256':digest(self.request),'before':current,'intents':{},'added':{}}
|
|
atomic(path,journal) # Immutable initial before: never recaptured on recovery.
|
|
for rule in self.request['rules']:
|
|
current=self.rows();found=self.inspect(current,journal)
|
|
if rule['name'] in found:
|
|
journal['added'][rule['name']]=found[rule['name']];atomic(path,journal);continue
|
|
journal['intents'][rule['name']]={'payload':rule,'attempt':journal['intents'].get(rule['name'],{}).get('attempt',0)+1,'at':int(time.time())}
|
|
atomic(path,journal)
|
|
payload=dict(name=rule['name'],tunnelId=self.request['tunnel_id'],inPort=rule['port'],remoteAddr=target(rule),strategy='fifo',speedId=None,ipMaxConn=0,maxConn=0,proxyProtocol=0,proxyProtocolReceive=0,proxyProtocolSend=0)
|
|
result=self.api('/forward/create',payload) # Exactly once per observed-absent attempt; no network retry.
|
|
require(result.get('code')==0,'create_outcome_requires_probe')
|
|
found=self.inspect(self.rows(),journal);require(rule['name'] in found,'create_outcome_requires_probe')
|
|
journal['added'][rule['name']]=found[rule['name']];atomic(path,journal)
|
|
final=self.rows();found=self.inspect(final,journal)
|
|
require(len(found)==len(self.request['rules']),'incomplete_batch')
|
|
journal['state']='applied';journal['added']=found;atomic(path,journal)
|
|
return {'state':'applied','captured_at':int(time.time()),'request_sha256':digest(self.request),'before_count':len(journal['before']),'after_count':len(final),'old_rules_unchanged':True,'new':list(found.values())}
|
|
def pause_owned(self):
|
|
path=self.root/'journal.json';require(path.is_file()and not path.is_symlink(),'owned_journal_required')
|
|
journal=json.loads(path.read_text());request=self.request
|
|
require(journal['request']==request and journal['request_sha256']==digest(request),'different_task_ownership')
|
|
require(len(journal['before'])==request['expected_before_count']and digest(journal['before'])==request['expected_before_sha256'],'frozen_journal_baseline_changed')
|
|
require(journal.get('state')in ['applied','pausing','paused']and len(journal['added'])==len(request['rules']),'complete_owned_batch_required')
|
|
expected={x['id']:x for x in journal['added'].values()}
|
|
require(len(expected)==len(request['rules']),'owned_ids_not_unique')
|
|
def check(rows):
|
|
by_id={x['id']:x for x in rows}
|
|
require(normalized([x for x in rows if x['id']not in expected])==journal['before'],'original_rule_inventory_changed')
|
|
for ident,before in expected.items():
|
|
current=by_id.get(ident);require(current is not None,'owned_rule_disappeared')
|
|
require(current.get('status')in [0,1]and dict(current,status=1)==before,'owned_rule_changed')
|
|
return by_id
|
|
check(self.rows());journal['state']='pausing';atomic(path,journal)
|
|
for ident in expected:
|
|
current=check(self.rows())[ident]
|
|
if current['status']==0:continue
|
|
# Current frontend contract: POST /forward/pause {id}; never delete/reset.
|
|
journal.setdefault('pause_intents',{})[str(ident)]=int(time.time());atomic(path,journal)
|
|
result=self.api('/forward/pause',{'id':ident});require(result.get('code')==0,'pause_outcome_requires_probe')
|
|
require(check(self.rows())[ident]['status']==0,'pause_not_confirmed')
|
|
after=check(self.rows());require(all(after[i]['status']==0 for i in expected),'pause_incomplete')
|
|
journal['state']='paused';atomic(path,journal)
|
|
return {'state':'paused','owned_ids':sorted(expected),'old_rules_unchanged':True,'new_rules_only':True}
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self,*args,**kwargs):raise Blocked('redirect_requires_review')
|
|
class API:
|
|
def __init__(self):self.base='https://hw.lshan.eu.org';self.token=None;self.opener=urllib.request.build_opener(NoRedirect())
|
|
def call(self,path,data=None,method='POST'):
|
|
require(re.fullmatch(r'/[A-Za-z0-9/_-]+',path),'unexpected_api_path')
|
|
headers={'Content-Type':'application/json','Accept':'application/json'}
|
|
if self.token:headers['Authorization']=self.token
|
|
raw=json.dumps(data or {}).encode() if method=='POST' else None
|
|
with self.opener.open(urllib.request.Request(self.base+'/api/v1'+path,data=raw,headers=headers,method=method),timeout=40) as response:return json.load(response)
|
|
def login(self,auth):
|
|
with self.opener.open(self.base+'/assets/index-C6H-F141-v186.js',timeout=30) as response:source=response.read().decode()
|
|
method,path=captcha_contract(source)
|
|
check=self.call(path,method=method);require(check.get('code')==0 and check.get('data')==0,'mandatory_captcha_requires_user')
|
|
result=self.call('/user/login',dict(username=auth['username'],password=auth['password'],captchaId=''));auth.clear()
|
|
require(result.get('code')==0,'normal_login_failed');require(not result['data'].get('requirePasswordChange'),'password_change_required')
|
|
self.token=result['data'].get('token');require(isinstance(self.token,str) and self.token,'login_token_missing')
|
|
def main():
|
|
data=json.load(sys.stdin);request=data.pop('request');apply=data.pop('apply',False);operation=data.pop('operation','apply'if apply else'probe');require(type(apply) is bool and operation in ['probe','apply','pause'],'explicit_operation_required');require(set(data)=={'username','password'},'authentication_fields_unknown');validate_request(request)
|
|
require(apply==(operation in ['apply','pause']),'operation_apply_flag_conflict')
|
|
api=API();api.login(data);root=Path(request['backup_root'])
|
|
# Applying owns a task-private lock and journal. A pure probe creates no files.
|
|
if apply:
|
|
root.mkdir(parents=True,mode=0o700,exist_ok=True);require(not root.is_symlink() and not root.stat().st_mode&0o077,'private_backup_required')
|
|
lock=root/'operation.lock';require(not lock.is_symlink(),'unsafe_lock')
|
|
with lock.open('a') as handle:
|
|
os.chmod(lock,0o600);fcntl.flock(handle,fcntl.LOCK_EX);batch=RelayBatch(request,api.call,root);result=batch.pause_owned()if operation=='pause'else batch.run(True)
|
|
else:result=RelayBatch(request,api.call,root).run(False)
|
|
print(json.dumps(result))
|
|
if __name__=='__main__':
|
|
try:main()
|
|
except Exception as error:
|
|
print(json.dumps({'state':'blocked','reason':str(error) if type(error) is Blocked else 'Remote outcome unknown; inspect protected journal and probe, never blindly replay','error_type':type(error).__name__}));raise SystemExit(2)
|