├── .gitignore ├── .editorconfig ├── test ├── CMakeLists.txt ├── test.cpp ├── pipe.cpp ├── user.cpp └── events.cpp ├── cmake ├── FindClara.cmake └── Findsodium.cmake ├── lib ├── common │ ├── common.cpp │ ├── winsupport.cpp │ ├── events.cpp │ └── overlapped.cpp ├── server │ ├── server.cpp │ ├── namedpipehandlefactory.cpp │ ├── main.cpp │ ├── session.cpp │ └── clientconnection.cpp └── client │ └── main.cpp ├── include └── wsudo │ ├── ntapi.h │ ├── client.h │ ├── session.h │ ├── server.h │ ├── winsupport.h │ ├── events.h │ └── wsudo.h ├── CMakeLists.txt ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /.vscode/ 2 | /bin/ 3 | /build/ 4 | /compile_commands.json 5 | 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | find_package(Catch2 CONFIG REQUIRED) 2 | 3 | set(SOURCES test.cpp events.cpp pipe.cpp user.cpp) 4 | 5 | add_executable(test ${SOURCES}) 6 | target_link_libraries(test Catch2::Catch2 wsudo_common wsudo_server wsudo_client) 7 | 8 | include(CTest) 9 | include(Catch) 10 | catch_discover_tests(test) 11 | -------------------------------------------------------------------------------- /cmake/FindClara.cmake: -------------------------------------------------------------------------------- 1 | find_path(Clara_INCLUDE_DIRS clara.hpp) 2 | 3 | if(Clara_INCLUDE_DIRS) 4 | add_library(Clara INTERFACE IMPORTED) 5 | target_include_directories(Clara INTERFACE ${Clara_INCLUDE_DIRS}) 6 | endif() 7 | 8 | include(FindPackageHandleStandardArgs) 9 | find_package_handle_standard_args(Clara REQUIRED_VARS Clara_INCLUDE_DIRS) 10 | -------------------------------------------------------------------------------- /test/test.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/wsudo.h" 2 | 3 | #include 4 | 5 | #define CATCH_CONFIG_RUNNER 6 | #include 7 | 8 | using namespace wsudo; 9 | 10 | int main(int argc, char *argv[]) { 11 | log::g_outLogger = spdlog::stdout_color_mt("wsudo.out"); 12 | log::g_errLogger = spdlog::stderr_color_mt("wsudo.err"); 13 | 14 | WSUDO_SCOPEEXIT { spdlog::drop_all(); }; 15 | 16 | int result = Catch::Session().run(argc, argv); 17 | 18 | return result; 19 | } 20 | -------------------------------------------------------------------------------- /cmake/Findsodium.cmake: -------------------------------------------------------------------------------- 1 | find_path(sodium_INCLUDE_DIR sodium.h) 2 | find_library(sodium_LIBRARY NAMES libsodium sodium) 3 | 4 | if(sodium_INCLUDE_DIR AND sodium_LIBRARY AND EXISTS ${sodium_INCLUDE_DIR}/sodium/core.h) 5 | add_library(sodium INTERFACE IMPORTED) 6 | target_link_libraries(sodium INTERFACE ${sodium_LIBRARY}) 7 | target_include_directories(sodium INTERFACE ${sodium_INCLUDE_DIR}) 8 | endif() 9 | 10 | include(FindPackageHandleStandardArgs) 11 | find_package_handle_standard_args(sodium REQUIRED_VARS sodium_INCLUDE_DIR sodium_LIBRARY HANDLE_COMPONENTS) 12 | -------------------------------------------------------------------------------- /lib/common/common.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/wsudo.h" 2 | 3 | namespace wsudo { 4 | 5 | namespace log { 6 | std::shared_ptr g_outLogger; 7 | std::shared_ptr g_errLogger; 8 | } 9 | 10 | const wchar_t *const PipeFullPath = L"\\\\.\\pipe\\wsudo_token_server"; 11 | 12 | namespace msg { 13 | namespace client { 14 | const char *const QuerySession = "QSES"; 15 | const char *const Credential = "CRED"; 16 | const char *const Bless = "BLES"; 17 | } 18 | 19 | namespace server { 20 | const char *const Success = "SUCC"; 21 | const char *const InvalidMessage = "MESG"; 22 | const char *const InternalError = "INTE"; 23 | const char *const AccessDenied = "DENY"; 24 | } 25 | } // namespace msg 26 | 27 | } // namespace wsudo 28 | -------------------------------------------------------------------------------- /test/pipe.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/server.h" 2 | #include "wsudo/client.h" 3 | 4 | #include 5 | 6 | using namespace wsudo; 7 | 8 | const wchar_t *const TestPipeName = L"\\\\.\\pipe\\wsudo_test_pipe"; 9 | 10 | TEST_CASE("Named pipe handle factory works", "[pipe]") { 11 | server::NamedPipeHandleFactory factory(TestPipeName); 12 | REQUIRE(factory.good()); 13 | auto firstHandle = factory(); 14 | REQUIRE(firstHandle != nullptr); 15 | auto secondHandle = factory(); 16 | REQUIRE(secondHandle != nullptr); 17 | } 18 | 19 | #if 0 20 | TEST_CASE("Named pipe client connections work", "[pipe]") { 21 | server::NamedPipeHandleFactory factory(TestPipeName); 22 | REQUIRE(factory.good()); 23 | 24 | auto firstHandle = factory(); 25 | auto secondHandle = factory(); 26 | 27 | ClientConnection firstClient(TestPipeName); 28 | REQUIRE(firstClient.good()); 29 | ClientConnection secondClient(TestPipeName); 30 | REQUIRE(secondClient.good()); 31 | } 32 | #endif 33 | -------------------------------------------------------------------------------- /include/wsudo/ntapi.h: -------------------------------------------------------------------------------- 1 | #if defined(WSUDO_NTAPI_H) || !defined(WSUDO_WSUDO_H) 2 | #error "Do not include this file directly; use wsudo.h." 3 | #else 4 | #define WSUDO_NTAPI_H 5 | 6 | /** 7 | * This header contains parts of the NT API not in Windows.h. Some of the 8 | * structures are incomplete; in those cases we don't have any need for the 9 | * rest of them. 10 | */ 11 | 12 | namespace wsudo::nt { 13 | 14 | typedef struct _PROCESS_ACCESS_TOKEN { 15 | HANDLE Token; 16 | HANDLE Thread; 17 | } PROCESS_ACCESS_TOKEN, *PPROCESS_ACCESS_TOKEN; 18 | 19 | constexpr ::PROCESSINFOCLASS ProcessAccessToken = (::PROCESSINFOCLASS)9; 20 | 21 | typedef ULONG (WINAPI *RtlNtStatusToDosError_t)(NTSTATUS); 22 | typedef NTSTATUS (WINAPI *NtQueryInformationProcess_t)( 23 | HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG 24 | ); 25 | typedef NTSTATUS (WINAPI *NtSetInformationProcess_t)( 26 | HANDLE, PROCESSINFOCLASS, PVOID, ULONG 27 | ); 28 | 29 | } // namespace wsudo::nt 30 | 31 | #endif // WSUDO_NTAPI_H 32 | -------------------------------------------------------------------------------- /lib/server/server.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/server.h" 2 | #include "wsudo/session.h" 3 | 4 | #pragma comment(lib, "Advapi32.lib") 5 | 6 | using namespace wsudo; 7 | using namespace wsudo::server; 8 | 9 | void wsudo::server::serverMain(Config &config) { 10 | using namespace events; 11 | 12 | session::SessionManager sessionManager{60 * 10}; 13 | 14 | NamedPipeHandleFactory pipeHandleFactory{config.pipeName.c_str()}; 15 | if (!pipeHandleFactory) { 16 | config.status = StatusCreatePipeFailed; 17 | return; 18 | } 19 | 20 | EventListener listener; 21 | *config.quitEvent = CreateEventW(nullptr, true, false, nullptr); 22 | listener.emplace(*config.quitEvent, [](EventListener &listener) { 23 | listener.stop(); 24 | return EventStatus::Finished; 25 | }); 26 | 27 | for (int id = 1; id <= MaxPipeConnections; ++id) { 28 | listener.emplace(pipeHandleFactory(), id, 29 | sessionManager); 30 | } 31 | 32 | EventStatus status = listener.run(); 33 | 34 | if (status == EventStatus::Failed) { 35 | config.status = StatusEventFailed; 36 | } else { 37 | config.status = StatusOk; 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /test/user.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/wsudo.h" 2 | #include 3 | 4 | TEST_CASE("LogonUser", "[.logon]") { 5 | wchar_t username[256]; 6 | wchar_t password[256]; 7 | DWORD length; 8 | 9 | length = GetEnvironmentVariableW(L"WSUSER", username, sizeof(username)); 10 | if (length == 0) { 11 | FAIL("Username (env WSUSER) not present."); 12 | } else if (length >= sizeof(username)) { 13 | FAIL("Username (env WSUSER) too long."); 14 | } 15 | 16 | length = GetEnvironmentVariableW(L"WSPASSWORD", password, sizeof(password)); 17 | if (length == 0) { 18 | FAIL("Password (env WSPASSWORD) not present."); 19 | } else if (length >= sizeof(password)) { 20 | FAIL("Password (env WSPASSWORD) too long."); 21 | } 22 | 23 | wsudo::HObject token; 24 | wsudo::HLocalPtr pSid; 25 | PVOID pProfileBuffer; 26 | DWORD profileLength; 27 | QUOTA_LIMITS quotaLimits; 28 | if (!LogonUserExW(username, L".", password, LOGON32_LOGON_NETWORK, 29 | LOGON32_PROVIDER_DEFAULT, &token, &pSid, &pProfileBuffer, 30 | &profileLength, "aLimits)) 31 | { 32 | FAIL("LogonUserExW failed" << wsudo::lastErrorString()); 33 | } 34 | REQUIRE(!!token); 35 | } 36 | -------------------------------------------------------------------------------- /test/events.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/events.h" 2 | 3 | #include 4 | 5 | TEST_CASE("EventListener chooses correctly.", "[events]") { 6 | using namespace wsudo::events; 7 | 8 | EventListener listener; 9 | FILETIME systemTime; 10 | int timerNr = 0; 11 | 12 | GetSystemTimeAsFileTime(&systemTime); 13 | 14 | // id = a number to identify the timer. 15 | // duration = time in milliseconds before the timer is triggered. 16 | auto addTimer = [&](int id, long duration) { 17 | HANDLE timer = CreateWaitableTimerW(nullptr, true, nullptr); 18 | 19 | union { 20 | FILETIME fileTime; 21 | LARGE_INTEGER dueTime; 22 | }; 23 | fileTime = systemTime; 24 | // Timers use 100ns intervals, but we want ms. 25 | dueTime.QuadPart += duration * 10000; 26 | 27 | SetWaitableTimer(timer, &dueTime, 0, nullptr, nullptr, false); 28 | 29 | listener.emplace(timer, [id, &timerNr](EventListener &){ 30 | timerNr = id; 31 | return EventStatus::Finished; 32 | }); 33 | }; 34 | 35 | // Timer order: 2, 3, 1. 36 | addTimer(1, 30); 37 | addTimer(2, 10); 38 | addTimer(3, 20); 39 | 40 | REQUIRE(listener.next() == EventStatus::Ok); 41 | REQUIRE(timerNr == 2); 42 | REQUIRE(listener.next() == EventStatus::Ok); 43 | REQUIRE(timerNr == 3); 44 | REQUIRE(listener.next() == EventStatus::Finished); 45 | REQUIRE(timerNr == 1); 46 | } 47 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10 FATAL_ERROR) 2 | 3 | project(wsudo) 4 | set(wsudo_VERSION_MAJOR 0) 5 | set(wsudo_VERSION_MINOR 1) 6 | set(wsudo_VERSION_PATCH 0) 7 | 8 | set(CMAKE_CXX_STANDARD 17) 9 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 10 | set(CMAKE_CXX_EXTENSIONS OFF) 11 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 12 | 13 | option(WSUDO_BUILD_TESTS "Build tests" ON) 14 | 15 | if(MSVC) 16 | add_compile_options(-diagnostics:caret) 17 | endif() 18 | 19 | list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) 20 | 21 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$") 22 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) 23 | 24 | find_package(spdlog CONFIG REQUIRED) 25 | find_package(fmt CONFIG REQUIRED) 26 | 27 | set(COMMON_SRC 28 | common.cpp 29 | events.cpp 30 | overlapped.cpp 31 | winsupport.cpp 32 | ) 33 | list(TRANSFORM COMMON_SRC PREPEND "lib/common/") 34 | 35 | set(CLIENT_SRC 36 | main.cpp 37 | ) 38 | list(TRANSFORM CLIENT_SRC PREPEND "lib/client/") 39 | 40 | set(SERVER_SRC 41 | clientconnection.cpp 42 | main.cpp 43 | namedpipehandlefactory.cpp 44 | server.cpp 45 | session.cpp 46 | ) 47 | list(TRANSFORM SERVER_SRC PREPEND "lib/server/") 48 | 49 | include_directories(${PROJECT_SOURCE_DIR}/include) 50 | link_libraries(spdlog::spdlog fmt::fmt-header-only) 51 | 52 | add_library(wsudo_common STATIC ${COMMON_SRC}) 53 | add_library(wsudo_client STATIC ${CLIENT_SRC}) 54 | add_library(wsudo_server STATIC ${SERVER_SRC}) 55 | 56 | add_executable(wsudo lib/client/main.cpp) 57 | add_executable(TokenServer lib/server/main.cpp) 58 | 59 | target_link_libraries(wsudo wsudo_client wsudo_common) 60 | target_link_libraries(TokenServer wsudo_server wsudo_common) 61 | 62 | if(WSUDO_BUILD_TESTS) 63 | add_subdirectory(test) 64 | endif() 65 | -------------------------------------------------------------------------------- /lib/common/winsupport.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/wsudo.h" 2 | 3 | #include 4 | 5 | namespace wsudo { 6 | 7 | #pragma warning(push) 8 | #pragma warning(disable: 4996) // codecvt deprecation warning 9 | 10 | std::string to_utf8(std::wstring_view utf16str) { 11 | if (utf16str.empty()) { 12 | return std::string{}; 13 | } 14 | 15 | return std::wstring_convert, wchar_t>{} 16 | .to_bytes(&utf16str.front(), &utf16str.back() + 1); 17 | } 18 | 19 | std::wstring to_utf16(std::string_view utf8str) { 20 | if (utf8str.empty()) { 21 | return std::wstring{}; 22 | } 23 | 24 | return std::wstring_convert, wchar_t>{} 25 | .from_bytes(&utf8str.front(), &utf8str.back() + 1); 26 | } 27 | 28 | #pragma warning(pop) 29 | 30 | bool setThreadName(const wchar_t *name) { 31 | try { 32 | return LinkedModule(L"kernel32.dll") 33 | .get("SetThreadDescription")( 34 | GetCurrentThread(), name 35 | ) == S_OK; 36 | } catch (module_load_error &) { 37 | return false; 38 | } 39 | } 40 | 41 | std::string lastErrorString(DWORD status) { 42 | constexpr DWORD bufferSize = 1024; 43 | char buffer[bufferSize]; 44 | // MSDN: Need to specify IGNORE_INSERTS with FROM_SYSTEM to avoid potential 45 | // bad memory access. 46 | auto size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | 47 | FORMAT_MESSAGE_IGNORE_INSERTS, 48 | nullptr, status, 0, buffer, bufferSize, nullptr); 49 | // Get rid of the final new line. 50 | if (size && buffer[size - 1] == '\n') { 51 | --size; 52 | if (size && buffer[size - 1] == '\r') { 53 | --size; 54 | } 55 | } 56 | return std::string{buffer, buffer + size}; 57 | } 58 | 59 | } // namespace wsudo 60 | 61 | -------------------------------------------------------------------------------- /include/wsudo/client.h: -------------------------------------------------------------------------------- 1 | #ifndef WSUDO_CLIENT_H 2 | #define WSUDO_CLIENT_H 3 | 4 | #include "wsudo.h" 5 | 6 | #include 7 | 8 | namespace wsudo { 9 | 10 | // Codes returned by client main indicating the reason for exiting. 11 | enum ClientExitCode { 12 | ClientExitOk = 0, 13 | ClientExitAccessDenied = 225, 14 | ClientExitUserCanceled = 226, 15 | ClientExitCreateProcessError = 227, 16 | ClientExitInvalidUsage = 228, 17 | ClientExitSystemError = 229, 18 | ClientExitServerNotFound = 230, 19 | }; 20 | 21 | // Returns a description of a ClientExitCode. 22 | static inline const char *clientExitToString(ClientExitCode code) { 23 | switch (code) { 24 | default: 25 | return "unknown"; 26 | case ClientExitOk: 27 | return "ok"; 28 | case ClientExitAccessDenied: 29 | return "access denied"; 30 | case ClientExitUserCanceled: 31 | return "user canceled"; 32 | case ClientExitCreateProcessError: 33 | return "error creating process"; 34 | case ClientExitInvalidUsage: 35 | return "invalid usage"; 36 | case ClientExitSystemError: 37 | return "system error"; 38 | case ClientExitServerNotFound: 39 | return "server not found"; 40 | } 41 | } 42 | 43 | class ClientConnection { 44 | HObject _pipe; 45 | std::vector _buffer; 46 | 47 | constexpr static int MaxConnectAttempts = 3; 48 | 49 | void connect( 50 | LPSECURITY_ATTRIBUTES secAttr, 51 | const wchar_t *pipeName, 52 | int attempts 53 | ); 54 | 55 | public: 56 | explicit ClientConnection(const wchar_t *pipeName); 57 | 58 | bool good() const { return !!_pipe; } 59 | explicit operator bool() const { return good(); } 60 | 61 | bool negotiate(const char *credentials, size_t length); 62 | bool bless(HANDLE process); 63 | 64 | bool readServerMessage(); 65 | }; 66 | 67 | } // namespace wsudo 68 | 69 | #endif // WSUDO_CLIENT_H 70 | 71 | -------------------------------------------------------------------------------- /include/wsudo/session.h: -------------------------------------------------------------------------------- 1 | #ifndef WSUDO_SESSION_H 2 | #define WSUDO_SESSION_H 3 | 4 | #include "wsudo.h" 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | namespace wsudo::session { 12 | 13 | class Session; 14 | 15 | class SessionManager { 16 | public: 17 | explicit SessionManager(unsigned defaultTtlSeconds) noexcept; 18 | SessionManager(const SessionManager &) = delete; 19 | SessionManager &operator=(const SessionManager &) = delete; 20 | SessionManager(SessionManager &&) = default; 21 | SessionManager &operator=(SessionManager &&) = default; 22 | 23 | std::shared_ptr find(std::wstring_view username, 24 | std::wstring_view domain = {}); 25 | 26 | template 27 | std::shared_ptr create(Args &&...args) { 28 | return store(Session(*this, std::forward(args)...)); 29 | } 30 | 31 | unsigned defaultTtlSeconds() const { 32 | return _defaultTtlSeconds; 33 | } 34 | 35 | private: 36 | std::shared_ptr store(Session &&session); 37 | 38 | unsigned _defaultTtlSeconds; 39 | HObject _timer; 40 | std::wstring _localDomain; 41 | std::unordered_map> _sessions; 42 | }; 43 | 44 | class Session { 45 | friend class SessionManager; 46 | 47 | // Password is a move reference in the hopes that we will get the only copy 48 | // and erase it after we're done with it. 49 | Session(const SessionManager &manager, std::wstring_view username, 50 | std::wstring_view domain, std::wstring &&password, 51 | unsigned ttlSeconds) noexcept; 52 | 53 | Session(const SessionManager &manager, std::wstring_view username, 54 | std::wstring_view domain, std::wstring &&password) noexcept; 55 | 56 | public: 57 | Session(const Session &) = delete; 58 | Session &operator=(const Session &) = delete; 59 | 60 | Session(Session &&) = default; 61 | Session &operator=(Session &&) = default; 62 | 63 | std::wstring_view username() const { 64 | return _username; 65 | } 66 | 67 | std::wstring_view domain() const { 68 | return _domain; 69 | } 70 | 71 | HANDLE token() const { 72 | return _token; 73 | } 74 | 75 | PSID psid() const { 76 | return _pSid; 77 | } 78 | 79 | explicit operator bool() const { 80 | return !!_token; 81 | } 82 | 83 | private: 84 | const std::wstring _username; 85 | const std::wstring _domain; 86 | HObject _token; 87 | HLocalPtr _pSid; 88 | // The amount of time this session will be kept open without being referenced. 89 | // Each time the session is used, its lifetime is reset to this value. 90 | unsigned _ttlResetSeconds; 91 | // The time when this session expires if left untouched. 92 | unsigned _ttlExpiresSeconds; 93 | }; 94 | 95 | } // namespace wsudo::session 96 | 97 | #endif // WSUDO_SESSION_H_ 98 | -------------------------------------------------------------------------------- /lib/server/namedpipehandlefactory.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/server.h" 2 | 3 | using namespace wsudo; 4 | using namespace wsudo::server; 5 | 6 | NamedPipeHandleFactory::NamedPipeHandleFactory(LPCWSTR pipeName) noexcept 7 | : _pipeName{pipeName} 8 | { 9 | _sidAuth = SECURITY_WORLD_SID_AUTHORITY; 10 | if (!AllocateAndInitializeSid(&_sidAuth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 11 | 0, 0, 0, &_sid)) 12 | { 13 | return; 14 | } 15 | 16 | _explicitAccess.grfAccessPermissions = SYNCHRONIZE | GENERIC_READ | 17 | GENERIC_WRITE; 18 | _explicitAccess.grfAccessMode = SET_ACCESS; 19 | _explicitAccess.grfInheritance = NO_INHERITANCE; 20 | _explicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID; 21 | _explicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; 22 | _explicitAccess.Trustee.ptstrName = (LPWSTR)&_sid; 23 | 24 | if (!SUCCEEDED(SetEntriesInAclW(1, &_explicitAccess, nullptr, &_acl))) { 25 | return; 26 | } 27 | 28 | _securityDescriptor = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); 29 | if (!_securityDescriptor) { 30 | return; 31 | } 32 | 33 | if (!InitializeSecurityDescriptor(_securityDescriptor, 34 | SECURITY_DESCRIPTOR_REVISION)) 35 | { 36 | return; 37 | } 38 | 39 | if (!SetSecurityDescriptorDacl(_securityDescriptor, true, _acl, false)) { 40 | return; 41 | } 42 | 43 | _securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); 44 | _securityAttributes.bInheritHandle = false; 45 | _securityAttributes.lpSecurityDescriptor = _securityDescriptor; 46 | 47 | log::debug("Named pipe security attributes initialized."); 48 | } 49 | 50 | HObject NamedPipeHandleFactory::operator()() { 51 | if (!*this) { 52 | return HObject{}; 53 | } 54 | 55 | DWORD openMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED; 56 | if (_firstInstance) { 57 | openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE; 58 | } 59 | 60 | HANDLE pipe = CreateNamedPipeW(_pipeName, openMode, 61 | PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | 62 | PIPE_REJECT_REMOTE_CLIENTS, 63 | MaxPipeConnections, PipeBufferSize, 64 | PipeBufferSize, PipeDefaultTimeout, 65 | &_securityAttributes); 66 | 67 | // We consider failing to open the first instance a critical failure, 68 | // but subsequent failures are just warnings because we still have an open 69 | // connection. 70 | if (_firstInstance) { 71 | if (!pipe) { 72 | log::critical(L"Failed to create named pipe '{}'.", _pipeName); 73 | } else { 74 | log::info(L"Listening on '{}'.", _pipeName); 75 | } 76 | } else { 77 | if (!pipe) { 78 | log::warn(L"Failed to open named pipe instance for '{}'.", _pipeName); 79 | } 80 | } 81 | 82 | _firstInstance = false; 83 | return HObject{pipe}; 84 | } 85 | 86 | bool NamedPipeHandleFactory::good() const { 87 | // _securityAttributes is only set when all initialization succeeded. 88 | return _securityAttributes.nLength == sizeof(SECURITY_ATTRIBUTES); 89 | } 90 | -------------------------------------------------------------------------------- /lib/server/main.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/server.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace wsudo; 13 | 14 | static HANDLE gs_quitEventHandle = nullptr; 15 | BOOL WINAPI consoleControlHandler(DWORD event) { 16 | const char *eventName; 17 | switch (event) { 18 | case CTRL_C_EVENT: 19 | eventName = "Ctrl-C"; 20 | break; 21 | case CTRL_BREAK_EVENT: 22 | eventName = "Ctrl-Break"; 23 | break; 24 | case CTRL_CLOSE_EVENT: 25 | eventName = "close"; 26 | break; 27 | case CTRL_LOGOFF_EVENT: 28 | eventName = "logoff"; 29 | break; 30 | case CTRL_SHUTDOWN_EVENT: 31 | eventName = "shutdown"; 32 | break; 33 | default: 34 | eventName = "unknown"; 35 | } 36 | 37 | log::info("Received {} event, quitting.", eventName); 38 | if (!gs_quitEventHandle || !SetEvent(gs_quitEventHandle)) { 39 | log::warn("Can't notify server thread; forcing shutdown."); 40 | std::terminate(); 41 | } 42 | 43 | // If this attempt fails, next time we will hit the terminate() path. 44 | gs_quitEventHandle = nullptr; 45 | return true; 46 | } 47 | 48 | int wmain(int argc, wchar_t *argv[]) { 49 | log::g_outLogger = spdlog::stdout_color_mt("wsudo.out"); 50 | log::g_outLogger->set_level(spdlog::level::trace); 51 | log::g_errLogger = spdlog::stderr_color_mt("wsudo.err"); 52 | log::g_errLogger->set_level(spdlog::level::warn); 53 | #ifndef NDEBUG 54 | // Set a more compact, readable log format for debugging. 55 | spdlog::set_pattern("\033[90m[%T.%e]\033[m %^[%l]%$ %v"); 56 | #else 57 | // Use a complete format for release mode. 58 | spdlog::set_pattern("[%Y-%m-%d %T.%e] %^[%l]%$ %v"); 59 | #endif 60 | 61 | // VC++ deadlock bug 62 | WSUDO_SCOPEEXIT { spdlog::drop_all(); }; 63 | 64 | HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 65 | HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 66 | 67 | DWORD stdinMode, stdoutMode; 68 | GetConsoleMode(hStdin, &stdinMode); 69 | SetConsoleMode(hStdin, stdinMode | ENABLE_PROCESSED_INPUT); 70 | GetConsoleMode(hStdout, &stdoutMode); 71 | SetConsoleMode(hStdout, 72 | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | 73 | ENABLE_VIRTUAL_TERMINAL_PROCESSING); 74 | 75 | log::info("WSudo Token Server: Pid = {}.", GetCurrentProcessId()); 76 | 77 | // Clear control handlers and then set ours. 78 | if (!SetConsoleCtrlHandler(nullptr, false) || 79 | !SetConsoleCtrlHandler(consoleControlHandler, true)) 80 | { 81 | log::warn("Failed to set Ctrl-C handler; kill process to exit."); 82 | } else { 83 | log::info("Starting server. Press Ctrl-C to exit."); 84 | } 85 | 86 | // Restore console modes on exit. 87 | WSUDO_SCOPEEXIT { 88 | SetConsoleMode(hStdin, stdinMode); 89 | SetConsoleMode(hStdout, stdoutMode); 90 | }; 91 | 92 | server::Config config{ PipeFullPath, &gs_quitEventHandle }; 93 | std::thread serverThread{&server::serverMain, std::ref(config)}; 94 | serverThread.join(); 95 | log::info("Event loop returned {}.", server::statusToString(config.status)); 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /lib/common/events.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/events.h" 2 | #include "wsudo/wsudo.h" 3 | 4 | using namespace wsudo; 5 | using namespace wsudo::events; 6 | 7 | // {{{ EventHandler 8 | 9 | EventHandler::~EventHandler() { 10 | } 11 | 12 | bool EventHandler::reset() { 13 | // By default, event handlers cannot be reused. Subclasses must opt in to 14 | // this behavior. 15 | return false; 16 | } 17 | 18 | // }}} EventHandler 19 | 20 | // {{{ EventListener 21 | 22 | EventStatus EventListener::next(DWORD timeout) { 23 | log::trace("Waiting on {} events.", _events.size()); 24 | 25 | if (_events.size() == 0) { 26 | return EventStatus::Finished; 27 | } 28 | 29 | auto waitResult = WaitForMultipleObjects( 30 | static_cast(_events.size()), &_events[0], false, timeout 31 | ); 32 | 33 | if (waitResult == WAIT_TIMEOUT) { 34 | log::error("WaitForMultipleObjects timed out."); 35 | return EventStatus::Failed; 36 | } else if (waitResult >= WAIT_OBJECT_0 && 37 | waitResult < WAIT_OBJECT_0 + _events.size()) 38 | { 39 | size_t index = static_cast(waitResult - WAIT_OBJECT_0); 40 | log::trace("Event #{} signaled.", index); 41 | 42 | switch ((*_handlers[index])(*this)) { 43 | case EventStatus::Ok: 44 | log::trace("Event #{} returned Ok.", index); 45 | break; 46 | case EventStatus::Finished: 47 | if (_handlers[index]->reset()) { 48 | log::trace("Event #{} returned Finished and was reset.", index); 49 | } else { 50 | log::debug("Event #{} returned Finished and will be removed.", index); 51 | remove(index); 52 | } 53 | break; 54 | case EventStatus::Failed: 55 | if (_handlers[index]->reset()) { 56 | log::warn("Event #{} returned Failed, but reset succeeded.", index); 57 | } else { 58 | log::error("Event #{} returned Failed.", index); 59 | remove(index); 60 | } 61 | break; 62 | } 63 | } else if (waitResult >= WAIT_ABANDONED_0 && 64 | waitResult < WAIT_ABANDONED_0 + _events.size()) 65 | 66 | { 67 | size_t index = (size_t)(waitResult - WAIT_ABANDONED_0); 68 | log::error("Mutex abandoned state signaled for handler #{}.", index); 69 | remove(index); 70 | } else if (waitResult == WAIT_FAILED) { 71 | log::critical("WaitForMultipleObjects failed: {}", 72 | lastErrorString()); 73 | return EventStatus::Failed; 74 | } else { 75 | log::critical("WaitForMultipleObjects returned 0x{:X}: {}", waitResult, 76 | lastErrorString()); 77 | return EventStatus::Failed; 78 | } 79 | 80 | return _events.size() > 0 ? EventStatus::Ok : EventStatus::Finished; 81 | } 82 | 83 | EventStatus EventListener::run(DWORD timeout) { 84 | _running = true; 85 | 86 | auto status = EventStatus::Finished; 87 | while (_running) { 88 | status = next(timeout); 89 | if (status != EventStatus::Ok) { 90 | break; 91 | } 92 | } 93 | 94 | return status; 95 | } 96 | 97 | void EventListener::remove(size_t index) { 98 | if (index >= _handlers.size()) { 99 | log::error("Event index {} out of range.", index); 100 | return; 101 | } 102 | 103 | assert(_handlers.size() == _events.size()); 104 | 105 | _events.erase(_events.cbegin() + index); 106 | _handlers.erase(_handlers.cbegin() + index); 107 | } 108 | 109 | // }}} EventListener 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `wsudo`: Proof of concept sudo for Windows 2 | 3 | ## ⚠ Not production ready! 4 | This project is in the very early stages. It may have bugs and security holes. Use at your own risk! 5 | 6 | ## What does it look like? 7 | A terminal. Or two terminals currently. [See this short demo](https://raw.githubusercontent.com/parkovski/wsudo/assets/demo.mp4). 8 | 9 | ## How to build/run? 10 | Currently the only dependencies are spdlog, fmt, and the Windows SDK. I use vcpkg to install these. The project builds with CMake - I use the Ninja generator but the VS one is probably fine. After making sure your spdlog and fmt work, do: 11 | 12 | ```powershell 13 | ...\wsudo> mkdir build 14 | ...\wsudo> cd build 15 | ...\wsudo> cmake -G Ninja .. 16 | ...\wsudo> cmake --build . 17 | ``` 18 | 19 | This will produce two binaries in `bin\Debug`. To try it, start `TokenServer.exe` in an admin console; then in a separate unelevated console run `wsudo.exe `. Currently you need to provide the full path to the program. It will ask for your password, but this is not yet implemented so the password is always `password`. To see the difference in elevation status, try `wsudo.exe C:\Windows\System32\whoami.exe /groups` and look for the `Mandatory Label` section. 20 | 21 | ## What makes this one different? 22 | It uses a token server, which can be run as a system service, to remotely reassign the primary token for an interactive process. A process you create with the `wsudo.exe` command inherits the environment as if you just called the target command itself, but it starts elevated with no UAC involvement. 23 | 24 | ## How? 25 | There are three ways to create an elevated process: 26 | 1. Request elevation with UAC. 27 | 2. Be an executable signed by the Windows Publisher. 28 | 3. Be an elevated process. 29 | 30 | The system will automatically start services elevated, but they have their own environment, which is not very useful for command line purposes. However, there's a trick - you can start a regular restricted process suspended in your own session and notify the service, which uses `NtSetInformationProcess` to change the remote process token to an elevated one before it starts. 31 | 32 | I originally created a remote process in the service, but setting up the environment is tricky and requires digging through undocumented parts of the PEB. With this method, the system sets up all the inheritance correctly, and we only need one undocumented call to elevate the process. 33 | 34 | It may be possible to achieve this without any undocumented APIs by creating the process in the server and using `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS`. 35 | 36 | ## What features are missing? 37 | Most of them. Here are the big ones: 38 | - Create a token for the client user instead of just duplicating the server's token. 39 | - Cache the users' tokens for a while after a successful authentication (note: should be per-session). 40 | - Implement Windows service functionality for the server. 41 | - Create some type of "sudoers" config file or registry key and enforce permissions. 42 | - Improve the client's command line handling - shouldn't have to type the full path to an exe. 43 | - Improve error handling and write tests. 44 | 45 | ### Other ideas 46 | - Options to set user and privileges. 47 | - PowerShell wrapper cmdlets. 48 | - Integration with WSL sudo. 49 | - COM elevation. 50 | - Session selection. 51 | 52 | ## Additional resources 53 | * [OpenSSH's usage of LSA](https://github.com/PowerShell/openssh-portable/blob/latestw_all/contrib/win32/win32compat/win32_usertoken_utils.c) 54 | -------------------------------------------------------------------------------- /include/wsudo/server.h: -------------------------------------------------------------------------------- 1 | #ifndef WSUDO_SERVER_H 2 | #define WSUDO_SERVER_H 3 | 4 | #include "wsudo.h" 5 | #include "events.h" 6 | #include "session.h" 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | namespace wsudo::server { 15 | 16 | // Server status codes 17 | enum Status : int { 18 | StatusUnset = -1, 19 | StatusOk = 0, 20 | StatusCreatePipeFailed, 21 | StatusTimedOut, 22 | StatusEventFailed, 23 | }; 24 | 25 | inline const char *statusToString(Status status) { 26 | switch (status) { 27 | default: return "unknown status"; 28 | case StatusUnset: return "status not set"; 29 | case StatusOk: return "ok"; 30 | case StatusCreatePipeFailed: return "pipe creation failed"; 31 | case StatusTimedOut: return "timed out"; 32 | case StatusEventFailed: return "event failed"; 33 | } 34 | } 35 | 36 | // Creates connections to a named pipe with the necessary security attributes. 37 | class NamedPipeHandleFactory final { 38 | public: 39 | explicit NamedPipeHandleFactory(LPCWSTR pipeName) noexcept; 40 | 41 | // Create a new pipe connection. 42 | HObject operator()(); 43 | 44 | // Returns true if initialization succeeded and a connection can be created. 45 | bool good() const; 46 | 47 | // 48 | explicit operator bool() const 49 | { return good(); } 50 | 51 | private: 52 | bool _firstInstance = true; 53 | LPCWSTR _pipeName; 54 | SID_IDENTIFIER_AUTHORITY _sidAuth; 55 | Handle _sid; 56 | EXPLICIT_ACCESS_W _explicitAccess; 57 | HLocalPtr _acl; 58 | HLocalPtr _securityDescriptor; 59 | SECURITY_ATTRIBUTES _securityAttributes; 60 | }; 61 | 62 | class ClientConnectionHandler : public events::EventOverlappedIO { 63 | public: 64 | using Self = ClientConnectionHandler; 65 | using Callback = recursive_mem_callback; 66 | 67 | explicit ClientConnectionHandler(HObject pipe, int clientId, 68 | session::SessionManager &sessionManager) 69 | noexcept; 70 | 71 | bool reset() override; 72 | 73 | events::EventStatus operator()(events::EventListener &) override; 74 | 75 | protected: 76 | HANDLE fileHandle() const override { 77 | return _pipe; 78 | } 79 | 80 | private: 81 | HObject _pipe; 82 | int _clientId; 83 | session::SessionManager &_sessionManager; 84 | Callback _callback; 85 | HObject _userToken{}; 86 | 87 | void createResponse(const char *header, 88 | std::string_view message = std::string_view{}); 89 | 90 | Callback beginConnect(); 91 | Callback endConnect(); 92 | Callback read(); 93 | Callback respond(); 94 | Callback resetConnection(); 95 | 96 | // Returns true to read another message, false to reset the connection. 97 | bool dispatchMessage(); 98 | bool tryToLogonUser(char *username, char *password); 99 | bool bless(HANDLE remoteHandle); 100 | }; 101 | 102 | // Server configuration. 103 | struct Config { 104 | // Named pipe filename. 105 | std::wstring pipeName; 106 | 107 | // Pointer to global quit event handle. 108 | HANDLE *quitEvent; 109 | 110 | // Server status return value. 111 | Status status = StatusUnset; 112 | 113 | explicit Config(std::wstring pipeName, HANDLE *quitEvent) 114 | : pipeName(std::move(pipeName)), quitEvent(quitEvent) 115 | {} 116 | }; 117 | 118 | // Run the server. This function will continue until an error occurs or the 119 | // quit event is triggered. After it returns, config.status will be set to 120 | // the server's exit status. 121 | void serverMain(Config &config); 122 | 123 | } // namespace wsudo::server 124 | 125 | #endif // WSUDO_SERVER_H 126 | 127 | -------------------------------------------------------------------------------- /lib/server/session.cpp: -------------------------------------------------------------------------------- 1 | #define WSUDO_NO_NT_API 2 | #include "wsudo/session.h" 3 | #include 4 | #include 5 | 6 | #define NT_SUCCESS(status) ((long)(status) >= 0) 7 | 8 | using namespace wsudo; 9 | using namespace wsudo::session; 10 | 11 | SessionManager::SessionManager(unsigned defaultTtlSeconds) noexcept 12 | : _defaultTtlSeconds{defaultTtlSeconds}, 13 | _timer{CreateWaitableTimerW(nullptr, false, nullptr)} 14 | { 15 | NTSTATUS status; 16 | LSA_OBJECT_ATTRIBUTES attr{{}}; 17 | Handle policy; 18 | 19 | status = LsaOpenPolicy(nullptr, &attr, POLICY_VIEW_LOCAL_INFORMATION, 20 | &policy); 21 | if (!NT_SUCCESS(status)) { 22 | log::error("LsaOpenPolicy failed: {}", 23 | lastErrorString(LsaNtStatusToWinError(status))); 24 | return; 25 | } 26 | 27 | Handle accountDomain; 28 | status = LsaQueryInformationPolicy(policy, PolicyAccountDomainInformation, 29 | reinterpret_cast(&accountDomain)); 30 | if (!NT_SUCCESS(status)) { 31 | log::error("LsaQueryInformationPolicy failed: {}", 32 | lastErrorString(LsaNtStatusToWinError(status))); 33 | return; 34 | } 35 | 36 | // Note: Length is the size in bytes, not including terminating null (if any). 37 | // wstring constructor expects a length in wchar_t sized characters. 38 | _localDomain = std::wstring{accountDomain->DomainName.Buffer, 39 | (size_t)(accountDomain->DomainName.Length) >> 1}; 40 | log::info(L"Session manager initialized for local domain '{}'.", 41 | _localDomain); 42 | } 43 | 44 | std::shared_ptr SessionManager::find(std::wstring_view username, 45 | std::wstring_view domain) 46 | { 47 | // TODO: Use full user@domain format. 48 | (void)domain; 49 | auto it = _sessions.find(username); 50 | if (it == _sessions.end()) { 51 | return std::shared_ptr{}; 52 | } 53 | return it->second; 54 | } 55 | 56 | std::shared_ptr SessionManager::store(Session &&session) { 57 | //std::wstring_view domain{session.domain()}; 58 | std::wstring_view name{session.username()}; 59 | if (!session) { 60 | log::info(L"Failed login attempt for {}.", name); 61 | return std::shared_ptr{}; 62 | } 63 | log::debug(L"Session username: {}.", name); 64 | auto [it, inserted] = _sessions.try_emplace( 65 | name, std::make_shared(std::move(session)) 66 | ); 67 | if (!inserted) { 68 | log::warn(L"Session already exists for '{}'.", name); 69 | } 70 | return it->second; 71 | } 72 | 73 | //////////////////////////////////////////////////////////////////////////////// 74 | // Session // 75 | //////////////////////////////////////////////////////////////////////////////// 76 | 77 | Session::Session(const SessionManager &, std::wstring_view username, 78 | std::wstring_view domain, std::wstring &&password, 79 | unsigned ttlSeconds) noexcept 80 | : _username{username}, 81 | _domain{domain}, 82 | _ttlResetSeconds{ttlSeconds}, 83 | _ttlExpiresSeconds{0} 84 | { 85 | PVOID pProfileBuffer; 86 | DWORD profileLength; 87 | QUOTA_LIMITS quotaLimits; 88 | if (!LogonUserExW(_username.c_str(), _domain.c_str(), password.c_str(), 89 | LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, 90 | &_token, &_pSid, &pProfileBuffer, &profileLength, 91 | "aLimits)) 92 | { 93 | log::debug("LogonUserExW failed: {}", lastErrorString()); 94 | } 95 | 96 | // TODO: Set expiration time. 97 | } 98 | 99 | Session::Session(const SessionManager &manager, std::wstring_view username, 100 | std::wstring_view domain, std::wstring &&password) noexcept 101 | : Session(manager, username, domain, std::move(password), 102 | manager.defaultTtlSeconds()) 103 | { 104 | } 105 | -------------------------------------------------------------------------------- /lib/common/overlapped.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/server.h" 2 | 3 | using namespace wsudo; 4 | using namespace wsudo::events; 5 | 6 | // Helpers {{{ 7 | 8 | inline void setOverlappedOffset(LPOVERLAPPED overlapped, size_t offset) { 9 | overlapped->Pointer = reinterpret_cast(offset); 10 | // MSDN: Zero unused members before use. 11 | overlapped->Internal = 0; 12 | overlapped->InternalHigh = 0; 13 | } 14 | 15 | // }}} 16 | 17 | EventOverlappedIO::EventOverlappedIO(bool isEventSet) noexcept { 18 | _overlapped.hEvent = CreateEventW(nullptr, false, isEventSet, nullptr); 19 | } 20 | 21 | EventOverlappedIO::~EventOverlappedIO() { 22 | CloseHandle(_overlapped.hEvent); 23 | } 24 | 25 | EventStatus EventOverlappedIO::beginRead() { 26 | _ioState = IOState::Reading; 27 | setOverlappedOffset(&_overlapped, _offset); 28 | _buffer.resize(_offset + ChunkSize); 29 | 30 | if (ReadFile(fileHandle(), _buffer.data() + _offset, ChunkSize, 31 | nullptr, &_overlapped)) 32 | { 33 | // Interpret the results. 34 | return endRead(); 35 | } 36 | auto error = GetLastError(); 37 | if (error == ERROR_IO_PENDING || error == ERROR_MORE_DATA) { 38 | log::debug("Read in progress."); 39 | return EventStatus::Ok; 40 | } else { 41 | log::error("ReadFile failed: {}", lastErrorString(error)); 42 | _ioState = IOState::Inactive; 43 | return EventStatus::Failed; 44 | } 45 | } 46 | 47 | EventStatus EventOverlappedIO::endRead() { 48 | DWORD bytesTransferred; 49 | if (GetOverlappedResult(fileHandle(), &_overlapped, &bytesTransferred, false)) 50 | { 51 | _offset += bytesTransferred; 52 | log::debug("Read finished: {} bytes.", _offset); 53 | _buffer.resize(_offset); 54 | _ioState = IOState::Inactive; 55 | return EventStatus::Finished; 56 | } 57 | auto error = GetLastError(); 58 | if (error == ERROR_IO_PENDING) { 59 | return EventStatus::Ok; 60 | } else if (error == ERROR_MORE_DATA) { 61 | return beginRead(); 62 | } else if (error == ERROR_BROKEN_PIPE) { 63 | log::info("Connection ended by client."); 64 | _ioState = IOState::Failed; 65 | return EventStatus::Failed; 66 | } 67 | log::error("Read failed: {}", lastErrorString(error)); 68 | _ioState = IOState::Failed; 69 | return EventStatus::Failed; 70 | } 71 | 72 | EventStatus EventOverlappedIO::beginWrite() { 73 | _ioState = IOState::Writing; 74 | setOverlappedOffset(&_overlapped, _offset); 75 | 76 | if (WriteFile(fileHandle(), _buffer.data() + _offset, 77 | static_cast(_buffer.size()), nullptr, &_overlapped)) 78 | { 79 | // Interpret the results. 80 | return endWrite(); 81 | } else if (GetLastError() == ERROR_IO_PENDING) { 82 | log::trace("Write in progress."); 83 | return EventStatus::Ok; 84 | } else { 85 | log::error("WriteFile failed: {}", lastErrorString()); 86 | _ioState = IOState::Failed; 87 | return EventStatus::Failed; 88 | } 89 | } 90 | 91 | EventStatus EventOverlappedIO::endWrite() { 92 | DWORD bytesTransferred; 93 | if (GetOverlappedResult(fileHandle(), &_overlapped, &bytesTransferred, false)) 94 | { 95 | _offset += bytesTransferred; 96 | if (_offset == _buffer.size()) { 97 | log::debug("Write finished: {} bytes.", _offset); 98 | _ioState = IOState::Inactive; 99 | return EventStatus::Finished; 100 | } else if (_offset > _buffer.size()) { 101 | log::warn("More data written ({} B) than expected ({} B).", 102 | _offset, _buffer.size()); 103 | _ioState = IOState::Inactive; 104 | return EventStatus::Finished; 105 | } else { 106 | log::debug("Write in progress: {}%.", _offset / _buffer.size()); 107 | return beginWrite(); 108 | } 109 | } 110 | auto error = GetLastError(); 111 | if (error == ERROR_IO_PENDING) { 112 | return EventStatus::Ok; 113 | } else if (error == ERROR_BROKEN_PIPE) { 114 | log::info("Connection ended by client."); 115 | _ioState = IOState::Failed; 116 | return EventStatus::Failed; 117 | } 118 | log::error("Write failed: {}", lastErrorString(error)); 119 | _ioState = IOState::Failed; 120 | return EventStatus::Failed; 121 | } 122 | 123 | bool EventOverlappedIO::reset() { 124 | _ioState = IOState::Inactive; 125 | _offset = 0; 126 | return false; 127 | } 128 | 129 | EventStatus EventOverlappedIO::operator()(EventListener &listener) { 130 | switch (_ioState) { 131 | case IOState::Inactive: 132 | return EventStatus::Finished; 133 | case IOState::Reading: 134 | return endRead(); 135 | case IOState::Writing: 136 | return endWrite(); 137 | case IOState::Failed: 138 | return EventStatus::Failed; 139 | } 140 | 141 | WSUDO_UNREACHABLE("Invalid IO State"); 142 | } 143 | 144 | -------------------------------------------------------------------------------- /include/wsudo/winsupport.h: -------------------------------------------------------------------------------- 1 | #if defined(WSUDO_WINSUPPORT_H) || !defined(WSUDO_WSUDO_H) 2 | #error "Do not include this file directly; use wsudo.h." 3 | #else 4 | #define WSUDO_WINSUPPORT_H 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | namespace wsudo { 12 | 13 | std::string to_utf8(std::wstring_view utf16str); 14 | std::wstring to_utf16(std::string_view utf8str); 15 | 16 | // Set thread name via new Win10 API, if it exists. 17 | // Returns false if the API was not found or failed. 18 | bool setThreadName(const wchar_t *name); 19 | 20 | // Convert a "GetLastError" code to string. 21 | std::string lastErrorString(DWORD status); 22 | 23 | // Convenience GetLastError->string. 24 | inline std::string lastErrorString() { 25 | return lastErrorString(::GetLastError()); 26 | } 27 | 28 | // Dynamic module (DLL) load error. 29 | class module_load_error : public std::exception { 30 | DWORD _error; 31 | std::string _message; 32 | public: 33 | explicit module_load_error(const char *module) 34 | : _error{GetLastError()}, 35 | _message{ 36 | std::string("Module '") + module + "' load failed: " + 37 | lastErrorString(_error) 38 | } 39 | {} 40 | 41 | explicit module_load_error(const char *module, const char *function) 42 | : _error{GetLastError()}, 43 | _message{ 44 | std::string("Function '") + module + "!" + function + "' not found: " + 45 | lastErrorString(_error) 46 | } 47 | {} 48 | 49 | DWORD syscode() const { 50 | return _error; 51 | } 52 | 53 | const char *what() const override { 54 | return _message.c_str(); 55 | } 56 | }; 57 | 58 | // Wrapper for calling dynamically into modules already loaded in this process. 59 | // Used for ntdll which must be called dynamically. 60 | class LinkedModule { 61 | const wchar_t *_name; 62 | HMODULE _module; 63 | 64 | public: 65 | // Throws a module_load_error on failure. 66 | LinkedModule(const wchar_t *dllName) 67 | : _name{dllName}, 68 | _module{GetModuleHandleW(dllName)} 69 | { 70 | if (!_module) { 71 | throw module_load_error{to_utf8(_name).c_str()}; 72 | } 73 | } 74 | 75 | template class Function; 76 | // Note: F may have a calling convention; R(Args...) does not. 77 | template 78 | class Function { 79 | public: 80 | // Throws a module_load_error on failure. 81 | Function(const LinkedModule &module, const char *name) 82 | : _function(reinterpret_cast(GetProcAddress(module._module, name))) 83 | { 84 | if (!_function) { 85 | throw module_load_error{to_utf8(module._name).c_str(), name}; 86 | } 87 | } 88 | 89 | R operator()(Args ...args) const { 90 | return _function(std::forward(args)...); 91 | } 92 | 93 | private: 94 | F _function; 95 | }; 96 | 97 | // Get a pointer to the function `name` with type F from this module. 98 | // Throws a module_load_error on failure. 99 | template 100 | Function get(const char *name) const { 101 | return Function{*this, name}; 102 | } 103 | }; 104 | 105 | template 106 | class Handle; 107 | 108 | namespace detail { 109 | template 110 | class pointer_operators {}; 111 | 112 | template 113 | class pointer_operators {}; 114 | 115 | template 116 | class pointer_operators {}; 117 | 118 | template 119 | class pointer_operators { 120 | using Self = Handle; 121 | 122 | public: 123 | T *operator->() { 124 | return static_cast(this)->operator T *(); 125 | } 126 | 127 | const T *operator->() const { 128 | return static_cast(this)->operator const T *(); 129 | } 130 | 131 | T &operator*() { 132 | return *operator->(); 133 | } 134 | 135 | const T &operator*() const { 136 | return *operator->(); 137 | } 138 | }; 139 | } // namespace detail 140 | 141 | // RAII wrapper around Windows HANDLE values. Free should be the function that 142 | // closes this type of handle (e.g. CloseHandle). 143 | // This class is basically a reimplementation of unique_ptr, except that it has 144 | // some conveniences to make it easier to use in Windows API calls. 145 | template 146 | class Handle : public detail::pointer_operators { 147 | H _handle; 148 | 149 | void free() { 150 | if (_handle) { 151 | Free(_handle); 152 | } 153 | } 154 | 155 | public: 156 | Handle() noexcept : _handle() {} 157 | explicit Handle(H handle) noexcept : _handle(handle) {} 158 | Handle(Handle &&other) noexcept : _handle(other.take()) {} 159 | 160 | ~Handle() { 161 | free(); 162 | } 163 | 164 | // Frees the old handle if any before assignment. 165 | Handle &operator=(Handle &&other) { 166 | free(); 167 | _handle = other.take(); 168 | return *this; 169 | } 170 | 171 | // Frees the old handle if any before assignment. 172 | Handle &operator=(H newHandle) { 173 | free(); 174 | _handle = newHandle; 175 | return *this; 176 | } 177 | 178 | // Gets a pointer to the inner handle. Be careful not to leak memory when 179 | // overwriting the handle value. 180 | H *operator&() { 181 | return &_handle; 182 | } 183 | 184 | // Gets a const pointer to the inner handle. 185 | const H *operator&() const { 186 | return &_handle; 187 | } 188 | 189 | // Release the handle without freeing it. 190 | H take() { 191 | auto handle = _handle; 192 | _handle = nullptr; 193 | return handle; 194 | } 195 | 196 | // Implicit conversion to a Windows handle - makes it easier to pass to 197 | // Win API functions. 198 | operator H() { 199 | return _handle; 200 | } 201 | 202 | operator const H() const { 203 | return _handle; 204 | } 205 | 206 | // Returns true if the handle is not null - does not test the actual validity 207 | // of the handle. 208 | bool good() const { 209 | return !!_handle; 210 | } 211 | 212 | // Null test. 213 | explicit operator bool() const { 214 | return !!_handle; 215 | } 216 | }; 217 | 218 | // Standard HANDLE with CloseHandle destructor. 219 | using HObject = Handle; 220 | 221 | // Pointer returned from Windows that needs to be freed with LocalFree. 222 | template 223 | using HLocalPtr = Handle; 224 | 225 | } // namespace wsudo 226 | 227 | #endif // WSUDO_WINSUPPORT_H 228 | -------------------------------------------------------------------------------- /include/wsudo/events.h: -------------------------------------------------------------------------------- 1 | #ifndef WSUDO_EVENTS_H 2 | #define WSUDO_EVENTS_H 3 | 4 | #include 5 | #include 6 | 7 | #include "wsudo.h" 8 | 9 | /** 10 | * Windows Event Server/Client 11 | * Uses WaitForMultipleObjects to execute callbacks on event completion. 12 | */ 13 | 14 | namespace wsudo::events { 15 | 16 | // Status codes for the listener to manage individual handlers. 17 | enum class EventStatus { 18 | // The event completed its work for this step. 19 | Ok, 20 | // The event has nothing more to do and should be removed from the list. 21 | Finished, 22 | // The event's state is invalid and it should be removed from the list. 23 | Failed, 24 | }; 25 | 26 | class EventListener; 27 | 28 | // A waitable event based on Windows timers. 29 | // The callback in operator() is triggered when the event is signaled. 30 | class EventHandler { 31 | public: 32 | EventHandler() = default; 33 | EventHandler(const EventHandler &) = default; 34 | EventHandler &operator=(const EventHandler &) = default; 35 | 36 | EventHandler(EventHandler &&) = default; 37 | EventHandler &operator=(EventHandler &&) = default; 38 | 39 | virtual ~EventHandler() = 0; 40 | 41 | // The Windows event that should trigger this event. 42 | virtual HANDLE event() const = 0; 43 | 44 | // Optional - return true if the state was reset. The default implementation 45 | // does nothing and returns false. 46 | virtual bool reset(); 47 | 48 | // Event handler implementation. 49 | virtual EventStatus operator()(EventListener &) = 0; 50 | }; 51 | 52 | // Lambda wrapper event handler. 53 | template< 54 | typename F, 55 | bool AllowReset = false, 56 | typename = std::enable_if_t< 57 | std::is_invocable_r_v 58 | > 59 | > 60 | class EventCallback final : public EventHandler { 61 | public: 62 | EventCallback(HANDLE event, F callback) noexcept 63 | : _callback(std::move(callback)), 64 | _event(event) 65 | {} 66 | 67 | HANDLE event() const override { return _event; } 68 | 69 | bool reset() override { 70 | if constexpr (AllowReset) { 71 | ResetEvent(_event); 72 | return true; 73 | } else { 74 | return false; 75 | } 76 | } 77 | 78 | EventStatus operator()(EventListener &listener) override { 79 | return _callback(listener); 80 | } 81 | 82 | private: 83 | F _callback; 84 | HObject _event; 85 | }; 86 | 87 | // Handles overlapped IO operations when the event is triggered. Inheriting from 88 | // this class enables subclasses to easily use overlapped IO to incrementally 89 | // read from a file handle and be notified when the entire message is received, 90 | // or to write a large message all at once but send it in smaller chunks. 91 | class EventOverlappedIO : public EventHandler { 92 | public: 93 | EventOverlappedIO() = delete; 94 | /// @param isEventSet Should action be taken immediately (true), or should we 95 | /// wait until the event is triggered another way (false)? 96 | explicit EventOverlappedIO(bool isEventSet) noexcept; 97 | ~EventOverlappedIO(); 98 | 99 | // This class is not copyable or movable because the embedded 100 | // OVERLAPPED must remain at the same memory address. 101 | 102 | EventOverlappedIO(const EventOverlappedIO &) = delete; 103 | EventOverlappedIO &operator=(const EventOverlappedIO &) = delete; 104 | 105 | EventOverlappedIO(EventOverlappedIO &&) = delete; 106 | EventOverlappedIO &operator=(EventOverlappedIO &&) = delete; 107 | 108 | // Returns false, but succeeds. Subclasses can override this to reset their 109 | // own state and return true. If this is overridden, a subclass must call 110 | // EventOverlappedIO::reset(). 111 | bool reset() override; 112 | 113 | // Returns the overlapped trigger event. 114 | HANDLE event() const override { return _overlapped.hEvent; } 115 | 116 | // Subclasses should call this first to handle chunked reading/writing. 117 | // Returns EventStatus::Finished when reading/writing is done. 118 | EventStatus operator()(EventListener &) override; 119 | 120 | protected: 121 | OVERLAPPED _overlapped{}; 122 | std::vector _buffer{}; 123 | 124 | // Subclasses should return an overlapped readable/writable handle here. 125 | virtual HANDLE fileHandle() const = 0; 126 | 127 | // Begin reading from the file handle. Subclasses must call operator() for 128 | // this to work. 129 | EventStatus readToBuffer() { _offset = 0; return beginRead(); } 130 | 131 | // Begin writing to the file handle. Subclasses must call operator() for 132 | // this to work. 133 | EventStatus writeFromBuffer() { _offset = 0; return beginWrite(); } 134 | 135 | private: 136 | // Position in buffer to begin reading or writing, depending on IO state. 137 | size_t _offset = 0; 138 | 139 | // Determines if any IO action needs to take place. 140 | enum class IOState { 141 | // No IO is queued. 142 | Inactive, 143 | // We are waiting to read from the file. 144 | Reading, 145 | // We are waiting to write to the file. 146 | Writing, 147 | // Reading or writing failed. 148 | Failed, 149 | } _ioState{IOState::Inactive}; 150 | 151 | const size_t BufferDoublingLimit = 4; 152 | 153 | // Max amount to read/write at once. 154 | const DWORD ChunkSize = static_cast(PipeBufferSize); 155 | 156 | // Begins an overlapped read operation. 157 | EventStatus beginRead(); 158 | // Finishes an overlapped read operation. Not all the data may be read at 159 | // this point. See EventOverlappedIO::operator(). 160 | EventStatus endRead(); 161 | // Begins an overlapped write operation. 162 | EventStatus beginWrite(); 163 | // Finishes an overlapped write operation. Not all the data may be written at 164 | // this point. See EventOverlappedIO::operator(). 165 | EventStatus endWrite(); 166 | }; 167 | 168 | // Manages a set of event handlers. 169 | class EventListener final { 170 | public: 171 | explicit EventListener() = default; 172 | 173 | EventListener(const EventListener &) = delete; 174 | EventListener &operator=(const EventListener &) = delete; 175 | 176 | EventListener(EventListener &&) = default; 177 | EventListener &operator=(EventListener &&) = default; 178 | 179 | // Construct a handler in place. 180 | template 181 | std::enable_if_t< 182 | std::conjunction_v< 183 | std::is_convertible, 184 | std::is_constructible 185 | >, 186 | H & 187 | > 188 | emplace(Args &&...args) { 189 | auto &handler = static_cast( 190 | *_handlers.emplace_back(std::make_unique(std::forward(args)...)) 191 | ); 192 | _events.emplace_back(handler.event()); 193 | return handler; 194 | } 195 | 196 | // Add a function object or lambda event handler with a custom event object. 197 | // If AllowReset is true, the event will be reset and the handler reused 198 | // after it finishes. 199 | template 200 | EventCallback & 201 | emplace(HANDLE event, F callback) { 202 | return emplace>(event, std::move(callback)); 203 | } 204 | 205 | // Run one iteration of the event loop. 206 | EventStatus next(DWORD timeout = INFINITE); 207 | 208 | // Run the event loop until a quit is triggered. Returns Finished or Failed. 209 | EventStatus run(DWORD timeout = INFINITE); 210 | 211 | // Return the number of events in the queue. 212 | size_t count() const { 213 | assert(_events.size() == _handlers.size()); 214 | return _events.size(); 215 | } 216 | 217 | bool isRunning() const { return _running; } 218 | void stop() { _running = false; } 219 | 220 | private: 221 | // List of events to pass to WaitForMultipleObjects. 222 | std::vector _events; 223 | // List of handlers, must be kept in sync with the event list. 224 | std::vector> _handlers; 225 | // Active flag. 226 | bool _running; 227 | 228 | // Remove an event handler from the list. 229 | void remove(size_t index); 230 | }; 231 | 232 | } // namespace wsudo::events 233 | 234 | #endif // WSUDO_EVENTS_H 235 | -------------------------------------------------------------------------------- /lib/client/main.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/client.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define SECURITY_WIN32 11 | #include 12 | #pragma comment(lib, "Secur32.lib") 13 | 14 | using namespace wsudo; 15 | 16 | void ClientConnection::connect( 17 | LPSECURITY_ATTRIBUTES secAttr, 18 | const wchar_t *pipeName, 19 | int attempts 20 | ) 21 | { 22 | if (attempts >= MaxConnectAttempts) { 23 | return; 24 | } 25 | HANDLE pipe = CreateFileW(pipeName, GENERIC_READ | GENERIC_WRITE, 26 | FILE_SHARE_READ | FILE_SHARE_WRITE, 27 | secAttr, OPEN_EXISTING, 0, nullptr); 28 | if (pipe == INVALID_HANDLE_VALUE) { 29 | WaitNamedPipeW(pipeName, NMPWAIT_USE_DEFAULT_WAIT); 30 | connect(secAttr, pipeName, ++attempts); 31 | return; 32 | } 33 | 34 | _pipe = pipe; 35 | } 36 | 37 | ClientConnection::ClientConnection(const wchar_t *pipeName) { 38 | SECURITY_ATTRIBUTES secAttr; 39 | secAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 40 | secAttr.bInheritHandle = false; 41 | secAttr.lpSecurityDescriptor = nullptr; 42 | connect(&secAttr, pipeName, 0); 43 | if (good()) { 44 | _buffer.reserve(PipeBufferSize); 45 | } 46 | } 47 | 48 | bool ClientConnection::negotiate(const char *credentials, size_t length) { 49 | DWORD bytes; 50 | size_t messageLength = length + 4; 51 | _buffer.resize(messageLength); 52 | assert(strlen(msg::client::Credential) == 4); 53 | std::memcpy(_buffer.data(), msg::client::Credential, 4); 54 | std::memcpy(_buffer.data() + 4, credentials, length); 55 | log::trace("Writing credential message, size {}", messageLength); 56 | if ( 57 | !WriteFile(_pipe, _buffer.data(), (DWORD)messageLength, &bytes, nullptr) || 58 | bytes != messageLength 59 | ) 60 | { 61 | log::error("Couldn't write negotiate message."); 62 | return false; 63 | } 64 | 65 | _buffer.resize(PipeBufferSize); 66 | if (!ReadFile(_pipe, _buffer.data(), PipeBufferSize, &bytes, nullptr)) { 67 | log::error("Couldn't read server response."); 68 | return false; 69 | } 70 | _buffer.resize(bytes); 71 | return readServerMessage(); 72 | } 73 | 74 | bool ClientConnection::bless(HANDLE process) { 75 | DWORD bytes; 76 | size_t messageLength = 4 + sizeof(HANDLE); 77 | _buffer.resize(messageLength); 78 | assert(strlen(msg::client::Bless) == 4); 79 | std::memcpy(_buffer.data(), msg::client::Bless, 4); 80 | std::memcpy(_buffer.data() + 4, &process, sizeof(HANDLE)); 81 | log::trace("Writing bless message, size {}", messageLength); 82 | if ( 83 | !WriteFile(_pipe, _buffer.data(), (DWORD)messageLength, &bytes, nullptr) || 84 | bytes != messageLength 85 | ) 86 | { 87 | log::error("Couldn't write bless message."); 88 | return false; 89 | } 90 | 91 | _buffer.resize(PipeBufferSize); 92 | if (!ReadFile(_pipe, _buffer.data(), PipeBufferSize, &bytes, nullptr)) { 93 | log::error("Couldn't read server response."); 94 | return false; 95 | } 96 | _buffer.resize(bytes); 97 | return readServerMessage(); 98 | } 99 | 100 | bool ClientConnection::readServerMessage() { 101 | if (_buffer.size() < 4) { 102 | log::error("Unknown server response.\n"); 103 | return false; 104 | } 105 | char header[5]; 106 | std::memcpy(header, _buffer.data(), 4); 107 | header[4] = 0; 108 | log::trace("Reading response with code {}.", header); 109 | if (!std::memcmp(header, msg::server::Success, 4)) { 110 | // Don't print a success message - just start the process. 111 | return true; 112 | } 113 | if (!std::memcmp(header, msg::server::InvalidMessage, 4)) { 114 | log::eprint("Invalid message"); 115 | } else if (!std::memcmp(header, msg::server::InternalError, 4)) { 116 | log::eprint("Internal server error"); 117 | } else if (!std::memcmp(header, msg::server::AccessDenied, 4)) { 118 | log::eprint("Access denied; this incident will be reported"); 119 | // TODO: Send email to police. 120 | } 121 | if (_buffer.size() > 4) { 122 | _buffer.push_back(0); 123 | log::eprint(": {}\n", (_buffer.data() + 4)); 124 | } else { 125 | log::eprint("\n"); 126 | } 127 | return false; 128 | } 129 | 130 | // FIXME: This is a hack and doesn't actually handle certain cases. 131 | std::wstring fullCommandLine(int argc, wchar_t *argv[]) { 132 | std::wstring cl; 133 | for (int i = 0; i < argc; ++i) { 134 | if (wcschr(argv[i], L' ')) { 135 | cl.push_back(L'"'); 136 | cl.append(argv[i]); 137 | cl.push_back(L'"'); 138 | } else { 139 | cl.append(argv[i]); 140 | } 141 | cl.push_back(L' '); 142 | } 143 | 144 | return cl; 145 | } 146 | 147 | // Returns {process, thread} 148 | std::pair createProcess(int argc, wchar_t *argv[]) { 149 | STARTUPINFOW si{}; 150 | si.cb = sizeof(STARTUPINFOW); 151 | si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); 152 | si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); 153 | si.hStdError = GetStdHandle(STD_ERROR_HANDLE); 154 | si.dwFlags = STARTF_USESTDHANDLES; 155 | PROCESS_INFORMATION pi; 156 | std::wstring commandLine{fullCommandLine(argc, argv)}; 157 | *(commandLine.end() - 1) = 0; 158 | if (!CreateProcessW(argv[0], commandLine.data(), nullptr, nullptr, true, 159 | CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED, 160 | nullptr, nullptr, &si, &pi)) 161 | { 162 | return {nullptr, nullptr}; 163 | } 164 | return {pi.hProcess, pi.hThread}; 165 | } 166 | 167 | int wmain(int argc, wchar_t *argv[]) { 168 | log::g_outLogger = spdlog::stdout_color_mt("wsudo.out"); 169 | log::g_outLogger->set_level(spdlog::level::trace); 170 | log::g_errLogger = spdlog::stderr_color_mt("wsudo.err"); 171 | log::g_errLogger->set_level(spdlog::level::warn); 172 | spdlog::set_pattern("%^[%l]%$ %v"); 173 | WSUDO_SCOPEEXIT { spdlog::drop_all(); }; 174 | 175 | if (argc < 2) { 176 | log::eprint("Usage: wsudo \n"); 177 | return ClientExitInvalidUsage; 178 | } 179 | 180 | ClientConnection conn{PipeFullPath}; 181 | if (!conn) { 182 | log::critical("Connection to server failed.\n"); 183 | return ClientExitServerNotFound; 184 | } 185 | 186 | HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 187 | DWORD stdinMode; 188 | GetConsoleMode(hStdin, &stdinMode); 189 | DWORD newStdinMode = ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | 190 | ENABLE_ECHO_INPUT | ENABLE_EXTENDED_FLAGS | 191 | ENABLE_QUICK_EDIT_MODE; 192 | SetConsoleMode(hStdin, newStdinMode); 193 | WSUDO_SCOPEEXIT { SetConsoleMode(hStdin, stdinMode); }; 194 | 195 | std::wstring username{}; 196 | ULONG usernameLength = 0; 197 | GetUserNameExW(NameSamCompatible, nullptr, &usernameLength); 198 | if (GetLastError() == ERROR_MORE_DATA) { 199 | username.resize(usernameLength); 200 | if (!GetUserNameExW(NameSamCompatible, username.data(), &usernameLength)) { 201 | log::critical("Can't get username.\n"); 202 | return ClientExitSystemError; 203 | } 204 | // It ends in a null that we don't want printed. 205 | username.erase(username.cend() - 1); 206 | } else { 207 | log::critical("Can't get username.\n"); 208 | return ClientExitSystemError; 209 | } 210 | 211 | if (auto slash = username.find(L'\\'); slash != std::wstring::npos) { 212 | username = username.substr(slash + 1); 213 | } 214 | 215 | std::wstring password{}; 216 | log::print(L"[wsudo] password for {}: ", username); 217 | fflush(stdout); 218 | { 219 | SetConsoleMode(hStdin, ENABLE_EXTENDED_FLAGS | ENABLE_QUICK_EDIT_MODE); 220 | while (true) { 221 | wchar_t ch; 222 | DWORD chRead; 223 | if (!ReadConsoleW(hStdin, &ch, 1, &chRead, nullptr)) { 224 | return ClientExitSystemError; 225 | } 226 | if (ch == 13 || ch == 10) { 227 | // Enter 228 | log::print("\n"); 229 | break; 230 | } else if (ch == 8 || ch == 0x7F) { 231 | // Backspace 232 | if (password.length() > 0) { 233 | password.erase(password.cend() - 1); 234 | } 235 | } else if (ch == 3) { 236 | // Ctrl-C 237 | log::print("\nCanceled.\n"); 238 | return ClientExitUserCanceled; 239 | } else { 240 | password.push_back((wchar_t)ch); 241 | } 242 | } 243 | SetConsoleMode(hStdin, newStdinMode); 244 | } 245 | 246 | auto u8creds = to_utf8(username); 247 | u8creds.push_back(0); 248 | u8creds.append(to_utf8(password)); 249 | if (!conn.negotiate(u8creds.data(), u8creds.length())) { 250 | return ClientExitAccessDenied; 251 | } 252 | 253 | auto [process, thread] = createProcess(argc - 1, argv + 1); 254 | if (!process) { 255 | log::critical("Error creating process: {}.\n", lastErrorString()); 256 | return ClientExitCreateProcessError; 257 | } 258 | 259 | if (!conn.bless(process)) { 260 | log::critical("Server failed to adjust privileges\n"); 261 | TerminateProcess(process, 1); 262 | CloseHandle(thread); 263 | CloseHandle(process); 264 | return ClientExitSystemError; 265 | } 266 | 267 | ResumeThread(thread); 268 | CloseHandle(thread); 269 | WaitForSingleObject(process, INFINITE); 270 | DWORD exitCode; 271 | GetExitCodeProcess(process, &exitCode); 272 | CloseHandle(process); 273 | 274 | return (int)exitCode; 275 | } 276 | 277 | -------------------------------------------------------------------------------- /include/wsudo/wsudo.h: -------------------------------------------------------------------------------- 1 | #ifndef WSUDO_WSUDO_H 2 | #define WSUDO_WSUDO_H 3 | 4 | #define WINVER _WIN32_WINNT_WIN7 5 | #define _WIN32_WINNT _WIN32_WINNT_WIN7 6 | #define NTDDI_VERSION NTDDI_WIN7 7 | #include 8 | #undef min 9 | #undef max 10 | #include "winsupport.h" 11 | 12 | // Winternl.h and NTSecAPI.h both define some of the same types so 13 | // we can't include both in the same file. Thanks Microsoft. 14 | #ifndef WSUDO_NO_NT_API 15 | # include 16 | # include "ntapi.h" 17 | #endif 18 | 19 | #define SPDLOG_WCHAR_TO_UTF8_SUPPORT 20 | #include 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | namespace wsudo { 28 | 29 | /// File path to the client-server communication pipe. 30 | extern const wchar_t *const PipeFullPath; 31 | 32 | /// Pipe's buffer size in bytes. 33 | constexpr size_t PipeBufferSize = 1024; 34 | 35 | // Maximum concurrent server connections. Being sudo, it's unlikely to have to 36 | // process many things concurrently, but we have to give Windows a number. 37 | constexpr int MaxPipeConnections = 3; 38 | 39 | // Pipe timeout, again for Windows. 40 | constexpr int PipeDefaultTimeout = 0; 41 | 42 | 43 | /// Message headers 44 | namespace msg { 45 | /// Client->Server message headers 46 | namespace client { 47 | /// Query session - server should tell how, if possible, to create the 48 | /// session. 49 | extern const char *const QuerySession; 50 | /// User credentials message 51 | extern const char *const Credential; 52 | /// Bless (elevate process) request message 53 | extern const char *const Bless; 54 | } 55 | 56 | /// Server->Client message headers 57 | namespace server { 58 | /// Success 59 | extern const char *const Success; 60 | /// Invalid message 61 | extern const char *const InvalidMessage; 62 | /// Internal error (server bug) 63 | extern const char *const InternalError; 64 | /// Access denied 65 | extern const char *const AccessDenied; 66 | } 67 | } // namespace msg 68 | 69 | namespace log { 70 | 71 | // Logger that prints to stdout. 72 | extern std::shared_ptr g_outLogger; 73 | 74 | // Logger that prints to stderr. 75 | extern std::shared_ptr g_errLogger; 76 | 77 | /// Print to stdout with no prefix. 78 | template 79 | static inline void print(const char *fmt, Args &&...args) 80 | { fmt::print(stdout, fmt, std::forward(args)...); } 81 | 82 | /// Print to stderr with no prefix. 83 | template 84 | static inline void eprint(const char *fmt, Args &&...args) 85 | { fmt::print(stderr, fmt, std::forward(args)...); } 86 | 87 | /// Trace logger. 88 | template 89 | static inline void trace(const char *fmt, Args &&...args) 90 | { g_outLogger->trace(fmt, std::forward(args)...); } 91 | 92 | /// Debug logger. 93 | template 94 | static inline void debug(const char *fmt, Args &&...args) 95 | { g_outLogger->debug(fmt, std::forward(args)...); } 96 | 97 | /// Info logger. 98 | template 99 | static inline void info(const char *fmt, Args &&...args) 100 | { g_outLogger->info(fmt, std::forward(args)...); } 101 | 102 | /// Warning logger. 103 | template 104 | static inline void warn(const char *fmt, Args &&...args) 105 | { g_errLogger->warn(fmt, std::forward(args)...); } 106 | 107 | /// Error logger. 108 | template 109 | static inline void error(const char *fmt, Args &&...args) 110 | { g_errLogger->error(fmt, std::forward(args)...); } 111 | 112 | /// Critical logger. 113 | template 114 | static inline void critical(const char *fmt, Args &&...args) 115 | { g_errLogger->critical(fmt, std::forward(args)...); } 116 | 117 | // wchar_t loggers (not currently working). 118 | #ifndef WSUDO_WCHAR_T_LOGGING 119 | 120 | /// Print to stdout with no prefix (wchar_t version). 121 | template 122 | static inline void print(const wchar_t *fmt, Args &&...args) 123 | { fmt::print(stdout, fmt, std::forward(args)...); } 124 | 125 | /// Print to stderr with no prefix (wchar_t version). 126 | template 127 | static inline void eprint(const wchar_t *fmt, Args &&...args) 128 | { fmt::print(stderr, fmt, std::forward(args)...); } 129 | 130 | /// Trace logger (wchar_t version). 131 | template 132 | static inline void trace(const wchar_t *fmt, Args &&...args) 133 | { g_outLogger->trace(fmt, std::forward(args)...); } 134 | 135 | /// Debug logger (wchar_t version). 136 | template 137 | static inline void debug(const wchar_t *fmt, Args &&...args) 138 | { g_outLogger->debug(fmt, std::forward(args)...); } 139 | 140 | /// Info logger (wchar_t version). 141 | template 142 | static inline void info(const wchar_t *fmt, Args &&...args) 143 | { g_outLogger->info(fmt, std::forward(args)...); } 144 | 145 | /// Warning logger (wchar_t version). 146 | template 147 | static inline void warn(const wchar_t *fmt, Args &&...args) 148 | { g_errLogger->warn(fmt, std::forward(args)...); } 149 | 150 | /// Error logger (wchar_t version). 151 | template 152 | static inline void error(const wchar_t *fmt, Args &&...args) 153 | { g_errLogger->error(fmt, std::forward(args)...); } 154 | 155 | /// Critical logger (wchar_t version). 156 | template 157 | static inline void critical(const wchar_t *fmt, Args &&...args) 158 | { g_errLogger->critical(fmt, std::forward(args)...); } 159 | 160 | #endif 161 | 162 | } // namespace log 163 | 164 | // Wrapper for a function that returns a pointer of its own type, enabling 165 | // endless recursive callbacks. 166 | template 167 | struct recursive_callback { 168 | using pointer = recursive_callback (*)(Args...); 169 | 170 | // Default (null pointer) constructor. 171 | constexpr recursive_callback() noexcept 172 | : function{nullptr} 173 | {} 174 | 175 | // Implicit conversion from pointer type. 176 | constexpr recursive_callback(pointer function) noexcept 177 | : function{function} 178 | {} 179 | 180 | // Copy 181 | recursive_callback(const recursive_callback &) = default; 182 | 183 | // Copy assign 184 | recursive_callback & operator=(const recursive_callback &) = default; 185 | 186 | // Call the function, returning the next callback. 187 | constexpr inline recursive_callback operator()(Args &&...args) const { 188 | return function(std::forward(args)...); 189 | } 190 | 191 | // Call the function, replacing it with the returned callback. 192 | constexpr inline bool call_and_swap(Args &&...args) { 193 | function = function(std::forward(args)...); 194 | return !!function; 195 | } 196 | 197 | // Null check. 198 | constexpr explicit operator bool() const { return !!function; } 199 | 200 | private: 201 | pointer function; 202 | }; 203 | 204 | // Wrapper for recursive member function callbacks. 205 | template 206 | struct recursive_mem_callback { 207 | using pointer = recursive_mem_callback (T::*)(Args...); 208 | 209 | // Default (null pointer) constructor. 210 | constexpr recursive_mem_callback() noexcept 211 | : function{nullptr} 212 | {} 213 | 214 | // Implicit conversion from member pointer type. 215 | constexpr recursive_mem_callback(pointer function) noexcept 216 | : function{function} 217 | {} 218 | 219 | // Copy. 220 | recursive_mem_callback(const recursive_mem_callback &) = default; 221 | 222 | // Copy assign. 223 | recursive_mem_callback & operator=(const recursive_mem_callback &) = default; 224 | 225 | // Call the function, returning the next callback. 226 | constexpr inline recursive_mem_callback operator()(T &self, Args &&...args) { 227 | return (self.*function)(std::forward(args)...); 228 | } 229 | 230 | // Call the function, replacing it with the returned callback. 231 | constexpr inline bool call_and_swap(T &self, Args &&...args) { 232 | function = (self.*function)(std::forward(args)...).function; 233 | return !!function; 234 | } 235 | 236 | // Null check. 237 | constexpr explicit operator bool() const { return !!function; } 238 | 239 | private: 240 | pointer function; 241 | }; 242 | 243 | namespace detail { 244 | /// RAII wrapper to run a function when the scope exits. 245 | template>> 247 | class ScopeExit { 248 | OnExit _onExit; 249 | public: 250 | explicit ScopeExit(OnExit onExit) : _onExit(std::move(onExit)) {} 251 | ScopeExit &operator=(const ScopeExit &) = delete; 252 | ~ScopeExit() { 253 | _onExit(); 254 | } 255 | }; 256 | 257 | struct ScopeExitHelper{}; 258 | 259 | // Use an arbitrary high precedence operator, even though there shouldn't 260 | // be anything else in these statements anyways. 261 | template 262 | ScopeExit operator%(const detail::ScopeExitHelper &, OnExit onExit) { 263 | return ScopeExit{std::move(onExit)}; 264 | } 265 | } 266 | 267 | } // namespace wsudo 268 | 269 | #define WSUDO_CONCAT_IMPL(a,b) a##b 270 | #define WSUDO_CONCAT2(a,b) WSUDO_CONCAT_IMPL(a,b) 271 | 272 | // Scope destructor. 273 | // Usage: WSUDO_SCOPEEXIT { capture-by-ref lambda body }; 274 | #define WSUDO_SCOPEEXIT \ 275 | [[maybe_unused]] auto const &WSUDO_CONCAT2(_scopeExit_, __LINE__) = \ 276 | ::wsudo::detail::ScopeExitHelper{} % [&]() 277 | 278 | // Scope destructor that captures the this pointer by value. 279 | #define WSUDO_SCOPEEXIT_THIS \ 280 | [[maybe_unused]] auto const &WSUDO_CONCAT2(_scopeExit_, __LINE__) = \ 281 | ::wsudo::detail::ScopeExitHelper{} % [&, this]() 282 | 283 | #ifndef NDEBUG 284 | # define WSUDO_UNREACHABLE(why) do { assert(0 && (why)); __assume(0); } while(0) 285 | #else 286 | # define WSUDO_UNREACHABLE(why) __assume(0) 287 | #endif 288 | 289 | #endif // WSUDO_WSUDO_H 290 | -------------------------------------------------------------------------------- /lib/server/clientconnection.cpp: -------------------------------------------------------------------------------- 1 | #include "wsudo/server.h" 2 | 3 | #include 4 | 5 | using namespace wsudo; 6 | using namespace wsudo::server; 7 | using namespace wsudo::events; 8 | 9 | ClientConnectionHandler::ClientConnectionHandler( 10 | HObject pipe, int clientId, session::SessionManager &sessionManager 11 | ) noexcept 12 | : EventOverlappedIO{true}, 13 | _pipe{std::move(pipe)}, 14 | _clientId{clientId}, 15 | _sessionManager{sessionManager}, 16 | _callback{&Self::beginConnect} 17 | { 18 | } 19 | 20 | bool ClientConnectionHandler::reset() { 21 | EventOverlappedIO::reset(); 22 | 23 | _userToken = nullptr; 24 | if (!DisconnectNamedPipe(_pipe) && 25 | GetLastError() != ERROR_PIPE_NOT_CONNECTED) 26 | { 27 | return false; 28 | } 29 | log::debug("Client {}: Resetting connection.", _clientId); 30 | _callback = &Self::beginConnect; 31 | SetEvent(_overlapped.hEvent); 32 | return true; 33 | } 34 | 35 | EventStatus ClientConnectionHandler::operator()(EventListener &listener) { 36 | // First see if there is any overlapped IO to process. 37 | switch (EventOverlappedIO::operator()(listener)) { 38 | case EventStatus::Finished: 39 | break; 40 | case EventStatus::Failed: 41 | return EventStatus::Failed; 42 | case EventStatus::Ok: 43 | return EventStatus::Ok; 44 | } 45 | 46 | // No IO, so move on to the next step. 47 | if (!_callback || !_callback.call_and_swap(*this)) { 48 | return EventStatus::Failed; 49 | } 50 | return EventStatus::Ok; 51 | } 52 | 53 | void ClientConnectionHandler::createResponse(const char *header, 54 | std::string_view message) 55 | { 56 | assert(strlen(header) == 4); 57 | size_t totalSize = 4 + message.length(); 58 | if (_buffer.size() < totalSize) { 59 | _buffer.resize(totalSize); 60 | } 61 | std::memcpy(_buffer.data(), header, 4); 62 | if (message.length()) { 63 | std::memcpy(_buffer.data() + 4, message.data(), message.length()); 64 | } 65 | } 66 | 67 | ClientConnectionHandler::Callback 68 | ClientConnectionHandler::beginConnect() { 69 | if (ConnectNamedPipe(_pipe, &_overlapped)) { 70 | log::trace("Client {}: connected.", _clientId); 71 | return read(); 72 | } 73 | 74 | switch (GetLastError()) { 75 | case ERROR_IO_PENDING: 76 | log::trace("Client {}: waiting for connection.", _clientId); 77 | return &Self::endConnect; 78 | case ERROR_PIPE_CONNECTED: 79 | log::trace("Client {}: already connected; reading.", _clientId); 80 | return endConnect(); 81 | default: 82 | log::error("Client {}: ConnectNamedPipe failed: {}", _clientId, 83 | lastErrorString()); 84 | return nullptr; 85 | } 86 | } 87 | 88 | ClientConnectionHandler::Callback 89 | ClientConnectionHandler::endConnect() { 90 | DWORD dummyBytesTransferred; 91 | if (!GetOverlappedResult(_pipe, &_overlapped, 92 | &dummyBytesTransferred, false)) 93 | { 94 | if (GetLastError() == ERROR_BROKEN_PIPE) { 95 | log::info("Client {}: connection ended by client.", _clientId); 96 | return nullptr; 97 | } 98 | log::error("Client {}: error finalizing connection: {}", _clientId, 99 | lastErrorString()); 100 | return nullptr; 101 | } 102 | return read(); 103 | } 104 | 105 | ClientConnectionHandler::Callback 106 | ClientConnectionHandler::read() { 107 | switch (readToBuffer()) { 108 | case EventStatus::Failed: 109 | return nullptr; 110 | case EventStatus::Finished: 111 | return respond(); 112 | case EventStatus::Ok: 113 | return &Self::respond; 114 | default: 115 | WSUDO_UNREACHABLE("Invalid EventStatus"); 116 | } 117 | } 118 | 119 | ClientConnectionHandler::Callback 120 | ClientConnectionHandler::respond() { 121 | Callback nextCb = &Self::resetConnection; 122 | if (dispatchMessage()) { 123 | nextCb = &Self::read; 124 | } 125 | 126 | switch (writeFromBuffer()) { 127 | case EventStatus::Ok: 128 | return nextCb; 129 | case EventStatus::Failed: 130 | return nullptr; 131 | case EventStatus::Finished: 132 | return nextCb(*this); 133 | default: 134 | WSUDO_UNREACHABLE("Invalid EventStatus"); 135 | } 136 | 137 | return nextCb; 138 | } 139 | 140 | ClientConnectionHandler::Callback 141 | ClientConnectionHandler::resetConnection() { 142 | if (!reset()) { 143 | log::error("Client {}: Reset failed.", _clientId); 144 | return nullptr; 145 | } 146 | return &Self::beginConnect; 147 | } 148 | 149 | bool ClientConnectionHandler::dispatchMessage() { 150 | if (_buffer.size() < 4) { 151 | log::warn("Client {}: No message header found.", _clientId); 152 | createResponse(msg::server::InvalidMessage, "No message header present"); 153 | return false; 154 | } 155 | 156 | char header[5]; 157 | std::memcpy(header, _buffer.data(), 4); 158 | header[4] = 0; 159 | log::debug("Client {}: Dispatching message '{}'.", _clientId, header); 160 | 161 | // Check if the header is still the same on exit; that means we forgot 162 | // to set it. 163 | WSUDO_SCOPEEXIT_THIS { 164 | if (_buffer.size() < 4 || !std::memcmp(_buffer.data(), header, 4)) { 165 | log::debug("Response was not set!"); 166 | createResponse(msg::server::InternalError); 167 | } 168 | }; 169 | 170 | if (!std::memcmp(header, msg::client::Credential, 4)) { 171 | // Verify the username/password pair. 172 | auto bufferEnd = _buffer.end(); 173 | auto usernameBegin = _buffer.begin() + 4; 174 | auto usernameEnd = usernameBegin; 175 | while (true) { 176 | if (usernameEnd >= bufferEnd - 1) { 177 | log::warn("Client {}: Password not found in message.", _clientId); 178 | createResponse(msg::server::InvalidMessage, 179 | "Password missing."); 180 | return false; 181 | } 182 | if (*usernameEnd == 0) { 183 | break; 184 | } 185 | ++usernameEnd; 186 | } 187 | auto passwordBegin = usernameEnd + 1; 188 | auto passwordEnd = passwordBegin; 189 | // The password shouldn't have any nulls. 190 | while (true) { 191 | if (passwordEnd == bufferEnd) { 192 | break; 193 | } 194 | if (*passwordEnd == 0) { 195 | log::warn("Client {}: Password contains NUL.", _clientId); 196 | createResponse(msg::server::InvalidMessage, 197 | "Incorrect password format."); 198 | return false; 199 | } 200 | ++passwordEnd; 201 | } 202 | _buffer.emplace_back(0); 203 | return tryToLogonUser(reinterpret_cast(&*usernameBegin), 204 | reinterpret_cast(&*passwordBegin)); 205 | } else if (!std::memcmp(header, msg::client::Bless, 4)) { 206 | if (_buffer.size() != 4 + sizeof(HANDLE)) { 207 | log::warn("Client {}: Invalid bless message.", _clientId); 208 | createResponse(msg::server::InvalidMessage); 209 | } else { 210 | HANDLE remoteHandle; 211 | std::memcpy(&remoteHandle, _buffer.data() + 4, sizeof(HANDLE)); 212 | if (bless(remoteHandle)) { 213 | createResponse(msg::server::Success); 214 | } else { 215 | createResponse(msg::server::InternalError, 216 | "Token substitution failed."); 217 | } 218 | } 219 | return false; 220 | } else { 221 | log::warn("Client {}: Unknown message header (0x{:2X}_{:2X}_{:2X}_{:2X}).", 222 | _clientId, header[0], header[1], header[2], header[3]); 223 | createResponse(msg::server::InvalidMessage, "Unknown message header"); 224 | return false; 225 | } 226 | } 227 | 228 | bool ClientConnectionHandler::tryToLogonUser(char *username, char *password) { 229 | auto username_w = to_utf16(username); 230 | auto password_w = to_utf16(password); 231 | // Zero the password from memory. 232 | while (*password) { 233 | *password++ = 0; 234 | } 235 | 236 | auto session = _sessionManager.find(username_w); 237 | if (!session) { 238 | session = _sessionManager.create(username_w, L"", std::move(password_w)); 239 | if (!session) { 240 | log::warn("Client {}: Access denied for user '{}'.", _clientId, username); 241 | createResponse(msg::server::AccessDenied); 242 | return false; 243 | } 244 | } 245 | 246 | // This response will be sent if there are any failures here. 247 | createResponse(msg::server::InternalError); 248 | 249 | HObject clientProcess; 250 | ULONG processId; 251 | if (!GetNamedPipeClientProcessId(_pipe, &processId)) { 252 | log::error("Client {}: Couldn't get client process ID: {}", _clientId, 253 | lastErrorString()); 254 | return false; 255 | } 256 | auto const access = 257 | PROCESS_DUP_HANDLE | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION; 258 | if (!(clientProcess = OpenProcess(access, false, processId))) { 259 | log::error("Client {}: Couldn't open client process: {}", _clientId, 260 | lastErrorString()); 261 | return false; 262 | } 263 | 264 | HObject currentToken; 265 | // if (!OpenProcessToken(clientProcess, TOKEN_DUPLICATE | TOKEN_READ, 266 | if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_READ, 267 | ¤tToken)) 268 | { 269 | log::error("Client {}: Couldn't open client process token: {}", _clientId, 270 | lastErrorString()); 271 | return false; 272 | } 273 | 274 | PSID ownerSid; 275 | PSID groupSid; 276 | PACL dacl; 277 | PACL sacl; 278 | PSECURITY_DESCRIPTOR secDesc; 279 | if (!SUCCEEDED(GetSecurityInfo(currentToken, SE_KERNEL_OBJECT, 280 | DACL_SECURITY_INFORMATION | 281 | SACL_SECURITY_INFORMATION | 282 | GROUP_SECURITY_INFORMATION | 283 | OWNER_SECURITY_INFORMATION, 284 | &ownerSid, &groupSid, &dacl, &sacl, 285 | &secDesc))) 286 | { 287 | log::error("Client {}: Couldn't get security info: {}", _clientId, 288 | lastErrorString()); 289 | return false; 290 | } 291 | WSUDO_SCOPEEXIT { LocalFree(secDesc); }; 292 | 293 | SECURITY_ATTRIBUTES secAttr; 294 | secAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 295 | secAttr.bInheritHandle = true; 296 | secAttr.lpSecurityDescriptor = secDesc; 297 | 298 | // 299 | 300 | HObject newToken; 301 | if (!DuplicateTokenEx(currentToken, MAXIMUM_ALLOWED, &secAttr, 302 | SecurityImpersonation, TokenPrimary, &newToken)) 303 | { 304 | log::error("Client {}: Couldn't duplicate token: {}", _clientId, 305 | lastErrorString()); 306 | return false; 307 | } 308 | 309 | _userToken = std::move(newToken); 310 | log::info("Client {}: Authorized; stored new token.", _clientId); 311 | 312 | createResponse(msg::server::Success); 313 | return true; 314 | } 315 | 316 | bool ClientConnectionHandler::bless(HANDLE remoteHandle) { 317 | HObject clientProcess; 318 | HObject localHandle; 319 | ULONG processId; 320 | if (!_userToken) { 321 | log::error("Client {}: Not authenticated.", _clientId); 322 | return false; 323 | } 324 | 325 | if (!GetNamedPipeClientProcessId(_pipe, &processId)) { 326 | log::error("Client {}: Couldn't get client process ID: {}", _clientId, 327 | lastErrorString()); 328 | return false; 329 | } 330 | auto const access = PROCESS_DUP_HANDLE | PROCESS_VM_READ; 331 | if (!(clientProcess = OpenProcess(access, false, processId))) { 332 | log::error("Client {}: Couldn't open client process: {}", _clientId, 333 | lastErrorString()); 334 | return false; 335 | } 336 | log::debug("Trying to duplicate remote handle 0x{:X}.", 337 | reinterpret_cast(remoteHandle)); 338 | if (!DuplicateHandle(clientProcess, remoteHandle, GetCurrentProcess(), 339 | &localHandle, PROCESS_SET_INFORMATION, false, 0)) 340 | { 341 | log::error("Client {}: Couldn't duplicate remote handle: {}", _clientId, 342 | lastErrorString()); 343 | return false; 344 | } 345 | 346 | auto ntdll = LinkedModule{L"ntdll.dll"}; 347 | auto NtSetInformationProcess = 348 | ntdll.get("NtSetInformationProcess"); 349 | 350 | nt::PROCESS_ACCESS_TOKEN processAccessToken{_userToken, nullptr}; 351 | if (!NT_SUCCESS(NtSetInformationProcess(localHandle, 352 | nt::ProcessAccessToken, 353 | &processAccessToken, 354 | sizeof(nt::PROCESS_ACCESS_TOKEN)))) 355 | { 356 | log::error("Client {}: Couldn't assign access token: {}", _clientId, 357 | lastErrorString()); 358 | return false; 359 | } 360 | 361 | log::info("Client {}: Successfully adjusted remote process token.", 362 | _clientId); 363 | 364 | return true; 365 | } 366 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------