Improve named pipe security
* Set the PIPE_REJECT_REMOTE_CLIENTS flag on Vista and up. * Set a DACL on named pipes that gives full control to the built-in administrators, the local system account, and the current security token's owner SID. This is the same DACL that is used by default, except that the default also grants read access to the Everyone group and the anonymous account. * The createSecurityDescriptorOwnerFullControlEveryoneWrite function is not currently used (or tested), but I think I'll use it in the debug server to allow collecting trace output from other accounts on the machine. (I think I'll make that behavior optional.)
This commit is contained in:
parent
63fa213594
commit
383138a0cc
@ -28,7 +28,9 @@ LIBWINPTY_OBJECTS = \
|
||||
build/libwinpty/shared/DebugClient.o \
|
||||
build/libwinpty/shared/GenRandom.o \
|
||||
build/libwinpty/shared/StringUtil.o \
|
||||
build/libwinpty/shared/WinptyAssert.o
|
||||
build/libwinpty/shared/WindowsSecurity.o \
|
||||
build/libwinpty/shared/WinptyAssert.o \
|
||||
build/libwinpty/shared/WinptyException.o
|
||||
|
||||
build/winpty.dll : $(LIBWINPTY_OBJECTS)
|
||||
$(info Linking $@)
|
||||
|
@ -33,6 +33,8 @@
|
||||
#include "../shared/GenRandom.h"
|
||||
#include "../shared/StringBuilder.h"
|
||||
#include "../shared/StringUtil.h"
|
||||
#include "../shared/WindowsSecurity.h"
|
||||
#include "../shared/WinptyException.h"
|
||||
|
||||
// TODO: Error handling, handle out-of-memory.
|
||||
|
||||
@ -144,17 +146,28 @@ static int32_t readInt32(winpty_t *pc)
|
||||
|
||||
static HANDLE createNamedPipe(const std::wstring &name, bool overlapped)
|
||||
{
|
||||
try {
|
||||
const auto sd = createPipeSecurityDescriptorOwnerFullControl();
|
||||
SECURITY_ATTRIBUTES sa = {};
|
||||
sa.nLength = sizeof(sa);
|
||||
sa.lpSecurityDescriptor = sd.get();
|
||||
return CreateNamedPipeW(name.c_str(),
|
||||
/*dwOpenMode=*/
|
||||
PIPE_ACCESS_DUPLEX |
|
||||
FILE_FLAG_FIRST_PIPE_INSTANCE |
|
||||
(overlapped ? FILE_FLAG_OVERLAPPED : 0),
|
||||
/*dwPipeMode=*/0,
|
||||
/*dwPipeMode=*/
|
||||
rejectRemoteClientsPipeFlag(),
|
||||
/*nMaxInstances=*/1,
|
||||
/*nOutBufferSize=*/0,
|
||||
/*nInBufferSize=*/0,
|
||||
/*nDefaultTimeOut=*/3000,
|
||||
NULL);
|
||||
&sa);
|
||||
} catch (const WinptyException &e) {
|
||||
trace("createNamedPipe: exception thrown: %s",
|
||||
utf8FromWide(e.what()).c_str());
|
||||
return INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
|
||||
struct BackgroundDesktop {
|
||||
@ -336,6 +349,9 @@ WINPTY_API winpty_t *winpty_open(int cols, int rows)
|
||||
// destroyed before the agent can connect with them.
|
||||
restoreOriginalDesktop(desktop);
|
||||
|
||||
// TODO: This comment is now out-of-date. The named pipes now have a DACL
|
||||
// that should prevent arbitrary users from connecting, even just to read.
|
||||
//
|
||||
// The default security descriptor for a named pipe allows anyone to connect
|
||||
// to the pipe to read, but not to write. Only the "creator owner" and
|
||||
// various system accounts can write to the pipe. By sending and receiving
|
||||
|
463
src/shared/WindowsSecurity.cc
Executable file
463
src/shared/WindowsSecurity.cc
Executable file
@ -0,0 +1,463 @@
|
||||
// Copyright (c) 2016 Ryan Prichard
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to
|
||||
// deal in the Software without restriction, including without limitation the
|
||||
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
// sell copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
// IN THE SOFTWARE.
|
||||
|
||||
#include "WindowsSecurity.h"
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "DebugClient.h"
|
||||
#include "OsModule.h"
|
||||
#include "StringBuilder.h"
|
||||
#include "WinptyAssert.h"
|
||||
#include "WinptyException.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct LocalFreer {
|
||||
void operator()(void *ptr) {
|
||||
if (ptr != nullptr) {
|
||||
LocalFree(reinterpret_cast<HLOCAL>(ptr));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
typedef std::unique_ptr<void, LocalFreer> PointerLocal;
|
||||
|
||||
template <typename T>
|
||||
SecurityItem<T> localItem(typename T::type v) {
|
||||
typedef typename T::type P;
|
||||
struct Impl : SecurityItem<T>::Impl {
|
||||
P m_v;
|
||||
Impl(P v) : m_v(v) {}
|
||||
virtual ~Impl() {
|
||||
LocalFree(reinterpret_cast<HLOCAL>(m_v));
|
||||
}
|
||||
};
|
||||
return SecurityItem<T>(v, std::unique_ptr<Impl>(new Impl { v }));
|
||||
}
|
||||
|
||||
Sid allocatedSid(PSID v) {
|
||||
struct Impl : Sid::Impl {
|
||||
PSID m_v;
|
||||
Impl(PSID v) : m_v(v) {}
|
||||
virtual ~Impl() {
|
||||
if (m_v != nullptr) {
|
||||
FreeSid(m_v);
|
||||
}
|
||||
}
|
||||
};
|
||||
return Sid(v, std::unique_ptr<Impl>(new Impl { v }));
|
||||
}
|
||||
|
||||
class Handle {
|
||||
HANDLE m_h;
|
||||
public:
|
||||
explicit Handle(HANDLE h) : m_h(h) {}
|
||||
~Handle() {
|
||||
if (m_h != nullptr) {
|
||||
CloseHandle(m_h);
|
||||
}
|
||||
}
|
||||
HANDLE get() const { return m_h; }
|
||||
Handle(const Handle &other) = delete;
|
||||
Handle &operator=(const Handle &other) = delete;
|
||||
Handle(Handle &&other) : m_h(other.m_h) {
|
||||
other.m_h = nullptr;
|
||||
}
|
||||
Handle &operator=(Handle &&other) {
|
||||
m_h = other.m_h;
|
||||
other.m_h = nullptr;
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
// Returns a handle to the thread's effective security token. If the thread
|
||||
// is impersonating another user, its token is returned, and otherwise, the
|
||||
// process' security token is opened. The handle is opened with TOKEN_QUERY.
|
||||
static Handle openSecurityTokenForQuery() {
|
||||
HANDLE token = nullptr;
|
||||
// It is unclear to me whether OpenAsSelf matters for winpty, or what the
|
||||
// most appropriate value is.
|
||||
if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY,
|
||||
/*OpenAsSelf=*/FALSE, &token)) {
|
||||
if (GetLastError() != ERROR_NO_TOKEN) {
|
||||
throwWindowsError(L"OpenThreadToken failed");
|
||||
}
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
|
||||
throwWindowsError(L"OpenProcessToken failed");
|
||||
}
|
||||
}
|
||||
ASSERT(token != nullptr &&
|
||||
"OpenThreadToken/OpenProcessToken token is NULL");
|
||||
return Handle(token);
|
||||
}
|
||||
|
||||
// Returns the TokenOwner of the thread's effective security token.
|
||||
Sid getOwnerSid() {
|
||||
struct Impl : Sid::Impl {
|
||||
std::unique_ptr<char[]> buffer;
|
||||
};
|
||||
|
||||
Handle token = openSecurityTokenForQuery();
|
||||
DWORD actual = 0;
|
||||
BOOL success;
|
||||
success = GetTokenInformation(token.get(), TokenOwner,
|
||||
nullptr, 0, &actual);
|
||||
if (success) {
|
||||
throwWinptyException(L"getOwnerSid: GetTokenInformation: "
|
||||
L"expected ERROR_INSUFFICIENT_BUFFER");
|
||||
} else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
|
||||
throwWindowsError(L"getOwnerSid: GetTokenInformation: "
|
||||
L"expected ERROR_INSUFFICIENT_BUFFER");
|
||||
}
|
||||
std::unique_ptr<Impl> impl(new Impl);
|
||||
impl->buffer = std::unique_ptr<char[]>(new char[actual]);
|
||||
success = GetTokenInformation(token.get(), TokenOwner,
|
||||
impl->buffer.get(), actual, &actual);
|
||||
if (!success) {
|
||||
throwWindowsError(L"getOwnerSid: GetTokenInformation");
|
||||
}
|
||||
TOKEN_OWNER tmp;
|
||||
ASSERT(actual >= sizeof(tmp));
|
||||
std::copy(
|
||||
impl->buffer.get(),
|
||||
impl->buffer.get() + sizeof(tmp),
|
||||
reinterpret_cast<char*>(&tmp));
|
||||
return Sid(tmp.Owner, std::move(impl));
|
||||
}
|
||||
|
||||
Sid wellKnownSid(
|
||||
const wchar_t *debuggingName,
|
||||
SID_IDENTIFIER_AUTHORITY authority,
|
||||
BYTE authorityCount,
|
||||
DWORD subAuthority0/*=0*/,
|
||||
DWORD subAuthority1/*=0*/) {
|
||||
PSID psid = nullptr;
|
||||
if (!AllocateAndInitializeSid(&authority, authorityCount,
|
||||
subAuthority0,
|
||||
subAuthority1,
|
||||
0, 0, 0, 0, 0, 0,
|
||||
&psid)) {
|
||||
const auto err = GetLastError();
|
||||
const auto msg =
|
||||
std::wstring(L"wellKnownSid: error getting ") +
|
||||
debuggingName + L" SID";
|
||||
throwWindowsError(msg.c_str(), err);
|
||||
}
|
||||
return allocatedSid(psid);
|
||||
}
|
||||
|
||||
Sid builtinAdminsSid() {
|
||||
// S-1-5-32-544
|
||||
SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };
|
||||
return wellKnownSid(L"BUILTIN\\Administrators group",
|
||||
authority, 2,
|
||||
SECURITY_BUILTIN_DOMAIN_RID, // 32
|
||||
DOMAIN_ALIAS_RID_ADMINS); // 544
|
||||
}
|
||||
|
||||
Sid localSystemSid() {
|
||||
// S-1-5-18
|
||||
SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };
|
||||
return wellKnownSid(L"LocalSystem account",
|
||||
authority, 1,
|
||||
SECURITY_LOCAL_SYSTEM_RID); // 18
|
||||
}
|
||||
|
||||
Sid everyoneSid() {
|
||||
// S-1-1-0
|
||||
SID_IDENTIFIER_AUTHORITY authority = { SECURITY_WORLD_SID_AUTHORITY };
|
||||
return wellKnownSid(L"Everyone account",
|
||||
authority, 1,
|
||||
SECURITY_WORLD_RID); // 0
|
||||
}
|
||||
|
||||
static SecurityDescriptor finishSecurityDescriptor(
|
||||
size_t daclEntryCount,
|
||||
EXPLICIT_ACCESSW *daclEntries,
|
||||
Acl &outAcl) {
|
||||
{
|
||||
PACL aclRaw = nullptr;
|
||||
DWORD aclError =
|
||||
SetEntriesInAcl(daclEntryCount,
|
||||
daclEntries,
|
||||
nullptr, &aclRaw);
|
||||
if (aclError != ERROR_SUCCESS) {
|
||||
WStringBuilder sb(64);
|
||||
sb << L"finishSecurityDescriptor: "
|
||||
<< L"SetEntriesInAcl failed: " << aclError;
|
||||
throwWinptyException(sb.c_str());
|
||||
}
|
||||
outAcl = localItem<AclTag>(aclRaw);
|
||||
}
|
||||
|
||||
const PSECURITY_DESCRIPTOR sdRaw =
|
||||
reinterpret_cast<PSECURITY_DESCRIPTOR>(
|
||||
LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH));
|
||||
if (sdRaw == nullptr) {
|
||||
throwWinptyException(L"finishSecurityDescriptor: LocalAlloc failed");
|
||||
}
|
||||
SecurityDescriptor sd = localItem<SecurityDescriptorTag>(sdRaw);
|
||||
if (!InitializeSecurityDescriptor(sdRaw, SECURITY_DESCRIPTOR_REVISION)) {
|
||||
throwWindowsError(
|
||||
L"finishSecurityDescriptor: InitializeSecurityDescriptor");
|
||||
}
|
||||
if (!SetSecurityDescriptorDacl(sdRaw, TRUE, outAcl.get(), FALSE)) {
|
||||
throwWindowsError(
|
||||
L"finishSecurityDescriptor: SetSecurityDescriptorDacl");
|
||||
}
|
||||
|
||||
return std::move(sd);
|
||||
}
|
||||
|
||||
// Create a security descriptor that grants full control to the local system
|
||||
// account, built-in administrators, and the owner.
|
||||
SecurityDescriptor
|
||||
createPipeSecurityDescriptorOwnerFullControl() {
|
||||
|
||||
struct Impl : SecurityDescriptor::Impl {
|
||||
Sid localSystem;
|
||||
Sid builtinAdmins;
|
||||
Sid owner;
|
||||
std::array<EXPLICIT_ACCESSW, 3> daclEntries;
|
||||
Acl dacl;
|
||||
SecurityDescriptor value;
|
||||
};
|
||||
|
||||
std::unique_ptr<Impl> impl(new Impl);
|
||||
impl->localSystem = localSystemSid();
|
||||
impl->builtinAdmins = builtinAdminsSid();
|
||||
impl->owner = getOwnerSid();
|
||||
|
||||
for (auto &ea : impl->daclEntries) {
|
||||
ea.grfAccessPermissions = GENERIC_ALL;
|
||||
ea.grfAccessMode = SET_ACCESS;
|
||||
ea.grfInheritance = NO_INHERITANCE;
|
||||
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
|
||||
}
|
||||
impl->daclEntries[0].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->localSystem.get());
|
||||
impl->daclEntries[1].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->builtinAdmins.get());
|
||||
impl->daclEntries[2].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->owner.get());
|
||||
|
||||
impl->value = finishSecurityDescriptor(
|
||||
impl->daclEntries.size(),
|
||||
impl->daclEntries.data(),
|
||||
impl->dacl);
|
||||
|
||||
const auto retValue = impl->value.get();
|
||||
return SecurityDescriptor(retValue, std::move(impl));
|
||||
}
|
||||
|
||||
SecurityDescriptor
|
||||
createPipeSecurityDescriptorOwnerFullControlEveryoneWrite() {
|
||||
|
||||
struct Impl : SecurityDescriptor::Impl {
|
||||
Sid localSystem;
|
||||
Sid builtinAdmins;
|
||||
Sid owner;
|
||||
Sid everyone;
|
||||
std::array<EXPLICIT_ACCESSW, 4> daclEntries;
|
||||
Acl dacl;
|
||||
SecurityDescriptor value;
|
||||
};
|
||||
|
||||
std::unique_ptr<Impl> impl(new Impl);
|
||||
impl->localSystem = localSystemSid();
|
||||
impl->builtinAdmins = builtinAdminsSid();
|
||||
impl->owner = getOwnerSid();
|
||||
impl->everyone = everyoneSid();
|
||||
|
||||
for (auto &ea : impl->daclEntries) {
|
||||
ea.grfAccessPermissions = GENERIC_ALL;
|
||||
ea.grfAccessMode = SET_ACCESS;
|
||||
ea.grfInheritance = NO_INHERITANCE;
|
||||
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
|
||||
}
|
||||
impl->daclEntries[0].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->localSystem.get());
|
||||
impl->daclEntries[1].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->builtinAdmins.get());
|
||||
impl->daclEntries[2].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->owner.get());
|
||||
impl->daclEntries[3].Trustee.ptstrName =
|
||||
reinterpret_cast<LPWSTR>(impl->everyone.get());
|
||||
// Avoid using FILE_GENERIC_WRITE because it includes FILE_APPEND_DATA,
|
||||
// which is equal to FILE_CREATE_PIPE_INSTANCE. Instead, include all the
|
||||
// flags that comprise FILE_GENERIC_WRITE, except for the one.
|
||||
impl->daclEntries[3].grfAccessPermissions =
|
||||
FILE_GENERIC_READ |
|
||||
FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | FILE_WRITE_EA |
|
||||
STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
|
||||
|
||||
impl->value = finishSecurityDescriptor(
|
||||
impl->daclEntries.size(),
|
||||
impl->daclEntries.data(),
|
||||
impl->dacl);
|
||||
|
||||
const auto retValue = impl->value.get();
|
||||
return SecurityDescriptor(retValue, std::move(impl));
|
||||
}
|
||||
|
||||
SecurityDescriptor getObjectSecurityDescriptor(HANDLE handle) {
|
||||
PACL dacl = nullptr;
|
||||
PSECURITY_DESCRIPTOR sd = nullptr;
|
||||
const DWORD errCode = GetSecurityInfo(handle, SE_KERNEL_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION |
|
||||
GROUP_SECURITY_INFORMATION |
|
||||
DACL_SECURITY_INFORMATION,
|
||||
nullptr, nullptr, &dacl, nullptr, &sd);
|
||||
if (errCode != ERROR_SUCCESS) {
|
||||
throwWindowsError(L"GetSecurityInfo failed");
|
||||
}
|
||||
return localItem<SecurityDescriptorTag>(sd);
|
||||
}
|
||||
|
||||
// The (SID/SD)<->string conversion APIs are useful for testing/debugging, so
|
||||
// create convenient accessor functions for them. They're too slow for
|
||||
// ordinary use. The APIs exist in XP and up, but the MinGW headers only
|
||||
// declare the SID<->string APIs, not the SD APIs. MinGW also gets the
|
||||
// prototype wrong for ConvertStringSidToSidW (LPWSTR instead of LPCWSTR) and
|
||||
// requires WINVER to be defined. MSVC and MinGW-w64 get everything right, but
|
||||
// for consistency, use LoadLibrary/GetProcAddress for all four APIs.
|
||||
|
||||
typedef BOOL WINAPI ConvertStringSidToSidW_t(
|
||||
LPCWSTR StringSid,
|
||||
PSID *Sid);
|
||||
|
||||
typedef BOOL WINAPI ConvertSidToStringSidW_t(
|
||||
PSID Sid,
|
||||
LPWSTR *StringSid);
|
||||
|
||||
typedef BOOL WINAPI ConvertStringSecurityDescriptorToSecurityDescriptorW_t(
|
||||
LPCWSTR StringSecurityDescriptor,
|
||||
DWORD StringSDRevision,
|
||||
PSECURITY_DESCRIPTOR *SecurityDescriptor,
|
||||
PULONG SecurityDescriptorSize);
|
||||
|
||||
typedef BOOL WINAPI ConvertSecurityDescriptorToStringSecurityDescriptorW_t(
|
||||
PSECURITY_DESCRIPTOR SecurityDescriptor,
|
||||
DWORD RequestedStringSDRevision,
|
||||
SECURITY_INFORMATION SecurityInformation,
|
||||
LPWSTR *StringSecurityDescriptor,
|
||||
PULONG StringSecurityDescriptorLen);
|
||||
|
||||
#define GET_MODULE_PROC(mod, funcName) \
|
||||
const auto p##funcName = \
|
||||
reinterpret_cast<funcName##_t*>( \
|
||||
mod.proc(#funcName)); \
|
||||
if (p##funcName == nullptr) { \
|
||||
throwWinptyException( \
|
||||
L"" L ## #funcName L" API is missing from ADVAPI32.DLL"); \
|
||||
}
|
||||
|
||||
const DWORD kSDDL_REVISION_1 = 1;
|
||||
|
||||
std::wstring sidToString(PSID sid) {
|
||||
OsModule advapi32(L"advapi32.dll");
|
||||
GET_MODULE_PROC(advapi32, ConvertSidToStringSidW);
|
||||
wchar_t *sidString = NULL;
|
||||
BOOL success = pConvertSidToStringSidW(sid, &sidString);
|
||||
if (!success) {
|
||||
throwWindowsError(L"ConvertSidToStringSidW failed");
|
||||
}
|
||||
PointerLocal freer(sidString);
|
||||
return std::wstring(sidString);
|
||||
}
|
||||
|
||||
Sid stringToSid(const std::wstring &str) {
|
||||
// Cast the string from const wchar_t* to LPWSTR because the function is
|
||||
// incorrectly prototyped in the MinGW sddl.h header. The API does not
|
||||
// modify the string -- it is correctly prototyped as taking LPCWSTR in
|
||||
// MinGW-w64, MSVC, and MSDN.
|
||||
OsModule advapi32(L"advapi32.dll");
|
||||
GET_MODULE_PROC(advapi32, ConvertStringSidToSidW);
|
||||
PSID psid = nullptr;
|
||||
BOOL success = pConvertStringSidToSidW(const_cast<LPWSTR>(str.c_str()),
|
||||
&psid);
|
||||
if (!success) {
|
||||
const auto err = GetLastError();
|
||||
throwWindowsError(
|
||||
(std::wstring(L"ConvertStringSidToSidW failed on \"") +
|
||||
str + L'"').c_str(),
|
||||
err);
|
||||
}
|
||||
return localItem<SidTag>(psid);
|
||||
}
|
||||
|
||||
SecurityDescriptor stringToSd(const std::wstring &str) {
|
||||
OsModule advapi32(L"advapi32.dll");
|
||||
GET_MODULE_PROC(advapi32, ConvertStringSecurityDescriptorToSecurityDescriptorW);
|
||||
PSECURITY_DESCRIPTOR desc = nullptr;
|
||||
if (!pConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
str.c_str(), kSDDL_REVISION_1, &desc, nullptr)) {
|
||||
const auto err = GetLastError();
|
||||
throwWindowsError(
|
||||
(std::wstring(L"ConvertStringSecurityDescriptorToSecurityDescriptorW failed on \"") +
|
||||
str + L'"').c_str(),
|
||||
err);
|
||||
}
|
||||
return localItem<SecurityDescriptorTag>(desc);
|
||||
}
|
||||
|
||||
std::wstring sdToString(PSECURITY_DESCRIPTOR sd) {
|
||||
OsModule advapi32(L"advapi32.dll");
|
||||
GET_MODULE_PROC(advapi32, ConvertSecurityDescriptorToStringSecurityDescriptorW);
|
||||
wchar_t *sdString = nullptr;
|
||||
if (!pConvertSecurityDescriptorToStringSecurityDescriptorW(
|
||||
sd,
|
||||
kSDDL_REVISION_1,
|
||||
OWNER_SECURITY_INFORMATION |
|
||||
GROUP_SECURITY_INFORMATION |
|
||||
DACL_SECURITY_INFORMATION,
|
||||
&sdString,
|
||||
nullptr)) {
|
||||
throwWindowsError(
|
||||
L"ConvertSecurityDescriptorToStringSecurityDescriptor failed");
|
||||
}
|
||||
PointerLocal freer(sdString);
|
||||
return std::wstring(sdString);
|
||||
}
|
||||
|
||||
// Vista added a useful flag to CreateNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
|
||||
// that rejects remote connections. Return this flag on Vista, or return 0
|
||||
// otherwise.
|
||||
DWORD rejectRemoteClientsPipeFlag() {
|
||||
// MinGW lacks this flag; MinGW-w64 has it.
|
||||
const DWORD kPIPE_REJECT_REMOTE_CLIENTS = 8;
|
||||
|
||||
OSVERSIONINFOW info = { sizeof(info) };
|
||||
if (!GetVersionExW(&info)) {
|
||||
trace("error: GetVersionExW failed: %u",
|
||||
static_cast<unsigned>(GetLastError()));
|
||||
return kPIPE_REJECT_REMOTE_CLIENTS;
|
||||
} else if (info.dwMajorVersion >= 6) {
|
||||
return kPIPE_REJECT_REMOTE_CLIENTS;
|
||||
} else {
|
||||
trace("Omitting PIPE_REJECT_REMOTE_CLIENTS on old OS (%d.%d)",
|
||||
static_cast<int>(info.dwMajorVersion),
|
||||
static_cast<int>(info.dwMinorVersion));
|
||||
return 0;
|
||||
}
|
||||
}
|
91
src/shared/WindowsSecurity.h
Executable file
91
src/shared/WindowsSecurity.h
Executable file
@ -0,0 +1,91 @@
|
||||
// Copyright (c) 2016 Ryan Prichard
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to
|
||||
// deal in the Software without restriction, including without limitation the
|
||||
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
// sell copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
// IN THE SOFTWARE.
|
||||
|
||||
#ifndef WINPTY_WINDOWS_SECURITY_H
|
||||
#define WINPTY_WINDOWS_SECURITY_H
|
||||
|
||||
#include <windows.h>
|
||||
#include <aclapi.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
// PSID and PSECURITY_DESCRIPTOR are both pointers to void, but we want
|
||||
// Sid and SecurityDescriptor to be different types.
|
||||
struct SidTag { typedef PSID type; };
|
||||
struct AclTag { typedef PACL type; };
|
||||
struct SecurityDescriptorTag { typedef PSECURITY_DESCRIPTOR type; };
|
||||
|
||||
template <typename T>
|
||||
class SecurityItem {
|
||||
public:
|
||||
struct Impl {
|
||||
virtual ~Impl() {}
|
||||
};
|
||||
|
||||
private:
|
||||
typedef typename T::type P;
|
||||
P m_v;
|
||||
std::unique_ptr<Impl> m_pimpl;
|
||||
|
||||
public:
|
||||
P get() const { return m_v; }
|
||||
operator bool() const { return m_v != nullptr; }
|
||||
|
||||
SecurityItem() : m_v(nullptr) {}
|
||||
SecurityItem(P v, std::unique_ptr<Impl> &&pimpl) :
|
||||
m_v(v), m_pimpl(std::move(pimpl)) {}
|
||||
SecurityItem(SecurityItem &&other) :
|
||||
m_v(other.m_v), m_pimpl(std::move(other.m_pimpl)) {
|
||||
other.m_v = nullptr;
|
||||
}
|
||||
SecurityItem &operator=(SecurityItem &&other) {
|
||||
m_v = other.m_v;
|
||||
other.m_v = nullptr;
|
||||
m_pimpl = std::move(other.m_pimpl);
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
typedef SecurityItem<SidTag> Sid;
|
||||
typedef SecurityItem<AclTag> Acl;
|
||||
typedef SecurityItem<SecurityDescriptorTag> SecurityDescriptor;
|
||||
|
||||
Sid getOwnerSid();
|
||||
Sid wellKnownSid(
|
||||
const wchar_t *debuggingName,
|
||||
SID_IDENTIFIER_AUTHORITY authority,
|
||||
BYTE authorityCount,
|
||||
DWORD subAuthority0=0,
|
||||
DWORD subAuthority1=0);
|
||||
Sid builtinAdminsSid();
|
||||
Sid localSystemSid();
|
||||
Sid everyoneSid();
|
||||
SecurityDescriptor createPipeSecurityDescriptorOwnerFullControl();
|
||||
SecurityDescriptor createPipeSecurityDescriptorOwnerFullControlEveryoneWrite();
|
||||
SecurityDescriptor getObjectSecurityDescriptor(HANDLE handle);
|
||||
std::wstring sidToString(PSID sid);
|
||||
Sid stringToSid(const std::wstring &str);
|
||||
SecurityDescriptor stringToSd(const std::wstring &str);
|
||||
std::wstring sdToString(PSECURITY_DESCRIPTOR sd);
|
||||
DWORD rejectRemoteClientsPipeFlag();
|
||||
|
||||
#endif // WINPTY_WINDOWS_SECURITY_H
|
57
src/shared/WinptyException.cc
Executable file
57
src/shared/WinptyException.cc
Executable file
@ -0,0 +1,57 @@
|
||||
// Copyright (c) 2016 Ryan Prichard
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to
|
||||
// deal in the Software without restriction, including without limitation the
|
||||
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
// sell copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
// IN THE SOFTWARE.
|
||||
|
||||
#include "WinptyException.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "StringBuilder.h"
|
||||
|
||||
namespace {
|
||||
|
||||
class ExceptionImpl : public WinptyException {
|
||||
public:
|
||||
ExceptionImpl(const wchar_t *what) :
|
||||
m_what(std::make_shared<std::wstring>(what)) {}
|
||||
virtual const wchar_t *what() const WINPTY_NOEXCEPT {
|
||||
return m_what->c_str();
|
||||
}
|
||||
private:
|
||||
// Using a shared_ptr ensures that copying the object raises no exception.
|
||||
std::shared_ptr<std::wstring> m_what;
|
||||
};
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
void throwWinptyException(const wchar_t *what) {
|
||||
throw ExceptionImpl(what);
|
||||
}
|
||||
|
||||
void throwWindowsError(const wchar_t *prefix, DWORD errorCode) {
|
||||
WStringBuilder sb(64);
|
||||
if (prefix != nullptr) {
|
||||
sb << prefix << L": ";
|
||||
}
|
||||
// It might make sense to use FormatMessage here, but IIRC, its API is hard
|
||||
// to figure out.
|
||||
sb << L"Windows error " << errorCode;
|
||||
throwWinptyException(sb.c_str());
|
||||
}
|
@ -21,6 +21,8 @@
|
||||
#ifndef WINPTY_EXCEPTION_H
|
||||
#define WINPTY_EXCEPTION_H
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#if defined(__GNUC__)
|
||||
#define WINPTY_NOEXCEPT noexcept
|
||||
#elif defined(_MSC_VER) && _MSC_VER >= 1900
|
||||
@ -35,4 +37,7 @@ public:
|
||||
virtual ~WinptyException() {}
|
||||
};
|
||||
|
||||
void throwWinptyException(const wchar_t *what);
|
||||
void throwWindowsError(const wchar_t *prefix, DWORD error=GetLastError());
|
||||
|
||||
#endif // WINPTY_EXCEPTION_H
|
||||
|
@ -84,6 +84,7 @@
|
||||
'shared/WinptyAssert.h',
|
||||
'shared/WinptyAssert.cc',
|
||||
'shared/WinptyException.h',
|
||||
'shared/WinptyException.cc',
|
||||
'shared/WinptyVersion.h',
|
||||
'shared/WinptyVersion.cc',
|
||||
'shared/winpty_snprintf.h',
|
||||
@ -115,9 +116,12 @@
|
||||
'shared/StringBuilder.h',
|
||||
'shared/StringUtil.cc',
|
||||
'shared/StringUtil.h',
|
||||
'shared/WindowsSecurity.cc',
|
||||
'shared/WindowsSecurity.h',
|
||||
'shared/WinptyAssert.h',
|
||||
'shared/WinptyAssert.cc',
|
||||
'shared/WinptyException.h',
|
||||
'shared/WinptyException.cc',
|
||||
'shared/winpty_snprintf.h',
|
||||
],
|
||||
},
|
||||
|
Loading…
Reference in New Issue
Block a user