├── src ├── Elevate │ ├── Elevate.rc │ ├── smart_handle.h │ ├── EnvironmentStrings.h │ ├── Win32Exception.h │ ├── resource.h │ ├── FileMappingView.h │ ├── smart_handle.cpp │ ├── EnvironmentStrings.cpp │ ├── FileMappingView.cpp │ ├── Utils.h │ ├── Win32Exception.cpp │ ├── Elevate.vcxproj.filters │ ├── Utils.cpp │ ├── Elevate.vcxproj │ └── Elevate.cpp └── Elevate.sln ├── .editorconfig ├── LICENSE.txt ├── .gitattributes └── .gitignore /src/Elevate/Elevate.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jnm2/Elevate/HEAD/src/Elevate/Elevate.rc -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | charset = utf-8 7 | insert_final_newline = true 8 | trim_trailing_whitespaces = true 9 | 10 | [*.{*proj,*proj.*}] 11 | indent_size = 2 12 | -------------------------------------------------------------------------------- /src/Elevate/smart_handle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class smart_handle 6 | { 7 | const std::shared_ptr handle; 8 | 9 | public: 10 | explicit smart_handle(HANDLE); 11 | operator HANDLE() const; 12 | operator bool() const; 13 | }; 14 | -------------------------------------------------------------------------------- /src/Elevate/EnvironmentStrings.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class EnvironmentStrings 6 | { 7 | const std::shared_ptr handle; 8 | 9 | public: 10 | EnvironmentStrings(); 11 | operator LPWCH() const; 12 | DWORD CalculateSize() const; 13 | }; 14 | -------------------------------------------------------------------------------- /src/Elevate/Win32Exception.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class Win32Exception : public std::runtime_error 6 | { 7 | DWORD errorCode; 8 | 9 | public: 10 | Win32Exception(); 11 | Win32Exception(DWORD errorCode); 12 | DWORD ErrorCode() const; 13 | }; 14 | -------------------------------------------------------------------------------- /src/Elevate/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Elevate.rc 4 | 5 | // Next default values for new objects 6 | // 7 | #ifdef APSTUDIO_INVOKED 8 | #ifndef APSTUDIO_READONLY_SYMBOLS 9 | #define _APS_NEXT_RESOURCE_VALUE 101 10 | #define _APS_NEXT_COMMAND_VALUE 40001 11 | #define _APS_NEXT_CONTROL_VALUE 1001 12 | #define _APS_NEXT_SYMED_VALUE 101 13 | #endif 14 | #endif 15 | -------------------------------------------------------------------------------- /src/Elevate/FileMappingView.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include "smart_handle.h" 5 | 6 | class FileMappingView 7 | { 8 | const std::shared_ptr handle; 9 | 10 | public: 11 | FileMappingView( 12 | smart_handle hFileMappingObject, 13 | DWORD dwDesiredAccess, 14 | DWORD dwFileOffsetHigh, 15 | DWORD dwFileOffsetLow, 16 | SIZE_T dwNumberOfBytesToMap 17 | ); 18 | operator LPVOID() const; 19 | }; 20 | -------------------------------------------------------------------------------- /src/Elevate/smart_handle.cpp: -------------------------------------------------------------------------------- 1 | #include "smart_handle.h" 2 | #include 3 | #include "Win32Exception.h" 4 | 5 | smart_handle::smart_handle(const HANDLE value) : handle(std::shared_ptr(value, [](const HANDLE value) 6 | { 7 | if (value && value != INVALID_HANDLE_VALUE && !CloseHandle(value)) 8 | throw Win32Exception(); 9 | })) 10 | { 11 | } 12 | 13 | smart_handle::operator HANDLE() const 14 | { 15 | return handle.get(); 16 | } 17 | 18 | smart_handle::operator bool() const 19 | { 20 | return handle.get() && handle.get() != INVALID_HANDLE_VALUE; 21 | } 22 | -------------------------------------------------------------------------------- /src/Elevate/EnvironmentStrings.cpp: -------------------------------------------------------------------------------- 1 | #include "EnvironmentStrings.h" 2 | #include "Win32Exception.h" 3 | 4 | EnvironmentStrings::EnvironmentStrings() 5 | : handle(std::shared_ptr(GetEnvironmentStrings(), [](const LPWCH value) 6 | { 7 | if (value && !FreeEnvironmentStrings(value)) 8 | throw Win32Exception(); 9 | })) 10 | { 11 | } 12 | 13 | EnvironmentStrings::operator LPWCH() const 14 | { 15 | return handle.get(); 16 | } 17 | 18 | DWORD EnvironmentStrings::CalculateSize() const 19 | { 20 | for (auto start = handle.get(), current = start;;) 21 | { 22 | const auto stringSize = wcslen(current); 23 | current += stringSize + 1; 24 | if (stringSize == 0) return static_cast(current - start); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Elevate/FileMappingView.cpp: -------------------------------------------------------------------------------- 1 | #include "FileMappingView.h" 2 | #include "Win32Exception.h" 3 | #include "smart_handle.h" 4 | 5 | FileMappingView::FileMappingView( 6 | smart_handle hFileMappingObject, 7 | DWORD dwDesiredAccess, 8 | DWORD dwFileOffsetHigh, 9 | DWORD dwFileOffsetLow, 10 | SIZE_T dwNumberOfBytesToMap 11 | ) 12 | : handle(std::shared_ptr(MapViewOfFile(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap), [](const LPVOID value) 13 | { 14 | if (value && !UnmapViewOfFile(value)) 15 | throw Win32Exception(); 16 | })) 17 | { 18 | if (!handle.get()) throw Win32Exception(); 19 | } 20 | 21 | FileMappingView::operator LPVOID() const 22 | { 23 | return handle.get(); 24 | } 25 | -------------------------------------------------------------------------------- /src/Elevate/Utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace Utils 4 | { 5 | bool IsElevated(); 6 | LPWSTR GetRawCommandLineArgs(); 7 | std::wstring GetCurrentProcessPath(); 8 | std::wstring GetProcessPath(DWORD pid); 9 | bool IsWhiteSpace(std::wstring value); 10 | DWORD GetParentProcessId(DWORD pid); 11 | std::wstring GetCurrentDirectory(); 12 | 13 | template 14 | int StandardMain(const TImplementation implementation, const TErrorHandler errorHandler) 15 | { 16 | try 17 | { 18 | implementation(); 19 | } 20 | catch (const std::exception& ex) 21 | { 22 | errorHandler(ex.what()); 23 | return -1; 24 | } 25 | catch (...) 26 | { 27 | errorHandler("Unknown error\r\n"); 28 | return -1; 29 | } 30 | 31 | return 0; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Elevate/Win32Exception.cpp: -------------------------------------------------------------------------------- 1 | #include "Win32Exception.h" 2 | #include 3 | 4 | 5 | std::string GetMessage(DWORD errorCode) 6 | { 7 | auto pBufferOutParameter = LPSTR(nullptr); 8 | const auto bufferLength = FormatMessageA( 9 | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 10 | nullptr, 11 | errorCode, 12 | 0, 13 | reinterpret_cast(&pBufferOutParameter), 14 | 0, 15 | nullptr); 16 | 17 | 18 | struct LocalDeleter 19 | { 20 | void operator()(HLOCAL toFree) const 21 | { 22 | LocalFree(toFree); 23 | } 24 | }; 25 | const auto pBuffer = std::unique_ptr(pBufferOutParameter); 26 | 27 | return std::string(pBuffer.get(), bufferLength); 28 | } 29 | 30 | Win32Exception::Win32Exception(DWORD errorCode) : runtime_error(GetMessage(errorCode)), errorCode(errorCode) 31 | { 32 | } 33 | Win32Exception::Win32Exception() : Win32Exception(GetLastError()) 34 | { 35 | } 36 | 37 | DWORD Win32Exception::ErrorCode() const 38 | { 39 | return errorCode; 40 | } 41 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright © 2018 Joseph Musser 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Elevate.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26228.9 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Elevate", "Elevate\Elevate.vcxproj", "{E69758D5-E8F7-41B1-A277-2E2854538474}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Debug|x64.ActiveCfg = Debug|x64 17 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Debug|x64.Build.0 = Debug|x64 18 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Debug|x86.ActiveCfg = Debug|Win32 19 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Debug|x86.Build.0 = Debug|Win32 20 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Release|x64.ActiveCfg = Release|x64 21 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Release|x64.Build.0 = Release|x64 22 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Release|x86.ActiveCfg = Release|Win32 23 | {E69758D5-E8F7-41B1-A277-2E2854538474}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /src/Elevate/Elevate.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | Source Files 23 | 24 | 25 | Source Files 26 | 27 | 28 | Source Files 29 | 30 | 31 | Source Files 32 | 33 | 34 | Source Files 35 | 36 | 37 | 38 | 39 | Header Files 40 | 41 | 42 | Header Files 43 | 44 | 45 | Header Files 46 | 47 | 48 | Header Files 49 | 50 | 51 | Header Files 52 | 53 | 54 | Header Files 55 | 56 | 57 | 58 | 59 | Resource Files 60 | 61 | 62 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/Elevate/Utils.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "smart_handle.h" 6 | #include "Win32Exception.h" 7 | 8 | namespace Utils 9 | { 10 | using namespace std; 11 | 12 | bool IsElevated() 13 | { 14 | auto hTokenOutParameter = HANDLE(nullptr); 15 | if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hTokenOutParameter)) 16 | throw Win32Exception(); 17 | const auto hToken = smart_handle(hTokenOutParameter); 18 | 19 | auto elevation = TOKEN_ELEVATION { }; 20 | auto cbSize = DWORD(sizeof(TOKEN_ELEVATION)); 21 | if (!GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &cbSize)) 22 | throw Win32Exception(); 23 | 24 | return elevation.TokenIsElevated; 25 | } 26 | 27 | LPWSTR GetRawCommandLineArgs() 28 | { 29 | auto c = GetCommandLine(); 30 | if (!c) return nullptr; 31 | 32 | if (*c == '"') 33 | { 34 | c++; 35 | while (*c && *c++ != '"') { } 36 | } 37 | else 38 | { 39 | while (*c && !isspace(*c++)) { } 40 | } 41 | 42 | while (*c && isspace(*c)) c++; 43 | 44 | return c; 45 | } 46 | 47 | wstring GetCurrentProcessPath() 48 | { 49 | for (auto bufferSize = MAX_PATH; ; bufferSize *= 2) 50 | { 51 | const auto buffer = make_unique(bufferSize); 52 | const auto nameSize = GetModuleFileName(nullptr, buffer.get(), bufferSize); 53 | if (nameSize == 0) throw Win32Exception(); 54 | 55 | if (!(nameSize == bufferSize && buffer[nameSize - 1]) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) 56 | return wstring(buffer.get(), nameSize); 57 | } 58 | } 59 | 60 | wstring GetProcessPath(const DWORD pid) 61 | { 62 | const auto hProcess = smart_handle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)); 63 | if (hProcess == nullptr) throw Win32Exception(); 64 | 65 | for (auto bufferSize = MAX_PATH; ; bufferSize *= 2) 66 | { 67 | const auto buffer = make_unique(bufferSize); 68 | auto nameSize = DWORD(bufferSize); 69 | if (!QueryFullProcessImageName(hProcess, 0, buffer.get(), &nameSize)) 70 | { 71 | const auto error = GetLastError(); 72 | if (error == ERROR_INSUFFICIENT_BUFFER) continue; 73 | throw Win32Exception(error); 74 | } 75 | 76 | return wstring(buffer.get(), nameSize); 77 | } 78 | } 79 | 80 | wstring GetCurrentDirectory() 81 | { 82 | const auto bufferSize = ::GetCurrentDirectory(0, nullptr); 83 | if (bufferSize == 0) throw Win32Exception(); 84 | 85 | const auto buffer = make_unique(bufferSize); 86 | const auto numCopied = ::GetCurrentDirectory(bufferSize, buffer.get()); 87 | if (numCopied == 0) throw Win32Exception(); 88 | 89 | if (numCopied != bufferSize - 1) throw runtime_error("Race condition: current directory changed while retrieving it."); 90 | 91 | return wstring(buffer.get(), numCopied); 92 | } 93 | 94 | bool IsWhiteSpace(const wstring value) 95 | { 96 | for (auto &c : value) 97 | if (!isspace(c)) return false; 98 | return true; 99 | } 100 | 101 | DWORD GetParentProcessId(const DWORD pid) 102 | { 103 | const auto hSnapshot = smart_handle(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); 104 | if (hSnapshot == INVALID_HANDLE_VALUE) throw Win32Exception(); 105 | 106 | auto processEntry = PROCESSENTRY32 { sizeof(PROCESSENTRY32) }; 107 | if (Process32First(hSnapshot, &processEntry)) 108 | { 109 | do 110 | { 111 | if (processEntry.th32ProcessID == pid) 112 | return processEntry.th32ParentProcessID; 113 | } while (Process32Next(hSnapshot, &processEntry)); 114 | } 115 | 116 | return 0; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/visualstudio 3 | 4 | ### VisualStudio ### 5 | ## Ignore Visual Studio temporary files, build results, and 6 | ## files generated by popular Visual Studio add-ons. 7 | ## 8 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 9 | 10 | # User-specific files 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | bld/ 27 | [Bb]in/ 28 | [Oo]bj/ 29 | [Ll]og/ 30 | 31 | # Visual Studio 2015 cache/options directory 32 | .vs/ 33 | # Uncomment if you have tasks that create the project's static files in wwwroot 34 | #wwwroot/ 35 | 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | 44 | # Build Results of an ATL Project 45 | [Dd]ebugPS/ 46 | [Rr]eleasePS/ 47 | dlldata.c 48 | 49 | # .NET Core 50 | project.lock.json 51 | project.fragment.lock.json 52 | artifacts/ 53 | **/Properties/launchSettings.json 54 | 55 | *_i.c 56 | *_p.c 57 | *_i.h 58 | *.ilk 59 | *.meta 60 | *.obj 61 | *.pch 62 | *.pdb 63 | *.pgc 64 | *.pgd 65 | *.rsp 66 | *.sbr 67 | *.tlb 68 | *.tli 69 | *.tlh 70 | *.tmp 71 | *.tmp_proj 72 | *.log 73 | *.vspscc 74 | *.vssscc 75 | .builds 76 | *.pidb 77 | *.svclog 78 | *.scc 79 | 80 | # Chutzpah Test files 81 | _Chutzpah* 82 | 83 | # Visual C++ cache files 84 | ipch/ 85 | *.aps 86 | *.ncb 87 | *.opendb 88 | *.opensdf 89 | *.sdf 90 | *.cachefile 91 | *.VC.db 92 | *.VC.VC.opendb 93 | 94 | # Visual Studio profiler 95 | *.psess 96 | *.vsp 97 | *.vspx 98 | *.sap 99 | 100 | # TFS 2012 Local Workspace 101 | $tf/ 102 | 103 | # Guidance Automation Toolkit 104 | *.gpState 105 | 106 | # ReSharper is a .NET coding add-in 107 | _ReSharper*/ 108 | *.[Rr]e[Ss]harper 109 | *.DotSettings.user 110 | 111 | # JustCode is a .NET coding add-in 112 | .JustCode 113 | 114 | # TeamCity is a build add-in 115 | _TeamCity* 116 | 117 | # DotCover is a Code Coverage Tool 118 | *.dotCover 119 | 120 | # Visual Studio code coverage results 121 | *.coverage 122 | *.coveragexml 123 | 124 | # NCrunch 125 | _NCrunch_* 126 | .*crunch*.local.xml 127 | nCrunchTemp_* 128 | 129 | # MightyMoose 130 | *.mm.* 131 | AutoTest.Net/ 132 | 133 | # Web workbench (sass) 134 | .sass-cache/ 135 | 136 | # Installshield output folder 137 | [Ee]xpress/ 138 | 139 | # DocProject is a documentation generator add-in 140 | DocProject/buildhelp/ 141 | DocProject/Help/*.HxT 142 | DocProject/Help/*.HxC 143 | DocProject/Help/*.hhc 144 | DocProject/Help/*.hhk 145 | DocProject/Help/*.hhp 146 | DocProject/Help/Html2 147 | DocProject/Help/html 148 | 149 | # Click-Once directory 150 | publish/ 151 | 152 | # Publish Web Output 153 | *.[Pp]ublish.xml 154 | *.azurePubxml 155 | # TODO: Comment the next line if you want to checkin your web deploy settings 156 | # but database connection strings (with potential passwords) will be unencrypted 157 | *.pubxml 158 | *.publishproj 159 | 160 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 161 | # checkin your Azure Web App publish settings, but sensitive information contained 162 | # in these scripts will be unencrypted 163 | PublishScripts/ 164 | 165 | # NuGet Packages 166 | *.nupkg 167 | # The packages folder can be ignored because of Package Restore 168 | **/packages/* 169 | # except build/, which is used as an MSBuild target. 170 | !**/packages/build/ 171 | # Uncomment if necessary however generally it will be regenerated when needed 172 | #!**/packages/repositories.config 173 | # NuGet v3's project.json files produces more ignorable files 174 | *.nuget.props 175 | *.nuget.targets 176 | 177 | # Microsoft Azure Build Output 178 | csx/ 179 | *.build.csdef 180 | 181 | # Microsoft Azure Emulator 182 | ecf/ 183 | rcf/ 184 | 185 | # Windows Store app package directories and files 186 | AppPackages/ 187 | BundleArtifacts/ 188 | Package.StoreAssociation.xml 189 | _pkginfo.txt 190 | 191 | # Visual Studio cache files 192 | # files ending in .cache can be ignored 193 | *.[Cc]ache 194 | # but keep track of directories ending in .cache 195 | !*.[Cc]ache/ 196 | 197 | # Others 198 | ClientBin/ 199 | ~$* 200 | *~ 201 | *.dbmdl 202 | *.dbproj.schemaview 203 | *.jfm 204 | *.pfx 205 | *.publishsettings 206 | orleans.codegen.cs 207 | 208 | # Since there are multiple workflows, uncomment next line to ignore bower_components 209 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 210 | #bower_components/ 211 | 212 | # RIA/Silverlight projects 213 | Generated_Code/ 214 | 215 | # Backup & report files from converting an old project file 216 | # to a newer Visual Studio version. Backup files are not needed, 217 | # because we have git ;-) 218 | _UpgradeReport_Files/ 219 | Backup*/ 220 | UpgradeLog*.XML 221 | UpgradeLog*.htm 222 | 223 | # SQL Server files 224 | *.mdf 225 | *.ldf 226 | *.ndf 227 | 228 | # Business Intelligence projects 229 | *.rdl.data 230 | *.bim.layout 231 | *.bim_*.settings 232 | 233 | # Microsoft Fakes 234 | FakesAssemblies/ 235 | 236 | # GhostDoc plugin setting file 237 | *.GhostDoc.xml 238 | 239 | # Node.js Tools for Visual Studio 240 | .ntvs_analysis.dat 241 | node_modules/ 242 | 243 | # Typescript v1 declaration files 244 | typings/ 245 | 246 | # Visual Studio 6 build log 247 | *.plg 248 | 249 | # Visual Studio 6 workspace options file 250 | *.opt 251 | 252 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 253 | *.vbw 254 | 255 | # Visual Studio LightSwitch build output 256 | **/*.HTMLClient/GeneratedArtifacts 257 | **/*.DesktopClient/GeneratedArtifacts 258 | **/*.DesktopClient/ModelManifest.xml 259 | **/*.Server/GeneratedArtifacts 260 | **/*.Server/ModelManifest.xml 261 | _Pvt_Extensions 262 | 263 | # Paket dependency manager 264 | .paket/paket.exe 265 | paket-files/ 266 | 267 | # FAKE - F# Make 268 | .fake/ 269 | 270 | # JetBrains Rider 271 | .idea/ 272 | *.sln.iml 273 | 274 | # CodeRush 275 | .cr/ 276 | 277 | # Python Tools for Visual Studio (PTVS) 278 | __pycache__/ 279 | *.pyc 280 | 281 | # Cake - Uncomment if you are using it 282 | tools/** 283 | # !tools/packages.config 284 | 285 | # Telerik's JustMock configuration file 286 | *.jmconfig 287 | 288 | # BizTalk build output 289 | *.btp.cs 290 | *.btm.cs 291 | *.odx.cs 292 | *.xsd.cs 293 | 294 | # End of https://www.gitignore.io/api/visualstudio 295 | -------------------------------------------------------------------------------- /src/Elevate/Elevate.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 15.0 23 | {E69758D5-E8F7-41B1-A277-2E2854538474} 24 | Win32Proj 25 | Elevate 26 | 10.0.14393.0 27 | bin\$(Platform)\$(Configuration)\ 28 | obj\$(Platform)\$(Configuration)\ 29 | 30 | 31 | 32 | Application 33 | true 34 | v141 35 | Unicode 36 | 37 | 38 | Application 39 | false 40 | v141 41 | true 42 | Unicode 43 | 44 | 45 | Application 46 | true 47 | v141 48 | Unicode 49 | 50 | 51 | Application 52 | false 53 | v141 54 | true 55 | Unicode 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | true 77 | 78 | 79 | true 80 | 81 | 82 | false 83 | 84 | 85 | false 86 | 87 | 88 | 89 | 90 | 91 | Level3 92 | Disabled 93 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 94 | 95 | 96 | Console 97 | 98 | 99 | 100 | 101 | 102 | 103 | Level3 104 | Disabled 105 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | 107 | 108 | Console 109 | 110 | 111 | 112 | 113 | Level3 114 | 115 | 116 | MaxSpeed 117 | true 118 | true 119 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | 121 | 122 | Console 123 | true 124 | true 125 | 126 | 127 | 128 | 129 | Level3 130 | 131 | 132 | MaxSpeed 133 | true 134 | true 135 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 136 | 137 | 138 | Console 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | -------------------------------------------------------------------------------- /src/Elevate/Elevate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Utils.h" 5 | #include "smart_handle.h" 6 | #include "Win32Exception.h" 7 | #include "EnvironmentStrings.h" 8 | #include "FileMappingView.h" 9 | #include 10 | 11 | using namespace std; 12 | 13 | 14 | const auto attachMarker = wstring(L"ELEVATE__DO_ATTACH_SELF_TO_PARENT_CONSOLE:"); 15 | auto mustReopenStdout = false; 16 | 17 | bool PopShouldAttachSelfToParent(wstring* rawCommandLineArgs, wstring* fileMappingName) 18 | { 19 | if (wcsncmp(rawCommandLineArgs->c_str(), attachMarker.c_str(), attachMarker.length()) != 0) 20 | return false; 21 | 22 | *fileMappingName = rawCommandLineArgs->substr(attachMarker.length(), 38); 23 | *rawCommandLineArgs = rawCommandLineArgs->substr(attachMarker.length() + 39); 24 | return true; 25 | } 26 | 27 | 28 | class EnvironmentStringsSource 29 | { 30 | FileMappingView hMappingView; 31 | LPWCH rawEnvironmentStrings; 32 | 33 | public: 34 | EnvironmentStringsSource(FileMappingView hMappingView, LPWCH rawEnvironmentStrings) 35 | : hMappingView(hMappingView), rawEnvironmentStrings(rawEnvironmentStrings) 36 | { 37 | } 38 | 39 | LPWCH get() const 40 | { 41 | return rawEnvironmentStrings; 42 | } 43 | }; 44 | 45 | void AttachSelfToParent(wstring fileMappingName, shared_ptr* rawEnvironmentStringsSource) 46 | { 47 | FreeConsole(); // It's okay if this fails 48 | 49 | if (!AttachConsole(ATTACH_PARENT_PROCESS)) 50 | { 51 | const auto exception = Win32Exception(); 52 | // We don't have a console, so MessageBox this one 53 | const auto message = string("AttachConsole failed: ") + exception.what(); 54 | MessageBoxA(nullptr, message.c_str(), nullptr, MB_ICONERROR); 55 | throw exception; 56 | } 57 | 58 | // Reopening now causes intermittent "application failed to initialize properly (0xc0000142)" 59 | // errors in the process started by CreateProcess, and is a waste unless there is an error. 60 | mustReopenStdout = true; 61 | 62 | 63 | const auto hMapping = smart_handle(OpenFileMapping(FILE_MAP_READ, false, fileMappingName.c_str())); 64 | if (!hMapping) throw Win32Exception(); 65 | 66 | const auto hMappingView = FileMappingView(hMapping, FILE_MAP_READ, 0, 0, 0); 67 | 68 | auto mappingPosition = LPWCH(LPVOID(hMappingView)); 69 | 70 | // Restore working directory 71 | if (!SetCurrentDirectory(mappingPosition)) 72 | throw Win32Exception(); 73 | mappingPosition += wcslen(mappingPosition) + 1; 74 | 75 | // Provide environment strings for CreateProcess 76 | *rawEnvironmentStringsSource = make_shared(hMappingView, mappingPosition); 77 | 78 | // Set the environment variables in this process rather than just passing to CreateProcess 79 | // in case it should be affecting the command line passed to CreateProcess. 80 | auto leftOverNames = unordered_set(); 81 | { 82 | const auto environmentStrings = EnvironmentStrings(); 83 | 84 | for (auto variable = LPWCH(environmentStrings); *variable; variable += wcslen(variable) + 1) 85 | { 86 | auto separator = wcschr(variable, L'='); 87 | if (separator == variable) continue; // Missing name 88 | leftOverNames.emplace(variable, separator); 89 | } 90 | } 91 | 92 | // Add new variables 93 | for (; *mappingPosition; mappingPosition += wcslen(mappingPosition) + 1) 94 | { 95 | auto separator = wcschr(mappingPosition, L'='); 96 | if (separator == mappingPosition) continue; // Missing name, causes SetEnvironmentVariable to error 97 | 98 | const auto name = wstring(mappingPosition, separator); 99 | if (!SetEnvironmentVariable(name.c_str(), separator + 1)) 100 | throw Win32Exception(); 101 | leftOverNames.erase(name); 102 | } 103 | 104 | // Remove existing variables for consistency 105 | for (auto &name : leftOverNames) 106 | if (!SetEnvironmentVariable(name.c_str(), nullptr)) 107 | throw Win32Exception(); 108 | } 109 | 110 | wstring GetDefaultCommandLine() 111 | { 112 | return L'"' + Utils::GetProcessPath(Utils::GetParentProcessId(GetCurrentProcessId())) + L'"'; 113 | } 114 | 115 | wstring GetNewGuidString() 116 | { 117 | auto mappingName = GUID { }; 118 | CoCreateGuid(&mappingName); 119 | 120 | const auto mappingNameString = make_unique(39); 121 | StringFromGUID2(mappingName, mappingNameString.get(), 39); 122 | 123 | return wstring(mappingNameString.get(), 38); 124 | } 125 | 126 | void ElevateSelf(wstring rawCommandLineArgs) 127 | { 128 | const auto environmentStrings = EnvironmentStrings(); 129 | const auto environmentSize = environmentStrings.CalculateSize() * sizeof(wchar_t); 130 | const auto currentDirectory = Utils::GetCurrentDirectory(); 131 | const auto currentDirectorySize = (currentDirectory.length() + 1) * sizeof(wchar_t); 132 | 133 | const auto mappingName = GetNewGuidString(); 134 | const auto hMapping = smart_handle(CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(currentDirectorySize + environmentSize), mappingName.c_str())); 135 | if (!hMapping) throw Win32Exception(); 136 | 137 | { 138 | const auto hMappingView = FileMappingView(hMapping, FILE_MAP_WRITE, 0, 0, 0); 139 | if (!hMappingView) throw Win32Exception(); 140 | 141 | memcpy(hMappingView, currentDirectory.c_str(), currentDirectorySize); 142 | memcpy(static_cast(LPVOID(hMappingView)) + currentDirectorySize, environmentStrings, environmentSize); 143 | } 144 | 145 | 146 | auto info = SHELLEXECUTEINFO { sizeof(SHELLEXECUTEINFO) }; 147 | info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE; 148 | info.lpVerb = L"runas"; 149 | 150 | const auto currentProcessPath = Utils::GetCurrentProcessPath(); 151 | info.lpFile = currentProcessPath.c_str(); 152 | 153 | const auto parameters = attachMarker + mappingName + L" " + rawCommandLineArgs; 154 | info.lpParameters = parameters.c_str(); 155 | 156 | if (!ShellExecuteEx(&info)) throw Win32Exception(); 157 | 158 | const auto hProcess = smart_handle(info.hProcess); 159 | 160 | if (WaitForSingleObject(hProcess, INFINITE) == WAIT_FAILED) throw Win32Exception(); 161 | } 162 | 163 | void ExecuteCommand(wstring rawCommandLineArgs, shared_ptr environmentStringsSource) 164 | { 165 | auto si = STARTUPINFO { sizeof(STARTUPINFO) }; 166 | auto pi = PROCESS_INFORMATION { }; 167 | const auto environmentStrings = environmentStringsSource == nullptr ? nullptr : environmentStringsSource->get(); 168 | 169 | if (!CreateProcess(nullptr, const_cast(rawCommandLineArgs.c_str()), nullptr, nullptr, false, CREATE_UNICODE_ENVIRONMENT, environmentStrings, nullptr, &si, &pi)) 170 | throw Win32Exception(); 171 | 172 | const auto hProcess = smart_handle(pi.hProcess); 173 | const auto hThread = smart_handle(pi.hThread); 174 | 175 | if (WaitForSingleObject(hProcess, INFINITE) == WAIT_FAILED) throw Win32Exception(); 176 | } 177 | 178 | int main() 179 | { 180 | return Utils::StandardMain([]() 181 | { 182 | auto args = wstring(Utils::GetRawCommandLineArgs()); 183 | 184 | auto fileMappingName = wstring { }; 185 | auto environmentStringsSource = shared_ptr { }; 186 | if (PopShouldAttachSelfToParent(&args, &fileMappingName)) 187 | AttachSelfToParent(fileMappingName, &environmentStringsSource); 188 | 189 | if (Utils::IsWhiteSpace(args)) 190 | args = GetDefaultCommandLine(); 191 | 192 | // Elevate only after default command line has been set from current parent 193 | if (!Utils::IsElevated()) 194 | return ElevateSelf(args); 195 | 196 | ExecuteCommand(args, environmentStringsSource); 197 | }, 198 | [](const char* error) 199 | { 200 | if (mustReopenStdout) 201 | { 202 | auto fp = static_cast(nullptr); 203 | freopen_s(&fp, "CONOUT$", "w+", stdout); // (Previously important: "w+" instead of "w" or else child process output will screw up) 204 | 205 | cout << error; 206 | 207 | // No cleanup necessary because the process is going down next 208 | } 209 | else 210 | { 211 | cout << error; 212 | } 213 | }); 214 | } 215 | --------------------------------------------------------------------------------