[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

@@ -27,11 +27,14 @@
#include <wdf.h>
#include <IddCx.h>
#include <avrt.h>
#include <bcrypt.h>
#include <wrl.h>
#include <limits>
#include <memory>
#include <utility>
#include "CDebug.h"
#include "ClipboardRing.h"
#include "display/CDisplayConfiguration.h"
#include "display/IddCxCompat.h"
#include "display/CDeviceContext.h"
@@ -42,7 +45,275 @@
WDFDEVICE l_wdfDevice = nullptr;
static const UINT IDDCX_VERSION_1_10 = 0x1A00;
static const UINT IDDCX_VERSION_1_10 = 0x1A00;
static uint64_t l_authorityInstanceId[2] = {};
static uint64_t l_authorityProcessCreated = 0;
static uint64_t FileTimeValue(const FILETIME& value)
{
ULARGE_INTEGER result = {};
result.LowPart = value.dwLowDateTime;
result.HighPart = value.dwHighDateTime;
return result.QuadPart;
}
static NTSTATUS InitAuthorityIdentity()
{
FILETIME created = {};
FILETIME exited = {};
FILETIME kernel = {};
FILETIME user = {};
if (!GetProcessTimes(GetCurrentProcess(),
&created, &exited, &kernel, &user))
{
const DWORD error = GetLastError();
DEBUG_ERROR_HR(error,
"Failed to query the LGIdd host process creation time");
return STATUS_UNSUCCESSFUL;
}
for (unsigned attempt = 0; attempt < 2; ++attempt)
{
const NTSTATUS status = BCryptGenRandom(nullptr,
reinterpret_cast<PUCHAR>(l_authorityInstanceId),
sizeof(l_authorityInstanceId), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
if (!NT_SUCCESS(status))
{
DEBUG_ERROR_HR(HRESULT_FROM_NT(status),
"Failed to generate the LGIdd authority instance identifier");
return status;
}
if (l_authorityInstanceId[0] && l_authorityInstanceId[1])
{
l_authorityProcessCreated = FileTimeValue(created);
return STATUS_SUCCESS;
}
}
DEBUG_ERROR_HR(ERROR_INVALID_DATA,
"Generated an invalid LGIdd authority instance identifier");
return STATUS_DATA_ERROR;
}
static bool AuthorityInstanceMatches(const uint64_t (&instanceId)[2])
{
return instanceId[0] == l_authorityInstanceId[0] &&
instanceId[1] == l_authorityInstanceId[1];
}
static void LGIddAuthorityFileCleanup(WDFFILEOBJECT fileObject)
{
g_pipe.CloseClipboardAuthorityFile(fileObject);
}
static void LGIddAuthorityIoDeviceControl(WDFDEVICE device,
WDFREQUEST request, size_t outputLength, size_t inputLength,
ULONG controlCode)
{
UNREFERENCED_PARAMETER(device);
NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST;
ULONG_PTR information = 0;
WDFFILEOBJECT fileObject = WdfRequestGetFileObject(request);
if (!fileObject)
{
DEBUG_WARN(
"LGIdd authority request has no file object");
WdfRequestComplete(request, STATUS_INVALID_HANDLE);
return;
}
switch (controlCode)
{
case IOCTL_LG_IDD_AUTHORITY_GET_HOST:
{
if (inputLength || outputLength < sizeof(LGIddAuthorityHost))
{
DEBUG_WARN(
"Rejected malformed LGIdd authority host request");
status = STATUS_BUFFER_TOO_SMALL;
break;
}
LGIddAuthorityHost * host = nullptr;
status = WdfRequestRetrieveOutputBuffer(request, sizeof(*host),
reinterpret_cast<void **>(&host), nullptr);
if (!NT_SUCCESS(status))
{
DEBUG_WARN_HR(HRESULT_FROM_NT(status),
"Failed to retrieve the LGIdd authority host output buffer");
break;
}
ZeroMemory(host, sizeof(*host));
host->size = sizeof(*host);
host->version = LG_IDD_AUTHORITY_VERSION;
host->processId = GetCurrentProcessId();
host->processCreated = l_authorityProcessCreated;
host->instanceId[0] = l_authorityInstanceId[0];
host->instanceId[1] = l_authorityInstanceId[1];
information = sizeof(*host);
status = STATUS_SUCCESS;
break;
}
case IOCTL_LG_IDD_AUTHORITY_REGISTER:
{
if (inputLength != sizeof(LGIddAuthorityRegistration) || outputLength)
{
DEBUG_WARN(
"Rejected malformed LGIdd authority registration request");
status = STATUS_INFO_LENGTH_MISMATCH;
break;
}
void * input = nullptr;
status = WdfRequestRetrieveInputBuffer(request,
sizeof(LGIddAuthorityRegistration), &input, nullptr);
if (!NT_SUCCESS(status))
{
DEBUG_WARN_HR(HRESULT_FROM_NT(status),
"Failed to retrieve the LGIdd authority registration buffer");
break;
}
const LGIddAuthorityRegistration * registration =
static_cast<const LGIddAuthorityRegistration *>(input);
if (registration->size != sizeof(*registration) ||
registration->version != LG_IDD_AUTHORITY_VERSION ||
registration->reserved ||
!AuthorityInstanceMatches(registration->instanceId) ||
!registration->mappingId[0] || !registration->mappingId[1] ||
!registration->mappingHandle ||
registration->mappingHandle >
static_cast<uint64_t>(
(std::numeric_limits<uintptr_t>::max)()) ||
registration->mappingHandle == static_cast<uint64_t>(
reinterpret_cast<uintptr_t>(INVALID_HANDLE_VALUE)))
{
DEBUG_WARN(
"Rejected invalid LGIdd authority registration data");
status = STATUS_DATA_ERROR;
break;
}
HANDLE rawMapping = reinterpret_cast<HANDLE>(
static_cast<uintptr_t>(registration->mappingHandle));
const auto closeInjectedMapping = [rawMapping]()
{
if (!CloseHandle(rawMapping))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to consume the injected clipboard authority handle");
return false;
}
return true;
};
const ClipboardMapping * view = static_cast<const ClipboardMapping *>(
MapViewOfFileFromApp(rawMapping,
FILE_MAP_READ | FILE_MAP_WRITE, 0, sizeof(ClipboardMapping)));
if (!view)
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to validate the injected clipboard authority handle");
closeInjectedMapping();
status = STATUS_INVALID_HANDLE;
break;
}
const uint64_t authorityId[2] =
{ view->authorityId[0], view->authorityId[1] };
if (!UnmapViewOfFile(view))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to unmap the injected clipboard authority handle");
closeInjectedMapping();
status = STATUS_UNSUCCESSFUL;
break;
}
if (!authorityId[0] || !authorityId[1])
{
DEBUG_WARN("Rejected clipboard mapping without an authority ID");
closeInjectedMapping();
status = STATUS_DATA_ERROR;
break;
}
HANDLE mapping = nullptr;
if (!DuplicateHandle(GetCurrentProcess(), rawMapping,
GetCurrentProcess(), &mapping,
SECTION_MAP_READ | SECTION_MAP_WRITE, FALSE, 0))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to privatize the injected clipboard authority handle");
closeInjectedMapping();
status = STATUS_INVALID_HANDLE;
break;
}
if (!closeInjectedMapping())
{
CloseHandle(mapping);
status = STATUS_UNSUCCESSFUL;
break;
}
if (!g_pipe.RegisterClipboardAuthority(fileObject, mapping,
registration->session, registration->mappingId, authorityId))
{
CloseHandle(mapping);
status = STATUS_ACCESS_DENIED;
break;
}
status = STATUS_SUCCESS;
break;
}
case IOCTL_LG_IDD_AUTHORITY_CLEAR:
{
if (inputLength != sizeof(LGIddAuthorityClear) || outputLength)
{
DEBUG_WARN(
"Rejected malformed LGIdd authority clear request");
status = STATUS_INFO_LENGTH_MISMATCH;
break;
}
void * input = nullptr;
status = WdfRequestRetrieveInputBuffer(request,
sizeof(LGIddAuthorityClear), &input, nullptr);
if (!NT_SUCCESS(status))
{
DEBUG_WARN_HR(HRESULT_FROM_NT(status),
"Failed to retrieve the LGIdd authority clear buffer");
break;
}
const LGIddAuthorityClear * clear =
static_cast<const LGIddAuthorityClear *>(input);
if (clear->size != sizeof(*clear) ||
clear->version != LG_IDD_AUTHORITY_VERSION ||
!AuthorityInstanceMatches(clear->instanceId))
{
DEBUG_WARN(
"Rejected invalid LGIdd authority clear data");
status = STATUS_DATA_ERROR;
break;
}
if (!g_pipe.ClearClipboardAuthority(fileObject))
{
status = STATUS_ACCESS_DENIED;
break;
}
status = STATUS_SUCCESS;
break;
}
}
WdfRequestCompleteWithInformation(request, status, information);
}
static bool LGIddCanUseIddCx110DDIs(UINT iddCxVersion)
{
@@ -283,6 +554,13 @@ NTSTATUS LGIddMonitorUnassignSwapChain(IDDCX_MONITOR monitor)
NTSTATUS LGIddCreateDevice(_Inout_ PWDFDEVICE_INIT deviceInit)
{
NTSTATUS status;
if (!l_authorityInstanceId[0] || !l_authorityInstanceId[1])
{
status = InitAuthorityIdentity();
if (!NT_SUCCESS(status))
return status;
}
IDARG_OUT_GETVERSION ver;
status = IddCxGetVersion(&ver);
if (FAILED(status))
@@ -302,6 +580,7 @@ NTSTATUS LGIddCreateDevice(_Inout_ PWDFDEVICE_INIT deviceInit)
IDD_CX_CLIENT_CONFIG config;
IDD_CX_CLIENT_CONFIG_INIT(&config);
config.EvtIddCxAdapterInitFinished = LGIddAdapterInitFinished;
config.EvtIddCxDeviceIoControl = LGIddAuthorityIoDeviceControl;
config.EvtIddCxMonitorGetDefaultDescriptionModes = LGIddMonitorGetDefaultModes;
config.EvtIddCxMonitorAssignSwapChain = LGIddMonitorAssignSwapChain;
config.EvtIddCxMonitorUnassignSwapChain = LGIddMonitorUnassignSwapChain;
@@ -328,6 +607,16 @@ NTSTATUS LGIddCreateDevice(_Inout_ PWDFDEVICE_INIT deviceInit)
if (!NT_SUCCESS(status))
return status;
WDF_FILEOBJECT_CONFIG fileConfig;
WDF_FILEOBJECT_CONFIG_INIT(&fileConfig,
WDF_NO_EVENT_CALLBACK, WDF_NO_EVENT_CALLBACK,
LGIddAuthorityFileCleanup);
WDF_OBJECT_ATTRIBUTES fileAttributes;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(
&fileAttributes, LGIddAuthorityFileContext);
WdfDeviceInitSetFileObjectConfig(
deviceInit, &fileConfig, &fileAttributes);
WDF_OBJECT_ATTRIBUTES deviceAttributes;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes, CDeviceContextWrapper);
deviceAttributes.EvtCleanupCallback = [](WDFOBJECT object)
@@ -335,6 +624,7 @@ NTSTATUS LGIddCreateDevice(_Inout_ PWDFDEVICE_INIT deviceInit)
auto * wrapper = WdfObjectGet_CDeviceContextWrapper(object);
if (wrapper)
{
g_pipe.ClearClipboardAuthority();
g_pipe.SetDeviceContext(nullptr);
wrapper->Cleanup();
}
@@ -346,6 +636,15 @@ NTSTATUS LGIddCreateDevice(_Inout_ PWDFDEVICE_INIT deviceInit)
if (!NT_SUCCESS(status))
return status;
status = WdfDeviceCreateDeviceInterface(
device, &GUID_DEVINTERFACE_LGIdd, nullptr);
if (!NT_SUCCESS(status))
{
DEBUG_ERROR_HR(HRESULT_FROM_NT(status),
"Failed to create the LGIdd authority device interface");
return status;
}
/*
* Construct the device context and cache the WDF device BEFORE calling
* IddCxDeviceInitialize. IddCxDeviceInitialize arms the IddCx callbacks, and

View File

@@ -20,7 +20,7 @@
#pragma once
#include "public.h"
#include "LGIddAuthority.h"
#include <Windows.h>

Binary file not shown.

View File

@@ -91,7 +91,6 @@
<ItemGroup>
<ClInclude Include="Device.h" />
<ClInclude Include="Driver.h" />
<ClInclude Include="Public.h" />
<ClInclude Include="Trace.h" />
<ClInclude Include="input\IInputSink.h" />
<ClInclude Include="ipc\CInputPipeServer.h" />
@@ -279,6 +278,7 @@
<PropertyGroup>
<LGPackageToolOutDir Condition="'$(Platform)'=='x64'">$([MSBuild]::NormalizeDirectory('$(LGDriverSolutionDir)$(Platform)\$(LGBaseConfiguration)'))</LGPackageToolOutDir>
<LGPackageToolOutDir Condition="'$(Platform)'=='Win32'">$([MSBuild]::NormalizeDirectory('$(LGDriverSolutionDir)$(LGBaseConfiguration)'))</LGPackageToolOutDir>
<InfVerif_AdditionalOptions>/sw2084</InfVerif_AdditionalOptions>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
@@ -289,7 +289,7 @@
<AdditionalIncludeDirectories>$(ProjectDir);$(SolutionDir)LGCommon;$(ProjectDir)..\..\repos\LGMP\lgmp\include;$(ProjectDir)..\..\vendor;$(ProjectDir)..\..\common\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;bcrypt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
</Link>
<DriverSign>
<FileDigestAlgorithm>SHA1</FileDigestAlgorithm>
@@ -304,7 +304,7 @@
<AdditionalIncludeDirectories>$(ProjectDir);$(SolutionDir)LGCommon;$(ProjectDir)..\..\repos\LGMP\lgmp\include;$(ProjectDir)..\..\vendor;$(ProjectDir)..\..\common\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;bcrypt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
</Link>
<DriverSign>
<FileDigestAlgorithm>SHA1</FileDigestAlgorithm>
@@ -319,7 +319,7 @@
<AdditionalIncludeDirectories>$(ProjectDir);$(SolutionDir)LGCommon;$(ProjectDir)..\..\repos\LGMP\lgmp\include;$(ProjectDir)..\..\vendor;$(ProjectDir)..\..\common\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;bcrypt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
</Link>
<DriverSign>
<FileDigestAlgorithm>SHA1</FileDigestAlgorithm>
@@ -334,7 +334,7 @@
<AdditionalIncludeDirectories>$(ProjectDir);$(SolutionDir)LGCommon;$(ProjectDir)..\..\repos\LGMP\lgmp\include;$(ProjectDir)..\..\vendor;$(ProjectDir)..\..\common\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies);OneCoreUAP.lib;avrt.lib;bcrypt.lib;d3d12.lib;d3dcompiler.lib</AdditionalDependencies>
</Link>
<DriverSign>
<FileDigestAlgorithm>SHA1</FileDigestAlgorithm>

View File

@@ -58,9 +58,6 @@
<ClInclude Include="Driver.h">
<Filter>Driver</Filter>
</ClInclude>
<ClInclude Include="Public.h">
<Filter>Driver</Filter>
</ClInclude>
<ClInclude Include="Trace.h">
<Filter>Driver</Filter>
</ClInclude>

View File

@@ -1,22 +0,0 @@
/**
* 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
*/
// {997b0b66-b74c-4017-9a89-e4aad41d3780}
DEFINE_GUID (GUID_DEVINTERFACE_LGIdd, 0x997b0b66,0xb74c,0x4017,0x9a,0x89,0xe4,0xaa,0xd4,0x1d,0x37,0x80);

View File

@@ -19,29 +19,340 @@
*/
#include "ipc/CPipeServer.h"
#include "CClipboardRing.h"
#include "CDebug.h"
#include "CSRWLock.h"
#include "display/CDeviceContext.h"
#include <sddl.h>
#include <vector>
CPipeServer g_pipe;
namespace
{
static constexpr DWORD NO_CONSOLE_SESSION = 0xFFFFFFFFU;
}
bool CPipeServer::Init()
{
DeInit();
// Only the driver identities may create/manage the endpoint. Interactive
// users receive client read/write access, then the first HELLO is matched
// against the SYSTEM service's device-bound clipboard authority.
static constexpr wchar_t PIPE_SECURITY[] =
L"D:P(A;;GA;;;SY)(A;;GA;;;LS)(A;;GA;;;NS)(A;;GA;;;UD)"
L"(A;;GRGW;;;IU)";
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
PIPE_SECURITY, SDDL_REVISION_1,
&m_pipeSecurityDescriptor, nullptr))
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to create named pipe security descriptor");
return false;
}
m_pipeSecurity.nLength = sizeof(m_pipeSecurity);
m_pipeSecurity.lpSecurityDescriptor = m_pipeSecurityDescriptor;
m_pipeSecurity.bInheritHandle = FALSE;
m_endpoint.SetHandler(this);
return m_endpoint.Start(
if (m_endpoint.Start(
LG_PIPE_NAME,
CPipeEndpoint::Mode::Server,
sizeof(LGPipeMsg));
sizeof(LGPipeMsg),
&m_pipeSecurity,
FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_REJECT_REMOTE_CLIENTS))
return true;
LocalFree(m_pipeSecurityDescriptor);
m_pipeSecurityDescriptor = nullptr;
m_pipeSecurity = {};
return false;
}
void CPipeServer::DeInit()
{
m_endpoint.Stop();
m_clipboard.Detach();
ClearClipboardAuthority();
if (m_pipeSecurityDescriptor)
{
LocalFree(m_pipeSecurityDescriptor);
m_pipeSecurityDescriptor = nullptr;
m_pipeSecurity = {};
}
}
bool CPipeServer::RegisterClipboardAuthority(WDFFILEOBJECT owner,
HANDLE mapping, DWORD session, const uint64_t (&mappingId)[2],
const uint64_t (&authorityId)[2])
{
if (!owner || !mapping || mapping == INVALID_HANDLE_VALUE ||
session == NO_CONSOLE_SESSION || !session ||
!mappingId[0] || !mappingId[1] ||
!authorityId[0] || !authorityId[1])
{
DEBUG_WARN(
"Rejected invalid clipboard authority registration");
return false;
}
const ClipboardMapping * view = static_cast<const ClipboardMapping *>(
MapViewOfFileFromApp(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0,
sizeof(ClipboardMapping)));
if (!view)
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to map the clipboard authority section");
return false;
}
if (!UnmapViewOfFile(view))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to unmap the clipboard authority section");
return false;
}
CSRWExclusiveLock lock(m_authorityLock);
const LGIddAuthorityFileContext * fileContext =
LGIddAuthorityGetFileContext(owner);
if (fileContext->closing)
{
DEBUG_WARN(
"Rejected clipboard authority registration for a closing file");
return false;
}
if (m_authorityOwner || m_authorityMapping)
{
DEBUG_WARN(
"Clipboard authority is already registered");
return false;
}
m_authorityOwner = owner;
m_authorityMapping = mapping;
m_authoritySession = session;
m_authorityMappingId[0] = mappingId[0];
m_authorityMappingId[1] = mappingId[1];
m_authorityId[0] = authorityId[0];
m_authorityId[1] = authorityId[1];
DEBUG_INFO("Registered clipboard authority for session %lu", session);
return true;
}
bool CPipeServer::ClearClipboardAuthority(WDFFILEOBJECT owner)
{
return ClearClipboardAuthorityInternal(owner, false);
}
void CPipeServer::CloseClipboardAuthorityFile(WDFFILEOBJECT owner)
{
(void) ClearClipboardAuthorityInternal(owner, true);
}
bool CPipeServer::ClearClipboardAuthorityInternal(
WDFFILEOBJECT owner, bool closing)
{
HANDLE authority = nullptr;
HANDLE pending = nullptr;
{
CSRWExclusiveLock lock(m_authorityLock);
if (closing)
{
if (!owner)
{
DEBUG_WARN(
"Cannot close an unspecified clipboard authority file");
return false;
}
LGIddAuthorityGetFileContext(owner)->closing = true;
if (m_authorityOwner != owner)
return true;
}
if (owner && m_authorityOwner && m_authorityOwner != owner)
{
DEBUG_WARN(
"Rejected clipboard authority clear from a different file object");
return false;
}
authority = m_authorityMapping;
pending = m_pendingClipboardMapping;
m_authorityOwner = nullptr;
m_authorityMapping = nullptr;
m_authoritySession = NO_CONSOLE_SESSION;
m_authorityMappingId[0] = 0;
m_authorityMappingId[1] = 0;
m_authorityId[0] = 0;
m_authorityId[1] = 0;
m_pendingClipboardMapping = nullptr;
m_pendingClipboardEpoch = 0;
m_clientAuthorityId[0] = 0;
m_clientAuthorityId[1] = 0;
m_endpoint.DisconnectClient();
m_clipboard.Detach();
}
if (pending)
CloseHandle(pending);
if (authority)
CloseHandle(authority);
if (authority || pending)
DEBUG_INFO("Cleared clipboard authority");
return true;
}
bool CPipeServer::AuthenticatePipeClient(
HANDLE pipe, const void * message, size_t size)
{
(void)pipe;
if (size != sizeof(LGPipeMsg))
{
DEBUG_WARN(
"Rejected Helper HELLO frame with %llu bytes, expected %llu",
static_cast<unsigned long long>(size),
static_cast<unsigned long long>(sizeof(LGPipeMsg)));
return false;
}
const LGPipeMsg& hello = *static_cast<const LGPipeMsg *>(message);
if (hello.size != sizeof(hello) || hello.type != LGPipeMsg::HELLO ||
hello.hello.version != LGPipeMsg::PROTOCOL_VERSION ||
!hello.hello.authorityId[0] || !hello.hello.authorityId[1])
{
DEBUG_WARN(
"Rejected malformed Helper HELLO: size=%u type=%u version=%u",
hello.size, static_cast<unsigned>(hello.type), hello.hello.version);
return false;
}
CSRWExclusiveLock lock(m_authorityLock);
if (!m_authorityOwner || !m_authorityMapping ||
m_authorityId[0] != hello.hello.authorityId[0] ||
m_authorityId[1] != hello.hello.authorityId[1])
{
DEBUG_WARN(
"Named pipe client does not match the clipboard authority");
return false;
}
HANDLE mapping = nullptr;
if (!DuplicateHandle(GetCurrentProcess(), m_authorityMapping,
GetCurrentProcess(), &mapping,
SECTION_MAP_READ | SECTION_MAP_WRITE, FALSE, 0))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to duplicate the authorized clipboard mapping");
return false;
}
const ClipboardMapping * view = static_cast<const ClipboardMapping *>(
MapViewOfFileFromApp(mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0,
sizeof(ClipboardMapping)));
if (!view)
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to validate the registered clipboard mapping");
CloseHandle(mapping);
return false;
}
const uint64_t epoch = view->epoch;
const bool valid = CClipboardRing::Valid(*view, epoch);
if (!UnmapViewOfFile(view))
{
const DWORD error = GetLastError();
DEBUG_WARN_HR(error,
"Failed to unmap the validated clipboard mapping");
CloseHandle(mapping);
return false;
}
if (!valid || !epoch)
{
DEBUG_WARN(
"Rejected an uninitialized registered clipboard mapping");
CloseHandle(mapping);
return false;
}
if (m_pendingClipboardMapping)
CloseHandle(m_pendingClipboardMapping);
m_pendingClipboardMapping = mapping;
m_pendingClipboardEpoch = epoch;
m_clientAuthorityId[0] = hello.hello.authorityId[0];
m_clientAuthorityId[1] = hello.hello.authorityId[1];
DEBUG_INFO("Authenticated clipboard Helper for session %lu",
m_authoritySession);
return true;
}
bool CPipeServer::PipeClientStillAuthorized(HANDLE pipe)
{
(void)pipe;
CSRWSharedLock lock(m_authorityLock);
if (!m_authorityOwner || !m_authorityMapping ||
!m_clientAuthorityId[0] || !m_clientAuthorityId[1])
{
DEBUG_WARN(
"Named pipe client authorization state is incomplete");
return false;
}
if (m_clientAuthorityId[0] != m_authorityId[0] ||
m_clientAuthorityId[1] != m_authorityId[1])
{
DEBUG_WARN(
"Named pipe client session authorization expired");
return false;
}
return true;
}
void CPipeServer::OnPipeConnected()
{
if (!PipeClientStillAuthorized(m_endpoint.NativeHandle()))
{
DEBUG_WARN("Named pipe client authorization expired before activation");
return;
}
uint64_t epoch = 0;
bool ready = false;
{
CSRWExclusiveLock lock(m_authorityLock);
HANDLE mapping = m_pendingClipboardMapping;
epoch = m_pendingClipboardEpoch;
m_pendingClipboardMapping = nullptr;
m_pendingClipboardEpoch = 0;
const bool authorityMatches = m_authorityOwner &&
m_authorityMapping &&
m_authorityId[0] == m_clientAuthorityId[0] &&
m_authorityId[1] == m_clientAuthorityId[1];
if (authorityMatches && mapping)
ready = m_clipboard.Attach(mapping, epoch, false, *this);
else
{
if (mapping)
CloseHandle(mapping);
DEBUG_ERROR("Authenticated clipboard mapping is missing or expired");
}
}
LGPipeMsg clipboardReady = {};
clipboardReady.size = sizeof(clipboardReady);
clipboardReady.type = LGPipeMsg::CLIPBOARD_READY;
clipboardReady.clipboardReady.epoch = epoch;
clipboardReady.clipboardReady.status = ready ?
ERROR_SUCCESS : ERROR_INVALID_DATA;
m_endpoint.Send(&clipboardReady, sizeof(clipboardReady));
CSRWExclusiveLock lock(m_queueLock);
std::vector<LGPipeMsg> queued;
queued.swap(m_queue);
@@ -63,7 +374,16 @@ void CPipeServer::OnPipeConnected()
void CPipeServer::OnPipeDisconnected()
{
m_clipboard.Detach();
{
CSRWExclusiveLock lock(m_authorityLock);
m_clipboard.Detach();
if (m_pendingClipboardMapping)
CloseHandle(m_pendingClipboardMapping);
m_pendingClipboardMapping = nullptr;
m_pendingClipboardEpoch = 0;
m_clientAuthorityId[0] = 0;
m_clientAuthorityId[1] = 0;
}
}
bool CPipeServer::OnPipeMessage(const void * message, size_t size)
@@ -89,51 +409,23 @@ bool CPipeServer::OnPipeMessage(const void * message, size_t size)
return true;
case LGPipeMsg::CLIPBOARD_SETUP:
{
HANDLE transferred = reinterpret_cast<HANDLE>(
static_cast<uintptr_t>(msg.clipboardSetup.handle));
HANDLE mapping = transferred;
uint64_t epoch = 0;
if (transferred &&
msg.clipboardSetup.bytes == sizeof(ClipboardMapping))
{
ClipboardMapping * view = static_cast<ClipboardMapping *>(
MapViewOfFile(mapping, FILE_MAP_READ, 0, 0,
sizeof(ClipboardMapping)));
if (view)
{
epoch = view->epoch;
UnmapViewOfFile(view);
}
}
else if (transferred)
{
CloseHandle(transferred);
mapping = nullptr;
}
// The transferred handle has exactly one owner from this point:
// Attach consumes it on both success and failure paths.
const bool ready = m_clipboard.Attach(
mapping, epoch, false, *this);
LGPipeMsg reply = {};
reply.size = sizeof(reply);
reply.type = LGPipeMsg::CLIPBOARD_READY;
reply.clipboardReady.epoch = epoch;
reply.clipboardReady.status = ready ? ERROR_SUCCESS : ERROR_INVALID_DATA;
m_endpoint.Send(&reply, sizeof(reply));
return true;
}
// Legacy SETUP names a handle in this process. Never interpret a value
// supplied by an unprivileged client as a local driver handle.
DEBUG_WARN("Rejected legacy clipboard mapping setup");
return false;
case LGPipeMsg::CLIPBOARD_READY:
// READY normally travels IDD to Helper. A failure in the reverse
// direction reports that Helper activation failed after IDD attach.
if (msg.clipboardReady.status != ERROR_SUCCESS &&
msg.clipboardReady.epoch == m_clipboard.Epoch())
if (msg.clipboardReady.status != ERROR_SUCCESS)
{
m_clipboard.Reset(
msg.clipboardReady.epoch, msg.clipboardReady.status);
m_clipboard.Detach();
CSRWExclusiveLock lock(m_authorityLock);
if (msg.clipboardReady.epoch == m_clipboard.Epoch())
{
m_clipboard.Reset(
msg.clipboardReady.epoch, msg.clipboardReady.status);
m_clipboard.Detach();
}
}
return true;
@@ -148,7 +440,7 @@ bool CPipeServer::OnPipeMessage(const void * message, size_t size)
default:
DEBUG_ERROR("Unknown message type %d", msg.type);
return true;
return false;
}
}

View File

@@ -32,6 +32,14 @@
class CDeviceContext;
struct LGIddAuthorityFileContext
{
bool closing;
};
WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(
LGIddAuthorityFileContext, LGIddAuthorityGetFileContext)
class CPipeServer : private IPipeEndpointHandler,
public IClipboardChannelDoorbell
{
@@ -56,14 +64,33 @@ class CPipeServer : private IPipeEndpointHandler,
void * m_recoveryOpaque = nullptr;
uint64_t m_recoveryRoute = 0;
CSRWLock m_authorityLock;
WDFFILEOBJECT m_authorityOwner = nullptr;
HANDLE m_authorityMapping = nullptr;
DWORD m_authoritySession = 0xFFFFFFFFU;
uint64_t m_authorityMappingId[2] = {};
uint64_t m_authorityId[2] = {};
PSECURITY_DESCRIPTOR m_pipeSecurityDescriptor = nullptr;
SECURITY_ATTRIBUTES m_pipeSecurity = {};
HANDLE m_pendingClipboardMapping = nullptr;
uint64_t m_pendingClipboardEpoch = 0;
uint64_t m_clientAuthorityId[2] = {};
void WriteMsg(const LGPipeMsg & msg);
void QueueMsgLocked(const LGPipeMsg & msg);
void HandleReloadSettings();
void HandleRecovery(const LGPipeMsg & msg);
bool ClearClipboardAuthorityInternal(
WDFFILEOBJECT owner, bool closing);
void OnPipeConnected() override;
void OnPipeDisconnected() override;
bool PipeClientAuthenticationRequired() const override { return true; }
bool AuthenticatePipeClient(HANDLE pipe,
const void * message, size_t size) override;
bool PipeClientStillAuthorized(HANDLE pipe) override;
bool OnPipeMessage(const void * message, size_t size) override;
public:
@@ -76,6 +103,12 @@ class CPipeServer : private IPipeEndpointHandler,
void SetRecoveryHandler(RecoveryHandler handler, void * opaque);
void ClearRecoveryHandler(void * opaque);
bool RegisterClipboardAuthority(WDFFILEOBJECT owner, HANDLE mapping,
DWORD session, const uint64_t (&mappingId)[2],
const uint64_t (&authorityId)[2]);
bool ClearClipboardAuthority(WDFFILEOBJECT owner = nullptr);
void CloseClipboardAuthorityFile(WDFFILEOBJECT owner);
bool SetCursorPos(int32_t x, int32_t y);
void SetDisplayMode(
uint32_t width, uint32_t height, uint32_t refreshMilliHz);