Files
LookingGlass/idd/LGIddHelper/CRegistrySettings.cpp
Geoffrey McRae f9ffce528a [idd] helper: run interactive process as desktop user
Explorer file copies were invisible to the Helper because the service
launched its child with a duplicate of the LocalSystem token and changed
only TokenSessionId. The child therefore remained a System-integrity
process. Windows filtered Explorer's file clipboard formats across that
integrity boundary. Basic text and bitmap formats continued to work.

Keep only the SCM service privileged. Obtain the active session user's
primary token with WTSQueryUserToken. For elevated accounts, prefer the
linked limited token. Validate its session and security properties.
Build the user environment and launch the interactive Helper on
WinSta0\Default. Gate Helper activation until the service has rechecked
the active session and registered the clipboard authority.

Use random lifetime, stop, and activation objects owned by the service.
Give the target logon SID synchronization access only. Recheck the
active console session and service state before activation. Make the
lifetime mutex terminate the Helper if the service exits unexpectedly.
Restart it when the active session, IDD host, or authority changes.

Replace the old process-handle mapping transfer with a device-bound
authority protocol on the LGIdd device interface. The service verifies
the exact driver host instance, duplicates only section map rights into
that process, and registers the session, mapping identifier, and handle.
Bind authority lifetime to its WDF file object, revoke it synchronously
on cleanup, and poll the driver host identity while the child is active.

Restrict the device stack to SYSTEM and isolate LGIdd in a unique UMDF
device group. Restrict the shared section to SYSTEM and the target logon
SID. Apply a medium mandatory label that prevents low-integrity readers
and writers. Map it with read/write rights instead of all access.

Give each clipboard mapping a second random authority identifier. Store
it only inside the logon-SID-protected mapping and send it in the
mandatory HELLO. LGIdd matches it against the service-injected mapping.
This authenticates the user Helper without the unsupported UMDF call to
GetNamedPipeClientSessionId. Have the Helper verify that its pipe server
is in session zero.

Extend the pipe endpoint with bounded authentication reads, cancellable
overlapped I/O, periodic authorization checks, and explicit disconnects.
Serialize authority changes with clipboard attach and detach. Prevent
stale cleanup from tearing down a replacement mapping. Disconnect the
user pipe immediately when its owning authority is revoked.

Run clipboard, OLE, display, configuration, and file access in the
user's interactive process. Retain its process token for worker-thread
file operations instead of querying and impersonating the desktop user
from a System process. Store Helper logs in LocalAppData and grant only
the registry rights needed by interactive configuration and UMDF.

Keep immediate, stage-specific Win32 and HRESULT diagnostics throughout
clipboard capture. Probe CF_HDROP while holding the Win32 clipboard and
enumerate the OLE object's advertised file formats. Validate returned
storage and fall back to Shell item paths when direct retrieval fails.
Validate clipboard sequence changes and defer retries during contention
without publishing incomplete clipboard state.

Complete the 1 MiB transfer work with full-sized Windows copy buffers.
Use full-sized FUSE reads and retain the named 64 KiB X11 chunk limit.
Validate the user-writable mapping with CClipboardRing before attaching.

The pipe, mapping, and authority protocols change together. LGIdd.dll,
the INF, and LGIddHelper.exe must be rebuilt and installed as one
matching set.
2026-08-15 00:42:24 +10:00

268 lines
7.0 KiB
C++

/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CRegistrySettings.h"
#include <optional>
#include <regex>
#include <CDebug.h>
#include "DefaultDisplayModes.h"
#include "RefreshRate.h"
#define LGIDD_REGKEY L"SOFTWARE\\LookingGlass\\IDD"
const DWORD DEFAULT_REFRESH = 120000;
CRegistrySettings::CRegistrySettings() : hKey(nullptr) {}
CRegistrySettings::~CRegistrySettings()
{
if (hKey)
RegCloseKey(hKey);
}
LSTATUS CRegistrySettings::open(bool writable)
{
HKEY key;
const REGSAM access = KEY_QUERY_VALUE |
(writable ? KEY_SET_VALUE : 0);
LSTATUS result = RegOpenKeyEx(
HKEY_LOCAL_MACHINE, LGIDD_REGKEY, 0, access, &key);
if (result == ERROR_SUCCESS)
hKey = key;
return result;
}
template<class T>
static std::basic_string<T> trim(const std::basic_string<T> &s)
{
size_t b = 0, e = s.size();
while (b < e && iswspace(s[b]))
++b;
while (e > b && iswspace(s[e - 1]))
--e;
return s.substr(b, e - b);
}
static std::wregex displayMode(
L"(\\d+)x(\\d+)@(\\d+(?:\\.\\d{1,3})?)(\\*)?");
static std::optional<DisplayMode> parseDisplayMode(const std::wstring &str)
{
std::wstring trimmed = trim(str);
std::wsmatch match;
if (!std::regex_match(trimmed, match, displayMode))
return {};
DisplayMode mode;
mode.width = std::stoul(match[1]);
mode.height = std::stoul(match[2]);
if (!LGParseRefreshRate(match[3], mode.refreshMilliHz))
return {};
mode.preferred = match[4] == L"*";
return mode;
}
std::vector<DisplayMode> CRegistrySettings::getDefaultModes()
{
auto defaultRefresh = getDefaultRefresh();
const unsigned refreshMilliHz =
defaultRefresh ? *defaultRefresh : DEFAULT_REFRESH;
std::vector<DisplayMode> result;
for (int i = 0; i < ARRAYSIZE(DefaultDisplayModes); ++i)
{
DisplayMode mode;
mode.width = DefaultDisplayModes[i][0];
mode.height = DefaultDisplayModes[i][1];
mode.refreshMilliHz = refreshMilliHz;
mode.preferred = i == DefaultPreferredDisplayMode;
result.emplace_back(mode);
}
return result;
}
std::optional<std::vector<DisplayMode>> CRegistrySettings::getModes()
{
LSTATUS status;
DWORD type = 0, cb = 0;
status = RegGetValue(hKey, nullptr, L"Modes", RRF_RT_REG_MULTI_SZ, &type, nullptr, &cb);
switch (status)
{
case ERROR_SUCCESS:
break;
case ERROR_FILE_NOT_FOUND:
return getDefaultModes();
default:
DEBUG_ERROR_HR(status, "RegGetValue(Modes) length computation");
return {};
}
LPWSTR buf = (LPWSTR) malloc(cb);
if (!buf)
{
DEBUG_ERROR("Failed to allocate memory for RegGetValue(Modes)");
return {};
}
status = RegGetValueW(hKey, nullptr, L"Modes", RRF_RT_REG_MULTI_SZ, &type, buf, &cb);
if (status != ERROR_SUCCESS)
{
DEBUG_ERROR_HR(status, "RegGetValue(Modes) read");
free(buf);
return {};
}
std::vector<DisplayMode> result;
for (LPWSTR s = buf; *s; s += wcslen(s) + 1)
{
auto mode = parseDisplayMode(s);
if (mode.has_value())
result.emplace_back(std::move(mode.value()));
}
free(buf);
return result;
}
LSTATUS CRegistrySettings::setModes(const std::vector<DisplayMode> &modes)
{
std::wstring serialized;
for (auto mode : modes)
{
serialized.append(mode.toString());
serialized.push_back('\0');
}
return RegSetValueEx(hKey, L"Modes", 0, REG_MULTI_SZ, (PBYTE)serialized.c_str(),
(DWORD)(serialized.length() + 1) * sizeof(wchar_t));
}
std::wstring DisplayMode::toString()
{
std::wstring serialized;
serialized.append(std::to_wstring(width));
serialized.push_back('x');
serialized.append(std::to_wstring(height));
serialized.push_back('@');
serialized.append(LGFormatRefreshRate(refreshMilliHz));
if (preferred)
serialized.push_back('*');
return serialized;
}
std::optional<DWORD> CRegistrySettings::getDefaultRefresh()
{
DWORD type = 0;
DWORD size = 0;
LSTATUS status = RegQueryValueExW(
hKey, L"DefaultRefresh", nullptr, &type, nullptr, &size);
if (status == ERROR_FILE_NOT_FOUND)
return DEFAULT_REFRESH;
if (status != ERROR_SUCCESS)
{
DEBUG_ERROR_HR(status, "RegQueryValueEx(DefaultRefresh)");
return {};
}
if (type == REG_DWORD && size == sizeof(DWORD))
{
DWORD refresh = 0;
status = RegQueryValueExW(hKey, L"DefaultRefresh", nullptr, &type,
(LPBYTE)&refresh, &size);
if (status == ERROR_SUCCESS && refresh >= 24 && refresh <= 1000)
return refresh * 1000;
}
else if ((type == REG_SZ || type == REG_EXPAND_SZ) && size &&
size % sizeof(wchar_t) == 0)
{
std::vector<wchar_t> value(size / sizeof(wchar_t) + 1, L'\0');
status = RegQueryValueExW(hKey, L"DefaultRefresh", nullptr, &type,
(LPBYTE)value.data(), &size);
if (status == ERROR_SUCCESS)
{
unsigned refreshMilliHz;
if (LGParseRefreshRate(value.data(), refreshMilliHz))
return refreshMilliHz;
}
}
DEBUG_ERROR("Invalid DefaultRefresh value");
return {};
}
LSTATUS CRegistrySettings::setDefaultRefresh(DWORD refreshMilliHz)
{
const std::wstring value = LGFormatRefreshRate(refreshMilliHz);
return RegSetValueExW(hKey, L"DefaultRefresh", 0, REG_SZ,
(const BYTE *)value.c_str(),
(DWORD)((value.size() + 1) * sizeof(wchar_t)));
}
std::optional<bool> CRegistrySettings::getNoGPU()
{
DWORD result, cbData = sizeof result;
LSTATUS status = RegGetValue(hKey, nullptr, L"NoGPU", RRF_RT_REG_DWORD, nullptr, &result, &cbData);
switch (status)
{
case ERROR_SUCCESS:
return !!result;
case ERROR_FILE_NOT_FOUND:
return false;
default:
DEBUG_ERROR_HR(status, "RegGetValue(NoGPU)");
return {};
}
}
LSTATUS CRegistrySettings::setNoGPU(bool noGPU)
{
DWORD dwValue = noGPU;
return RegSetValueEx(hKey, L"NoGPU", 0, REG_DWORD, (LPBYTE)&dwValue, sizeof(DWORD));
}
std::optional<bool> CRegistrySettings::getExclusiveMonitor()
{
DWORD result, cbData = sizeof result;
LSTATUS status = RegGetValue(hKey, nullptr, L"ExclusiveMonitor", RRF_RT_REG_DWORD, nullptr, &result, &cbData);
switch (status)
{
case ERROR_SUCCESS:
return !!result;
case ERROR_FILE_NOT_FOUND:
return true;
default:
DEBUG_ERROR_HR(status, "RegGetValue(ExclusiveMonitor)");
return {};
}
}
LSTATUS CRegistrySettings::setExclusiveMonitor(bool exclusive)
{
DWORD dwValue = exclusive;
return RegSetValueEx(hKey, L"ExclusiveMonitor", 0, REG_DWORD, (LPBYTE)&dwValue, sizeof(DWORD));
}