Fix(server): stop at startup when the process runs at Low integrity

An exe carrying a Low integrity label makes Windows downgrade the process
token, so HKCU reads/writes and %TEMP% logging all fail silently: the
settings dialog shows defaults, saving does nothing, and no log file is
ever written. Nothing in the UI hints at the real cause.

- Read TokenIntegrityLevel on startup and abort when below Medium
- Print the icacls fix command; Yes copies it to the clipboard
- Never fall through into the main window: running at Low IL is useless
- Keep the service-spawned agent silent, otherwise the 10-second relaunch
  loop turns the dialog into a flood
- Do not try runas: with UAC approval mode off it is a no-op and the child
  inherits Low, so icacls fails with "cannot assign the specified label"
- Add en_US / zh_TW / de_DE translations

The check has to run before both the UAC relaunch and the service self-heal.
Placed after HandleServiceCommandLine, a double-click installs/starts the
service, returns TRUE and exits, so the dialog could only come from the
service-spawned agent - which stays silent to avoid a flood, and the user
saw nothing at all. Placed after LaunchAsAdmin, a Low process without admin
rights loops forever, because runas spawns a child that is still Low.
Service commands (-service/-install/-uninstall) are exempted so the service
can still be installed and removed.

Co-Authored-By: DeepSeek-V4.1-Flash
This commit is contained in:
yuanyuanxiangandDeepSeek-V4.1-Flash committed 2026-11-15 11:21:58 +01:00
1 parent 7faca2c01b
commit d987941e57
4 files changed
+166 -13

No files matched your search

+151 -13
View File
@@ -328,6 +328,18 @@ static BOOL IsAgentMode()
return cmdLine.Find(_T("-agent")) != -1;
}
// 是否为服务相关的命令行。
// 这几个分支由 HandleServiceCommandLine 自己处理,低完整性检查必须放行 ——
// 否则服务装不上也卸不掉,等于把唯一的补救手段也堵死了。
static bool IsServiceRelatedCommand()
{
CString cmdLine = ::GetCommandLine();
cmdLine.MakeLower();
return cmdLine.Find(_T("-service")) != -1
|| cmdLine.Find(_T("-install")) != -1
|| cmdLine.Find(_T("-uninstall")) != -1;
}
// CMy2015RemoteApp 初始化
BOOL IsRunningAsAdmin()
@@ -373,6 +385,116 @@ BOOL LaunchAsAdmin(const char* szFilePath, const char* verb)
return ShellExecuteExA(&shExecInfo);
}
// 取当前进程的完整性级别 RID(Low=0x1000 / Medium=0x2000 / High=0x3000)
// 失败返回 0(此时调用方按"未知"处理,不做任何提示)
static DWORD GetProcessIntegrityRid()
{
DWORD dwRid = 0;
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
return 0;
}
BYTE buf[256] = { 0 };
DWORD cbSize = sizeof(buf);
if (GetTokenInformation(hToken, TokenIntegrityLevel, buf, cbSize, &cbSize)) {
TOKEN_MANDATORY_LABEL* pTml = (TOKEN_MANDATORY_LABEL*)buf;
if (pTml->Label.Sid != NULL) {
DWORD nSub = *GetSidSubAuthorityCount(pTml->Label.Sid);
if (nSub > 0) {
dwRid = *GetSidSubAuthority(pTml->Label.Sid, nSub - 1);
}
}
}
CloseHandle(hToken);
return dwRid;
}
// 把文本放进剪贴板(工程是 MultiByte,用 CF_TEXT)
static void CopyTextToClipboard(const CString& text)
{
if (!::OpenClipboard(NULL)) {
return;
}
::EmptyClipboard();
int nLen = (text.GetLength() + 1) * sizeof(TCHAR);
HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, nLen);
if (hMem != NULL) {
void* pDst = ::GlobalLock(hMem);
if (pDst != NULL) {
memcpy(pDst, (LPCTSTR)text, nLen);
::GlobalUnlock(hMem);
if (::SetClipboardData(CF_TEXT, hMem) != NULL) {
hMem = NULL; // 所有权已交给剪贴板,不能再释放
}
}
if (hMem != NULL) {
::GlobalFree(hMem);
}
}
::CloseClipboard();
}
// 低完整性自检
//
// 返回值:true = 允许继续启动;false = 应当中止启动
//
// 现象:exe 文件带 Low 完整性标签时,Windows 会把进程 IL 压到 Low,
// 即使「以管理员身份运行」也一样(服务+代理模式同样无效),
// 表现为「设置全是默认值、保存无效」。
//
// 为什么程序自己修不了:
// 进程 IL 在创建后不可更改,Low 进程又受 no-write-up 限制,连自己
// exe 的标签都改不了(实测报「指明特定的安全 ID 可能不能作为对象
// 的标签分配」);runas 提权同样无效(UAC 批准模式关闭时是空操作,
// 子进程继承 Low)。所以只能把修复命令交给用户在管理员命令行执行。
//
// 为什么返回 false 而不是继续启动:带着 Low IL 进主界面没有任何意义 ——
// 配置全是默认值、改了也存不下来,用户只会以为是别的 bug。
//
// 服务实例(-service)走不到这里:它在 HandleServiceCommandLine 就返回了。
// 代理模式(-agent-asuser)由服务每 10 秒拉起一次,弹窗会变成弹窗轰炸,
// 所以只记日志、直接退出。
static bool CheckLowIntegrity(bool bAgentMode)
{
DWORD dwRid = GetProcessIntegrityRid();
if (dwRid == 0 || dwRid >= SECURITY_MANDATORY_MEDIUM_RID) {
return true; // Medium 及以上,正常
}
char exePath[MAX_PATH] = { 0 };
GetModuleFileNameA(NULL, exePath, MAX_PATH);
Mprintf("[完整性] 警告:进程完整性级别为 Low(RID=0x%X),"
"注册表与日志写入会失败。exe=%s\n", dwRid, exePath);
if (bAgentMode) {
return false; // 服务拉起的实例:静默退出,避免反复弹窗
}
CString fixCmd;
fixCmd.Format(_T("icacls \"%s\" /setintegritylevel M"), exePath);
CString msg;
msg.Format(_TR(
"本程序运行在「低完整性」模式下,部分功能会异常。\n\n"
"请以管理员身份打开命令提示符,执行:\n\n"
" %s\n\n"
"执行后重新启动本程序。\n\n"
"点「是」复制上面的命令,点「否」关闭。"), (LPCTSTR)fixCmd);
if (::MessageBox(NULL, msg, _TR("完整性级别受限"),
MB_ICONWARNING | MB_YESNO) == IDYES) {
CopyTextToClipboard(fixCmd);
::MessageBox(NULL,
_TR("修复命令已复制到剪贴板。\n\n"
"请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。"),
_TR("已复制"), MB_ICONINFORMATION | MB_OK);
}
return false; // 无论点是还是否,都不继续启动
}
BOOL CMy2015RemoteApp::ProcessZstaCmd()
{
// 检查是否已注册右键菜单
@@ -510,6 +632,35 @@ BOOL CMy2015RemoteApp::InitInstance()
// 代理模式由服务管理,不应再次请求管理员权限提升
// 否则会导致:1) 原进程正常退出(exitCode=0)不被视为崩溃 2) 被提升的进程脱离服务监控
BOOL isAgentMode = IsAgentMode();
// 设置线程区域为中文,确保 MBCS 程序在非中文系统上也能正确显示对话框中的中文
// 必须在创建任何对话框之前调用
SetChineseThreadLocale();
// 加载语言包(必须在显示任何文本之前)
// 内嵌资源支持 en_US 和 zh_TW,无需外部文件
auto lang = THIS_CFG.GetStr("settings", "Language", "en_US");
auto langDir = THIS_CFG.GetStr("settings", "LangDir", "./lang");
langDir = langDir.empty() ? "./lang" : langDir;
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
// 低完整性自检 —— 必须排在「提权」和「服务自愈」之前。
// 1) 排在 HandleServiceCommandLine 之后:双击时程序会先把服务装好/启动,
// 然后自己 return FALSE 退出,提示只能由服务拉起的 -agent-asuser 弹出来;
// 而 agent 为了防轰炸是静默的,结果就是「双击没反应、一个字都不提示」。
// 2) 排在 LaunchAsAdmin 之后:Low 下 runas 是空操作,提权出来的子进程依然是
// Low,会陷入「弹 UAC → 还是 Low → 再弹 UAC」的死循环。
// 服务相关命令行(-service/-install/-uninstall)放行,交给下面处理。
if (!IsServiceRelatedCommand()) {
if (!CheckLowIntegrity(isAgentMode != FALSE)) {
Mprintf("[InitInstance] 低完整性,已中止启动。\n");
return FALSE;
}
}
// 普通用户提权(低完整性已在上面拦下,走到这里说明 IL 正常)
if (runNormal != 1 && !isAgentMode && !IsRunningAsAdmin() && LaunchAsAdmin(curFile, "runas")) {
Mprintf("[InitInstance] 程序没有管理员权限,用户选择以管理员身份重新运行。\n");
return FALSE;
@@ -534,19 +685,6 @@ BOOL CMy2015RemoteApp::InitInstance()
if (pfn) pfn(L"YAMA");
}
// 设置线程区域为中文,确保 MBCS 程序在非中文系统上也能正确显示对话框中的中文
// 必须在创建任何对话框之前调用
SetChineseThreadLocale();
// 加载语言包(必须在显示任何文本之前)
// 内嵌资源支持 en_US 和 zh_TW,无需外部文件
auto lang = THIS_CFG.GetStr("settings", "Language", "en_US");
auto langDir = THIS_CFG.GetStr("settings", "LangDir", "./lang");
langDir = langDir.empty() ? "./lang" : langDir;
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
// 创建并显示启动画面
CSplashDlg* pSplash = new CSplashDlg();
pSplash->Create(NULL);