fix: restrict explicit force release to verified user document clients

This commit is contained in:
阿白叔 committed 2026-11-05 23:31:35 +08:00
1 parent e4266ae88c
commit e53c5d0e92
18 files changed
+2090 -1623

No files matched your search

+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.3b1"
__version__ = "0.2.4b1"
+64 -2
View File
@@ -15,6 +15,23 @@ _NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe',
'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES
_WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'}
_WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
_FORCE_CLIENT_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'viewdraw.exe', 'icdbprojectbackup.exe'}
def force_block_reason(row):
"""A library path proves scope, never exclusive ownership of a server."""
if row.get('scope_confirmed') is not True:
return '进程归属未确认,不允许强制结束'
name = str(row.get('name', '')).casefold()
if name not in _FORCE_CLIENT_NAMES:
return '服务器或其他受保护进程仅供观察,不允许强制结束'
if (not row.get('created_handle') or not row.get('image')
or Path(row['image']).name.casefold() != name):
return '客户端身份未确认,不允许强制结束'
if (row.get('force_user_confirmed') is not True or not row.get('owner_sid')
or not isinstance(row.get('session_id'), int)):
return '未确认属于当前用户和 Windows 会话,不允许强制结束'
return ''
@contextmanager
@@ -45,7 +62,30 @@ def _handle_identity(handle):
def _process_identity(row):
with _process_handle(row['pid']) as handle:
return _handle_identity(handle)
identity = _handle_identity(handle)
try:
identity.update(_force_ownership(handle, row['pid']))
except Exception as error:
identity.update(force_user_confirmed=False, owner_error=str(error))
return identity
def _force_ownership(handle, pid):
import win32api, win32con, win32process, win32security, win32ts
if win32process.GetProcessId(handle) != pid:
raise ValueError('进程身份已变化')
def owner(process):
token = win32security.OpenProcessToken(process, win32con.TOKEN_QUERY)
try:
return win32security.ConvertSidToStringSid(
win32security.GetTokenInformation(token, win32security.TokenUser)[0])
finally:
token.Close()
sid = owner(handle)
session = win32ts.ProcessIdToSessionId(pid)
return {'owner_sid': sid, 'session_id': session, 'force_user_confirmed':
sid == owner(win32api.GetCurrentProcess())
and session == win32ts.ProcessIdToSessionId(os.getpid())}
def _process_windows(pids):
@@ -191,6 +231,10 @@ def inspect_residual_sessions(library, *, block_names=()):
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
item['force_block_reason'] = force_block_reason(item)
item['force_allowed'] = not item['force_block_reason']
if item['force_block_reason']:
item['detail'] += ';'+item['force_block_reason']
sessions.append(item)
previous = []
marker = blocker_path(library)
@@ -253,15 +297,21 @@ def _force_close(row, *, stop=None):
import win32api, win32con, win32event
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if reason := force_block_reason(row):
return {'release_status': 'WAITING', 'detail': reason}
with _process_handle(row['pid'], terminate=True) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已退出'}
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'}
ownership = _force_ownership(handle, row['pid'])
if (not ownership['force_user_confirmed'] or
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
win32api.TerminateProcess(handle, 1)
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
return {'release_status': 'RELEASED' if exited else 'WAITING',
'detail': '已强制结束,工程需重新检查' if exited else '已请求结束,等待退出'}
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
def _finish_library_release(library, evidence):
@@ -277,6 +327,16 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
root.mkdir(parents=True)
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
if force:
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**row, 'force_allowed': not force_block_reason(row),
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
with consent_path.open('x', encoding='utf-8') as stream:
json.dump(consent, stream, ensure_ascii=False, indent=2)
stream.flush(); os.fsync(stream.fileno())
result['consent_path'] = str(consent_path)
fresh = {r['pid']: r for r in query_process_snapshot()}
# Close native children first, so their supervisors can finish and drop leases.
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
@@ -292,6 +352,8 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(original)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
except Exception as error:
File diff suppressed because it is too large. Load diff
@@ -7,6 +7,7 @@ from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushB
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
from .workers import ServiceWorker
from ..residual_sessions import force_block_reason
class ResidualReleaseDialog(QDialog):
@@ -39,7 +40,7 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button = QPushButton('重新检查')
self.confirm_button = QPushButton('确认释放')
self.prompt_button = QPushButton('处理保存提示…')
self.force_button = QPushButton('强制结束所列会话…')
self.force_button = QPushButton('强制结束客户端…')
self.force_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.close_button = QPushButton('关闭')
@@ -71,7 +72,7 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button.setEnabled(True)
self.confirm_button.setEnabled(self.plan is not None)
self.force_button.setEnabled(bool(self.plan and any(
r.get('scope_confirmed', True) for r in self.plan['sessions'])))
not force_block_reason(r) for r in self.plan['sessions'])))
self.close_button.setText('关闭')
self._update_prompt()
if self._refresh_after:
@@ -132,11 +133,12 @@ class ResidualReleaseDialog(QDialog):
def force_release(self):
if self.busy or not self.plan or not self.plan['sessions']: return
targets = [r for r in self.plan['sessions'] if r.get('scope_confirmed', True)]
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
if not targets: return
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
answer = QMessageBox.warning(self, '强制结束会话',
'将强制结束以下进程,未保存的更改会丢失,正在写入的工程可能需要恢复。\n\n'+names+
answer = QMessageBox.warning(self, '强制结束客户端',
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
if answer == QMessageBox.Yes: self.confirm_release(force=True)