[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.
This commit is contained in:
Geoffrey McRae
2026-08-15 00:11:01 +10:00
parent e40dc19c7e
commit f9ffce528a
35 changed files with 2803 additions and 665 deletions

View File

@@ -22,7 +22,6 @@
#include <ShlObj.h>
#include <strsafe.h>
#include <WtsApi32.h>
#include <algorithm>
#include <cstring>
@@ -41,7 +40,7 @@ namespace
static constexpr uint64_t WINDOWS_EPOCH_TICKS =
UINT64_C(116444736000000000);
static constexpr size_t COPY_BUFFER_BYTES =
static_cast<size_t>(64U) * 1024U;
KVMFR_CLIPBOARD_FILE_READ_BYTES;
class CThreadImpersonation final
{
@@ -165,14 +164,6 @@ namespace
{
token = nullptr;
winError = ERROR_SUCCESS;
DWORD sessionId = 0;
if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId))
{
winError = GetLastError();
error = TokenError(winError);
return false;
}
HANDLE processToken = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE,
&processToken))
@@ -182,83 +173,11 @@ namespace
return false;
}
HANDLE brokerToken = nullptr;
const bool brokerDuplicated = DuplicateTokenEx(processToken,
TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE, nullptr,
SecurityImpersonation, TokenImpersonation, &brokerToken) != FALSE;
const DWORD brokerError = brokerDuplicated ? ERROR_SUCCESS :
GetLastError();
CloseHandle(processToken);
if (!brokerDuplicated)
{
winError = brokerError;
error = TokenError(brokerError);
return false;
}
LUID privilege = {};
if (!LookupPrivilegeValueW(nullptr, SE_TCB_NAME, &privilege))
{
winError = GetLastError();
CloseHandle(brokerToken);
error = TokenError(winError);
return false;
}
TOKEN_PRIVILEGES privileges = {};
privileges.PrivilegeCount = 1;
privileges.Privileges[0].Luid = privilege;
privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
SetLastError(ERROR_SUCCESS);
const bool adjusted = AdjustTokenPrivileges(brokerToken, FALSE,
&privileges, 0, nullptr, nullptr) != FALSE;
const DWORD adjustError = GetLastError();
if (!adjusted || adjustError != ERROR_SUCCESS)
{
CloseHandle(brokerToken);
winError = adjustError ? adjustError : ERROR_ACCESS_DENIED;
error = TokenError(winError);
return false;
}
CThreadImpersonation brokerImpersonation(brokerToken);
if (!brokerImpersonation.Active())
{
const DWORD brokerImpersonationError = brokerImpersonation.Error();
CloseHandle(brokerToken);
winError = brokerImpersonationError;
error = TokenError(winError);
return false;
}
HANDLE sourceToken = nullptr;
const bool queried = WTSQueryUserToken(sessionId, &sourceToken) != FALSE;
const DWORD queryError = queried ? ERROR_SUCCESS : GetLastError();
if (!brokerImpersonation.Finish())
{
const DWORD restoreError = brokerImpersonation.Error();
if (sourceToken)
CloseHandle(sourceToken);
CloseHandle(brokerToken);
winError = restoreError;
error = TokenError(winError);
return false;
}
CloseHandle(brokerToken);
if (!queried || !sourceToken)
{
if (sourceToken)
CloseHandle(sourceToken);
winError = queryError ? queryError : ERROR_ACCESS_DENIED;
error = TokenError(winError);
return false;
}
const bool duplicated = DuplicateTokenEx(sourceToken,
const bool duplicated = DuplicateTokenEx(processToken,
TOKEN_QUERY | TOKEN_IMPERSONATE, nullptr, SecurityImpersonation,
TokenImpersonation, &token) != FALSE;
const DWORD duplicateError = duplicated ? ERROR_SUCCESS : GetLastError();
CloseHandle(sourceToken);
CloseHandle(processToken);
if (!duplicated)
{
winError = duplicateError;
@@ -1162,61 +1081,6 @@ namespace
};
}
class CClipboardUserImpersonation::Impl
{
public:
HANDLE token;
CThreadImpersonation impersonation;
explicit Impl(HANDLE token) :
token(token), impersonation(token)
{
}
~Impl()
{
impersonation.Finish();
CloseHandle(token);
}
};
CClipboardUserImpersonation::CClipboardUserImpersonation(
KVMFRClipboardFileError& error)
{
HANDLE token = nullptr;
if (!CaptureUserToken(token, error, m_error))
return;
try
{
m_impl = std::make_unique<Impl>(token);
}
catch (const std::bad_alloc&)
{
CloseHandle(token);
m_error = ERROR_OUTOFMEMORY;
error = KVMFR_CLIPBOARD_FILE_ERROR_NO_MEMORY;
return;
}
if (!m_impl->impersonation.Active())
{
m_error = m_impl->impersonation.Error();
m_impl.reset();
error = TokenError(m_error);
}
}
CClipboardUserImpersonation::~CClipboardUserImpersonation() = default;
bool CClipboardUserImpersonation::Active() const
{
return m_impl && m_impl->impersonation.Active();
}
DWORD CClipboardUserImpersonation::Error() const
{
return m_error;
}
CLocalClipboardFiles::CLocalClipboardFiles(HANDLE userToken) :
m_userToken(userToken)
{

View File

@@ -45,25 +45,6 @@ struct ClipboardRemoteFileEntry
std::wstring name;
};
class CClipboardUserImpersonation final
{
private:
class Impl;
std::unique_ptr<Impl> m_impl;
DWORD m_error = ERROR_SUCCESS;
public:
explicit CClipboardUserImpersonation(KVMFRClipboardFileError& error);
~CClipboardUserImpersonation();
CClipboardUserImpersonation(const CClipboardUserImpersonation&) = delete;
CClipboardUserImpersonation& operator=(
const CClipboardUserImpersonation&) = delete;
bool Active() const;
DWORD Error() const;
};
class CLocalClipboardFiles final
{
public:

View File

@@ -79,12 +79,6 @@ namespace
~ComScope() { if (initialized) CoUninitialize(); }
};
struct ClipboardDataObjectScope
{
IDataObject * object = nullptr;
~ClipboardDataObjectScope() { if (object) object->Release(); }
};
struct ClipboardStorageScope
{
STGMEDIUM medium = {};
@@ -106,7 +100,14 @@ namespace
~ClipboardTaskStringScope() { CoTaskMemFree(value); }
};
bool ClipboardDataObjectHasFileFormats(IDataObject * object,
enum ClipboardFileCandidate : uint32_t
{
CLIPBOARD_FILE_CANDIDATE_NONE = 0,
CLIPBOARD_FILE_CANDIDATE_HDROP = 1U << 0,
CLIPBOARD_FILE_CANDIDATE_SHELL = 1U << 1,
};
uint32_t ClipboardDataObjectFileCandidates(IDataObject * object,
DWORD sequence, HRESULT& enumError)
{
enumError = E_INVALIDARG;
@@ -116,7 +117,7 @@ namespace
"Failed to inspect local clipboard file formats: "
"stage=IDataObject sequence=%lu",
static_cast<unsigned long>(sequence));
return false;
return CLIPBOARD_FILE_CANDIDATE_NONE;
}
ClipboardComScope<IEnumFORMATETC> formats;
@@ -129,15 +130,17 @@ namespace
"Failed to inspect local clipboard file formats: "
"stage=IDataObject::EnumFormatEtc sequence=%lu",
static_cast<unsigned long>(sequence));
return false;
return CLIPBOARD_FILE_CANDIDATE_NONE;
}
HRESULT registrationError = S_OK;
const UINT shellIDList = RegisterClipboardFormatW(CFSTR_SHELLIDLIST);
if (!shellIDList)
{
const DWORD formatError = GetLastError();
DEBUG_ERROR_HR(formatError ? HRESULT_FROM_WIN32(formatError) :
E_UNEXPECTED,
registrationError = formatError ? HRESULT_FROM_WIN32(formatError) :
E_UNEXPECTED;
DEBUG_ERROR_HR(registrationError,
"Failed to inspect local clipboard file formats: "
"stage=RegisterClipboardFormatW(CFSTR_SHELLIDLIST) sequence=%lu",
static_cast<unsigned long>(sequence));
@@ -147,39 +150,44 @@ namespace
if (!fileDescriptor)
{
const DWORD formatError = GetLastError();
DEBUG_ERROR_HR(formatError ? HRESULT_FROM_WIN32(formatError) :
E_UNEXPECTED,
const HRESULT formatHRESULT = formatError ?
HRESULT_FROM_WIN32(formatError) : E_UNEXPECTED;
if (SUCCEEDED(registrationError))
registrationError = formatHRESULT;
DEBUG_ERROR_HR(formatHRESULT,
"Failed to inspect local clipboard file formats: "
"stage=RegisterClipboardFormatW(CFSTR_FILEDESCRIPTORW) sequence=%lu",
static_cast<unsigned long>(sequence));
}
uint32_t candidates = CLIPBOARD_FILE_CANDIDATE_NONE;
for (;;)
{
FORMATETC format = {};
ULONG fetched = 0;
enumError = formats.object->Next(1, &format, &fetched);
const bool files = fetched == 1U &&
(format.cfFormat == CF_HDROP ||
(shellIDList && format.cfFormat == shellIDList) ||
(fileDescriptor && format.cfFormat == fileDescriptor));
CoTaskMemFree(format.ptd);
if (files)
{
enumError = S_OK;
return true;
}
if (enumError == S_FALSE)
{
enumError = S_OK;
return false;
}
if (FAILED(enumError))
{
DEBUG_ERROR_HR(enumError,
"Failed to inspect local clipboard file formats: "
"stage=IEnumFORMATETC::Next sequence=%lu",
static_cast<unsigned long>(sequence));
return false;
CoTaskMemFree(format.ptd);
return candidates;
}
if (fetched == 1U)
{
if (format.cfFormat == CF_HDROP)
candidates |= CLIPBOARD_FILE_CANDIDATE_HDROP;
if ((shellIDList && format.cfFormat == shellIDList) ||
(fileDescriptor && format.cfFormat == fileDescriptor))
candidates |= CLIPBOARD_FILE_CANDIDATE_SHELL;
}
CoTaskMemFree(format.ptd);
if (enumError == S_FALSE)
{
enumError = registrationError;
return candidates;
}
if (!fetched)
{
@@ -188,11 +196,40 @@ namespace
"Failed to inspect local clipboard file formats: "
"stage=IEnumFORMATETC::Next sequence=%lu fetched=0",
static_cast<unsigned long>(sequence));
return false;
return candidates;
}
}
}
int CountClipboardFormatsLogged(const char * stage, DWORD sequence)
{
SetLastError(ERROR_SUCCESS);
const int count = CountClipboardFormats();
if (count)
return count;
const DWORD error = GetLastError();
if (error)
DEBUG_ERROR_HR(HRESULT_FROM_WIN32(error),
"Failed to count clipboard formats: stage=%s sequence=%lu",
stage, static_cast<unsigned long>(sequence));
return 0;
}
void FreeClipboardDrop(HGLOBAL memory, DWORD sequence)
{
SetLastError(ERROR_SUCCESS);
const HGLOBAL result = GlobalFree(memory);
if (!result)
return;
const DWORD error = GetLastError();
DEBUG_ERROR_HR(error ? HRESULT_FROM_WIN32(error) : E_UNEXPECTED,
"Failed to capture local clipboard files: "
"stage=GlobalFree(DROPFILES) sequence=%lu",
static_cast<unsigned long>(sequence));
}
HRESULT ClipboardFileHRESULT(KVMFRClipboardFileError error)
{
switch (error)
@@ -3281,32 +3318,24 @@ void CClipboardManager::HandleFileDataObject(UIWork& work)
m_ownedSequence = GetClipboardSequenceNumber();
}
bool CClipboardManager::OpenClipboardRetry(DWORD * error,
const char * stage, bool useWindow) const
HRESULT CClipboardManager::OpenClipboardRetry(const char * stage) const
{
HRESULT result = CLIPBRD_E_CANT_OPEN;
for (unsigned int attempt = 0; attempt != 8; ++attempt)
{
if (OpenClipboard(useWindow ? m_hwnd : nullptr))
{
if (error)
*error = ERROR_SUCCESS;
return true;
}
if (OpenClipboard(m_hwnd))
return S_OK;
const DWORD openError = GetLastError();
DEBUG_ERROR_HR(openError ? HRESULT_FROM_WIN32(openError) :
CLIPBRD_E_CANT_OPEN,
result = openError ? HRESULT_FROM_WIN32(openError) :
CLIPBRD_E_CANT_OPEN;
DEBUG_ERROR_HR(result,
"OpenClipboard failed: stage=%s attempt=%u",
stage ? stage : "unspecified", attempt + 1U);
stage, attempt + 1U);
if (attempt + 1U == 8U)
{
if (error)
*error = openError;
SetLastError(openError);
return false;
}
return result;
Sleep(5U << (std::min)(attempt, 5U));
}
return false;
return result;
}
bool CClipboardManager::IsOurClipboard()
@@ -3323,7 +3352,8 @@ bool CClipboardManager::IsOurClipboard()
}
if (!m_formatOrigin || !m_remoteGeneration ||
!IsClipboardFormatAvailable(m_formatOrigin) || !OpenClipboardRetry())
!IsClipboardFormatAvailable(m_formatOrigin) ||
FAILED(OpenClipboardRetry("IsOurClipboard")))
return false;
bool ours = false;
@@ -3383,26 +3413,10 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
return nullptr;
}
CClipboardUserImpersonation user(error);
if (!user.Active())
{
const DWORD userError = user.Error();
oleError = userError ? HRESULT_FROM_WIN32(userError) :
ClipboardFileHRESULT(error);
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: "
"stage=impersonate-interactive-user sequence=%lu rawFormats=%d "
"fileError=%u", static_cast<unsigned long>(sequence),
rawFormatCount, static_cast<unsigned int>(error));
return nullptr;
}
// Acquire the clipboard before probing CF_HDROP. Explorer can still hold
// the clipboard when WM_CLIPBOARDUPDATE is delivered, in which case an
// unlocked IsClipboardFormatAvailable probe can observe no formats.
DWORD openError = ERROR_SUCCESS;
if (!OpenClipboardRetry(&openError, "CaptureClipboardFiles(CF_HDROP)",
false))
if (FAILED(OpenClipboardRetry("CaptureClipboardFiles(CF_HDROP)")))
{
oleError = CLIPBRD_E_CANT_OPEN;
retryStage = "OpenClipboard";
@@ -3415,7 +3429,8 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
int openedRawFormatCount = 0;
if (GetClipboardSequenceNumber() == sequence)
{
openedRawFormatCount = CountClipboardFormats();
openedRawFormatCount = CountClipboardFormatsLogged(
"CaptureClipboardFiles(CF_HDROP)", sequence);
win32Candidate = IsClipboardFormatAvailable(CF_HDROP) != FALSE;
if (win32Candidate)
{
@@ -3463,14 +3478,19 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
static_cast<unsigned long>(GetClipboardSequenceNumber()));
}
if (!CloseClipboard())
const BOOL closed = CloseClipboard();
if (!closed)
{
const DWORD closeError = GetLastError();
DEBUG_ERROR_HR(closeError ? HRESULT_FROM_WIN32(closeError) :
CLIPBRD_E_CANT_CLOSE,
oleError = closeError ? HRESULT_FROM_WIN32(closeError) :
CLIPBRD_E_CANT_CLOSE;
error = closeError == ERROR_ACCESS_DENIED ?
KVMFR_CLIPBOARD_FILE_ERROR_ACCESS : KVMFR_CLIPBOARD_FILE_ERROR_IO;
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: stage=CloseClipboard "
"sequence=%lu rawFormats=%d",
static_cast<unsigned long>(sequence), rawFormatCount);
return nullptr;
}
if (files)
return files;
@@ -3488,7 +3508,7 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
return nullptr;
}
ClipboardDataObjectScope object;
ClipboardComScope<IDataObject> object;
oleError = OleGetClipboard(&object.object);
if (FAILED(oleError) || !object.object)
{
@@ -3503,66 +3523,94 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
return nullptr;
}
FORMATETC format = {
static_cast<CLIPFORMAT>(CF_HDROP),
nullptr,
DVASPECT_CONTENT,
-1,
TYMED_HGLOBAL,
};
ClipboardStorageScope storage;
const HRESULT hdropError = object.object->GetData(
&format, &storage.medium);
if (FAILED(hdropError))
HRESULT candidateError = S_OK;
const uint32_t candidates = ClipboardDataObjectFileCandidates(
object.object, sequence, candidateError);
const bool optimistic = FAILED(candidateError);
if (!optimistic && !win32Candidate &&
candidates == CLIPBOARD_FILE_CANDIDATE_NONE)
{
DEBUG_ERROR_HR(hdropError,
"Failed to capture local clipboard files: "
"stage=IDataObject::GetData(CF_HDROP) sequence=%lu rawFormats=%d",
static_cast<unsigned long>(sequence), rawFormatCount);
}
if (hdropError == CLIPBRD_E_CANT_OPEN)
{
oleError = hdropError;
retryStage = "IDataObject::GetData(CF_HDROP)";
error = KVMFR_CLIPBOARD_FILE_ERROR_NONE;
oleError = S_FALSE;
return nullptr;
}
if (SUCCEEDED(hdropError))
HRESULT hdropError = S_FALSE;
bool hdropAttempted = false;
if (optimistic || win32Candidate ||
(candidates & CLIPBOARD_FILE_CANDIDATE_HDROP))
{
storage.acquired = true;
if (storage.medium.tymed == TYMED_HGLOBAL && storage.medium.hGlobal)
hdropAttempted = true;
FORMATETC format = {
static_cast<CLIPFORMAT>(CF_HDROP),
nullptr,
DVASPECT_CONTENT,
-1,
TYMED_HGLOBAL,
};
ClipboardStorageScope storage;
hdropError = object.object->GetData(&format, &storage.medium);
if (FAILED(hdropError))
{
std::shared_ptr<CLocalClipboardFiles> files =
CLocalClipboardFiles::Capture(
static_cast<HDROP>(storage.medium.hGlobal), error);
if (files)
{
viaOLE = true;
oleError = S_OK;
return files;
}
oleError = ClipboardFileHRESULT(error);
DEBUG_ERROR_HR(oleError,
DEBUG_ERROR_HR(hdropError,
"Failed to capture local clipboard files: "
"stage=CLocalClipboardFiles::Capture(CF_HDROP/ole) sequence=%lu "
"rawFormats=%d fileError=%u",
static_cast<unsigned long>(sequence), rawFormatCount,
static_cast<unsigned int>(error));
return nullptr;
"stage=IDataObject::GetData(CF_HDROP) sequence=%lu rawFormats=%d",
static_cast<unsigned long>(sequence), rawFormatCount);
if (hdropError == CLIPBRD_E_CANT_OPEN)
{
oleError = hdropError;
retryStage = "IDataObject::GetData(CF_HDROP)";
return nullptr;
}
}
else
{
storage.acquired = true;
if (storage.medium.tymed != TYMED_HGLOBAL ||
!storage.medium.hGlobal)
{
oleError = DV_E_TYMED;
error = KVMFR_CLIPBOARD_FILE_ERROR_INVALID;
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: "
"stage=IDataObject::GetData(CF_HDROP)/STGMEDIUM sequence=%lu "
"rawFormats=%d tymed=0x%08lx hasHGlobal=%u",
static_cast<unsigned long>(sequence), rawFormatCount,
static_cast<unsigned long>(storage.medium.tymed),
storage.medium.hGlobal ? 1U : 0U);
return nullptr;
}
files = CLocalClipboardFiles::Capture(
static_cast<HDROP>(storage.medium.hGlobal), error);
if (!files)
{
oleError = ClipboardFileHRESULT(error);
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: "
"stage=CLocalClipboardFiles::Capture(CF_HDROP/ole) sequence=%lu "
"rawFormats=%d fileError=%u",
static_cast<unsigned long>(sequence), rawFormatCount,
static_cast<unsigned int>(error));
return nullptr;
}
viaOLE = true;
oleError = S_OK;
return files;
}
}
if (SUCCEEDED(hdropError))
if (!optimistic &&
!(candidates & CLIPBOARD_FILE_CANDIDATE_SHELL))
{
oleError = DV_E_TYMED;
error = KVMFR_CLIPBOARD_FILE_ERROR_INVALID;
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: "
"stage=IDataObject::GetData(CF_HDROP)/STGMEDIUM sequence=%lu "
"rawFormats=%d tymed=0x%08lx hasHGlobal=%u",
static_cast<unsigned long>(sequence), rawFormatCount,
static_cast<unsigned long>(storage.medium.tymed),
storage.medium.hGlobal ? 1U : 0U);
if (hdropAttempted)
oleError = hdropError;
else
{
error = KVMFR_CLIPBOARD_FILE_ERROR_NONE;
oleError = S_FALSE;
}
return nullptr;
}
@@ -3589,17 +3637,6 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
oleError = FAILED(shellError) ? shellError : E_UNEXPECTED;
if (oleError == CLIPBRD_E_CANT_OPEN)
retryStage = "SHCreateShellItemArrayFromDataObject";
HRESULT enumError = S_OK;
const bool fileCandidate = win32Candidate ||
hdropError != DV_E_FORMATETC ||
ClipboardDataObjectHasFileFormats(object.object, sequence, enumError);
if (!fileCandidate && SUCCEEDED(enumError) &&
oleError != CLIPBRD_E_CANT_OPEN)
{
error = KVMFR_CLIPBOARD_FILE_ERROR_NONE;
oleError = S_FALSE;
return nullptr;
}
return nullptr;
}
@@ -3707,16 +3744,7 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: stage=GlobalLock(DROPFILES) "
"sequence=%lu", static_cast<unsigned long>(sequence));
SetLastError(ERROR_SUCCESS);
HGLOBAL freeResult = GlobalFree(drop);
if (freeResult)
{
const DWORD freeError = GetLastError();
DEBUG_ERROR_HR(freeError ? HRESULT_FROM_WIN32(freeError) : E_UNEXPECTED,
"Failed to capture local clipboard files: "
"stage=GlobalFree(DROPFILES) sequence=%lu",
static_cast<unsigned long>(sequence));
}
FreeClipboardDrop(drop, sequence);
return nullptr;
}
header->pFiles = sizeof(*header);
@@ -3733,10 +3761,15 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
const DWORD unlockError = unlocked ? ERROR_SUCCESS : GetLastError();
if (!unlocked && unlockError != ERROR_SUCCESS)
{
DEBUG_ERROR_HR(HRESULT_FROM_WIN32(unlockError),
oleError = HRESULT_FROM_WIN32(unlockError);
error = unlockError == ERROR_ACCESS_DENIED ?
KVMFR_CLIPBOARD_FILE_ERROR_ACCESS : KVMFR_CLIPBOARD_FILE_ERROR_IO;
DEBUG_ERROR_HR(oleError,
"Failed to capture local clipboard files: "
"stage=GlobalUnlock(DROPFILES) sequence=%lu",
static_cast<unsigned long>(sequence));
FreeClipboardDrop(drop, sequence);
return nullptr;
}
files = CLocalClipboardFiles::Capture(static_cast<HDROP>(drop), error);
@@ -3749,16 +3782,7 @@ CClipboardManager::CaptureClipboardFiles(DWORD sequence, int rawFormatCount,
"fileError=%u", static_cast<unsigned long>(sequence),
static_cast<unsigned int>(error));
}
SetLastError(ERROR_SUCCESS);
HGLOBAL freeResult = GlobalFree(drop);
if (freeResult)
{
const DWORD freeError = GetLastError();
DEBUG_ERROR_HR(freeError ? HRESULT_FROM_WIN32(freeError) : E_UNEXPECTED,
"Failed to capture local clipboard files: "
"stage=GlobalFree(DROPFILES) sequence=%lu",
static_cast<unsigned long>(sequence));
}
FreeClipboardDrop(drop, sequence);
if (!files)
return nullptr;
viaOLE = true;
@@ -3829,7 +3853,8 @@ void CClipboardManager::PublishLocalClipboard()
const DWORD before = GetClipboardSequenceNumber();
uint32_t formats = EnumerateFormats();
const uint32_t recognizedFormats = formats;
const int rawFormatCount = CountClipboardFormats();
const int rawFormatCount = CountClipboardFormatsLogged(
"PublishLocalClipboard", before);
const DWORD after = GetClipboardSequenceNumber();
if (before != after)
{
@@ -4132,11 +4157,8 @@ bool CClipboardManager::ApplyRemoteOffer(uint32_t formats,
m_oleClipboard->Release();
m_oleClipboard = nullptr;
}
if (!OpenClipboardRetry())
{
DEBUG_WARN_HR(GetLastError(), "Failed to open the clipboard");
if (FAILED(OpenClipboardRetry("ApplyRemoteOffer")))
return false;
}
m_applyingRemote = true;
const bool emptied = EmptyClipboard() != FALSE;
@@ -4200,7 +4222,8 @@ bool CClipboardManager::ApplyRemoteOffer(uint32_t formats,
if (!error)
error = ERROR_INVALID_DATA;
SetLastError(error);
DEBUG_WARN_HR(error, "Failed to replace the clipboard");
DEBUG_WARN_HR(HRESULT_FROM_WIN32(error),
"Failed to replace the clipboard");
return false;
}
m_ownedSequence = GetClipboardSequenceNumber();
@@ -4217,7 +4240,8 @@ void CClipboardManager::ClearOwnedClipboard()
m_oleClipboard->Release();
m_oleClipboard = nullptr;
}
if (m_hwnd && GetClipboardOwner() == m_hwnd && OpenClipboardRetry())
if (m_hwnd && GetClipboardOwner() == m_hwnd &&
SUCCEEDED(OpenClipboardRetry("ClearOwnedClipboard")))
{
m_applyingRemote = true;
EmptyClipboard();
@@ -4271,8 +4295,14 @@ std::shared_ptr<CClipboardSpool> CClipboardManager::CaptureFormat(
SetLastError(ERROR_RETRY);
return nullptr;
}
if (!OpenClipboardRetry())
const HRESULT openResult = OpenClipboardRetry("CaptureFormat");
if (FAILED(openResult))
{
const DWORD openError = HRESULT_FACILITY(openResult) == FACILITY_WIN32 ?
static_cast<DWORD>(HRESULT_CODE(openResult)) : ERROR_BUSY;
SetLastError(openError);
return nullptr;
}
if (GetClipboardSequenceNumber() != sequence)
{
@@ -4576,7 +4606,7 @@ void CClipboardManager::RenderFormat(UINT windowsFormat, uint64_t deadline)
void CClipboardManager::RenderAllFormats()
{
if (!OpenClipboardRetry())
if (FAILED(OpenClipboardRetry("RenderAllFormats")))
return;
if (GetClipboardOwner() != m_hwnd)
{

View File

@@ -295,8 +295,7 @@ private:
void RetryLocalClipboard();
void RetryRemoteOffer();
bool OpenClipboardRetry(DWORD * error = nullptr,
const char * stage = nullptr, bool useWindow = true) const;
HRESULT OpenClipboardRetry(const char * stage) const;
bool IsOurClipboard();
uint32_t EnumerateFormats() const;
std::shared_ptr<CLocalClipboardFiles> CaptureClipboardFiles(

View File

@@ -45,7 +45,7 @@ bool CConfigWindow::registerClass()
CConfigWindow::CConfigWindow() : m_scale(1)
{
LSTATUS error = m_settings.open();
LSTATUS error = m_settings.open(true);
if (error != ERROR_SUCCESS)
DEBUG_ERROR_HR(error, "Failed to load settings");
else

View File

@@ -391,6 +391,12 @@ bool CPipeClient::Init()
return false;
}
{
CSRWExclusiveLock lock(m_clipboardSetupLock);
if (!PrepareClipboardMappingLocked())
return false;
}
m_endpoint.SetHandler(this);
return m_endpoint.Start(
LG_PIPE_NAME,
@@ -477,6 +483,44 @@ void CPipeClient::WriteMsg(const LGPipeMsg& msg)
m_endpoint.Send(&msg, sizeof(msg));
}
bool CPipeClient::PipeServerIsAuthorized(HANDLE pipe)
{
DWORD session = 0xFFFFFFFFU;
if (!GetNamedPipeServerSessionId(pipe, &session))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error, "Failed to identify named pipe server session");
return false;
}
if (session != 0)
{
DEBUG_WARN(
"Rejected named pipe server outside the service session");
return false;
}
return true;
}
bool CPipeClient::BuildPipeClientHello(void * message, size_t size)
{
CSRWSharedLock setupLock(m_clipboardSetupLock);
if (!message || size != sizeof(LGPipeMsg) ||
!m_clipboardMapping || !m_clipboardEpoch)
{
DEBUG_ERROR("Clipboard mapping was not prepared before pipe connection");
return false;
}
LGPipeMsg& hello = *static_cast<LGPipeMsg *>(message);
hello = {};
hello.size = sizeof(hello);
hello.type = LGPipeMsg::HELLO;
hello.hello.version = LGPipeMsg::PROTOCOL_VERSION;
hello.hello.authorityId[0] = m_clipboardAuthorityId[0];
hello.hello.authorityId[1] = m_clipboardAuthorityId[1];
return true;
}
void CPipeClient::OnPipeConnected()
{
bool hasStatus;
@@ -489,82 +533,6 @@ void CPipeClient::OnPipeConnected()
if (hasStatus)
WriteMsg(status);
if (!m_clipboardEnabled)
return;
CSRWExclusiveLock setupLock(m_clipboardSetupLock);
ResetClipboardSetupLocked();
LARGE_INTEGER size = {};
size.QuadPart = sizeof(ClipboardMapping);
m_clipboardMapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr,
PAGE_READWRITE, size.HighPart, size.LowPart, nullptr);
if (!m_clipboardMapping)
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to create the clipboard mapping");
return;
}
ClipboardMapping * view = static_cast<ClipboardMapping *>(MapViewOfFile(
m_clipboardMapping, FILE_MAP_ALL_ACCESS, 0, 0,
sizeof(ClipboardMapping)));
if (!view)
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to initialize the clipboard mapping");
ResetClipboardSetupLocked();
return;
}
++m_clipboardEpochCounter;
if (!m_clipboardEpochCounter)
++m_clipboardEpochCounter;
m_clipboardEpoch = m_clipboardEpochCounter;
CClipboardRing::Initialize(*view, m_clipboardEpoch);
UnmapViewOfFile(view);
DWORD serverPid = 0;
if (!GetNamedPipeServerProcessId(m_endpoint.NativeHandle(), &serverPid))
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to identify the clipboard mapping target");
ResetClipboardSetupLocked();
return;
}
HANDLE target = OpenProcess(PROCESS_DUP_HANDLE, FALSE, serverPid);
HANDLE remote = nullptr;
if (!target || !DuplicateHandle(GetCurrentProcess(),
m_clipboardMapping, target, &remote, 0, FALSE,
DUPLICATE_SAME_ACCESS))
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to share the clipboard mapping with the IDD");
if (target)
CloseHandle(target);
ResetClipboardSetupLocked();
return;
}
LGPipeMsg setup = {};
setup.size = sizeof(setup);
setup.type = LGPipeMsg::CLIPBOARD_SETUP;
setup.clipboardSetup.handle =
static_cast<uint64_t>(reinterpret_cast<uintptr_t>(remote));
setup.clipboardSetup.bytes = sizeof(ClipboardMapping);
const bool sent = m_endpoint.Send(&setup, sizeof(setup));
if (!sent)
{
DEBUG_WARN("Failed to send clipboard mapping setup");
HANDLE reclaimed = nullptr;
if (DuplicateHandle(target, remote, GetCurrentProcess(), &reclaimed,
0, FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
CloseHandle(reclaimed);
ResetClipboardSetupLocked();
}
CloseHandle(target);
}
void CPipeClient::OnPipeDisconnected()
@@ -589,6 +557,12 @@ bool CPipeClient::ShouldReconnect()
const bool attached = IsLGIddDeviceAttached();
if (!attached)
DEBUG_INFO("Looking Glass Indirect Display Device was removed");
else
{
CSRWExclusiveLock lock(m_clipboardSetupLock);
if (!m_clipboardMapping && !PrepareClipboardMappingLocked())
DEBUG_WARN("Clipboard mapping is not ready for reconnection");
}
return attached;
}
@@ -840,13 +814,46 @@ bool CPipeClient::OnPipeMessage(const void * message, size_t size)
return true;
}
HANDLE mapping = nullptr;
if (!m_clipboardMapping ||
!DuplicateHandle(GetCurrentProcess(), m_clipboardMapping,
GetCurrentProcess(), &mapping, 0, FALSE, DUPLICATE_SAME_ACCESS) ||
!m_clipboard.Attach(mapping, m_clipboardEpoch, true, *this))
if (!m_clipboardEnabled)
{
const uint64_t epoch = m_clipboardEpoch;
ResetClipboardSetupLocked();
setupLock.Unlock();
LGPipeMsg failure = {};
failure.size = sizeof(failure);
failure.type = LGPipeMsg::CLIPBOARD_READY;
failure.clipboardReady.epoch = epoch;
failure.clipboardReady.status = ERROR_NOT_SUPPORTED;
m_endpoint.Send(&failure, sizeof(failure));
return true;
}
HANDLE mapping = nullptr;
DWORD failureStatus = ERROR_SUCCESS;
if (!m_clipboardMapping)
{
failureStatus = ERROR_NOT_READY;
DEBUG_ERROR_HR(failureStatus,
"Service-owned clipboard mapping is unavailable");
}
else if (!DuplicateHandle(GetCurrentProcess(), m_clipboardMapping,
GetCurrentProcess(), &mapping, 0, FALSE, DUPLICATE_SAME_ACCESS))
{
failureStatus = GetLastError();
DEBUG_ERROR_HR(failureStatus,
"Failed to duplicate the service-owned clipboard mapping");
}
else if (!m_clipboard.Attach(
mapping, m_clipboardEpoch, true, *this))
{
failureStatus = ERROR_INVALID_DATA;
DEBUG_ERROR_HR(failureStatus,
"Failed to activate the service-owned clipboard mapping");
}
if (failureStatus != ERROR_SUCCESS)
{
DEBUG_ERROR("Failed to activate the clipboard mapping");
const uint64_t epoch = m_clipboardEpoch;
ResetClipboardSetupLocked();
setupLock.Unlock();
@@ -857,7 +864,7 @@ bool CPipeClient::OnPipeMessage(const void * message, size_t size)
failure.size = sizeof(failure);
failure.type = LGPipeMsg::CLIPBOARD_READY;
failure.clipboardReady.epoch = epoch;
failure.clipboardReady.status = ERROR_NOT_READY;
failure.clipboardReady.status = failureStatus;
m_endpoint.Send(&failure, sizeof(failure));
}
return true;
@@ -897,13 +904,87 @@ void CPipeClient::ClipboardResetPeer(uint64_t epoch, uint32_t reason)
m_endpoint.Send(&msg, sizeof(msg));
}
bool CPipeClient::PrepareClipboardMappingLocked()
{
if (m_clipboardMapping)
return true;
if (!m_clipboardMappingId[0] || !m_clipboardMappingId[1])
{
DEBUG_ERROR("Invalid service-owned clipboard mapping identifier");
return false;
}
wchar_t mappingName[128];
const int nameResult = _snwprintf_s(
mappingName, _countof(mappingName), _TRUNCATE,
L"Global\\LookingGlassIDDClipboard-%016llx%016llx",
static_cast<unsigned long long>(m_clipboardMappingId[0]),
static_cast<unsigned long long>(m_clipboardMappingId[1]));
if (nameResult < 0)
{
DEBUG_ERROR_HR(ERROR_INSUFFICIENT_BUFFER,
"Failed to format service-owned clipboard mapping name");
return false;
}
m_clipboardMapping = OpenFileMappingW(
FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mappingName);
if (!m_clipboardMapping)
{
const DWORD error = GetLastError();
DEBUG_ERROR_HR(error,
"Failed to open service-owned clipboard mapping");
return false;
}
ClipboardMapping * view = static_cast<ClipboardMapping *>(MapViewOfFile(
m_clipboardMapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0,
sizeof(ClipboardMapping)));
if (!view)
{
const DWORD error = GetLastError();
DEBUG_ERROR_HR(error,
"Failed to initialize service-owned clipboard mapping");
ResetClipboardSetupLocked();
return false;
}
m_clipboardAuthorityId[0] = view->authorityId[0];
m_clipboardAuthorityId[1] = view->authorityId[1];
if (!m_clipboardAuthorityId[0] || !m_clipboardAuthorityId[1])
{
DEBUG_ERROR("Invalid clipboard authority identifier");
UnmapViewOfFile(view);
ResetClipboardSetupLocked();
return false;
}
++m_clipboardEpochCounter;
if (!m_clipboardEpochCounter)
++m_clipboardEpochCounter;
m_clipboardEpoch = m_clipboardEpochCounter;
CClipboardRing::Initialize(
*view, m_clipboardEpoch, m_clipboardAuthorityId);
if (!UnmapViewOfFile(view))
{
const DWORD error = GetLastError();
DEBUG_ERROR_HR(error,
"Failed to unmap initialized service-owned clipboard mapping");
ResetClipboardSetupLocked();
return false;
}
return true;
}
void CPipeClient::ResetClipboardSetupLocked()
{
m_clipboard.Detach();
if (m_clipboardMapping)
CloseHandle(m_clipboardMapping);
m_clipboardMapping = nullptr;
m_clipboardEpoch = 0;
m_clipboardMapping = nullptr;
m_clipboardEpoch = 0;
m_clipboardAuthorityId[0] = 0;
m_clipboardAuthorityId[1] = 0;
}
void CPipeClient::HandleSetCursorPos(const LGPipeMsg& msg)

View File

@@ -35,10 +35,12 @@ private:
CPipeEndpoint m_endpoint;
CClipboardChannel m_clipboard;
CSRWLock m_clipboardSetupLock;
HANDLE m_clipboardMapping = nullptr;
uint64_t m_clipboardEpoch = 0;
uint64_t m_clipboardEpochCounter = 0;
bool m_clipboardEnabled = false;
HANDLE m_clipboardMapping = nullptr;
uint64_t m_clipboardEpoch = 0;
uint64_t m_clipboardEpochCounter = 0;
uint64_t m_clipboardMappingId[2] = {};
uint64_t m_clipboardAuthorityId[2] = {};
bool m_clipboardEnabled = false;
CSRWLock m_displayLock;
bool m_recoveryActive = false;
@@ -58,11 +60,15 @@ private:
void HandleGPUStatus(const LGPipeMsg& msg);
void HandleResolutionRejected(const LGPipeMsg& msg);
void HandleSetRecovery(const LGPipeMsg& msg);
bool PrepareClipboardMappingLocked();
void ResetClipboardSetupLocked();
void OnPipeConnected() override;
void OnPipeDisconnected() override;
bool ShouldReconnect() override;
bool PipeServerIsAuthorized(HANDLE pipe) override;
bool PipeClientHelloRequired() const override { return true; }
bool BuildPipeClientHello(void * message, size_t size) override;
bool OnPipeMessage(const void * message, size_t size) override;
public:
@@ -72,6 +78,11 @@ public:
bool Init();
void DeInit();
void SetClipboardMappingId(uint64_t high, uint64_t low)
{
m_clipboardMappingId[0] = high;
m_clipboardMappingId[1] = low;
}
bool IsRunning() { return m_endpoint.IsRunning(); }
CClipboardChannel& Clipboard() { return m_clipboard; }

View File

@@ -39,10 +39,13 @@ CRegistrySettings::~CRegistrySettings()
RegCloseKey(hKey);
}
LSTATUS CRegistrySettings::open()
LSTATUS CRegistrySettings::open(bool writable)
{
HKEY key;
LSTATUS result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LGIDD_REGKEY, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &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;

View File

@@ -41,7 +41,7 @@ public:
CRegistrySettings();
~CRegistrySettings();
LSTATUS open();
LSTATUS open(bool writable = false);
bool isOpen() { return !!hKey; }
std::vector<DisplayMode> getDefaultModes();

File diff suppressed because it is too large Load Diff